Ejemplo n.º 1
0
 def setup_context_menu(self):
     """Setup shell context menu"""
     self.menu = QMenu(self)
     self.cut_action = create_action(self,
                                     translate("ShellBaseWidget", "Cut"),
                                     shortcut=keybinding('Cut'),
                                     icon=get_icon('editcut.png'),
                                     triggered=self.cut)
     self.copy_action = create_action(self,
                                      translate("ShellBaseWidget", "Copy"),
                                      shortcut=keybinding('Copy'),
                                      icon=get_icon('editcopy.png'),
                                      triggered=self.copy)
     paste_action = create_action(self,
                                  translate("ShellBaseWidget", "Paste"),
                                  shortcut=keybinding('Paste'),
                                  icon=get_icon('editpaste.png'),
                                  triggered=self.paste)
     save_action = create_action(self,
                                 translate("ShellBaseWidget",
                                           "Save history log..."),
                                 icon=get_icon('filesave.png'),
                                 tip=translate(
                                     "ShellBaseWidget",
                                     "Save current history log (i.e. all "
                                     "inputs and outputs) in a text file"),
                                 triggered=self.save_historylog)
     add_actions(self.menu, (self.cut_action, self.copy_action,
                             paste_action, None, save_action))
Ejemplo n.º 2
0
 def set_user_env(reg):
     """Set HKCU (current user) environment variables"""
     reg = listdict2envdict(reg)
     types = dict()
     key = OpenKey(HKEY_CURRENT_USER, "Environment")
     for name in reg:
         try:
             _, types[name] = QueryValueEx(key, name)
         except WindowsError:
             types[name] = REG_EXPAND_SZ
     key = OpenKey(HKEY_CURRENT_USER, "Environment", 0, KEY_SET_VALUE)
     for name in reg:
         SetValueEx(key, name, 0, types[name], reg[name])
     try:
         from win32gui import SendMessageTimeout
         from win32con import (HWND_BROADCAST, WM_SETTINGCHANGE,
                               SMTO_ABORTIFHUNG)
         SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
                            "Environment", SMTO_ABORTIFHUNG, 5000)
     except ImportError:
         QMessageBox.warning(
             self, translate("WinUserEnvDialog", "Warning"),
             translate(
                 "WinUserEnvDialog",
                 "Module <b>pywin32 was not found</b>.<br>"
                 "Please restart this Windows <i>session</i> "
                 "(not the computer) for changes to take effect."))
Ejemplo n.º 3
0
 def insert_item(self):
     """Insert item"""
     index = self.currentIndex()
     if not index.isValid():
         row = self.model.rowCount()
     else:
         row = index.row()
     data = self.model.get_data()
     if isinstance(data, list):
         key = row
         data.insert(row, '')
     elif isinstance(data, dict):
         key, valid = QInputDialog.getText(self,
                           translate("DictEditor", 'Insert'),
                           translate("DictEditor", 'Key:'),
                           QLineEdit.Normal)
         if valid and not key.isEmpty():
             key = try_to_eval(unicode(key))
         else:
             return
     else:
         return
     value, valid = QInputDialog.getText(self,
               translate("DictEditor", 'Insert'),
               translate("DictEditor", 'Value:'),
               QLineEdit.Normal)
     if valid and not value.isEmpty():
         self.new_value(key, try_to_eval(unicode(value)))
Ejemplo n.º 4
0
    def set_user_env(reg):
        """Set HKCU (current user) environment variables"""
        reg = listdict2envdict(reg)
        types = dict()
        key = OpenKey(HKEY_CURRENT_USER, "Environment")
        for name in reg:
            try:
                _, types[name] = QueryValueEx(key, name)
            except WindowsError:
                types[name] = REG_EXPAND_SZ
        key = OpenKey(HKEY_CURRENT_USER, "Environment", 0, KEY_SET_VALUE)
        for name in reg:
            SetValueEx(key, name, 0, types[name], reg[name])
        try:
            from win32gui import SendMessageTimeout
            from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG

            SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000)
        except ImportError:
            QMessageBox.warning(
                self,
                translate("WinUserEnvDialog", "Warning"),
                translate(
                    "WinUserEnvDialog",
                    "Module <b>pywin32 was not found</b>.<br>"
                    "Please restart this Windows <i>session</i> "
                    "(not the computer) for changes to take effect.",
                ),
            )
Ejemplo n.º 5
0
 def insert_item(self):
     """Insert item"""
     index = self.currentIndex()
     if not index.isValid():
         row = self.model.rowCount()
     else:
         row = index.row()
     data = self.model.get_data()
     if isinstance(data, list):
         key = row
         data.insert(row, '')
     elif isinstance(data, dict):
         key, valid = QInputDialog.getText(
             self, translate("DictEditor", 'Insert'),
             translate("DictEditor", 'Key:'), QLineEdit.Normal)
         if valid and not key.isEmpty():
             key = try_to_eval(unicode(key))
         else:
             return
     else:
         return
     value, valid = QInputDialog.getText(self,
                                         translate("DictEditor", 'Insert'),
                                         translate("DictEditor", 'Value:'),
                                         QLineEdit.Normal)
     if valid and not value.isEmpty():
         self.new_value(key, try_to_eval(unicode(value)))
Ejemplo n.º 6
0
 def start(self):
     filename = unicode(self.filecombo.currentText())
     
     self.process = QProcess(self)
     self.process.setProcessChannelMode(QProcess.SeparateChannels)
     self.process.setWorkingDirectory(osp.dirname(filename))
     self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
                  self.read_output)
     self.connect(self.process, SIGNAL("readyReadStandardError()"),
                  lambda: self.read_output(error=True))
     self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"),
                  self.finished)
     self.connect(self.stop_button, SIGNAL("clicked()"),
                  self.process.kill)
     
     self.output = ''
     self.error_output = ''
     p_args = [osp.basename(filename)]
     self.process.start(PYLINT_PATH, p_args)
     
     running = self.process.waitForStarted()
     self.set_running_state(running)
     if not running:
         QMessageBox.critical(self, translate('Pylint', "Error"),
                              translate('Pylint', "Process failed to start"))
Ejemplo n.º 7
0
 def setup_context_menu(self):
     """Reimplements ShellBaseWidget method"""
     ShellBaseWidget.setup_context_menu(self)
     self.copy_without_prompts_action = create_action(self,
                                  translate("PythonShellWidget",
                                            "Copy without prompts"),
                                  icon=get_icon('copywop.png'),
                                  triggered=self.copy_without_prompts)
     clear_line_action = create_action(self, translate("PythonShellWidget",
                                                       "Clear line"),
                                  QKeySequence("Escape"),
                                  icon=get_icon('eraser.png'),
                                  tip=translate("PythonShellWidget",
                                                "Clear line"),
                                  triggered=self.clear_line)
     clear_action = create_action(self,
                                  translate("PythonShellWidget",
                                            "Clear shell"),
                                  icon=get_icon('clear.png'),
                                  tip=translate("PythonShellWidget",
                                                "Clear shell contents "
                                              "('cls' command)"),
                                  triggered=self.clear_terminal)
     add_actions(self.menu, (self.copy_without_prompts_action,
                 clear_line_action, clear_action))
Ejemplo n.º 8
0
 def show_docstring(self, text, call=False):
     """Show docstring or arguments"""
     if not self.calltips:
         return
     
     text = unicode(text) # Useful only for ExternalShellBase
     
     if (self.docviewer is not None) and \
        (self.docviewer.dockwidget.isVisible()):
         # DocViewer widget exists and is visible
         self.docviewer.refresh(text)
         self.setFocus() # if docviewer was not at top level, raising it to
                         # top will automatically give it focus because of
                         # the visibility_changed signal, so we must give
                         # focus back to shell
         if call:
             # Display argument list if this is function call
             iscallable = self.iscallable(text)
             if iscallable is not None:
                 if iscallable:
                     arglist = self.get_arglist(text)
                     if arglist:
                         self.show_calltip(translate("PythonShellWidget",
                                                     "Arguments"),
                                           arglist, '#129625')
     else: # docviewer is not visible
         doc = self.get__doc__(text)
         if doc is not None:
             self.show_calltip(translate("PythonShellWidget",
                                         "Documentation"), doc)
Ejemplo n.º 9
0
    def __init__(self, parent):
        PluginWidget.__init__(self, parent)

        # Read-only editor
        self.editor = QsciEditor(self)
        self.editor.setup_editor(linenumbers=False, language='py',
                                 code_folding=True)
        self.connect(self.editor, SIGNAL("focus_changed()"),
                     lambda: self.emit(SIGNAL("focus_changed()")))
        self.editor.setReadOnly(True)
        self.editor.set_font( get_font(self.ID) )
        self.editor.toggle_wrap_mode( CONF.get(self.ID, 'wrap') )
        
        # Add entries to read-only editor context-menu
        font_action = create_action(self, translate("Editor", "&Font..."), None,
                                    'font.png',
                                    translate("Editor", "Set font style"),
                                    triggered=self.change_font)
        wrap_action = create_action(self, translate("Editor", "Wrap lines"),
                                    toggled=self.toggle_wrap_mode)
        wrap_action.setChecked( CONF.get(self.ID, 'wrap') )
        self.editor.readonly_menu.addSeparator()
        add_actions(self.editor.readonly_menu, (font_action, wrap_action))
        
        # Find/replace widget
        self.find_widget = FindReplace(self)
        self.find_widget.set_editor(self.editor)
        self.find_widget.hide()
Ejemplo n.º 10
0
 def setup_context_menu(self):
     """Setup shell context menu"""
     self.menu = QMenu(self)
     self.cut_action = create_action(self,
                                     translate("ShellBaseWidget", "Cut"),
                                     shortcut=keybinding('Cut'),
                                     icon=get_icon('editcut.png'),
                                     triggered=self.cut)
     self.copy_action = create_action(self,
                                      translate("ShellBaseWidget", "Copy"),
                                      shortcut=keybinding('Copy'),
                                      icon=get_icon('editcopy.png'),
                                      triggered=self.copy)
     paste_action = create_action(self,
                                  translate("ShellBaseWidget", "Paste"),
                                  shortcut=keybinding('Paste'),
                                  icon=get_icon('editpaste.png'),
                                  triggered=self.paste)
     save_action = create_action(self,
                                 translate("ShellBaseWidget",
                                           "Save history log..."),
                                 icon=get_icon('filesave.png'),
                                 tip=translate("ShellBaseWidget",
                                       "Save current history log (i.e. all "
                                       "inputs and outputs) in a text file"),
                                 triggered=self.save_historylog)
     add_actions(self.menu, (self.cut_action, self.copy_action,
                             paste_action, None, save_action) )
Ejemplo n.º 11
0
    def start(self):
        filename = unicode(self.filecombo.currentText())

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setWorkingDirectory(osp.dirname(filename))
        self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
                     self.read_output)
        self.connect(self.process, SIGNAL("readyReadStandardError()"),
                     lambda: self.read_output(error=True))
        self.connect(self.process,
                     SIGNAL("finished(int,QProcess::ExitStatus)"),
                     self.finished)
        self.connect(self.stop_button, SIGNAL("clicked()"), self.process.kill)

        self.output = ''
        self.error_output = ''
        p_args = [osp.basename(filename)]
        self.process.start(PYLINT_PATH, p_args)

        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(
                self, translate('Pylint', "Error"),
                translate('Pylint', "Process failed to start"))
Ejemplo n.º 12
0
    def show_docstring(self, text, call=False):
        """Show docstring or arguments"""
        if not self.calltips:
            return

        text = unicode(text)  # Useful only for ExternalShellBase

        if (self.docviewer is not None) and \
           (self.docviewer.dockwidget.isVisible()):
            # DocViewer widget exists and is visible
            self.docviewer.refresh(text)
            self.setFocus()  # if docviewer was not at top level, raising it to
            # top will automatically give it focus because of
            # the visibility_changed signal, so we must give
            # focus back to shell
            if call:
                # Display argument list if this is function call
                iscallable = self.iscallable(text)
                if iscallable is not None:
                    if iscallable:
                        arglist = self.get_arglist(text)
                        if arglist:
                            self.show_calltip(
                                translate("PythonShellWidget", "Arguments"),
                                arglist, '#129625')
        else:  # docviewer is not visible
            doc = self.get__doc__(text)
            if doc is not None:
                self.show_calltip(
                    translate("PythonShellWidget", "Documentation"), doc)
Ejemplo n.º 13
0
 def start(self):
     self.datelabel.setText('Profiling, please wait...')
     filename = unicode(self.filecombo.currentText())
     
     self.process = QProcess(self)
     self.process.setProcessChannelMode(QProcess.SeparateChannels)
     self.process.setWorkingDirectory(os.path.dirname(filename))
     self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
                  self.read_output)
     self.connect(self.process, SIGNAL("readyReadStandardError()"),
                  lambda: self.read_output(error=True))
     self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"),
                  self.finished)
     self.connect(self.stop_button, SIGNAL("clicked()"),
                  self.process.kill)
     
     self.output = ''
     self.error_output = ''
     p_args = [os.path.basename(filename)]
     
     # FIXME: Use the system path to 'python' as opposed to hardwired
     p_args = ['-m', PROFILER_PATH, '-o', self.DATAPATH, os.path.basename(filename)]
     self.process.start('python', p_args)
     
     running = self.process.waitForStarted()
     self.set_running_state(running)
     if not running:
         QMessageBox.critical(self, translate('Profiler', "Error"),
                              translate('Profiler', "Process failed to start"))
Ejemplo n.º 14
0
 def get_toolbar_buttons(self):
     if self.run_button is None:
         self.run_button = create_toolbutton(self, get_icon('run.png'),
                           translate('ExternalShellBase', "Run"),
                           tip=translate('ExternalShellBase',
                                         "Run again this program"),
                           triggered=self.start)
     if self.kill_button is None:
         self.kill_button = create_toolbutton(self, get_icon('kill.png'),
                           translate('ExternalShellBase', "Kill"),
                           tip=translate('ExternalShellBase',
                                         "Kills the current process, "
                                         "causing it to exit immediately"))
     buttons = [self.run_button, self.kill_button]
     if self.options_button is None:
         options = self.get_options_menu()
         if options:
             self.options_button = create_toolbutton(self,
                                         text=self.tr("Options"),
                                         icon=get_icon('tooloptions.png'))
             self.options_button.setPopupMode(QToolButton.InstantPopup)
             menu = QMenu(self)
             add_actions(menu, options)
             self.options_button.setMenu(menu)
     if self.options_button is not None:
         buttons.insert(1, self.options_button)
     return buttons
Ejemplo n.º 15
0
 def _set_step(self,step):
     """Proceed to a given step"""
     new_tab = self.tab_widget.currentIndex() + step
     assert new_tab < self.tab_widget.count() and new_tab >= 0
     if new_tab == self.tab_widget.count()-1:
         try:
             self.table_widget.open_data(self._get_plain_text(),
                                     self.text_widget.get_col_sep(),
                                     self.text_widget.get_row_sep(),
                                     self.text_widget.trnsp_box.isChecked(),
                                     self.text_widget.get_skiprows(),
                                     self.text_widget.get_comments())
             self.done_btn.setEnabled(True)
             self.done_btn.setDefault(True)
             self.fwd_btn.setEnabled(False)
             self.back_btn.setEnabled(True)
         except (SyntaxError, AssertionError), error:
             QMessageBox.critical(self,
                         translate("ImportWizard", "Import wizard"),
                         translate("ImportWizard",
                                   "<b>Unable to proceed to next step</b>"
                                   "<br><br>Please check your entries."
                                   "<br><br>Error message:<br>%2") \
                         .arg(str(error)))
             return
Ejemplo n.º 16
0
    def __init__(self, parent, data, readonly=False, title="",
                 names=False, truncate=True, minmax=False,
                 inplace=False, collvalue=True):
        BaseTableView.__init__(self, parent)
        self.dictfilter = None
        self.readonly = readonly or isinstance(data, tuple)
        self.model = None
        self.delegate = None
        DictModelClass = ReadOnlyDictModel if self.readonly else DictModel
        self.model = DictModelClass(self, data, title, names=names,
                                    truncate=truncate, minmax=minmax,
                                    collvalue=collvalue)
        self.setModel(self.model)
        self.delegate = DictDelegate(self, inplace=inplace)
        self.setItemDelegate(self.delegate)

        self.setup_table()
        self.menu = self.setup_menu(truncate, minmax, inplace, collvalue)
        self.copy_action = create_action(self,
                                      translate("DictEditor", "Copy"),
                                      icon=get_icon('editcopy.png'),
                                      triggered=self.copy)                                      
        self.paste_action = create_action(self,
                                      translate("DictEditor", "Paste"),
                                      icon=get_icon('editpaste.png'),
                                      triggered=self.paste)
        self.menu.insertAction(self.remove_action, self.copy_action)
        self.menu.insertAction(self.remove_action, self.paste_action)
        
        self.empty_ws_menu = QMenu(self)
        self.empty_ws_menu.addAction(self.paste_action)
Ejemplo n.º 17
0
 def select_file(self):
     self.emit(SIGNAL('redirect_stdio(bool)'), False)
     filename = QFileDialog.getOpenFileName(
         self, translate('Pylint', "Select Python script"), os.getcwdu(),
         translate('Pylint', "Python scripts") + " (*.py ; *.pyw)")
     self.emit(SIGNAL('redirect_stdio(bool)'), False)
     if filename:
         self.analyze(filename)
Ejemplo n.º 18
0
 def select_file(self):
     self.emit(SIGNAL('redirect_stdio(bool)'), False)
     filename = QFileDialog.getOpenFileName(self,
                   translate('Pylint', "Select Python script"), os.getcwdu(),
                   translate('Pylint', "Python scripts")+" (*.py ; *.pyw)")
     self.emit(SIGNAL('redirect_stdio(bool)'), False)
     if filename:
         self.analyze(filename)
Ejemplo n.º 19
0
 def get_plugin_actions(self):
     """Setup actions"""
     # Font
     font_action = create_action(self, translate('Explorer', "&Font..."),
                                 None, 'font.png',
                                 translate("Explorer", "Set font style"),
                                 triggered=self.change_font)
     self.treewidget.common_actions.append(font_action)
     return (None, None)
Ejemplo n.º 20
0
 def __prepare_plot(self):
     try:
         from matplotlib import rcParams
         rcParams['backend'] = 'Qt4agg'
         return True
     except ImportError:
         QMessageBox.warning(self, translate("DictEditor", "Import error"),
                 translate("DictEditor",
                           "Please install <b>matplotlib</b>."))
Ejemplo n.º 21
0
 def get_arguments(self):
     arguments, valid = QInputDialog.getText(self,
                               translate('ExternalShellBase', 'Arguments'),
                               translate('ExternalShellBase',
                                         'Command line arguments:'),
                               QLineEdit.Normal, self.arguments)
     if valid:
         self.arguments = unicode(arguments)
     return valid
Ejemplo n.º 22
0
 def __prepare_plot(self):
     try:
         from matplotlib import rcParams
         rcParams['backend'] = 'Qt4agg'
         return True
     except ImportError:
         QMessageBox.warning(
             self, translate("DictEditor", "Import error"),
             translate("DictEditor", "Please install <b>matplotlib</b>."))
Ejemplo n.º 23
0
 def set_actions(self):
     """Setup actions"""
     # Font
     font_action = create_action(self, translate('Explorer', "&Font..."),
                                 None, 'font.png',
                                 translate("Explorer", "Set font style"),
                                 triggered=self.change_font)
     self.treewidget.common_actions.append(font_action)
     return (None, None)
Ejemplo n.º 24
0
    def __init__(self,
                 parent,
                 search_text=r"# ?TODO|# ?FIXME|# ?XXX",
                 search_text_regexp=True,
                 search_path=None,
                 include=".",
                 include_regexp=True,
                 exclude=r"\.pyc$|\.orig$|\.hg|\.svn",
                 exclude_regexp=True,
                 supported_encodings=("utf-8", "iso-8859-1", "cp1252")):
        QWidget.__init__(self, parent)

        self.search_thread = SearchThread(self)
        self.connect(self.search_thread, SIGNAL("finished()"),
                     self.search_complete)

        self.find_options = FindOptions(self, search_text, search_text_regexp,
                                        search_path, include, include_regexp,
                                        exclude, exclude_regexp,
                                        supported_encodings)
        self.connect(self.find_options, SIGNAL('find()'), self.find)
        self.connect(self.find_options, SIGNAL('stop()'), self.stop)

        self.result_browser = ResultsBrowser(self)

        collapse_btn = create_toolbutton(
            self,
            get_icon("collapse.png"),
            tip=translate('FindInFiles', "Collapse all"),
            triggered=self.result_browser.collapseAll)
        expand_btn = create_toolbutton(self,
                                       get_icon("expand.png"),
                                       tip=translate('FindInFiles',
                                                     "Expand all"),
                                       triggered=self.result_browser.expandAll)
        restore_btn = create_toolbutton(self,
                                        get_icon("restore.png"),
                                        tip=translate(
                                            'FindInFiles',
                                            "Restore original tree layout"),
                                        triggered=self.result_browser.restore)
        btn_layout = QVBoxLayout()
        btn_layout.setAlignment(Qt.AlignTop)
        for widget in [collapse_btn, expand_btn, restore_btn]:
            btn_layout.addWidget(widget)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.result_browser)
        hlayout.addLayout(btn_layout)

        layout = QVBoxLayout()
        left, _, right, bottom = layout.getContentsMargins()
        layout.setContentsMargins(left, 0, right, bottom)
        layout.addWidget(self.find_options)
        layout.addLayout(hlayout)
        self.setLayout(layout)
Ejemplo n.º 25
0
 def __prepare_plot(self):
     try:
         from spyderlib import mpl_patch
         mpl_patch.set_backend("Qt4Agg")
         mpl_patch.apply()
         return True
     except ImportError:
         QMessageBox.warning(self, translate("DictEditor", "Import error"),
                 translate("DictEditor",
                           "Please install <b>matplotlib</b>."))
Ejemplo n.º 26
0
 def imshow_item(self):
     """Imshow item"""
     index = self.currentIndex()
     if self.__prepare_plot():
         key = self.model.get_key(index)
         try:
             self.imshow(key)
         except ValueError, error:
             QMessageBox.critical(self, translate("DictEditor", "Plot"),
                 translate("DictEditor", "<b>Unable to show image.</b>"
                           "<br><br>Error message:<br>%1").arg(str(error)))
Ejemplo n.º 27
0
 def edit_filter(self):
     """Edit name filters"""
     filters, valid = QInputDialog.getText(
         self, translate('Explorer', 'Edit filename filters'),
         translate('Explorer', 'Name filters:'), QLineEdit.Normal,
         ", ".join(self.name_filters))
     if valid:
         filters = [f.strip() for f in unicode(filters).split(',')]
         self.parent_widget.emit(SIGNAL('option_changed'), 'name_filters',
                                 filters)
         self.set_name_filters(filters)
Ejemplo n.º 28
0
 def toggle_more_options(self, state):
     for layout in self.more_widgets:
         for index in range(layout.count()):
             layout.itemAt(index).widget().setVisible(state)
     if state:
         icon_name = 'options_less.png'
         tip = translate('FindInFiles', 'Hide advanced options')
     else:
         icon_name = 'options_more.png'
         tip = translate('FindInFiles', 'Show advanced options')
     self.more_options.setIcon(get_icon(icon_name))
     self.more_options.setToolTip(tip)
Ejemplo n.º 29
0
 def edit_filter(self):
     """Edit name filters"""
     filters, valid = QInputDialog.getText(self,
                           translate('Explorer', 'Edit filename filters'),
                           translate('Explorer', 'Name filters:'),
                           QLineEdit.Normal,
                           ", ".join(self.name_filters))
     if valid:
         filters = [f.strip() for f in unicode(filters).split(',')]
         self.parent_widget.emit(SIGNAL('option_changed'),
                                 'name_filters', filters)
         self.set_name_filters(filters)
Ejemplo n.º 30
0
 def refresh(self):
     title = translate('Pylint', 'Results for ')+self.filename
     self.set_title(title)
     self.clear()
     self.data = {}
     # Populating tree
     results = ((translate('Pylint', 'Convention'),
                 get_icon('convention.png'), self.results['C:']),
                (translate('Pylint', 'Refactor'),
                 get_icon('refactor.png'), self.results['R:']),
                (translate('Pylint', 'Warning'),
                 get_icon('warning.png'), self.results['W:']),
                (translate('Pylint', 'Error'),
                 get_icon('error.png'), self.results['E:']))
     for title, icon, messages in results:
         title += ' (%d message%s)' % (len(messages),
                                       's' if len(messages)>1 else '')
         title_item = QTreeWidgetItem(self, [title])
         title_item.setIcon(0, icon)
         if not messages:
             title_item.setDisabled(True)
         modules = {}
         for module, lineno, message in messages:
             basename = osp.splitext(osp.basename(self.filename))[0]
             if not module.startswith(basename):
                 # Pylint bug
                 i_base = module.find(basename)
                 module = module[i_base:]
             dirname = osp.dirname(self.filename)
             if module.startswith('.'):
                 modname = osp.join(dirname, module)
             else:
                 modname = osp.join(dirname, *module.split('.'))
             if osp.isdir(modname):
                 modname = osp.join(modname, '__init__')
             for ext in ('.py', '.pyw'):
                 if osp.isfile(modname+ext):
                     modname = modname + ext
                     break
             if osp.isdir(self.filename):
                 parent = modules.get(modname)
                 if parent is None:
                     item = QTreeWidgetItem(title_item, [module])
                     item.setIcon(0, get_icon('py.png'))
                     modules[modname] = item
                     parent = item
             else:
                 parent = title_item
             msg_item = QTreeWidgetItem(parent,
                                        ["%d : %s" % (lineno, message)])
             msg_item.setIcon(0, get_icon('arrow.png'))
             self.data[msg_item] = (modname, lineno)
Ejemplo n.º 31
0
 def set_running_state(self, state=True):
     self.set_buttons_runnning_state(state)
     self.shell.setReadOnly(not state)
     if state:
         self.state_label.setText(translate('ExternalShellBase',
                "<span style=\'color: #44AA44\'><b>Running...</b></span>"))
         self.t0 = time()
         self.connect(self.timer, SIGNAL("timeout()"), self.show_time)
         self.timer.start(1000)        
     else:
         self.state_label.setText(translate('ExternalShellBase',
                                            'Terminated.'))
         self.disconnect(self.timer, SIGNAL("timeout()"), self.show_time)
Ejemplo n.º 32
0
 def set_actions(self):
     """Setup actions"""
     # Font
     history_action = create_action(self, self.tr("History..."),
                                    None, 'history.png',
                                    self.tr("Set history maximum entries"),
                                    triggered=self.change_history_depth)
     font_action = create_action(self, translate('Pylint', "&Font..."),
                                 None, 'font.png',
                                 translate("Pylint", "Set font style"),
                                 triggered=self.change_font)
     self.treewidget.common_actions += (None, history_action, font_action)
     return (None, None)
Ejemplo n.º 33
0
 def refresh(self):
     title = translate('Pylint', 'Results for ') + self.filename
     self.set_title(title)
     self.clear()
     self.data = {}
     # Populating tree
     results = ((translate('Pylint', 'Convention'),
                 get_icon('convention.png'), self.results['C:']),
                (translate('Pylint', 'Refactor'), get_icon('refactor.png'),
                 self.results['R:']),
                (translate('Pylint', 'Warning'), get_icon('warning.png'),
                 self.results['W:']), (translate('Pylint', 'Error'),
                                       get_icon('error.png'),
                                       self.results['E:']))
     for title, icon, messages in results:
         title += ' (%d message%s)' % (len(messages),
                                       's' if len(messages) > 1 else '')
         title_item = QTreeWidgetItem(self, [title])
         title_item.setIcon(0, icon)
         if not messages:
             title_item.setDisabled(True)
         modules = {}
         for module, lineno, message in messages:
             basename = osp.splitext(osp.basename(self.filename))[0]
             if not module.startswith(basename):
                 # Pylint bug
                 i_base = module.find(basename)
                 module = module[i_base:]
             dirname = osp.dirname(self.filename)
             modname = osp.join(dirname, *module.split('.'))
             if osp.isdir(modname):
                 modname = osp.join(modname, '__init__')
             for ext in ('.py', '.pyw'):
                 if osp.isfile(modname + ext):
                     modname = modname + ext
                     break
             if osp.isdir(self.filename):
                 parent = modules.get(modname)
                 if parent is None:
                     item = QTreeWidgetItem(title_item, [module])
                     item.setIcon(0, get_icon('py.png'))
                     modules[modname] = item
                     parent = item
             else:
                 parent = title_item
             msg_item = QTreeWidgetItem(parent,
                                        ["%d : %s" % (lineno, message)])
             msg_item.setIcon(0, get_icon('arrow.png'))
             self.data[msg_item] = (modname, lineno)
Ejemplo n.º 34
0
 def headerData(self, section, orientation, role=Qt.DisplayRole):
     """Overriding method headerData"""
     if role != Qt.DisplayRole:
         if role == Qt.FontRole:
             return QVariant(get_font('dicteditor_header'))
         else:
             return QVariant()
     i_column = int(section)
     if orientation == Qt.Horizontal:
         headers = (self.header0, translate("DictEditor", "Type"),
                    translate("DictEditor",
                              "Size"), translate("DictEditor", "Value"))
         return QVariant(headers[i_column])
     else:
         return QVariant()
Ejemplo n.º 35
0
 def paste(self):
     """Import text/data/code from clipboard"""
     clipboard = QApplication.clipboard()
     cliptext = u""
     if clipboard.mimeData().hasText():
         cliptext = unicode(clipboard.text())
     if cliptext.strip():
         self.import_from_string(cliptext,
                                 title=translate("DictEditor",
                                                 "Import from clipboard"))
     else:
         QMessageBox.warning(self,
                             translate("DictEditor", "Empty clipboard"),
                             translate("DictEditor", "Nothing to be imported"
                                       " from clipboard."))
Ejemplo n.º 36
0
 def paste(self):
     """Import text/data/code from clipboard"""
     clipboard = QApplication.clipboard()
     cliptext = u""
     if clipboard.mimeData().hasText():
         cliptext = unicode(clipboard.text())
     if cliptext.strip():
         self.import_from_string(cliptext,
                                 title=translate("DictEditor",
                                                 "Import from clipboard"))
     else:
         QMessageBox.warning(
             self, translate("DictEditor", "Empty clipboard"),
             translate("DictEditor", "Nothing to be imported"
                       " from clipboard."))
Ejemplo n.º 37
0
 def headerData(self, section, orientation, role=Qt.DisplayRole):
     """Overriding method headerData"""
     if role != Qt.DisplayRole:
         if role == Qt.FontRole:
             return QVariant(get_font('dicteditor_header'))
         else:
             return QVariant()
     i_column = int(section)
     if orientation == Qt.Horizontal:
         headers = (self.header0,
                    translate("DictEditor", "Type"),
                    translate("DictEditor", "Size"),
                    translate("DictEditor", "Value"))
         return QVariant( headers[i_column] )
     else:
         return QVariant()
Ejemplo n.º 38
0
 def get_actions_from_items(self, items):
     """Reimplemented OneColumnTree method"""
     fromcursor_act = create_action(self,
                     text=translate('ClassBrowser', 'Go to cursor position'),
                     icon=get_icon('fromcursor.png'),
                     triggered=self.go_to_cursor_position)
     fullpath_act = create_action(self,
                     text=translate('ClassBrowser', 'Show absolute path'),
                     toggled=self.toggle_fullpath_mode)
     fullpath_act.setChecked(self.show_fullpath)
     allfiles_act = create_action(self,
                     text=translate('ClassBrowser', 'Show all files'),
                     toggled=self.toggle_show_all_files)
     allfiles_act.setChecked(self.show_all_files)
     actions = [fullpath_act, allfiles_act, fromcursor_act]
     return actions
Ejemplo n.º 39
0
 def setup_common_actions(self):
     """Setup context menu common actions"""
     # Filters
     filters_action = create_action(self,
                                    translate('Explorer',
                                              "Edit filename filters..."),
                                    None, get_icon('filter.png'),
                                    triggered=self.edit_filter)
     # Show all files
     all_action = create_action(self,
                                translate('Explorer', "Show all files"),
                                toggled=self.toggle_all)
     all_action.setChecked(self.show_all)
     self.toggle_all(self.show_all)
     
     return [filters_action, all_action]
Ejemplo n.º 40
0
 def change_font(self):
     """Change font"""
     font, valid = QFontDialog.getFont(get_font(self.ID), self,
                               translate("Pylint", "Select a new font"))
     if valid:
         self.set_font(font)
         set_font(font, self.ID)
Ejemplo n.º 41
0
 def change_font(self):
     """Change console font"""
     font, valid = QFontDialog.getFont(get_font(self.ID), self,
                                   translate("Editor", "Select a new font"))
     if valid:
         self.editor.set_font(font)
         set_font(font, self.ID)
Ejemplo n.º 42
0
 def change_format(self):
     """Change display format"""
     format, valid = QInputDialog.getText(self,
                              translate("ArrayEditor", 'Format'),
                              translate("ArrayEditor", "Float formatting"),
                              QLineEdit.Normal, self.model.get_format())
     if valid:
         format = str(format)
         try:
             format % 1.1
         except:
             QMessageBox.critical(self, translate("ArrayEditor", "Error"),
                       translate("ArrayEditor",
                                 "Format (%1) is incorrect").arg(format))
             return
         self.model.set_format(format)    
Ejemplo n.º 43
0
 def change_font(self):
     """Change font"""
     font, valid = QFontDialog.getFont(
         get_font(self.ID), self, translate("Pylint", "Select a new font"))
     if valid:
         self.set_font(font)
         set_font(font, self.ID)
Ejemplo n.º 44
0
def get_type(item):
    """Return type of an item"""
    found = re.findall(r"<type '([\S]*)'>", str(type(item)))
    text = unicode(translate('DictEditor', 'unknown')) \
           if not found else found[0]
    if isinstance(item, ndarray):
        text = item.dtype.name
    return text[text.find('.') + 1:]
Ejemplo n.º 45
0
 def resize_to_contents(self):
     """Resize cells to contents"""
     size = 1
     for dim in self.shape:
         size *= dim
     if size > 1e5:
         answer = QMessageBox.warning(self, translate("ArrayEditor",
                                                      "Array editor"),
                             translate("ArrayEditor",
                                       "Resizing cells of a table of such "
                                       "size could take a long time.\n"
                                       "Do you want to continue anyway?"),
                             QMessageBox.Yes | QMessageBox.No)
         if answer == QMessageBox.No:
             return
     self.resizeColumnsToContents()
     self.resizeRowsToContents()
Ejemplo n.º 46
0
    def setup_common_actions(self):
        """Setup context menu common actions"""
        # Filters
        filters_action = create_action(self,
                                       translate('Explorer',
                                                 "Edit filename filters..."),
                                       None,
                                       get_icon('filter.png'),
                                       triggered=self.edit_filter)
        # Show all files
        all_action = create_action(self,
                                   translate('Explorer', "Show all files"),
                                   toggled=self.toggle_all)
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        return [filters_action, all_action]
Ejemplo n.º 47
0
 def remove_item(self):
     """Remove item"""
     indexes = self.selectedIndexes()
     if not indexes:
         return
     for index in indexes:
         if not index.isValid():
             return
     answer = QMessageBox.question(self,
         translate("DictEditor", "Remove"),
         translate("DictEditor", "Do you want to remove selected item%1?") \
         .arg('s' if len(indexes)>1 else ''),
         QMessageBox.Yes | QMessageBox.No)
     if answer == QMessageBox.Yes:
         idx_rows = unsorted_unique(map(lambda idx: idx.row(), indexes))
         keys = [self.model.keys[idx_row] for idx_row in idx_rows]
         self.remove_values(keys)
Ejemplo n.º 48
0
 def change_format(self):
     """Change display format"""
     format, valid = QInputDialog.getText(
         self, translate("ArrayEditor", 'Format'),
         translate("ArrayEditor", "Float formatting"), QLineEdit.Normal,
         self.model.get_format())
     if valid:
         format = str(format)
         try:
             format % 1.1
         except:
             QMessageBox.critical(
                 self, translate("ArrayEditor", "Error"),
                 translate("ArrayEditor",
                           "Format (%1) is incorrect").arg(format))
             return
         self.model.set_format(format)
Ejemplo n.º 49
0
 def set_actions(self):
     """Setup actions"""
     # Font
     history_action = create_action(self,
                                    self.tr("History..."),
                                    None,
                                    'history.png',
                                    self.tr("Set history maximum entries"),
                                    triggered=self.change_history_depth)
     font_action = create_action(self,
                                 translate('Pylint', "&Font..."),
                                 None,
                                 'font.png',
                                 translate("Pylint", "Set font style"),
                                 triggered=self.change_font)
     self.treewidget.common_actions += (None, history_action, font_action)
     return (None, None)
Ejemplo n.º 50
0
 def setup_context_menu(self):
     """Reimplement PythonShellWidget method"""
     PythonShellWidget.setup_context_menu(self)
     self.help_action = create_action(self,
                        translate("InteractiveShell", "Help..."),
                        icon=get_std_icon('DialogHelpButton'),
                        triggered=self.help)
     self.menu.addAction(self.help_action)
Ejemplo n.º 51
0
 def resize_to_contents(self):
     """Resize cells to contents"""
     size = 1
     for dim in self.shape:
         size *= dim
     if size > 1e5:
         answer = QMessageBox.warning(
             self, translate("ArrayEditor", "Array editor"),
             translate(
                 "ArrayEditor", "Resizing cells of a table of such "
                 "size could take a long time.\n"
                 "Do you want to continue anyway?"),
             QMessageBox.Yes | QMessageBox.No)
         if answer == QMessageBox.No:
             return
     self.resizeColumnsToContents()
     self.resizeRowsToContents()
Ejemplo n.º 52
0
    def show_data(self, justanalyzed=False):
        if not justanalyzed:
            self.output = None
        self.log_button.setEnabled(self.output is not None \
                                   and len(self.output) > 0)
        self.kill_if_running()
        filename = unicode(self.filecombo.currentText())
        if not filename:
            return

        _index, data = self.get_data(filename)
        if data is None:
            text = translate('Pylint', 'Source code has not been rated yet.')
            self.treewidget.clear()
            date_text = ''
        else:
            datetime, rate, previous_rate, results = data
            if rate is None:
                text = translate(
                    'Pylint', 'Analysis did not succeed '
                    '(see output for more details).')
                self.treewidget.clear()
                date_text = ''
            else:
                text_style = "<span style=\'color: #444444\'><b>%s </b></span>"
                rate_style = "<span style=\'color: %s\'><b>%s</b></span>"
                prevrate_style = "<span style=\'color: #666666\'>%s</span>"
                color = "#FF0000"
                if float(rate) > 5.:
                    color = "#22AA22"
                elif float(rate) > 3.:
                    color = "#EE5500"
                text = translate('Pylint', 'Global evaluation:')
                text = (text_style % text) + (rate_style % (color,
                                                            ('%s/10' % rate)))
                if previous_rate:
                    text_prun = translate('Pylint', 'previous run:')
                    text_prun = ' (%s %s/10)' % (text_prun, previous_rate)
                    text += prevrate_style % text_prun
                self.treewidget.set_results(filename, results)
                date_text = text_style % time.strftime("%d %b %Y %H:%M",
                                                       datetime)

        self.ratelabel.setText(text)
        self.datelabel.setText(date_text)
Ejemplo n.º 53
0
 def select_directory(self):
     """Select directory"""
     self.parent().emit(SIGNAL('redirect_stdio(bool)'), False)
     directory = QFileDialog.getExistingDirectory(
         self, translate('FindInFiles', "Select directory"),
         self.dir_combo.currentText())
     if not directory.isEmpty():
         self.set_directory(directory)
     self.parent().emit(SIGNAL('redirect_stdio(bool)'), True)
Ejemplo n.º 54
0
 def copy_item(self, erase_original=False):
     """Copy item"""
     indexes = self.selectedIndexes()
     if not indexes:
         return
     idx_rows = unsorted_unique(map(lambda idx: idx.row(), indexes))
     if len(idx_rows) > 1 or not indexes[0].isValid():
         return
     orig_key = self.model.keys[idx_rows[0]]
     new_key, valid = QInputDialog.getText(
         self, translate("DictEditor", 'Rename'),
         translate("DictEditor", 'Key:'), QLineEdit.Normal, orig_key)
     if valid and not new_key.isEmpty():
         new_key = try_to_eval(unicode(new_key))
         if new_key == orig_key:
             return
         self.copy_value(orig_key, new_key)
         if erase_original:
             self.remove_values([orig_key])
Ejemplo n.º 55
0
    def __init__(self,
                 parent,
                 data,
                 readonly=False,
                 title="",
                 names=False,
                 truncate=True,
                 minmax=False,
                 inplace=False,
                 collvalue=True):
        BaseTableView.__init__(self, parent)
        self.dictfilter = None
        self.readonly = readonly or isinstance(data, tuple)
        self.model = None
        self.delegate = None
        DictModelClass = ReadOnlyDictModel if self.readonly else DictModel
        self.model = DictModelClass(self,
                                    data,
                                    title,
                                    names=names,
                                    truncate=truncate,
                                    minmax=minmax,
                                    collvalue=collvalue)
        self.setModel(self.model)
        self.delegate = DictDelegate(self, inplace=inplace)
        self.setItemDelegate(self.delegate)

        self.setup_table()
        self.menu = self.setup_menu(truncate, minmax, inplace, collvalue)
        self.copy_action = create_action(self,
                                         translate("DictEditor", "Copy"),
                                         icon=get_icon('editcopy.png'),
                                         triggered=self.copy)
        self.paste_action = create_action(self,
                                          translate("DictEditor", "Paste"),
                                          icon=get_icon('editpaste.png'),
                                          triggered=self.paste)
        self.menu.insertAction(self.remove_action, self.copy_action)
        self.menu.insertAction(self.remove_action, self.paste_action)

        self.empty_ws_menu = QMenu(self)
        self.empty_ws_menu.addAction(self.paste_action)
Ejemplo n.º 56
0
    def __init__(self, parent, data, xy, readonly):
        QWidget.__init__(self, parent)
        self.data = data
        self.old_data_shape = None
        if len(self.data.shape) == 1:
            self.old_data_shape = self.data.shape
            self.data.shape = (self.data.shape[0], 1)
        elif len(self.data.shape) == 0:
            self.old_data_shape = self.data.shape
            self.data.shape = (1, 1)

        self.changes = {}

        format = SUPPORTED_FORMATS.get(data.dtype.name, '%s')
        self.model = ArrayModel(self.data,
                                self.changes,
                                format=format,
                                xy_mode=xy,
                                readonly=readonly,
                                parent=self)
        self.view = ArrayView(self, self.model, data.dtype, data.shape)

        btn_layout = QHBoxLayout()
        btn_layout.setAlignment(Qt.AlignLeft)
        btn = QPushButton(translate("ArrayEditor", "Format"))
        # disable format button for int type
        btn.setEnabled(is_float(data.dtype))
        btn_layout.addWidget(btn)
        self.connect(btn, SIGNAL("clicked()"), self.change_format)
        btn = QPushButton(translate("ArrayEditor", "Resize"))
        btn_layout.addWidget(btn)
        self.connect(btn, SIGNAL("clicked()"), self.view.resize_to_contents)
        bgcolor = QCheckBox(translate("ArrayEditor", 'Background color'))
        bgcolor.setChecked(self.model.bgcolor_enabled)
        bgcolor.setEnabled(self.model.bgcolor_enabled)
        self.connect(bgcolor, SIGNAL("stateChanged(int)"), self.model.bgcolor)
        btn_layout.addWidget(bgcolor)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(btn_layout)
        self.setLayout(layout)
Ejemplo n.º 57
0
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = translate("ShellBaseWidget", "Save history log")
     self.emit(SIGNAL('redirect_stdio(bool)'), False)
     filename = QFileDialog.getSaveFileName(self, title,
                                            self.historylog_filename,
                                            "History logs (*.log)")
     self.emit(SIGNAL('redirect_stdio(bool)'), True)
     if filename:
         filename = osp.normpath(unicode(filename))
         try:
             encoding.write(unicode(self.text()), filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError, error:
             QMessageBox.critical(self, title,
                             translate("ShellBaseWidget",
                                       "<b>Unable to save file '%1'</b>"
                                       "<br><br>Error message:<br>%2") \
                             .arg(osp.basename(filename)).arg(str(error)))
Ejemplo n.º 58
0
 def __init__(self, parent=None):
     super(WinUserEnvDialog,
           self).__init__(get_user_env(),
                          title="HKEY_CURRENT_USER\Environment",
                          width=600)
     if parent is None:
         parent = self
     QMessageBox.warning(
         parent, translate("WinUserEnvDialog", "Warning"),
         translate(
             "WinUserEnvDialog", "If you accept changes, "
             "this will modify the current user environment "
             "variables directly <b>in Windows registry</b>. "
             "Use it with precautions, at your own risks.<br>"
             "<br>Note that for changes to take effect, you will "
             "need to restart the parent process of this applica"
             "tion (simply restart Spyder if you have executed it "
             "from a Windows shortcut, otherwise restart any "
             "application from which you may have executed it, "
             "like <i>Python(x,y) Home</i> for example)"))
Ejemplo n.º 59
0
 def setup_menu(self):
     """Setup context menu"""
     self.copy_action = create_action(self,
                                      translate("ArrayEditor", "Copy"),
                                      shortcut=keybinding("Copy"),
                                      icon=get_icon('editcopy.png'),
                                      triggered=self.copy,
                                      window_context=False)
     menu = QMenu(self)
     add_actions(menu, [
         self.copy_action,
     ])
     return menu
Ejemplo n.º 60
0
 def save_array(self):
     """Save array"""
     title = translate("DictEditor", "Save array")
     if self.array_filename is None:
         self.array_filename = os.getcwdu()
     self.emit(SIGNAL('redirect_stdio(bool)'), False)
     filename = QFileDialog.getSaveFileName(
         self, title, self.array_filename,
         translate('DictEditor', "NumPy arrays") + " (*.npy)")
     self.emit(SIGNAL('redirect_stdio(bool)'), True)
     if filename:
         self.array_filename = unicode(filename)
         data = self.delegate.get_value(self.currentIndex())
         try:
             import numpy as np
             np.save(self.array_filename, data)
         except Exception, error:
             QMessageBox.critical(
                 self, title,
                 translate(
                     'DictEditor', "<b>Unable to save array</b>"
                     "<br><br>Error message:<br>%1").arg(str(error)))