Beispiel #1
0
 def __init__(self, parent):
     PydocBrowser.__init__(self, parent)
     SpyderPluginMixin.__init__(self, parent)
     
     self.set_zoom_factor(CONF.get(self.ID, 'zoom_factor'))
     self.url_combo.setMaxCount(CONF.get(self.ID, 'max_history_entries'))
     self.url_combo.addItems( self.load_history() )
Beispiel #2
0
    def show_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner
        
        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            backend_o = CONF.get('ipython_console', 'pylab/backend', 0)
            backends = {0: 'module://IPython.zmq.pylab.backend_inline',
                        1: 'Qt4Agg', 2: 'Qt4Agg', 3: 'MacOSX', 4: 'GTKAgg',
                        5: 'WXAgg', 6: 'TKAgg'}
            pylab_013_message = """
Welcome to pylab, a matplotlib-based Python environment [backend: %s].
For more information, type 'help(pylab)'.\n""" % backends[backend_o]
            pylab_1_message = """
Populating the interactive namespace from numpy and matplotlib"""
            if programs.is_module_installed('IPython', '>=1.0'):
                banner = banner + pylab_1_message
            else:
                banner = banner + pylab_013_message
        
        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
Beispiel #3
0
    def long_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner
        
        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            pylab_message = ("\nPopulating the interactive namespace from "
                             "numpy and matplotlib")
            banner = banner + pylab_message
        
        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
Beispiel #4
0
 def setup_api(self):
     """Load and prepare Python API"""
     if self.lexer() is None:
         return
     self.api = QsciAPIs(self.lexer())
     is_api_ready = False
     api_path = CONF.get('editor', 'api')
     if not osp.isfile(api_path):
         from spyderlib.config import DATA_PATH
         api_path = osp.join(DATA_PATH, 'python.api')
         if osp.isfile(api_path):
             CONF.set('editor', 'api', api_path)
         else:
             return False
     api_size = CONF.get('editor', 'api_size', None)
     current_api_size = os.stat(api_path).st_size
     if api_size is not None and api_size == current_api_size:
         if self.api.isPrepared():
             is_api_ready = self.api.loadPrepared()
     else:
         CONF.set('editor', 'api_size', current_api_size)
     if not is_api_ready:
         if self.api.load(api_path):
             self.api.prepare()
             self.connect(self.api, SIGNAL("apiPreparationFinished()"),
                          self.api.savePrepared)
     return is_api_ready
Beispiel #5
0
    def long_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner

        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            pylab_message = ("\nPopulating the interactive namespace from "
                             "numpy and matplotlib")
            banner = banner + pylab_message

        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
Beispiel #6
0
 def open_interpreter_at_startup(self):
     """Open an interpreter at startup, IPython if module is available"""
     if CONF.get(self.ID, 'open_ipython_at_startup') \
        and programs.is_module_installed("IPython"):
         self.open_ipython()
     if CONF.get(self.ID, 'open_python_at_startup'):
         self.open_interpreter()
Beispiel #7
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.shell = parent

        # Dict editor:
        truncate = CONF.get(self.ID, 'truncate')
        inplace = CONF.get(self.ID, 'inplace')
        minmax = CONF.get(self.ID, 'minmax')
        collvalue = CONF.get(self.ID, 'collvalue')
        self.editor = RemoteDictEditorTableView(
            parent,
            None,
            truncate=truncate,
            inplace=inplace,
            minmax=minmax,
            collvalue=collvalue,
            get_value_func=self.get_value,
            set_value_func=self.set_value,
            new_value_func=self.set_value,
            remove_values_func=self.remove_values,
            copy_value_func=self.copy_value)
        self.connect(self.editor, SIGNAL('option_changed'),
                     self.option_changed)

        # Setup layout
        vlayout = QVBoxLayout()
        hlayout = QHBoxLayout()
        self.setup_toolbar(hlayout)
        vlayout.addLayout(hlayout)
        vlayout.addWidget(self.editor)
        self.setLayout(vlayout)

        self.connect(self, SIGNAL('option_changed'), self.option_changed)
Beispiel #8
0
    def __init__(self, parent):
        PluginWidget.__init__(self, parent)

        # Read-only editor
        self.editor = QsciEditor(self)
        self.editor.setup_editor(linenumbers=False, language='py',
                                 code_folding=True)
        self.connect(self.editor, SIGNAL("focus_changed()"),
                     lambda: self.emit(SIGNAL("focus_changed()")))
        self.editor.setReadOnly(True)
        self.editor.set_font( get_font(self.ID) )
        self.editor.toggle_wrap_mode( CONF.get(self.ID, 'wrap') )
        
        # Add entries to read-only editor context-menu
        font_action = create_action(self, translate("Editor", "&Font..."), None,
                                    'font.png',
                                    translate("Editor", "Set font style"),
                                    triggered=self.change_font)
        wrap_action = create_action(self, translate("Editor", "Wrap lines"),
                                    toggled=self.toggle_wrap_mode)
        wrap_action.setChecked( CONF.get(self.ID, 'wrap') )
        self.editor.readonly_menu.addSeparator()
        add_actions(self.editor.readonly_menu, (font_action, wrap_action))
        
        # Find/replace widget
        self.find_widget = FindReplace(self)
        self.find_widget.set_editor(self.editor)
        self.find_widget.hide()
Beispiel #9
0
 def setup(self):
     """Configure QTextEdit"""
     # Calltips
     self.calltip_size = CONF.get('shell_appearance', 'calltips/size')
     self.calltip_font = get_font('shell_appearance', 'calltips')
     # Completion
     self.completion_size = CONF.get('shell_appearance', 'completion/size')
     self.completion_font = get_font('shell_appearance', 'completion')
Beispiel #10
0
 def update_margins(self):
     layout = self.layout()
     if self.default_margins is None:
         self.default_margins = layout.getContentsMargins()
     if CONF.get('main', 'use_custom_margin'):
         margin = CONF.get('main', 'custom_margin')
         layout.setContentsMargins(*[margin] * 4)
     else:
         layout.setContentsMargins(*self.default_margins)
Beispiel #11
0
def _get_run_configurations():
    history_count = CONF.get('run', 'history', 20)
    try:
        return [(filename, options)
                for filename, options in CONF.get('run', 'configurations', [])
                if osp.isfile(filename)][:history_count]
    except ValueError:
        CONF.set('run', 'configurations', [])
        return []
 def update_margins(self):
     layout = self.layout()
     if self.default_margins is None:
         self.default_margins = layout.getContentsMargins()
     if CONF.get('main', 'use_custom_margin'):
         margin = CONF.get('main', 'custom_margin')
         layout.setContentsMargins(*[margin]*4)
     else:
         layout.setContentsMargins(*self.default_margins)
Beispiel #13
0
 def setup(self):
     """Configure QPlainTextEdit"""
     # Calltips
     self.calltip_size = CONF.get('shell_appearance', 'calltips/size')
     self.calltip_font = get_font('shell_appearance', 'calltips')
     # Completion
     size = CONF.get('shell_appearance', 'completion/size')
     font = get_font('shell_appearance', 'completion')
     self.completion_widget.setup_appearance(size, font)
Beispiel #14
0
def _get_run_configurations():
    history_count = CONF.get('run', 'history', 20)
    try:
        return [(filename, options)
                for filename, options in CONF.get('run', 'configurations', [])
                if osp.isfile(filename)][:history_count]
    except ValueError:
        CONF.set('run', 'configurations', [])
        return []
Beispiel #15
0
def wsfilter(input_dict, itermax=ITERMAX, filters=FILTERS):
    """Keep only objects that can be pickled"""
    exclude_private = CONF.get('workspace', 'exclude_private')
    exclude_upper = CONF.get('workspace', 'exclude_upper')
    exclude_unsupported = CONF.get('workspace', 'exclude_unsupported')
    excluded_names = CONF.get('workspace', 'excluded_names')
    return globalsfilter(input_dict, itermax=itermax, filters=filters,
                         exclude_private=exclude_private,
                         exclude_upper=exclude_upper,
                         exclude_unsupported=exclude_unsupported,
                         excluded_names=excluded_names)
Beispiel #16
0
    def __init__(self, parent):
        ReadOnlyEditor.__init__(self, parent)
        
        self.shell = None
        
        self.external_console = None
        
        # locked = disable link with Console
        self.locked = False
        self._last_text = None
        
        # Object name
        layout_edit = QHBoxLayout()
        layout_edit.addWidget(QLabel(self.tr("Object")))
        self.combo = ObjectComboBox(self)
        layout_edit.addWidget(self.combo)
        self.combo.setMaxCount(CONF.get(self.ID, 'max_history_entries'))
        self.combo.addItems( self.load_history() )
        self.connect(self.combo, SIGNAL("valid(bool)"),
                     lambda valid: self.force_refresh())
        
        # Doc/source option
        help_or_doc = create_action(self, self.tr("Show source"),
                                    toggled=self.toggle_help)
        help_or_doc.setChecked(False)
        self.docstring = True
        
        # Automatic import option
        auto_import = create_action(self, self.tr("Automatic import"),
                                    toggled=self.toggle_auto_import)
        auto_import_state = CONF.get('inspector', 'automatic_import')
        auto_import.setChecked(auto_import_state)
        
        # Lock checkbox
        self.locked_button = create_toolbutton(self,
                                               triggered=self.toggle_locked)
        layout_edit.addWidget(self.locked_button)
        self._update_lock_icon()
        
        # Option menu
        options_button = create_toolbutton(self, text=self.tr("Options"),
                                           icon=get_icon('tooloptions.png'))
        options_button.setPopupMode(QToolButton.InstantPopup)
        menu = QMenu(self)
        add_actions(menu, [help_or_doc, auto_import])
        options_button.setMenu(menu)
        layout_edit.addWidget(options_button)

        # Main layout
        layout = QVBoxLayout()
        layout.addLayout(layout_edit)
        layout.addWidget(self.editor)
        layout.addWidget(self.find_widget)
        self.setLayout(layout)
Beispiel #17
0
def set_color_scheme(name, color_scheme, replace=True):
    """Set syntax color scheme"""
    section = "color_schemes"
    names = CONF.get("color_schemes", "names", [])
    for key in sh.COLOR_SCHEME_KEYS:
        option = "%s/%s" % (name, key)
        value = CONF.get(section, option, default=None)
        if value is None or replace or name not in names:
            CONF.set(section, option, color_scheme[key])
    names.append(to_text_string(name))
    CONF.set(section, "names", sorted(list(set(names))))
Beispiel #18
0
def set_color_scheme(name, color_scheme, replace=True):
    """Set syntax color scheme"""
    section = "color_schemes"
    names = CONF.get("color_schemes", "names", [])
    for key in sh.COLOR_SCHEME_KEYS:
        option = "%s/%s" % (name, key)
        value = CONF.get(section, option, default=None)
        if value is None or replace or name not in names:
            CONF.set(section, option, color_scheme[key])
    names.append(to_text_string(name))
    CONF.set(section, "names", sorted(list(set(names))))
Beispiel #19
0
    def __init__(self, parent, history_filename, debug=False, profile=False):
        """
        parent : specifies the parent widget
        """
        ConsoleBaseWidget.__init__(self, parent)
                
        # Prompt position: tuple (line, index)
        self.current_prompt_pos = None
        self.new_input_line = True
        
        # History
        self.histidx = None
        self.hist_wholeline = False
        assert isinstance(history_filename, (str, unicode))
        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()

        # Debug mode
        self.debug = debug

        # 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') )
Beispiel #20
0
    def __init__(self, parent=None, path=None):
        ExplorerWidget.__init__(self, parent=parent, path=path,
                            name_filters=CONF.get(self.ID, 'name_filters'),
                            valid_types=CONF.get(self.ID, 'valid_filetypes'),
                            show_all=CONF.get(self.ID, 'show_all'),
                            show_toolbar=CONF.get(self.ID, 'show_toolbar'),
                            show_icontext=CONF.get(self.ID, 'show_icontext'))
        PluginMixin.__init__(self, parent)

        self.set_font(get_font(self.ID))
        
        self.connect(self, SIGNAL("open_file(QString)"), self.open_file)
Beispiel #21
0
def wsfilter(input_dict, itermax=ITERMAX, filters=FILTERS):
    """Keep only objects that can be pickled"""
    exclude_private = CONF.get('workspace', 'exclude_private')
    exclude_upper = CONF.get('workspace', 'exclude_upper')
    exclude_unsupported = CONF.get('workspace', 'exclude_unsupported')
    excluded_names = CONF.get('workspace', 'excluded_names')
    return globalsfilter(input_dict,
                         itermax=itermax,
                         filters=filters,
                         exclude_private=exclude_private,
                         exclude_upper=exclude_upper,
                         exclude_unsupported=exclude_unsupported,
                         excluded_names=excluded_names)
Beispiel #22
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get('internal_console', 'external_editor/path')
     goto_option = CONF.get('internal_console', 'external_editor/gotoline')
     try:
         if goto > 0 and goto_option:
             Popen(r'%s "%s" %s%d' % (editor_path, filename,
                                      goto_option, goto))
         else:
             Popen(r'%s "%s"' % (editor_path, filename))
     except OSError:
         self.write_error("External editor was not found:"
                          " %s\n" % editor_path)
Beispiel #23
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get('shell', 'external_editor/path')
     goto_option = CONF.get('shell', 'external_editor/gotoline')
     try:
         if goto > 0 and goto_option:
             Popen(r'%s "%s" %s%d' % (editor_path, filename,
                                      goto_option, goto))
         else:
             Popen(r'%s "%s"' % (editor_path, filename))
     except OSError:
         self.write_error("External editor was not found:"
                          " %s\n" % editor_path)
 def set_actions(self):
     """Setup actions"""
     interpreter_action = create_action(self,
                         self.tr("Open &interpreter"), None,
                         'python.png', self.tr("Open a Python interpreter"),
                         triggered=self.open_interpreter)
     if os.name == 'nt':
         text = self.tr("Open &command prompt")
         tip = self.tr("Open a Windows command prompt")
     else:
         text = self.tr("Open &command shell")
         tip = self.tr("Open a shell window inside Spyder")
     console_action = create_action(self, text, None, 'cmdprompt.png', tip,
                         triggered=self.open_console)
     run_action = create_action(self,
                         self.tr("&Run..."), None,
                         'run_small.png', self.tr("Run a Python script"),
                         triggered=self.run_script)
     font_action = create_action(self,
                         self.tr("&Font..."), None,
                         'font.png', self.tr("Set shell font style"),
                         triggered=self.change_font)
     wrap_action = create_action(self,
                         self.tr("Wrap lines"),
                         toggled=self.toggle_wrap_mode)
     wrap_action.setChecked( CONF.get(self.ID, 'wrap') )
     calltips_action = create_action(self, self.tr("Balloon tips"),
                         toggled=self.toggle_calltips)
     calltips_action.setChecked( CONF.get(self.ID, 'calltips') )
     codecompletion_action = create_action(self, self.tr("Code completion"),
                         toggled=self.toggle_codecompletion)
     codecompletion_action.setChecked( CONF.get(self.ID,
                                                'autocompletion/enabled') )
     codecompenter_action = create_action(self,
                                 self.tr("Enter key selects completion"),
                                 toggled=self.toggle_codecompletion_enter)
     codecompenter_action.setChecked( CONF.get(self.ID,
                                               'autocompletion/enter-key') )
     singletab_action = create_action(self,
                         self.tr("One tab per script"),
                         toggled=self.toggle_singletab)
     singletab_action.setChecked( CONF.get(self.ID, 'single_tab') )
     self.menu_actions = [interpreter_action, run_action, None,
                          font_action, wrap_action, calltips_action,
                          codecompletion_action, codecompenter_action,
                          singletab_action]
     if console_action:
         self.menu_actions.insert(1, console_action)
     return (self.menu_actions, None)
Beispiel #25
0
    def __init__(self, parent=None, path=None):
        ExplorerWidget.__init__(
            self,
            parent=parent,
            path=path,
            name_filters=CONF.get(self.ID, "name_filters"),
            valid_types=CONF.get(self.ID, "valid_filetypes"),
            show_all=CONF.get(self.ID, "show_all"),
            show_toolbar=CONF.get(self.ID, "show_toolbar"),
            show_icontext=CONF.get(self.ID, "show_icontext"),
        )
        PluginMixin.__init__(self, parent)

        self.set_font(get_font(self.ID))

        self.connect(self, SIGNAL("open_file(QString)"), self.open_file)
Beispiel #26
0
    def show_help(self, obj_text):
        """Show help"""
        if self.shell is None:
            return
        self._check_if_shell_is_running()
        obj_text = unicode(obj_text)

        if CONF.get('inspector', 'automatic_import'):
            self.shell.is_defined(obj_text, force_import=True) # force import
        
        if self.shell.is_defined(obj_text):
            doc_text = self.shell.get_doc(obj_text)
            source_text = self.shell.get_source(obj_text)
        else:
            doc_text = None
            source_text = None
        if self.docstring:
            hlp_text = doc_text
            if hlp_text is None:
                hlp_text = source_text
                if hlp_text is None:
                    hlp_text = self.tr("No documentation available.")
        else:
            hlp_text = source_text
            if hlp_text is None:
                hlp_text = doc_text
                if hlp_text is None:
                    hlp_text = self.tr("No source code available.")
        self.editor.set_text(hlp_text)
        self.editor.set_cursor_position('sof')
Beispiel #27
0
 def closing(self, cancelable=False):
     """Perform actions before parent main window is closed"""
     if CONF.get(self.ID, 'autosave'):
         # Saving workspace
         self.__save(self.TEMPFILE_PATH)
     else:
         workspace = self.get_namespace(itermax=-1)
         if workspace is None:
             return True
         refnb = len(workspace)
         if refnb > 1:
             srefnb = str(refnb)
             s_or_not = 's'
             it_or_them = self.tr('them')
         else:
             srefnb = self.tr('one')
             s_or_not = ''
             it_or_them = self.tr('it')
         if refnb > 0:
             buttons = QMessageBox.Yes | QMessageBox.No
             if cancelable:
                 buttons = buttons | QMessageBox.Cancel
             answer = QMessageBox.question(self, self.get_widget_title(),
                self.tr("Workspace is currently keeping reference "
                        "to %1 object%2.\n\nDo you want to save %3?") \
                .arg(srefnb).arg(s_or_not).arg(it_or_them), buttons)
             if answer == QMessageBox.Yes:
                 # Saving workspace
                 self.__save(self.TEMPFILE_PATH)
             elif answer == QMessageBox.Cancel:
                 return False
             elif osp.isfile(self.TEMPFILE_PATH):
                 # Removing last saved workspace
                 os.remove(self.TEMPFILE_PATH)
     return True
Beispiel #28
0
 def open_ipython(self, wdir=None):
     """Open IPython"""
     if wdir is None:
         wdir = os.getcwdu()
     self.start(fname=None, wdir=unicode(wdir), ask_for_arguments=False,
                interact=True, debug=False, python=True, ipython=True,
                arguments=CONF.get(self.ID, 'ipython_options', ""))
Beispiel #29
0
 def change_history_depth(self):
     "Change history max entries" ""
     depth, valid = QInputDialog.getInteger(
         self, self.tr('History'), self.tr('Maximum entries'),
         CONF.get(self.ID, 'max_entries'), 10, 10000)
     if valid:
         CONF.set(self.ID, 'max_entries', depth)
Beispiel #30
0
 def closing(self, cancelable=False):
     """Perform actions before parent main window is closed"""
     if CONF.get(self.ID, 'autosave'):
         # Saving workspace
         self.__save(self.TEMPFILE_PATH)
     else:
         workspace = self.get_namespace(itermax=-1)
         if workspace is None:
             return True
         refnb = len(workspace)
         if refnb > 1:
             srefnb = str(refnb)
             s_or_not = 's'
             it_or_them = self.tr('them')
         else:
             srefnb = self.tr('one')
             s_or_not = ''
             it_or_them = self.tr('it')
         if refnb > 0:
             buttons = QMessageBox.Yes | QMessageBox.No
             if cancelable:
                 buttons = buttons | QMessageBox.Cancel
             answer = QMessageBox.question(self, self.get_widget_title(),
                self.tr("Workspace is currently keeping reference "
                        "to %1 object%2.\n\nDo you want to save %3?") \
                .arg(srefnb).arg(s_or_not).arg(it_or_them), buttons)
             if answer == QMessageBox.Yes:
                 # Saving workspace
                 self.__save(self.TEMPFILE_PATH)
             elif answer == QMessageBox.Cancel:
                 return False
             elif osp.isfile(self.TEMPFILE_PATH):
                 # Removing last saved workspace
                 os.remove(self.TEMPFILE_PATH)
     return True
Beispiel #31
0
def send_args_to_spyder(args):
    """
    Simple socket client used to send the args passed to the Spyder 
    executable to an already running instance.

    Args can be Python scripts or files with these extensions: .spydata, .mat,
    .npy, or .h5, which can be imported by the Variable Explorer.
    """
    port = CONF.get('main', 'open_files_port')

    # Wait ~50 secs for the server to be up
    # Taken from http://stackoverflow.com/a/4766598/438386
    for _x in range(200):
        try:
            for arg in args:
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                       socket.IPPROTO_TCP)
                client.connect(("127.0.0.1", port))
                if is_unicode(arg):
                    arg = arg.encode('utf-8')
                client.send(osp.abspath(arg))
                client.close()
        except socket.error:
            time.sleep(0.25)
            continue
        break
Beispiel #32
0
    def __init__(self, parent=None):
        PylintWidget.__init__(self,
                              parent=parent,
                              max_entries=CONF.get(self.ID, 'max_entries'))
        PluginMixin.__init__(self, parent)

        self.set_font(get_font(self.ID))
Beispiel #33
0
 def load_config(self):
     """Load configuration: opened projects & tree widget state"""
     data = cPickle.load(file(self.DATAPATH))
     self.set_project_config(data)
     expanded_state = CONF.get(self.ID, 'expanded_state', None)
     if expanded_state is not None:
         self.treewidget.set_expanded_state(expanded_state)
Beispiel #34
0
def send_args_to_spyder(args):
    """
    Simple socket client used to send the args passed to the Spyder 
    executable to an already running instance.

    Args can be Python scripts or files with these extensions: .spydata, .mat,
    .npy, or .h5, which can be imported by the Variable Explorer.
    """
    port = CONF.get('main', 'open_files_port')

    # Wait ~50 secs for the server to be up
    # Taken from http://stackoverflow.com/a/4766598/438386
    for _x in range(200):
        try:
            for arg in args:
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                       socket.IPPROTO_TCP)
                client.connect(("127.0.0.1", port))
                if is_unicode(arg):
                    arg = arg.encode('utf-8')
                client.send(osp.abspath(arg))
                client.close()
        except socket.error:
            time.sleep(0.25)
            continue
        break
Beispiel #35
0
    def create_dockwidget(self):
        """Add to parent QMainWindow as a dock widget"""

        # This is not clear yet why the following do not work...
        # (see Issue #880)
        ##         # Using Qt.Window window flags solves Issue #880 (detached dockwidgets
        ##         # are not painted after restarting Spyder and restoring their hexstate)
        ##         # but it does not work with PyQt <=v4.7 (dockwidgets can't be docked)
        ##         # or non-Windows platforms (lot of warnings are printed out)
        ##         # (so in those cases, we use the default window flags: Qt.Widget):
        ##         flags = Qt.Widget if is_old_pyqt or os.name != 'nt' else Qt.Window
        dock = SpyderDockWidget(self.get_plugin_title(), self.main)  # , flags)

        dock.setObjectName(self.__class__.__name__ + "_dw")
        dock.setAllowedAreas(self.ALLOWED_AREAS)
        dock.setFeatures(self.FEATURES)
        dock.setWidget(self)
        self.update_margins()
        self.connect(dock, SIGNAL("visibilityChanged(bool)"), self.visibility_changed)
        self.connect(dock, SIGNAL("plugin_closed()"), self.plugin_closed)
        self.dockwidget = dock
        try:
            short = CONF.get("shortcuts", "_/switch to %s" % self.CONF_SECTION)
        except configparser.NoOptionError:
            short = None
        if short is not None:
            shortcut = QShortcut(QKeySequence(short), self.main, self.switch_to_plugin)
            self.register_shortcut(shortcut, "_", "Switch to %s" % self.CONF_SECTION)
        return (dock, self.LOCATION)
Beispiel #36
0
    def add_history(self, filename):
        """
        Add new history tab
        Slot for SIGNAL('add_history(QString)') emitted by shell instance
        """
        filename = encoding.to_unicode(filename)
        if filename in self.filenames:
            return
        editor = CodeEditor(self)
        if osp.splitext(filename)[1] == '.py':
            language = 'py'
            icon = get_icon('python.png')
        else:
            language = 'bat'
            icon = get_icon('cmdprompt.png')
        editor.setup_editor(linenumbers=False, language=language,
                            code_folding=True, scrollflagarea=False)
        self.connect(editor, SIGNAL("focus_changed()"),
                     lambda: self.emit(SIGNAL("focus_changed()")))
        editor.setReadOnly(True)
        editor.set_font( get_font(self.ID) )
        editor.toggle_wrap_mode( CONF.get(self.ID, 'wrap') )

        text, _ = encoding.read(filename)
        editor.set_text(text)
        editor.set_cursor_position('eof')
        
        self.editors.append(editor)
        self.filenames.append(filename)
        self.icons.append(icon)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setTabIcon(index, icon)
        self.tabwidget.setCurrentIndex(index)
Beispiel #37
0
 def _install_rollback_importer(self):
     if self.rollback_importer is not None:
         self.rollback_importer.uninstall()
     if CONF.get('shell', 'rollback_importer'):
         self.rollback_importer = RollbackImporter()
     else:
         self.rollback_importer = None
Beispiel #38
0
    def create_dockwidget(self):
        """Add to parent QMainWindow as a dock widget"""

        # This is not clear yet why the following do not work...
        # (see Issue #880)
        ##         # Using Qt.Window window flags solves Issue #880 (detached dockwidgets
        ##         # are not painted after restarting Spyder and restoring their hexstate)
        ##         # but it does not work with PyQt <=v4.7 (dockwidgets can't be docked)
        ##         # or non-Windows platforms (lot of warnings are printed out)
        ##         # (so in those cases, we use the default window flags: Qt.Widget):
        ##         flags = Qt.Widget if is_old_pyqt or os.name != 'nt' else Qt.Window
        dock = SpyderDockWidget(self.get_plugin_title(), self.main)  #, flags)

        dock.setObjectName(self.__class__.__name__ + "_dw")
        dock.setAllowedAreas(self.ALLOWED_AREAS)
        dock.setFeatures(self.FEATURES)
        dock.setWidget(self)
        self.update_margins()
        self.connect(dock, SIGNAL('visibilityChanged(bool)'),
                     self.visibility_changed)
        self.connect(dock, SIGNAL('plugin_closed()'), self.plugin_closed)
        self.dockwidget = dock
        try:
            short = CONF.get('shortcuts', '_/switch to %s' % self.CONF_SECTION)
        except configparser.NoOptionError:
            short = None
        if short is not None:
            shortcut = QShortcut(QKeySequence(short), self.main,
                                 self.switch_to_plugin)
            self.register_shortcut(shortcut, "_",
                                   "Switch to %s" % self.CONF_SECTION)
        return (dock, self.LOCATION)
Beispiel #39
0
    def setup_page(self):
        settings_group = QGroupBox(_("Settings"))
        hist_spin = self.create_spinbox(
                            _("History depth: "), _(" entries"),
                            'max_entries', min_=10, max_=10000, step=10,
                            tip=_("Set maximum line count"))

        sourcecode_group = QGroupBox(_("Source code"))
        wrap_mode_box = self.create_checkbox(_("Wrap lines"), 'wrap')
        go_to_eof_box = self.create_checkbox(
                        _("Scroll automatically to last entry"), 'go_to_eof')
        font_group = self.create_fontgroup(option=None,
                                    text=_("Font style"),
                                    fontfilters=QFontComboBox.MonospacedFonts)
        names = CONF.get('color_schemes', 'names')
        choices = list(zip(names, names))
        cs_combo = self.create_combobox(_("Syntax color scheme: "),
                                        choices, 'color_scheme_name')

        settings_layout = QVBoxLayout()
        settings_layout.addWidget(hist_spin)
        settings_group.setLayout(settings_layout)

        sourcecode_layout = QVBoxLayout()
        sourcecode_layout.addWidget(wrap_mode_box)
        sourcecode_layout.addWidget(go_to_eof_box)
        sourcecode_layout.addWidget(cs_combo)
        sourcecode_group.setLayout(sourcecode_layout)
        
        vlayout = QVBoxLayout()
        vlayout.addWidget(settings_group)
        vlayout.addWidget(font_group)
        vlayout.addWidget(sourcecode_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Beispiel #40
0
    def setup_page(self):
        settings_group = QGroupBox(_("Settings"))
        hist_spin = self.create_spinbox(
                            _("History depth: "), _(" entries"),
                            'max_entries', min_=10, max_=10000, step=10,
                            tip=_("Set maximum line count"))

        sourcecode_group = QGroupBox(_("Source code"))
        wrap_mode_box = self.create_checkbox(_("Wrap lines"), 'wrap')
        go_to_eof_box = self.create_checkbox(
                        _("Scroll automatically to last entry"), 'go_to_eof')
        font_group = self.create_fontgroup(option=None,
                                    text=_("Font style"),
                                    fontfilters=QFontComboBox.MonospacedFonts)
        names = CONF.get('color_schemes', 'names')
        choices = list(zip(names, names))
        cs_combo = self.create_combobox(_("Syntax color scheme: "),
                                        choices, 'color_scheme_name')

        settings_layout = QVBoxLayout()
        settings_layout.addWidget(hist_spin)
        settings_group.setLayout(settings_layout)

        sourcecode_layout = QVBoxLayout()
        sourcecode_layout.addWidget(wrap_mode_box)
        sourcecode_layout.addWidget(go_to_eof_box)
        sourcecode_layout.addWidget(cs_combo)
        sourcecode_group.setLayout(sourcecode_layout)
        
        vlayout = QVBoxLayout()
        vlayout.addWidget(font_group)
        vlayout.addWidget(settings_group)
        vlayout.addWidget(sourcecode_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
    def __init__(self, main):
        """Bind widget to a QMainWindow instance"""
        super(SpyderPluginMixin, self).__init__()
        assert self.CONF_SECTION is not None
        self.main = main
        self.default_margins = None
        self.plugin_actions = None
        self.dockwidget = None
        self.mainwindow = None
        self.ismaximized = False
        self.isvisible = False

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

        # We decided to create our own toggle action instead of using
        # the one that comes with dockwidget because it's not possible
        # to raise and focus the plugin with it.
        self.toggle_view_action = None
Beispiel #42
0
 def _install_rollback_importer(self):
     if self.rollback_importer is not None:
         self.rollback_importer.uninstall()
     if CONF.get('shell', 'rollback_importer'):
         self.rollback_importer = RollbackImporter()
     else:
         self.rollback_importer = None
Beispiel #43
0
 def __init__(self, fname=None):
     self.args = None
     self.args_enabled = None
     self.wdir = None
     self.wdir_enabled = None
     self.current = None
     self.systerm = None
     self.interact = None
     self.show_kill_warning = None
     self.python_args = None
     self.python_args_enabled = None
     self.set(CONF.get('run', 'defaultconfiguration', default={}))
     if fname is not None and\
        CONF.get('run', WDIR_USE_SCRIPT_DIR_OPTION, True):
         self.wdir = osp.dirname(fname)
         self.wdir_enabled = True
Beispiel #44
0
    def __init__(self, main=None, **kwds):
        """Bind widget to a QMainWindow instance"""
        super(SpyderPluginMixin, self).__init__(**kwds)
        assert self.CONF_SECTION is not None
        self.main = main
        self.default_margins = None
        self.plugin_actions = None
        self.dockwidget = None
        self.mainwindow = None
        self.ismaximized = False
        self.isvisible = False

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

        # We decided to create our own toggle action instead of using
        # the one that comes with dockwidget because it's not possible
        # to raise and focus the plugin with it.
        self.toggle_view_action = None
Beispiel #45
0
 def change_exteditor(self):
     """Change external editor path"""
     path, valid = QInputDialog.getText(self, self.tr('External editor'),
                       self.tr('External editor executable path:'),
                       QLineEdit.Normal,
                       CONF.get(self.ID, 'external_editor/path'))
     if valid:
         CONF.set(self.ID, 'external_editor/path', unicode(path))
Beispiel #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.__flushtimer.timeout.connect(self.flush)

        # Give focus to widget
        self.setFocus()

        # Completion
        completion_size = CONF.get('shell_appearance', 'completion/size')
        completion_font = get_font('console')
        self.completion_widget.setup_appearance(completion_size,
                                                completion_font)
        # Cursor width
        self.setCursorWidth(CONF.get('shell_appearance', 'cursor/width'))
Beispiel #47
0
 def change_exteditor(self):
     """Change external editor path"""
     path, valid = QInputDialog.getText(
         self, self.tr('External editor'),
         self.tr('External editor executable path:'), QLineEdit.Normal,
         CONF.get(self.ID, 'external_editor/path'))
     if valid:
         CONF.set(self.ID, 'external_editor/path', unicode(path))
 def set_default_color_scheme(self, name='Spyder'):
     """Set default color scheme (only once)"""
     color_scheme_name = self.get_option('color_scheme_name', None)
     if color_scheme_name is None:
         names = CONF.get("color_schemes", "names")
         if name not in names:
             name = names[0]
         self.set_option('color_scheme_name', name)
Beispiel #49
0
 def set_default_color_scheme(self, name='Spyder'):
     """Set default color scheme (only once)"""
     color_scheme_name = self.get_option('color_scheme_name', None)
     if color_scheme_name is None:
         names = CONF.get("color_schemes", "names")
         if name not in names:
             name = names[0]
         self.set_option('color_scheme_name', name)
Beispiel #50
0
    def shellwidget_config(self):
        """
        Generate a Config instance for shell widgets using our config
        system
        
        This lets us create each widget with its own config (as opposed to
        IPythonQtConsoleApp, where all widgets have the same config)
        """
        # ---- IPython config ----
        try:
            profile_path = osp.join(get_ipython_dir(), 'profile_default')
            full_ip_cfg = load_pyconfig_files(['ipython_qtconsole_config.py'],
                                              profile_path)

            # From the full config we only select the IPythonWidget section
            # because the others have no effect here.
            ip_cfg = Config({'IPythonWidget': full_ip_cfg.IPythonWidget})
        except:
            ip_cfg = Config()

        # ---- Spyder config ----
        spy_cfg = Config()

        # Make the pager widget a rich one (i.e a QTextEdit)
        spy_cfg.IPythonWidget.kind = 'rich'

        # Gui completion widget
        completion_type_o = CONF.get('ipython_console', 'completion_type')
        completions = {0: "droplist", 1: "ncurses", 2: "plain"}
        spy_cfg.IPythonWidget.gui_completion = completions[completion_type_o]

        # Pager
        pager_o = self.get_option('use_pager')
        if pager_o:
            spy_cfg.IPythonWidget.paging = 'inside'
        else:
            spy_cfg.IPythonWidget.paging = 'none'

        # Calltips
        calltips_o = self.get_option('show_calltips')
        spy_cfg.IPythonWidget.enable_calltips = calltips_o

        # Buffer size
        buffer_size_o = self.get_option('buffer_size')
        spy_cfg.IPythonWidget.buffer_size = buffer_size_o

        # Prompts
        in_prompt_o = self.get_option('in_prompt')
        out_prompt_o = self.get_option('out_prompt')
        if in_prompt_o:
            spy_cfg.IPythonWidget.in_prompt = in_prompt_o
        if out_prompt_o:
            spy_cfg.IPythonWidget.out_prompt = out_prompt_o

        # Merge IPython and Spyder configs. Spyder prefs will have prevalence
        # over IPython ones
        ip_cfg._merge(spy_cfg)
        return ip_cfg
Beispiel #51
0
 def __init__(self, parent, history_filename, debug=False, profile=False):
     PythonShellWidget.__init__(self, parent, history_filename, debug,
                                profile)
     # Code completion / calltips
     getcfg = lambda option: CONF.get('external_shell', option)
     case_sensitive = getcfg('autocompletion/case-sensitivity')
     show_single = getcfg('autocompletion/select-single')
     from_document = getcfg('autocompletion/from-document')
     self.setup_code_completion(case_sensitive, show_single, from_document)
Beispiel #52
0
 def set(self, options):
     self.args = options.get('args', '')
     self.args_enabled = options.get('args/enabled', False)
     if CONF.get('run', WDIR_USE_FIXED_DIR_OPTION, False):
         default_wdir = CONF.get('run', WDIR_FIXED_DIR_OPTION, getcwd())
         self.wdir = options.get('workdir', default_wdir)
         self.wdir_enabled = True
     else:
         self.wdir = options.get('workdir', getcwd())
         self.wdir_enabled = options.get('workdir/enabled', False)
     self.current = options.get('current',
                        CONF.get('run', CURRENT_INTERPRETER_OPTION, True))
     self.systerm = options.get('systerm',
                        CONF.get('run', SYSTERM_INTERPRETER_OPTION, False))
     self.interact = options.get('interact', False)
     self.show_kill_warning = options.get('show_kill_warning', True)
     self.python_args = options.get('python_args', '')
     self.python_args_enabled = options.get('python_args/enabled', False)
Beispiel #53
0
 def _banner_default(self):
     """
     Reimplement banner creation to let the user decide if he wants a
     banner or not
     """
     banner_o = CONF.get('ipython_console', 'show_banner', True)
     if banner_o:
         return self.long_banner()
     else:
         return self.short_banner()
Beispiel #54
0
 def refresh_table(self):
     sock = self.shell.monitor_socket
     if sock is None:
         return
     settings = {}
     for name in ('filters', 'itermax', 'exclude_private', 'exclude_upper',
                  'exclude_unsupported', 'excluded_names', 'truncate',
                  'minmax', 'collvalue'):
         settings[name] = CONF.get('external_shell', name)
     self.set_data(monitor_get_remote_view(sock, settings))
Beispiel #55
0
 def get_settings():
     """
     Return Variable Explorer settings dictionary
     (i.e. namespace browser settings according to Spyder's configuration file)
     """
     settings = {}
     #        CONF.load_from_ini() # necessary only when called from another process
     for name in REMOTE_SETTINGS:
         settings[name] = CONF.get(VariableExplorer.CONF_SECTION, name)
     return settings
Beispiel #56
0
    def __init__(self,
                 parent=None,
                 namespace=None,
                 commands=[],
                 message=None,
                 max_line_count=300,
                 font=None,
                 exitfunc=None,
                 profile=False,
                 multithreaded=True,
                 light_background=True):
        PythonShellWidget.__init__(self, parent,
                                   get_conf_path('history_internal.py'),
                                   profile)

        self.set_light_background(light_background)
        self.multithreaded = multithreaded
        self.setMaximumBlockCount(max_line_count)

        # For compatibility with ExtPythonShellWidget
        self.is_ipykernel = False

        if font is not None:
            self.set_font(font)

        # Allow raw_input support:
        self.input_loop = None
        self.input_mode = False

        # KeyboardInterrupt support
        self.interrupted = False  # used only for not-multithreaded mode
        self.sig_keyboard_interrupt.connect(self.keyboard_interrupt)

        # Code completion / calltips
        getcfg = lambda option: CONF.get('internal_console', option)
        case_sensitive = getcfg('codecompletion/case_sensitive')
        self.set_codecompletion_case(case_sensitive)

        # keyboard events management
        self.eventqueue = []

        # Init interpreter
        self.exitfunc = exitfunc
        self.commands = commands
        self.message = message
        self.interpreter = None
        self.start_interpreter(namespace)

        # Clear status bar
        self.status.emit('')

        # Embedded shell -- requires the monitor (which installs the
        # 'open_in_spyder' function in builtins)
        if hasattr(builtins, 'open_in_spyder'):
            self.go_to_error.connect(self.open_with_external_spyder)
Beispiel #57
0
 def set_spyder_breakpoints(self):
     self.clear_all_breaks()
     #------Really deleting all breakpoints:
     for bp in bdb.Breakpoint.bpbynumber:
         if bp:
             bp.deleteMe()
     bdb.Breakpoint.next = 1
     bdb.Breakpoint.bplist = {}
     bdb.Breakpoint.bpbynumber = [None]
     #------
     from spyderlib.config import CONF
     CONF.load_from_ini()
     if CONF.get('run', 'breakpoints/enabled', True):
         breakpoints = CONF.get('run', 'breakpoints', {})
         i = 0
         for fname, data in list(breakpoints.items()):
             for linenumber, condition in data:
                 i += 1
                 self.set_break(self.canonic(fname), linenumber,
                                cond=condition)
Beispiel #58
0
    def show_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner

        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            backend_o = CONF.get('ipython_console', 'pylab/backend', 0)
            backends = {
                0: 'module://IPython.zmq.pylab.backend_inline',
                1: 'Qt4Agg',
                2: 'Qt4Agg',
                3: 'MacOSX',
                4: 'GTKAgg',
                5: 'WXAgg',
                6: 'TKAgg'
            }
            pylab_013_message = """
Welcome to pylab, a matplotlib-based Python environment [backend: %s].
For more information, type 'help(pylab)'.\n""" % backends[backend_o]
            pylab_1_message = """
Populating the interactive namespace from numpy and matplotlib"""
            if programs.is_module_installed('IPython', '>=1.0'):
                banner = banner + pylab_1_message
            else:
                banner = banner + pylab_013_message

        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner