예제 #1
0
 def export_pipeline(self):
     exp = ExportDialog(self._settings.segmentation_pipelines,
                        ProfileDictViewer)
     if not exp.exec_():
         return
     dial = QFileDialog(self, "Export pipeline segment")
     dial.setFileMode(QFileDialog.AnyFile)
     dial.setAcceptMode(QFileDialog.AcceptSave)
     dial.setDirectory(self._settings.get("io.save_directory", ""))
     dial.setNameFilter("Segment pipeline (*.json)")
     dial.setDefaultSuffix("json")
     dial.selectFile("segment_pipeline.json")
     dial.setHistory(dial.history() + self._settings.get_path_history())
     if dial.exec_():
         file_path = dial.selectedFiles()[0]
         data = {
             x: self._settings.segmentation_pipelines[x]
             for x in exp.get_export_list()
         }
         with open(file_path, "w") as ff:
             json.dump(data,
                       ff,
                       cls=self._settings.json_encoder_class,
                       indent=2)
         self._settings.set("io.save_directory", os.path.dirname(file_path))
         self._settings.add_path_history(os.path.dirname(file_path))
 def import_plans(self):
     dial = QFileDialog(self, "Import calculation plans")
     dial.setFileMode(QFileDialog.ExistingFile)
     dial.setAcceptMode(QFileDialog.AcceptOpen)
     dial.setDirectory(
         self.settings.get("io.open_directory", str(Path.home())))
     dial.setNameFilter("Calculation plans (*.json)")
     dial.setDefaultSuffix("json")
     dial.setHistory(dial.history() + self.settings.get_path_history())
     if dial.exec_():
         file_path = dial.selectedFiles()[0]
         plans, err = self.settings.load_part(file_path)
         self.settings.set("io.batch_plan_directory",
                           os.path.dirname(file_path))
         self.settings.add_path_history(os.path.dirname(file_path))
         if err:
             QMessageBox.warning(
                 self, "Import error",
                 "error during importing, part of data were filtered.")
         choose = ImportDialog(plans, self.settings.batch_plans,
                               PlanPreview)
         if choose.exec_():
             for original_name, final_name in choose.get_import_list():
                 self.settings.batch_plans[final_name] = plans[
                     original_name]
             self.update_plan_list()
 def export_plans(self):
     choose = ExportDialog(self.settings.batch_plans, PlanPreview)
     if not choose.exec_():
         return
     dial = QFileDialog(self, "Export calculation plans")
     dial.setFileMode(QFileDialog.AnyFile)
     dial.setAcceptMode(QFileDialog.AcceptSave)
     dial.setDirectory(
         dial.setDirectory(
             self.settings.get("io.batch_plan_directory",
                               str(Path.home()))))
     dial.setNameFilter("Calculation plans (*.json)")
     dial.setDefaultSuffix("json")
     dial.selectFile("calculation_plans.json")
     dial.setHistory(dial.history() + self.settings.get_path_history())
     if dial.exec_():
         file_path = str(dial.selectedFiles()[0])
         self.settings.set("io.batch_plan_directory",
                           os.path.dirname(file_path))
         self.settings.add_path_history(os.path.dirname(file_path))
         data = {
             x: self.settings.batch_plans[x]
             for x in choose.get_export_list()
         }
         with open(file_path, "w") as ff:
             json.dump(data,
                       ff,
                       cls=self.settings.json_encoder_class,
                       indent=2)
예제 #4
0
 def import_profiles(self):
     dial = QFileDialog(self, "Import profile segment")
     dial.setFileMode(QFileDialog.ExistingFile)
     dial.setAcceptMode(QFileDialog.AcceptOpen)
     dial.setDirectory(
         self._settings.get("io.save_directory", str(Path.home())))
     dial.setNameFilter("Segment profile (*.json)")
     dial.setHistory(dial.history() + self._settings.get_path_history())
     if dial.exec_():
         file_path = dial.selectedFiles()[0]
         save_dir = os.path.dirname(file_path)
         self._settings.set("io.save_directory", save_dir)
         self._settings.add_path_history(save_dir)
         profs, err = self._settings.load_part(file_path)
         if err:
             QMessageBox.warning(
                 self, "Import error",
                 "error during importing, part of data were filtered.")
         profiles_dict = self._settings.segmentation_profiles
         imp = ImportDialog(profs, profiles_dict, ProfileDictViewer)
         if not imp.exec_():
             return
         for original_name, final_name in imp.get_import_list():
             profiles_dict[final_name] = profs[original_name]
         self._settings.dump()
         self.update_profile_list()
예제 #5
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])
예제 #6
0
 def choose_data_prefix(self):
     dial = QFileDialog()
     dial.setAcceptMode(QFileDialog.AcceptOpen)
     dial.setFileMode(QFileDialog.Directory)
     dial.setDirectory(self.base_prefix.text())
     dial.setHistory(dial.history() + self.settings.get_path_history())
     if dial.exec_():
         dir_path = str(dial.selectedFiles()[0])
         self.base_prefix.setText(dir_path)
예제 #7
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)
예제 #8
0
 def mapping_dialog():
     dial = QFileDialog(self, "Select file")
     dial.setHistory(dial.history() + self.settings.get_path_history())
     base_path = str(self.base_prefix.text()).strip()
     if base_path != "":
         dial.setDirectory(base_path)
     dial.setFileMode(QFileDialog.ExistingFile)
     if dial.exec_():
         path = str(dial.selectedFiles())
         self.mask_path_list[i].setText(path)
         file_mapper: MaskFile = self.mask_mapper_list[pos]
         file_mapper.set_map_path(path)
예제 #9
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])
예제 #10
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
     )
     if folder not in {'', None}:
         self.viewer.open([folder])
         update_open_history(folder)
예제 #11
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])
예제 #12
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"))

        msg = trans._("selected") if selected else trans._("all")
        dlg = QFileDialog()
        hist = get_save_history()
        dlg.setHistory(hist)
        filename, _ = dlg.getSaveFileName(
            parent=self,
            caption=trans._('Save {msg} layers', msg=msg),
            directory=hist[0],  # home dir by default
        )

        if filename:
            with warnings.catch_warnings(record=True) as wa:
                saved = self.viewer.layers.save(filename, selected=selected)
                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])
예제 #13
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])
예제 #14
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)
예제 #15
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])
예제 #16
0
    def _start_trace_dialog(self):
        """Open Save As dialog to start recording a trace file."""
        viewer = self._win._qt_viewer

        dlg = QFileDialog()
        hist = get_save_history()
        dlg.setHistory(hist)
        filename, _ = dlg.getSaveFileName(
            parent=viewer,
            caption=trans._('Record performance trace file'),
            directory=hist[0],
            filter=trans._("Trace Files (*.json)"),
        )
        if filename:
            if not filename.endswith(".json"):
                filename += ".json"

            # Schedule this to avoid bogus "MetaCall" event for the entire
            # time the file dialog was up.
            QTimer.singleShot(0, lambda: self._start_trace(filename))

            update_save_history(filename)
예제 #17
0
    def _start_trace_dialog(self):
        """Open Save As dialog to start recording a trace file."""
        viewer = self.main_window.qt_viewer

        dlg = QFileDialog()
        hist = get_save_history()
        dlg.setHistory(hist)
        filename, _ = dlg.getSaveFileName(
            parent=viewer,
            caption=trans._('Record performance trace file'),
            directory=hist[0],
            filter=trans._("Trace Files (*.json)"),
        )
        if filename:
            filename = _ensure_extension(filename, '.json')

            def start_trace():
                self._start_trace(filename)

            # Schedule this to avoid bogus "MetaCall" event for the entire
            # time the file dialog was up.
            QTimer.singleShot(0, start_trace)

            update_save_history(filename)
예제 #18
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.
        if selected and len(self.viewer.layers.selection) == 1:
            selected_layer = list(self.viewer.layers.selection)[0]
            # single selected layer.
            if selected_layer._type_string == 'image':

                ext = imsave_extensions()

                ext_list = []
                for val in ext:
                    ext_list.append("*" + val)

                ext_str = ';;'.join(ext_list)

                ext_str = trans._(
                    "All Files (*);; Image file types:;;{ext_str}",
                    ext_str=ext_str,
                )

            elif selected_layer._type_string == 'points':

                ext_str = trans._("All Files (*);; *.csv;;")

            else:
                # layer other than image or points
                ext_str = trans._("All Files (*);;")

        else:
            # multiple layers.
            ext_str = trans._("All Files (*);;")

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

        filename, _ = dlg.getSaveFileName(
            parent=self,
            caption=trans._('Save {msg} layers', msg=msg),
            directory=hist[0],  # home dir by default,
            filter=ext_str,
        )

        if filename:
            with warnings.catch_warnings(record=True) as wa:
                saved = self.viewer.layers.save(filename, selected=selected)
                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])