Пример #1
0
    def open_database(self):
        options = QFileDialog.Options()

        if not self.config.value('native_dialogs', False):
            options |= QFileDialog.DontUseNativeDialog

        filename, _ = QFileDialog.getOpenFileName(
            self.mainwin,
            self.tr("Open patch database"),
            self.config.value('paths/last_database_path', ''),
            "SQLite Database (*.sqlite *.db);;All Files (*)",
            options=options)

        if filename and exists(filename):
            self.config.setValue('paths/last_database_path', dirname(filename))
            log.info(f"Opening database file '{filename}'...")
            try:
                self.load_database(filename)
            except Exception as exc:
                log.exception(f"Error opening database file '{filename}'.")
                dlg = self.create_error_dlg(
                    self.tr("Could not load patch database <i>{}</i>.").format(
                        basename(filename)),
                    detail=str(exc),
                    ignore_buttons=False)
                dlg.exec_()
            else:
                self.config.setValue('database/last_opened', filename)
Пример #2
0
def open_file_dialog(self, title, default_filename, file_types):
    """
    Common method for opening files


    Parameters
    ----------
    self : ???
        the main GUI; not a vbox
    title : str
        the title of the dialog
    default_filename : str
        the default directory
    file_types : str
        the wildcard
        'Nastran Geometry - Punch (*.bdf; *.dat; *.nas; *.ecd; *.pch);;All files (*)'

    """
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fname, flt = QFileDialog.getOpenFileName(self,
                                             title,
                                             default_filename,
                                             file_types,
                                             options=options)
    #flt = str(filt).strip()
    return fname, flt
Пример #3
0
    def import_patches(self):
        options = QFileDialog.Options()

        if not self.config.value('native_dialogs', False):
            options |= QFileDialog.DontUseNativeDialog

        files, _ = QFileDialog.getOpenFileNames(
            self.mainwin,
            self.tr("Import SysEx patches"),
            self.config.value('paths/last_import_path', ''),
            "SysEx Files (*.syx);;All Files (*)",
            options=options)

        if files:
            self.config.setValue('paths/last_import_path', dirname(files[0]))

            self.patches.layoutAboutToBeChanged.emit()
            with self.session.begin():
                for file in files:
                    with open(file, 'rb') as syx:
                        data = syx.read()

                    #assert len(data) == 241
                    if is_reface_dx_voice(data):
                        name = get_patch_name(data)
                        displayname = splitext(basename(file))[0].replace(
                            '_', ' ').strip()
                        patch = Patch(name=name,
                                      displayname=displayname,
                                      data=data)
                        self.session.add(patch)

            # TODO: check if any patches were actually added
            self.patches._update()
            self.patches.layoutChanged.emit()
Пример #4
0
    def get_brainreg_directory(self, standard_space):
        """
        Shows file dialog to choose output directory
        and sets global directory info
        """
        if standard_space:
            self.plugin = "brainreg_standard"
            self.standard_space = True
        else:
            self.plugin = "brainreg"
            self.standard_space = False

        self.status_label.setText("Loading...")
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        brainreg_directory = QFileDialog.getExistingDirectory(
            self,
            "Select brainreg directory",
            options=options,
        )

        if not brainreg_directory:
            return

        if self.directory != brainreg_directory:
            status = self.remove_layers()
            if not status:
                return  # Something prevented deletion
            self.directory = Path(brainreg_directory)
        else:
            print(f"{str(brainreg_directory)} already loaded.")
            return

        # Otherwise, proceed loading brainreg dir
        self.load_brainreg_directory()
Пример #5
0
def open_file_dialog(self, title, default_filename, file_types):
    """
    Common method for opening files


    Parameters
    ----------
    self : ???
        the main GUI; not a vbox
    title : str
        the title of the dialog
    default_filename : str
        the default directory
    file_types : str
        the wildcard
        'Nastran Geometry - Punch (*.bdf; *.dat; *.nas; *.ecd; *.pch);;All files (*)'

    """
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    if qt_version == 4:
        # works in: pyqt4, pyside
        # doesn't work in: pyqt5
        fname, wildcard_level = QFileDialog.getOpenFileNameAndFilter(
            self, title, default_filename, file_types, options=options)
        return str(fname), str(wildcard_level)
    else:
        fname, flt = QFileDialog.getOpenFileName(self,
                                                 title,
                                                 default_filename,
                                                 file_types,
                                                 options=options)
        #flt = str(filt).strip()
    return fname, flt
Пример #6
0
    def load_registration_directory(self):
        self.status_label.setText("Loading...")
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        directory = QFileDialog.getExistingDirectory(
            self,
            "Select registration directory",
            options=options,
        )
        # deal with existing dialog
        if directory is not "":
            self.registration_directory = Path(directory)
            self.initialise_registration_paths()
            self.load_cellfinder_project_button.setVisible(False)
            self.load_registration_project_button.setVisible(False)
            self.load_raw_data_directory_button.setVisible(True)
            self.load_raw_data_single_button.setVisible(True)

            self.image_scales = self.get_registration_scaling()
            if self.image_scales is not None:
                self.load_registration_button.setVisible(True)
                self.load_downsampled_data_button.setVisible(True)
            else:
                print("Config files and logs could not be parsed to detect "
                      "the data scaling")
        self.status_label.setText("Ready")
Пример #7
0
    def _save_layers_dialog(self, selected=False):
        """Save layers (all or selected) to disk, using ``LayerList.save()``.

        Parameters
        ----------
        selected : bool
            If True, only layers that are selected in the viewer will be saved.
            By default, all layers are saved.
        """
        msg = ''
        if not len(self.viewer.layers):
            msg = trans._("There are no layers in the viewer to save")
        elif selected and not len(self.viewer.layers.selection):
            msg = trans._('Please select one or more layers to save,'
                          '\nor use "Save all layers..."')
        if msg:
            raise OSError(trans._("Nothing to save"))

        # prepare list of extensions for drop down menu.
        ext_str, writers = _extension_string_for_layers(
            list(self.viewer.layers.selection) if selected else self.viewer.
            layers)

        msg = trans._("selected") if selected else trans._("all")
        dlg = QFileDialog()
        hist = get_save_history()
        dlg.setHistory(hist)

        filename, selected_filter = dlg.getSaveFileName(
            parent=self,
            caption=trans._('Save {msg} layers', msg=msg),
            directory=hist[0],  # home dir by default,
            filter=ext_str,
            options=(QFileDialog.DontUseNativeDialog
                     if in_ipython() else QFileDialog.Options()),
        )
        logging.debug(f'QFileDialog - filename: {filename or None} '
                      f'selected_filter: {selected_filter or None}')

        if filename:
            writer = _npe2_decode_selected_filter(ext_str, selected_filter,
                                                  writers)
            with warnings.catch_warnings(record=True) as wa:
                saved = self.viewer.layers.save(filename,
                                                selected=selected,
                                                _writer=writer)
                logging.debug(f'Saved {saved}')
                error_messages = "\n".join(str(x.message.args[0]) for x in wa)

            if not saved:
                raise OSError(
                    trans._(
                        "File {filename} save failed.\n{error_messages}",
                        deferred=True,
                        filename=filename,
                        error_messages=error_messages,
                    ))
            else:
                update_save_history(saved[0])
Пример #8
0
def _qfiledialog_wrapper(attr, parent=None, caption='', basedir='',
                         filters='', selectedfilter='', options=None):
    if options is None:
        options = QFileDialog.Options(0)
    try:
        # PyQt <v4.6 (API #1)
        from qtpy.QtCore import QString
    except ImportError:
        # PySide or PyQt >=v4.6
        QString = None  # analysis:ignore
    tuple_returned = True
    try:
        # PyQt >=v4.6
        func = getattr(QFileDialog, attr+'AndFilter')
    except AttributeError:
        # PySide or PyQt <v4.6
        func = getattr(QFileDialog, attr)
        if QString is not None:
            selectedfilter = QString()
            tuple_returned = False

    # Calling QFileDialog static method
    if sys.platform == "win32":
        # On Windows platforms: redirect standard outputs
        _temp1, _temp2 = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = None, None
    try:
        result = func(parent, caption, basedir,
                      filters, selectedfilter, options)
    except TypeError:
        # The selectedfilter option (`initialFilter` in Qt) has only been
        # introduced in Jan. 2010 for PyQt v4.7, that's why we handle here
        # the TypeError exception which will be raised with PyQt v4.6
        # (see Issue 960 for more details)
        result = func(parent, caption, basedir, filters, options)
    finally:
        if sys.platform == "win32":
            # On Windows platforms: restore standard outputs
            sys.stdout, sys.stderr = _temp1, _temp2

    # Processing output
    if tuple_returned:
        # PySide or PyQt >=v4.6
        output, selectedfilter = result
    else:
        # PyQt <v4.6 (API #1)
        output = result
    if QString is not None:
        # PyQt API #1: conversions needed from QString/QStringList
        selectedfilter = to_text_string(selectedfilter)
        if isinstance(output, QString):
            # Single filename
            output = to_text_string(output)
        else:
            # List of filenames
            output = [to_text_string(fname) for fname in output]

    # Always returns the tuple (output, selectedfilter)
    return output, selectedfilter
Пример #9
0
 def get_brainreg_directory(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     self.brainreg_directory = QFileDialog.getExistingDirectory(
         self,
         "Select brainreg directory",
         options=options,
     )
Пример #10
0
 def openFileDialogAction(self):
     options = QFileDialog.Options()
     fileName, filtr = QFileDialog.getOpenFileName(self,
             config.thisTranslation["menu7_open"],
             "notes",
             "UniqueBible.app Note Files (*.uba);;HTML Files (*.html);;HTM Files (*.htm);;All Files (*)", "", options)
     if fileName:
         self.openNoteFile(fileName)
Пример #11
0
def choose_directory_dialog(parent=None, prompt="Select directory"):
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    directory = QFileDialog.getExistingDirectory(
        parent,
        prompt,
        options=options,
    )
    return directory
Пример #12
0
 def get_output_directory(self):
     if self.output_directory is None:
         options = QFileDialog.Options()
         options |= QFileDialog.DontUseNativeDialog
         self.output_directory = QFileDialog.getExistingDirectory(
             self,
             "Select output directory",
             options=options,
         )
         self.output_directory = Path(self.output_directory)
Пример #13
0
 def select_nii_file(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     file, _ = QFileDialog.getOpenFileName(
         self,
         "Select the downsampled image you wish to segment",
         "",
         "Nifti files (*.nii)",
         options=options,
     )
     self.downsampled_file = Path(file)
Пример #14
0
 def openImageDialog(self, external=True):
     options = QFileDialog.Options()
     fileName, filtr = QFileDialog.getOpenFileName(self,
             config.thisTranslation["html_open"],
             self.parent.openFileNameLabel.text(),
             "JPG Files (*.jpg);;JPEG Files (*.jpeg);;PNG Files (*.png);;GIF Files (*.gif);;BMP Files (*.bmp);;All Files (*)", "", options)
     if fileName:
         if external:
             self.linkExternalImage(fileName)
         else:
             self.embedImage(fileName)
Пример #15
0
 def set_output_directory(self):
     self.status_label.setText("Loading...")
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     self.directory = QFileDialog.getExistingDirectory(
         self,
         "Select output directory",
         options=options,
     )
     if self.directory != "":
         self.directory = Path(self.directory)
Пример #16
0
 def openSaveAsDialog(self):
     if self.noteFileName:
         *_, defaultName = os.path.split(self.noteFileName)
     else:
         defaultName = "new.uba"
     options = QFileDialog.Options()
     fileName, filtr = QFileDialog.getSaveFileName(self,
             config.thisTranslation["note_saveAs"],
             defaultName,
             "UniqueBible.app Note Files (*.uba);;HTML Files (*.html);;HTM Files (*.htm);;All Files (*)", "", options)
     if fileName:
         self.saveAsNote(fileName)
Пример #17
0
 def saveHtmlToFile(self, html):
     options = QFileDialog.Options()
     fileName, filtr = QFileDialog.getSaveFileName(
         self, config.thisTranslation["note_saveAs"], "",
         "HTML Files (*.html)", "", options)
     if fileName:
         if not "." in os.path.basename(fileName):
             fileName = fileName + ".html"
         file = open(fileName, "w")
         file.write(html)
         file.close()
         self.parent.displayMessage(config.thisTranslation["saved"])
Пример #18
0
 def openFileNameDialog(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     fileName, _ = QFileDialog.getOpenFileName(self,
                                               "Elige tu archivo",
                                               "",
                                               "Text Files (*.txt)",
                                               options=options)
     if fileName:
         Dialog = QDialog()
         ui = Noticia_Dialog(Dialog)
         ui.setupUi(fileName)
Пример #19
0
    def __add_from_file(self, fun, name_from_file=True):
        """
        General function for selecting, loading
        and adding to scene a file.

        Arguments:
        -----------

        fun: function. One of Scene's methods used to add the file's
                content to the scene.
        name_from_file: bool, optional. If True the actor's name is the name of the files loaded
        """
        options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog

        fname, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "All Files (*)",
            options=options,
        )

        if not fname:
            return
        else:
            # Get actor color and alpha
            dialog = AddFromFileWindow(self, self.palette)
            dialog.exec()

            alpha = get_alpha_from_string(dialog.alpha_textbox.text())
            color = get_color_from_string(dialog.color_textbox.text())

            # Add actor
            act = fun(fname)
            if not isinstance(act, (tuple, list)):
                act = [act]

            # Edit actor
            for actor in act:
                actor.name = Path(fname).name

                if color != "default":
                    actor.mesh.c(color)

                if alpha is not None:
                    actor.mesh.alpha(alpha)

            # Update
            self._update()
Пример #20
0
    def AC_load(self):
        try:
            options = QFileDialog.Options()
            self.AC, _ = QFileDialog.getOpenFileName(None,
                                                     'Upload Image',
                                                     '',
                                                     '*.png *.jpg *.jpeg',
                                                     options=options)
            self.img_AC = self.getGrayImage(self.AC)

            self.total_settings_AC()

        except Exception as err:
            print(err)
Пример #21
0
    def getFilePath(self, fileExtension="xlsx"):
        from qtpy.QtWidgets import QFileDialog

        defaultName = "Interlinear_Data.{0}".format(fileExtension)
        options = QFileDialog.Options()
        filePath, *_ = QFileDialog.getSaveFileName(
            self, config.thisTranslation["note_saveAs"], defaultName,
            "Spreadsheet File (*.{0})".format(fileExtension), "", options)
        if filePath:
            filePath = filePath.replace(" ", "_")
            if not filePath.endswith(".{0}".format(fileExtension)):
                filePath = "{0}.{1}".format(filePath, fileExtension)
            return filePath
        else:
            return ""
Пример #22
0
def open_exe_name_dialog(parent, appname):
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    file_name, _ = QFileDialog.getOpenFileName(
        parent,
        "{} could not be found. Please locate it manually".format(appname),
        "",
        "Valid {} executable (*);;".format(appname),
        options=options,
    )
    if file_name:
        print(file_name)
        return file_name
    else:
        print("No file is selected. guiscrcpy is likely to fail")
Пример #23
0
    def imgA_load_btn(self):
        try:
            options = QFileDialog.Options()
            self.hyb1, _ = QFileDialog.getOpenFileName(None,
                                                       'Upload Image',
                                                       '',
                                                       '*.png *.jpg *.jpeg',
                                                       options=options)
            pixmap = QPixmap(self.hyb1)
            pixmap = pixmap.scaled(self.label_histograms_input_2.width(),
                                   self.label_histograms_input_2.height(),
                                   QtCore.Qt.KeepAspectRatio)
            self.label_histograms_input_2.setPixmap(pixmap)

        except Exception as err:
            print(err)
Пример #24
0
 def load_raw_data_single(self):
     self.status_label.setText("Loading...")
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     file, _ = QFileDialog.getOpenFileName(
         self,
         "Select image",
         "",
         "Images (*.tif *.tiff *.nii)",
         options=options,
     )
     # deal with existing dialog
     if file is not "":
         file = Path(file)
         self.add_single_image(file)
     self.status_label.setText("Ready")
Пример #25
0
 def frequency_load(self):
     try:
         options = QFileDialog.Options()
         self.freq, _ = QFileDialog.getOpenFileName(None,
                                                    'Upload Image',
                                                    '',
                                                    '*.png *.jpg *.jpeg',
                                                    options=options)
         pixmap = QPixmap(self.freq)
         pixmap = pixmap.scaled(self.label_pass_input.width(),
                                self.label_pass_input.height(),
                                QtCore.Qt.KeepAspectRatio)
         self.label_pass_input.setPixmap(pixmap)
         self.label_pass_output.clear()
     except Exception as err:
         print(err)
Пример #26
0
def open_exe_name_dialog(parent, appname):
    options = QFileDialog.Options()
    options |= QDir.AllEntries
    options |= QDir.Hidden

    file_dialog = QFileDialog()
    file_dialog.setFilter(QDir.AllEntries | QDir.Hidden)
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    file_dialog.setWindowTitle(
        f"{appname} could not be found. Please locate in"
        "manually")
    if file_dialog.exec():
        file_name = file_dialog.selectedFiles()
        print(file_name[0])
        return file_name[0]
    else:
        print("No file is selected. guiscrcpy is likely to fail")
Пример #27
0
 def load_raw_data_directory(self):
     self.status_label.setText("Loading...")
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     directory = QFileDialog.getExistingDirectory(
         self,
         "Select data directory",
         options=options,
     )
     # deal with existing dialog
     if directory is not "":
         directory = Path(directory)
         img_paths = get_sorted_file_paths(directory,
                                           file_extension=".tif*")
         images = magic_imread(img_paths, use_dask=True, stack=True)
         self.viewer.add_image(images, name=directory.stem)
     self.status_label.setText("Ready")
Пример #28
0
    def _open_files_dialog(self):
        """Add files from the menubar."""
        dlg = QFileDialog()
        hist = get_open_history()
        dlg.setHistory(hist)

        filenames, _ = dlg.getOpenFileNames(
            parent=self,
            caption=trans._('Select file(s)...'),
            directory=hist[0],
            options=(QFileDialog.DontUseNativeDialog
                     if in_ipython() else QFileDialog.Options()),
        )

        if (filenames != []) and (filenames is not None):
            self.viewer.open(filenames)
            update_open_history(filenames[0])
Пример #29
0
    def _open_files_dialog_as_stack_dialog(self):
        """Add files as a stack, from the menubar."""
        dlg = QFileDialog()
        hist = get_open_history()
        dlg.setHistory(hist)

        filenames, _ = dlg.getOpenFileNames(
            parent=self,
            caption=trans._('Select files...'),
            directory=hist[0],  # home dir by default
            options=(QFileDialog.DontUseNativeDialog
                     if in_ipython() else QFileDialog.Options()),
        )

        if (filenames != []) and (filenames is not None):
            self._qt_open(filenames, stack=True)
            update_open_history(filenames[0])
Пример #30
0
    def _open_folder_dialog(self):
        """Add a folder of files from the menubar."""
        dlg = QFileDialog()
        hist = get_open_history()
        dlg.setHistory(hist)

        folder = dlg.getExistingDirectory(
            parent=self,
            caption=trans._('Select folder...'),
            directory=hist[0],  # home dir by default
            options=(QFileDialog.DontUseNativeDialog
                     if in_ipython() else QFileDialog.Options()),
        )

        if folder not in {'', None}:
            self._qt_open([folder], stack=False)
            update_open_history(folder)