Esempio n. 1
0
 def save_data(self, filename=None):
     """Save data"""
     if filename is None:
         filename = self.filename
         if filename is None:
             filename = getcwd()
         filename, _selfilter = getsavefilename(self, _("Save data"),
                                                filename,
                                                iofunctions.save_filters)
         if filename:
             self.filename = filename
         else:
             return False
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents()
     if self.is_internal_shell:
         wsfilter = self.get_internal_shell_filter('picklable',
                                                   check_all=True)
         namespace = wsfilter(self.shellwidget.interpreter.namespace).copy()
         error_message = iofunctions.save(namespace, filename)
     else:
         settings = self.get_view_settings()
         error_message = monitor_save_globals(self._get_sock(),
                                              settings, filename)
     QApplication.restoreOverrideCursor()
     QApplication.processEvents()
     if error_message is not None:
         QMessageBox.critical(self, _("Save data"),
                         _("<b>Unable to save current workspace</b>"
                           "<br><br>Error message:<br>%s") % error_message)
     self.save_button.setEnabled(self.filename is not None)
Esempio n. 2
0
 def compare(self):
     filename, _selfilter = getopenfilename(self, _("Select script to compare"),
                                            getcwd(), _("Profiler result")+" (*.Result)")
     if filename:
         self.datatree.compare(filename)
         self.show_data()
         self.clear_button.setEnabled(True)
Esempio n. 3
0
    def open_project(self, path=None, restart_consoles=True,
                     save_previous_files=True):
        """Open the project located in `path`"""
        if path is None:
            basedir = get_home_dir()
            path = getexistingdirectory(parent=self,
                                        caption=_("Open project"),
                                        basedir=basedir)
            if not self.is_valid_project(path):
                if path:
                    QMessageBox.critical(self, _('Error'),
                                _("<b>%s</b> is not a Spyder project!") % path)
                return
            else:
                self.add_to_recent(path)

        # A project was not open before
        if self.current_active_project is None:
            if save_previous_files:
                self.editor.save_open_files()
            self.editor.set_option('last_working_dir', getcwd())
            self.show_explorer()
        else: # we are switching projects
            self.set_project_filenames(self.editor.get_open_filenames())

        self.current_active_project = EmptyProject(path)
        self.latest_project = EmptyProject(path)
        self.set_option('current_project_path', self.get_active_project_path())
        self.setup_menu_actions()
        self.sig_project_loaded.emit(path)
        self.pythonpath_changed.emit()
        if restart_consoles:
            self.restart_consoles()
 def select_file(self):
     self.redirect_stdio.emit(False)
     filename = getexistingdirectory(
         self, _("Select directory"), getcwd())
     self.redirect_stdio.emit(False)
     if filename:
         self.analyze(filename)
Esempio n. 5
0
    def save_data(self, filename=None):
        """Save data"""
        if filename is None:
            filename = self.filename
            if filename is None:
                filename = getcwd()
            filename, _selfilter = getsavefilename(self, _("Save data"),
                                                   filename,
                                                   iofunctions.save_filters)
            if filename:
                self.filename = filename
            else:
                return False
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()

        error_message = self.shellwidget.save_namespace(self.filename)
        self.shellwidget._kernel_reply = None

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        if error_message is not None:
            QMessageBox.critical(self, _("Save data"),
                            _("<b>Unable to save current workspace</b>"
                              "<br><br>Error message:<br>%s") % error_message)
        self.save_button.setEnabled(self.filename is not None)
Esempio n. 6
0
 def select_file(self):
     self.redirect_stdio.emit(False)
     filename, _selfilter = getopenfilename(self, _("Select Python file"),
                        getcwd(), _("Python files")+" (*.py ; *.pyw)")
     self.redirect_stdio.emit(True)
     if filename:
         self.analyze(filename)
Esempio n. 7
0
 def open_interpreter(self, wdir=None):
     """Open interpreter"""
     if not wdir:
         wdir = getcwd()
     self.visibility_changed(True)
     self.start(fname=None, wdir=to_text_string(wdir), args='',
                interact=True, debug=False, python=True)
Esempio n. 8
0
 def save_data(self):
     """Save data"""
     title = _( "Save profiler result")
     filename, _selfilter = getsavefilename(self, title,
                                            getcwd(),
                                            _("Profiler result")+" (*.Result)")
     if filename:
         self.datatree.save_data(filename)
Esempio n. 9
0
 def select_directory(self):
     """Select directory"""
     self.redirect_stdio.emit(False)
     directory = getexistingdirectory(self.main, _("Select directory"),
                                      getcwd())
     if directory:
         self.chdir(directory)
     self.redirect_stdio.emit(True)
Esempio n. 10
0
 def run_script(self):
     """Run a Python script"""
     self.redirect_stdio.emit(False)
     filename, _selfilter = getopenfilename(self, _("Run Python script"),
             getcwd(), _("Python scripts")+" (*.py ; *.pyw ; *.ipy)")
     self.redirect_stdio.emit(True)
     if filename:
         self.start(fname=filename, wdir=None, args='',
                    interact=False, debug=False)
Esempio n. 11
0
 def refresh_plugin(self):
     """Refresh widget"""
     curdir = getcwd()
     self.pathedit.add_text(curdir)
     self.save_wdhistory()
     self.set_previous_enabled.emit(
                          self.histindex is not None and self.histindex > 0)
     self.set_next_enabled.emit(self.histindex is not None and \
                                self.histindex < len(self.history)-1)
Esempio n. 12
0
 def select_directory(self):
     """Display dialog for user to select working directory."""
     basedir = to_text_string(self.wdir_lineedit.text())
     if not osp.isdir(basedir):
         basedir = getcwd()
     title = _("Select directory")
     directory = getexistingdirectory(self, title, basedir)
     if directory:
         self.wdir_lineedit.setText(directory)
Esempio n. 13
0
 def select_directory(self):
     """Select directory"""
     basedir = to_text_string(self.wd_edit.text())
     if not osp.isdir(basedir):
         basedir = getcwd()
     directory = getexistingdirectory(self, _("Select directory"), basedir)
     if directory:
         self.wd_edit.setText(directory)
         self.wd_cb.setChecked(True)
Esempio n. 14
0
def getcwd_or_home():
    """Safe version of getcwd that will fallback to home user dir.

    This will catch the error raised when the current working directory
    was removed for an external program.
    """
    try:
        return getcwd()
    except OSError:
        logger.debug("WARNING: Current working directory was deleted, "
                     "falling back to home dirertory")
        return get_home_dir()
Esempio n. 15
0
 def refresh(self, new_path=None, force_current=False):
     """Refresh widget
     force=False: won't refresh widget if path has not changed"""
     if new_path is None:
         new_path = getcwd()
     if force_current:
         index = self.set_current_folder(new_path)
         self.expand(index)
         self.setCurrentIndex(index)
     self.set_previous_enabled.emit(
                          self.histindex is not None and self.histindex > 0)
     self.set_next_enabled.emit(self.histindex is not None and \
                                self.histindex < len(self.history)-1)
Esempio n. 16
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',
                        CONF.get('run', 'interact', False))
     self.show_kill_warning = options.get('show_kill_warning', 
                        CONF.get('run', 'show_kill_warning', False))
     self.post_mortem = options.get('post_mortem',
                        CONF.get('run', 'post_mortem', False))
     self.python_args = options.get('python_args', '')
     self.python_args_enabled = options.get('python_args/enabled', False)
    def update_default_wdir(self):
        """
        Update default working dir for running unit tests.

        The default working dir for running unit tests is set to the project
        directory if a project is open, or the current working directory if no
        project is opened. This function is called whenever this directory may
        change.
        """
        wdir = self.main.projects.get_active_project_path()
        if not wdir:  # if no project opened
            wdir = getcwd()
        self.unittestwidget.default_wdir = wdir
Esempio n. 18
0
    def setup_page(self):
        about_label = QLabel(_("The <b>current working directory</b> is "
                    "the working directory for IPython consoles "
                    "and the current directory for the File Explorer."))
        about_label.setWordWrap(True)

        console_group = QGroupBox(_("Console directory"))
        console_label = QLabel(_("The working directory for new consoles is:"))
        console_label.setWordWrap(True)
        console_bg = QButtonGroup(console_group)
        console_project_radio = self.create_radiobutton(
                                _("The current project directory "
                                  "or user home directory "
                                  "(if no project is active)"),
                                'console/use_project_or_home_directory',
                                True,
                                button_group=console_bg)
        console_cwd_radio = self.create_radiobutton(
                                _("The current working directory"),
                                'console/use_cwd',
                                False,
                                button_group=console_bg)

        console_dir_radio = self.create_radiobutton(
                                _("the following directory:"),
                                'console/use_fixed_directory', False,
                                _("The directory when a new console "
                                  "is open will be the specified path"),
                                button_group=console_bg)
        console_dir_bd = self.create_browsedir("", 'console/fixed_directory',
                                               getcwd())
        console_dir_radio.toggled.connect(console_dir_bd.setEnabled)
        console_project_radio.toggled.connect(console_dir_bd.setDisabled)
        console_cwd_radio.toggled.connect(console_dir_bd.setDisabled)
        console_dir_layout = QHBoxLayout()
        console_dir_layout.addWidget(console_dir_radio)
        console_dir_layout.addWidget(console_dir_bd)

        console_layout = QVBoxLayout()
        console_layout.addWidget(console_label)
        console_layout.addWidget(console_project_radio)
        console_layout.addWidget(console_cwd_radio)
        console_layout.addLayout(console_dir_layout)
        console_group.setLayout(console_layout)

        vlayout = QVBoxLayout()
        vlayout.addWidget(about_label)
        vlayout.addSpacing(10)
        vlayout.addWidget(console_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Esempio n. 19
0
    def __init__(self, parent=None, pathlist=None, ro_pathlist=None,
                 not_active_pathlist=None, sync=True):
        QDialog.__init__(self, parent)
        
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)
        
        assert isinstance(pathlist, list)
        self.pathlist = pathlist
        if not_active_pathlist is None:
            not_active_pathlist = []
        self.not_active_pathlist = not_active_pathlist
        if ro_pathlist is None:
            ro_pathlist = []
        self.ro_pathlist = ro_pathlist
        
        self.last_path = getcwd()
        
        self.setWindowTitle(_("PYTHONPATH manager"))
        self.setWindowIcon(ima.icon('pythonpath'))
        self.resize(500, 300)
        
        self.selection_widgets = []
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        top_layout = QHBoxLayout()
        layout.addLayout(top_layout)
        self.toolbar_widgets1 = self.setup_top_toolbar(top_layout)

        self.listwidget = QListWidget(self)
        self.listwidget.currentRowChanged.connect(self.refresh)
        self.listwidget.itemChanged.connect(self.update_not_active_pathlist)
        layout.addWidget(self.listwidget)

        bottom_layout = QHBoxLayout()
        layout.addLayout(bottom_layout)
        self.sync_button = None
        self.toolbar_widgets2 = self.setup_bottom_toolbar(bottom_layout, sync)        
        
        # Buttons configuration
        bbox = QDialogButtonBox(QDialogButtonBox.Close)
        bbox.rejected.connect(self.reject)
        bottom_layout.addWidget(bbox)
        
        self.update_list()
        self.refresh()
Esempio n. 20
0
def save_dictionary(data, filename):
    """Save dictionary in a single file .spydata file"""
    filename = osp.abspath(filename)
    old_cwd = getcwd()
    os.chdir(osp.dirname(filename))
    error_message = None
    try:
        saved_arrays = {}
        if load_array is not None:
            # Saving numpy arrays with np.save
            arr_fname = osp.splitext(filename)[0]
            for name in list(data.keys()):
                if isinstance(data[name], np.ndarray) and data[name].size > 0:
                    # Saving arrays at data root
                    fname = __save_array(data[name], arr_fname,
                                       len(saved_arrays))
                    saved_arrays[(name, None)] = osp.basename(fname)
                    data.pop(name)
                elif isinstance(data[name], (list, dict)):
                    # Saving arrays nested in lists or dictionaries
                    if isinstance(data[name], list):
                        iterator = enumerate(data[name])
                    else:
                        iterator = iter(list(data[name].items()))
                    to_remove = []
                    for index, value in iterator:
                        if isinstance(value, np.ndarray) and value.size > 0:
                            fname = __save_array(value, arr_fname,
                                               len(saved_arrays))
                            saved_arrays[(name, index)] = osp.basename(fname)
                            to_remove.append(index)
                    for index in sorted(to_remove, reverse=True):
                        data[name].pop(index)
            if saved_arrays:
                data['__saved_arrays__'] = saved_arrays
        pickle_filename = osp.splitext(filename)[0]+'.pickle'
        with open(pickle_filename, 'wb') as fdesc:
            pickle.dump(data, fdesc, 2)
        tar = tarfile.open(filename, "w")
        for fname in [pickle_filename]+[fn for fn in list(saved_arrays.values())]:
            tar.add(osp.basename(fname))
            os.remove(fname)
        tar.close()
        if saved_arrays:
            data.pop('__saved_arrays__')
    except (RuntimeError, pickle.PicklingError, TypeError) as error:
        error_message = to_text_string(error)
    os.chdir(old_cwd)
    return error_message
Esempio n. 21
0
def guess_filename(filename):
    """Guess filename"""
    if osp.isfile(filename):
        return filename
    if not filename.endswith('.py'):
        filename += '.py'
    for path in [getcwd()] + sys.path:
        fname = osp.join(path, filename)
        if osp.isfile(fname):
            return fname
        elif osp.isfile(fname+'.py'):
            return fname+'.py'
        elif osp.isfile(fname+'.pyw'):
            return fname+'.pyw'
    return filename
Esempio n. 22
0
def load_dictionary(filename):
    """Load dictionary from .spydata file"""
    filename = osp.abspath(filename)
    old_cwd = getcwd()
    tmp_folder = tempfile.mkdtemp()
    os.chdir(tmp_folder)
    data = None
    error_message = None
    try:
        tar = tarfile.open(filename, "r")
        tar.extractall()
        data_file = osp.basename(filename)
        pickle_filename = osp.splitext(data_file)[0]+'.pickle'
        try:
            # Old format (Spyder 2.0-2.1 for Python 2)
            with open(pickle_filename, 'U') as fdesc:
                data = pickle.loads(fdesc.read())
        except (pickle.PickleError, TypeError, UnicodeDecodeError):
            # New format (Spyder >=2.2 for Python 2 and Python 3)
            with open(pickle_filename, 'rb') as fdesc:
                data = pickle.loads(fdesc.read())
        saved_arrays = {}
        if load_array is not None:
            # Loading numpy arrays saved with np.save
            try:
                saved_arrays = data.pop('__saved_arrays__')
                for (name, index), fname in list(saved_arrays.items()):
                    arr = np.load( osp.join(tmp_folder, fname) )
                    if index is None:
                        data[name] = arr
                    elif isinstance(data[name], dict):
                        data[name][index] = arr
                    else:
                        data[name].insert(index, arr)
            except KeyError:
                pass
    except (EOFError, ValueError) as error:
        error_message = to_text_string(error)
    os.chdir(old_cwd)
    try:
        shutil.rmtree(tmp_folder)
    except OSError as error:
        error_message = to_text_string(error)
    return data, error_message
Esempio n. 23
0
    def __init__(self, parent, server_args_fmt='',
                 server_settings={}, external_server=False,
                 folder=getcwd(), language='python',
                 plugin_configurations={}):
        QObject.__init__(self)
        # LSPMethodProviderMixIn.__init__(self)
        self.manager = parent
        self.zmq_in_socket = None
        self.zmq_out_socket = None
        self.zmq_in_port = None
        self.zmq_out_port = None
        self.transport_client = None
        self.language = language

        self.initialized = False
        self.ready_to_close = False
        self.request_seq = 1
        self.req_status = {}
        self.plugin_registry = {}
        self.watched_files = {}
        self.req_reply = {}

        self.transport_args = [sys.executable, '-u',
                               osp.join(LOCATION, 'transport', 'main.py')]
        self.external_server = external_server

        self.folder = folder
        self.plugin_configurations = plugin_configurations
        self.client_capabilites = CLIENT_CAPABILITES
        self.server_capabilites = SERVER_CAPABILITES
        self.context = zmq.Context()

        server_args = server_args_fmt % (server_settings)
        # transport_args = self.local_server_fmt % (server_settings)
        # if self.external_server:
        transport_args = self.external_server_fmt % (server_settings)

        self.server_args = [server_settings['cmd']]
        self.server_args += server_args.split(' ')
        self.transport_args += transport_args.split(' ')
        self.transport_args += ['--folder', folder]
        self.transport_args += ['--transport-debug', str(get_debug_level())]
Esempio n. 24
0
 def run_script(self, filename=None, silent=False, set_focus=False, args=None):
     """Run a Python script"""
     if filename is None:
         self.shell.interpreter.restore_stds()
         filename, _selfilter = getopenfilename(
             self, _("Run Python script"), getcwd(), _("Python scripts") + " (*.py ; *.pyw ; *.ipy)"
         )
         self.shell.interpreter.redirect_stds()
         if filename:
             os.chdir(osp.dirname(filename))
             filename = osp.basename(filename)
         else:
             return
     debug_print(args)
     filename = osp.abspath(filename)
     rbs = remove_backslashes
     command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args))
     if set_focus:
         self.shell.setFocus()
     if self.dockwidget and not self.ismaximized:
         self.dockwidget.setVisible(True)
         self.dockwidget.raise_()
     self.shell.write(command + "\n")
     self.shell.run_command(command)
Esempio n. 25
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)
                    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()
Esempio n. 26
0
    def setup_page(self):
        run_dlg = _("Run Settings")
        run_menu = _("Run")
        about_label = QLabel(_("The following are the default <i>%s</i>. "\
                               "These options may be overriden using the "\
                               "<b>%s</b> dialog box (see the <b>%s</b> menu)"\
                               ) % (run_dlg, run_dlg, run_menu))
        about_label.setWordWrap(True)

        interpreter_group = QGroupBox(_("Console"))
        interpreter_bg = QButtonGroup(interpreter_group)
        self.current_radio = self.create_radiobutton(
            CURRENT_INTERPRETER,
            CURRENT_INTERPRETER_OPTION,
            True,
            button_group=interpreter_bg)
        self.dedicated_radio = self.create_radiobutton(
            DEDICATED_INTERPRETER,
            DEDICATED_INTERPRETER_OPTION,
            False,
            button_group=interpreter_bg)
        self.systerm_radio = self.create_radiobutton(
            SYSTERM_INTERPRETER,
            SYSTERM_INTERPRETER_OPTION,
            False,
            button_group=interpreter_bg)

        interpreter_layout = QVBoxLayout()
        interpreter_group.setLayout(interpreter_layout)
        interpreter_layout.addWidget(self.current_radio)
        interpreter_layout.addWidget(self.dedicated_radio)
        interpreter_layout.addWidget(self.systerm_radio)

        general_group = QGroupBox(_("General settings"))
        wdir_bg = QButtonGroup(general_group)
        wdir_label = QLabel(_("Default working directory is:"))
        wdir_label.setWordWrap(True)
        dirname_radio = self.create_radiobutton(_("the script directory"),
                                                WDIR_USE_SCRIPT_DIR_OPTION,
                                                True,
                                                button_group=wdir_bg)
        thisdir_radio = self.create_radiobutton(_("the following directory:"),
                                                WDIR_USE_FIXED_DIR_OPTION,
                                                False,
                                                button_group=wdir_bg)
        thisdir_bd = self.create_browsedir("", WDIR_FIXED_DIR_OPTION, getcwd())
        thisdir_radio.toggled.connect(thisdir_bd.setEnabled)
        dirname_radio.toggled.connect(thisdir_bd.setDisabled)
        thisdir_layout = QHBoxLayout()
        thisdir_layout.addWidget(thisdir_radio)
        thisdir_layout.addWidget(thisdir_bd)

        post_mortem = self.create_checkbox(
            _("Enter debugging mode when errors appear during execution"),
            'post_mortem', False)

        general_layout = QVBoxLayout()
        general_layout.addWidget(wdir_label)
        general_layout.addWidget(dirname_radio)
        general_layout.addLayout(thisdir_layout)
        general_layout.addWidget(post_mortem)
        general_group.setLayout(general_layout)

        dedicated_group = QGroupBox(_("Dedicated Python console"))
        interact_after = self.create_checkbox(
            _("Interact with the Python console after execution"), 'interact',
            False)
        show_warning = self.create_checkbox(
            _("Show warning when killing running processes"),
            'show_kill_warning', True)

        dedicated_layout = QVBoxLayout()
        dedicated_layout.addWidget(interact_after)
        dedicated_layout.addWidget(show_warning)
        dedicated_group.setLayout(dedicated_layout)

        firstrun_cb = self.create_checkbox(
            ALWAYS_OPEN_FIRST_RUN % _("Run Settings dialog"),
            ALWAYS_OPEN_FIRST_RUN_OPTION, False)

        vlayout = QVBoxLayout()
        vlayout.addWidget(about_label)
        vlayout.addSpacing(10)
        vlayout.addWidget(interpreter_group)
        vlayout.addWidget(general_group)
        vlayout.addWidget(dedicated_group)
        vlayout.addWidget(firstrun_cb)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Esempio n. 27
0
        Returns
        -------
        Config
            Test configuration
        """
        framework = self.framework_combobox.currentText()
        if framework == '':
            framework = None
        return Config(framework=framework, wdir=self.wdir_lineedit.text())


def ask_for_config(frameworks, config, parent=None):
    """
    Ask user to specify a test configuration.

    This is a convenience function which displays a modal dialog window
    of type `ConfigDialog`.
    """
    dialog = ConfigDialog(frameworks, config, parent)
    result = dialog.exec_()
    if result == QDialog.Accepted:
        return dialog.get_config()


if __name__ == '__main__':
    app = QApplication([])
    frameworks = ['nose', 'pytest', 'unittest']
    config = Config(framework=None, wdir=getcwd())
    print(ask_for_config(frameworks, config))
Esempio n. 28
0
    def __init__(self,
                 host='127.0.0.1',
                 port=2087,
                 workspace=getcwd(),
                 use_external_server=False,
                 zmq_in_port=7000,
                 zmq_out_port=7001,
                 server='pyls',
                 server_args=['--tcp']):
        self.req_status = {}
        self.host = host
        self.port = port
        self.workspace = workspace
        # self.request_seq = 1

        self.server = None
        self.is_local_server_running = not use_external_server
        if not use_external_server:
            logger.info('Starting server: {0} {1} on {2}:{3}'.format(
                server, ' '.join(server_args), self.host, self.port))
            exec_line = [sys.executable, '-m', server] + server_args
            logger.info(' '.join(exec_line))

            self.server = subprocess.Popen(exec_line,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE)

        logger.info('Connecting to language server at {0}:{1}'.format(
            self.host, self.port))

        connected = False
        initial_time = time.time()
        connection_error = None
        while not connected:
            try:
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.connect((self.host, int(self.port)))
                connected = True
            except Exception as e:
                connection_error = e

            if time.time() - initial_time > self.MAX_TIMEOUT_TIME:
                break

        if not connected:
            logger.error("The client was unable to establish a connection "
                         "with the Language Server. The error was: "
                         "{}".format(connection_error))
            raise Exception("An error occurred while trying to create a "
                            "client to connect to the Language Server! The "
                            "error was\n\n{}".format(connection_error))

        self.socket.setblocking(True)

        logger.info('Starting ZMQ connection...')
        self.context = zmq.Context()
        self.zmq_in_socket = self.context.socket(zmq.PAIR)
        self.zmq_in_socket.connect("tcp://localhost:{0}".format(zmq_in_port))
        self.zmq_out_socket = self.context.socket(zmq.PAIR)
        self.zmq_out_socket.connect("tcp://localhost:{0}".format(zmq_out_port))
        logger.info('Sending server_ready...')
        self.zmq_out_socket.send_pyobj({
            'id': -1,
            'method': 'server_ready',
            'params': {}
        })

        logger.info('Creating consumer Thread...')
        self.reading_thread = IncomingMessageThread()
        self.reading_thread.initialize(self.socket, self.zmq_out_socket,
                                       self.req_status)
Esempio n. 29
0
    def __init__(self,
                 host='127.0.0.1',
                 port=2087,
                 workspace=getcwd(),
                 use_external_server=False,
                 zmq_in_port=7000,
                 zmq_out_port=7001,
                 server='pyls',
                 server_args=['--tcp']):
        self.req_status = {}
        self.host = host
        self.port = port
        self.workspace = workspace
        # self.request_seq = 1

        self.server = None
        self.is_local_server_running = not use_external_server
        if not use_external_server:
            LOGGER.info('Starting server: {0} {1} on {2}:{3}'.format(
                server, ' '.join(server_args), self.host, self.port))
            exec_line = [server] + server_args
            LOGGER.info(' '.join(exec_line))

            self.server = subprocess.Popen(exec_line,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE)

        LOGGER.info('Connecting to language server at {0}:{1}'.format(
            self.host, self.port))
        connected = False

        initial_time = time.time()
        while not connected:
            LOGGER.info('Attempting LSP server connection {0}:{1}'.format(
                self.host, self.port))
            try:
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.connect((self.host, int(self.port)))
                connected = True
            except Exception as e:
                LOGGER.info('Connection error: {}'.format(e))

            if time.time() - initial_time > self.MAX_TIMEOUT_TIME:
                break

        if not connected:
            LOGGER.error("The client was unable to establish a connection "
                         "with the language server, terminating process...")
            raise Exception('Error!')

        self.socket.setblocking(True)

        # LOGGER.info('Initializing server connection...')
        # self.__initialize()

        LOGGER.info('Starting ZMQ connection...')
        self.context = zmq.Context()
        self.zmq_in_socket = self.context.socket(zmq.PAIR)
        self.zmq_in_socket.connect("tcp://localhost:{0}".format(zmq_in_port))
        self.zmq_out_socket = self.context.socket(zmq.PAIR)
        self.zmq_out_socket.connect("tcp://localhost:{0}".format(zmq_out_port))
        LOGGER.info('Sending server_ready...')
        self.zmq_out_socket.send_pyobj({
            'id': -1,
            'method': 'server_ready',
            'params': {}
        })

        LOGGER.info('Creating consumer Thread...')
        self.reading_thread = IncomingMessageThread()
        self.reading_thread.initialize(self.socket, self.zmq_out_socket,
                                       self.req_status)
Esempio n. 30
0
 def set_as_current_console_wd(self):
     """Set as current console working directory"""
     self.set_current_console_wd.emit(getcwd())
Esempio n. 31
0
        Returns
        -------
        Config
            Test configuration
        """
        framework = self.framework_combobox.currentText()
        if framework == '':
            framework = None
        return Config(framework=framework, wdir=self.wdir_lineedit.text())


def ask_for_config(frameworks, config, parent=None):
    """
    Ask user to specify a test configuration.

    This is a convenience function which displays a modal dialog window
    of type `ConfigDialog`.
    """
    dialog = ConfigDialog(frameworks, config, parent)
    result = dialog.exec_()
    if result == QDialog.Accepted:
        return dialog.get_config()


if __name__ == '__main__':
    app = QApplication([])
    frameworks = ['nose', 'pytest', 'unittest']
    config = Config(framework=None, wdir=getcwd())
    print(ask_for_config(frameworks, config))
Esempio n. 32
0
 def refreshdir(self):
     """Refresh search directory"""
     self.findinfiles.find_options.set_directory(getcwd())
Esempio n. 33
0
 def getcwd(self):
     """Return current working directory"""
     return getcwd()
Esempio n. 34
0
    def setup_page(self):
        about_label = QLabel(
            _("The <b>current working directory</b> is "
              "the working directory for IPython consoles "
              "and the current directory for the File Explorer."))
        about_label.setWordWrap(True)

        startup_group = QGroupBox(_("Startup"))
        startup_bg = QButtonGroup(startup_group)
        startup_label = QLabel(
            _("At startup, the current working "
              "directory is:"))
        startup_label.setWordWrap(True)
        lastdir_radio = self.create_radiobutton(
            _("The current project directory "
              "or user home directory "
              "(if no project is active)"),
            'startup/use_project_or_home_directory',
            True,
            _("At startup,"),  # TODO
            button_group=startup_bg)
        thisdir_radio = self.create_radiobutton(
            _("the following directory:"),
            'startup/use_fixed_directory',
            False,
            _("At startup, the current working "
              "directory will be the specified path"),
            button_group=startup_bg)
        thisdir_bd = self.create_browsedir("", 'startup/fixed_directory',
                                           getcwd())
        thisdir_radio.toggled.connect(thisdir_bd.setEnabled)
        lastdir_radio.toggled.connect(thisdir_bd.setDisabled)
        thisdir_layout = QHBoxLayout()
        thisdir_layout.addWidget(thisdir_radio)
        thisdir_layout.addWidget(thisdir_bd)

        startup_layout = QVBoxLayout()
        startup_layout.addWidget(startup_label)
        startup_layout.addWidget(lastdir_radio)
        startup_layout.addLayout(thisdir_layout)
        startup_group.setLayout(startup_layout)

        # Console Directory

        console_group = QGroupBox(_("Console directory"))
        console_label = QLabel(_("The working directory for new consoles is:"))
        console_label.setWordWrap(True)
        console_bg = QButtonGroup(console_group)
        console_project_radio = self.create_radiobutton(
            _("The current project directory "
              "or user home directory "
              "(if no project is active)"),
            'console/use_project_or_home_directory',
            True,
            button_group=console_bg)
        console_cwd_radio = self.create_radiobutton(
            _("The current working directory"),
            'console/use_cwd',
            False,
            button_group=console_bg)

        console_dir_radio = self.create_radiobutton(
            _("the following directory:"),
            'console/use_fixed_directory',
            False,
            _("The directory when a new console "
              "is open will be the specified path"),
            button_group=console_bg)
        console_dir_bd = self.create_browsedir("", 'console/fixed_directory',
                                               getcwd())
        console_dir_radio.toggled.connect(console_dir_bd.setEnabled)
        console_project_radio.toggled.connect(console_dir_bd.setDisabled)
        console_cwd_radio.toggled.connect(console_dir_bd.setDisabled)
        console_dir_layout = QHBoxLayout()
        console_dir_layout.addWidget(console_dir_radio)
        console_dir_layout.addWidget(console_dir_bd)

        console_layout = QVBoxLayout()
        console_layout.addWidget(console_label)
        console_layout.addWidget(console_project_radio)
        console_layout.addWidget(console_cwd_radio)
        console_layout.addLayout(console_dir_layout)
        console_group.setLayout(console_layout)

        vlayout = QVBoxLayout()
        vlayout.addWidget(about_label)
        vlayout.addSpacing(10)
        vlayout.addWidget(startup_group)
        vlayout.addWidget(console_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Esempio n. 35
0
    def setup_page(self):
        about_label = QLabel(_("The following are the default options for "
                               "running files.These options may be overriden "
                               "using the <b>Configuration per file</b> entry "
                               "of the <b>Run</b> menu."))
        about_label.setWordWrap(True)

        interpreter_group = QGroupBox(_("Console"))
        interpreter_bg = QButtonGroup(interpreter_group)
        self.current_radio = self.create_radiobutton(CURRENT_INTERPRETER,
                                CURRENT_INTERPRETER_OPTION, True,
                                button_group=interpreter_bg)
        self.dedicated_radio = self.create_radiobutton(DEDICATED_INTERPRETER,
                                DEDICATED_INTERPRETER_OPTION, False,
                                button_group=interpreter_bg)
        self.systerm_radio = self.create_radiobutton(SYSTERM_INTERPRETER,
                                SYSTERM_INTERPRETER_OPTION, False,
                                button_group=interpreter_bg)

        interpreter_layout = QVBoxLayout()
        interpreter_group.setLayout(interpreter_layout)
        interpreter_layout.addWidget(self.current_radio)
        interpreter_layout.addWidget(self.dedicated_radio)
        interpreter_layout.addWidget(self.systerm_radio)
        
        general_group = QGroupBox(_("General settings"))
        post_mortem = self.create_checkbox(POST_MORTEM, 'post_mortem', False)
        clear_variables = self.create_checkbox(CLEAR_ALL_VARIABLES, 
            'clear_namespace', False)

        general_layout = QVBoxLayout()
        general_layout.addWidget(clear_variables)
        general_layout.addWidget(post_mortem)
        general_group.setLayout(general_layout)

        wdir_group = QGroupBox(_("Working Directory settings"))
        wdir_bg = QButtonGroup(wdir_group)
        wdir_label = QLabel(_("Default working directory is:"))
        wdir_label.setWordWrap(True)
        dirname_radio = self.create_radiobutton(
                    FILE_DIR,
                    WDIR_USE_SCRIPT_DIR_OPTION, True,
                    button_group=wdir_bg)
        cwd_radio = self.create_radiobutton(
                    CW_DIR,
                    WDIR_USE_CWD_DIR_OPTION, False,
                    button_group=wdir_bg)

        thisdir_radio = self.create_radiobutton(
                FIXED_DIR,
                WDIR_USE_FIXED_DIR_OPTION, False,
                button_group=wdir_bg)
        thisdir_bd = self.create_browsedir("", WDIR_FIXED_DIR_OPTION, getcwd())
        thisdir_radio.toggled.connect(thisdir_bd.setEnabled)
        dirname_radio.toggled.connect(thisdir_bd.setDisabled)
        cwd_radio.toggled.connect(thisdir_bd.setDisabled)
        thisdir_layout = QHBoxLayout()
        thisdir_layout.addWidget(thisdir_radio)
        thisdir_layout.addWidget(thisdir_bd)

        wdir_layout = QVBoxLayout()
        wdir_layout.addWidget(wdir_label)
        wdir_layout.addWidget(dirname_radio)
        wdir_layout.addWidget(cwd_radio)
        wdir_layout.addLayout(thisdir_layout)
        wdir_group.setLayout(wdir_layout)


        external_group = QGroupBox(_("External system terminal"))
        interact_after = self.create_checkbox(INTERACT, 'interact', False)

        external_layout = QVBoxLayout()
        external_layout.addWidget(interact_after)
        external_group.setLayout(external_layout)

        firstrun_cb = self.create_checkbox(
                            ALWAYS_OPEN_FIRST_RUN % _("Run Settings dialog"),
                            ALWAYS_OPEN_FIRST_RUN_OPTION, False)
        
        vlayout = QVBoxLayout()
        vlayout.addWidget(about_label)
        vlayout.addSpacing(10)
        vlayout.addWidget(interpreter_group)
        vlayout.addWidget(general_group)
        vlayout.addWidget(wdir_group)
        vlayout.addWidget(external_group)
        vlayout.addWidget(firstrun_cb)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Esempio n. 36
0
 def get_last_working_dir(self):
     """Get the path of the last working directory"""
     return self.editor.get_option('last_working_dir', default=getcwd())
Esempio n. 37
0
 def open_terminal(self, wdir=None):
     """Open terminal"""
     if not wdir:
         wdir = getcwd()
     self.start(fname=None, wdir=to_text_string(wdir), args='',
                interact=True, debug=False, python=False)
Esempio n. 38
0
    def __init__(self, parent, search_text, search_text_regexp, search_path,
                 exclude, exclude_idx, exclude_regexp,
                 supported_encodings, in_python_path, more_options):
        QWidget.__init__(self, parent)

        if search_path is None:
            search_path = getcwd()

        self.path = ''
        self.project_path = None
        self.file_path = None

        if not isinstance(search_text, (list, tuple)):
            search_text = [search_text]
        if not isinstance(search_path, (list, tuple)):
            search_path = [search_path]
        if not isinstance(exclude, (list, tuple)):
            exclude = [exclude]

        self.supported_encodings = supported_encodings

        # Layout 1
        hlayout1 = QHBoxLayout()
        self.search_text = PatternComboBox(self, search_text,
                                           _("Search pattern"))
        self.edit_regexp = create_toolbutton(self,
                                             icon=ima.icon('advanced'),
                                             tip=_('Regular expression'))
        self.edit_regexp.setCheckable(True)
        self.edit_regexp.setChecked(search_text_regexp)
        self.more_widgets = ()
        self.more_options = create_toolbutton(self,
                                              toggled=self.toggle_more_options)
        self.more_options.setCheckable(True)
        self.more_options.setChecked(more_options)

        self.ok_button = create_toolbutton(self, text=_("Search"),
                                           icon=ima.icon('find'),
                                           triggered=lambda: self.find.emit(),
                                           tip=_("Start search"),
                                           text_beside_icon=True)
        self.ok_button.clicked.connect(self.update_combos)
        self.stop_button = create_toolbutton(self, text=_("Stop"),
                                             icon=ima.icon('editclear'),
                                             triggered=lambda:
                                             self.stop.emit(),
                                             tip=_("Stop search"),
                                             text_beside_icon=True)
        self.stop_button.setEnabled(False)
        for widget in [self.search_text, self.edit_regexp,
                       self.ok_button, self.stop_button, self.more_options]:
            hlayout1.addWidget(widget)

        # Layout 2
        hlayout2 = QHBoxLayout()
        self.exclude_pattern = PatternComboBox(self, exclude,
                                               _("Excluded filenames pattern"))
        if exclude_idx is not None and exclude_idx >= 0 \
           and exclude_idx < self.exclude_pattern.count():
            self.exclude_pattern.setCurrentIndex(exclude_idx)
        self.exclude_regexp = create_toolbutton(self,
                                                icon=ima.icon('advanced'),
                                                tip=_('Regular expression'))
        self.exclude_regexp.setCheckable(True)
        self.exclude_regexp.setChecked(exclude_regexp)
        exclude_label = QLabel(_("Exclude:"))
        exclude_label.setBuddy(self.exclude_pattern)
        for widget in [exclude_label, self.exclude_pattern,
                       self.exclude_regexp]:
            hlayout2.addWidget(widget)

        # Layout 3
        hlayout3 = QHBoxLayout()

        self.global_path_search = QRadioButton(_("Current working "
                                                 "directory"), self)
        self.global_path_search.setChecked(True)
        self.global_path_search.setToolTip(_("Search in all files and "
                                             "directories present on the"
                                             "current Spyder path"))

        self.project_search = QRadioButton(_("Project"), self)
        self.project_search.setToolTip(_("Search in all files and "
                                         "directories present on the"
                                         "current project path (If opened)"))

        self.project_search.setEnabled(False)

        self.file_search = QRadioButton(_("File"), self)
        self.file_search.setToolTip(_("Search in current opened file"))

        for wid in [self.global_path_search,
                    self.project_search, self.file_search]:
            hlayout3.addWidget(wid)

        hlayout3.addStretch(1)

        self.search_text.valid.connect(lambda valid: self.find.emit())
        self.exclude_pattern.valid.connect(lambda valid: self.find.emit())

        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        self.more_widgets = (hlayout2,)
        self.toggle_more_options(more_options)
        self.setLayout(vlayout)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
Esempio n. 39
0
    def run_opensbml(self,
                     filenames=None,
                     goto=None,
                     word='',
                     editorwindow=None,
                     processevents=True):
        """Prompt the user to load a SBML file, translate to antimony, and 
        display in a new window"""
        editorwindow = None  #Used in editor.load
        processevents = True  #Used in editor.load
        editor = self.main.editor
        basedir = getcwd()
        if CONF.get('workingdir', 'editor/open/browse_scriptdir'):
            c_fname = editor.get_current_filename()
            if c_fname is not None and c_fname != editor.TEMPFILE_PATH:
                basedir = os.path.dirname(c_fname)
        editor.redirect_stdio.emit(False)
        parent_widget = editor.get_current_editorstack()
        selectedfilter = ''
        filters = 'SBML files (*.sbml *.xml);;All files (*.*)'
        filenames, _selfilter = getopenfilenames(parent_widget,
                                                 _("Open SBML file"),
                                                 basedir,
                                                 filters,
                                                 selectedfilter=selectedfilter)
        editor.redirect_stdio.emit(True)
        if filenames:
            filenames = [os.path.normpath(fname) for fname in filenames]
            if CONF.get('workingdir', 'editor/open/auto_set_to_basedir'):
                directory = os.path.dirname(filenames[0])
                editor.emit(Signal("open_dir(QString)"), directory)
        else:
            #The file dialog box was closed without selecting a file.
            return
        focus_widget = QApplication.focusWidget()
        if editor.dockwidget and not editor.ismaximized and\
           (not editor.dockwidget.isAncestorOf(focus_widget)\
            and not isinstance(focus_widget, CodeEditor)):
            editor.dockwidget.setVisible(True)
            editor.dockwidget.setFocus()
            editor.dockwidget.raise_()

        def _convert(fname):
            fname = os.path.abspath(encoding.to_unicode_from_fs(fname))
            if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':':
                fname = fname[0].upper() + fname[1:]
            return fname

        if hasattr(filenames, 'replaceInStrings'):
            # This is a QStringList instance (PyQt API #1), converting to list:
            filenames = list(filenames)
        if not isinstance(filenames, list):
            filenames = [_convert(filenames)]
        else:
            filenames = [_convert(fname) for fname in list(filenames)]

        for index, filename in enumerate(filenames):
            p = re.compile('(.xml$|.sbml$)')
            pythonfile = p.sub('_antimony.py', filename)
            if (pythonfile == filename):
                pythonfile = filename + "_antimony.py"
            current_editor = editor.set_current_filename(
                pythonfile, editorwindow)
            if current_editor is not None:
                # -- TODO:  Do not open an already opened file
                pass
            else:
                # -- Not an existing opened file:
                if not os.path.isfile(filename):
                    continue
                # --
                current_es = editor.get_current_editorstack(editorwindow)

                # Creating the editor widget in the first editorstack (the one
                # that can't be destroyed), then cloning this editor widget in
                # all other editorstacks:
                finfo, newname = self.load_and_translate(
                    filename, pythonfile, editor)
                finfo.path = editor.main.get_spyder_pythonpath()
                editor._clone_file_everywhere(finfo)
                current_editor = current_es.set_current_filename(newname)
                #if (current_editor is not None):
                #    editor.register_widget_shortcuts("Editor", current_editor)

                current_es.analyze_script()

            if (current_editor is not None):
                current_editor.clearFocus()
                current_editor.setFocus()
                current_editor.window().raise_()
            if processevents:
                QApplication.processEvents()
Esempio n. 40
0
                    default=7000,
                    help="ZMQ (in) port to be contacted")
parser.add_argument('--zmq-out-port',
                    default=7001,
                    help="ZMQ (out) port to be contacted")
parser.add_argument('--server-host',
                    default='127.0.0.1',
                    help='Host that serves the ls-server')
parser.add_argument('--server-port',
                    default=2087,
                    help="Deployment port of the ls-server")
parser.add_argument('--server-log-file',
                    default=None,
                    help="Log file to register ls-server activity")
parser.add_argument('--folder',
                    default=getcwd(),
                    help="Initial current working directory used to "
                         "initialize ls-server")
parser.add_argument('--external-server',
                    action="store_true",
                    help="Do not start a local server")
parser.add_argument('--stdio-server',
                    action="store_true",
                    help='Server communication should use stdio pipes')
parser.add_argument('--transport-debug',
                    default=0,
                    type=int,
                    help='Verbosity level for log messages')
args, extra_args = parser.parse_known_args()

Esempio n. 41
0
    def __init__(self, parent):
        """Widget constructor."""
        SpyderPluginWidget.__init__(self, parent)
        self.tab_widget = None
        self.menu_actions = None
        self.server_retries = 0
        self.server_ready = False
        self.port = select_port(default_port=8071)

        self.cmd = find_program(self.get_option('shell'))
        self.CONF = CONF
        self.server_stdout = subprocess.PIPE
        self.server_stderr = subprocess.PIPE
        self.stdout_file = osp.join(getcwd(), 'spyder_terminal_out.log')
        self.stderr_file = osp.join(getcwd(), 'spyder_terminal_err.log')
        if DEV:
            self.server_stdout = open(self.stdout_file, 'w')
            self.server_stderr = open(self.stderr_file, 'w')
        self.server = subprocess.Popen([
            sys.executable, '-m', 'spyder_terminal.server', '--port',
            str(self.port), '--shell', self.cmd
        ],
                                       stdout=self.server_stdout,
                                       stderr=self.server_stderr)

        self.main = parent

        self.terms = []
        self.untitled_num = 0

        self.project_path = None
        self.current_file_path = None
        self.current_cwd = getcwd()

        try:
            # Spyder 3
            self.initialize_plugin()
        except AttributeError:
            # Spyder 4
            pass

        layout = QVBoxLayout()
        new_term_btn = create_toolbutton(self,
                                         icon=ima.icon('expand_selection'),
                                         tip=_('Open a new terminal'),
                                         triggered=self.create_new_term)

        corner_widgets = {
            Qt.TopRightCorner: [new_term_btn, self.options_button]
        }
        self.tabwidget = Tabs(self,
                              menu=self._options_menu,
                              actions=self.menu_actions,
                              corner_widgets=corner_widgets,
                              rename_tabs=True)

        if hasattr(self.tabwidget, 'setDocumentMode') \
           and not sys.platform == 'darwin':
            # Don't set document mode to true on OSX because it generates
            # a crash when the console is detached from the main window
            # Fixes Issue 561
            self.tabwidget.setDocumentMode(True)
        self.tabwidget.currentChanged.connect(self.refresh_plugin)
        self.tabwidget.move_data.connect(self.move_tab)

        self.tabwidget.set_close_function(self.close_term)

        layout.addWidget(self.tabwidget)
        self.setLayout(layout)

        new_term_shortcut = QShortcut(
            CONF.get_shortcut(CONF_SECTION, 'new_term'), self,
            self.create_new_term)
        new_term_shortcut.setContext(Qt.WidgetWithChildrenShortcut)

        self.color_scheme = CONF.get('appearance', 'ui_theme')
        self.theme = CONF.get('appearance', 'selected')

        self.__wait_server_to_start()
Esempio n. 42
0
 def create_new_term(self, name=None, give_focus=True, path=getcwd()):
     """Add a new terminal tab."""
     font = self.get_plugin_font()
     term = TerminalWidget(self, self.port, path=path, font=font.family())
     self.add_tab(term)
Esempio n. 43
0
    def __init__(self, parent, search_text, search_text_regexp, search_path,
                 exclude, exclude_idx, exclude_regexp,
                 supported_encodings, in_python_path, more_options,
                 case_sensitive, external_path_history):
        QWidget.__init__(self, parent)

        if search_path is None:
            search_path = getcwd()

        self.path = ''
        self.project_path = None
        self.file_path = None
        self.external_path = None
        self.external_path_history = external_path_history

        if not isinstance(search_text, (list, tuple)):
            search_text = [search_text]
        if not isinstance(search_path, (list, tuple)):
            search_path = [search_path]
        if not isinstance(exclude, (list, tuple)):
            exclude = [exclude]
        if not isinstance(external_path_history, (list, tuple)):
            external_path_history = [external_path_history]

        self.supported_encodings = supported_encodings

        # Layout 1
        hlayout1 = QHBoxLayout()
        self.search_text = PatternComboBox(self, search_text,
                                           _("Search pattern"))
        self.edit_regexp = create_toolbutton(self,
                                             icon=ima.icon('advanced'),
                                             tip=_('Regular expression'))
        self.case_button = create_toolbutton(self,
                                             icon=get_icon("upper_lower.png"),
                                             tip=_("Case Sensitive"))
        self.case_button.setCheckable(True)
        self.case_button.setChecked(case_sensitive)
        self.edit_regexp.setCheckable(True)
        self.edit_regexp.setChecked(search_text_regexp)
        self.more_widgets = ()
        self.more_options = create_toolbutton(self,
                                              toggled=self.toggle_more_options)
        self.more_options.setCheckable(True)
        self.more_options.setChecked(more_options)

        self.ok_button = create_toolbutton(self, text=_("Search"),
                                           icon=ima.icon('find'),
                                           triggered=lambda: self.find.emit(),
                                           tip=_("Start search"),
                                           text_beside_icon=True)
        self.ok_button.clicked.connect(self.update_combos)
        self.stop_button = create_toolbutton(self, text=_("Stop"),
                                             icon=ima.icon('editclear'),
                                             triggered=lambda:
                                             self.stop.emit(),
                                             tip=_("Stop search"),
                                             text_beside_icon=True)
        self.stop_button.setEnabled(False)
        for widget in [self.search_text, self.edit_regexp, self.case_button,
                       self.ok_button, self.stop_button, self.more_options]:
            hlayout1.addWidget(widget)

        # Layout 2
        hlayout2 = QHBoxLayout()
        self.exclude_pattern = PatternComboBox(self, exclude,
                                               _("Excluded filenames pattern"))
        if exclude_idx is not None and exclude_idx >= 0 \
           and exclude_idx < self.exclude_pattern.count():
            self.exclude_pattern.setCurrentIndex(exclude_idx)
        self.exclude_regexp = create_toolbutton(self,
                                                icon=ima.icon('advanced'),
                                                tip=_('Regular expression'))
        self.exclude_regexp.setCheckable(True)
        self.exclude_regexp.setChecked(exclude_regexp)
        exclude_label = QLabel(_("Exclude:"))
        exclude_label.setBuddy(self.exclude_pattern)
        for widget in [exclude_label, self.exclude_pattern,
                       self.exclude_regexp]:
            hlayout2.addWidget(widget)

        # Layout 3
        hlayout3 = QHBoxLayout()

        search_on_label = QLabel(_("Search in:"))
        self.path_selection_combo = PatternComboBox(self, exclude,
                                                    _('Search directory'))
        self.path_selection_combo.setEditable(False)
        self.path_selection_contents = QListWidget(self.path_selection_combo)
        self.path_selection_contents.hide()
        self.path_selection_combo.setModel(
            self.path_selection_contents.model())

        self.path_selection_contents.addItem(_("Current working directory"))
        item = self.path_selection_contents.item(0)
        item.setToolTip(_("Search in all files and "
                          "directories present on the"
                          "current Spyder path"))

        self.path_selection_contents.addItem(_("Project"))
        item = self.path_selection_contents.item(1)
        item.setToolTip(_("Search in all files and "
                          "directories present on the"
                          "current project path "
                          "(If opened)"))
        item.setFlags(item.flags() & ~Qt.ItemIsEnabled)

        self.path_selection_contents.addItem(_("File").replace('&', ''))
        item = self.path_selection_contents.item(2)
        item.setToolTip(_("Search in current opened file"))

        self.path_selection_contents.addItem(_("Select other directory"))
        item = self.path_selection_contents.item(3)
        item.setToolTip(_("Search in other folder present on the file system"))

        self.path_selection_combo.insertSeparator(3)
        self.path_selection_combo.insertSeparator(5)
        for path in external_path_history:
            item = ExternalPathItem(None, path)
            self.path_selection_contents.addItem(item)

        self.path_selection_combo.currentIndexChanged.connect(
            self.path_selection_changed)

        hlayout3.addWidget(search_on_label)
        hlayout3.addWidget(self.path_selection_combo)

        self.search_text.valid.connect(lambda valid: self.find.emit())
        self.exclude_pattern.valid.connect(lambda valid: self.find.emit())

        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        self.more_widgets = (hlayout2,)
        self.toggle_more_options(more_options)
        self.setLayout(vlayout)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
Esempio n. 44
0
 def parent_directory(self):
     """Change working directory to parent directory"""
     self.chdir(os.path.join(getcwd(), os.path.pardir))
Esempio n. 45
0
 def go_to_parent_directory(self):
     """Go to parent directory"""
     self.chdir(osp.abspath(osp.join(getcwd(), os.pardir)))
Esempio n. 46
0
    def setup_page(self):
        about_label = QLabel(_("The <b>global working directory</b> is "
                    "the working directory for newly opened <i>consoles</i> "
                    "(Python/IPython consoles and terminals), for the "
                    "<i>file explorer</i>, for the <i>find in files</i> "
                    "plugin and for new files created in the <i>editor</i>."))
        about_label.setWordWrap(True)
        
        startup_group = QGroupBox(_("Startup"))
        startup_bg = QButtonGroup(startup_group)
        startup_label = QLabel(_("At startup, the global working "
                                       "directory is:"))
        startup_label.setWordWrap(True)
        lastdir_radio = self.create_radiobutton(
                                _("the same as in last session"),
                                'startup/use_last_directory', True,
                                _("At startup, Spyder will restore the "
                                        "global directory from last session"),
                                button_group=startup_bg)
        thisdir_radio = self.create_radiobutton(
                                _("the following directory:"),
                                'startup/use_fixed_directory', False,
                                _("At startup, the global working "
                                        "directory will be the specified path"),
                                button_group=startup_bg)
        thisdir_bd = self.create_browsedir("", 'startup/fixed_directory',
                                           getcwd())
        thisdir_radio.toggled.connect(thisdir_bd.setEnabled)
        lastdir_radio.toggled.connect(thisdir_bd.setDisabled)
        thisdir_layout = QHBoxLayout()
        thisdir_layout.addWidget(thisdir_radio)
        thisdir_layout.addWidget(thisdir_bd)

        editor_o_group = QGroupBox(_("Open file"))
        editor_o_label = QLabel(_("Files are opened from:"))
        editor_o_label.setWordWrap(True)
        editor_o_bg = QButtonGroup(editor_o_group)
        editor_o_radio1 = self.create_radiobutton(
                                _("the current file directory"),
                                'editor/open/browse_scriptdir',
                                button_group=editor_o_bg)
        editor_o_radio2 = self.create_radiobutton(
                                _("the global working directory"),
                                'editor/open/browse_workdir', 
                                button_group=editor_o_bg)
        
        editor_n_group = QGroupBox(_("New file"))
        editor_n_label = QLabel(_("Files are created in:"))
        editor_n_label.setWordWrap(True)
        editor_n_bg = QButtonGroup(editor_n_group)
        editor_n_radio1 = self.create_radiobutton(
                                _("the current file directory"),
                                'editor/new/browse_scriptdir',
                                button_group=editor_n_bg)
        editor_n_radio2 = self.create_radiobutton(
                                _("the global working directory"),
                                'editor/new/browse_workdir',
                                button_group=editor_n_bg)
        # Note: default values for the options above are set in plugin's
        #       constructor (see below)
        
        other_group = QGroupBox(_("Change to file base directory"))
        newcb = self.create_checkbox
        open_box = newcb(_("When opening a file"),
                         'editor/open/auto_set_to_basedir')
        save_box = newcb(_("When saving a file"),
                         'editor/save/auto_set_to_basedir')
        
        startup_layout = QVBoxLayout()
        startup_layout.addWidget(startup_label)
        startup_layout.addWidget(lastdir_radio)
        startup_layout.addLayout(thisdir_layout)
        startup_group.setLayout(startup_layout)

        editor_o_layout = QVBoxLayout()
        editor_o_layout.addWidget(editor_o_label)
        editor_o_layout.addWidget(editor_o_radio1)
        editor_o_layout.addWidget(editor_o_radio2)
        editor_o_group.setLayout(editor_o_layout)

        editor_n_layout = QVBoxLayout()
        editor_n_layout.addWidget(editor_n_label)
        editor_n_layout.addWidget(editor_n_radio1)
        editor_n_layout.addWidget(editor_n_radio2)
        editor_n_group.setLayout(editor_n_layout)
        
        other_layout = QVBoxLayout()
        other_layout.addWidget(open_box)
        other_layout.addWidget(save_box)
        other_group.setLayout(other_layout)
        
        vlayout = QVBoxLayout()
        vlayout.addWidget(about_label)
        vlayout.addSpacing(10)
        vlayout.addWidget(startup_group)
        vlayout.addWidget(editor_o_group)
        vlayout.addWidget(editor_n_group)
        vlayout.addWidget(other_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Esempio n. 47
0
 def set_as_current_console_wd(self):
     """Set as current console working directory"""
     self.set_current_console_wd.emit(getcwd())
Esempio n. 48
0
 def get_cdlistdir(self):
     """Return shell current directory list dir"""
     return os.listdir(getcwd())
Esempio n. 49
0
    def run_Import(self, action):
        """Prompt user to load a COMBINE archive or SED-ML file and translates it"""
        if action == 'c2p' or action == 'c2pwp' or action == 's2p' or action == 's2pwp':
            editorwindow = None  #Used in editor.load
            processevents = True  #Used in editor.load
            goto = None
            word = ''

            editor = self.main.editor
            editor0 = editor.get_current_editor()
            if editor0 is not None:
                position0 = editor0.get_position('cursor')
                filename0 = editor.get_current_filename()
            else:
                position0, filename0 = None, None
            # Recent files action
            raction = editor.sender()
            if isinstance(raction, QAction):
                filenames = from_qvariant(raction.data(), to_text_string)
            if not filenames:
                basedir = getcwd()
                if editor.edit_filetypes is None:
                    editor.edit_filetypes = get_edit_filetypes()
                if editor.edit_filters is None:
                    editor.edit_filters = get_edit_filters()

                c_fname = editor.get_current_filename()
                if c_fname is not None and c_fname != editor.TEMPFILE_PATH:
                    basedir = os.path.dirname(c_fname)
                editor.redirect_stdio.emit(False)
                parent_widget = editor.get_current_editorstack()
                if filename0 is not None:
                    selectedfilter = get_filter(editor.edit_filetypes,
                                                os.path.splitext(filename0)[1])
                else:
                    selectedfilter = ''
                if action == 'c2p' or action == 'c2pwp':
                    filters = 'Combine archives (*.zip *.omex);;All files (*.*)'
                    filenames, _selfilter = getopenfilenames(
                        parent_widget,
                        _("Open combine archive"),
                        basedir,
                        filters,
                        selectedfilter=selectedfilter)
                else:
                    filters = 'SED-ML files (*.sedml *.xml);;All files (*.*)'
                    filenames, _selfilter = getopenfilenames(
                        parent_widget,
                        _("Open SED-ML file"),
                        basedir,
                        filters,
                        selectedfilter=selectedfilter)
                editor.redirect_stdio.emit(True)
                if filenames:
                    filenames = [
                        os.path.normpath(fname) for fname in filenames
                    ]
                else:
                    return

            focus_widget = QApplication.focusWidget()
            if editor.dockwidget and\
               (not editor.dockwidget.isAncestorOf(focus_widget)\
                and not isinstance(focus_widget, CodeEditor)):
                editor.dockwidget.setVisible(True)
                editor.dockwidget.setFocus()
                editor.dockwidget.raise_()

            def _convert(fname):
                fname = os.path.abspath(encoding.to_unicode_from_fs(fname))
                if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':':
                    fname = fname[0].upper() + fname[1:]
                return fname

            if hasattr(filenames, 'replaceInStrings'):
                # This is a QStringList instance (PyQt API #1), converting to list:
                filenames = list(filenames)
            if not isinstance(filenames, list):
                filenames = [_convert(filenames)]
            else:
                filenames = [_convert(fname) for fname in list(filenames)]

            if isinstance(goto, int):
                goto = [goto]
            elif goto is not None and len(goto) != len(filenames):
                goto = None

            for index, filename in enumerate(filenames):
                if action == 'c2p' or action == 'c2pwp':
                    p = re.compile('(.zip$|.omex$)')
                    pythonfile = p.sub('.py', filename)
                    if (pythonfile == filename):
                        pythonfile = filename + ".py"
                else:
                    p = re.compile('(.xml$|.sedml$)')
                    if action == 's2p':
                        pythonfile = p.sub('_sedml.py', filename)
                        if (pythonfile == filename):
                            pythonfile = filename + "_sedml.py"
                    else:
                        pythonfile = p.sub('_phrasedml.py', filename)
                        if (pythonfile == filename):
                            pythonfile = filename + "_phrasedml.py"
                current_editor = editor.set_current_filename(
                    pythonfile, editorwindow)
                if current_editor is None:
                    # -- Not a valid filename:
                    if not os.path.isfile(filename):
                        continue
                    # --
                    current_es = editor.get_current_editorstack(editorwindow)

                    # Creating the editor widget in the first editorstack (the one
                    # that can't be destroyed), then cloning this editor widget in
                    # all other editorstacks:
                    finfo, newname = self.load_and_translate(
                        filename, pythonfile, editor, action)
                    finfo.path = editor.main.get_spyder_pythonpath()
                    editor._clone_file_everywhere(finfo)
                    current_editor = current_es.set_current_filename(newname)

                    current_es.analyze_script()
                if goto is not None:  # 'word' is assumed to be None as well
                    current_editor.go_to_line(goto[index], word=word)
                    position = current_editor.get_position('cursor')
                    editor.cursor_moved(filename0, position0, filename,
                                        position)
                if (current_editor is not None):
                    current_editor.clearFocus()
                    current_editor.setFocus()
                    current_editor.window().raise_()
                if processevents:
                    QApplication.processEvents()
Esempio n. 50
0
    def __init__(self, parent, search_text, search_text_regexp, search_path,
                 exclude, exclude_idx, exclude_regexp, supported_encodings,
                 in_python_path, more_options, case_sensitive,
                 external_path_history):
        QWidget.__init__(self, parent)

        if search_path is None:
            search_path = getcwd()

        self.path = ''
        self.project_path = None
        self.file_path = None
        self.external_path = None
        self.external_path_history = external_path_history

        if not isinstance(search_text, (list, tuple)):
            search_text = [search_text]
        if not isinstance(search_path, (list, tuple)):
            search_path = [search_path]
        if not isinstance(exclude, (list, tuple)):
            exclude = [exclude]
        if not isinstance(external_path_history, (list, tuple)):
            external_path_history = [external_path_history]

        self.supported_encodings = supported_encodings

        # Layout 1
        hlayout1 = QHBoxLayout()
        self.search_text = PatternComboBox(self, search_text,
                                           _("Search pattern"))
        self.edit_regexp = create_toolbutton(self,
                                             icon=ima.icon('advanced'),
                                             tip=_('Regular expression'))
        self.case_button = create_toolbutton(self,
                                             icon=get_icon("upper_lower.png"),
                                             tip=_("Case Sensitive"))
        self.case_button.setCheckable(True)
        self.case_button.setChecked(case_sensitive)
        self.edit_regexp.setCheckable(True)
        self.edit_regexp.setChecked(search_text_regexp)
        self.more_widgets = ()
        self.more_options = create_toolbutton(self,
                                              toggled=self.toggle_more_options)
        self.more_options.setCheckable(True)
        self.more_options.setChecked(more_options)

        self.ok_button = create_toolbutton(self,
                                           text=_("Search"),
                                           icon=ima.icon('find'),
                                           triggered=lambda: self.find.emit(),
                                           tip=_("Start search"),
                                           text_beside_icon=True)
        self.ok_button.clicked.connect(self.update_combos)
        self.stop_button = create_toolbutton(
            self,
            text=_("Stop"),
            icon=ima.icon('editclear'),
            triggered=lambda: self.stop.emit(),
            tip=_("Stop search"),
            text_beside_icon=True)
        self.stop_button.setEnabled(False)
        for widget in [
                self.search_text, self.edit_regexp, self.case_button,
                self.ok_button, self.stop_button, self.more_options
        ]:
            hlayout1.addWidget(widget)

        # Layout 2
        hlayout2 = QHBoxLayout()
        self.exclude_pattern = PatternComboBox(self, exclude,
                                               _("Excluded filenames pattern"))
        if exclude_idx is not None and exclude_idx >= 0 \
           and exclude_idx < self.exclude_pattern.count():
            self.exclude_pattern.setCurrentIndex(exclude_idx)
        self.exclude_regexp = create_toolbutton(self,
                                                icon=ima.icon('advanced'),
                                                tip=_('Regular expression'))
        self.exclude_regexp.setCheckable(True)
        self.exclude_regexp.setChecked(exclude_regexp)
        exclude_label = QLabel(_("Exclude:"))
        exclude_label.setBuddy(self.exclude_pattern)
        for widget in [
                exclude_label, self.exclude_pattern, self.exclude_regexp
        ]:
            hlayout2.addWidget(widget)

        # Layout 3
        hlayout3 = QHBoxLayout()

        search_on_label = QLabel(_("Search in:"))
        self.path_selection_combo = PatternComboBox(self, exclude,
                                                    _('Search directory'))
        self.path_selection_combo.setEditable(False)
        self.path_selection_contents = QListWidget(self.path_selection_combo)
        self.path_selection_contents.hide()
        self.path_selection_combo.setModel(
            self.path_selection_contents.model())

        self.path_selection_contents.addItem(_("Current working directory"))
        item = self.path_selection_contents.item(0)
        item.setToolTip(
            _("Search in all files and "
              "directories present on the"
              "current Spyder path"))

        self.path_selection_contents.addItem(_("Project"))
        item = self.path_selection_contents.item(1)
        item.setToolTip(
            _("Search in all files and "
              "directories present on the"
              "current project path "
              "(If opened)"))
        item.setFlags(item.flags() & ~Qt.ItemIsEnabled)

        self.path_selection_contents.addItem(_("File").replace('&', ''))
        item = self.path_selection_contents.item(2)
        item.setToolTip(_("Search in current opened file"))

        self.path_selection_contents.addItem(_("Select other directory"))
        item = self.path_selection_contents.item(3)
        item.setToolTip(_("Search in other folder present on the file system"))

        self.path_selection_combo.insertSeparator(3)
        self.path_selection_combo.insertSeparator(5)
        for path in external_path_history:
            item = ExternalPathItem(None, path)
            self.path_selection_contents.addItem(item)

        self.path_selection_combo.currentIndexChanged.connect(
            self.path_selection_changed)

        hlayout3.addWidget(search_on_label)
        hlayout3.addWidget(self.path_selection_combo)

        self.search_text.valid.connect(lambda valid: self.find.emit())
        self.exclude_pattern.valid.connect(lambda valid: self.find.emit())

        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        self.more_widgets = (hlayout2, )
        self.toggle_more_options(more_options)
        self.setLayout(vlayout)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
Esempio n. 51
0
    def __init__(self, parent):
        """Widget constructor."""
        SpyderPluginWidget.__init__(self, parent)
        self.tab_widget = None
        self.menu_actions = None
        self.server_retries = 0
        self.server_ready = False
        self.port = select_port(default_port=8071)

        self.cmd = 'bash'
        if WINDOWS:
            self.cmd = 'cmd'

        self.server_stdout = subprocess.PIPE
        self.server_stderr = subprocess.PIPE
        self.stdout_file = osp.join(getcwd(), 'spyder_terminal_out.log')
        self.stderr_file = osp.join(getcwd(), 'spyder_terminal_err.log')
        if DEV:
            self.server_stdout = open(self.stdout_file, 'w')
            self.server_stderr = open(self.stderr_file, 'w')

        self.server = subprocess.Popen([
            sys.executable, '-m', 'spyder_terminal.server', '--port',
            str(self.port), '--shell', self.cmd
        ],
                                       stdout=self.server_stdout,
                                       stderr=self.server_stderr)

        self.main = parent

        self.terms = []
        self.untitled_num = 0

        self.project_path = None
        self.current_file_path = None
        self.current_cwd = getcwd()
        self.options_menu = QMenu(self)

        self.initialize_plugin()

        layout = QVBoxLayout()
        new_term_btn = create_toolbutton(self,
                                         icon=ima.icon('project_expanded'),
                                         tip=_('Open a new terminal'),
                                         triggered=self.create_new_term)
        menu_btn = create_toolbutton(self,
                                     icon=ima.icon('tooloptions'),
                                     tip=_('Options'))
        menu_btn.setMenu(self.options_menu)
        menu_btn.setPopupMode(menu_btn.InstantPopup)
        add_actions(self.options_menu, self.menu_actions)
        # if self.get_option('first_time', True):
        # self.setup_shortcuts()
        # self.shortcuts = self.create_shortcuts()
        corner_widgets = {Qt.TopRightCorner: [new_term_btn, menu_btn]}
        self.tabwidget = Tabs(self,
                              menu=self.options_menu,
                              actions=self.menu_actions,
                              corner_widgets=corner_widgets,
                              rename_tabs=True)

        if hasattr(self.tabwidget, 'setDocumentMode') \
           and not sys.platform == 'darwin':
            # Don't set document mode to true on OSX because it generates
            # a crash when the console is detached from the main window
            # Fixes Issue 561
            self.tabwidget.setDocumentMode(True)
        self.tabwidget.currentChanged.connect(self.refresh_plugin)
        self.tabwidget.move_data.connect(self.move_tab)

        self.tabwidget.set_close_function(self.close_term)

        layout.addWidget(self.tabwidget)
        self.setLayout(layout)

        new_term_shortcut = QShortcut(QKeySequence("Ctrl+Alt+Shift+T"), self,
                                      self.create_new_term)
        new_term_shortcut.setContext(Qt.WidgetWithChildrenShortcut)

        self.__wait_server_to_start()
Esempio n. 52
0
 def refreshdir(self):
     """Refresh search directory"""
     self.findinfiles.find_options.set_directory(getcwd())
Esempio n. 53
0
 def parent_directory(self):
     """Change working directory to parent directory"""
     self.chdir(os.path.join(getcwd(), os.path.pardir))
Esempio n. 54
0
    def __init__(self, parent, search_text, search_text_regexp, search_path,
                 include, include_idx, include_regexp,
                 exclude, exclude_idx, exclude_regexp,
                 supported_encodings, in_python_path, more_options):
        QWidget.__init__(self, parent)
        
        if search_path is None:
            search_path = getcwd()
        
        if not isinstance(search_text, (list, tuple)):
            search_text = [search_text]
        if not isinstance(search_path, (list, tuple)):
            search_path = [search_path]
        if not isinstance(include, (list, tuple)):
            include = [include]
        if not isinstance(exclude, (list, tuple)):
            exclude = [exclude]

        self.supported_encodings = supported_encodings

        # Layout 1
        hlayout1 = QHBoxLayout()
        self.search_text = PatternComboBox(self, search_text,
                                           _("Search pattern"))
        self.edit_regexp = create_toolbutton(self,
                                             icon=ima.icon('advanced'),
                                             tip=_('Regular expression'))
        self.edit_regexp.setCheckable(True)
        self.edit_regexp.setChecked(search_text_regexp)
        self.more_widgets = ()
        self.more_options = create_toolbutton(self,
                                              toggled=self.toggle_more_options)
        self.more_options.setCheckable(True)
        self.more_options.setChecked(more_options)
        
        self.ok_button = create_toolbutton(self, text=_("Search"),
                                icon=ima.icon('DialogApplyButton'),
                                triggered=lambda: self.find.emit(),
                                tip=_("Start search"),
                                text_beside_icon=True)
        self.ok_button.clicked.connect(self.update_combos)
        self.stop_button = create_toolbutton(self, text=_("Stop"),
                                icon=ima.icon('stop'),
                                triggered=lambda: self.stop.emit(),
                                tip=_("Stop search"),
                                text_beside_icon=True)
        self.stop_button.setEnabled(False)
        for widget in [self.search_text, self.edit_regexp,
                       self.ok_button, self.stop_button, self.more_options]:
            hlayout1.addWidget(widget)

        # Layout 2
        hlayout2 = QHBoxLayout()
        self.include_pattern = PatternComboBox(self, include,
                                               _("Included filenames pattern"))
        if include_idx is not None and include_idx >= 0 \
           and include_idx < self.include_pattern.count():
            self.include_pattern.setCurrentIndex(include_idx)
        self.include_regexp = create_toolbutton(self,
                                            icon=ima.icon('advanced'),
                                            tip=_('Regular expression'))
        self.include_regexp.setCheckable(True)
        self.include_regexp.setChecked(include_regexp)
        include_label = QLabel(_("Include:"))
        include_label.setBuddy(self.include_pattern)
        self.exclude_pattern = PatternComboBox(self, exclude,
                                               _("Excluded filenames pattern"))
        if exclude_idx is not None and exclude_idx >= 0 \
           and exclude_idx < self.exclude_pattern.count():
            self.exclude_pattern.setCurrentIndex(exclude_idx)
        self.exclude_regexp = create_toolbutton(self,
                                            icon=ima.icon('advanced'),
                                            tip=_('Regular expression'))
        self.exclude_regexp.setCheckable(True)
        self.exclude_regexp.setChecked(exclude_regexp)
        exclude_label = QLabel(_("Exclude:"))
        exclude_label.setBuddy(self.exclude_pattern)
        for widget in [include_label, self.include_pattern,
                       self.include_regexp,
                       exclude_label, self.exclude_pattern,
                       self.exclude_regexp]:
            hlayout2.addWidget(widget)

        # Layout 3
        hlayout3 = QHBoxLayout()
        self.python_path = QRadioButton(_("PYTHONPATH"), self)
        self.python_path.setChecked(in_python_path)
        self.python_path.setToolTip(_(
                          "Search in all directories listed in sys.path which"
                          " are outside the Python installation directory"))        
        self.hg_manifest = QRadioButton(_("Hg repository"), self)
        self.detect_hg_repository()
        self.hg_manifest.setToolTip(
                                _("Search in current directory hg repository"))
        self.custom_dir = QRadioButton(_("Here:"), self)
        self.custom_dir.setChecked(not in_python_path)
        self.dir_combo = PathComboBox(self)
        self.dir_combo.addItems(search_path)
        self.dir_combo.setToolTip(_("Search recursively in this directory"))
        self.dir_combo.open_dir.connect(self.set_directory)
        self.python_path.toggled.connect(self.dir_combo.setDisabled)
        self.hg_manifest.toggled.connect(self.dir_combo.setDisabled)
        browse = create_toolbutton(self, icon=ima.icon('DirOpenIcon'),
                                   tip=_('Browse a search directory'),
                                   triggered=self.select_directory)
        for widget in [self.python_path, self.hg_manifest, self.custom_dir,
                       self.dir_combo, browse]:
            hlayout3.addWidget(widget)
            
        self.search_text.valid.connect(lambda valid: self.find.emit())
        self.include_pattern.valid.connect(lambda valid: self.find.emit())
        self.exclude_pattern.valid.connect(lambda valid: self.find.emit())
        self.dir_combo.valid.connect(lambda valid: self.find.emit())
            
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        self.more_widgets = (hlayout2, hlayout3)
        self.toggle_more_options(more_options)
        self.setLayout(vlayout)
                
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
Esempio n. 55
0
    def setup_page(self):
        about_label = QLabel(
            _("The <b>global working directory</b> is "
              "the working directory for newly opened <i>consoles</i> "
              "(Python/IPython consoles and terminals), for the "
              "<i>file explorer</i>, for the <i>find in files</i> "
              "plugin and for new files created in the <i>editor</i>."))
        about_label.setWordWrap(True)

        startup_group = QGroupBox(_("Startup"))
        startup_bg = QButtonGroup(startup_group)
        startup_label = QLabel(
            _("At startup, the global working "
              "directory is:"))
        startup_label.setWordWrap(True)
        lastdir_radio = self.create_radiobutton(
            _("the same as in last session"),
            'startup/use_last_directory',
            True,
            _("At startup, Spyder will restore the "
              "global directory from last session"),
            button_group=startup_bg)
        thisdir_radio = self.create_radiobutton(
            _("the following directory:"),
            'startup/use_fixed_directory',
            False,
            _("At startup, the global working "
              "directory will be the specified path"),
            button_group=startup_bg)
        thisdir_bd = self.create_browsedir("", 'startup/fixed_directory',
                                           getcwd())
        thisdir_radio.toggled.connect(thisdir_bd.setEnabled)
        lastdir_radio.toggled.connect(thisdir_bd.setDisabled)
        thisdir_layout = QHBoxLayout()
        thisdir_layout.addWidget(thisdir_radio)
        thisdir_layout.addWidget(thisdir_bd)

        editor_o_group = QGroupBox(_("Open file"))
        editor_o_label = QLabel(_("Files are opened from:"))
        editor_o_label.setWordWrap(True)
        editor_o_bg = QButtonGroup(editor_o_group)
        editor_o_radio1 = self.create_radiobutton(
            _("the current file directory"),
            'editor/open/browse_scriptdir',
            button_group=editor_o_bg)
        editor_o_radio2 = self.create_radiobutton(
            _("the global working directory"),
            'editor/open/browse_workdir',
            button_group=editor_o_bg)

        editor_n_group = QGroupBox(_("New file"))
        editor_n_label = QLabel(_("Files are created in:"))
        editor_n_label.setWordWrap(True)
        editor_n_bg = QButtonGroup(editor_n_group)
        editor_n_radio1 = self.create_radiobutton(
            _("the current file directory"),
            'editor/new/browse_scriptdir',
            button_group=editor_n_bg)
        editor_n_radio2 = self.create_radiobutton(
            _("the global working directory"),
            'editor/new/browse_workdir',
            button_group=editor_n_bg)
        # Note: default values for the options above are set in plugin's
        #       constructor (see below)

        other_group = QGroupBox(_("Change to file base directory"))
        newcb = self.create_checkbox
        open_box = newcb(_("When opening a file"),
                         'editor/open/auto_set_to_basedir')
        save_box = newcb(_("When saving a file"),
                         'editor/save/auto_set_to_basedir')

        startup_layout = QVBoxLayout()
        startup_layout.addWidget(startup_label)
        startup_layout.addWidget(lastdir_radio)
        startup_layout.addLayout(thisdir_layout)
        startup_group.setLayout(startup_layout)

        editor_o_layout = QVBoxLayout()
        editor_o_layout.addWidget(editor_o_label)
        editor_o_layout.addWidget(editor_o_radio1)
        editor_o_layout.addWidget(editor_o_radio2)
        editor_o_group.setLayout(editor_o_layout)

        editor_n_layout = QVBoxLayout()
        editor_n_layout.addWidget(editor_n_label)
        editor_n_layout.addWidget(editor_n_radio1)
        editor_n_layout.addWidget(editor_n_radio2)
        editor_n_group.setLayout(editor_n_layout)

        other_layout = QVBoxLayout()
        other_layout.addWidget(open_box)
        other_layout.addWidget(save_box)
        other_group.setLayout(other_layout)

        vlayout = QVBoxLayout()
        vlayout.addWidget(about_label)
        vlayout.addSpacing(10)
        vlayout.addWidget(startup_group)
        vlayout.addWidget(editor_o_group)
        vlayout.addWidget(editor_n_group)
        vlayout.addWidget(other_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Esempio n. 56
0
def _getcdlistdir():
    """Return current directory list dir"""
    return os.listdir(getcwd())
Esempio n. 57
0
    def __init__(self,
                 parent=None,
                 name_filters=['*.py', '*.pyw'],
                 show_all=False,
                 show_cd_only=None,
                 show_icontext=True):
        QWidget.__init__(self, parent)

        # Widgets
        self.treewidget = ExplorerTreeWidget(self, show_cd_only=show_cd_only)
        button_previous = QToolButton(self)
        button_next = QToolButton(self)
        button_parent = QToolButton(self)
        self.button_menu = QToolButton(self)
        menu = QMenu(self)

        self.action_widgets = [
            button_previous, button_next, button_parent, self.button_menu
        ]

        # Actions
        icontext_action = create_action(self,
                                        _("Show icons and text"),
                                        toggled=self.toggle_icontext)
        previous_action = create_action(
            self,
            text=_("Previous"),
            icon=ima.icon('ArrowBack'),
            triggered=self.treewidget.go_to_previous_directory)
        next_action = create_action(
            self,
            text=_("Next"),
            icon=ima.icon('ArrowForward'),
            triggered=self.treewidget.go_to_next_directory)
        parent_action = create_action(
            self,
            text=_("Parent"),
            icon=ima.icon('ArrowUp'),
            triggered=self.treewidget.go_to_parent_directory)
        options_action = create_action(self, text='', tip=_('Options'))

        # Setup widgets
        self.treewidget.setup(name_filters=name_filters, show_all=show_all)
        self.treewidget.chdir(getcwd())
        self.treewidget.common_actions += [None, icontext_action]

        button_previous.setDefaultAction(previous_action)
        previous_action.setEnabled(False)

        button_next.setDefaultAction(next_action)
        next_action.setEnabled(False)

        button_parent.setDefaultAction(parent_action)

        self.button_menu.setIcon(ima.icon('tooloptions'))
        self.button_menu.setPopupMode(QToolButton.InstantPopup)
        self.button_menu.setMenu(menu)
        add_actions(menu, self.treewidget.common_actions)
        options_action.setMenu(menu)

        self.toggle_icontext(show_icontext)
        icontext_action.setChecked(show_icontext)

        for widget in self.action_widgets:
            widget.setAutoRaise(True)
            widget.setIconSize(QSize(16, 16))

        # Layouts
        blayout = QHBoxLayout()
        blayout.addWidget(button_previous)
        blayout.addWidget(button_next)
        blayout.addWidget(button_parent)
        blayout.addStretch()
        blayout.addWidget(self.button_menu)

        layout = QVBoxLayout()
        layout.addLayout(blayout)
        layout.addWidget(self.treewidget)
        self.setLayout(layout)

        # Signals and slots
        self.treewidget.set_previous_enabled.connect(
            previous_action.setEnabled)
        self.treewidget.set_next_enabled.connect(next_action.setEnabled)