Beispiel #1
0
    def get_plugin_actions(self):
        """Return a list of actions related to plugin"""
        self.new_project_action = create_action(self,
                                    _("New Project..."),
                                    triggered=self.create_new_project)
        self.open_project_action = create_action(self,
                                    _("Open Project..."),
                                    triggered=lambda v: self.open_project())
        self.close_project_action = create_action(self,
                                    _("Close Project"),
                                    triggered=self.close_project)
        self.clear_recent_projects_action =\
            create_action(self, _("Clear this list"),
                          triggered=self.clear_recent_projects)
        self.edit_project_preferences_action =\
            create_action(self, _("Project Preferences"),
                          triggered=self.edit_project_preferences)
        self.recent_project_menu = QMenu(_("Recent Projects"), self)
        explorer_action = self.toggle_view_action

        self.main.projects_menu_actions += [self.new_project_action,
                                            None,
                                            self.open_project_action,
                                            self.close_project_action,
                                            None,
                                            self.recent_project_menu,
                                            explorer_action]

        self.setup_menu_actions()
        return []
Beispiel #2
0
    def get_options_menu(self):
        """Return options menu"""
        env_action = create_action(
                        self,
                        _("Show environment variables"),
                        icon=ima.icon('environ'),
                        triggered=self.shellwidget.get_env
                     )

        syspath_action = create_action(
                            self,
                            _("Show sys.path contents"),
                            icon=ima.icon('syspath'),
                            triggered=self.shellwidget.get_syspath
                         )

        self.show_time_action.setChecked(self.show_elapsed_time)
        additional_actions = [MENU_SEPARATOR,
                              env_action,
                              syspath_action,
                              self.show_time_action]

        if self.menu_actions is not None:
            console_menu = self.menu_actions + additional_actions
            return console_menu

        else:
            return additional_actions
Beispiel #3
0
 def setup_common_actions(self):
     """Setup context menu common actions"""
     self.collapse_all_action = create_action(self,
                                  text=_('Collapse all'),
                                  icon=ima.icon('collapse'),
                                  triggered=self.collapseAll)
     self.expand_all_action = create_action(self,
                                  text=_('Expand all'),
                                  icon=ima.icon('expand'),
                                  triggered=self.expandAll)
     self.restore_action = create_action(self,
                                  text=_('Restore'),
                                  tip=_('Restore original tree layout'),
                                  icon=ima.icon('restore'),
                                  triggered=self.restore)
     self.collapse_selection_action = create_action(self,
                                  text=_('Collapse selection'),
                                  icon=ima.icon('collapse_selection'),
                                  triggered=self.collapse_selection)
     self.expand_selection_action = create_action(self,
                                  text=_('Expand selection'),
                                  icon=ima.icon('expand_selection'),
                                  triggered=self.expand_selection)
     return [self.collapse_all_action, self.expand_all_action,
             self.restore_action, None,
             self.collapse_selection_action, self.expand_selection_action]
Beispiel #4
0
    def get_options_menu(self):
        """Return options menu"""
        reset_action = create_action(self, _("Remove all variables"),
                                     icon=ima.icon('editdelete'),
                                     triggered=self.reset_namespace)

        self.show_time_action = create_action(self, _("Show elapsed time"),
                                         toggled=self.set_elapsed_time_visible)

        env_action = create_action(
                        self,
                        _("Show environment variables"),
                        icon=ima.icon('environ'),
                        triggered=self.shellwidget.get_env
                     )

        syspath_action = create_action(
                            self,
                            _("Show sys.path contents"),
                            icon=ima.icon('syspath'),
                            triggered=self.shellwidget.get_syspath
                         )

        self.show_time_action.setChecked(self.show_elapsed_time)
        additional_actions = [reset_action,
                              MENU_SEPARATOR,
                              env_action,
                              syspath_action,
                              self.show_time_action]

        if self.menu_actions is not None:
            return self.menu_actions + additional_actions
        else:
            return additional_actions
Beispiel #5
0
 def add_actions_to_context_menu(self, menu):
     """Add actions to IPython widget context menu"""
     inspect_action = create_action(self, _("Inspect current object"),
                                 QKeySequence(get_shortcut('console',
                                                 'inspect current object')),
                                 icon=ima.icon('MessageBoxInformation'),
                                 triggered=self.inspect_object)
     clear_line_action = create_action(self, _("Clear line or block"),
                                       QKeySequence("Shift+Escape"),
                                       icon=ima.icon('editdelete'),
                                       triggered=self.clear_line)
     reset_namespace_action = create_action(self, _("Reset namespace"),
                                       QKeySequence("Ctrl+Alt+R"),
                                       triggered=self.reset_namespace)
     clear_console_action = create_action(self, _("Clear console"),
                                          QKeySequence(get_shortcut('console',
                                                            'clear shell')),
                                          icon=ima.icon('editclear'),
                                          triggered=self.clear_console)
     quit_action = create_action(self, _("&Quit"), icon=ima.icon('exit'),
                                 triggered=self.exit_callback)
     add_actions(menu, (None, inspect_action, clear_line_action,
                        clear_console_action, reset_namespace_action,
                        None, quit_action))
     return menu
Beispiel #6
0
 def get_plugin_actions(self):
     """Return a list of actions related to plugin"""
     quit_action = create_action(self, _("&Quit"),
                                 icon=ima.icon('exit'), 
                                 tip=_("Quit"),
                                 triggered=self.quit)
     self.register_shortcut(quit_action, "_", "Quit", "Ctrl+Q")
     run_action = create_action(self, _("&Run..."), None,
                         ima.icon('run_small'),
                         _("Run a Python script"),
                         triggered=self.run_script)
     environ_action = create_action(self,
                         _("Environment variables..."),
                         icon=ima.icon('environ'),
                         tip=_("Show and edit environment variables"
                                     " (for current session)"),
                         triggered=self.show_env)
     syspath_action = create_action(self,
                         _("Show sys.path contents..."),
                         icon=ima.icon('syspath'),
                         tip=_("Show (read-only) sys.path"),
                         triggered=self.show_syspath)
     buffer_action = create_action(self,
                         _("Buffer..."), None,
                         tip=_("Set maximum line count"),
                         triggered=self.change_max_line_count)
     exteditor_action = create_action(self,
                         _("External editor path..."), None, None,
                         _("Set external editor executable path"),
                         triggered=self.change_exteditor)
     wrap_action = create_action(self,
                         _("Wrap lines"),
                         toggled=self.toggle_wrap_mode)
     wrap_action.setChecked(self.get_option('wrap'))
     calltips_action = create_action(self, _("Display balloon tips"),
         toggled=self.toggle_calltips)
     calltips_action.setChecked(self.get_option('calltips'))
     codecompletion_action = create_action(self,
                                       _("Automatic code completion"),
                                       toggled=self.toggle_codecompletion)
     codecompletion_action.setChecked(self.get_option('codecompletion/auto'))
     codecompenter_action = create_action(self,
                                 _("Enter key selects completion"),
                                 toggled=self.toggle_codecompletion_enter)
     codecompenter_action.setChecked(self.get_option(
                                                 'codecompletion/enter_key'))
     
     option_menu = QMenu(_('Internal console settings'), self)
     option_menu.setIcon(ima.icon('tooloptions'))
     add_actions(option_menu, (buffer_action, wrap_action,
                               calltips_action, codecompletion_action,
                               codecompenter_action, exteditor_action))
                 
     plugin_actions = [None, run_action, environ_action, syspath_action,
                       option_menu, None, quit_action]
     
     # Add actions to context menu
     add_actions(self.shell.menu, plugin_actions)
     
     return plugin_actions
Beispiel #7
0
    def get_plugin_actions(self):
        """Return a list of actions related to plugin"""
        interpreter_action = create_action(self,
                            _("Open a &Python console"), None,
                            ima.icon('python'),
                            triggered=self.open_interpreter)
        if os.name == 'nt':
            text = _("Open &command prompt")
            tip = _("Open a Windows command prompt")
        else:
            text = _("Open a &terminal")
            tip = _("Open a terminal window")
        terminal_action = create_action(self, text, None, None, tip,
                                        triggered=self.open_terminal)
        run_action = create_action(self,
                            _("&Run..."), None,
                            ima.icon('run_small'), _("Run a Python script"),
                            triggered=self.run_script)

        consoles_menu_actions = [interpreter_action]
        tools_menu_actions = [terminal_action]
        self.menu_actions = [interpreter_action, terminal_action, run_action]

        self.main.consoles_menu_actions += consoles_menu_actions
        self.main.tools_menu_actions += tools_menu_actions

        return self.menu_actions+consoles_menu_actions+tools_menu_actions
Beispiel #8
0
    def setup_toolbar(self, exclude_private, exclude_uppercase,
                      exclude_capitalized, exclude_unsupported):
        """Setup toolbar"""
        self.setup_in_progress = True
        toolbar = []

        load_button = create_toolbutton(self, text=_('Import data'),
                                        icon=ima.icon('fileimport'),
                                        triggered=lambda: self.import_data())
        self.save_button = create_toolbutton(self, text=_("Save data"),
                            icon=ima.icon('filesave'),
                            triggered=lambda: self.save_data(self.filename))
        self.save_button.setEnabled(False)
        save_as_button = create_toolbutton(self,
                                           text=_("Save data as..."),
                                           icon=ima.icon('filesaveas'),
                                           triggered=self.save_data)
        reset_namespace_button = create_toolbutton(
                self, text=_("Reset the namespace"),
                icon=ima.icon('editclear'), triggered=self.reset_namespace)

        toolbar += [load_button, self.save_button, save_as_button,
                    reset_namespace_button]

        self.exclude_private_action = create_action(self,
                _("Exclude private references"),
                tip=_("Exclude references which name starts"
                            " with an underscore"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_private', state))
        self.exclude_private_action.setChecked(exclude_private)
        
        self.exclude_uppercase_action = create_action(self,
                _("Exclude all-uppercase references"),
                tip=_("Exclude references which name is uppercase"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_uppercase', state))
        self.exclude_uppercase_action.setChecked(exclude_uppercase)
        
        self.exclude_capitalized_action = create_action(self,
                _("Exclude capitalized references"),
                tip=_("Exclude references which name starts with an "
                      "uppercase character"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_capitalized', state))
        self.exclude_capitalized_action.setChecked(exclude_capitalized)
        
        self.exclude_unsupported_action = create_action(self,
                _("Exclude unsupported data types"),
                tip=_("Exclude references to unsupported data types"
                            " (i.e. which won't be handled/saved correctly)"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_unsupported', state))
        self.exclude_unsupported_action.setChecked(exclude_unsupported)
        
        self.setup_in_progress = False
        
        return toolbar
Beispiel #9
0
 def get_plugin_actions(self):
     """Return a list of actions related to plugin"""
     history_action = create_action(self, _("History..."),
                                    None, ima.icon('history'),
                                    _("Set history maximum entries"),
                                    triggered=self.change_history_depth)
     self.wrap_action = create_action(self, _("Wrap lines"),
                                 toggled=self.toggle_wrap_mode)
     self.wrap_action.setChecked( self.get_option('wrap') )
     self.menu_actions = [history_action, self.wrap_action]
     return self.menu_actions
Beispiel #10
0
 def __init__(self, parent):
     QWebEngineView.__init__(self, parent)
     self.zoom_factor = 1.
     self.zoom_out_action = create_action(self, _("Zoom out"),
                                          icon=ima.icon('zoom_out'),
                                          triggered=self.zoom_out)
     self.zoom_in_action = create_action(self, _("Zoom in"),
                                         icon=ima.icon('zoom_in'),
                                         triggered=self.zoom_in)
     if WEBENGINE:
         web_page = WebPage(self)
         self.setPage(web_page)
Beispiel #11
0
 def setup_common_actions(self):
     """Setup context menu common actions"""
     # Filters
     filters_action = create_action(self, _("Edit filename filters..."),
                                    None, ima.icon('filter'),
                                    triggered=self.edit_filter)
     # Show all files
     all_action = create_action(self, _("Show all files"),
                                toggled=self.toggle_all)
     all_action.setChecked(self.show_all)
     self.toggle_all(self.show_all)
     
     return [filters_action, all_action]
Beispiel #12
0
 def create_toggle_view_action(self):
     """Associate a toggle view action with each plugin"""
     title = self.get_plugin_title()
     if self.CONF_SECTION == 'editor':
         title = _('Editor')
     if self.shortcut is not None:
         action = create_action(self, title,
                          toggled=lambda checked: self.toggle_view(checked),
                          shortcut=QKeySequence(self.shortcut),
                          context=Qt.WidgetShortcut)
     else:
         action = create_action(self, title, toggled=lambda checked:
                                             self.toggle_view(checked))
     self.toggle_view_action = action
Beispiel #13
0
 def create_undock_action(self):
     """Create the undock action for the plugin."""
     self.undock_action = create_action(self,
                                        _("Undock"),
                                        icon=ima.icon('newwindow'),
                                        tip=_("Undock the plugin"),
                                        triggered=self.undock_plugin)
Beispiel #14
0
    def __init__(self, parent=None, show_fullpath=True, fullpath_sorting=True,
                 show_all_files=True, show_comments=True):
        QWidget.__init__(self, parent)

        self.treewidget = OutlineExplorerTreeWidget(self,
                                            show_fullpath=show_fullpath,
                                            fullpath_sorting=fullpath_sorting,
                                            show_all_files=show_all_files,
                                            show_comments=show_comments)

        self.visibility_action = create_action(self,
                                           _("Show/hide outline explorer"),
                                           icon='outline_explorer_vis.png',
                                           toggled=self.toggle_visibility)
        self.visibility_action.setChecked(True)
        
        btn_layout = QHBoxLayout()
        btn_layout.setAlignment(Qt.AlignLeft)
        for btn in self.setup_buttons():
            btn_layout.addWidget(btn)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addLayout(btn_layout)
        layout.addWidget(self.treewidget)
        self.setLayout(layout)
Beispiel #15
0
 def get_actions_from_items(self, items):
     """Reimplemented OneColumnTree method"""
     fromcursor_act = create_action(self, text=_('Go to cursor position'),
                     icon=ima.icon('fromcursor'),
                     triggered=self.go_to_cursor_position)
     fullpath_act = create_action(self, text=_( 'Show absolute path'),
                     toggled=self.toggle_fullpath_mode)
     fullpath_act.setChecked(self.show_fullpath)
     allfiles_act = create_action(self, text=_( 'Show all files'),
                     toggled=self.toggle_show_all_files)
     allfiles_act.setChecked(self.show_all_files)
     comment_act = create_action(self, text=_('Show special comments'),
                     toggled=self.toggle_show_comments)
     comment_act.setChecked(self.show_comments)
     actions = [fullpath_act, allfiles_act, comment_act, fromcursor_act]
     return actions
Beispiel #16
0
    def register_plugin(self):
        """Register plugin in Spyder's main window"""
        self.findinfiles.get_pythonpath_callback = \
            self.main.get_spyder_pythonpath
        self.main.add_dockwidget(self)
        self.findinfiles.result_browser.sig_edit_goto.connect(
                                                         self.main.editor.load)
        self.findinfiles.find_options.redirect_stdio.connect(
                                        self.main.redirect_internalshell_stdio)
        self.main.workingdirectory.refresh_findinfiles.connect(self.refreshdir)
        self.main.projects.sig_project_loaded.connect(self.set_project_path)
        self.main.projects.sig_project_closed.connect(self.unset_project_path)
        self.main.editor.open_file_update.connect(self.set_current_opened_file)

        findinfiles_action = create_action(
                                   self, _("&Find in files"),
                                   icon=ima.icon('findf'),
                                   triggered=self.switch_to_plugin,
                                   shortcut=QKeySequence(self.shortcut),
                                   context=Qt.WidgetShortcut,
                                   tip=_("Search text in multiple files"))

        self.main.search_menu_actions += [MENU_SEPARATOR, findinfiles_action]
        self.main.search_toolbar_actions += [MENU_SEPARATOR,
                                             findinfiles_action]
        self.refreshdir()
Beispiel #17
0
    def update_browse_tabs_menu(self):
        """Update browse tabs menu"""
        self.browse_tabs_menu.clear()
        names = []
        dirnames = []
        for index in range(self.count()):
            if self.menu_use_tooltips:
                text = to_text_string(self.tabToolTip(index))
            else:
                text = to_text_string(self.tabText(index))
            names.append(text)
            if osp.isfile(text):
                # Testing if tab names are filenames
                dirnames.append(osp.dirname(text))
        offset = None
        
        # If tab names are all filenames, removing common path:
        if len(names) == len(dirnames):
            common = get_common_path(dirnames)
            if common is None:
                offset = None
            else:
                offset = len(common)+1
                if offset <= 3:
                    # Common path is not a path but a drive letter...
                    offset = None

        for index, text in enumerate(names):
            tab_action = create_action(self, text[offset:],
                                       icon=self.tabIcon(index),
                                       toggled=lambda state, index=index:
                                               self.setCurrentIndex(index),
                                       tip=self.tabToolTip(index))
            tab_action.setChecked(index == self.currentIndex())
            self.browse_tabs_menu.addAction(tab_action)
    def register_plugin(self):
        """Register plugin in Spyder's main window."""
        # Get information from Spyder proper into plugin
        self.update_pythonpath()
        self.update_default_wdir()

        # Connect to relevant signals
        self.main.sig_pythonpath_changed.connect(self.update_pythonpath)
        self.main.workingdirectory.set_explorer_cwd.connect(
            self.update_default_wdir)
        self.main.projects.sig_project_created.connect(
            self.handle_project_change)
        self.main.projects.sig_project_loaded.connect(
            self.handle_project_change)
        self.main.projects.sig_project_closed.connect(
            self.handle_project_change)
        self.unittestwidget.sig_newconfig.connect(self.save_config)
        self.unittestwidget.sig_edit_goto.connect(self.goto_in_editor)

        # Add plugin as dockwidget to main window
        self.main.add_dockwidget(self)

        # Create action and add it to Spyder's menu
        unittesting_act = create_action(
            self,
            _("Run unit tests"),
            icon=ima.icon('profiler'),
            shortcut="Shift+Alt+F11",
            triggered=self.maybe_configure_and_start)
        self.main.run_menu_actions += [unittesting_act]
        self.main.editor.pythonfile_dependent_actions += [unittesting_act]

        # Save all files before running tests
        self.unittestwidget.pre_test_hook = self.main.editor.save_all
Beispiel #19
0
    def __init__(self, parent=None, show_fullpath=True, fullpath_sorting=True,
                 show_all_files=True, show_comments=True, options_button=None):
        QWidget.__init__(self, parent)

        self.treewidget = OutlineExplorerTreeWidget(self,
                                            show_fullpath=show_fullpath,
                                            fullpath_sorting=fullpath_sorting,
                                            show_all_files=show_all_files,
                                            show_comments=show_comments)

        self.visibility_action = create_action(self,
                                           _("Show/hide outline explorer"),
                                           icon='outline_explorer_vis.png',
                                           toggled=self.toggle_visibility)
        self.visibility_action.setChecked(True)
        
        btn_layout = QHBoxLayout()
        for btn in self.setup_buttons():
            btn.setAutoRaise(True)
            btn.setIconSize(QSize(16, 16))
            btn_layout.addWidget(btn)
        if options_button:
            btn_layout.addStretch()
            btn_layout.addWidget(options_button, Qt.AlignRight)

        layout = create_plugin_layout(btn_layout, self.treewidget)
        self.setLayout(layout)
Beispiel #20
0
 def setup_context_menu(self):
     """Reimplement PythonShellWidget method"""
     PythonShellWidget.setup_context_menu(self)
     self.help_action = create_action(self, _("Help..."),
                        icon=ima.icon('DialogHelpButton'),
                        triggered=self.help)
     self.menu.addAction(self.help_action)
Beispiel #21
0
    def setup_menu_actions(self):
        """Setup and update the menu actions."""
        self.recent_project_menu.clear()
        self.recent_projects_actions = []
        if self.recent_projects:
            for project in self.recent_projects:
                if self.is_valid_project(project):
                    name = project.replace(get_home_dir(), '~')

                    def slot():
                        self.switch_to_plugin()
                        self.open_project(path=project)

                    action = create_action(self,
                        name,
                        icon = ima.icon('project'),
                        triggered=slot)
                    self.recent_projects_actions.append(action)
                else:
                    self.recent_projects.remove(project)
            self.recent_projects_actions += [None,
                                             self.clear_recent_projects_action]
        else:
            self.recent_projects_actions = [self.clear_recent_projects_action]
        add_actions(self.recent_project_menu, self.recent_projects_actions)
        self.update_project_actions()
Beispiel #22
0
 def get_options_menu(self):
     self.show_time_action = create_action(self, _("Show elapsed time"),
                                       toggled=self.set_elapsed_time_visible)
     self.show_time_action.setChecked(self.show_elapsed_time)
     actions = [self.show_time_action]
     if self.menu_actions is not None:
         actions += [None]+self.menu_actions
     return actions
Beispiel #23
0
 def create_folder_manage_actions(self, fnames):
     """Return folder management actions"""
     actions = []
     if os.name == 'nt':
         _title = _("Open command prompt here")
     else:
         _title = _("Open terminal here")
     action = create_action(self, _title, icon=ima.icon('cmdprompt'),
                            triggered=lambda:
                            self.open_terminal(fnames))
     actions.append(action)
     _title = _("Open Python console here")
     action = create_action(self, _title, icon=ima.icon('python'),
                            triggered=lambda:
                            self.open_interpreter(fnames))
     actions.append(action)
     return actions
Beispiel #24
0
    def __init__(self, parent):
        QTableView.__init__(self, parent)
        self._model = None

        # Setting up actions
        self.date_dayfirst_action = create_action(self, "dayfirst",
            triggered=ft_partial(self.parse_to_type, atype="date", dayfirst=True))
        self.date_monthfirst_action = create_action(self, "monthfirst",
            triggered=ft_partial(self.parse_to_type, atype="date", dayfirst=False))
        self.perc_action = create_action(self, "perc",
            triggered=ft_partial(self.parse_to_type, atype="perc"))
        self.acc_action = create_action(self, "account",
            triggered=ft_partial(self.parse_to_type, atype="account"))
        self.str_action = create_action(self, "unicode",
            triggered=ft_partial(self.parse_to_type, atype="unicode"))
        self.int_action = create_action(self, "int",
            triggered=ft_partial(self.parse_to_type, atype="int"))
        self.float_action = create_action(self, "float",
            triggered=ft_partial(self.parse_to_type, atype="float"))

        # Setting up menus
        self.date_menu = QMenu()
        self.date_menu.setTitle("Date")
        add_actions( self.date_menu, (self.date_dayfirst_action,
                                      self.date_monthfirst_action))
        self.parse_menu = QMenu(self)
        self.parse_menu.addMenu(self.date_menu)
        add_actions( self.parse_menu, (self.perc_action, self.acc_action))
        self.parse_menu.setTitle("String to")
        self.opt_menu = QMenu(self)
        self.opt_menu.addMenu(self.parse_menu)
        add_actions( self.opt_menu, (self.str_action, self.int_action,
                                     self.float_action))
Beispiel #25
0
 def get_options_menu(self):
     ExternalShellBase.get_options_menu(self)
     self.interact_action = create_action(self, _("Interact"))
     self.interact_action.setCheckable(True)
     self.debug_action = create_action(self, _("Debug"))
     self.debug_action.setCheckable(True)
     self.args_action = create_action(self, _("Arguments..."),
                                      triggered=self.get_arguments)
     self.post_mortem_action = create_action(self, _("Post Mortem Debug"))
     self.post_mortem_action.setCheckable(True)
     run_settings_menu = QMenu(_("Run settings"), self)
     add_actions(run_settings_menu,
                 (self.interact_action, self.debug_action, self.args_action,
                  self.post_mortem_action))
     self.cwd_button = create_action(self, _("Working directory"),
                             icon=ima.icon('DirOpenIcon'),
                             tip=_("Set current working directory"),
                             triggered=self.set_current_working_directory)
     self.env_button = create_action(self, _("Environment variables"),
                                     icon=ima.icon('environ'),
                                     triggered=self.show_env)
     self.syspath_button = create_action(self,
                                         _("Show sys.path contents"),
                                         icon=ima.icon('syspath'),
                                         triggered=self.show_syspath)
     actions = [run_settings_menu, self.show_time_action, None,
                self.cwd_button, self.env_button, self.syspath_button]
     if self.menu_actions is not None:
         actions += [None]+self.menu_actions
     return actions
Beispiel #26
0
 def get_plugin_actions(self):
     """Return a list of actions related to plugin"""
     # Font
     history_action = create_action(self, _("History..."),
                                    None, ima.icon('history'),
                                    _("Set history maximum entries"),
                                    triggered=self.change_history_depth)
     self.pylint.treewidget.common_actions += (None, history_action)
     return []
Beispiel #27
0
 def build_context_menu(self, index):
     """Build context menu for test item that given index points to."""
     contextMenu = QMenu(self)
     if self.isExpanded(index):
         menuItem = create_action(self, _('Collapse'),
                                  triggered=lambda: self.collapse(index))
     else:
         menuItem = create_action(self, _('Expand'),
                                  triggered=lambda: self.expand(index))
         menuItem.setEnabled(self.model().hasChildren(index))
     contextMenu.addAction(menuItem)
     menuItem = create_action(
             self, _('Go to definition'),
             triggered=lambda: self.go_to_test_definition(index))
     test_location = self.model().data(index, Qt.UserRole)
     menuItem.setEnabled(test_location[0] is not None)
     contextMenu.addAction(menuItem)
     return contextMenu
Beispiel #28
0
 def setup_menu(self):
     """Setup context menu"""
     self.copy_action = create_action(self, _('Copy'),
                                      shortcut=keybinding('Copy'),
                                      icon=ima.icon('editcopy'),
                                      triggered=self.copy,
                                      context=Qt.WidgetShortcut)
     menu = QMenu(self)
     add_actions(menu, [self.copy_action, ])
     return menu
Beispiel #29
0
 def register_plugin(self):
     """Register plugin in Spyder's main window."""
     autopep8_act = create_action(
         self.main, _("Run autopep8 code autoformatting"),
         icon=self.get_plugin_icon(),
         triggered=self.run_autopep8)
     fixed_shortcut("Shift+F8", self.main,
                    self.run_autopep8)
     self.main.source_menu_actions += [None, autopep8_act]
     self.main.editor.pythonfile_dependent_actions += [autopep8_act]
Beispiel #30
0
    def setup_option_actions(self, exclude_private, exclude_uppercase,
                             exclude_capitalized, exclude_unsupported):
        """Setup the actions to show in the cog menu."""
        self.setup_in_progress = True

        self.exclude_private_action = create_action(self,
                _("Exclude private references"),
                tip=_("Exclude references which name starts"
                            " with an underscore"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_private', state))
        self.exclude_private_action.setChecked(exclude_private)
        
        self.exclude_uppercase_action = create_action(self,
                _("Exclude all-uppercase references"),
                tip=_("Exclude references which name is uppercase"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_uppercase', state))
        self.exclude_uppercase_action.setChecked(exclude_uppercase)
        
        self.exclude_capitalized_action = create_action(self,
                _("Exclude capitalized references"),
                tip=_("Exclude references which name starts with an "
                      "uppercase character"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_capitalized', state))
        self.exclude_capitalized_action.setChecked(exclude_capitalized)
        
        self.exclude_unsupported_action = create_action(self,
                _("Exclude unsupported data types"),
                tip=_("Exclude references to unsupported data types"
                            " (i.e. which won't be handled/saved correctly)"),
                toggled=lambda state:
                self.sig_option_changed.emit('exclude_unsupported', state))
        self.exclude_unsupported_action.setChecked(exclude_unsupported)

        self.actions = [
            self.exclude_private_action, self.exclude_uppercase_action,
            self.exclude_capitalized_action, self.exclude_unsupported_action]
        if is_module_installed('numpy'):
            self.actions.extend([MENU_SEPARATOR, self.editor.minmax_action])

        self.setup_in_progress = False
Beispiel #31
0
 def setup_context_menu(self):
     """Setup shell context menu"""
     self.menu = QMenu(self)
     self.cut_action = create_action(self,
                                     _("Cut"),
                                     shortcut=keybinding('Cut'),
                                     icon=ima.icon('editcut'),
                                     triggered=self.cut)
     self.copy_action = create_action(self,
                                      _("Copy"),
                                      shortcut=keybinding('Copy'),
                                      icon=ima.icon('editcopy'),
                                      triggered=self.copy)
     paste_action = create_action(self,
                                  _("Paste"),
                                  shortcut=keybinding('Paste'),
                                  icon=ima.icon('editpaste'),
                                  triggered=self.paste)
     save_action = create_action(self,
                                 _("Save history log..."),
                                 icon=ima.icon('filesave'),
                                 tip=_(
                                     "Save current history log (i.e. all "
                                     "inputs and outputs) in a text file"),
                                 triggered=self.save_historylog)
     self.delete_action = create_action(self,
                                        _("Delete"),
                                        shortcut=keybinding('Delete'),
                                        icon=ima.icon('editdelete'),
                                        triggered=self.delete)
     selectall_action = create_action(self,
                                      _("Select All"),
                                      shortcut=keybinding('SelectAll'),
                                      icon=ima.icon('selectall'),
                                      triggered=self.selectAll)
     add_actions(
         self.menu,
         (self.cut_action, self.copy_action, paste_action,
          self.delete_action, None, selectall_action, None, save_action))
Beispiel #32
0
    def get_plugin_actions(self):
        """Return a list of actions related to plugin"""
        self.new_project_action = create_action(self,
                                    _("New Project..."),
                                    triggered=self.create_new_project)
        self.open_project_action = create_action(self,
                                    _("Open Project..."),
                                    triggered=lambda v: self.open_project())
        self.close_project_action = create_action(self,
                                    _("Close Project"),
                                    triggered=self.close_project)
        self.delete_project_action = create_action(self,
                                    _("Delete Project"),
                                    triggered=self.delete_project)
        self.clear_recent_projects_action = create_action(
            self,
            _("Clear this list"),
            triggered=self.clear_recent_projects)
        self.recent_project_menu = QMenu(_("Recent Projects"), self)

        self.max_recent_action = create_action(
            self,
            _("Maximum number of recent projects..."),
            triggered=self.change_max_recent_projects)

        if self.main is not None:
            self.main.projects_menu_actions += [self.new_project_action,
                                                MENU_SEPARATOR,
                                                self.open_project_action,
                                                self.close_project_action,
                                                self.delete_project_action,
                                                MENU_SEPARATOR,
                                                self.recent_project_menu,
                                                self._toggle_view_action]

        self.setup_menu_actions()
        return []
Beispiel #33
0
    def __init__(self, parent):
        """Unit testing widget."""
        QWidget.__init__(self, parent)

        self.setWindowTitle("Unit testing")

        self.config = None
        self.pythonpath = None
        self.default_wdir = None
        self.testrunner = None
        self.output = None
        self.datatree = UnitTestDataTree(self)

        self.start_button = create_toolbutton(self, text_beside_icon=True)
        self.set_running_state(False)

        self.status_label = QLabel('', self)

        self.config_action = create_action(self,
                                           text=_("Configure ..."),
                                           icon=ima.icon('configure'),
                                           triggered=self.configure)
        self.log_action = create_action(self,
                                        text=_('Show output'),
                                        icon=ima.icon('log'),
                                        triggered=self.show_log)
        self.collapse_action = create_action(
            self,
            text=_('Collapse all'),
            icon=ima.icon('collapse'),
            triggered=self.datatree.collapseAll())
        self.expand_action = create_action(self,
                                           text=_('Expand all'),
                                           icon=ima.icon('expand'),
                                           triggered=self.datatree.expandAll())

        options_menu = QMenu()
        options_menu.addAction(self.config_action)
        options_menu.addAction(self.log_action)
        options_menu.addAction(self.collapse_action)
        options_menu.addAction(self.expand_action)

        self.options_button = QToolButton(self)
        self.options_button.setIcon(ima.icon('tooloptions'))
        self.options_button.setPopupMode(QToolButton.InstantPopup)
        self.options_button.setMenu(options_menu)
        self.options_button.setAutoRaise(True)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.start_button)
        hlayout.addStretch()
        hlayout.addWidget(self.status_label)
        hlayout.addStretch()
        hlayout.addWidget(self.options_button)

        layout = QVBoxLayout()
        layout.addLayout(hlayout)
        layout.addWidget(self.datatree)
        self.setLayout(layout)

        if not is_unittesting_installed():
            for widget in (self.datatree, self.log_action, self.start_button,
                           self.collapse_action, self.expand_action):
                widget.setDisabled(True)
        else:
            pass  # self.show_data()
Beispiel #34
0
    def __init__(self, parent=None, css_path=CSS_PATH):
        SpyderPluginWidget.__init__(self, parent)

        self.internal_shell = None
        self.console = None
        self.css_path = css_path

        self.no_doc_string = _("No documentation available")

        self._last_console_cb = None
        self._last_editor_cb = None

        self.plain_text = PlainText(self)
        self.rich_text = RichText(self)

        color_scheme = self.get_color_scheme()
        self.set_plain_text_font(self.get_font(), color_scheme)
        self.plain_text.editor.toggle_wrap_mode(self.get_option('wrap'))

        # Add entries to read-only editor context-menu
        self.wrap_action = create_action(self, _("Wrap lines"),
                                         toggled=self.toggle_wrap_mode)
        self.wrap_action.setChecked(self.get_option('wrap'))
        self.plain_text.editor.readonly_menu.addSeparator()
        add_actions(self.plain_text.editor.readonly_menu, (self.wrap_action,))

        self.set_rich_text_font(self.get_font(rich_text=True))

        self.shell = None

        # locked = disable link with Console
        self.locked = False
        self._last_texts = [None, None]
        self._last_editor_doc = None

        # Object name
        layout_edit = QHBoxLayout()
        layout_edit.setContentsMargins(0, 0, 0, 0)
        txt = _("Source")
        if sys.platform == 'darwin':
            source_label = QLabel("  " + txt)
        else:
            source_label = QLabel(txt)
        layout_edit.addWidget(source_label)
        self.source_combo = QComboBox(self)
        self.source_combo.addItems([_("Console"), _("Editor")])
        self.source_combo.currentIndexChanged.connect(self.source_changed)
        if (not programs.is_module_installed('rope') and
                not programs.is_module_installed('jedi', '>=0.11.0')):
            self.source_combo.hide()
            source_label.hide()
        layout_edit.addWidget(self.source_combo)
        layout_edit.addSpacing(10)
        layout_edit.addWidget(QLabel(_("Object")))
        self.combo = ObjectComboBox(self)
        layout_edit.addWidget(self.combo)
        self.object_edit = QLineEdit(self)
        self.object_edit.setReadOnly(True)
        layout_edit.addWidget(self.object_edit)
        self.combo.setMaxCount(self.get_option('max_history_entries'))
        self.combo.addItems( self.load_history() )
        self.combo.setItemText(0, '')
        self.combo.valid.connect(self.force_refresh)

        # Plain text docstring option
        self.docstring = True
        self.rich_help = self.get_option('rich_mode', True)
        self.plain_text_action = create_action(self, _("Plain Text"),
                                               toggled=self.toggle_plain_text)

        # Source code option
        self.show_source_action = create_action(self, _("Show Source"),
                                                toggled=self.toggle_show_source)

        # Rich text option
        self.rich_text_action = create_action(self, _("Rich Text"),
                                         toggled=self.toggle_rich_text)

        # Add the help actions to an exclusive QActionGroup
        help_actions = QActionGroup(self)
        help_actions.setExclusive(True)
        help_actions.addAction(self.plain_text_action)
        help_actions.addAction(self.rich_text_action)

        # Automatic import option
        self.auto_import_action = create_action(self, _("Automatic import"),
                                                toggled=self.toggle_auto_import)
        auto_import_state = self.get_option('automatic_import')
        self.auto_import_action.setChecked(auto_import_state)

        # Lock checkbox
        self.locked_button = create_toolbutton(self,
                                               triggered=self.toggle_locked)
        layout_edit.addWidget(self.locked_button)
        self._update_lock_icon()

        # Option menu
        layout_edit.addWidget(self.options_button)

        if self.rich_help:
            self.switch_to_rich_text()
        else:
            self.switch_to_plain_text()
        self.plain_text_action.setChecked(not self.rich_help)
        self.rich_text_action.setChecked(self.rich_help)
        self.source_changed()

        # Main layout
        layout = create_plugin_layout(layout_edit)
        # we have two main widgets, but only one of them is shown at a time
        layout.addWidget(self.plain_text)
        layout.addWidget(self.rich_text)
        self.setLayout(layout)

        # Add worker thread for handling rich text rendering
        self._sphinx_thread = SphinxThread(
                              html_text_no_doc=warning(self.no_doc_string,
                                                       css_path=self.css_path),
                              css_path=self.css_path)
        self._sphinx_thread.html_ready.connect(
                                             self._on_sphinx_thread_html_ready)
        self._sphinx_thread.error_msg.connect(self._on_sphinx_thread_error_msg)

        # Handle internal and external links
        view = self.rich_text.webview
        if not WEBENGINE:
            view.page().setLinkDelegationPolicy(QWebEnginePage.DelegateAllLinks)
        view.linkClicked.connect(self.handle_link_clicks)

        self._starting_up = True
Beispiel #35
0
    def setup_toolbar(self, exclude_private, exclude_uppercase,
                      exclude_capitalized, exclude_unsupported):
        """Setup toolbar"""
        self.setup_in_progress = True
        toolbar = []

        load_button = create_toolbutton(self,
                                        text=_('Import data'),
                                        icon=ima.icon('fileimport'),
                                        triggered=lambda: self.import_data())
        self.save_button = create_toolbutton(
            self,
            text=_("Save data"),
            icon=ima.icon('filesave'),
            triggered=lambda: self.save_data(self.filename))
        self.save_button.setEnabled(False)
        save_as_button = create_toolbutton(self,
                                           text=_("Save data as..."),
                                           icon=ima.icon('filesaveas'),
                                           triggered=self.save_data)

        toolbar += [load_button, self.save_button, save_as_button]

        self.exclude_private_action = create_action(
            self,
            _("Exclude private references"),
            tip=_("Exclude references which name starts"
                  " with an underscore"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_private', state))
        self.exclude_private_action.setChecked(exclude_private)

        self.exclude_uppercase_action = create_action(
            self,
            _("Exclude all-uppercase references"),
            tip=_("Exclude references which name is uppercase"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_uppercase', state))
        self.exclude_uppercase_action.setChecked(exclude_uppercase)

        self.exclude_capitalized_action = create_action(
            self,
            _("Exclude capitalized references"),
            tip=_("Exclude references which name starts with an "
                  "uppercase character"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_capitalized', state))
        self.exclude_capitalized_action.setChecked(exclude_capitalized)

        self.exclude_unsupported_action = create_action(
            self,
            _("Exclude unsupported data types"),
            tip=_("Exclude references to unsupported data types"
                  " (i.e. which won't be handled/saved correctly)"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_unsupported', state))
        self.exclude_unsupported_action.setChecked(exclude_unsupported)

        self.setup_in_progress = False

        return toolbar
Beispiel #36
0
    def create_action(self,
                      name,
                      text,
                      icon=None,
                      icon_text='',
                      tip=None,
                      toggled=None,
                      triggered=None,
                      shortcut_context=None,
                      context=Qt.WidgetWithChildrenShortcut,
                      initial=None,
                      register_shortcut=False,
                      section=None,
                      option=None,
                      parent=None):
        """
        name: str
            unique identifiable name for the action
        text: str
           Localized text for the action
        icon: QIcon,
            Icon for the action when applied to menu or toolbutton.
        icon_text: str
            Icon for text in toolbars. If True, this will also disable
            the tooltip on this toolbutton if part of a toolbar.
        tip: str
            Tooltip to define for action on menu or toolbar.
        toggled: Optional[Union[Callable, bool]]
            If True, then the action modifies the configuration option on the
            section specified. Otherwise, it should be a callable to use
            when toggling this action. If None, then the action does not
            behave like a checkbox.
        triggered: callable
            The callable to use when triggering this action.
        shortcut_context: str
            Set the `str` context of the shortcut.
        context: Qt.ShortcutContext
            Set the context for the shortcut.
        initial: object
            Sets the initial state of a togglable action. This does not emit
            the toggled signal.
        section: Optional[str]
            Name of the configuration section whose option is going to be
            modified. If None, and `option` is not None, then it defaults to
            the class `CONF_SECTION` attribute.
        option: ConfigurationKey
            Name of the configuration option whose value is reflected and
            affected by the action.
        register_shortcut: bool, optional
            If True, main window will expose the shortcut in Preferences.
            The default value is `False`.
        parent: QWidget (None)
            Define the parent of the widget. Use `self` if not provided.

        Notes
        -----
        There is no need to set shortcuts right now. We only create actions
        with this (and similar methods) and these are then exposed as possible
        shortcuts on plugin registration in the main window with the
        register_shortcut argument.

        If icon_text is True, this will also disable the tooltip.

        If a shortcut is found in the default config then it is assigned,
        otherwise it's left blank for the user to define one for it.
        """
        actions = getattr(self, '_actions', None)
        if actions is None:
            self._actions = OrderedDict()

        if triggered is None and toggled is None:
            raise SpyderAPIError(
                'Action must provide the toggled or triggered parameters!')

        # Check name
        if name in self._actions:
            raise SpyderAPIError(
                'Action name "{}" already in use!'.format(name))

        if parent is None:
            parent = self

        if toggled and not callable(toggled):
            toggled = lambda value: None

        if toggled is not None:
            if section is None and option is not None:
                section = self.CONF_SECTION

        action = create_action(parent,
                               text=text,
                               icon=icon,
                               tip=tip,
                               toggled=toggled,
                               triggered=triggered,
                               context=context,
                               section=section,
                               option=option)
        action.name = name
        if icon_text:
            action.setIconText(icon_text)

        action.text_beside_icon = bool(icon_text)
        action.shortcut_context = shortcut_context
        action.register_shortcut = register_shortcut
        action.tip = tip

        if initial is not None:
            if toggled:
                action.setChecked(initial)
            elif triggered:
                raise SpyderAPIError(
                    'Initial values can only apply to togglable actions!')
        else:
            if toggled:
                if section is not None and option is not None:
                    value = CONF.get(section, option)
                    action.setChecked(value)

        self._actions[name] = action
        return action
Beispiel #37
0
    def create_action(self,
                      name,
                      text,
                      icon=None,
                      icon_text='',
                      tip=None,
                      toggled=None,
                      triggered=None,
                      shortcut_context=None,
                      context=Qt.WidgetWithChildrenShortcut,
                      initial=None,
                      register_shortcut=False,
                      parent=None):
        """
        name: str
            unique identifiable name for the action
        text: str
           Localized text for the action
        icon: QIcon,
            Icon for the action when applied to menu or toolbutton.
        icon_text: str
            Icon for text in toolbars. If True, this will also disable
            the tooltip on this toolbutton if part of a toolbar.
        tip: str
            Tooltip to define for action on menu or toolbar.
        toggled: callable
            The callable to use when toggling this action
        triggered: callable
            The callable to use when triggering this action.
        shortcut_context: str
            Set the `str` context of the shortcut.
        context: Qt.ShortcutContext
            Set the context for the shortcut.
        initial: object
            Sets the initial state of a togglable action. This does not emit
            the toggled signal.
        register_shortcut: bool, optional
            If True, main window will expose the shortcut in Preferences.
            The default value is `False`.
        parent: QWidget (None)
            Define the parent of the widget. Use `self` if not provided.

        Notes
        -----
        There is no need to set shortcuts right now. We only create actions
        with this (and similar methods) and these are then exposed as possible
        shortcuts on plugin registration in the main window with the
        register_shortcut argument.

        If icon_text is True, this will also disable the tooltip.

        If a shortcut is found in the default config then it is assigned,
        otherwise it's left blank for the user to define one for it.
        """
        actions = getattr(self, '_actions', None)
        if actions is None:
            self._actions = OrderedDict()

        if triggered is None and toggled is None:
            raise SpyderAPIError(
                'Action must provide the toggled or triggered parameters!')

        # Check name
        if name in self._actions:
            raise SpyderAPIError(
                'Action name "{}" already in use!'.format(name))

        if parent is None:
            parent = self

        action = create_action(
            parent,
            text=text,
            icon=icon,
            tip=tip,
            toggled=toggled,
            triggered=triggered,
            context=context,
        )
        action.name = name
        if icon_text:
            action.setIconText(icon_text)

        action.text_beside_icon = bool(icon_text)
        action.shortcut_context = shortcut_context
        action.register_shortcut = register_shortcut
        action.tip = tip

        if initial is not None:
            if toggled:
                self.blockSignals(True)
                action.setChecked(initial)
                self.blockSignals(False)
            elif triggered:
                raise SpyderAPIError(
                    'Initial values can only apply to togglable actions!')

        self._actions[name] = action
        return action
Beispiel #38
0
def setup_reports_actions(qtbot):
    """Set up reports, with some actions."""
    action = create_action(None, "Some action", triggered=lambda self: None)
    widget = ReportsWidget(None, [action])
    qtbot.addWidget(widget)
    return widget, action
Beispiel #39
0
    def setup_toolbar(self, exclude_private, exclude_uppercase,
                      exclude_capitalized, exclude_unsupported, autorefresh):
        """Setup toolbar"""
        self.setup_in_progress = True

        toolbar = []

        # There is no need of refreshes for ipyclients
        if not self.is_ipyclient:
            refresh_button = create_toolbutton(self,
                                               text=_('Refresh'),
                                               icon=ima.icon('reload'),
                                               triggered=self.refresh_table)
            self.auto_refresh_button = create_toolbutton(
                self,
                text=_('Refresh periodically'),
                icon=ima.icon('auto_reload'),
                toggled=self.toggle_auto_refresh)
            self.auto_refresh_button.setChecked(autorefresh)
        else:
            refresh_button = self.auto_refresh_button = None

        load_button = create_toolbutton(self,
                                        text=_('Import data'),
                                        icon=ima.icon('fileimport'),
                                        triggered=lambda: self.import_data())
        self.save_button = create_toolbutton(
            self,
            text=_("Save data"),
            icon=ima.icon('filesave'),
            triggered=lambda: self.save_data(self.filename))
        self.save_button.setEnabled(False)
        save_as_button = create_toolbutton(self,
                                           text=_("Save data as..."),
                                           icon=ima.icon('filesaveas'),
                                           triggered=self.save_data)

        if self.is_ipyclient:
            toolbar += [load_button, self.save_button, save_as_button]
        else:
            toolbar += [
                refresh_button, self.auto_refresh_button, load_button,
                self.save_button, save_as_button
            ]

        self.exclude_private_action = create_action(
            self,
            _("Exclude private references"),
            tip=_("Exclude references which name starts"
                  " with an underscore"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_private', state))
        self.exclude_private_action.setChecked(exclude_private)

        self.exclude_uppercase_action = create_action(
            self,
            _("Exclude all-uppercase references"),
            tip=_("Exclude references which name is uppercase"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_uppercase', state))
        self.exclude_uppercase_action.setChecked(exclude_uppercase)

        self.exclude_capitalized_action = create_action(
            self,
            _("Exclude capitalized references"),
            tip=_("Exclude references which name starts with an "
                  "uppercase character"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_capitalized', state))
        self.exclude_capitalized_action.setChecked(exclude_capitalized)

        self.exclude_unsupported_action = create_action(
            self,
            _("Exclude unsupported data types"),
            tip=_("Exclude references to unsupported data types"
                  " (i.e. which won't be handled/saved correctly)"),
            toggled=lambda state: self.sig_option_changed.emit(
                'exclude_unsupported', state))
        self.exclude_unsupported_action.setChecked(exclude_unsupported)

        self.setup_in_progress = False

        return toolbar
Beispiel #40
0
    def __init__(self, parent, workdir=None, **kwds):
        if PYQT5:
            super(WorkingDirectory, self).__init__(parent, **kwds)
        else:
            QToolBar.__init__(self, parent)
            SpyderPluginMixin.__init__(self, parent)

        # Initialize plugin
        self.initialize_plugin()

        self.setWindowTitle(self.get_plugin_title())  # Toolbar title
        self.setObjectName(
            self.get_plugin_title())  # Used to save Window state

        # Previous dir action
        self.history = []
        self.histindex = None
        self.previous_action = create_action(self,
                                             "previous",
                                             None,
                                             ima.icon('previous'),
                                             _('Back'),
                                             triggered=self.previous_directory)
        self.addAction(self.previous_action)

        # Next dir action
        self.history = []
        self.histindex = None
        self.next_action = create_action(self,
                                         "next",
                                         None,
                                         ima.icon('next'),
                                         _('Next'),
                                         triggered=self.next_directory)
        self.addAction(self.next_action)

        # Enable/disable previous/next actions
        self.set_previous_enabled.connect(self.previous_action.setEnabled)
        self.set_next_enabled.connect(self.next_action.setEnabled)

        # Path combo box
        adjust = self.get_option('working_dir_adjusttocontents')
        self.pathedit = PathComboBox(self, adjust_to_contents=adjust)
        self.pathedit.setToolTip(
            _("This is the working directory for newly\n"
              "opened consoles (Python/IPython consoles and\n"
              "terminals), for the file explorer, for the\n"
              "find in files plugin and for new files\n"
              "created in the editor"))
        self.pathedit.open_dir.connect(self.chdir)
        self.pathedit.activated[str].connect(self.chdir)
        self.pathedit.setMaxCount(self.get_option('working_dir_history'))
        wdhistory = self.load_wdhistory(workdir)
        if workdir is None:
            if self.get_option('console/use_project_or_home_directory'):
                workdir = get_home_dir()
            else:
                workdir = self.get_option('console/fixed_directory',
                                          default='')
                if not osp.isdir(workdir):
                    workdir = get_home_dir()
        self.chdir(workdir)
        self.pathedit.addItems(wdhistory)
        self.pathedit.selected_text = self.pathedit.currentText()
        self.refresh_plugin()
        self.addWidget(self.pathedit)

        # Browse action
        browse_action = create_action(self,
                                      "browse",
                                      None,
                                      ima.icon('DirOpenIcon'),
                                      _('Browse a working directory'),
                                      triggered=self.select_directory)
        self.addAction(browse_action)

        # Parent dir action
        parent_action = create_action(self,
                                      "parent",
                                      None,
                                      ima.icon('up'),
                                      _('Change to parent directory'),
                                      triggered=self.parent_directory)
        self.addAction(parent_action)
Beispiel #41
0
 def register_plugin(self):
     """Register plugin in Spyder's main window"""
     opensbml_act = create_action(self.main,
                                  _("Open SBML file"),
                                  triggered=self.run_opensbml)
     self.main.file_menu_actions.insert(5, opensbml_act)
Beispiel #42
0
    def __init__(self,
                 parent=None,
                 name_filters=['*.py', '*.pyw'],
                 show_all=False,
                 show_cd_only=None,
                 show_icontext=True):
        QWidget.__init__(self, parent)

        # Widgets
        self.treewidget = ExplorerTreeWidget(self, show_cd_only=show_cd_only)
        button_previous = QToolButton(self)
        button_next = QToolButton(self)
        button_parent = QToolButton(self)
        self.button_menu = QToolButton(self)
        menu = QMenu(self)

        self.action_widgets = [
            button_previous, button_next, button_parent, self.button_menu
        ]

        # Actions
        icontext_action = create_action(self,
                                        _("Show icons and text"),
                                        toggled=self.toggle_icontext)
        previous_action = create_action(
            self,
            text=_("Previous"),
            icon=ima.icon('ArrowBack'),
            triggered=self.treewidget.go_to_previous_directory)
        next_action = create_action(
            self,
            text=_("Next"),
            icon=ima.icon('ArrowForward'),
            triggered=self.treewidget.go_to_next_directory)
        parent_action = create_action(
            self,
            text=_("Parent"),
            icon=ima.icon('ArrowUp'),
            triggered=self.treewidget.go_to_parent_directory)
        options_action = create_action(self, text='', tip=_('Options'))

        # Setup widgets
        self.treewidget.setup(name_filters=name_filters, show_all=show_all)
        self.treewidget.chdir(getcwd())
        self.treewidget.common_actions += [None, icontext_action]

        button_previous.setDefaultAction(previous_action)
        previous_action.setEnabled(False)

        button_next.setDefaultAction(next_action)
        next_action.setEnabled(False)

        button_parent.setDefaultAction(parent_action)

        self.button_menu.setIcon(ima.icon('tooloptions'))
        self.button_menu.setPopupMode(QToolButton.InstantPopup)
        self.button_menu.setMenu(menu)
        add_actions(menu, self.treewidget.common_actions)
        options_action.setMenu(menu)

        self.toggle_icontext(show_icontext)
        icontext_action.setChecked(show_icontext)

        for widget in self.action_widgets:
            widget.setAutoRaise(True)
            widget.setIconSize(QSize(16, 16))

        # Layouts
        blayout = QHBoxLayout()
        blayout.addWidget(button_previous)
        blayout.addWidget(button_next)
        blayout.addWidget(button_parent)
        blayout.addStretch()
        blayout.addWidget(self.button_menu)

        layout = QVBoxLayout()
        layout.addLayout(blayout)
        layout.addWidget(self.treewidget)
        self.setLayout(layout)

        # Signals and slots
        self.treewidget.set_previous_enabled.connect(
            previous_action.setEnabled)
        self.treewidget.set_next_enabled.connect(next_action.setEnabled)
Beispiel #43
0
    def __init__(self, parent=None):
        super(BasePluginWidgetMixin, self).__init__()

        # Actions to add to the Options menu
        self._plugin_actions = None

        # Attribute to keep track if the plugin is undocked in a
        # separate window
        self._undocked_window = None

        self._ismaximized = False
        self._default_margins = None
        self._isvisible = False

        # Options buttons
        self.options_button = create_toolbutton(self,
                                                text=_('Options'),
                                                icon=ima.icon('tooloptions'))
        self.options_button.setPopupMode(QToolButton.InstantPopup)

        # Don't show menu arrow and remove padding
        if is_dark_interface():
            self.options_button.setStyleSheet(
                ("QToolButton::menu-indicator{image: none;}\n"
                 "QToolButton{padding: 3px;}"))
        else:
            self.options_button.setStyleSheet(
                "QToolButton::menu-indicator{image: none;}")

        # Options menu
        self._options_menu = QMenu(self)

        # NOTE: Don't use the default option of CONF.get to assign a
        # None shortcut to plugins that don't have one. That will mess
        # the creation of our Keyboard Shortcuts prefs page
        try:
            self.shortcut = CONF.get('shortcuts',
                                     '_/switch to %s' % self.CONF_SECTION)
        except configparser.NoOptionError:
            pass

        # We decided to create our own toggle action instead of using
        # the one that comes with dockwidget because it's not possible
        # to raise and focus the plugin with it.
        self._toggle_view_action = None

        # Default actions for Options menu
        self._dock_action = create_action(self,
                                          _("Dock"),
                                          icon=ima.icon('dock'),
                                          tip=_("Dock the pane"),
                                          triggered=self._close_window)

        self._undock_action = create_action(self,
                                            _("Undock"),
                                            icon=ima.icon('undock'),
                                            tip=_("Undock the pane"),
                                            triggered=self._create_window)

        self._close_plugin_action = create_action(
            self,
            _("Close"),
            icon=ima.icon('close_pane'),
            tip=_("Close the pane"),
            triggered=self._plugin_closed)
Beispiel #44
0
    def create_file_manage_actions(self, fnames):
        """Return file management actions"""
        only_files = all([osp.isfile(_fn) for _fn in fnames])
        only_modules = all([
            osp.splitext(_fn)[1] in ('.py', '.pyw', '.ipy') for _fn in fnames
        ])
        only_notebooks = all(
            [osp.splitext(_fn)[1] == '.ipynb' for _fn in fnames])
        only_valid = all([encoding.is_text_file(_fn) for _fn in fnames])
        run_action = create_action(self,
                                   _("Run"),
                                   icon=ima.icon('run'),
                                   triggered=self.run)
        edit_action = create_action(self,
                                    _("Edit"),
                                    icon=ima.icon('edit'),
                                    triggered=self.clicked)
        move_action = create_action(self,
                                    _("Move..."),
                                    icon="move.png",
                                    triggered=self.move)
        delete_action = create_action(self,
                                      _("Delete..."),
                                      icon=ima.icon('editdelete'),
                                      triggered=self.delete)
        rename_action = create_action(self,
                                      _("Rename..."),
                                      icon=ima.icon('rename'),
                                      triggered=self.rename)
        open_action = create_action(self, _("Open"), triggered=self.open)
        ipynb_convert_action = create_action(self,
                                             _("Convert to Python script"),
                                             icon=ima.icon('python'),
                                             triggered=self.convert_notebooks)

        actions = []
        if only_modules:
            actions.append(run_action)
        if only_valid and only_files:
            actions.append(edit_action)
        else:
            actions.append(open_action)
        actions += [delete_action, rename_action]
        basedir = fixpath(osp.dirname(fnames[0]))
        if all([fixpath(osp.dirname(_fn)) == basedir for _fn in fnames]):
            actions.append(move_action)
        actions += [None]
        if only_notebooks and nbexporter is not None:
            actions.append(ipynb_convert_action)

        # VCS support is quite limited for now, so we are enabling the VCS
        # related actions only when a single file/folder is selected:
        dirname = fnames[0] if osp.isdir(fnames[0]) else osp.dirname(fnames[0])
        if len(fnames) == 1 and vcs.is_vcs_repository(dirname):
            # QAction.triggered works differently for PySide and PyQt
            if not API == 'pyside':
                commit_slot = lambda _checked, fnames=[dirname]:\
                                    self.vcs_command(fnames, 'commit')
                browse_slot = lambda _checked, fnames=[dirname]:\
                                    self.vcs_command(fnames, 'browse')
            else:
                commit_slot = lambda fnames=[dirname]:\
                                    self.vcs_command(fnames, 'commit')
                browse_slot = lambda fnames=[dirname]:\
                                    self.vcs_command(fnames, 'browse')
            vcs_ci = create_action(self,
                                   _("Commit"),
                                   icon=ima.icon('vcs_commit'),
                                   triggered=commit_slot)
            vcs_log = create_action(self,
                                    _("Browse repository"),
                                    icon=ima.icon('vcs_browse'),
                                    triggered=browse_slot)
            actions += [None, vcs_ci, vcs_log]

        return actions
Beispiel #45
0
    def __init__(self,
                 plugin,
                 id_,
                 history_filename,
                 config_options,
                 additional_options,
                 interpreter_versions,
                 connection_file=None,
                 hostname=None,
                 menu_actions=None,
                 slave=False,
                 external_kernel=False,
                 given_name=None,
                 options_button=None,
                 show_elapsed_time=False,
                 reset_warning=True,
                 ask_before_restart=True,
                 css_path=None):
        super(ClientWidget, self).__init__(plugin)
        SaveHistoryMixin.__init__(self, history_filename)

        # --- Init attrs
        self.id_ = id_
        self.connection_file = connection_file
        self.hostname = hostname
        self.menu_actions = menu_actions
        self.slave = slave
        self.external_kernel = external_kernel
        self.given_name = given_name
        self.show_elapsed_time = show_elapsed_time
        self.reset_warning = reset_warning
        self.ask_before_restart = ask_before_restart

        # --- Other attrs
        self.options_button = options_button
        self.stop_button = None
        self.reset_button = None
        self.stop_icon = ima.icon('stop')
        self.history = []
        self.allow_rename = True
        self.stderr_dir = None
        self.is_error_shown = False

        if css_path is None:
            self.css_path = CSS_PATH
        else:
            self.css_path = css_path

        # --- Widgets
        self.shellwidget = ShellWidget(
            config=config_options,
            ipyclient=self,
            additional_options=additional_options,
            interpreter_versions=interpreter_versions,
            external_kernel=external_kernel,
            local_kernel=True)
        self.infowidget = WebView(self)
        self.set_infowidget_font()
        self.loading_page = self._create_loading_page()
        self._show_loading_page()

        # Elapsed time
        self.time_label = None
        self.t0 = time.monotonic()
        self.timer = QTimer(self)
        self.show_time_action = create_action(
            self,
            _("Show elapsed time"),
            toggled=self.set_elapsed_time_visible)

        # --- Layout
        vlayout = QVBoxLayout()
        toolbar_buttons = self.get_toolbar_buttons()

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.create_time_label())
        hlayout.addStretch(0)
        for button in toolbar_buttons:
            hlayout.addWidget(button)

        vlayout.addLayout(hlayout)
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addWidget(self.shellwidget)
        vlayout.addWidget(self.infowidget)
        self.setLayout(vlayout)

        # --- Exit function
        self.exit_callback = lambda: plugin.close_client(client=self)

        # --- Dialog manager
        self.dialog_manager = DialogManager()

        # Show timer
        self.update_time_label_visibility()
Beispiel #46
0
    def __init__(self,
                 plugin,
                 id_,
                 history_filename,
                 config_options,
                 additional_options,
                 interpreter_versions,
                 connection_file=None,
                 hostname=None,
                 menu_actions=None,
                 slave=False,
                 external_kernel=False,
                 given_name="MxConsole",
                 show_elapsed_time=False,
                 reset_warning=True,
                 **kwargs):
        super(ClientWidget, self).__init__(plugin)
        SaveHistoryMixin.__init__(self, history_filename)

        # --- Init attrs
        self.plugin = plugin
        self.id_ = id_
        self.connection_file = connection_file
        self.hostname = hostname
        self.menu_actions = menu_actions
        self.slave = slave
        self.external_kernel = external_kernel
        self.given_name = given_name
        self.show_elapsed_time = show_elapsed_time
        self.reset_warning = reset_warning
        if "ask_before_restart" in kwargs:
            self.ask_before_restart = kwargs["ask_before_restart"]

        # --- Other attrs
        if spyder.version_info > (4, ) and "options_button" in kwargs:
            self.options_button = kwargs["options_button"]
        else:
            self.options_button = None
        self.stop_button = None
        self.reset_button = None
        self.stop_icon = ima.icon('stop')
        self.history = []
        self.allow_rename = True
        self.stderr_dir = None
        self.is_error_shown = False
        self.restart_thread = None

        if "css_path" in kwargs:
            if kwargs["css_path"] is None:
                self.css_path = CSS_PATH
            else:
                self.css_path = kwargs["css_path"]

        # --- Widgets
        self.shellwidget = MxShellWidget(
            config=config_options,
            ipyclient=self,
            additional_options=additional_options,
            interpreter_versions=interpreter_versions,
            external_kernel=external_kernel,
            local_kernel=True)

        if spyder.version_info < (4, ):
            self.infowidget = WebView(self)
            self.set_infowidget_font()
        else:
            self.infowidget = plugin.infowidget
            self.blank_page = self._create_blank_page()

        self.loading_page = self._create_loading_page()
        # To keep a reference to the page to be displayed
        # in infowidget
        self.info_page = None
        if spyder.version_info < (4, 1):
            self._show_loading_page()
        else:
            self._before_prompt_is_ready()

        # Elapsed time
        self.time_label = None
        if spyder.version_info < (4, ):
            self.t0 = None
        else:
            self.t0 = time.monotonic()
        self.timer = QTimer(self)
        if spyder.version_info > (4, ):
            self.show_time_action = create_action(
                self,
                _("Show elapsed time"),
                toggled=self.set_elapsed_time_visible)
        # --- Layout
        self.layout = QVBoxLayout()
        toolbar_buttons = self.get_toolbar_buttons()

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.create_time_label())
        hlayout.addStretch(0)
        for button in toolbar_buttons:
            hlayout.addWidget(button)

        self.layout.addLayout(hlayout)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.shellwidget)
        self.layout.addWidget(self.infowidget)
        self.setLayout(self.layout)

        # --- Exit function
        self.exit_callback = lambda: plugin.close_client(client=self)

        # --- Dialog manager
        self.dialog_manager = DialogManager()

        # Show timer
        self.update_time_label_visibility()
Beispiel #47
0
    def get_plugin_actions(self):
        """Return a list of actions related to plugin"""
        quit_action = create_action(self,
                                    _("&Quit"),
                                    icon=ima.icon('exit'),
                                    tip=_("Quit"),
                                    triggered=self.quit)
        self.register_shortcut(quit_action, "_", "Quit", "Ctrl+Q")
        run_action = create_action(self,
                                   _("&Run..."),
                                   None,
                                   ima.icon('run_small'),
                                   _("Run a Python script"),
                                   triggered=self.run_script)
        environ_action = create_action(
            self,
            _("Environment variables..."),
            icon=ima.icon('environ'),
            tip=_("Show and edit environment variables"
                  " (for current session)"),
            triggered=self.show_env)
        syspath_action = create_action(self,
                                       _("Show sys.path contents..."),
                                       icon=ima.icon('syspath'),
                                       tip=_("Show (read-only) sys.path"),
                                       triggered=self.show_syspath)
        buffer_action = create_action(self,
                                      _("Buffer..."),
                                      None,
                                      tip=_("Set maximum line count"),
                                      triggered=self.change_max_line_count)
        exteditor_action = create_action(
            self,
            _("External editor path..."),
            None,
            None,
            _("Set external editor executable path"),
            triggered=self.change_exteditor)
        wrap_action = create_action(self,
                                    _("Wrap lines"),
                                    toggled=self.toggle_wrap_mode)
        wrap_action.setChecked(self.get_option('wrap'))
        calltips_action = create_action(self,
                                        _("Display balloon tips"),
                                        toggled=self.toggle_calltips)
        calltips_action.setChecked(self.get_option('calltips'))
        codecompletion_action = create_action(
            self,
            _("Automatic code completion"),
            toggled=self.toggle_codecompletion)
        codecompletion_action.setChecked(
            self.get_option('codecompletion/auto'))
        codecompenter_action = create_action(
            self,
            _("Enter key selects completion"),
            toggled=self.toggle_codecompletion_enter)
        codecompenter_action.setChecked(
            self.get_option('codecompletion/enter_key'))

        option_menu = QMenu(_('Internal console settings'), self)
        option_menu.setIcon(ima.icon('tooloptions'))
        add_actions(
            option_menu,
            (buffer_action, wrap_action, calltips_action,
             codecompletion_action, codecompenter_action, exteditor_action))

        plugin_actions = [
            None, run_action, environ_action, syspath_action, option_menu,
            MENU_SEPARATOR, quit_action, self.undock_action
        ]

        return plugin_actions
Beispiel #48
0
    def create_action(self,
                      name,
                      text,
                      icon=None,
                      icon_text='',
                      tip=None,
                      toggled=None,
                      triggered=None,
                      shortcut_context=None,
                      context=Qt.WidgetWithChildrenShortcut,
                      initial=None,
                      register_shortcut=False,
                      section=None,
                      option=None,
                      parent=None,
                      register_action=True,
                      overwrite=False,
                      context_name=None,
                      menurole=None):
        """
        name: str
            unique identifiable name for the action
        text: str
           Localized text for the action
        icon: QIcon,
            Icon for the action when applied to menu or toolbutton.
        icon_text: str
            Icon for text in toolbars. If True, this will also disable
            the tooltip on this toolbutton if part of a toolbar.
        tip: str
            Tooltip to define for action on menu or toolbar.
        toggled: Optional[Union[Callable, bool]]
            If True, then the action modifies the configuration option on the
            section specified. Otherwise, it should be a callable to use
            when toggling this action. If None, then the action does not
            behave like a checkbox.
        triggered: callable
            The callable to use when triggering this action.
        shortcut_context: str
            Set the `str` context of the shortcut.
        context: Qt.ShortcutContext
            Set the context for the shortcut.
        initial: object
            Sets the initial state of a togglable action. This does not emit
            the toggled signal.
        section: Optional[str]
            Name of the configuration section whose option is going to be
            modified. If None, and `option` is not None, then it defaults to
            the class `CONF_SECTION` attribute.
        option: ConfigurationKey
            Name of the configuration option whose value is reflected and
            affected by the action.
        register_shortcut: bool, optional
            If True, main window will expose the shortcut in Preferences.
            The default value is `False`.
        parent: QWidget (None)
            Define the parent of the widget. Use `self` if not provided.
        register_action: bool, optional
            If True, the action will be registered and searchable.
            The default value is `True`.
        overwrite: bool, optional
            If True, in case of action overwriting no warning will be shown.
            The default value is `False`
        context_name: Optional[str]
            Name of the context that holds the action in case of registration.
            The combination of `name` and `context_name` is unique so trying
            to register an action with the same `name` and `context_name` will
            cause a warning unless `overwrite` is set to `True`.
        menurole: QAction.MenuRole, optional
            Menu role for the action (it only has effect on macOS).

        Notes
        -----
        There is no need to set shortcuts right now. We only create actions
        with this (and similar methods) and these are then exposed as possible
        shortcuts on plugin registration in the main window with the
        register_shortcut argument.

        If icon_text is True, this will also disable the tooltip.

        If a shortcut is found in the default config then it is assigned,
        otherwise it's left blank for the user to define one for it.
        """
        if triggered is None and toggled is None:
            raise SpyderAPIError(
                'Action must provide the toggled or triggered parameters!')

        if parent is None:
            parent = self

        if toggled and not callable(toggled):
            toggled = lambda value: None

        if toggled is not None:
            if section is None and option is not None:
                section = self.CONF_SECTION

        action = create_action(
            parent,
            text=text,
            icon=icon,
            tip=tip,
            toggled=toggled,
            triggered=triggered,
            context=context,
            section=section,
            option=option,
            id_=name,
            plugin=self.PLUGIN_NAME,
            context_name=(self.CONTEXT_NAME
                          if context_name is None else context_name),
            register_action=register_action,
            overwrite=overwrite,
            menurole=menurole)
        action.name = name
        if icon_text:
            action.setIconText(icon_text)

        action.text_beside_icon = bool(icon_text)
        action.shortcut_context = shortcut_context
        action.register_shortcut = register_shortcut
        action.tip = tip

        if initial is not None:
            if toggled:
                action.setChecked(initial)
            elif triggered:
                raise SpyderAPIError(
                    'Initial values can only apply to togglable actions!')
        else:
            if toggled:
                if section is not None and option is not None:
                    value = CONF.get(section, option)
                    action.setChecked(value)

        return action