def dlg_export(parent):

	dialog = QFileDialog(parent)
	dialog.setWindowTitle(_("Export the simulation as"))
	dialog.setAcceptMode(QFileDialog.AcceptSave)
	types=[]
	types.append(_("gpvdm archive input+output files")+" (*.gpvdm)")
	types.append(_("gpvdm archive input files")+" (*.gpvdm)")
	types.append(_("optical materials database")+" (*.zip)")
	types.append(_("pdf file")+" (*.pdf)")
	types.append(_("jpg image")+" (*.jpg)")
	types.append(_("tex file")+" (*.tex)")

	dialog.setNameFilters(types)
	dialog.setFileMode(QFileDialog.ExistingFile)
	dialog.setAcceptMode(QFileDialog.AcceptSave)

	if dialog.exec_() == QDialog.Accepted:
		file_name = dialog.selectedFiles()[0]
		#print(dialog.selectedNameFilter())
		if dialog.selectedNameFilter()==_("gpvdm archive input+output files")+" (*.gpvdm)":
			export_archive(file_name,True)
		elif dialog.selectedNameFilter()==_("gpvdm archive input files")+" (*.gpvdm)":
			export_archive(file_name,False)
		elif dialog.selectedNameFilter()==_("optical materials database")+" (*.zip)":
			export_materials(file_name)
		elif dialog.selectedNameFilter()==_("pdf file")+" (*.pdf)" or dialog.selectedNameFilter()==_("jpg image")+" (*.jpg)" or dialog.selectedNameFilter()==_("tex file")+" (*.tex)":
			export_as(file_name)
Beispiel #2
0
 def saveFileAs(self):
     fileFormats = OrderedDict([
         (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3),
         (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2),
     ])
     state = settings.saveFileDialogState()
     path = self._font.path or self._font.binaryPath
     if path:
         directory = os.path.dirname(path)
     else:
         directory = None if state else QStandardPaths.standardLocations(
             QStandardPaths.DocumentsLocation)[0]
     # TODO: switch to directory dlg on platforms that need it
     dialog = QFileDialog(
         self, self.tr("Save File"), directory,
         ";;".join(fileFormats.keys()))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     if directory:
         dialog.setDirectory(directory)
     ok = dialog.exec_()
     settings.setSaveFileDialogState(dialog.saveState())
     if ok:
         nameFilter = dialog.selectedNameFilter()
         path = dialog.selectedFiles()[0]
         self.saveFile(path, fileFormats[nameFilter])
         self.setWindowTitle(self.fontTitle())
Beispiel #3
0
def getFileName(mode, context, caption, directory, tfilter):
    if not isLinux:
        if mode == 'save':
            file_path, file_type = QFileDialog.getSaveFileName(
                context, caption, directory, tfilter)
            return file_path
        elif mode == 'open':
            file_path, file_type = QFileDialog.getOpenFileName(
                context, caption, directory, tfilter)
            return file_path
        else:
            raise ValueError
    dlg = QFileDialog(context, caption, directory, tfilter)
    if mode == 'save':
        mode = QFileDialog.AcceptSave
    elif mode == 'open':
        mode = QFileDialog.AcceptOpen
    else:
        raise ValueError
    dlg.setAcceptMode(mode)
    dlg.setViewMode(QFileDialog.List)
    dlg.setOption(QFileDialog.DontUseNativeDialog)
    if dlg.exec() == QDialog.Accepted:
        filt = dlg.selectedNameFilter()
        ext = get_ext(filt)
        ret = dlg.selectedFiles()[0]
        if not ret.endswith(ext):
            ret += ext
        return ret
    return ''
Beispiel #4
0
 def exportFile(self):
     fileFormats = [
         (self.tr("PostScript OT font {}").format("(*.otf)")),
         (self.tr("TrueType OT font {}").format("(*.ttf)")),
     ]
     state = settings.exportFileDialogState()
     # TODO: font.path as default?
     # TODO: store per-font export path in lib
     directory = None if state else QStandardPaths.standardLocations(
         QStandardPaths.DocumentsLocation)[0]
     dialog = QFileDialog(
         self, self.tr("Export File"), directory,
         ";;".join(fileFormats))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     ok = dialog.exec_()
     settings.setExportFileDialogState(dialog.saveState())
     if ok:
         fmt = "ttf" if dialog.selectedNameFilter(
             ) == fileFormats[1] else "otf"
         path = dialog.selectedFiles()[0]
         try:
             self._font.export(path, fmt)
         except Exception as e:
             errorReports.showCriticalException(e)
def open_as_filter(parent, my_filter, path="", multi_files=False):
    selected_filter = ""
    if path == "":
        open_path = os.getcwd()
    else:
        open_path = path

    dialog = QFileDialog(parent, _("Open file"))
    dialog.setDirectory(open_path)

    dialog.setNameFilter(my_filter)
    dialog.setAcceptMode(QFileDialog.AcceptOpen)
    if multi_files == True:
        dialog.setFileMode(QFileDialog.ExistingFiles)

    if dialog.exec_() == QDialog.Accepted:
        ret_list = []
        s = dialog.selectedNameFilter()
        if s.count("(*") == 1:
            s = s.split("(*")[1]
            s = s[:-1]

        filenames = dialog.selectedFiles()
        for f in filenames:
            if f.endswith(s) == False:
                ret_list.append(f + s)
            else:
                ret_list.append(f)

        if multi_files == True:
            return ret_list
        else:
            return ret_list[0]
    else:
        return None
Beispiel #6
0
def open_as_filter(parent, my_filter, path=""):
    selected_filter = ""
    if path == "":
        open_path = os.getcwd()
    else:
        open_path = path

    dialog = QFileDialog(parent, _("Open file"))
    dialog.setDirectory(open_path)
    print(">>>>>", open_path)
    dialog.setNameFilter(my_filter)
    dialog.setAcceptMode(QFileDialog.AcceptOpen)
    if dialog.exec_() == QDialog.Accepted:
        filename = dialog.selectedFiles()[0]
        s = dialog.selectedNameFilter()
        if s.count("(*") == 1:
            s = s.split("(*")[1]
            s = s[:-1]

            if filename.endswith(s) == False:
                filename = filename + s
            else:
                filename = filename

        return filename
    else:
        return None
Beispiel #7
0
 def saveFileAs(self):
     fileFormats = OrderedDict([
         (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3),
         (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2),
     ])
     state = settings.saveFileDialogState()
     path = self._font.path or self._font.binaryPath
     if path:
         directory = os.path.dirname(path)
     else:
         directory = (None if state else QStandardPaths.standardLocations(
             QStandardPaths.DocumentsLocation)[0])
     # TODO: switch to directory dlg on platforms that need it
     dialog = QFileDialog(self, self.tr("Save File"), directory,
                          ";;".join(fileFormats.keys()))
     if state:
         dialog.restoreState(state)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     if directory:
         dialog.setDirectory(directory)
     ok = dialog.exec_()
     settings.setSaveFileDialogState(dialog.saveState())
     if ok:
         nameFilter = dialog.selectedNameFilter()
         path = dialog.selectedFiles()[0]
         if not os.path.basename(path).endswith(".ufo"):
             path += ".ufo"
         self.saveFile(path, fileFormats[nameFilter])
         app = QApplication.instance()
         app.setCurrentFile(self._font.path)
         self.setWindowTitle(self.fontTitle())
Beispiel #8
0
def _fileDialog(acceptMode, fileMode,
                parent=None, caption='', directory='', filters=(),
                selectedFilter=None, options=0):

    nameFilters = make_filters(filters)

    dialog = QFileDialog(parent, caption, directory)
    dialog.setNameFilters(nameFilters)
    dialog.setAcceptMode(acceptMode)
    dialog.setFileMode(fileMode)
    dialog.setOptions(QFileDialog.Options(options))
    if selectedFilter is not None:
        dialog.selectNameFilter(nameFilters[selectedFilter])

    if dialog.exec_() != QDialog.Accepted:
        return None

    filename = dialog.selectedFiles()[0]
    if fileMode != QFileDialog.Directory:
        selectedFilter = nameFilters.index(dialog.selectedNameFilter())

        _, ext = os.path.splitext(filename)

        if not ext:
            ext = filters[selectedFilter][1]    # use first extension
            if ext.startswith('*.') and ext != '*.*':
                return filename + ext[1:]       # remove leading '*'
    return filename
Beispiel #9
0
def get_save_file_name(initial_name: str,
                       wav_only=False,
                       parent=None,
                       caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        filter = "Complex files (*.complex);;Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            filter = "wav files (*.wav);;all files (*)"
    else:
        filter = "Textfiles (*.txt);;All files (*)"

    filename = None
    dialog = QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setNameFilter(filter)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setDirectory(RECENT_PATH)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setWindowTitle(caption)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.selectFile(initial_name)

    if (dialog.exec()):
        filename = dialog.selectedFiles()[0]
        filter = dialog.selectedNameFilter()
        ext = filter[filter.index('*'):filter.index(')')][1:]
        if not os.path.exists(
                filename) and len(ext) > 0 and not filename.endswith(ext):
            filename += ext

    if filename:
        RECENT_PATH = os.path.split(filename)[0]

    return filename
Beispiel #10
0
def _fileDialog(acceptMode,
                fileMode,
                parent=None,
                caption='',
                directory='',
                filters=(),
                selectedFilter=None,
                options=0):

    nameFilters = make_filters(filters)

    dialog = QFileDialog(parent, caption, directory)
    dialog.setNameFilters(nameFilters)
    dialog.setAcceptMode(acceptMode)
    dialog.setFileMode(fileMode)
    dialog.setOptions(QFileDialog.Options(options))
    if selectedFilter is not None:
        dialog.selectNameFilter(nameFilters[selectedFilter])

    if dialog.exec_() != QDialog.Accepted:
        return None

    filename = dialog.selectedFiles()[0]
    if fileMode != QFileDialog.Directory:
        selectedFilter = nameFilters.index(dialog.selectedNameFilter())

        _, ext = os.path.splitext(filename)

        if not ext:
            ext = filters[selectedFilter][1]  # use first extension
            if ext.startswith('*.') and ext != '*.*':
                return filename + ext[1:]  # remove leading '*'
    return filename
Beispiel #11
0
def getSaveFileNameWithSuffix(parent,
                              caption,
                              directory,
                              filter,
                              options=None,
                              selectedFilter=None,
                              defaultSuffix=None):
    """
    A reimplemented version of QFileDialog.getSaveFileName() because we would like to make use
    of the QFileDialog.defaultSuffix property that getSaveFileName() does not let us adjust.

    Note: knowing the selected filter is not an invitation to change the chosen filename later.
    """
    dialog = QFileDialog(parent=parent,
                         caption=caption,
                         directory=directory,
                         filter=filter)
    if options:
        dialog.setOptions(options)
    if defaultSuffix:
        dialog.setDefaultSuffix(defaultSuffix)
    dialog.setFileMode(QFileDialog.AnyFile)
    if hasattr(dialog, 'setSupportedSchemes'):  # Pre-Qt5.6 lacks this.
        dialog.setSupportedSchemes(("file", ))
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    if selectedFilter:
        dialog.selectNameFilter(selectedFilter)
    if (dialog.exec() == QFileDialog.Accepted):
        return dialog.selectedFiles()[0], dialog.selectedNameFilter()
    return None, None
Beispiel #12
0
def dlg_export(parent):

	dialog = QFileDialog(parent)
	dialog.setWindowTitle(_("Export the simulation as"))
	dialog.setAcceptMode(QFileDialog.AcceptSave)
	types=[]
	types.append(_("gpvdm archive input+output files (*.gpvdm)"))
	types.append(_("gpvdm archive input files (*.gpvdm)"))
	types.append(_("optical materials database (*.zip)"))
	types.append(_("pdf file (*.pdf)"))
	types.append(_("jpg image (*.jpg)"))
	types.append(_("tex file (*.tex)"))
	types.append(_("Excel file (*.xlsx)"))

	dialog.setNameFilters(types)
	dialog.setFileMode(QFileDialog.ExistingFile)
	dialog.setAcceptMode(QFileDialog.AcceptSave)

	if dialog.exec_() == QDialog.Accepted:
		file_name = dialog.selectedFiles()[0]
		if dialog.selectedNameFilter()==_("gpvdm archive input+output files (*.gpvdm)"):
			export_archive(file_name,True)
		elif dialog.selectedNameFilter()==_("gpvdm archive input files (*.gpvdm)"):
			export_archive(file_name,False)
		elif dialog.selectedNameFilter()==_("optical materials database (*.zip)"):
			export_materials(file_name)
		elif dialog.selectedNameFilter()==_("pdf file (*.pdf)") or dialog.selectedNameFilter()==_("jpg image (*.jpg)") or dialog.selectedNameFilter()==_("tex file (*.tex)"):
			export_as(file_name)
		elif dialog.selectedNameFilter()==_("Excel file (*.xlsx)"):
			gen_workbook(os.getcwd(),file_name)
Beispiel #13
0
 def saveFileAs(self):
     fileFormats = OrderedDict([
         (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3),
         (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2),
     ])
     # TODO: switch to directory on platforms that need it
     dialog = QFileDialog(
         self, self.tr("Save File"), None, ";;".join(fileFormats.keys()))
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     ok = dialog.exec_()
     if ok:
         nameFilter = dialog.selectedNameFilter()
         path = dialog.selectedFiles()[0]
         self.saveFile(path, fileFormats[nameFilter])
         self.setWindowTitle()
def dlg_export_xls(parent):

	dialog = QFileDialog(parent)
	dialog.setWindowTitle(_("Export to xls file"))
	dialog.setAcceptMode(QFileDialog.AcceptSave)
	types=[]
	types.append(_("Excel file")+" (*.xlsx)")

	dialog.setNameFilters(types)
	dialog.setFileMode(QFileDialog.ExistingFile)
	dialog.setAcceptMode(QFileDialog.AcceptSave)

	if dialog.exec_() == QDialog.Accepted:
		file_name = dialog.selectedFiles()[0]
		#print(dialog.selectedNameFilter())
		if dialog.selectedNameFilter()==_("Excel file")+" (*.xlsx)":
			gen_workbook(get_sim_path(),set_file_ext(file_name,".xlsx"))
Beispiel #15
0
def exportDataDictAs(self, dic):
    """Exports a data dictionnary in various formats"""
    # -- prepare available formats
    export_list = {}
    export_list["csv file (*.csv)"] = (_exportDataDictAsCSV, ".csv")
    export_list["hdf5 file (*.hdf5)"] = (_exportDataDictAsHDF5, ".hdf5")
    # -- select output file
    folder = self.current_export_folder
    folder = str(folder) if folder is not None else folder
    dlg = QFileDialog(self, "Select output file", folder)
    dlg.setNameFilters(list(export_list.keys()))
    dlg.setFileMode(QFileDialog.AnyFile)
    dlg.setAcceptMode(QFileDialog.AcceptSave)
    if not dlg.exec():
        logger.debug("Why do you bother me then ?")
        return
    # -- save
    # get file name
    filename = dlg.selectedFiles()[0]
    filepath = Path(filename)
    # check if the file exist, so that we don't ask overwrite confirmation twice
    license_to_kill = filepath.is_file()
    # check selected format
    fmt = dlg.selectedNameFilter()
    if fmt not in export_list:
        logger.warning(f"Requested format '{fmt}'' is not implemented")
        return
    # get extension / append default if missing
    export_func, default_suffix = export_list[fmt]
    if not filepath.suffix:
        filepath = filepath.with_suffix(default_suffix)
    # store current folder
    self.current_export_folder = filepath.parent
    # if file exist, ask for confirmation
    # NB : already handled by QFileDialog, but since we might hav
    # changed the suffix we have to check a second time
    if filepath.is_file() and not license_to_kill:
        msg = f"{filepath} exists : overwrite ?"
        title = "This mission is too important..."
        answer = QMessageBox.question(self, title, msg,
                                      QMessageBox.Yes | QMessageBox.No)
        if answer == QMessageBox.No:
            return
    # export
    export_func(self, dic, str(filepath))
    logger.debug(f"Saved as {filepath}")
Beispiel #16
0
    def saveTrace(self, checked):
        #diag = QFileDialog.getSaveFileName(self, "Select destination", "./", "Comma Separated Values (*.csv)");
        diag = QFileDialog(self)
        diag.setAcceptMode(QFileDialog.AcceptSave)  #Save file, not open one
        diag.setNameFilter(
            "Comma Separated Values (*.csv);;Space separated Values (*.csv)")
        diag.setDefaultSuffix("csv")
        # Make sure selected files end in .csv
        diag.exec()
        try:
            filename = diag.selectedFiles()[0]
        except IndexError:
            filename = ''
        user_filter = diag.selectedNameFilter()
        if (user_filter == "Space separated Values (*.csv)"):
            delimiter = " "
        else:
            delimiter = ","

        if (filename != '' and not os.path.isdir(filename)):

            npzfile = self.last_result
            t = npzfile["t"]
            cos2 = npzfile["cos2"]
            cos2d = npzfile["cos2d"]
            extra_header = []
            extra_columns = []
            if ('Javg' in npzfile.keys()):
                Javg = npzfile["Javg"]
                std = npzfile["std"]
                psi_pulse = npzfile["psi"]
                psi_final = psi_pulse[-1]
                psi_out = numpy.abs(psi_final)**2
                percentile_999 = npzfile["percentile_999"]
                extra_header = [
                    "<J>", "std(J)", "J_99.9%", "Probability coefficients"
                ]
                extra_columns = [Javg, std, percentile_999, psi_out]

            utils.save_to_csv(filename, t, cos2, cos2d, extra_header,
                              extra_columns, delimiter)
def save_as_filter(parent, my_filter):
    selected_filter = ""
    dialog = QFileDialog(parent)
    dialog.setWindowTitle(_("Save as"))
    dialog.setNameFilter(my_filter)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    if dialog.exec_() == QDialog.Accepted:
        filename = dialog.selectedFiles()[0]
        s = dialog.selectedNameFilter()
        if s.count("(*") == 1:
            s = s.split("(*")[1]
            s = s[:-1]

            if filename.endswith(s) == False and s != ".":
                filename = filename + s
            else:
                filename = filename

        return filename
    else:
        return None
Beispiel #18
0
def save_as_filter(parent,my_filter):
	selected_filter = ""
	dialog = QFileDialog(parent)
	dialog.setWindowTitle(_("Save as"))
	dialog.setNameFilter(my_filter)
	dialog.setAcceptMode(QFileDialog.AcceptSave)
	if dialog.exec_() == QDialog.Accepted:
		filename = dialog.selectedFiles()[0]
		s=dialog.selectedNameFilter()
		if s.count("(*")==1:
			s=s.split("(*")[1]
			s=s[:-1]

			if filename.endswith(s)==False:
				filename=filename+s
			else:
				filename=filename

		return filename
	else:
		return None
    def saveTrace(self,checked):
        #diag = QFileDialog.getSaveFileName(self, "Select destination", "./", "Comma Separated Values (*.csv)");
        diag = QFileDialog(self);
        diag.setAcceptMode(QFileDialog.AcceptSave) #Save file, not open one
        diag.setNameFilter("Comma Separated Values (*.csv);;Space separated Values (*.csv)");
        diag.setDefaultSuffix("csv"); # Make sure selected files end in .csv
        diag.exec();
        try:
            filename = diag.selectedFiles()[0];
        except IndexError:
            filename = '';
        user_filter = diag.selectedNameFilter();
        if (user_filter == "Space separated Values (*.csv)"):
            delimiter = " ";
        else:
            delimiter = ",";

        if (filename != '' and not os.path.isdir(filename)):

            npzfile = self.last_result;
            t = npzfile["t"];
            cos2 = npzfile["cos2"];
            cos2d = npzfile["cos2d"];                
            extra_header = [];
            extra_columns = [];
            if ('Javg' in npzfile.keys()):
                Javg = npzfile["Javg"];
                std = npzfile["std"];
                psi_pulse = npzfile["psi"];
                psi_final = psi_pulse[-1];
                psi_out=numpy.abs(psi_final)**2;
                percentile_999 = npzfile["percentile_999"];
                extra_header = ["<J>","std(J)","J_99.9%","Probability coefficients"];
                extra_columns = [Javg,std,percentile_999,psi_out];


            utils.save_to_csv(filename,t,cos2,cos2d,extra_header,extra_columns,delimiter);
Beispiel #20
0
    def browse(self):
        """
        Open a file dialog and select a user specified file.
        """
        formats = [
            "Text - comma separated (*.csv, *)",
            "Text - tab separated (*.tsv, *)",
            "Text - all files (*)"
        ]

        dlg = QFileDialog(
            self, windowTitle="Open Data File",
            acceptMode=QFileDialog.AcceptOpen,
            fileMode=QFileDialog.ExistingFile
        )
        dlg.setNameFilters(formats)
        state = self.dialog_state
        lastdir = state.get("directory", "")
        lastfilter = state.get("filter", "")

        if lastdir and os.path.isdir(lastdir):
            dlg.setDirectory(lastdir)
        if lastfilter:
            dlg.selectNameFilter(lastfilter)

        status = dlg.exec_()
        dlg.deleteLater()
        if status == QFileDialog.Accepted:
            self.dialog_state["directory"] = dlg.directory().absolutePath()
            self.dialog_state["filter"] = dlg.selectedNameFilter()

            selected_filter = dlg.selectedNameFilter()
            path = dlg.selectedFiles()[0]
            # pre-flight check; try to determine the nature of the file
            mtype = _mime_type_for_path(path)
            if not mtype.inherits("text/plain"):
                mb = QMessageBox(
                    parent=self,
                    windowTitle="",
                    icon=QMessageBox.Question,
                    text="The '{basename}' may be a binary file.\n"
                         "Are you sure you want to continue?".format(
                             basename=os.path.basename(path)),
                    standardButtons=QMessageBox.Cancel | QMessageBox.Yes
                )
                mb.setWindowModality(Qt.WindowModal)
                if mb.exec() == QMessageBox.Cancel:
                    return

            # initialize dialect based on selected extension
            if selected_filter in formats[:-1]:
                filter_idx = formats.index(selected_filter)
                if filter_idx == 0:
                    dialect = csv.excel()
                elif filter_idx == 1:
                    dialect = csv.excel_tab()
                else:
                    dialect = csv.excel_tab()
                header = True
            else:
                try:
                    dialect, header = sniff_csv_with_path(path)
                except Exception:  # pylint: disable=broad-except
                    dialect, header = csv.excel(), True

            options = None
            # Search for path in history.
            # If found use the stored params to initialize the import dialog
            items = self.itemsFromSettings()
            idx = index_where(items, lambda t: samepath(t[0], path))
            if idx is not None:
                _, options_ = items[idx]
                if options_ is not None:
                    options = options_

            if options is None:
                if not header:
                    rowspec = []
                else:
                    rowspec = [(range(0, 1), RowSpec.Header)]
                options = Options(
                    encoding="utf-8", dialect=dialect, rowspec=rowspec)

            dlg = CSVImportDialog(
                self, windowTitle="Import Options", sizeGripEnabled=True)
            dlg.setWindowModality(Qt.WindowModal)
            dlg.setPath(path)
            dlg.setOptions(options)
            status = dlg.exec_()
            dlg.deleteLater()
            if status == QDialog.Accepted:
                self.set_selected_file(path, dlg.options())
    def requestWrite(self, nodes, file_name = None, limit_mimetypes = None, file_handler = None, **kwargs):
        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        # Set up and display file dialog
        dialog = QFileDialog()

        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None

        if "preferred_mimetypes" in kwargs and kwargs["preferred_mimetypes"] is not None:
            preferred_mimetypes = kwargs["preferred_mimetypes"]
        else:
            preferred_mimetypes = Application.getInstance().getPreferences().getValue("local_file/last_used_type")
        preferred_mimetype_list = preferred_mimetypes.split(";")

        if not file_handler:
            file_handler = Application.getInstance().getMeshFileHandler()

        file_types = file_handler.getSupportedFileTypesWrite()

        file_types.sort(key = lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(filter(lambda i: i["mime_type"] in limit_mimetypes, file_types))

        file_types = [ft for ft in file_types if not ft["hide_in_file_dialog"]]

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:warning", "There are no file types available to write with!"))

        # Find the first available preferred mime type
        preferred_mimetype = None
        for mime_type in preferred_mimetype_list:
            if any(ft["mime_type"] == mime_type for ft in file_types):
                preferred_mimetype = mime_type
                break

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"], item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if preferred_mimetype == item["mime_type"]:
                selected_filter = type_filter
                if file_name:
                    file_name += "." + item["extension"]

        # CURA-6411: This code needs to be before dialog.selectFile and the filters, because otherwise in macOS (for some reason) the setDirectory call doesn't work.
        stored_directory = Application.getInstance().getPreferences().getValue("local_file/dialog_save_path")
        dialog.setDirectory(stored_directory)

        # Add the file name before adding the extension to the dialog
        if file_name is not None:
            dialog.selectFile(file_name)

        dialog.setNameFilters(filters)
        if selected_filter is not None:
            dialog.selectNameFilter(selected_filter)

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        save_path = dialog.directory().absolutePath()
        Application.getInstance().getPreferences().setValue("local_file/dialog_save_path", save_path)

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Application.getInstance().getPreferences().setValue("local_file/last_used_type", selected_type["mime_type"])

        # Get file name from file dialog
        file_name = dialog.selectedFiles()[0]
        Logger.log("d", "Writing to [%s]..." % file_name)
        
        if os.path.exists(file_name):
            result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"), catalog.i18nc("@label Don't translate the XML tag <filename>!", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)

        # Actually writing file
        if file_handler:
            file_writer = file_handler.getWriter(selected_type["id"])
        else:
            file_writer = Application.getInstance().getMeshFileHandler().getWriter(selected_type["id"])

        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode", file_name)
                stream = open(file_name, "wt", encoding = "utf-8")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode", file_name)
                stream = open(file_name, "wb")
            else:
                Logger.log("e", "Unrecognised OutputMode.")
                return None

            job = WriteFileJob(file_writer, stream, nodes, mode)
            job.setFileName(file_name)
            job.setAddToRecentFiles(True)  # The file will be added into the "recent files" list upon success
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(catalog.i18nc("@info:progress Don't translate the XML tags <filename>!", "Saving to <filename>{0}</filename>").format(file_name),
                              0, False, -1 , catalog.i18nc("@info:title", "Saving"))
            message.show()

            job.setMessage(message)
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(catalog.i18nc("@info:status Don't translate the XML tags <filename>!", "Permission denied when trying to save <filename>{0}</filename>").format(file_name)) from e
        except OSError as e:
            Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format()) from e
    def requestWrite(self,
                     nodes,
                     file_name=None,
                     limit_mimetypes=None,
                     file_handler=None):
        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        dialog = QFileDialog()

        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None
        last_used_type = Preferences.getInstance().getValue(
            "local_file/last_used_type")

        if not file_handler:
            file_handler = Application.getInstance().getMeshFileHandler()

        file_types = file_handler.getSupportedFileTypesWrite()

        file_types.sort(key=lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(
                filter(lambda i: i["mime_type"] in limit_mimetypes,
                       file_types))

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError()

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"],
                                               item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if last_used_type == item["mime_type"]:
                selected_filter = type_filter
                if file_name:
                    file_name += "." + item["extension"]

        dialog.setNameFilters(filters)
        if selected_filter is not None:
            dialog.selectNameFilter(selected_filter)

        if file_name is not None:
            dialog.selectFile(file_name)

        stored_directory = Preferences.getInstance().getValue(
            "local_file/dialog_save_path")
        dialog.setDirectory(stored_directory)

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        save_path = dialog.directory().absolutePath()
        Preferences.getInstance().setValue("local_file/dialog_save_path",
                                           save_path)

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Preferences.getInstance().setValue("local_file/last_used_type",
                                           selected_type["mime_type"])

        file_name = dialog.selectedFiles()[0]

        if os.path.exists(file_name):
            result = QMessageBox.question(
                None, catalog.i18nc("@title:window", "File Already Exists"),
                catalog.i18nc(
                    "@label",
                    "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?"
                ).format(file_name))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)

        if file_handler:
            file_writer = file_handler.getWriter(selected_type["id"])
        else:
            file_writer = Application.getInstance().getMeshFileHandler(
            ).getWriter(selected_type["id"])

        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode",
                           file_name)
                stream = open(file_name, "wt", encoding="utf-8")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode",
                           file_name)
                stream = open(file_name, "wb")

            job = WriteFileJob(file_writer, stream, nodes, mode)
            job.setFileName(file_name)
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(
                catalog.i18nc(
                    "@info:progress",
                    "Saving to <filename>{0}</filename>").format(file_name), 0,
                False, -1)
            message.show()

            job._message = message
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(
                catalog.i18nc(
                    "@info:status",
                    "Permission denied when trying to save <filename>{0}</filename>"
                ).format(file_name)) from e
        except OSError as e:
            Logger.log("e",
                       "Operating system would not let us write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(
                catalog.i18nc(
                    "@info:status",
                    "Could not save to <filename>{0}</filename>: <message>{1}</message>"
                ).format()) from e
Beispiel #23
0
    def requestWrite(self,
                     nodes,
                     file_name=None,
                     limit_mimetypes=None,
                     file_handler=None,
                     **kwargs):
        """Request the specified nodes to be written to a file.

        :param nodes: A collection of scene nodes that should be written to the
        file.
        :param file_name: A suggestion for the file name to write
        to. Can be freely ignored if providing a file name makes no sense.
        :param limit_mimetypes: Should we limit the available MIME types to the
        MIME types available to the currently active machine?
        :param kwargs: Keyword arguments.
        """

        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        # Set up and display file dialog
        dialog = QFileDialog()

        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to Disk"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None

        if "preferred_mimetypes" in kwargs and kwargs[
                "preferred_mimetypes"] is not None:
            preferred_mimetypes = kwargs["preferred_mimetypes"]
        else:
            preferred_mimetypes = Application.getInstance().getPreferences(
            ).getValue("local_file/last_used_type")
        preferred_mimetype_list = preferred_mimetypes.split(";")

        if not file_handler:
            file_handler = Application.getInstance().getMeshFileHandler()

        file_types = file_handler.getSupportedFileTypesWrite()

        file_types.sort(key=lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(
                filter(lambda i: i["mime_type"] in limit_mimetypes,
                       file_types))

        file_types = [ft for ft in file_types if not ft["hide_in_file_dialog"]]

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError(
                catalog.i18nc(
                    "@info:warning",
                    "There are no file types available to write with!"))

        # Find the first available preferred mime type
        preferred_mimetype = None
        for mime_type in preferred_mimetype_list:
            if any(ft["mime_type"] == mime_type for ft in file_types):
                preferred_mimetype = mime_type
                break

        extension_added = False
        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"],
                                               item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if preferred_mimetype == item["mime_type"]:
                selected_filter = type_filter
                if file_name and not extension_added:
                    extension_added = True
                    file_name += "." + item["extension"]

        # CURA-6411: This code needs to be before dialog.selectFile and the filters, because otherwise in macOS (for some reason) the setDirectory call doesn't work.
        stored_directory = Application.getInstance().getPreferences().getValue(
            "local_file/dialog_save_path")
        if stored_directory and stored_directory != "":
            dialog.setDirectory(stored_directory)

        # Add the file name before adding the extension to the dialog
        if file_name is not None:
            dialog.selectFile(file_name)

        dialog.setNameFilters(filters)
        if selected_filter is not None:
            dialog.selectNameFilter(selected_filter)

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        save_path = dialog.directory().absolutePath()
        Application.getInstance().getPreferences().setValue(
            "local_file/dialog_save_path", save_path)

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Application.getInstance().getPreferences().setValue(
            "local_file/last_used_type", selected_type["mime_type"])

        # Get file name from file dialog
        file_name = dialog.selectedFiles()[0]
        Logger.log("d", "Writing to [%s]..." % file_name)

        if os.path.exists(file_name):
            result = QMessageBox.question(
                None, catalog.i18nc("@title:window", "File Already Exists"),
                catalog.i18nc(
                    "@label Don't translate the XML tag <filename>!",
                    "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?"
                ).format(file_name))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)

        # Actually writing file
        if file_handler:
            file_writer = file_handler.getWriter(selected_type["id"])
        else:
            file_writer = Application.getInstance().getMeshFileHandler(
            ).getWriter(selected_type["id"])

        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode",
                           file_name)
                stream = open(file_name, "wt", encoding="utf-8")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode",
                           file_name)
                stream = open(file_name, "wb")
            else:
                Logger.log("e", "Unrecognised OutputMode.")
                return None

            job = WriteFileJob(file_writer, stream, nodes, mode)
            job.setFileName(file_name)
            job.setAddToRecentFiles(
                True
            )  # The file will be added into the "recent files" list upon success
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(
                catalog.i18nc(
                    "@info:progress Don't translate the XML tags <filename>!",
                    "Saving to <filename>{0}</filename>").format(file_name), 0,
                False, -1, catalog.i18nc("@info:title", "Saving"))
            message.show()

            job.setMessage(message)
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(
                catalog.i18nc(
                    "@info:status Don't translate the XML tags <filename>!",
                    "Permission denied when trying to save <filename>{0}</filename>"
                ).format(file_name)) from e
        except OSError as e:
            Logger.log("e",
                       "Operating system would not let us write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(
                catalog.i18nc(
                    "@info:status Don't translate the XML tags <filename> or <message>!",
                    "Could not save to <filename>{0}</filename>: <message>{1}</message>"
                ).format(file_name, str(e))) from e
    def requestWrite(self,
                     nodes,
                     file_name=None,
                     limit_mimetypes=None,
                     file_handler=None,
                     **kwargs):
        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

            # Set up and display file dialog
        dialog = QFileDialog()

        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None
        last_used_type = self._preferences.getValue(
            "local_file/last_used_type")

        if not file_handler:
            file_handler = Application.getInstance().getMeshFileHandler()

        file_types = file_handler.getSupportedFileTypesWrite()

        file_types.sort(key=lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(
                filter(lambda i: i["mime_type"] in limit_mimetypes,
                       file_types))

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError()

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"],
                                               item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if last_used_type == item["mime_type"]:
                selected_filter = type_filter
                if file_name:
                    file_name += "." + item["extension"]

        dialog.setNameFilters(filters)
        if selected_filter is not None:
            dialog.selectNameFilter(selected_filter)

        if file_name is not None:
            dialog.selectFile(file_name)

        stored_directory = self._preferences.getValue(
            "local_file/dialog_save_path")
        dialog.setDirectory(stored_directory)

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        save_path = dialog.directory().absolutePath()
        self._preferences.setValue("local_file/dialog_save_path", save_path)

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        self._preferences.setValue("local_file/last_used_type",
                                   selected_type["mime_type"])

        # Get file name from file dialog
        file_name = dialog.selectedFiles()[0]
        active_build_plate = Application.getInstance().getMultiBuildPlateModel(
        ).activeBuildPlate
        scene = Application.getInstance().getController().getScene()
        gcode_dict = getattr(scene, "gcode_dict", None)
        if not gcode_dict:
            return
        _gcode = gcode_dict.get(active_build_plate, None)
        self.save_gcode(file_name, _gcode)
Beispiel #25
0
def get_file(window, mode):
    """Prompt user for and return filename"""

    # Load data
    if mode == 0:
        dialog = QFileDialog(
            window,
            _translate("MainWindow", "Open File"),
            "",
            _translate("MainWindow",
                       "DB Design File (*.fdcover);;All files (*.*)"),
            options=0)
        dialog.setFileMode(QFileDialog.ExistingFile)

    # Load schema (csv)
    elif mode == 1:
        dialog = QFileDialog(
            window,
            _translate("MainWindow", "Open File"),
            "",
            _translate("MainWindow",
                       "Comma-separated file (*.csv);;All files (*.*)"),
            options=0)
        dialog.setFileMode(QFileDialog.ExistingFile)

    # Load schema (db)
    elif mode == 2:
        dialog = QFileDialog(window,
                             _translate("MainWindow", "Open File"),
                             "",
                             _translate(
                                 "MainWindow",
                                 "Sqlite Database (*.db);;All files (*.*)"),
                             options=0)
        dialog.setFileMode(QFileDialog.ExistingFile)

    # Load character-delimited
    elif mode == 3:
        dialog = QFileDialog(window,
                             _translate("MainWindow", "Open File"),
                             "",
                             _translate("MainWindow", "All files (*.*)"),
                             options=0)
        dialog.setFileMode(QFileDialog.ExistingFile)

    # Save data
    elif mode == 4:
        dialog = QFileDialog(
            window,
            _translate("MainWindow", "Save File"),
            "",
            _translate(
                "MainWindow",
                "DB Design File (*.fdcover);;Plain text file (*.txt);;All files (*.*)"
            ),
            options=0)
        dialog.setFileMode(QFileDialog.AnyFile)

    dialog.text = lambda x=dialog.result: dialog.selectedFiles()[0] if x(
    ) else None
    dialog.accepted.connect(lambda: dialog.text)
    dialog.exec_()
    if mode == 4:
        ext = dialog.selectedNameFilter()[:-1].split('*')[1]
    else:
        ext = ""
    fileName = dialog.text()
    if fileName is not None:
        fileName += ext
    return fileName
Beispiel #26
0
       dialog.setNameFilter(filter)
>>>>>>>-b1ae517
 dialog.setViewMode(QFileDialog.Detail)
    dialog.setDirectory(RECENT_PATH)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setWindowTitle(caption)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.selectFile(initial_name)

<<<    if dialog.exec():
        filename = dialog.selectedFiles()[0]
>>>>>>>+HEAD
====
       if (dialog.exec()):
        filename = dialog.selectedFiles()[0]
        filter = dialog.selectedNameFilter()
        ext = filter[filter.index('*'):filter.index(')')][1:]
        if not os.path.exists(filename) and len(ext) > 0 and not filename.endswith(ext):
            filename += ext
>>>>>>>-b1ae517
  if filename:
        RECENT_PATH = os.path.split(filename)[0]

    return filename


<<<def save_data_dialog(signal_name: str, data, wav_only=False, parent=None) -> str:
    filename = get_save_file_name(signal_name, wav_only)
>>>>>>>+HEAD
====
defdef save_data_dialog(signalname: str, data, wav_only=False, parent=None) -> str:
    def requestWrite(self, node, file_name = None, limit_mimetypes = None):
        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        dialog = QFileDialog()
        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None
        last_used_type = Preferences.getInstance().getValue("local_file/last_used_type")

        file_types = Application.getInstance().getMeshFileHandler().getSupportedFileTypesWrite()
        file_types.sort(key = lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(filter(lambda i: i["mime_type"] in limit_mimetypes, file_types))

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError()

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"], item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if last_used_type == item["mime_type"]:
                selected_filter = type_filter
                if file_name:
                    file_name += "." + item["extension"]

        dialog.setNameFilters(filters)
        if selected_filter != None:
            dialog.selectNameFilter(selected_filter)

        if file_name != None:
            dialog.selectFile(file_name)

        dialog.restoreState(Preferences.getInstance().getValue("local_file/dialog_state").encode())

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        Preferences.getInstance().setValue("local_file/dialog_state", str(dialog.saveState()))

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Preferences.getInstance().setValue("local_file/last_used_type", selected_type["mime_type"])

        file_name = dialog.selectedFiles()[0]

        if os.path.exists(file_name):
            result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"), catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)
        mesh_writer = Application.getInstance().getMeshFileHandler().getWriter(selected_type["id"])
        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode", file_name)
                stream = open(file_name, "wt")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode", file_name)
                stream = open(file_name, "wb")

            job = WriteMeshJob(mesh_writer, stream, node, mode)
            job.setFileName(file_name)
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(catalog.i18nc("@info:progress", "Saving to <filename>{0}</filename>").format(file_name), 0, False, -1)
            message.show()

            job._message = message
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(catalog.i18nc("@info:status", "Permission denied when trying to save <filename>{0}</filename>").format(file_name)) from e
        except OSError as e:
            Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format()) from e
    def browse(self):
        """
        Open a file dialog and select a user specified file.
        """
        formats = [
            "Text - comma separated (*.csv, *)",
            "Text - tab separated (*.tsv, *)",
            "Text - all files (*)"
        ]

        dlg = QFileDialog(
            self, windowTitle="Open Data File",
            acceptMode=QFileDialog.AcceptOpen,
            fileMode=QFileDialog.ExistingFile
        )
        dlg.setNameFilters(formats)
        state = self.dialog_state
        lastdir = state.get("directory", "")
        lastfilter = state.get("filter", "")

        if lastdir and os.path.isdir(lastdir):
            dlg.setDirectory(lastdir)
        if lastfilter:
            dlg.selectNameFilter(lastfilter)

        status = dlg.exec_()
        dlg.deleteLater()
        if status == QFileDialog.Accepted:
            self.dialog_state["directory"] = dlg.directory().absolutePath()
            self.dialog_state["filter"] = dlg.selectedNameFilter()

            selected_filter = dlg.selectedNameFilter()
            path = dlg.selectedFiles()[0]
            # pre-flight check; try to determine the nature of the file
            mtype = _mime_type_for_path(path)
            if not mtype.inherits("text/plain"):
                mb = QMessageBox(
                    parent=self,
                    windowTitle="",
                    icon=QMessageBox.Question,
                    text="The '{basename}' may be a binary file.\n"
                         "Are you sure you want to continue?".format(
                            basename=os.path.basename(path)),
                    standardButtons=QMessageBox.Cancel | QMessageBox.Yes
                )
                mb.setWindowModality(Qt.WindowModal)
                if mb.exec() == QMessageBox.Cancel:
                    return

            # initialize dialect based on selected extension
            if selected_filter in formats[:-1]:
                filter_idx = formats.index(selected_filter)
                if filter_idx == 0:
                    dialect = csv.excel()
                elif filter_idx == 1:
                    dialect = csv.excel_tab()
                else:
                    dialect = csv.excel_tab()
                header = True
            else:
                try:
                    dialect, header = sniff_csv_with_path(path)
                except Exception:
                    dialect, header = csv.excel(), True

            options = None
            # Search for path in history.
            # If found use the stored params to initialize the import dialog
            items = self.itemsFromSettings()
            idx = index_where(items, lambda t: samepath(t[0], path))
            if idx is not None:
                _, options_ = items[idx]
                if options_ is not None:
                    options = options_

            if options is None:
                if not header:
                    rowspec = []
                else:
                    rowspec = [(range(0, 1), RowSpec.Header)]
                options = Options(
                    encoding="utf-8", dialect=dialect, rowspec=rowspec)

            dlg = CSVImportDialog(
                self, windowTitle="Import Options",  sizeGripEnabled=True)
            dlg.setWindowModality(Qt.WindowModal)
            dlg.setPath(path)
            dlg.setOptions(options)
            status = dlg.exec_()
            dlg.deleteLater()
            if status == QDialog.Accepted:
                self.set_selected_file(path, dlg.options())
Beispiel #29
0
    def requestWrite(self,
                     nodes,
                     file_name=None,
                     limit_mimetypes=None,
                     file_handler=None,
                     **kwargs):
        application = cast(CuraApplication, Application.getInstance())
        machine_manager = application.getMachineManager()
        global_stack = machine_manager.activeMachine

        filename_format = Application.getInstance().getPreferences().getValue(
            "gcode_filename_format/filename_format")

        Logger.log("d", "filename_format = %s", filename_format)

        if filename_format is "":
            filename_format = DEFAULT_FILENAME_FORMAT

        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        self.getModifiedPrintSettings(application, global_stack)

        dialog = QFileDialog()

        dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None

        if "preferred_mimetypes" in kwargs and kwargs[
                "preferred_mimetypes"] is not None:
            preferred_mimetypes = kwargs["preferred_mimetypes"]
        else:
            preferred_mimetypes = Application.getInstance().getPreferences(
            ).getValue("gcode_filename_format/last_used_type")
        preferred_mimetype_list = preferred_mimetypes.split(";")

        if not file_handler:
            file_handler = Application.getInstance().getMeshFileHandler()

        file_types = file_handler.getSupportedFileTypesWrite()

        file_types.sort(key=lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(
                filter(lambda i: i["mime_type"] in limit_mimetypes,
                       file_types))

        file_types = [ft for ft in file_types if not ft["hide_in_file_dialog"]]

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError(
                catalog.i18nc(
                    "@info:warning",
                    "There are no file types available to write with!"))

        preferred_mimetype = None
        for mime_type in preferred_mimetype_list:
            if any(ft["mime_type"] == mime_type for ft in file_types):
                preferred_mimetype = mime_type
                break

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"],
                                               item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if preferred_mimetype == item["mime_type"]:
                selected_filter = type_filter
                file_name = self.parseFilenameFormat(filename_format,
                                                     file_name, application,
                                                     global_stack)
                #file_name += self.filenameTackOn(print_setting)
                if file_name:
                    file_name += "." + item["extension"]

        stored_directory = Application.getInstance().getPreferences().getValue(
            "gcode_filename_format/dialog_save_path")
        dialog.setDirectory(stored_directory)

        if file_name is not None:
            dialog.selectFile(file_name)

        dialog.setNameFilters(filters)
        if selected_filter is not None:
            dialog.selectNameFilter(selected_filter)

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        save_path = dialog.directory().absolutePath()
        Application.getInstance().getPreferences().setValue(
            "gcode_filename_format/dialog_save_path", save_path)

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Application.getInstance().getPreferences().setValue(
            "gcode_filename_format/last_used_type", selected_type["mime_type"])

        file_name = dialog.selectedFiles()[0]
        Logger.log("d", "Writing to [%s]..." % file_name)

        if os.path.exists(file_name):
            result = QMessageBox.question(
                None, catalog.i18nc("@title:window", "File Already Exists"),
                catalog.i18nc(
                    "@label Don't translate the XML tag <filename>!",
                    "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?"
                ).format(file_name))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)

        if file_handler:
            file_writer = file_handler.getWriter(selected_type["id"])
        else:
            file_writer = Application.getInstance().getMeshFileHandler(
            ).getWriter(selected_type["id"])

        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode",
                           file_name)
                stream = open(file_name, "wt", encoding="utf-8")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode",
                           file_name)
                stream = open(file_name, "wb")
            else:
                Logger.log("e", "Unrecognised OutputMode.")
                return None

            job = WriteFileJob(file_writer, stream, nodes, mode)
            job.setFileName(file_name)
            job.setAddToRecentFiles(True)
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(
                catalog.i18nc(
                    "@info:progress Don't translate the XML tags <filename>!",
                    "Saving to <filename>{0}</filename>").format(file_name), 0,
                False, -1, catalog.i18nc("@info:title", "Saving"))
            message.show()

            job.setMessage(message)
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(
                catalog.i18nc(
                    "@info:status Don't translate the XML tags <filename>!",
                    "Permission denied when trying to save <filename>{0}</filename>"
                ).format(file_name)) from e
        except OSError as e:
            Logger.log("e",
                       "Operating system would not let us write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(
                catalog.i18nc(
                    "@info:status Don't translate the XML tags <filename> or <message>!",
                    "Could not save to <filename>{0}</filename>: <message>{1}</message>"
                ).format()) from e
    def requestWrite(self,
                     nodes,
                     file_name=None,
                     limit_mimetypes=None,
                     file_handler=None,
                     **kwargs):
        if self._writing:
            raise OutputDeviceError.DeviceBusyError()

        # Set up and display file dialog
        dialog = QFileDialog()

        dialog.setWindowTitle(self._translations.get("save_file_window"))
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        # Ensure platform never ask for overwrite confirmation since we do this ourselves
        dialog.setOption(QFileDialog.DontConfirmOverwrite)

        if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ:
            dialog.setOption(QFileDialog.DontUseNativeDialog)

        filters = []
        mime_types = []
        selected_filter = None

        if "preferred_mimetypes" in kwargs and kwargs[
                "preferred_mimetypes"] is not None:
            preferred_mimetypes = kwargs["preferred_mimetypes"]
        else:
            preferred_mimetypes = Application.getInstance().getPreferences(
            ).getValue("local_file/last_used_type")
        preferred_mimetype_list = preferred_mimetypes.split(";")

        if not file_handler:
            file_handler = Application.getInstance().getMeshFileHandler()

        file_types = file_handler.getSupportedFileTypesWrite()

        file_types.sort(key=lambda k: k["description"])
        if limit_mimetypes:
            file_types = list(
                filter(lambda i: i["mime_type"] in limit_mimetypes,
                       file_types))

        file_types = [ft for ft in file_types if not ft["hide_in_file_dialog"]]

        if len(file_types) == 0:
            Logger.log("e", "There are no file types available to write with!")
            raise OutputDeviceError.WriteRequestFailedError(
                self._translations.get("no_file_warning"))

        # Find the first available preferred mime type
        preferred_mimetype = None
        for mime_type in preferred_mimetype_list:
            if any(ft["mime_type"] == mime_type for ft in file_types):
                preferred_mimetype = mime_type
                break

        for item in file_types:
            type_filter = "{0} (*.{1})".format(item["description"],
                                               item["extension"])
            filters.append(type_filter)
            mime_types.append(item["mime_type"])
            if preferred_mimetype == item["mime_type"]:
                selected_filter = type_filter
                if file_name:
                    file_name += "." + item["extension"]

        # CURA-6411: This code needs to be before dialog.selectFile and the filters, because otherwise in macOS (for some reason) the setDirectory call doesn't work.
        stored_directory = Application.getInstance().getPreferences().getValue(
            "local_file/dialog_save_path")
        dialog.setDirectory(stored_directory)

        # Add the file name before adding the extension to the dialog
        if file_name is not None:
            dialog.selectFile(file_name)

        dialog.setNameFilters(filters)
        if selected_filter is not None:
            dialog.selectNameFilter(selected_filter)

        if not dialog.exec_():
            raise OutputDeviceError.UserCanceledError()

        save_path = dialog.directory().absolutePath()
        Application.getInstance().getPreferences().setValue(
            "local_file/dialog_save_path", save_path)

        selected_type = file_types[filters.index(dialog.selectedNameFilter())]
        Application.getInstance().getPreferences().setValue(
            "local_file/last_used_type", selected_type["mime_type"])

        # Get file name from file dialog
        file_name = dialog.selectedFiles()[0]
        Logger.log("d", "Writing to [%s]..." % file_name)

        if os.path.exists(file_name):
            result = QMessageBox.question(
                None,
                self._translations.get("file_exists_window").format(
                    file_name[file_name.rfind("/") + 1:]),
                self._translations.get("file_overwrite_label").format(
                    file_name[file_name.rfind("/") + 1:]))
            if result == QMessageBox.No:
                raise OutputDeviceError.UserCanceledError()

        self.writeStarted.emit(self)

        # Actually writing file
        if file_handler:
            file_writer = file_handler.getWriter(selected_type["id"])
        else:
            file_writer = Application.getInstance().getMeshFileHandler(
            ).getWriter(selected_type["id"])

        try:
            mode = selected_type["mode"]
            if mode == MeshWriter.OutputMode.TextMode:
                Logger.log("d", "Writing to Local File %s in text mode",
                           file_name)
                stream = open(file_name, "wt", encoding="utf-8")
            elif mode == MeshWriter.OutputMode.BinaryMode:
                Logger.log("d", "Writing to Local File %s in binary mode",
                           file_name)
                stream = open(file_name, "wb")
            else:
                Logger.log("e", "Unrecognised OutputMode.")
                return None

            # Adding screeshot section
            screenshot_string = utils.add_screenshot()

            if screenshot_string != "":
                stream.write(screenshot_string)
            # End of screeshot section

            job = WriteFileJob(file_writer, stream, nodes, mode)
            job.setFileName(file_name)
            # The file will be added into the "recent files" list upon success
            job.setAddToRecentFiles(True)
            job.progress.connect(self._onJobProgress)
            job.finished.connect(self._onWriteJobFinished)

            message = Message(
                self._translations.get("file_saving_progress").format(
                    file_name), 0, False, -1,
                self._translations.get("file_saving_title"))
            message.show()

            job.setMessage(message)
            self._writing = True
            job.start()
        except PermissionError as e:
            Logger.log("e", "Permission denied when trying to write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.PermissionDeniedError(
                self._translations.get("permission_denied").format(
                    file_name)) from e
        except OSError as e:
            Logger.log("e",
                       "Operating system would not let us write to %s: %s",
                       file_name, str(e))
            raise OutputDeviceError.WriteRequestFailedError(
                self._translations.get("permission_denied2").format(
                    file_name, str(e))) from e