Example #1
0
 def set(self, section, option, value, verbose=False, save=True):
     """
     Set an option
     section=None: attribute a default section name
     """
     section = self.__check_section_option(section, option)
     default_value = self.get_default(section, option)
     if default_value is NoDefault:
         # This let us save correctly string value options with
         # no config default that contain non-ascii chars in
         # Python 2
         if PY2 and is_text_string(value):
             value = repr(value)
         default_value = value
         self.set_default(section, option, default_value)
     if isinstance(default_value, bool):
         value = bool(value)
     elif isinstance(default_value, float):
         value = float(value)
     elif isinstance(default_value, int):
         value = int(value)
     elif not is_text_string(default_value):
         value = repr(value)
     self._set(section, option, value, verbose)
     if save:
         self._save()
Example #2
0
 def set(self, section, option, value, verbose=False, save=True):
     """
     Set an option
     section=None: attribute a default section name
     """
     section = self.__check_section_option(section, option)
     default_value = self.get_default(section, option)
     if default_value is NoDefault:
         # This let us save correctly string value options with
         # no config default that contain non-ascii chars in
         # Python 2
         if PY2 and is_text_string(value):
             value = repr(value)
         default_value = value
         self.set_default(section, option, default_value)
     if isinstance(default_value, bool):
         value = bool(value)
     elif isinstance(default_value, float):
         value = float(value)
     elif isinstance(default_value, int):
         value = int(value)
     elif not is_text_string(default_value):
         value = repr(value)
     self._set(section, option, value, verbose)
     if save:
         self._save()
Example #3
0
 def __check_section_option(self, section, option):
     """
     Private method to check section and option types
     """
     if section is None:
         section = self.DEFAULT_SECTION_NAME
     elif not is_text_string(section):
         raise RuntimeError("Argument 'section' must be a string")
     if not is_text_string(option):
         raise RuntimeError("Argument 'option' must be a string")
     return section
Example #4
0
 def __check_section_option(self, section, option):
     """
     Private method to check section and option types
     """
     if section is None:
         section = self.DEFAULT_SECTION_NAME
     elif not is_text_string(section):
         raise RuntimeError("Argument 'section' must be a string")
     if not is_text_string(option):
         raise RuntimeError("Argument 'option' must be a string")
     return section
Example #5
0
def create_toolbutton(parent,
                      text=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      toggled=None,
                      triggered=None,
                      autoraise=True,
                      text_beside_icon=False):
    """Create a QToolButton"""
    button = QToolButton(parent)
    if text is not None:
        button.setText(text)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        button.setIcon(icon)
    if text is not None or tip is not None:
        button.setToolTip(text if tip is None else tip)
    if text_beside_icon:
        button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
    button.setAutoRaise(autoraise)
    if triggered is not None:
        button.clicked.connect(triggered)
    if toggled is not None:
        button.toggled.connect(toggled)
        button.setCheckable(True)
    if shortcut is not None:
        button.setShortcut(shortcut)
    return button
 def register_plugin(self):
     """Register plugin in Spyder's main window"""
     self.connect(self, SIGNAL("edit_goto(QString,int,QString)"),
                  self.main.editor.load)
     self.connect(self, SIGNAL('redirect_stdio(bool)'),
                  self.main.redirect_internalshell_stdio)
     self.main.add_dockwidget(self)
     
     c2p_act = create_action(self, _("Import COMBINE as Python"),
                                triggered=self.run_c2p)
     c2p_act.setEnabled(True)
     #self.register_shortcut(c2p_act, context="Combine to Python",
     #                       name="Import combine archive", default="Alt-C")
     for item in self.main.file_menu_actions:
         try:
             menu_title = item.title()
         except AttributeError:
             pass
         else:
             if not is_text_string(menu_title): # string is a QString
                 menu_title = to_text_string(menu_title.toUtf8)
             if item.title() == str("Import"):
                 item.addAction(c2p_act)
     c2p_actions = (None, c2p_act)
     import_menu = QMenu(_("Import"))
     add_actions(import_menu, c2p_actions)
     self.main.file_menu_actions.insert(8, import_menu)
Example #7
0
def create_toolbutton(parent,
                      text=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      toggled=None,
                      triggered=None,
                      autoraise=True,
                      text_beside_icon=False):
    """Create a QToolButton"""
    button = QToolButton(parent)
    if text is not None:
        button.setText(text)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        button.setIcon(icon)
    if text is not None or tip is not None:
        button.setToolTip(text if tip is None else tip)
    if text_beside_icon:
        button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
    button.setAutoRaise(autoraise)
    if triggered is not None:
        button.clicked.connect(triggered)
    if toggled is not None:
        button.toggled.connect(toggled)
        button.setCheckable(True)
    if shortcut is not None:
        button.setShortcut(shortcut)
    return button
Example #8
0
 def go_to(self, url_or_text):
     """Go to page *address*"""
     if is_text_string(url_or_text):
         url = QUrl(url_or_text)
     else:
         url = url_or_text
     self.webview.load(url)
Example #9
0
    def send_to_process(self, text):
        if not self.is_running():
            return

        if not is_text_string(text):
            text = to_text_string(text)
        if self.mpl_backend == 'Qt4Agg' and os.name == 'nt' and \
          self.introspection_socket is not None:
            communicate(self.introspection_socket,
                        "toggle_inputhook_flag(True)")
#            # Socket-based alternative (see input hook in sitecustomize.py):
#            while self.local_server.hasPendingConnections():
#                self.local_server.nextPendingConnection().write('go!')
        if any([text == cmd for cmd in ['%ls', '%pwd', '%scientific']]) or \
          any([text.startswith(cmd) for cmd in ['%cd ', '%clear ']]):
            text = 'evalsc(r"%s")\n' % text
        if not text.endswith('\n'):
            text += '\n'
        self.process.write(to_binary_string(text, 'utf8'))
        self.process.waitForBytesWritten(-1)

        # Eventually write prompt faster (when hitting Enter continuously)
        # -- necessary/working on Windows only:
        if os.name == 'nt':
            self.write_error()
def getobjdir(obj):
    """
    For standard objects, will simply return dir(obj)
    In special cases (e.g. WrapITK package), will return only string elements
    of result returned by dir(obj)
    """
    return [item for item in dir(obj) if is_text_string(item)]
Example #11
0
    def send_to_process(self, text):
        if not self.is_running():
            return
            
        if not is_text_string(text):
            text = to_text_string(text)
        if self.mpl_backend == 'Qt4Agg' and os.name == 'nt' and \
          self.introspection_socket is not None:
            communicate(self.introspection_socket,
                        "toggle_inputhook_flag(True)")
#            # Socket-based alternative (see input hook in sitecustomize.py):
#            while self.local_server.hasPendingConnections():
#                self.local_server.nextPendingConnection().write('go!')
        if any([text == cmd for cmd in ['%ls', '%pwd', '%scientific']]) or \
          any([text.startswith(cmd) for cmd in ['%cd ', '%clear ']]):
            text = 'evalsc(r"%s")\n' % text
        if not text.endswith('\n'):
            text += '\n'
        self.process.write(to_binary_string(text, 'utf8'))
        self.process.waitForBytesWritten(-1)
        
        # Eventually write prompt faster (when hitting Enter continuously)
        # -- necessary/working on Windows only:
        if os.name == 'nt':
            self.write_error()
Example #12
0
    def register_plugin(self):
        """Register plugin in Spyder's main window"""
        self.edit_goto.connect(self.main.editor.load)
        # self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
        self.clear_all_breakpoints.connect(self.main.editor.clear_all_breakpoints)
        self.clear_breakpoint.connect(self.main.editor.clear_breakpoint)
        self.main.editor.breakpoints_saved.connect(self.set_data)
        self.set_or_edit_conditional_breakpoint.connect(self.main.editor.set_or_edit_conditional_breakpoint)

        self.main.add_dockwidget(self)

        list_action = create_action(self, _("List breakpoints"), triggered=self.show)
        list_action.setEnabled(True)

        # A fancy way to insert the action into the Breakpoints menu under
        # the assumption that Breakpoints is the first QMenu in the list.
        for item in self.main.debug_menu_actions:
            try:
                menu_title = item.title()
            except AttributeError:
                pass
            else:
                # Depending on Qt API version, could get a QString or
                # unicode from title()
                if not is_text_string(menu_title):  # string is a QString
                    menu_title = to_text_string(menu_title.toUtf8)
                item.addAction(list_action)
                # If we've reached this point it means we've located the
                # first QMenu in the run_menu. Since there might be other
                # QMenu entries in run_menu, we'll break so that the
                # breakpoint action is only inserted once into the run_menu.
                break
        self.main.editor.pythonfile_dependent_actions += [list_action]
Example #13
0
    def register_plugin(self):
        """Register plugin in Spyder's main window"""
        self.connect(self, SIGNAL("edit_goto(QString,int,QString)"),
                     self.main.editor.load)
        self.connect(self, SIGNAL('redirect_stdio(bool)'),
                     self.main.redirect_internalshell_stdio)
        self.main.add_dockwidget(self)

        s2pwp_act = create_action(self,
                                  _("Import SED-ML as PhrasedML"),
                                  triggered=self.run_s2pwp)
        s2pwp_act.setEnabled(True)
        #self.register_shortcut(s2p_act, context="SED-ML to Python",
        #                       name="Import SED-ML file", default="Alt-I")

        for item in self.main.file_menu_actions:
            try:
                menu_title = item.title()
            except AttributeError:
                pass
            else:
                if not is_text_string(menu_title):  # string is a QString
                    menu_title = to_text_string(menu_title.toUtf8)
                if item.title() == str("Import"):
                    item.addAction(s2pwp_act)
Example #14
0
    def setData(self, index, value, role=Qt.EditRole, change_type=None):
        """Cell content change"""
        column = index.column()
        row = index.row()

        if change_type is not None:
            try:
                value = self.data(index, role=Qt.DisplayRole)
                val = from_qvariant(value, str)
                if change_type is bool:
                    val = bool_false_check(val)
                self.df.iloc[row, column - 1] = change_type(val)
            except ValueError:
                self.df.iloc[row, column - 1] = change_type('0')
        else:
            val = from_qvariant(value, str)
            current_value = self.get_value(row, column-1)
            if isinstance(current_value, bool):
                val = bool_false_check(val)
            if isinstance(current_value, ((bool,) + _sup_nr + _sup_com)) or \
               is_text_string(current_value):
                try:
                    self.df.iloc[row, column-1] = current_value.__class__(val)
                except ValueError as e:
                    QMessageBox.critical(self.dialog, "Error",
                                         "Value error: %s" % str(e))
                    return False
            else:
                QMessageBox.critical(self.dialog, "Error",
                                     "The type of the cell is not a supported "
                                     "type")
                return False
        self.max_min_col_update()
        return True
Example #15
0
def create_action(parent,
                  text,
                  shortcut=None,
                  icon=None,
                  tip=None,
                  toggled=None,
                  triggered=None,
                  data=None,
                  menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        action.setIcon(icon)
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)
    #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(context)
    return action
Example #16
0
def create_action(parent, text, shortcut=None, icon=None, tip=None,
                  toggled=None, triggered=None, data=None, menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        parent.connect(action, SIGNAL("triggered()"), triggered)
    if toggled is not None:
        parent.connect(action, SIGNAL("toggled(bool)"), toggled)
        action.setCheckable(True)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        action.setIcon(icon)
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)
    #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(context)
    return action
Example #17
0
def getobjdir(obj):
    """
    For standard objects, will simply return dir(obj)
    In special cases (e.g. WrapITK package), will return only string elements
    of result returned by dir(obj)
    """
    return [item for item in dir(obj) if is_text_string(item)]
Example #18
0
    def setData(self, index, value, role=Qt.EditRole, change_type=None):
        """Cell content change"""
        column = index.column()
        row = index.row()

        if change_type is not None:
            try:
                value = self.data(index, role=Qt.DisplayRole)
                val = from_qvariant(value, str)
                if change_type is bool:
                    val = bool_false_check(val)
                self.df.iloc[row, column - 1] = change_type(val)
            except ValueError:
                self.df.iloc[row, column - 1] = change_type('0')
        else:
            val = from_qvariant(value, str)
            current_value = self.get_value(row, column-1)
            if isinstance(current_value, bool):
                val = bool_false_check(val)
            if isinstance(current_value, ((bool,) + _sup_nr + _sup_com)) or \
               is_text_string(current_value):
                try:
                    self.df.iloc[row, column-1] = current_value.__class__(val)
                except ValueError as e:
                    QMessageBox.critical(self.dialog, "Error",
                                         "Value error: %s" % str(e))
                    return False
            else:
                QMessageBox.critical(self.dialog, "Error",
                                     "The type of the cell is not a supported "
                                     "type")
                return False
        self.max_min_col_update()
        return True
Example #19
0
 def get_bgcolor(self, index):
     """Background color depending on value"""
     column = index.column()
     if column == 0:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.8)
         return color
     if not self.bgcolor_enabled:
         return
     value = self.get_value(index.row(), column - 1)
     if isinstance(value, _sup_com):
         color_func = abs
     else:
         color_func = float
     if isinstance(value, _sup_nr + _sup_com) and self.bgcolor_enabled:
         vmax, vmin = self.return_max(self.max_min_col, column - 1)
         hue = self.hue0 + self.dhue * (vmax - color_func(value)) / (vmax -
                                                                     vmin)
         hue = float(abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
     elif is_text_string(value):
         color = QColor(Qt.lightGray)
         color.setAlphaF(.05)
     else:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.3)
     return color
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    if minmax and isinstance(value, (ndarray, MaskedArray)):
        if value.size == 0:
            return repr(value)
        try:
            return 'Min: %r\nMax: %r' % (value.min(), value.max())
        except TypeError:
            pass
        except ValueError:
            # Happens when one of the array cell contains a sequence
            pass
    if isinstance(value, Image):
        return '%s  Mode: %s' % (address(value), value.mode)
    if isinstance(value, DataFrame):
        cols = value.columns
        cols = [to_text_string(c) for c in cols]
        return 'Column names: ' + ', '.join(list(cols))
    if is_binary_string(value):
        try:
            value = to_text_string(value, 'utf8')
        except:
            pass
    if not is_text_string(value):
        if isinstance(value, (list, tuple, dict, set)):
            value = CollectionsRepr.repr(value)
        else:
            value = repr(value)
    if truncate and len(value) > trunc_len:
        value = value[:trunc_len].rstrip() + ' ...'
    return value
    def register_plugin(self):
        """Register plugin in Spyder's main window"""
        self.connect(self, SIGNAL("edit_goto(QString,int,QString)"),
                     self.main.editor.load)
        self.connect(self, SIGNAL('redirect_stdio(bool)'),
                     self.main.redirect_internalshell_stdio)
        self.main.add_dockwidget(self)

        c2p_act = create_action(self,
                                _("Import COMBINE as Python"),
                                triggered=self.run_c2p)
        c2p_act.setEnabled(True)
        #self.register_shortcut(c2p_act, context="Combine to Python",
        #                       name="Import combine archive", default="Alt-C")
        for item in self.main.file_menu_actions:
            try:
                menu_title = item.title()
            except AttributeError:
                pass
            else:
                if not is_text_string(menu_title):  # string is a QString
                    menu_title = to_text_string(menu_title.toUtf8)
                if item.title() == str("Import"):
                    item.addAction(c2p_act)
        c2p_actions = (None, c2p_act)
        import_menu = QMenu(_("Import"))
        add_actions(import_menu, c2p_actions)
        self.main.file_menu_actions.insert(8, import_menu)
Example #22
0
 def get_bgcolor(self, index):
     """Background color depending on value"""
     column = index.column()
     if column == 0:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.8)
         return color
     if not self.bgcolor_enabled:
         return
     value = self.get_value(index.row(), column-1)
     if isinstance(value, _sup_com):
         color_func = abs
     else:
         color_func = float
     if isinstance(value, _sup_nr+_sup_com) and self.bgcolor_enabled:
         vmax, vmin = self.return_max(self.max_min_col, column-1)
         hue = self.hue0 + self.dhue*(vmax-color_func(value)) / (vmax-vmin)
         hue = float(abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
     elif is_text_string(value):
         color = QColor(Qt.lightGray)
         color.setAlphaF(.05)
     else:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.3)
     return color
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    if minmax and isinstance(value, (ndarray, MaskedArray)):
        if value.size == 0:
            return repr(value)
        try:
            return 'Min: %r\nMax: %r' % (value.min(), value.max())
        except TypeError:
            pass
        except ValueError:
            # Happens when one of the array cell contains a sequence
            pass
    if isinstance(value, Image):
        return '%s  Mode: %s' % (address(value), value.mode)
    if isinstance(value, DataFrame):
        cols = value.columns
        cols = [to_text_string(c) for c in cols]
        return 'Column names: ' + ', '.join(list(cols))
    if is_binary_string(value):
        try:
            value = to_text_string(value, 'utf8')
        except:
            pass
    if not is_text_string(value):
        if isinstance(value, (list, tuple, dict, set)):
            value = CollectionsRepr.repr(value)
        else:
            value = repr(value)
    if truncate and len(value) > trunc_len:
        value = value[:trunc_len].rstrip() + ' ...'
    return value
Example #24
0
 def go_to(self, url_or_text):
     """Go to page *address*"""
     if is_text_string(url_or_text):
         url = QUrl(url_or_text)
     else:
         url = url_or_text
     self.webview.load(url)
Example #25
0
 def translate_gettext(x):
     if not PY3 and is_unicode(x):
         x = x.encode("utf-8")
     y = lgettext(x)
     if is_text_string(y) and PY3:
         return y
     else:
         return to_text_string(y, "utf-8")
Example #26
0
def create_python_script_action(parent, text, icon, package, module, args=[]):
    """Create action to run a GUI based Python script"""
    if is_text_string(icon):
        icon = get_icon(icon)
    if programs.python_script_exists(package, module):
        return create_action(parent, text, icon=icon,
                             triggered=lambda:
                             programs.run_python_script(package, module, args))
Example #27
0
 def set_eol_chars(self, text):
     """Set widget end-of-line (EOL) characters from text (analyzes text)"""
     if not is_text_string(text):  # testing for QString (PyQt API#1)
         text = to_text_string(text)
     eol_chars = sourcecode.get_eol_chars(text)
     if eol_chars is not None and self.eol_chars is not None:
         self.document().setModified(True)
     self.eol_chars = eol_chars
Example #28
0
def create_python_script_action(parent, text, icon, package, module, args=[]):
    """Create action to run a GUI based Python script"""
    if is_text_string(icon):
        icon = get_icon(icon)
    if programs.python_script_exists(package, module):
        return create_action(parent, text, icon=icon,
                             triggered=lambda:
                             programs.run_python_script(package, module, args))
Example #29
0
 def set_eol_chars(self, text):
     """Set widget end-of-line (EOL) characters from text (analyzes text)"""
     if not is_text_string(text): # testing for QString (PyQt API#1)
         text = to_text_string(text)
     eol_chars = sourcecode.get_eol_chars(text)
     if eol_chars is not None and self.eol_chars is not None:
         self.document().setModified(True)
     self.eol_chars = eol_chars
Example #30
0
 def setup_page(self):
     tabs = QTabWidget()
     names = self.get_option("names")
     names.pop(names.index(CUSTOM_COLOR_SCHEME_NAME))
     names.insert(0, CUSTOM_COLOR_SCHEME_NAME)
     fieldnames = {
                   "background":     _("Background:"),
                   "currentline":    _("Current line:"),
                   "currentcell":    _("Current cell:"),
                   "occurence":      _("Occurence:"),
                   "ctrlclick":      _("Link:"),
                   "sideareas":      _("Side areas:"),
                   "matched_p":      _("Matched parentheses:"),
                   "unmatched_p":    _("Unmatched parentheses:"),
                   "normal":         _("Normal text:"),
                   "keyword":        _("Keyword:"),
                   "builtin":        _("Builtin:"),
                   "definition":     _("Definition:"),
                   "comment":        _("Comment:"),
                   "string":         _("String:"),
                   "number":         _("Number:"),
                   "instance":       _("Instance:"),
                   }
     from spyderlib.utils import syntaxhighlighters
     assert all([key in fieldnames
                 for key in syntaxhighlighters.COLOR_SCHEME_KEYS])
     for tabname in names:
         cs_group = QGroupBox(_("Color scheme"))
         cs_layout = QGridLayout()
         for row, key in enumerate(syntaxhighlighters.COLOR_SCHEME_KEYS):
             option = "%s/%s" % (tabname, key)
             value = self.get_option(option)
             name = fieldnames[key]
             if is_text_string(value):
                 label, clayout = self.create_coloredit(name, option,
                                                        without_layout=True)
                 label.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
                 cs_layout.addWidget(label, row+1, 0)
                 cs_layout.addLayout(clayout, row+1, 1)
             else:
                 label, clayout, cb_bold, cb_italic = self.create_scedit(
                                         name, option, without_layout=True)
                 label.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
                 cs_layout.addWidget(label, row+1, 0)
                 cs_layout.addLayout(clayout, row+1, 1)
                 cs_layout.addWidget(cb_bold, row+1, 2)
                 cs_layout.addWidget(cb_italic, row+1, 3)
         cs_group.setLayout(cs_layout)
         if tabname in sh.COLOR_SCHEME_NAMES:
             def_btn = self.create_button(_("Reset to default values"),
                                      lambda: self.reset_to_default(tabname))
             tabs.addTab(self.create_tab(cs_group, def_btn), tabname)
         else:
             tabs.addTab(self.create_tab(cs_group), tabname)
     
     vlayout = QVBoxLayout()
     vlayout.addWidget(tabs)
     self.setLayout(vlayout)
Example #31
0
 def setup_page(self):
     tabs = QTabWidget()
     names = self.get_option("names")
     names.pop(names.index(CUSTOM_COLOR_SCHEME_NAME))
     names.insert(0, CUSTOM_COLOR_SCHEME_NAME)
     fieldnames = {
                   "background":     _("Background:"),
                   "currentline":    _("Current line:"),
                   "currentcell":    _("Current cell:"),
                   "occurence":      _("Occurence:"),
                   "ctrlclick":      _("Link:"),
                   "sideareas":      _("Side areas:"),
                   "matched_p":      _("Matched parentheses:"),
                   "unmatched_p":    _("Unmatched parentheses:"),
                   "normal":         _("Normal text:"),
                   "keyword":        _("Keyword:"),
                   "builtin":        _("Builtin:"),
                   "definition":     _("Definition:"),
                   "comment":        _("Comment:"),
                   "string":         _("String:"),
                   "number":         _("Number:"),
                   "instance":       _("Instance:"),
                   }
     from spyderlib.widgets.sourcecode import syntaxhighlighters
     assert all([key in fieldnames
                 for key in syntaxhighlighters.COLOR_SCHEME_KEYS])
     for tabname in names:
         cs_group = QGroupBox(_("Color scheme"))
         cs_layout = QGridLayout()
         for row, key in enumerate(syntaxhighlighters.COLOR_SCHEME_KEYS):
             option = "%s/%s" % (tabname, key)
             value = self.get_option(option)
             name = fieldnames[key]
             if is_text_string(value):
                 label, clayout = self.create_coloredit(name, option,
                                                        without_layout=True)
                 label.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
                 cs_layout.addWidget(label, row+1, 0)
                 cs_layout.addLayout(clayout, row+1, 1)
             else:
                 label, clayout, cb_bold, cb_italic = self.create_scedit(
                                         name, option, without_layout=True)
                 label.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
                 cs_layout.addWidget(label, row+1, 0)
                 cs_layout.addLayout(clayout, row+1, 1)
                 cs_layout.addWidget(cb_bold, row+1, 2)
                 cs_layout.addWidget(cb_italic, row+1, 3)
         cs_group.setLayout(cs_layout)
         if tabname in sh.COLOR_SCHEME_NAMES:
             def_btn = self.create_button(_("Reset to default values"),
                                      lambda: self.reset_to_default(tabname))
             tabs.addTab(self.create_tab(cs_group, def_btn), tabname)
         else:
             tabs.addTab(self.create_tab(cs_group), tabname)
     
     vlayout = QVBoxLayout()
     vlayout.addWidget(tabs)
     self.setLayout(vlayout)
Example #32
0
def create_program_action(parent, text, name, icon=None, nt_name=None):
    """Create action to run a program"""
    if is_text_string(icon):
        icon = get_icon(icon)
    if os.name == "nt" and nt_name is not None:
        name = nt_name
    path = programs.find_program(name)
    if path is not None:
        return create_action(parent, text, icon=icon, triggered=lambda: programs.run_program(name))
Example #33
0
def create_program_action(parent, text, name, icon=None, nt_name=None):
    """Create action to run a program"""
    if is_text_string(icon):
        icon = get_icon(icon)
    if os.name == 'nt' and nt_name is not None:
        name = nt_name
    path = programs.find_program(name)
    if path is not None:
        return create_action(parent, text, icon=icon,
                             triggered=lambda: programs.run_program(name))
 def load_config(self):
     """Load configuration: tree widget state"""
     expanded_state = self.get_option('expanded_state', None)
     # Sometimes the expanded state option may be truncated in .ini file
     # (for an unknown reason), in this case it would be converted to a
     # string by 'userconfig':
     if is_text_string(expanded_state):
         expanded_state = None
     if expanded_state is not None:
         self.treewidget.set_expanded_state(expanded_state)
Example #35
0
 def load_config(self):
     """Load configuration: tree widget state"""
     expanded_state = self.get_option('expanded_state', None)
     # Sometimes the expanded state option may be truncated in .ini file
     # (for an unknown reason), in this case it would be converted to a
     # string by 'userconfig':
     if is_text_string(expanded_state):
         expanded_state = None
     if expanded_state is not None:
         self.treewidget.set_expanded_state(expanded_state)
Example #36
0
 def _set(self, section, option, value, verbose):
     """
     Private set method
     """
     if not self.has_section(section):
         self.add_section( section )
     if not is_text_string(value):
         value = repr( value )
     if verbose:
         print('%s[ %s ] = %s' % (section, option, value))
     cp.ConfigParser.set(self, section, option, value)
Example #37
0
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    try:
        if isinstance(value, recarray):
            fields = value.names
            display = 'Field names: ' + ', '.join(fields)
        elif minmax and isinstance(value, (ndarray, MaskedArray)):
            if value.size == 0:
                display = repr(value)
            try:
                display = 'Min: %r\nMax: %r' % (value.min(), value.max())
            except TypeError:
                pass
            except ValueError:
                # Happens when one of the array cell contains a sequence
                pass
        elif isinstance(value, (list, tuple, dict, set)):
            display = CollectionsRepr.repr(value)
        elif isinstance(value, Image):
            display = '%s  Mode: %s' % (address(value), value.mode)
        elif isinstance(value, DataFrame):
            cols = value.columns
            if PY2 and len(cols) > 0:
                # Get rid of possible BOM utf-8 data present at the
                # beginning of a file, which gets attached to the first
                # column header when headers are present in the first
                # row.
                # Fixes Issue 2514
                try:
                    ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                except:
                    ini_col = to_text_string(cols[0])
                cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
            else:
                cols = [to_text_string(c) for c in cols]
            display = 'Column names: ' + ', '.join(list(cols))
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
        elif is_binary_string(value):
            try:
                display = to_text_string(value, 'utf8')
            except:
                pass
        elif is_text_string(value):
            display = value
        else:
            display = repr(value)
            if truncate and len(display) > trunc_len:
                display = display[:trunc_len].rstrip() + ' ...'
    except:
        display = to_text_string(type(value))

    return display
Example #38
0
 def eval(self, text):
     """
     Evaluate text and return (obj, valid)
     where *obj* is the object represented by *text*
     and *valid* is True if object evaluation did not raise any exception
     """
     assert is_text_string(text)
     try:
         return eval(text, self.locals), True
     except:
         return None, False
Example #39
0
def value_to_display(value, truncate=False, trunc_len=80, minmax=False):
    """Convert value for display purpose"""
    try:
        if isinstance(value, recarray):
            fields = value.names
            display = 'Field names: ' + ', '.join(fields)
        elif minmax and isinstance(value, (ndarray, MaskedArray)):
            if value.size == 0:
                display = repr(value)
            try:
                display = 'Min: %r\nMax: %r' % (value.min(), value.max())
            except TypeError:
                pass
            except ValueError:
                # Happens when one of the array cell contains a sequence
                pass
        elif isinstance(value, (list, tuple, dict, set)):
            display = CollectionsRepr.repr(value)
        elif isinstance(value, Image):
            display = '%s  Mode: %s' % (address(value), value.mode)
        elif isinstance(value, DataFrame):
            cols = value.columns
            if PY2 and len(cols) > 0:
                # Get rid of possible BOM utf-8 data present at the
                # beginning of a file, which gets attached to the first
                # column header when headers are present in the first
                # row.
                # Fixes Issue 2514
                try:
                    ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                except:
                    ini_col = to_text_string(cols[0])
                cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
            else:
                cols = [to_text_string(c) for c in cols]
            display = 'Column names: ' + ', '.join(list(cols))
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
        elif is_binary_string(value):
            try:
                display = to_text_string(value, 'utf8')
            except:
                pass
        elif is_text_string(value):
            display = value
        else:
            display = repr(value)
            if truncate and len(display) > trunc_len:
                display = display[:trunc_len].rstrip() + ' ...'
    except:
        display = to_text_string(type(value))

    return display
Example #40
0
 def _set(self, section, option, value, verbose):
     """
     Private set method
     """
     if not self.has_section(section):
         self.add_section( section )
     if not is_text_string(value):
         value = repr( value )
     if verbose:
         print('%s[ %s ] = %s' % (section, option, value))
     cp.ConfigParser.set(self, section, option, value)
Example #41
0
 def eval(self, text):
     """
     Evaluate text and return (obj, valid)
     where *obj* is the object represented by *text*
     and *valid* is True if object evaluation did not raise any exception
     """
     assert is_text_string(text)
     try:
         return eval(text, self.locals), True
     except:
         return None, False
Example #42
0
 def _eval(self, text):
     """
     Evaluate text and return (obj, valid)
     where *obj* is the object represented by *text*
     and *valid* is True if object evaluation did not raise any exception
     """
     assert is_text_string(text)
     ns = self.get_current_namespace(with_magics=True)
     try:
         return eval(text, ns), True
     except:
         return None, False
Example #43
0
 def _eval(self, text):
     """
     Evaluate text and return (obj, valid)
     where *obj* is the object represented by *text*
     and *valid* is True if object evaluation did not raise any exception
     """
     assert is_text_string(text)
     ns = self.get_current_namespace(with_magics=True)
     try:
         return eval(text, ns), True
     except:
         return None, False
Example #44
0
 def append_to_history(self, filename, command):
     """
     Append an entry to history filename
     Slot for append_to_history signal emitted by shell instance
     """
     if not is_text_string(filename):  # filename is a QString
         filename = to_text_string(filename.toUtf8(), 'utf-8')
     command = to_text_string(command)
     index = self.filenames.index(filename)
     self.editors[index].append(command)
     if self.get_option('go_to_eof'):
         self.editors[index].set_cursor_position('eof')
     self.tabwidget.setCurrentIndex(index)
Example #45
0
 def append_to_history(self, filename, command):
     """
     Append an entry to history filename
     Slot for append_to_history signal emitted by shell instance
     """
     if not is_text_string(filename): # filename is a QString
         filename = to_text_string(filename.toUtf8(), 'utf-8')
     command = to_text_string(command)
     index = self.filenames.index(filename)
     self.editors[index].append(command)
     if self.get_option('go_to_eof'):
         self.editors[index].set_cursor_position('eof')
     self.tabwidget.setCurrentIndex(index)
Example #46
0
    def __init__(self, parent, history_filename, profile=False):
        """
        parent : specifies the parent widget
        """
        ConsoleBaseWidget.__init__(self, parent)
        SaveHistoryMixin.__init__(self)
                
        # Prompt position: tuple (line, index)
        self.current_prompt_pos = None
        self.new_input_line = True
        
        # History
        self.histidx = None
        self.hist_wholeline = False
        assert is_text_string(history_filename)
        self.history_filename = history_filename
        self.history = self.load_history()
        
        # Session
        self.historylog_filename = CONF.get('main', 'historylog_filename',
                                            get_conf_path('history.log'))
        
        # Context menu
        self.menu = None
        self.setup_context_menu()

        # Simple profiling test
        self.profile = profile
        
        # Buffer to increase performance of write/flush operations
        self.__buffer = []
        self.__timestamp = 0.0
        self.__flushtimer = QTimer(self)
        self.__flushtimer.setSingleShot(True)
        self.connect(self.__flushtimer, SIGNAL('timeout()'), self.flush)

        # Give focus to widget
        self.setFocus()
                
        # Calltips
        calltip_size = CONF.get('shell_appearance', 'calltips/size')
        calltip_font = get_font('shell_appearance', 'calltips')
        self.setup_calltips(calltip_size, calltip_font)
        
        # Completion
        completion_size = CONF.get('shell_appearance', 'completion/size')
        completion_font = get_font('shell_appearance', 'completion')
        self.completion_widget.setup_appearance(completion_size,
                                                completion_font)
        # Cursor width
        self.setCursorWidth( CONF.get('shell_appearance', 'cursor/width') )
Example #47
0
def create_dialog(obj, obj_name):
    """Creates the editor dialog and returns a tuple (dialog, func) where func
    is the function to be called with the dialog instance as argument, after 
    quitting the dialog box
    
    The role of this intermediate function is to allow easy monkey-patching.
    (uschmitt suggested this indirection here so that he can monkey patch 
    oedit to show eMZed related data)
    """
    # Local import
    from spyderlib.widgets.texteditor import TextEditor
    from spyderlib.widgets.dicteditorutils import (ndarray, FakeObject,
                                                   Image, is_known_type,
                                                   DataFrame, TimeSeries)
    from spyderlib.widgets.dicteditor import DictEditor
    from spyderlib.widgets.arrayeditor import ArrayEditor
    if DataFrame is not FakeObject:
        from spyderlib.widgets.dataframeeditor import DataFrameEditor
    
    conv_func = lambda data: data
    readonly = not is_known_type(obj)
    if isinstance(obj, ndarray) and ndarray is not FakeObject:
        dialog = ArrayEditor()
        if not dialog.setup_and_check(obj, title=obj_name,
                                      readonly=readonly):
            return
    elif isinstance(obj, Image) and Image is not FakeObject \
         and ndarray is not FakeObject:
        dialog = ArrayEditor()
        import numpy as np
        data = np.array(obj)
        if not dialog.setup_and_check(data, title=obj_name,
                                      readonly=readonly):
            return
        from spyderlib.pil_patch import Image
        conv_func = lambda data: Image.fromarray(data, mode=obj.mode)
    elif isinstance(obj, (DataFrame, TimeSeries)) \
         and DataFrame is not FakeObject:
        dialog = DataFrameEditor()
        if not dialog.setup_and_check(obj):
            return		
    elif is_text_string(obj):
        dialog = TextEditor(obj, title=obj_name, readonly=readonly)
    else:
        dialog = DictEditor()
        dialog.setup(obj, title=obj_name, readonly=readonly)

    def end_func(dialog):
        return conv_func(dialog.get_value())

    return dialog, end_func
Example #48
0
def create_dialog(obj, obj_name):
    """Creates the editor dialog and returns a tuple (dialog, func) where func
    is the function to be called with the dialog instance as argument, after 
    quitting the dialog box
    
    The role of this intermediate function is to allow easy monkey-patching.
    (uschmitt suggested this indirection here so that he can monkey patch 
    oedit to show eMZed related data)
    """
    # Local import
    from spyderlib.widgets.texteditor import TextEditor
    from spyderlib.widgets.dicteditorutils import (ndarray, FakeObject,
                                                   Image, is_known_type,
                                                   DataFrame, TimeSeries)
    from spyderlib.widgets.dicteditor import DictEditor
    from spyderlib.widgets.arrayeditor import ArrayEditor
    if DataFrame is not FakeObject:
        from spyderlib.widgets.dataframeeditor import DataFrameEditor
    
    conv_func = lambda data: data
    readonly = not is_known_type(obj)
    if isinstance(obj, ndarray) and ndarray is not FakeObject:
        dialog = ArrayEditor()
        if not dialog.setup_and_check(obj, title=obj_name,
                                      readonly=readonly):
            return
    elif isinstance(obj, Image) and Image is not FakeObject \
         and ndarray is not FakeObject:
        dialog = ArrayEditor()
        import numpy as np
        data = np.array(obj)
        if not dialog.setup_and_check(data, title=obj_name,
                                      readonly=readonly):
            return
        from spyderlib.pil_patch import Image
        conv_func = lambda data: Image.fromarray(data, mode=obj.mode)
    elif isinstance(obj, (DataFrame, TimeSeries)) \
         and DataFrame is not FakeObject:
        dialog = DataFrameEditor()
        if not dialog.setup_and_check(obj):
            return		
    elif is_text_string(obj):
        dialog = TextEditor(obj, title=obj_name, readonly=readonly)
    else:
        dialog = DictEditor()
        dialog.setup(obj, title=obj_name, readonly=readonly)

    def end_func(dialog):
        return conv_func(dialog.get_value())

    return dialog, end_func
Example #49
0
 def send_to_process(self, text):
     if not is_text_string(text):
         text = to_text_string(text)
     if text[:-1] in ["clear", "cls", "CLS"]:
         self.shell.clear()
         self.send_to_process(os.linesep)
         return
     if not text.endswith('\n'):
         text += '\n'
     if os.name == 'nt':
         self.process.write(text.encode('cp850'))
     else:
         self.process.write(LOCALE_CODEC.fromUnicode(text))
     self.process.waitForBytesWritten(-1)
Example #50
0
 def send_to_process(self, text):
     if not is_text_string(text):
         text = to_text_string(text)
     if text[:-1] in ["clear", "cls", "CLS"]:
         self.shell.clear()
         self.send_to_process(os.linesep)
         return
     if not text.endswith('\n'):
         text += '\n'
     if os.name == 'nt':
         self.process.write(text.encode('cp850'))
     else:
         self.process.write(LOCALE_CODEC.fromUnicode(text))
     self.process.waitForBytesWritten(-1)
Example #51
0
def shell_split(text):
    """Split the string `text` using shell-like syntax
    
    This avoids breaking single/double-quoted strings (e.g. containing 
    strings with spaces). This function is almost equivalent to the shlex.split
    function (see standard library `shlex`) except that it is supporting 
    unicode strings (shlex does not support unicode until Python 2.7.3)."""
    assert is_text_string(text)  # in case a QString is passed...
    pattern = r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')'
    out = []
    for token in re.split(pattern, text):
        if token.strip():
            out.append(token.strip('"').strip("'"))
    return out
Example #52
0
def add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=False):
    # PyQt API 1/2 compatibility-related tests:
    assert isinstance(env, list)
    assert all([is_text_string(path) for path in env])

    pypath = "PYTHONPATH"
    pathstr = os.pathsep.join(pathlist)
    if os.environ.get(pypath) is not None and not drop_env:
        for index, var in enumerate(env[:]):
            if var.startswith(pypath + "="):
                env[index] = var.replace(pypath + "=", pypath + "=" + pathstr + os.pathsep)
        env.append("OLD_PYTHONPATH=" + os.environ[pypath])
    else:
        env.append(pypath + "=" + pathstr)
Example #53
0
def shell_split(text):
    """Split the string `text` using shell-like syntax
    
    This avoids breaking single/double-quoted strings (e.g. containing 
    strings with spaces). This function is almost equivalent to the shlex.split
    function (see standard library `shlex`) except that it is supporting 
    unicode strings (shlex does not support unicode until Python 2.7.3)."""
    assert is_text_string(text)  # in case a QString is passed...
    pattern = r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')'
    out = []
    for token in re.split(pattern, text):
        if token.strip():
            out.append(token.strip('"').strip("'"))
    return out
Example #54
0
def create_action(parent,
                  text,
                  shortcut=None,
                  icon=None,
                  tip=None,
                  toggled=None,
                  triggered=None,
                  data=None,
                  menurole=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        action.toggled.connect(toggled)
        action.setCheckable(True)
    if icon is not None:
        if is_text_string(icon):
            icon = get_icon(icon)
        action.setIcon(icon)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(to_qvariant(data))
    if menurole is not None:
        action.setMenuRole(menurole)

    # Workround for Mac because setting context=Qt.WidgetShortcut
    # there doesn't have any effect
    if sys.platform == 'darwin':
        action._shown_shortcut = None
        if context == Qt.WidgetShortcut:
            if shortcut is not None:
                action._shown_shortcut = shortcut
            else:
                # This is going to be filled by
                # main.register_shortcut
                action._shown_shortcut = 'missing'
        else:
            if shortcut is not None:
                action.setShortcut(shortcut)
            action.setShortcutContext(context)
    else:
        if shortcut is not None:
            action.setShortcut(shortcut)
        action.setShortcutContext(context)

    return action
Example #55
0
 def runfile(self, filename, args=None):
     """
     Run filename
     args: command line arguments (string)
     """
     if args is not None and not is_text_string(args):
         raise TypeError("expected a character buffer object")
     self.namespace['__file__'] = filename
     sys.argv = [filename]
     if args is not None:
         for arg in args.split():
             sys.argv.append(arg)
     self.execfile(filename)
     sys.argv = ['']
     self.namespace.pop('__file__')
Example #56
0
 def runfile(self, filename, args=None):
     """
     Run filename
     args: command line arguments (string)
     """
     if args is not None and not is_text_string(args):
         raise TypeError("expected a character buffer object")
     self.namespace['__file__'] = filename
     sys.argv = [filename]
     if args is not None:
         for arg in args.split():
             sys.argv.append(arg)
     self.execfile(filename)
     sys.argv = ['']
     self.namespace.pop('__file__')
Example #57
0
 def create_mainwindow(self):
     """
     Create a QMainWindow instance containing this plugin
     Note: this method is currently not used
     """
     self.mainwindow = mainwindow = QMainWindow()
     mainwindow.setAttribute(Qt.WA_DeleteOnClose)
     icon = self.get_widget_icon()
     if is_text_string(icon):
         icon = get_icon(icon)
     mainwindow.setWindowIcon(icon)
     mainwindow.setWindowTitle(self.get_plugin_title())
     mainwindow.setCentralWidget(self)
     self.refresh_plugin()
     return mainwindow
Example #58
0
def add_pathlist_to_PYTHONPATH(env, pathlist):
    # PyQt API 1/2 compatibility-related tests:
    assert isinstance(env, list)
    assert all([is_text_string(path) for path in env])

    pypath = "PYTHONPATH"
    pathstr = os.pathsep.join(pathlist)
    if os.environ.get(pypath) is not None:
        for index, var in enumerate(env[:]):
            if var.startswith(pypath + '='):
                env[index] = var.replace(pypath + '=',
                                         pypath + '=' + pathstr + os.pathsep)
        env.append('OLD_PYTHONPATH=' + os.environ[pypath])
    else:
        env.append(pypath + '=' + pathstr)
Example #59
0
 def create_mainwindow(self):
     """
     Create a QMainWindow instance containing this plugin
     Note: this method is currently not used
     """
     self.mainwindow = mainwindow = QMainWindow()
     mainwindow.setAttribute(Qt.WA_DeleteOnClose)
     icon = self.get_widget_icon()
     if is_text_string(icon):
         icon = get_icon(icon)
     mainwindow.setWindowIcon(icon)
     mainwindow.setWindowTitle(self.get_plugin_title())
     mainwindow.setCentralWidget(self)
     self.refresh_plugin()
     return mainwindow