Example #1
0
 def _load(self):
     if not self.methodWidget.status:
         self.methodWidget._build()
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     filename = os.path.join(self.methodWidget.folder,
                             self.methodWidget.label + '.init')
     dialog.selectFile(filename)
     fname, _ = dialog.getOpenFileName(self,
                                       'Load initial values',
                                       filename,
                                       "All Files (*);;PyPHS initial values (*.init)",
                                       "PyPHS initial values (*.init)",
                                       options=options)
     if not fname == '':
         with open(fname, 'r') as f:
             for name in self._names:
                 line = f.readline()
                 if len(line) > 0:
                     values = list(map(float, line.split(' ')))
                     if not len(values) == len(geteval(self.method, name)):
                         text = 'Initial values shape error: ' + name
                         raise ValueError(text)
                 else:
                     values = []
                 self.inits[name] = values
     self.modifSig.sig.emit()
Example #2
0
def writeSct(sctPars, sctfile):
    """
    Write a *.sct file from a dictionary.
    """
    fd = QFileDialog(None, "Save updated .sct file")
    fd.setLabelText(QFileDialog.Accept, "Export as")
    fd.setNameFilters(["Scan description (*.sct)", "All Files (*)"])
    fd.setOptions(QFileDialog.DontUseNativeDialog)
    fd.setViewMode(QFileDialog.List)
    fd.selectFile(sctfile)
    if fd.exec():
        #fd.getSaveFileName(directory=sctfile)
        filenames = fd.selectedFiles()
        filename = filenames[0]
        if filename[-4:] != '.sct':
            filename += '.sct'
        print("Exporting scan description to file: ", filename)
        with io.open(filename, mode='w') as f:
            for key in sctPars.keys():
                if sctPars[key] != "":
                    #print(sctPars[key])
                    f.write("{0:25s} #{1:s}\n".format(sctPars[key],
                                                      key.upper()))
        print('File ' + filename + ' exported.')
        msg = "File " + filename + ' exported.\n'
    else:
        msg = 'Updated .sct file not saved.\n'
    return msg
Example #3
0
    def handlebuttonbrowse(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        dlg.setLabelText(QFileDialog.Accept, "Save comparison")
        dlg.setDefaultSuffix(self.expected_extension.strip('.'))

        inputfilename = self.settings.get_object('inputfilename')
        dirname = os.path.dirname(inputfilename)
        suggested_filename = os.path.splitext(
            os.path.basename(inputfilename))[0] + self.expected_extension
        dlg.setDirectory(dirname)
        dlg.selectFile(suggested_filename)

        filternames = [
            "%s files (*%s)" % (ext.strip('.'), ext)
            for ext in [self.expected_extension]
        ]
        filternames += ["all files (*)"]
        dlg.setNameFilters(filternames)

        if dlg.exec_():
            self.outputfilename = str(dlg.selectedFiles()[0])
        self.settings.register('outputfilename', self)
        self.outputfile.setText(shorten_path(self.outputfilename))

        if self.outputfilename:
            self.compare()
            self.issaved = True

            print('Complete!')

            self.buttonshow.setEnabled(True)
Example #4
0
def get_save_file_name(initial_name: str, wav_only=False, caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        name_filter = "Complex files (*.complex);;Complex16 files (2 unsigned int8) " \
                 "(*.complex16u);;Complex16 files (2 signed int8) (*.complex16s);;" \
                 "Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            name_filter = "wav files (*.wav);;all files (*)"
    elif caption == "Save fuzz profile":
        name_filter = "Fuzzfiles (*.fuzz);;All files (*)"
    elif caption == "Save encoding":
        name_filter = ""
    else:
        name_filter = "Protocols (*.proto);;All files (*)"

    filename = None
    dialog = QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setNameFilter(name_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]

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

    return filename
Example #5
0
 def _writejuce(self):
     if not self.status:
         self.methodWidget._build()
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     dialog.selectFile(self.folder)
     folder = dialog.getExistingDirectory(self,
                                          "Save JUCE snippets files in...",
                                          self.folder,
                                          options=options)
     if not folder == '':
         inputs = []
         for i, u in enumerate(self.method.u):
             if self.io.io['u'][i]:
                 inputs.append(u)
         outputs = []
         for i, y in enumerate(self.method.y):
             if self.io.io['y'][i]:
                 outputs.append(y)
         juce.fx.method2jucefx(self.method,
                               path=folder,
                               io=(inputs, outputs),
                               inits=self.inits.inits,
                               config=self.parameters)
Example #6
0
    def _writefaust(self):
        if not self.status:
            self.methodWidget._build()
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        dialog = QFileDialog()
        filename = os.path.join(self.folder, self.method.label + '.dsp')
        dialog.selectFile(filename)
        fname, _ = dialog.getSaveFileName(self,
                                          "Save FAUST code as...",
                                          filename,
                                          "All Files (*);;FAUST code (*.dsp)",
                                          "FAUST code (*.dsp)",
                                          options=options)
        if not fname == '':
            if not fname.endswith('.dsp'):
                fname += '.dsp'
            print('FAUST: write ' + fname)
            methodIMat = faust.MethodInvMat(self.method._core,
                                            self.methodWidget.parameters,
                                            self.method.label)

            faust.write_faust_fx(methodIMat,
                                 path=fname,
                                 inputs=self.inout[0],
                                 outputs=self.inout[1],
                                 inits=self.inits.inits,
                                 nIt=self.parameters['maxit'])
Example #7
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
Example #8
0
 def saveRotatedFits(self, name_orig):
     """ Save the downloaded FITS image """
     
     filename, file_extension = os.path.splitext(name_orig)
     #fileroot = os.path.basename(filename)
     #print('file root is ', fileroot)
     print('Saving ',filename+'_NE.fits')
     # Dialog to save file
     fd = QFileDialog()
     fd.setLabelText(QFileDialog.Accept, "Save as")
     fd.setNameFilters(["Fits Files (*.fits)","All Files (*)"])
     fd.setOptions(QFileDialog.DontUseNativeDialog)
     fd.setViewMode(QFileDialog.List)
     fd.selectFile(filename+'_NE.fits')        
     if (fd.exec()):
         fileName = fd.selectedFiles()
         outfile = fileName[0]
         filename, file_extension = os.path.splitext(outfile)
         # basename = os.path.basename(filename)            
         # Primary header
         image = self.data
         wcs   = self.wcs
         header = wcs.to_header()
         header.remove('WCSAXES')
         header['INSTRUME'] = (self.source, 'Instrument')
         hdu = fits.PrimaryHDU(image)
         hdu.header.extend(header)
         hdul = fits.HDUList([hdu])
         hdul.writeto(outfile,overwrite=True) # clobber true  allows rewriting
         hdul.close()
Example #9
0
def get_save_file_name(initial_name: str, wav_only=False, caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        filter = "Complex files (*.complex);;Complex16 files (2 unsigned int8) (*.complex16u);;Complex16 files (2 signed int8) (*.complex16s);;Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            filter = "wav files (*.wav);;all files (*)"
    elif caption == "Save fuzz profile":
        filter = "Fuzzfiles (*.fuzz);;All files (*)"
    elif caption == "Save encoding":
        filter = ""
    else:
        filter = "Protocols (*.proto);;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]

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

    return filename
Example #10
0
 def _save(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     filename = os.path.join(self.methodWidget.folder,
                             self.methodWidget.label + '.io')
     dialog.selectFile(filename)
     fname, _ = dialog.getSaveFileName(
         self,
         "Save initial values file as...",
         filename,
         "All Files (*);;PyPHS input/output selection (*.io)",
         "PyPHS input/output selection (*.io)",
         options=options)
     if not fname == '':
         if not fname[-3:] == '.io':
             fname += '.io'
         try:
             os.remove(fname)
         except:
             pass
         with open(fname, 'w') as f:
             for name in self._names:
                 line = ' '.join(list(map(str, self.io[name]))) + '\n'
                 f.write(line)
Example #11
0
 def save_released(self):
     """Action performned on save button released."""
     dialog = QFileDialog(parent=self)
     dialog.setFileMode(QFileDialog.AnyFile)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.setNameFilter("Text (*.txt)")
     dialog.selectFile("word.txt")
     if dialog.exec_():
         self.save_text(dialog.selectedFiles()[0])
Example #12
0
 def _save_dialog(self):
     file = "{}{}".format(self.model_file.text().split(".")[0], ".json")
     dialog = QFileDialog(self, 'Save Config', directory=os.getcwd())
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.selectFile(file)
     if dialog.exec_() == QDialog.Accepted:
         self._save(file=dialog.selectedFiles()[0])
         return True
     return False
Example #13
0
def cif_file_save_dialog(filename: str) -> str:
    """
    Returns a cif file name from a file dialog.
    """
    dialog = QFileDialog(filter="CIF file (*.cif)", caption='Save .cif File')
    dialog.setDefaultSuffix('.cif')
    dialog.selectFile(filename)
    filename, _ = dialog.getSaveFileName(None, 'Select file name', filename)
    return filename
Example #14
0
 def read_cfg(self):
     dialog = QFileDialog(self, 'Read configuration settings', '.', '*.ini')
     dialog.setDefaultSuffix('ini')
     dialog.selectFile('muoscope.ini')
     dialog.setAcceptMode(QFileDialog.AcceptOpen)
     if dialog.exec() == QDialog.Accepted:
         name = dialog.selectedFiles()
         settings = QSettings(name[0], QSettings.IniFormat)
         self.read_cfg_settings(settings)
Example #15
0
 def write_cfg(self):
   dialog = QFileDialog(self, 'Write configuration settings', '.', '*.ini')
   dialog.setDefaultSuffix('ini')
   dialog.selectFile('vna.ini')
   dialog.setAcceptMode(QFileDialog.AcceptSave)
   dialog.setOptions(QFileDialog.DontConfirmOverwrite)
   if dialog.exec() == QDialog.Accepted:
     name = dialog.selectedFiles()
     settings = QSettings(name[0], QSettings.IniFormat)
     self.write_cfg_settings(settings)
Example #16
0
 def write_cfg(self):
   dialog = QFileDialog(self, 'Write configuration settings', '.', '*.ini')
   dialog.setDefaultSuffix('ini')
   dialog.selectFile('vna.ini')
   dialog.setAcceptMode(QFileDialog.AcceptSave)
   dialog.setOptions(QFileDialog.DontConfirmOverwrite)
   if dialog.exec() == QDialog.Accepted:
     name = dialog.selectedFiles()
     settings = QSettings(name[0], QSettings.IniFormat)
     self.write_cfg_settings(settings)
Example #17
0
 def read_cfg(self):
   dialog = QFileDialog(self, 'Read configuration settings', '.', '*.ini')
   dialog.setDefaultSuffix('ini')
   dialog.selectFile('vna.ini')
   dialog.setAcceptMode(QFileDialog.AcceptOpen)
   if dialog.exec() == QDialog.Accepted:
     name = dialog.selectedFiles()
     settings = QSettings(name[0], QSettings.IniFormat)
     self.read_cfg_settings(settings)
     window.update_tab()
Example #18
0
 def save_game(self):
     fileDialog = QFileDialog()
     fileDialog.setWindowTitle("保存为")
     fileDialog.setAcceptMode(QFileDialog.AcceptSave)
     fileDialog.setFileMode(QFileDialog.AnyFile)
     fileDialog.setViewMode(QFileDialog.Detail)
     fileDialog.setDirectory(QDir.homePath())
     fileDialog.selectFile("DotsAndBoxesRecord.dbr")
     if (fileDialog.exec() == QDialog.Accepted):
         path = fileDialog.selectedFiles()[0]
         self._dots_and_boxes.save_to_file(path)
     fileDialog.show()
    def display(self):
        dialog = QFileDialog(
                            parent=self.__parentWidget,
                            caption=self.__tr("Select location to save debugging information"),
                            directory=QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0],
                            filter="ZIP files (*.zip)",
                            )

        dialog.selectFile(time.strftime("MO2_Debug_Info_%Y%m%d_%H%M%S.zip"))
        if(dialog.exec()):
            with ZipFile(dialog.selectedFiles()[0], 'w', ZIP_LZMA) as file_zip:
                self.getProcesses(file_zip)
                self.getServices(file_zip)
Example #20
0
    def save_image(self):
        im = pil_Image.fromarray(self.screen_img)

        save_dialog = QFileDialog(self)
        save_dialog.selectFile('pysigview_screenshot.png')
        save_path = save_dialog.getSaveFileName(self, 'Save File',
                                                get_home_dir(),
                                                "Images (*.png *.tiff *.jpg)")
        path = save_path[0]
        if not any([x for x in ['.png', '.tiff', '.jpg'] if x in path]):
            path += '.png'
        im.save(path)
        return
Example #21
0
    def handlebuttonbrowse(self):
        dlg = QFileDialog()
        dlg.setNameFilters(["%s files (*%s)" % ('odml', '.odml'),
                            "%s files (*%s)" % ('xml', '.xml')])
        fn = self.settings.get_object('inputfilename')
        if fn:
            dlg.selectFile(fn)

        if dlg.exec_():
            self.inputfilename = str(dlg.selectedFiles()[0])

        self.settings.register('inputfilename', self, useconfig=False)
        self.inputfile.setText(shorten_path(self.inputfilename))
Example #22
0
def save_dialog(parent, default_dir=None, default_name=None):
    default_dir = default_dir or os.getcwd()
    default_name = default_name or ""
    dialog = QFileDialog(parent)
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.setDirectory(os.getcwd())
    dialog.selectFile(default_name)
    if not (dialog.exec_()):
        return None
    saveloc = dialog.selectedFiles()[0]
    return saveloc
Example #23
0
    def _get_save_name(self, ext):
        fullname = '{}_{}{}'.format(self.root_file, self.save_postfix ,ext)

        dialog = QFileDialog()
        
        dialog.selectFile(fullname)
        dialog.setOptions(QFileDialog.DontUseNativeDialog)
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setNameFilters(['*' + ext])
        ret = dialog.exec();
        if (ret == QDialog.Accepted):
            fullname = dialog.selectedFiles()[0]
        return fullname
Example #24
0
def get_save_file_name(initial_name: str,
                       wav_only=False,
                       caption="Save signal",
                       selected_name_filter=None):
    global RECENT_PATH
    if caption == "Save signal":
        name_filter = "Complex (*.complex);;" \
                      "Complex16 unsigned (*.complex16u *.cu8);;" \
                      "Complex16 signed (*.complex16s *.cs8);;" \
                      "Complex32 unsigned (*.complex32u *.cu16);;" \
                      "Complex32 signed (*.complex32s *.cs16);;" \
                      "Complex compressed (*.coco);;" \
                      "WAV (*.wav);;" \
                      "All Files (*)"
        if wav_only:
            name_filter = "WAV (*.wav);;All Files (*)"
    elif caption == "Save fuzz profile":
        name_filter = "Fuzzing Profile (*.fuzz.xml *.fuzz);;All Files (*)"
    elif caption == "Save encoding":
        name_filter = ""
    elif caption == "Save simulator profile":
        name_filter = "Simulator (*.sim.xml *.sim);;All Files (*)"
    elif caption == "Export spectrogram":
        name_filter = "Frequency Time (*.ft);;Frequency Time Amplitude (*.fta)"
    else:
        name_filter = "Protocols (*.proto.xml *.proto);;Binary Protocol (*.bin);;All Files (*)"

    filename = None
    dialog = QFileDialog(directory=RECENT_PATH,
                         caption=caption,
                         filter=name_filter)
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setViewMode(QFileDialog.Detail)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setAcceptMode(QFileDialog.AcceptSave)

    if selected_name_filter is not None:
        dialog.selectNameFilter(selected_name_filter)

    dialog.selectFile(initial_name)

    if dialog.exec():
        filename = dialog.selectedFiles()[0]

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

    return filename
Example #25
0
 def saveFileDialog(self, removeExt=True):
     caption = f'{APP_NAME} - Choose File'
     filters = f'File (*{LabelFile.suffix})'
     openDialogPath = self.currentPath()
     dlg = QFileDialog(self, caption, openDialogPath, filters)
     dlg.setDefaultSuffix(LabelFile.suffix[1:])
     dlg.setAcceptMode(QFileDialog.AcceptSave)
     filenameWithoutExtension = os.path.splitext(self.filePath)[0]
     dlg.selectFile(filenameWithoutExtension)
     dlg.setOption(QFileDialog.DontUseNativeDialog, False)
     if dlg.exec_():
         fullFilePath = str(dlg.selectedFiles()[0])
         if removeExt:
             return os.path.splitext(fullFilePath)[0]
         else:
             return fullFilePath
     return ''
Example #26
0
    def on_downloadRequested(self, download):
        downloadHandleHit = False
        old_path = download.path()
        suffix = QtCore.QFileInfo(old_path).suffix()
        if (args.downloadHandle):
            for x in args.downloadHandle:
                handle = x.split("|")
                if (suffix == handle[0]):
                    downloadHandleHit = True
                    filepath = handle[2] + "/tmp." + suffix
                    download.setPath(filepath)
                    download.accept()
                    download.finished.connect(
                        partial(self.runProcess, handle, filepath, download))

        if (args.download and not downloadHandleHit):
            #path, _ = QtWidgets.QFileDialog.getSaveFileName(self.view(), "Save File", old_path, "*."+suffix)
            path = ""
            suffix = QtCore.QFileInfo(old_path).suffix()
            downloadDialog = QFileDialog()

            if (args.downloadPath):
                downloadDialog.setDirectory(args.downloadPath)
                downloadDialog.selectFile(os.path.basename(old_path))
            else:
                downloadDialog.selectFile(old_path)

            downloadDialog.setFileMode(QFileDialog.AnyFile)
            downloadDialog.setAcceptMode(QFileDialog.AcceptSave)
            downloadDialog.setNameFilters(["*." + suffix])

            options = QFileDialog.Options()
            options |= QFileDialog.DontUseNativeDialog
            downloadDialog.setOptions(options)

            # dialogLabel = QFileDialog.DialogLabel()
            # dialogLabel |= QFileDialog.FileName
            # downloadDialog.setLabelText(dialogLabel, "Download")

            if downloadDialog.exec_():
                path = downloadDialog.selectedFiles()[0]

            if path:
                download.setPath(path)
                download.accept()
Example #27
0
 def _open(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     try:
         filename = os.path.join(self.netlist.path)
     except AttributeError:
         filename = os.path.join(os.getcwd(), 'netlist.net')
     dialog.selectFile(filename)
     fname, _ = dialog.getOpenFileName(
         self,
         'Open netlist file',
         filename,
         "All Files (*);;PyPHS netlist files (*.net)",
         "PyPHS netlist files (*.net)",
         options=options)
     if not fname == '':
         self.path = fname
         self._read()
Example #28
0
def LoadFile(Title="Load ...", Filters=['All files (*.*)'], Suffix=None, currentDirectory=None, currentFile=None):
    from PyQt5.QtWidgets import QDialog, QFileDialog
    import PyQt5.QtCore as QtCore
    dialog = QFileDialog()
    dialog.setWindowTitle(Title)
    if currentDirectory is not None:
        if len(currentDirectory):
            dialog.setDirectory(currentDirectory)
    if currentFile is not None:
        dialog.selectFile(currentFile)
    if Suffix is not None:
        dialog.setDefaultSuffix(Suffix)
    dialog.setOption(QFileDialog.DontUseNativeDialog)
    dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden)
    dialog.setNameFilters(Filters)
    dialog.setAcceptMode(QFileDialog.AcceptOpen)
    if dialog.exec_() == QDialog.Accepted:
        return dialog.selectedFiles()[0]
    return []
Example #29
0
def ask_save_file_name(initial_name: str,
                       caption="Save signal",
                       selected_name_filter=None):
    global RECENT_PATH
    if caption == "Save signal":
        name_filter = __get__name_filter_for_signals()
    elif caption == "Save fuzzing profile":
        name_filter = FUZZING_FILE_FILTER
    elif caption == "Save encoding":
        name_filter = ""
    elif caption == "Save simulator profile":
        name_filter = SIMULATOR_FILE_FILTER
    elif caption == "Export spectrogram":
        name_filter = "Frequency Time (*.ft);;Frequency Time Amplitude (*.fta)"
    elif caption == "Save protocol":
        name_filter = ";;".join(
            [PROTOCOL_FILE_FILTER, BINARY_PROTOCOL_FILE_FILTER])
    elif caption == "Export demodulated":
        name_filter = WAV_FILE_FILTER
    else:
        name_filter = EVERYTHING_FILE_FILTER

    filename = None
    dialog = QFileDialog(directory=RECENT_PATH,
                         caption=caption,
                         filter=name_filter)
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setLabelText(QFileDialog.Accept, "Save")
    dialog.setAcceptMode(QFileDialog.AcceptSave)

    if selected_name_filter is not None:
        dialog.selectNameFilter(selected_name_filter)

    dialog.selectFile(initial_name)

    if dialog.exec():
        filename = dialog.selectedFiles()[0]

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

    return filename
Example #30
0
 def _writelatex(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     filename = os.path.join(self.folder, self.label + '.tex')
     dialog.selectFile(filename)
     fileName, _ = dialog.getSaveFileName(
         self,
         "Save LaTeX file as...",
         filename,
         "All Files (*);;Latex Files (*.tex)",
         "Latex Files (*.tex)",
         options=options)
     if not fileName == '':
         content = netlist2tex(
             self.coreWidget.graphWidget.netlistWidget.netlist)
         content += graphplot2tex(self.coreWidget.graphWidget.graph)
         content += core2tex(self.core)
         title = self.core.label
         texdocument(content, fileName, title)
Example #31
0
 def _writecpp(self):
     if not self.status:
         self.methodWidget._build()
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     dialog.selectFile(self.folder)
     folder = dialog.getExistingDirectory(self,
                                          "Save c++ files in...",
                                          self.folder,
                                          options=options)
     if not folder == '':
         folder = os.path.join(folder, self.method.label + '_Sources')
         args = {
             'objlabel': self.method.label,
             'path': folder,
             'inits': self.inits.inits,
             'config': self.parameters,
             'subs': None
         }
         self.method.to_cpp(**args)
Example #32
0
 def _new(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     dialog = QFileDialog()
     try:
         filename = os.path.join(self.netlist.path)
     except AttributeError:
         filename = os.path.join(os.getcwd(), 'netlist.net')
     dialog.selectFile(filename)
     fname, _ = dialog.getSaveFileName(
         self,
         "Save new netlist file as...",
         filename,
         "All Files (*);;PyPHS netlist files (*.net)",
         "PyPHS netlist files (*.net)",
         options=options)
     if not fname == '':
         if not fname[-4:] == '.net':
             fname += '.net'
         self.path = fname
         self._read()
Example #33
0
def get_save_file_name(initial_name: str,
                       wav_only=False,
                       caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        name_filter = "Complex files (*.complex);;Complex16 files (2 unsigned int8) " \
                      "(*.complex16u *.cu8);;Complex16 files (2 signed int8) (*.complex16s *.cs8);;" \
                      "Compressed complex files (*.coco);;wav files (*.wav);;all files (*)"
        if wav_only:
            name_filter = "wav files (*.wav);;all files (*)"
    elif caption == "Save fuzz profile":
        name_filter = "Fuzzfiles (*.fuzz.xml *.fuzz);;All files (*)"
    elif caption == "Save encoding":
        name_filter = ""
    elif caption == "Save simulator profile":
        name_filter = "Simulator (*.sim.xml *.sim);;All files (*)"
    elif caption == "Export spectrogram":
        name_filter = "Frequency Time (*.ft);;Frequency Time Amplitude (*.fta)"
    else:
        name_filter = "Protocols (*.proto.xml *.proto);;Binary Protocol (*.bin);;All files (*)"

    filename = None
    dialog = QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setNameFilter(name_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]

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

    return filename
Example #34
0
def get_save_file_name(initial_name: str, wav_only=False, caption="Save signal"):
    global RECENT_PATH
    if caption == "Save signal":
        name_filter = "Complex (*.complex);;" \
                      "Complex16 unsigned (*.complex16u *.cu8);;" \
                      "Complex16 signed (*.complex16s *.cs8);;" \
                      "Complex compressed (*.coco);;" \
                      "WAV (*.wav);;" \
                      "All Files (*)"
        if wav_only:
            name_filter = "WAV Files (*.wav);;All Files (*)"
    elif caption == "Save fuzz profile":
        name_filter = "Fuzzing Profile (*.fuzz.xml *.fuzz);;All Files (*)"
    elif caption == "Save encoding":
        name_filter = ""
    elif caption == "Save simulator profile":
        name_filter = "Simulator (*.sim.xml *.sim);;All Files (*)"
    elif caption == "Export spectrogram":
        name_filter = "Frequency Time (*.ft);;Frequency Time Amplitude (*.fta)"
    else:
        name_filter = "Protocols (*.proto.xml *.proto);;Binary Protocol (*.bin);;All Files (*)"

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

    if dialog.exec():
        filename = dialog.selectedFiles()[0]

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

    return filename
    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 write_output_files(self, result_name, figure, output=None):
        """
        Export the created diagrams and save calculation results in a POF
        (processing output file) file.

        :param result_name:
        :param figure:
        :param output:
        :return:
        """
        path = self._settings.value(self._path_name)
        if not os.path.isdir(path):
            box = QMessageBox()
            box.setText("Export Folder does not exist yet.")
            box.setInformativeText("Do you want to create it? \n"
                                   "{}".format(os.path.abspath(path)))
            box.setStandardButtons(QMessageBox.Ok | QMessageBox.No)
            box.setDefaultButton(QMessageBox.Ok)
            ret = box.exec_()
            if ret == QMessageBox.Ok:
                os.makedirs(path)
            else:
                path = os.path.curdir

        sub_path = os.path.join(path, self.name)
        if not os.path.isdir(sub_path):
            os.makedirs(sub_path)

        dialog = QFileDialog()
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setDirectory(sub_path)
        dialog.setNameFilter("{} (*{})".format(self._file_info,
                                               self._file_type))
        dialog.selectFile(result_name + self._file_type)

        if dialog.exec_():
            file_path = dialog.selectedFiles()[0]
        else:
            self._logger.warning("Export Aborted")
            return

        new_path = os.path.sep.join(file_path.split(os.path.sep)[:-2])
        if new_path != self._settings.value(self._path_name):
            box = QMessageBox()
            box.setText("Use this path as new default?")
            box.setInformativeText("{}".format(new_path))
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            box.setDefaultButton(QMessageBox.Yes)
            ret = box.exec_()
            if ret == QMessageBox.Yes:
                self._settings.setValue(self._path_name, new_path)

        if output:
            with open(file_path, "wb") as f:
                dump(output, f, protocol=4)

        if figure:
            for export_format in self._export_formats:
                figure.savefig(file_path.split(".")[0] + export_format,
                               bbox_inches='tight')
    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 _save_data(self, file_path=None):
        """
        Save the current simulation results.

        If *fie_name* is given, the result will be saved to the specified
        location, making automated exporting easier.

        Args:
            file_path(str): Absolute path of the target file. If `None` the
                use will be asked for a storage location.
        """
        regime_name = self._regimes[self._current_regime_index]["Name"]

        if file_path is None:
            # get default path
            path = self._settings.value("path/simulation_results")

            # create canonic file name
            suggestion = self._simfile_name(regime_name)
        else:
            path = os.path.dirname(file_path)
            suggestion = os.path.basename(file_path)

        # check if path exists otherwise create it
        if not os.path.isdir(path):
            box = QMessageBox()
            box.setText("Export Folder does not exist yet.")
            box.setInformativeText("Do you want to create it? \n"
                                   "{}".format(os.path.abspath(path)))
            box.setStandardButtons(QMessageBox.Ok | QMessageBox.No)
            box.setDefaultButton(QMessageBox.Ok)
            ret = box.exec_()
            if ret == QMessageBox.Ok:
                os.makedirs(path)
            else:
                path = os.path.abspath(os.path.curdir)
                file_path = None

        # If no path was given, present the default and let the user choose
        if file_path is None:
            dialog = QFileDialog(self)
            dialog.setAcceptMode(QFileDialog.AcceptSave)
            dialog.setFileMode(QFileDialog.AnyFile)
            dialog.setDirectory(path)
            dialog.setNameFilter("PyMoskito Results (*.pmr)")
            dialog.selectFile(suggestion)

            if dialog.exec_():
                file_path = dialog.selectedFiles()[0]
            else:
                self._logger.warning("Export Aborted")
                return -1

        # ask whether this should act as new default
        path = os.path.abspath(os.path.dirname(file_path))
        if path != self._settings.value("path/simulation_results"):
            box = QMessageBox()
            box.setText("Use this path as new default?")
            box.setInformativeText("{}".format(path))
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            box.setDefaultButton(QMessageBox.Yes)
            ret = box.exec_()
            if ret == QMessageBox.Yes:
                self._settings.setValue("path/simulation_results", path)

        self.currentDataset.update({"regime name": regime_name})
        with open(file_path, "wb") as f:
            pickle.dump(self.currentDataset, f, protocol=4)

        self.statusLabel.setText("results saved to {}".format(file_path))
        self._logger.info("results saved to {}".format(file_path))