Пример #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_ipyclient:
         error_message = self.shellwidget.save_namespace(self.filename)
         self.shellwidget._kernel_reply = None
     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)
Пример #2
0
 def detect_hg_repository(self, path=None):
     if path is None:
         path = getcwd()
     hg_repository = is_hg_installed() and get_vcs_root(path) is not None
     self.hg_manifest.setEnabled(hg_repository)
     if not hg_repository and self.hg_manifest.isChecked():
         self.custom_dir.setChecked(True)
Пример #3
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)
Пример #4
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)
Пример #5
0
 def select_file(self):
     self.redirect_stdio.emit(False)
     filename, _selfilter = getopenfilename(
         self, _("Select Python script"), getcwd(),
         _("Python scripts") + " (*.py ; *.pyw)")
     self.redirect_stdio.emit(True)
     if filename:
         self.analyze(filename)
Пример #6
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)
Пример #7
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)
Пример #8
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)
Пример #9
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)
Пример #10
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)
Пример #11
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)
Пример #12
0
    def __init__(self,
                 parent=None,
                 pathlist=None,
                 ro_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 TRex), 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 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)
        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()
Пример #13
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
Пример #14
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)
     self.clear_namespace = options.get('clear_namespace',  
                                 CONF.get('run', 'clear_namespace', False))
Пример #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)
     # Disable the view of .spyproject. 
     self.filter_directories()
Пример #16
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
Пример #17
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 (TRex 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 (TRex >=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
Пример #18
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 TRex 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()
Пример #19
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)
Пример #20
0
 def get_cdlistdir(self):
     """Return shell current directory list dir"""
     return os.listdir(getcwd())
Пример #21
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)
        clear_variables = self.create_checkbox(CLEAR_ALL_VARIABLES, 
            'clear_namespace', False)

        general_layout = QVBoxLayout()
        general_layout.addWidget(clear_variables)
        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)
Пример #22
0
 def go_to_parent_directory(self):
     """Go to parent directory"""
     self.chdir( osp.abspath(osp.join(getcwd(), os.pardir)) )
Пример #23
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)
Пример #24
0
 def set_as_current_console_wd(self):
     """Set as current console working directory"""
     self.set_current_console_wd.emit(getcwd())
Пример #25
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, TRex 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)
Пример #26
0
 def parent_directory(self):
     """Change working directory to parent directory"""
     self.chdir(os.path.join(getcwd(), os.path.pardir))
Пример #27
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())

        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)
Пример #28
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())
Пример #29
0
def _getcdlistdir():
    """Return current directory list dir"""
    return os.listdir(getcwd())
Пример #30
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.set_value(var_name, clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                if self.is_ipyclient:
                    error_message = self.shellwidget.load_data(
                        self.filename, ext)
                    self.shellwidget._kernel_reply = None
                else:
                    error_message = monitor_load_globals(
                        self._get_sock(), self.filename, ext)
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()

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