Beispiel #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()
Beispiel #2
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
Beispiel #3
0
    def get(self, section, option, default=NoDefault):
        """
        Get an option
        section=None: attribute a default section name
        default: default value (if not specified, an exception
        will be raised if option doesn't exist)
        """
        section = self._check_section_option(section, option)

        if not self.has_section(section):
            if default is NoDefault:
                raise cp.NoSectionError(section)
            else:
                self.add_section(section)
        
        if not self.has_option(section, option):
            if default is NoDefault:
                raise cp.NoOptionError(option, section)
            else:
                self.set(section, option, default)
                return default
            
        value = cp.ConfigParser.get(self, section, option, raw=self.raw)
        # Use type of default_value to parse value correctly
        default_value = self.get_default(section, option)
        if isinstance(default_value, bool):
            value = ast.literal_eval(value)
        elif isinstance(default_value, float):
            value = float(value)
        elif isinstance(default_value, int):
            value = int(value)
        elif is_text_string(default_value):
            if PY2:
                try:
                    value = value.decode('utf-8')
                    try:
                        # Some str config values expect to be eval after decoding
                        new_value = ast.literal_eval(value)
                        if is_text_string(new_value):
                            value = new_value
                    except (SyntaxError, ValueError):
                        pass
                except (UnicodeEncodeError, UnicodeDecodeError):
                    pass
        else:
            try:
                # lists, tuples, ...
                value = ast.literal_eval(value)
            except (SyntaxError, ValueError):
                pass
        return value
Beispiel #4
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)
            supported_types = (bool,) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES
            if (isinstance(current_value, supported_types) 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
Beispiel #5
0
 def get_bgcolor(self, index):
     """Background color depending on value"""
     column = index.column()
     if column == 0:
         color = QColor(BACKGROUND_NONNUMBER_COLOR)
         color.setAlphaF(BACKGROUND_INDEX_ALPHA)
         return color
     if not self.bgcolor_enabled:
         return
     value = self.get_value(index.row(), column-1)
     if self.max_min_col[column - 1] is None:
         color = QColor(BACKGROUND_NONNUMBER_COLOR)
         if is_text_string(value):
             color.setAlphaF(BACKGROUND_STRING_ALPHA)
         else:
             color.setAlphaF(BACKGROUND_MISC_ALPHA)
     else:
         if isinstance(value, COMPLEX_NUMBER_TYPES):
             color_func = abs
         else:
             color_func = float
         vmax, vmin = self.return_max(self.max_min_col, column-1)
         hue = (BACKGROUND_NUMBER_MINHUE + BACKGROUND_NUMBER_HUERANGE *
                (vmax - color_func(value)) / (vmax - vmin))
         hue = float(abs(hue))
         if hue > 1:
             hue = 1
         color = QColor.fromHsvF(hue, BACKGROUND_NUMBER_SATURATION,
                                 BACKGROUND_NUMBER_VALUE, BACKGROUND_NUMBER_ALPHA)
     return color
Beispiel #6
0
def add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=False,
                               ipyconsole=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:
        old_pypath = os.environ[pypath]
        if not ipyconsole:
            for index, var in enumerate(env[:]):
                if var.startswith(pypath+'='):
                    env[index] = var.replace(pypath+'=',
                                             pypath+'='+pathstr+os.pathsep)
            env.append('OLD_PYTHONPATH='+old_pypath)
        else:
            pypath =  {'PYTHONPATH': pathstr + os.pathsep + old_pypath,
                       'OLD_PYTHONPATH': old_pypath}
            return pypath
    else:
        if not ipyconsole:
            env.append(pypath+'='+pathstr)
        else:
            return {'PYTHONPATH': pathstr}
Beispiel #7
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)
Beispiel #8
0
 def python_executable_changed(self, pyexec):
     """Custom Python executable value has been changed"""
     if not self.cus_exec_radio.isChecked():
         return
     if not is_text_string(pyexec):
         pyexec = to_text_string(pyexec.toUtf8(), 'utf-8')
     self.warn_python_compatibility(pyexec)
Beispiel #9
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)]
Beispiel #10
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
Beispiel #11
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")
Beispiel #12
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))
Beispiel #13
0
 def python_executable_switched(self, custom):
     """Python executable default/custom radio button has been toggled"""
     def_pyexec = get_python_executable()
     cust_pyexec = self.pyexec_edit.text()
     if not is_text_string(cust_pyexec):
         cust_pyexec = to_text_string(cust_pyexec.toUtf8(), 'utf-8')
     if def_pyexec != cust_pyexec:
         if custom:
             self.warn_python_compatibility(cust_pyexec)
Beispiel #14
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))
Beispiel #15
0
 def load_config(self):
     """Load configuration: opened projects & 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.explorer.treewidget.set_expanded_state(expanded_state)
Beispiel #16
0
 def load_config(self):
     """Load configuration: opened projects & tree widget state"""
     self.set_workspace(self.get_option('workspace', None))
     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)
Beispiel #17
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
Beispiel #18
0
    def __init__(self,
                 parent,
                 history_filename,
                 profile=False,
                 initial_message=None,
                 default_foreground_color=None,
                 error_foreground_color=None,
                 traceback_foreground_color=None,
                 prompt_foreground_color=None,
                 background_color=None):
        """
        parent : specifies the parent widget
        """
        ConsoleBaseWidget.__init__(self, parent)
        SaveHistoryMixin.__init__(self, history_filename)
        BrowseHistoryMixin.__init__(self)

        # Prompt position: tuple (line, index)
        self.current_prompt_pos = None
        self.new_input_line = True

        # History
        assert is_text_string(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 = []
        if initial_message:
            self.__buffer.append(initial_message)

        self.__timestamp = 0.0
        self.__flushtimer = QTimer(self)
        self.__flushtimer.setSingleShot(True)
        self.__flushtimer.timeout.connect(self.flush)

        # Give focus to widget
        self.setFocus()

        # Cursor width
        self.setCursorWidth(CONF.get('main', 'cursor/width'))

        # Adjustments to completion_widget to use it here
        self.completion_widget.currentRowChanged.disconnect()
Beispiel #19
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
Beispiel #20
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)
Beispiel #21
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)
     is_document_modified = eol_chars is not None and self.eol_chars is not None
     self.eol_chars = eol_chars
     if is_document_modified:
         self.document().setModified(True)
         if self.sig_eol_chars_changed is not None:
             self.sig_eol_chars_changed.emit(eol_chars)
Beispiel #22
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))  # spyder: test-skip
     cp.ConfigParser.set(self, section, option, value)
Beispiel #23
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))
Beispiel #24
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
Beispiel #25
0
    def _check_defaults(self, defaults):
        """Check if defaults are valid and update defaults values."""
        if isinstance(defaults, dict):
            defaults = [(self.DEFAULT_SECTION_NAME, defaults)]
        elif isinstance(defaults, list):
            # Check is a list of tuples with strings and dictionaries
            for sec, options in defaults:
                assert is_text_string(sec)
                assert isinstance(options, dict)
                for opt, _ in options.items():
                    assert is_text_string(opt)
        else:
            raise ValueError('`defaults` must be a dict or a list of tuples!')

        # This attribute is overriding a method from cp.ConfigParser
        self.defaults = defaults

        if defaults is not None:
            self.reset_to_defaults(save=False)

        return defaults
Beispiel #26
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
Beispiel #27
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 spyder_kernels.utils.nsview import (ndarray, FakeObject,
                                             Image, is_known_type, DataFrame,
                                             Series)
    from spyder.plugins.variableexplorer.widgets.texteditor import TextEditor
    from spyder.plugins.variableexplorer.widgets.collectionseditor import (
            CollectionsEditor)
    from spyder.plugins.variableexplorer.widgets.arrayeditor import (
            ArrayEditor)
    if DataFrame is not FakeObject:
        from spyder.plugins.variableexplorer.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 spyder.pil_patch import Image
        conv_func = lambda data: Image.fromarray(data, mode=obj.mode)
    elif isinstance(obj, (DataFrame, Series)) 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 = CollectionsEditor()
        dialog.setup(obj, title=obj_name, readonly=readonly)

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

    return dialog, end_func
Beispiel #28
0
    def _set(self, section, option, value, verbose):
        """Set method."""
        if not self.has_section(section):
            self.add_section(section)

        if not is_text_string(value):
            value = repr(value)

        if verbose:
            text = '[{}][{}] = {}'.format(section, option, value)
            print(text)  # spyder: test-skip

        super(DefaultsConfig, self).set(section, option, value)
Beispiel #29
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)
Beispiel #30
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)
Beispiel #31
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)
Beispiel #32
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 = SpyderAction(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
Beispiel #33
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)
Beispiel #34
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 spyder.widgets.variableexplorer.texteditor import TextEditor
    from spyder.widgets.variableexplorer.utils import (ndarray, FakeObject,
                                               Image, is_known_type, DataFrame,
                                               Series)
    from spyder.widgets.variableexplorer.collectionseditor import CollectionsEditor
    from spyder.widgets.variableexplorer.arrayeditor import ArrayEditor
    if DataFrame is not FakeObject:
        from spyder.widgets.variableexplorer.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 spyder.pil_patch import Image
        conv_func = lambda data: Image.fromarray(data, mode=obj.mode)
    elif isinstance(obj, (DataFrame, Series)) 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 = CollectionsEditor()
        dialog.setup(obj, title=obj_name, readonly=readonly)

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

    return dialog, end_func
Beispiel #35
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_plugin_icon()
     if is_text_string(icon):
         icon = self.get_icon(icon)
     mainwindow.setWindowIcon(icon)
     mainwindow.setWindowTitle(self.get_plugin_title())
     mainwindow.setCentralWidget(self)
     self.refresh_plugin()
     return mainwindow
Beispiel #36
0
 def python_executable_changed(self, pyexec):
     """Custom Python executable value has been changed"""
     if not self.cus_exec_radio.isChecked():
         return
     if not is_text_string(pyexec):
         pyexec = to_text_string(pyexec.toUtf8(), 'utf-8')
     if programs.is_python_interpreter(pyexec):
         self.warn_python_compatibility(pyexec)
     else:
         QMessageBox.warning(self, _('Warning'),
                 _("You selected an invalid Python interpreter for the "
                   "console so the previous interpreter will stay. Please "
                   "make sure to select a valid one."), QMessageBox.Ok)
         self.pyexec_edit.setText(get_python_executable())
         return
Beispiel #37
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__')
Beispiel #38
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)
Beispiel #39
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_plugin_icon()
     if is_text_string(icon):
         icon = self.get_icon(icon)
     mainwindow.setWindowIcon(icon)
     mainwindow.setWindowTitle(self.get_plugin_title())
     mainwindow.setCentralWidget(self)
     self.refresh_plugin()
     return mainwindow
Beispiel #40
0
    def __init__(self, parent, history_filename, profile=False,
                 initial_message=None, default_foreground_color=None,
                 error_foreground_color=None, traceback_foreground_color=None,
                 prompt_foreground_color=None, background_color=None):
        """
        parent : specifies the parent widget
        """
        ConsoleBaseWidget.__init__(self, parent)
        SaveHistoryMixin.__init__(self, history_filename)
        BrowseHistoryMixin.__init__(self)
                
        # Prompt position: tuple (line, index)
        self.current_prompt_pos = None
        self.new_input_line = True
        
        # History
        assert is_text_string(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 = []
        if initial_message:
            self.__buffer.append(initial_message)

        self.__timestamp = 0.0
        self.__flushtimer = QTimer(self)
        self.__flushtimer.setSingleShot(True)
        self.__flushtimer.timeout.connect(self.flush)

        # Give focus to widget
        self.setFocus()

        # Cursor width
        self.setCursorWidth(CONF.get('main', 'cursor/width'))

        # Adjustments to completion_widget to use it here
        self.completion_widget.currentRowChanged.disconnect()
Beispiel #41
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
Beispiel #42
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
Beispiel #43
0
 def python_executable_changed(self, pyexec):
     """Custom Python executable value has been changed"""
     if not self.cus_exec_radio.isChecked():
         return
     if not is_text_string(pyexec):
         pyexec = to_text_string(pyexec.toUtf8(), 'utf-8')
     if programs.is_python_interpreter(pyexec):
         self.warn_python_compatibility(pyexec)
     else:
         QMessageBox.warning(
             self, _('Warning'),
             _("You selected an invalid Python interpreter for the "
               "console so the previous interpreter will stay. Please "
               "make sure to select a valid one."), QMessageBox.Ok)
         self.pyexec_edit.setText(get_python_executable())
         return
Beispiel #44
0
def display_to_value(value, default_value, ignore_errors=True):
    """Convert back to value"""
    from qtpy.compat import from_qvariant
    value = from_qvariant(value, to_text_string)
    try:
        np_dtype = get_numpy_dtype(default_value)
        if isinstance(default_value, bool):
            # We must test for boolean before NumPy data types
            # because `bool` class derives from `int` class
            try:
                value = bool(float(value))
            except ValueError:
                value = value.lower() == "true"
        elif np_dtype is not None:
            if 'complex' in str(type(default_value)):
                value = np_dtype(complex(value))
            else:
                value = np_dtype(value)
        elif is_binary_string(default_value):
            value = to_binary_string(value, 'utf8')
        elif is_text_string(default_value):
            value = to_text_string(value)
        elif isinstance(default_value, complex):
            value = complex(value)
        elif isinstance(default_value, float):
            value = float(value)
        elif isinstance(default_value, int):
            try:
                value = int(value)
            except ValueError:
                value = float(value)
        elif isinstance(default_value, datetime.datetime):
            value = datestr_to_datetime(value)
        elif isinstance(default_value, datetime.date):
            value = datestr_to_datetime(value).date()
        elif isinstance(default_value, datetime.timedelta):
            value = str_to_timedelta(value)
        elif ignore_errors:
            value = try_to_eval(value)
        else:
            value = eval(value)
    except (ValueError, SyntaxError):
        if ignore_errors:
            value = try_to_eval(value)
        else:
            return default_value
    return value
Beispiel #45
0
def create_action(parent, text, shortcut=None, icon=None, tip=None,
                  toggled=None, triggered=None, data=None, menurole=None,
                  context=Qt.WindowShortcut, option=None, section=None,
                  id_=None, plugin=None, context_name=None,
                  register_action=False, overwrite=False):
    """Create a QAction"""
    action = SpyderAction(text, parent, action_id=id_)
    if triggered is not None:
        action.triggered.connect(triggered)
    if toggled is not None:
        setup_toggled_action(action, toggled, section, option)
    if icon is not None:
        if is_text_string(icon):
            icon = ima.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)

    if register_action:
        ACTION_REGISTRY.register_reference(
            action, id_, plugin, context_name, overwrite)
    return action
Beispiel #46
0
def display_to_value(value, default_value, ignore_errors=True):
    """Convert back to value"""
    from qtpy.compat import from_qvariant
    value = from_qvariant(value, to_text_string)
    try:
        np_dtype = get_numpy_dtype(default_value)
        if isinstance(default_value, bool):
            # We must test for boolean before NumPy data types
            # because `bool` class derives from `int` class
            try:
                value = bool(float(value))
            except ValueError:
                value = value.lower() == "true"
        elif np_dtype is not None:
            if 'complex' in str(type(default_value)):
                value = np_dtype(complex(value))
            else:
                value = np_dtype(value)
        elif is_binary_string(default_value):
            value = to_binary_string(value, 'utf8')
        elif is_text_string(default_value):
            value = to_text_string(value)
        elif isinstance(default_value, complex):
            value = complex(value)
        elif isinstance(default_value, float):
            value = float(value)
        elif isinstance(default_value, int):
            try:
                value = int(value)
            except ValueError:
                value = float(value)
        elif isinstance(default_value, datetime.datetime):
            value = datestr_to_datetime(value)
        elif isinstance(default_value, datetime.date):
            value = datestr_to_datetime(value).date()
        elif isinstance(default_value, datetime.timedelta):
            value = str_to_timedelta(value)
        elif ignore_errors:
            value = try_to_eval(value)
        else:
            value = eval(value)
    except (ValueError, SyntaxError):
        if ignore_errors:
            value = try_to_eval(value)
        else:
            return default_value
    return value
Beispiel #47
0
    def append_to_history(self, filename, command, go_to_eof):
        """
        Append an entry to history filename.

        Args:
            filename (str): file to be updated in a new tab.
            command (str): line to be added.
            go_to_eof (bool): scroll to the end of file.
        """
        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 go_to_eof:
            self.editors[index].set_cursor_position('eof')
        self.tabwidget.setCurrentIndex(index)
Beispiel #48
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
        """
        if not IS_EXT_INTERPRETER:
            from spyder.py3compat import is_text_string
        else:
            from py3compat import is_text_string

        assert is_text_string(text)
        ns = self._get_current_namespace(with_magics=True)
        try:
            return eval(text, ns), True
        except:
            return None, False
Beispiel #49
0
 def get(self):
     valuelist = []
     for index, (label, value) in enumerate(self.data):
         field = self.widgets[index]
         if label is None:
             # Separator / Comment
             continue
         elif tuple_to_qfont(value) is not None:
             value = field.get_font()
         elif is_text_string(value):
             if isinstance(field, QTextEdit):
                 value = to_text_string(field.toPlainText()
                                        ).replace(u"\u2029", os.linesep)
             else:
                 value = to_text_string(field.text())
         elif isinstance(value, (list, tuple)):
             index = int(field.currentIndex())
             if isinstance(value[0], int):
                 # Return an int index, if initialization was an int
                 value = index
             else:
                 value = value[index+1]
                 if isinstance(value, (list, tuple)):
                     value = value[0]
         elif isinstance(value, bool):
             value = field.checkState() == Qt.Checked
         elif isinstance(value, float):
             value = float(field.text())
         elif isinstance(value, int):
             value = int(field.value())
         elif isinstance(value, datetime.datetime):
             value = field.dateTime()
             try:
                 value = value.toPyDateTime()  # PyQt
             except AttributeError:
                 value = value.toPython()  # PySide
         elif isinstance(value, datetime.date):
             value = field.date()
             try:
                 value = value.toPyDate()  # PyQt
             except AttributeError:
                 value = value.toPython()  # PySide
         else:
             value = eval(str(field.text()))
         valuelist.append(value)
     return valuelist
Beispiel #50
0
 def get(self):
     valuelist = []
     for index, (label, value) in enumerate(self.data):
         field = self.widgets[index]
         if label is None:
             # Separator / Comment
             continue
         elif tuple_to_qfont(value) is not None:
             value = field.get_font()
         elif is_text_string(value):
             if isinstance(field, QTextEdit):
                 value = to_text_string(field.toPlainText()
                                        ).replace(u"\u2029", os.linesep)
             else:
                 value = to_text_string(field.text())
         elif isinstance(value, (list, tuple)):
             index = int(field.currentIndex())
             if isinstance(value[0], int):
                 # Return an int index, if initialization was an int
                 value = index
             else:
                 value = value[index+1]
                 if isinstance(value, (list, tuple)):
                     value = value[0]
         elif isinstance(value, bool):
             value = field.checkState() == Qt.Checked
         elif isinstance(value, float):
             value = float(field.text())
         elif isinstance(value, int):
             value = int(field.value())
         elif isinstance(value, datetime.datetime):
             value = field.dateTime()
             try:
                 value = value.toPyDateTime()  # PyQt
             except AttributeError:
                 value = value.toPython()  # PySide
         elif isinstance(value, datetime.date):
             value = field.date()
             try:
                 value = value.toPyDate()  # PyQt
             except AttributeError:
                 value = value.toPython()  # PySide
         else:
             value = eval(str(field.text()))
         valuelist.append(value)
     return valuelist
Beispiel #51
0
    def _create_window(self):
        """Create a QMainWindow instance containing this plugin."""
        self._undocked_window = window = PluginWindow(self)
        window.setAttribute(Qt.WA_DeleteOnClose)
        icon = self.get_plugin_icon()
        if is_text_string(icon):
            icon = self.get_icon(icon)
        window.setWindowIcon(icon)
        window.setWindowTitle(self.get_plugin_title())
        window.setCentralWidget(self)
        window.resize(self.size())
        self.refresh_plugin()

        self.dockwidget.setFloating(False)
        self.dockwidget.setVisible(False)

        window.show()
Beispiel #52
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
        """
        if not IS_EXT_INTERPRETER:
            from spyder.py3compat import is_text_string
        else:
            from py3compat import is_text_string

        assert is_text_string(text)
        ns = self._get_current_namespace(with_magics=True)
        try:
            return eval(text, ns), True
        except:
            return None, False
Beispiel #53
0
    def get(self, name_or_class):
        """
        Gets a specific panel instance.

        :param name_or_klass: Name or class of the panel to retrieve.
        :return: The specified panel instance.
        """
        if not is_text_string(name_or_class):
            name_or_class = name_or_class.__name__
        for zone in range(5):
            try:
                panel = self._panels[zone][name_or_class]
            except KeyError:
                pass
            else:
                return panel
        raise KeyError(name_or_class)
Beispiel #54
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.__buffer.append("NOTE: The Python console is going to "
                             "be REMOVED in Spyder 3.2. Please start "
                             "to migrate your work to the "
                             "IPython console instead.\n\n")
        self.__timestamp = 0.0
        self.__flushtimer = QTimer(self)
        self.__flushtimer.setSingleShot(True)
        self.__flushtimer.timeout.connect(self.flush)

        # Give focus to widget
        self.setFocus()

        # Cursor width
        self.setCursorWidth( CONF.get('main', 'cursor/width') )
Beispiel #55
0
def text_to_qcolor(text):
    """
    Create a QColor from specified string
    Avoid warning from Qt when an invalid QColor is instantiated
    """
    color = QColor()
    text = str(text)
    if not is_text_string(text):
        return color
    if text.startswith('#') and len(text) == 7:
        correct = '#0123456789abcdef'
        for char in text:
            if char.lower() not in correct:
                return color
    elif text not in list(QColor.colorNames()):
        return color
    color.setNamedColor(text)
    return color
Beispiel #56
0
    def get(self, section, option, default=NoDefault):
        """
        Get an option
        section=None: attribute a default section name
        default: default value (if not specified, an exception
        will be raised if option doesn't exist)
        """
        section = self._check_section_option(section, option)

        if not self.has_section(section):
            if default is NoDefault:
                raise cp.NoSectionError(section)
            else:
                self.add_section(section)

        if not self.has_option(section, option):
            if default is NoDefault:
                raise cp.NoOptionError(option, section)
            else:
                self.set(section, option, default)
                return default

        value = cp.ConfigParser.get(self, section, option, raw=self.raw)
        # Use type of default_value to parse value correctly
        default_value = self.get_default(section, option)
        if isinstance(default_value, bool):
            value = ast.literal_eval(value)
        elif isinstance(default_value, float):
            value = float(value)
        elif isinstance(default_value, int):
            value = int(value)
        elif is_text_string(default_value):
            if PY2:
                try:
                    value = value.decode('utf-8')
                except (UnicodeEncodeError, UnicodeDecodeError):
                    pass
        else:
            try:
                # lists, tuples, ...
                value = ast.literal_eval(value)
            except (SyntaxError, ValueError):
                pass
        return value
Beispiel #57
0
    def start(self):
        """Main method of the WorkerUpdates worker"""
        self.url = 'https://api.github.com/repos/spyder-ide/spyder/releases'
        self.update_available = False
        self.latest_release = __version__

        error_msg = None

        try:
            if hasattr(ssl, '_create_unverified_context'):
                # Fix for issue # 2685 [Works only with Python >=2.7.9]
                # More info: https://www.python.org/dev/peps/pep-0476/#opting-out
                context = ssl._create_unverified_context()
                page = urlopen(self.url, context=context)
            else:
                page = urlopen(self.url)
            try:
                data = page.read()

                # Needed step for python3 compatibility
                if not is_text_string(data):
                    data = data.decode()

                data = json.loads(data)
                releases = [item['tag_name'].replace('v', '') for item in data]
                version = __version__

                result = self.check_update_available(version, releases)
                self.update_available, self.latest_release = result
            except Exception:
                error_msg = _('Unable to retrieve information.')
        except HTTPError:
            error_msg = _('Unable to retrieve information.')
        except URLError:
            error_msg = _('Unable to connect to the internet. <br><br>Make '
                          'sure the connection is working properly.')
        except Exception:
            error_msg = _('Unable to check for updates.')

        # Don't show dialog when starting up spyder and an error occur
        if not (self.startup and error_msg is not None):
            self.error = error_msg
            self.sig_ready.emit()
 def setEditorData(self, editor, index):
     """
     Overriding method setEditorData
     Model --> Editor
     """
     value = self.get_value(index)
     if isinstance(editor, QLineEdit):
         if is_binary_string(value):
             try:
                 value = to_text_string(value, 'utf8')
             except Exception:
                 pass
         if not is_text_string(value):
             value = repr(value)
         editor.setText(value)
     elif isinstance(editor, QDateEdit):
         editor.setDate(value)
     elif isinstance(editor, QDateTimeEdit):
         editor.setDateTime(QDateTime(value.date(), value.time()))