예제 #1
0
 def pick_output_dir(self):
     '''
     Sets the output directory.
     '''
     dialog = QFileDialog(parent=self)
     dialog.setFileMode(QFileDialog.DirectoryOnly)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     dialog.setWindowTitle('Select a location to store the generated minidsp config files')
     if dialog.exec():
         selected = dialog.selectedFiles()
         if len(selected) > 0:
             if os.path.abspath(selected[0]) == os.path.abspath(self.__beq_dir):
                 QMessageBox.critical(self, '',
                                      f"Output directory cannot be inside the input directory, choose a different folder",
                                      QMessageBox.Ok)
             else:
                 abspath = os.path.abspath(f"{selected[0]}{os.path.sep}beq_minidsp")
                 if not os.path.exists(abspath):
                     try:
                         os.mkdir(abspath)
                     except:
                         QMessageBox.critical(self, '', f"Unable to create directory - {abspath}", QMessageBox.Ok)
                 if os.path.exists(abspath):
                     self.outputDirectory.setText(abspath)
     self.__enable_process()
예제 #2
0
 def choose_result_prefix(self):
     dial = QFileDialog()
     dial.setOption(QFileDialog.DontUseNativeDialog, True)
     dial.setAcceptMode(QFileDialog.AcceptOpen)
     dial.setFileMode(QFileDialog.Directory)
     dial.setDirectory(self.result_prefix.text())
     dial.setHistory(dial.history() + self.settings.get_path_history())
     if dial.exec_():
         dir_path = str(dial.selectedFiles()[0])
         self.result_prefix.setText(dir_path)
예제 #3
0
def showSelectProjectDialog(parent: QWidget = None) -> Optional[Path]:
    dialog = QFileDialog(parent, Qt.Dialog)
    dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.Dialog)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.setLabelText(QFileDialog.LookIn, "Select project folder")
    dialog.setFileMode(QFileDialog.Directory)
    dialog.setOption(QFileDialog.ShowDirsOnly, True)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setDirectory(QDir.homePath())

    if dialog.exec_():
        paths = dialog.selectedFiles()
        assert len(paths) == 1
        path = Path(paths[0])
        return path
예제 #4
0
 def pick_user_source_dir(self):
     '''
     Sets the user source directory.
     '''
     dialog = QFileDialog(parent=self)
     dialog.setFileMode(QFileDialog.DirectoryOnly)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     dialog.setWindowTitle('Choose a directory which holds your own BEQ files')
     if dialog.exec():
         selected = dialog.selectedFiles()
         if len(selected) > 0:
             if os.path.abspath(selected[0]) == os.path.abspath(self.__beq_dir):
                 QMessageBox.critical(self, '',
                                      f"User directory cannot be inside the input directory, choose a different folder",
                                      QMessageBox.Ok)
             else:
                 self.userSourceDir.setText(selected[0])
                 self.update_beq_count()
예제 #5
0
class FileLineEdit(QLineEdit):
    def __init__(self,
                 check_exists: bool = False,
                 parent: Optional[QWidget] = None):
        super(FileLineEdit, self).__init__(parent)

        browse_action_icon = self.window().style().standardIcon(
            QStyle.SP_DirOpenIcon)
        self._browse_action = self.addAction(browse_action_icon,
                                             QLineEdit.LeadingPosition)

        self._file_dialog = QFileDialog(self)
        self._file_dialog.setOption(QFileDialog.DontUseNativeDialog)

        # noinspection PyUnusedLocal
        # noinspection PyUnresolvedReferences
        @self._browse_action.triggered.connect
        def on_browse_action_triggered(checked=False):
            path = self.path
            if path is not None:
                if path.parent.is_dir():
                    self._file_dialog.setDirectory(str(path.parent))
                if path.exists():
                    self._file_dialog.selectFile(str(path))
            if self._file_dialog.exec() == QFileDialog.Accepted:
                selected_files = self._file_dialog.selectedFiles()
                self.setText(selected_files[0])

        if check_exists:
            # noinspection PyUnresolvedReferences
            @self.textChanged.connect
            def on_text_changed(text):
                if not text or Path(text).exists():
                    self.setStyleSheet('')
                else:
                    self.setStyleSheet('background-color: #88ff0000')

    @property
    def file_dialog(self) -> QFileDialog:
        return self._file_dialog

    @property
    def path(self) -> Optional[Path]:
        return Path(self.text()) if self.text() else None
예제 #6
0
class VMainWindow(VMainWindowBaseClass, Ui_VMainWindowClass):
    #                      str, DataFrame, DataType
    data_selected = Signal(str, object, object)
    predicted_data_selected = Signal(dict)
    ground_truth_data_selected = Signal(dict)
    image_data_selected = Signal([str, list], [str])
    file_loaded = Signal(object)

    def __init__(self):
        super(VMainWindow, self).__init__()
        self.setupUi(self)

        self._widget_setup()
        self._signals_setup()

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        try:
            self.controller.cleanup()
        except AttributeError:
            pass

    def _widget_setup(self):
        self._error_dialog = VErrorMessageBox(self)

        self._file_dialog = QFileDialog(self, self.tr('Open File'), '')
        self._file_dialog.setOption(QFileDialog.DontUseNativeDialog)

        # type(self.marker_options_groupbox) -> widgets.VMarkerOptionsGroupBox
        self.marker_options_groupbox.add_widget(
            'Predicted', DataType.PREDICTED)
        self.marker_options_groupbox.add_widget(
            'Ground Truth', DataType.GROUND_TRUTH)

        shapes = (Shape.CIRCLE, Shape.DIAMOND)
        icons = (QIcon(r':/circle'), QIcon(r':/diamond'))
        for widget in self.marker_options_groupbox.widgets.values():
            for icon, shape in zip(icons, shapes):
                widget.add_marker_shape(shape, icon)

        scene = VGraphicsScene()
        self.graphics_view.setScene(scene)

        self.controller = Controller(scene, self.tables_tab_widget, self.marker_options_groupbox)

    def _signals_setup(self) -> None:
        self.action_open_ground_truth.triggered.connect(
            lambda: self.open(DataType.GROUND_TRUTH))
        self.action_open_predicted.triggered.connect(
            lambda: self.open(DataType.PREDICTED))
        self.action_open_image.triggered.connect(
            lambda: self.open(DataType.IMAGE))

        self.graphics_view_scrollbar.value_changed[int].connect(
            self.controller.set_index)

        self.file_loaded[object].connect(self.marker_options_groupbox.enable)
        self.file_loaded[object].connect(
            lambda d: self.menu_open_data.setEnabled(True) if d & DataType.IMAGE else None)

    def _parse_filename(self, filelist: Sequence[str], dtype: DataType) -> str:
        """
        Checks for errors in the list of filenames, i.e if list is empty, or if
        list has more than one filename. If the list passes the checks, we
        proceed to load the file. For now, we reject TIFF files because loading
        TIFF images is not implemented.
        """
        def create_error_dialog(message):
            self._error_dialog.message = message
            self._error_dialog.exec_()

        if len(filelist) > 1:
            return create_error_dialog(
                '{} files were selected '.format(len(filelist)) +
                'but we can only load one file at a time.')
        elif len(filelist) == 0:
            return create_error_dialog('No files were selected.')
        else:
            filename = filelist[0]
        # temporary to reject loaded tif images because loading them
        # hasn't been implemented yet
        print('***parsing filename***')
        filename_ext = splitext(filename)[-1]
        if filename_ext in EXTENSIONS[DataType.TIFF_IMAGE][0]:
            create_error_dialog('tiff files not yet supported.')
            return ''
        else:
            return filename

    def open(self, dtype: DataType) -> None:
        """
        Opens a QDialog in which the user selects an HDF5 or TIFF file.
        """
        # we must first create a properly-formated regexp string for the
        # 'filter' argument of the 'setNameFilter' method in our already-
        # instantiated but not shown QDialog.
        extensions = OrderedDict(zip(FILETYPES[dtype], EXTENSIONS[dtype]))
        ext = [[''] + list(ext) for ext in extensions.values()]
        extlist = [self.tr(k) + " (" + ' *'.join(e) + ")" for k, e in zip(extensions, ext)]
        filter_ = ';;'.join(extlist)
        # example filter_ string:
        # Tiff Files (*.tif, *.tiff, *.ome.tif);;HDF5 Files (*.h5, *.hdf5, *.hf5, *.hd5)
        self._file_dialog.setNameFilter(filter_)
        # closing the QDialog returns an enum, either "Accepted" or "Rejected"
        # depending on whether the "Ok" or "Cancel" button was pressed,
        # respectively
        result = self._file_dialog.exec_()
        if result == QFileDialog.Accepted:
            filename = self._parse_filename(
                self._file_dialog.selectedFiles(), dtype)
            if filename:
                self.open_inspection_widget(filename, dtype)

    def open_inspection_widget(self, filename: str, dtype: DataType):
        list_widget_columns = ['name', 'directory']
        ground_truth_titles = OrderedDict(
            [('Ground Truth Coordinates', list_widget_columns)])
        predicted_titles = OrderedDict(
            [('Predicted Coordinates', list_widget_columns),
             ('Probabilities', list_widget_columns)])
        image_titles = OrderedDict(
            [('Images', list_widget_columns)])

        list_widget_args = EnumDict([
            (DataType.GROUND_TRUTH, ground_truth_titles),
            (DataType.PREDICTED, predicted_titles),
            (DataType.HDF_IMAGE, image_titles)])

        args = list_widget_args[dtype][0]
        dialog = make_dialog(filename, args, dtype)
        result = dialog.exec_()
        if result == QFileDialog.Accepted:
            self.load(filename, dtype, dialog.get_data('directory'))

    def load(self, filename: str, dtype: DataType, handles: DataFrame):
        if dtype & DataType.HDF_IMAGE:
            req = HDF5Request1D(filename, handles, axis=0)
            self.graphics_view_scrollbar.setEnabled(True)
        elif dtype & DataType.DATA:
            req = HDF5Request2D(filename, handles)
        else:
            raise NotImplementedError('Loading {} not yet implemented.'.format(dtype))

        print(filename)
        print(dtype)
        print(handles)
        source = HDF5DataSource(filename, req)
        self.controller.set_datasource(source, dtype)
        self.graphics_view_scrollbar.setMaximum(len(source) - 1)
        self.file_loaded.emit(dtype)

    @Slot()
    def save(self):
        pass

    @Slot()
    def save_as(self):
        pass

    @Slot()
    def quit(self):
        sys.exit(0)
예제 #7
0
class LoadMeasurementsDialog(QDialog, Ui_loadMeasurementDialog):
    '''
    Load Measurement dialog
    '''
    def __init__(self, parent=None):
        super(LoadMeasurementsDialog, self).__init__(parent)
        self.setupUi(self)
        self.buttonBox.button(QDialogButtonBox.Open).setText("Select File(s)")
        _translate = QtCore.QCoreApplication.translate
        self.fs.setCurrentText(_translate("loadMeasurementDialog", "48000"))
        self.__dialog = QFileDialog(parent=self)
        self.__errors = 0

    def accept(self):
        '''
        Shows the file select dialog based on the chosen options.
        :return:
        '''
        self.__errors = 0
        self.loadedFiles.clear()
        self.ignoredFiles.clear()
        loadType = self.fileType.currentText()
        fileMode = None
        option = QFileDialog.ShowDirsOnly
        if loadType == 'txt' or loadType == 'dbl':
            fileMode = QFileDialog.DirectoryOnly
        elif loadType == 'wav':
            fileMode = QFileDialog.DirectoryOnly
        elif loadType == 'HolmImpulse':
            fileMode = QFileDialog.ExistingFile
            option = QFileDialog.DontConfirmOverwrite
        elif loadType == 'REW':
            fileMode = QFileDialog.DirectoryOnly
        elif loadType == 'ARTA':
            fileMode = QFileDialog.DirectoryOnly
        else:
            QMessageBox.about(self, "Error", "Unknown format " + loadType)
        if fileMode is not None:
            self.__dialog.setFileMode(fileMode)
            self.__dialog.setOption(option)
            self.__dialog.setWindowTitle("Load Measurements")
            self.__dialog.exec()

    def load(self, measurementModel, dataPathField):
        '''
        Loads the measurements by looking in the selected directory.
        :param measurementModel: the model to load.
        :param dataPathField: the display field.
        :return:
        '''
        selected = self.__dialog.selectedFiles()
        loadType = self.fileType.currentText()
        if len(selected) > 0:
            dataPathField.setText(selected[0])
            if loadType == 'txt':
                measurementModel.load(
                    TxtLoader(self.onFile, selected[0],
                              int(self.fs.currentText())).load())
            elif loadType == 'dbl':
                measurementModel.load(
                    DblLoader(self.onFile, selected[0],
                              int(self.fs.currentText())).load())
            elif loadType == 'wav':
                measurementModel.load(
                    WavLoader(self.onFile, selected[0]).load())
            elif loadType == 'HolmImpulse':
                measurementModel.load(
                    HolmLoader(self.onFile, selected[0]).load())
            elif loadType == 'REW':
                measurementModel.load(
                    REWLoader(self.onFile, selected[0]).load())
            elif loadType == 'ARTA':
                measurementModel.load(
                    ARTALoader(self.onFile, selected[0]).load())
        else:
            measurementModel.clear()
            dataPathField.setText('')
        if self.__errors == 0:
            QDialog.accept(self)

    def onFile(self, filename, loaded):
        if loaded is True:
            self.loadedFiles.appendPlainText(filename)
        else:
            self.ignoredFiles.appendPlainText(filename)
            self.__errors += 1

    def fileTypeChanged(self, text):
        '''
        Hides the fs field if the fs is determined by the source file.
        :param text: the selected text.
        '''
        visible = True
        if text == 'txt' or text == 'dbl':
            pass
        else:
            visible = False
        self.fs.setVisible(visible)
        self.fsLabel.setVisible(visible)