Пример #1
0
    def on_file_dialog(self, dialog_type, directory, allow_multiple,
                       save_filename, file_filter):
        if dialog_type == FOLDER_DIALOG:
            self._file_name = QFileDialog.getExistingDirectory(
                self,
                self.localization['linux.openFolder'],
                options=QFileDialog.ShowDirsOnly)
        elif dialog_type == OPEN_DIALOG:
            if allow_multiple:
                self._file_name = QFileDialog.getOpenFileNames(
                    self, self.localization['linux.openFiles'], directory,
                    file_filter)
            else:
                self._file_name = QFileDialog.getOpenFileName(
                    self, self.localization['linux.openFile'], directory,
                    file_filter)
        elif dialog_type == SAVE_DIALOG:
            if directory:
                save_filename = os.path.join(str(directory),
                                             str(save_filename))

            self._file_name = QFileDialog.getSaveFileName(
                self, self.localization['global.saveFile'], save_filename)

        self._file_name_semaphore.release()
Пример #2
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()
Пример #3
0
 def add_file(self, _e):
     sm = self.tableViewDataset.selectionModel()
     if sm.hasSelection():
         q_index = sm.selectedRows()
         if len(q_index):
             dataset_qry = self.tableViewDataset.model().qry
             # dataset_id = dataset_qry[q_index[0].row()].id
             while True:
                 paths = QFileDialog.getOpenFileNames(
                     self, "Select one or more files", '',
                     "All Files (*)")[0]
                 if len(paths):
                     dataset_id = dataset_qry[q_index[0].row()].id
                     files = [File(path=path) for path in paths]
                     try:
                         self.model.add_files(dataset_id, files)
                     except IntegrityError as e:  # this should not be happening
                         self.model.session.rollback()
                         QMessageBox.information(
                             self,
                             "Integrity Error",
                             e,
                             defaultButton=QMessageBox.Ok)
                     else:
                         self.tableViewFile.model().change_layout()
                         self.statusBar().showMessage('Added file(s).')
                         break
                 else:  # cancel
                     self.statusBar().showMessage('Cancelled.')
                     return  # exit loop
Пример #4
0
    def read_files(self):
        """Read file and save in database."""
        table_name = self.twg_database.get_current_table_name()
        if table_name is None:
            return

        object_class = self._table_object_dict[table_name]

        fns = _QFileDialog.getOpenFileNames(
            self, caption='Read files', directory=self.directory,
            filter="Text files (*.txt *.dat)")

        if isinstance(fns, tuple):
            fns = fns[0]

        if len(fns) == 0:
            return

        try:
            idns = []
            for filename in fns:
                obj = object_class(
                    database_name=self.database_name,
                    mongo=self.mongo, server=self.server)
                obj.read_file(filename)
                idn = obj.db_save()
                idns.append(idn)
            msg = 'Added to database table.\nIDs: ' + str(idns)
            self.update_database_tables()
            _QMessageBox.information(self, 'Information', msg, _QMessageBox.Ok)
        except Exception:
            _traceback.print_exc(file=_sys.stdout)
            msg = 'Failed to read files and save values in database.'
            _QMessageBox.critical(self, 'Failure', msg, _QMessageBox.Ok)
            return
Пример #5
0
 def _open_images(self):
     """Adds image files from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption='Select image(s)...',
         directory=self._last_visited_dir,  # home dir by default
     )
     self._add_files(filenames)
Пример #6
0
def load_sq(main_window):
    """
    Load S(Q) from file
    Returns
    -------

    """
    # get default dir
    if main_window._currDataDir is None:
        default_dir = os.getcwd()
    else:
        default_dir = get_default_dir(main_window, sub_dir='SofQ')

    # get the file
    ext = 'dat (*.dat);;nxs (*.nxs);;All (*.*)'
    sq_file_names = QFileDialog.getOpenFileNames(main_window,
                                                 'Choose S(Q) File',
                                                 default_dir, ext)
    if isinstance(sq_file_names, tuple):
        sq_file_names = sq_file_names[0]
    if sq_file_names is None or sq_file_names == '' or len(sq_file_names) == 0:
        return

    # update current data directory
    main_window._currDataDir = os.path.split(os.path.abspath(
        sq_file_names[0]))[0]
    check_in_fixed_dir_structure(main_window, 'SofQ')

    # load S(q)
    for sq_file_name in sq_file_names:
        sq_file_name = str(sq_file_name)
        sq_ws_name, q_min, q_max = main_window._myController.load_sq(
            sq_file_name)
        if sq_ws_name == "InvalidInput" and q_min == 0 and q_max == 0:
            return
        # add to color management
        color = main_window._pdfColorManager.add_sofq(sq_ws_name)

        # set to the tree and combo box
        main_window.calculategr_ui.treeWidget_grWsList.add_sq(sq_ws_name)
        main_window.calculategr_ui.comboBox_SofQ.addItem(sq_ws_name)
        main_window.calculategr_ui.comboBox_SofQ.setCurrentIndex(
            main_window.calculategr_ui.comboBox_SofQ.count() - 1)

        # set the UI widgets
        main_window.calculategr_ui.doubleSpinBoxQmin.setValue(q_min)
        main_window.calculategr_ui.doubleSpinBoxQmax.setValue(q_max)

        # plot S(Q) - TODO why is it getting the name again?
        ws_name = main_window._myController.get_current_sq_name()

        plot_sq(main_window, ws_name, color=color, clear_prev=False)

        # calculate and calculate G(R)
        generate_gr_step1(main_window)

    check_widgets_status(main_window)
Пример #7
0
 def _open_files_dialog(self):
     """Add files from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption=trans._('Select file(s)...'),
         directory=self._last_visited_dir,  # home dir by default
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.open(filenames)
Пример #8
0
 def _open_files_dialog_as_stack_dialog(self):
     """Add files as a stack, from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption='Select files...',
         directory=self._last_visited_dir,  # home dir by default
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.open(filenames, stack=True)
Пример #9
0
 def input_from_multiple(self, format_name: str,
                         format_choose: Sequence[str]) -> List[str]:
     """Get external file names."""
     file_names, suffix = QFileDialog.getOpenFileNames(
         self, f"Open {format_name} files ...", self.env,
         ';;'.join(format_choose))
     if file_names:
         self.set_locate(QFileInfo(file_names[0]).absolutePath())
     return file_names
Пример #10
0
 def _open_images(self):
     """Add image files from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption='Select image(s)...',
         directory=self._last_visited_dir,  # home dir by default
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.add_path(filenames)
Пример #11
0
    def do_browse_load_file(self):
        """
        load scan's reduced files and optionally load it!
        :return: a list of tuple (detector ID, file name)
        """
        # check
        self._check_core()

        # TESTME - 20180925 - Make it work!

        # browse file
        default_dir = self._get_default_hdf()
        if default_dir is None:
            default_dir = self._core.working_dir

        # FIXME : multiple file types seems not be supported on some MacOSX
        file_filter = 'HDF(*.hdf5);;All Files(*.*)'
        open_value = QFileDialog.getOpenFileNames(self, 'HB2B Raw HDF File', default_dir, file_filter)

        if isinstance(open_value, tuple):
            # PyQt5
            hdf_name_list = open_value[0]
        else:
            hdf_name_list = open_value

        if len(hdf_name_list) == 0:
            # use cancel
            return

        # convert the files
        new_file_list = list()
        # TODO FIXME - 20180930 - count number of files loaded successfully and unsuccessfullly and decided
        # TODO                    fail or go on!
        error_msg = ''
        for ifile, file_name in enumerate(hdf_name_list):
            try:
                det_id = int(file_name.split('[')[1].split(']')[0])
            except IndexError as err:
                error_msg += 'Unable to retrieve detector ID from file {} due to {}\n' \
                             ''.format(file_name, err)
            else:
                new_file_list.append((det_id, str(file_name)))
        # END-FOR

        # auto load
        if self.ui.checkBox_autoLoad.isChecked():
            self.load_h5_scans(new_file_list)

        # Error message
        if error_msg != '':
            pyrs.interface.gui_helper.pop_message(self, 'Loading error', error_msg, 'error')

        return
Пример #12
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
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.open(filenames, stack=True)
         update_open_history(filenames[0])
Пример #13
0
    def _dialog_load_element(self, loader: classmethod, hint: str, *args, **kwargs) -> None:
        (paths, selected_filter) = QFileDialog.getOpenFileNames(
            parent=self,
            directory=self.last_dir,
            filter=self.filters_dict.get(hint).get('load'))

        # If path == '', then bool(path) is False
        path_list = sorted(filter(bool, paths))

        if len(path_list) > 0:
            self.statusBar.showMessage(f'Loading {len(path_list)} element(s)...')
            self._thread_runner(self.viewer.load_multiple, path_list, loader, *args, **kwargs)
            self.last_dir = QFileInfo(path_list[-1]).absoluteDir().absolutePath()
Пример #14
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],
        )

        if (filenames != []) and (filenames is not None):
            self.viewer.open(filenames)
            update_open_history(filenames[0])
Пример #15
0
 def openFileDialog(self):
     fileNames, _ = QFileDialog.getOpenFileNames(
         self,
         self.name,
         "",
         self.fileType,
         options=QFileDialog.DontUseNativeDialog)
     if fileNames:
         success = self.parent.controller.filesSelected(
             self.name, fileNames)
         if success:
             self.lineEdit.setText(', '.join(
                 os.path.basename(filename) for filename in fileNames))
         else:
             self.lineEdit.setText(None)
         self.parent.update_plot()
Пример #16
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])
Пример #17
0
    def add_package_button_clicked(self):

        file_names = QFileDialog.getOpenFileNames(
            self, 'select package file (nodes.py)', '../packages', '(*.py)')[0]

        for file_name in file_names:
            try:
                # simply try to open the file to make sure it's valid
                f = open(file_name)
                f.close()

                self.file_paths.append(file_name)
                self.packages.append(NodesPackage(dirname(file_name)))

            except FileNotFoundError:
                pass

        self.rebuild_selected_packages_list_widget()
Пример #18
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):
            for filename in filenames:
                self._qt_open([filename], stack=False)
            update_open_history(filenames[0])
Пример #19
0
def open_bragg_files(main_window):
    """
    Get the Bragg files including GSAS, NeXus, 3-column ASCii from File Dialog
    :retur: List of Bragg Files to load
    """
    # get file
    ext = 'GSAS (*.gsa *.gda *.gss);;Processed Nexus (*.nxs);;dat (*.dat);;All (*.*)'

    # get default dir
    if main_window._currDataDir is None:
        default_dir = os.getcwd()
    else:
        default_dir = addie.utilities.get_default_dir(main_window,
                                                      sub_dir='GSAS')

    bragg_file_names = QFileDialog.getOpenFileNames(main_window,
                                                    'Choose Bragg File',
                                                    default_dir, ext)
    if isinstance(bragg_file_names, tuple):
        bragg_file_names = bragg_file_names[0]
    if bragg_file_names is None or bragg_file_names == '' or len(
            bragg_file_names) == 0:
        return
    bragg_file_names = [
        str(bragg_file_name) for bragg_file_name in bragg_file_names
    ]

    # update stored data directory
    try:
        main_window._currDataDir = os.path.split(
            os.path.abspath(bragg_file_names[0]))[0]
    except IndexError as index_err:
        err_message = 'Unable to get absolute path of {0} due to {1}'.format(
            bragg_file_names, index_err)
        print(err_message)

    addie.utilities.check_in_fixed_dir_structure(main_window, sub_dir='GSAS')
    return bragg_file_names
Пример #20
0
    def selectFileToOpen(self):
        def getPreProcessingChoice(self, filename, filestructure):
            items = ("Choose the longest", "Merge all")
            item, okPressed = QInputDialog.getItem(
                self, "Multiple tracks/segments", "File '" + filename +
                "' contains more than one track/segment\n\n" + infos +
                "\nWhat to do?", items, 0, False)
            if okPressed and item:
                return items.index(item)
            else:
                return 0

        # Try to recover the last used directory
        old_directory = self.settings.value("lastdirectory", str)

        # Check if the setting exists
        if old_directory is not None:
            # Check if it's not empty
            if old_directory:
                old_directory = old_directory
            else:
                old_directory = bombo.TRACKS_FOLDER
        else:
            old_directory = bombo.TRACKS_FOLDER

        # Open the dialog box
        fullfilename_list = QFileDialog.getOpenFileNames(
            self, 'Open .gpx', old_directory, "GPX files (*.gpx)")
        if os.environ['QT_API'] == 'pyqt':
            pass
        elif os.environ['QT_API'] == 'pyqt5':
            fullfilename_list = fullfilename_list[0]

        # Process every selected file
        for i, fullfilename in enumerate(fullfilename_list):
            # Process filename
            directory, filename = os.path.split(str(fullfilename))
            filename, fileextension = os.path.splitext(filename)

            # Save the new directory in the application settings (it only
            # needs to be done once)
            if i == 0:
                # print "New directory to be saved: {}\n".format(directory)
                if os.environ['QT_API'] == 'pyqt':
                    self.settings.setValue("lastdirectory", str(directory))
                elif os.environ['QT_API'] == 'pyqt5':
                    self.settings.setValue("lastdirectory",
                                           QtCore.QVariant(str(directory)))

            # Open file and inspect what's inside
            gpxraw, longest_traseg, Ntracks, Nsegments, infos = bombo.LoadGPX(
                fullfilename)

            # If there's more than one track or segment, ask how to proceed
            if (Ntracks > 1) or (Nsegments > 1):
                preprocessingchoice = getPreProcessingChoice(
                    self, filename, infos)
                if preprocessingchoice == 0:
                    preprocessedgpx = bombo.SelectOneTrackAndSegmentFromGPX(
                        gpxraw, longest_traseg[0], longest_traseg[1])
                    listname = filename + " (longest)"
                elif preprocessingchoice == 1:
                    preprocessedgpx = bombo.MergeAllTracksAndSegmentsFromGPX(
                        gpxraw)
                    listname = filename + " (merged)"
            else:
                preprocessedgpx = gpxraw
                listname = filename

            # Append the list of open GPX files using the next available color (that's the size of the list -1)
            self.gpxlist.append(preprocessedgpx)
            self.gpxnamelist.append(listname)
            newitem = QListWidgetItem(listname)
            newitem.setBackground(
                QtGui.QColor(self.palette[len(self.gpxlist) - 1]))
            self.tracklist.addItem(newitem)

        return
Пример #21
0
def do_load_bragg_file(main_window):
    """
    Load Bragg files including GSAS, NeXus, 3-column ASCii.
    """
    # get file
    ext = 'GSAS (*.gsa *.gda *.gss);;Processed Nexus (*.nxs);;dat (*.dat);;All (*.*)'

    # get default dir
    if main_window._currDataDir is None:
        default_dir = os.getcwd()
    else:
        default_dir = getDefaultDir(main_window, sub_dir='GSAS')

    bragg_file_names = QFileDialog.getOpenFileNames(main_window, 'Choose Bragg File', default_dir, ext)
    if isinstance(bragg_file_names, tuple):
        bragg_file_names = bragg_file_names[0]
    if bragg_file_names is None or bragg_file_names == '' or len(bragg_file_names) == 0:
        return
    bragg_file_names = [str(bragg_file_name) for bragg_file_name in bragg_file_names]

    # update stored data directory
    try:
        main_window._currDataDir = os.path.split(os.path.abspath(bragg_file_names[0]))[0]
    except IndexError as index_err:
        err_message = 'Unable to get absolute path of {0} due to {1}'.format(bragg_file_names, index_err)
        print(err_message)

    check_in_fixed_dir_structure(main_window, sub_dir='GSAS')

    # load file
    try:
        gss_ws_names = list()
        for bragg_file_name in bragg_file_names:
            gss_ws_name, bank_angles = main_window._myController.load_bragg_file(bragg_file_name)
            gss_ws_names.append(gss_ws_name)
            banks_list = list()
            for i, angle in enumerate(bank_angles):
                banks_list.append('Bank {} - {}'.format(i + 1, angle))

            # add to tree
            main_window.rietveld_ui.treeWidget_braggWSList.add_bragg_ws_group(gss_ws_name, banks_list)

        # get plot mode
        if len(bragg_file_names) == 1:
            main_window.rietveld_ui.graphicsView_bragg.set_to_single_gss(True)
            main_window.rietveld_ui.radioButton_multiBank.setChecked(True)
            main_window.rietveld_ui.radioButton_multiGSS.setChecked(False)
        else:
            main_window.rietveld_ui.graphicsView_bragg.set_to_single_gss(False)
            main_window.rietveld_ui.radioButton_multiBank.setChecked(False)
            main_window.rietveld_ui.radioButton_multiGSS.setChecked(True)

        multi_bank_mode = main_window.rietveld_ui.radioButton_multiBank.isChecked()

        if multi_bank_mode:
            # single-GSS/multi-bank mode
            # rename bank
            for bank_id in main_window._braggBankWidgets:
                bank_check_box = main_window._braggBankWidgets[bank_id]

                if bank_id > len(bank_angles) or bank_angles[bank_id - 1] is None:
                    bank_check_box.setText('Bank %d' % bank_id)
                else:
                    bank_check_box.setText('Bank %.1f' % bank_angles[bank_id - 1])
                    # END-IF
                # END-IF-ELSE
            # END-FOR

            # clear all previous lines
            main_window.rietveld_ui.graphicsView_bragg.reset()
        # END-IF

        # banks
        main_window._onCanvasGSSBankList = get_bragg_banks_selected(main_window)
        if len(main_window._onCanvasGSSBankList) == 0:
            # select bank 1 as default
            main_window._noEventBankWidgets = True
            main_window.rietveld_ui.checkBox_bank1.setChecked(True)
            main_window._noEventBankWidgets = False
            main_window._onCanvasGSSBankList = get_bragg_banks_selected(main_window)

        # while in multiple-gss mode, no change will be made on the canvas at all

        # prepare to plot new Bragg
        plot_data_dict = dict()
        for gss_ws_name in gss_ws_names:
            plot_data_dict[gss_ws_name] = main_window._onCanvasGSSBankList[:]

        # plot
        # FIXME/ISSUE/NOW - get a summary on calling to plot_banks
        main_window.rietveld_ui.graphicsView_bragg.plot_banks(plot_data_dict, main_window._currBraggXUnit)

        # reset unit
        reset_bragg_data_range(main_window, main_window._currBraggXUnit)

    except RuntimeError as e:
        print('Encountered exception')
        print(e)

        main_window.setStyleSheet("QStatusBar{padding-left:8px;color:red;font-weight:bold;}")
        main_window.ui.statusbar.showMessage("Error loading {}".format(bragg_file_names), 10000)

    check_rietveld_widgets(main_window)
Пример #22
0
def browse_file(parent,
                caption,
                default_dir,
                file_filter,
                file_list=False,
                save_file=False):
    """Browse a file or files

    Parameters
    ----------
    parent : QWindow
        parent window
    caption : str
        Dialog box's caption
    default_dir : str
        Default directory to browse the file
    file_filter : str
        File type filter
    file_list : bool
        Flag for browse a list of files; otherwise, single file
    save_file : bool

    Returns
    -------
    str or ~list or None
        File name or A list of file names or None for user to cancel the operation

    """
    # check inputs
    # assert isinstance(parent, object), 'Parent {} must be of some object.'.format(parent)
    # checkdatatypes.check_string_variable('File browsing title/caption', caption)
    # checkdatatypes.check_file_name(default_dir, check_exist=False, is_dir=True)
    # checkdatatypes.check_bool_variable('Flag for browse a list of files to load', file_list)
    # checkdatatypes.check_bool_variable('Flag to select loading or saving file', save_file)
    if file_filter is None:
        file_filter = 'All Files (*.*)'
    else:
        checkdatatypes.check_string_variable('File filter', file_filter)
        file_filter = '{};;All Files (*.*)'.format(file_filter)

    if save_file:
        # browse file name to save to
        save_set = QFileDialog.getSaveFileName(parent,
                                               caption=caption,
                                               directory=default_dir,
                                               filter=file_filter)
        if isinstance(save_set, tuple):
            # returned include both file name and filter
            file_name = str(save_set[0])
        else:
            file_name = str(save_set)

    elif file_list:
        # browse file names to load
        open_set = QFileDialog.getOpenFileNames(parent, caption, default_dir,
                                                file_filter)

        if isinstance(open_set, tuple):
            file_name_list = open_set[0]
        else:
            file_name_list = open_set

        if len(file_name_list) == 0:  # user cancel browser
            return None
        else:
            return file_name_list

    else:
        # browse single file name
        open_set = QFileDialog.getOpenFileName(parent, caption, default_dir,
                                               file_filter)

        if isinstance(open_set, tuple):
            file_name = open_set[0]
        else:
            file_name = open_set

    # check result for single file whether user cancels operation
    if len(file_name) == 0:
        return None

    return str(file_name)