Exemplo n.º 1
0
    def add_history(self, filename):
        """
        Add new history tab
        Slot for add_history signal emitted by shell instance
        """
        filename = encoding.to_unicode_from_fs(filename)
        if filename in self.filenames:
            return
        editor = codeeditor.CodeEditor(self)
        if osp.splitext(filename)[1] == '.py':
            language = 'py'
        else:
            language = 'bat'
        editor.setup_editor(linenumbers=False,
                            language=language,
                            scrollflagarea=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)
        color_scheme = self.get_color_scheme()
        editor.set_font(self.get_plugin_font(), color_scheme)
        editor.toggle_wrap_mode(self.get_option('wrap'))

        text, _ = encoding.read(filename)
        editor.set_text(text)
        editor.set_cursor_position('eof')

        self.editors.append(editor)
        self.filenames.append(filename)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setCurrentIndex(index)
Exemplo n.º 2
0
    def get_filename_text(self, filename):
        """
        Read and return content from filename.

        Parameters
        ----------
        filename: str
            The file path to read.

        Returns
        -------
        str
            Content of the filename.
        """
        # Avoid a possible error when reading the history file
        try:
            text, _ = encoding.read(filename)
        except (IOError, OSError):
            text = "# Previous history could not be read from disk, sorry\n\n"

        text = normalize_eols(text)
        linebreaks = [m.start() for m in re.finditer('\n', text)]

        if len(linebreaks) > MAX_LINES:
            text = text[linebreaks[-MAX_LINES - 1] + 1:]
            # Avoid an error when trying to write the trimmed text to disk.
            # See spyder-ide/spyder#9093.
            try:
                encoding.write(text, filename)
            except (IOError, OSError):
                pass

        return text
Exemplo n.º 3
0
    def add_history(self, filename, color_scheme, font, wrap):
        """
        Add new history tab.

        Args:
            filename (str): file to be loaded in a new tab.
        """
        filename = encoding.to_unicode_from_fs(filename)
        if filename in self.filenames:
            return
        editor = codeeditor.CodeEditor(self)
        if osp.splitext(filename)[1] == '.py':
            language = 'py'
        else:
            language = 'bat'
        editor.setup_editor(linenumbers=False,
                            language=language,
                            scrollflagarea=False,
                            show_class_func_dropdown=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)

        editor.set_font(font, color_scheme)
        editor.toggle_wrap_mode(wrap)

        text, _ = encoding.read(filename)
        editor.set_text(text)
        editor.set_cursor_position('eof')

        self.editors.append(editor)
        self.filenames.append(filename)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setCurrentIndex(index)
Exemplo n.º 4
0
    def add_history(self, filename):
        """
        Add new history tab
        Slot for add_history signal emitted by shell instance
        """
        filename = encoding.to_unicode_from_fs(filename)
        if filename in self.filenames:
            return
        editor = codeeditor.CodeEditor(self)
        if osp.splitext(filename)[1] == ".py":
            language = "py"
        else:
            language = "bat"
        editor.setup_editor(linenumbers=False, language=language, scrollflagarea=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)
        color_scheme = self.get_color_scheme()
        editor.set_font(self.get_plugin_font(), color_scheme)
        editor.toggle_wrap_mode(self.get_option("wrap"))

        text, _ = encoding.read(filename)
        editor.set_text(text)
        editor.set_cursor_position("eof")

        self.editors.append(editor)
        self.filenames.append(filename)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setCurrentIndex(index)
Exemplo n.º 5
0
    def add_history(self, filename):
        """
        Add new history tab
        Slot for add_history signal emitted by shell instance
        """
        filename = encoding.to_unicode_from_fs(filename)
        if filename in self.filenames:
            return
        editor = codeeditor.CodeEditor(self)
        if osp.splitext(filename)[1] == '.py':
            language = 'py'
        else:
            language = 'bat'
        editor.setup_editor(linenumbers=self.get_option('line_numbers'),
                            language=language,
                            scrollflagarea=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)
        color_scheme = self.get_color_scheme()
        editor.set_font(self.get_font(), color_scheme)
        editor.toggle_wrap_mode(self.get_option('wrap'))

        # Avoid a possible error when reading the history file
        try:
            text, _ = encoding.read(filename)
        except (IOError, OSError):
            text = "# Previous history could not be read from disk, sorry\n\n"
        text = normalize_eols(text)
        linebreaks = [m.start() for m in re.finditer('\n', text)]
        maxNline = self.get_option('max_entries')
        if len(linebreaks) > maxNline:
            text = text[linebreaks[-maxNline - 1] + 1:]
            # Avoid an error when trying to write the trimmed text to
            # disk.
            # See issue 9093
            try:
                encoding.write(text, filename)
            except (IOError, OSError):
                pass
        editor.set_text(text)
        editor.set_cursor_position('eof')

        self.editors.append(editor)
        self.filenames.append(filename)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setCurrentIndex(index)
Exemplo n.º 6
0
    def add_history(self, filename):
        """
        Add new history tab
        Slot for add_history signal emitted by shell instance
        """
        filename = encoding.to_unicode_from_fs(filename)
        if filename in self.filenames:
            return
        editor = codeeditor.CodeEditor(self)
        if osp.splitext(filename)[1] == '.py':
            language = 'py'
        else:
            language = 'bat'
        editor.setup_editor(linenumbers=self.get_option('line_numbers'),
                            language=language,
                            scrollflagarea=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)
        color_scheme = self.get_color_scheme()
        editor.set_font( self.get_plugin_font(), color_scheme )
        editor.toggle_wrap_mode( self.get_option('wrap') )

        # Avoid a possible error when reading the history file
        try:
            text, _ = encoding.read(filename)
        except (IOError, OSError):
            text = "# Previous history could not be read from disk, sorry\n\n"
        text = normalize_eols(text)
        linebreaks = [m.start() for m in re.finditer('\n', text)]
        maxNline = self.get_option('max_entries')
        if len(linebreaks) > maxNline:
            text = text[linebreaks[-maxNline - 1] + 1:]
            # Avoid an error when trying to write the trimmed text to
            # disk.
            # See issue 9093
            try:
                encoding.write(text, filename)
            except (IOError, OSError):
                pass
        editor.set_text(text)
        editor.set_cursor_position('eof')

        self.editors.append(editor)
        self.filenames.append(filename)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setCurrentIndex(index)
Exemplo n.º 7
0
    def load_and_translate(self,
                           sbmlfile,
                           pythonfile,
                           editor,
                           set_current=True):
        """
        Read filename as combine archive, unzip, translate, reconstitute in 
        Python, and create an editor instance and return it
        *Warning* This is loading file, creating editor but not executing
        the source code analysis -- the analysis must be done by the editor
        plugin (in case multiple editorstack instances are handled)
        """
        widgeteditor = editor.editorstacks[0]
        sbmlfile = str(sbmlfile)
        widgeteditor.starting_long_process.emit(_("Loading %s...") % sbmlfile)
        text, enc = encoding.read(sbmlfile)
        sbmlstr = te.readFromFile(sbmlfile)
        try:
            transtext = str(te.sbmlToAntimony(sbmlstr))
        except Exception as e:
            transtext = """*********************WARNING*********************
Failed to translate the SBML model to Antimony string.
Please check that the SBML file is valid.
*********************WARNING*********************"""
            transtext = transtext + "\n\n" + str(e)
        text = "import tellurium as te\n\nr = te.loada('''\n" + transtext + "''')"
        finfo = widgeteditor.create_new_editor(pythonfile,
                                               enc,
                                               text,
                                               set_current,
                                               new=True)
        index = widgeteditor.data.index(finfo)
        widgeteditor._refresh_outlineexplorer(index, update=True)
        widgeteditor.ending_long_process.emit("")
        if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \
         and sourcecode.has_mixed_eol_chars(text):
            name = os.path.basename(pythonfile)
            QMessageBox.warning(
                self, widgeteditor.title,
                _("<b>%s</b> contains mixed end-of-line "
                  "characters.<br>Spyder will fix this "
                  "automatically.") % name, QMessageBox.Ok)
            widgeteditor.set_os_eol_chars(index)
        widgeteditor.is_analysis_done = False
        finfo.editor.set_cursor_position('eof')
        finfo.editor.insert_text(os.linesep)
        return finfo, sbmlfile
Exemplo n.º 8
0
    def handle_get_file_code(self, filename, save_all=True):
        """
        Return the bytes that compose the file.

        Bytes are returned instead of str to support non utf-8 files.
        """
        editorstack = self.get_editorstack()
        if save_all and CONF.get('editor', 'save_all_before_run', True):
            editorstack.save_all(save_new_files=False)
        editor = self.get_editor(filename)

        if editor is None:
            # Load it from file instead
            text, _enc = encoding.read(filename)
            return text

        return editor.toPlainText()
Exemplo n.º 9
0
def get_file_language(filename, text=None):
    """Get file language from filename"""
    ext = osp.splitext(filename)[1]
    if ext.startswith('.'):
        ext = ext[1:]  # file extension with leading dot
    language = ext
    if not ext:
        if text is None:
            text, _enc = encoding.read(filename)
        for line in text.splitlines():
            if not line.strip():
                continue
            if line.startswith('#!'):
                shebang = line[2:]
                if 'python' in shebang:
                    language = 'python'
            else:
                break
    return language
Exemplo n.º 10
0
    def import_data(self, filenames=None):
        """Import data from text file."""
        title = _("Import data")
        if filenames is None:
            if self.filename is None:
                basedir = getcwd_or_home()
            else:
                basedir = osp.dirname(self.filename)
            filenames, _selfilter = getopenfilenames(self, title, basedir,
                                                     iofunctions.load_filters)
            if not filenames:
                return
        elif is_text_string(filenames):
            filenames = [filenames]

        for filename in filenames:
            self.filename = to_text_string(filename)
            if os.name == "nt":
                self.filename = remove_backslashes(self.filename)
            ext = osp.splitext(self.filename)[1].lower()

            if ext not in iofunctions.load_funcs:
                buttons = QMessageBox.Yes | QMessageBox.Cancel
                answer = QMessageBox.question(
                    self, title,
                    _("<b>Unsupported file extension '%s'</b><br><br>"
                      "Would you like to import it anyway "
                      "(by selecting a known file format)?") % ext, buttons)
                if answer == QMessageBox.Cancel:
                    return
                formats = list(iofunctions.load_extensions.keys())
                item, ok = QInputDialog.getItem(self, title,
                                                _('Open file as:'), formats, 0,
                                                False)
                if ok:
                    ext = iofunctions.load_extensions[to_text_string(item)]
                else:
                    return

            load_func = iofunctions.load_funcs[ext]

            # 'import_wizard' (self.setup_io)
            if is_text_string(load_func):
                # Import data with import wizard
                error_message = None
                try:
                    text, _encoding = encoding.read(self.filename)
                    base_name = osp.basename(self.filename)
                    editor = ImportWizard(
                        self,
                        text,
                        title=base_name,
                        varname=fix_reference_name(base_name))
                    if editor.exec_():
                        var_name, clip_data = editor.get_data()
                        self.editor.new_value(var_name, clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                error_message = self.shellwidget.load_data(self.filename, ext)
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()

            if error_message is not None:
                QMessageBox.critical(
                    self, title,
                    _("<b>Unable to load '%s'</b>"
                      "<br><br>"
                      "The error message was:<br>%s") %
                    (self.filename, error_message))
            self.refresh_table()
Exemplo n.º 11
0
    def import_data(self, filenames=None):
        """Import data from text file."""
        title = _("Import data")
        if filenames is None:
            if self.filename is None:
                basedir = getcwd_or_home()
            else:
                basedir = osp.dirname(self.filename)
            filenames, _selfilter = getopenfilenames(self, title, basedir,
                                                     iofunctions.load_filters)
            if not filenames:
                return
        elif is_text_string(filenames):
            filenames = [filenames]

        for filename in filenames:
            self.filename = to_text_string(filename)
            ext = osp.splitext(self.filename)[1].lower()

            if ext not in iofunctions.load_funcs:
                buttons = QMessageBox.Yes | QMessageBox.Cancel
                answer = QMessageBox.question(self, title,
                            _("<b>Unsupported file extension '%s'</b><br><br>"
                              "Would you like to import it anyway "
                              "(by selecting a known file format)?"
                              ) % ext, buttons)
                if answer == QMessageBox.Cancel:
                    return
                formats = list(iofunctions.load_extensions.keys())
                item, ok = QInputDialog.getItem(self, title,
                                                _('Open file as:'),
                                                formats, 0, False)
                if ok:
                    ext = iofunctions.load_extensions[to_text_string(item)]
                else:
                    return

            load_func = iofunctions.load_funcs[ext]
                
            # 'import_wizard' (self.setup_io)
            if is_text_string(load_func):
                # Import data with import wizard
                error_message = None
                try:
                    text, _encoding = encoding.read(self.filename)
                    base_name = osp.basename(self.filename)
                    editor = ImportWizard(self, text, title=base_name,
                                  varname=fix_reference_name(base_name))
                    if editor.exec_():
                        var_name, clip_data = editor.get_data()
                        self.editor.new_value(var_name, clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                error_message = self.shellwidget.load_data(self.filename, ext)
                self.shellwidget._kernel_reply = None
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()
    
            if error_message is not None:
                QMessageBox.critical(self, title,
                                     _("<b>Unable to load '%s'</b>"
                                       "<br><br>Error message:<br>%s"
                                       ) % (self.filename, error_message))
            self.refresh_table()
Exemplo n.º 12
0
 def load_and_translate(self,
                        inputfile,
                        pythonfile,
                        editor,
                        action,
                        set_current=True):
     """
     If the input is COMBINE archive, read filename as combine archive, 
     unzip, translate, reconstitute in Python or PhrasedML, and create an 
     editor instance and return it
     If the input is SED-ML file, read filename as SED-ML file, translate 
     it to Python, and create an editor instance and return it
     *Warning* This is loading file, creating editor but not executing
     the source code analysis -- the analysis must be done by the editor
     plugin (in case multiple editorstack instances are handled)
     """
     inputfile = str(inputfile)
     text, enc = encoding.read(inputfile)
     if action == 'c2p':
         fformat = '.py'
         text = Translatecombine2P(inputfile)
         zipextloctemp, sbmlloclisttemp, sedmlloclisttemp = manifestsearch(
             inputfile)
     elif action == 'c2pwp':
         fformat = '_phrasedml.py'
         text = Translatecombine2WP(inputfile)
         zipextloctemp, sbmlloclisttemp, sedmlloclisttemp = manifestsearch(
             inputfile)
     elif action == 's2p':
         fname = os.path.basename(inputfile)
         temp = '"End of code generated by Import SED-ML plugin ' + time.strftime(
             "%m/%d/%Y") + '"\n"Extracted from ' + fname + '"\n\n'
         text = te.sedmlToPython(inputfile) + temp
     else:
         fname = os.path.basename(inputfile)
         temp = '"End of code generated by Import SED-ML with PhrasedML plugin ' + time.strftime(
             '%m/%d/%Y') + '"\n"Extracted from ' + fname + '"'
         text = "import tellurium as te\n\nphrasedmlStr = '''" + pl.convertFile(
             inputfile
         ) + "'''\n\nte.executeSEDML(te.sedml.tephrasedml.phrasedml.convertString(phrasedmlStr))\n\n" + temp
     if action == 'c2p' or action == 'c2pwp':
         for i in range(len(text)):
             widgeteditor = editor.editorstacks[0]
             widgeteditor.starting_long_process.emit(
                 _("Loading %s...") % inputfile)
             sedmlfname = os.path.basename(sedmlloclisttemp[i])
             finfo = widgeteditor.create_new_editor(
                 os.path.splitext(sedmlfname)[0] + fformat,
                 enc,
                 text[i],
                 set_current,
                 new=True)
             index = widgeteditor.data.index(finfo)
             widgeteditor._refresh_outlineexplorer(index, update=True)
             widgeteditor.ending_long_process.emit("")
             if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \
              and sourcecode.has_mixed_eol_chars(text[i]):
                 if action == 'c2p':
                     name = os.path.basename(
                         os.path.splitext(sedmlfname)[0] + fformat)
                 else:
                     name = os.path.basename(pythonfile[:-3] + fformat)
                 QMessageBox.warning(
                     self, widgeteditor.title,
                     _("<b>%s</b> contains mixed end-of-line "
                       "characters.<br>Spyder will fix this "
                       "automatically.") % name, QMessageBox.Ok)
                 widgeteditor.set_os_eol_chars(index)
             widgeteditor.is_analysis_done = False
             finfo.editor.set_cursor_position('eof')
             finfo.editor.insert_text(os.linesep)
     else:
         widgeteditor = editor.editorstacks[0]
         widgeteditor.starting_long_process.emit(
             _("Loading %s...") % inputfile)
         finfo = widgeteditor.create_new_editor(pythonfile,
                                                enc,
                                                text,
                                                set_current,
                                                new=True)
         index = widgeteditor.data.index(finfo)
         widgeteditor._refresh_outlineexplorer(index, update=True)
         widgeteditor.ending_long_process.emit("")
         if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \
           and sourcecode.has_mixed_eol_chars(text):
             name = os.path.basename(pythonfile)
             QMessageBox.warning(
                 self, widgeteditor.title,
                 _("<b>%s</b> contains mixed end-of-line "
                   "characters.<br>Spyder will fix this "
                   "automatically.") % name, QMessageBox.Ok)
             widgeteditor.set_os_eol_chars(index)
         widgeteditor.is_analysis_done = False
         finfo.editor.set_cursor_position('eof')
         finfo.editor.insert_text(os.linesep)
     return finfo, inputfile
Exemplo n.º 13
0
    def import_data(self, filenames=None):
        """Import data from text file"""
        title = _("Import data")
        if filenames is None:
            if self.filename is None:
                basedir = getcwd()
            else:
                basedir = osp.dirname(self.filename)
            filenames, _selfilter = getopenfilenames(self, title, basedir,
                                                     iofunctions.load_filters)
            if not filenames:
                return
        elif is_text_string(filenames):
            filenames = [filenames]

        for filename in filenames:
            self.filename = to_text_string(filename)
            ext = osp.splitext(self.filename)[1].lower()

            if ext not in iofunctions.load_funcs:
                buttons = QMessageBox.Yes | QMessageBox.Cancel
                answer = QMessageBox.question(
                    self, title,
                    _("<b>Unsupported file extension '%s'</b><br><br>"
                      "Would you like to import it anyway "
                      "(by selecting a known file format)?") % ext, buttons)
                if answer == QMessageBox.Cancel:
                    return
                formats = list(iofunctions.load_extensions.keys())
                item, ok = QInputDialog.getItem(self, title,
                                                _('Open file as:'), formats, 0,
                                                False)
                if ok:
                    ext = iofunctions.load_extensions[to_text_string(item)]
                else:
                    return

            load_func = iofunctions.load_funcs[ext]

            # 'import_wizard' (self.setup_io)
            if is_text_string(load_func):
                # Import data with import wizard
                error_message = None
                try:
                    text, _encoding = encoding.read(self.filename)
                    if self.is_internal_shell:
                        self.editor.import_from_string(text)
                    else:
                        base_name = osp.basename(self.filename)
                        editor = ImportWizard(
                            self,
                            text,
                            title=base_name,
                            varname=fix_reference_name(base_name))
                        if editor.exec_():
                            var_name, clip_data = editor.get_data()
                            monitor_set_global(self._get_sock(), var_name,
                                               clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                if self.is_internal_shell:
                    namespace, error_message = load_func(self.filename)
                    interpreter = self.shellwidget.interpreter
                    for key in list(namespace.keys()):
                        new_key = fix_reference_name(
                            key, blacklist=list(interpreter.namespace.keys()))
                        if new_key != key:
                            namespace[new_key] = namespace.pop(key)
                    if error_message is None:
                        interpreter.namespace.update(namespace)
                else:
                    error_message = monitor_load_globals(
                        self._get_sock(), self.filename, ext)
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()

            if error_message is not None:
                QMessageBox.critical(
                    self, title,
                    _("<b>Unable to load '%s'</b>"
                      "<br><br>Error message:<br>%s") %
                    (self.filename, error_message))
            self.refresh_table()