Example #1
0
 def download(self):
     if not empty(self.subtitle.url):
         if self.subtitle.url.endswith('.rar'):
             ext = '.rar'
         elif self.subtitle.url.endswith('.srt'):
             ext = '.srt'
         else:
             ext = '.zip'
     fileDial = QFileDialog(self, 'Save "%s" subtitle file' %
                            self.subtitle.name, '%s%s' % (self.subtitle.name, ext), 'all files (*)')
     fileDial.setAcceptMode(QFileDialog.AcceptSave)
     fileDial.setLabelText(QFileDialog.Accept, 'Save subtitle file')
     fileDial.setLabelText(QFileDialog.FileName, 'Subtitle file name')
     ok = (fileDial.exec_() == 1)
     if not ok:
         return
     result = fileDial.selectedFiles()
     if len(result) > 0:
         dest = result[0]
         data = self.backend.get_subtitle_file(self.subtitle.id)
         try:
             with open(dest, 'w') as f:
                 f.write(data)
         except IOError as e:
             print('Unable to write subtitle file in "%s": %s' % (dest, e), file=self.stderr)
             return 1
         return
Example #2
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)
Example #3
0
 def openAfterMaybeSave(self):
     """
     This is the method that initiates file opening. It is called by
     actionOpenSlot to spawn a QFileDialog and connect it to a callback
     method.
     """
     path = self._file_open_path
     if util.isWindows():  # required for native looking file window#"/",
         fname = QFileDialog.getOpenFileName(
                     None,
                     "Open Document", path,
                     "cadnano1 / cadnano2 Files (*.nno *.json *.cadnano)")
         self.filesavedialog = None
         self.openAfterMaybeSaveCallback(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
                     self.win,
                     "Open Document",
                     path,
                     "cadnano1 / cadnano2 Files (*.nno *.json *.cadnano)")
         fdialog.setAcceptMode(QFileDialog.AcceptOpen)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.fileopendialog = fdialog
         self.fileopendialog.filesSelected.connect(self.openAfterMaybeSaveCallback)
         fdialog.open()
Example #4
0
 def dumpXML(self):
     browser = QFileDialog(self, "Pick a file to save the XML to.")
     browser.setAcceptMode(QFileDialog.AcceptSave)
     browser.setDefaultSuffix("xml")
     if browser.exec_() == QDialog.Accepted:
         exportXML(self._model, self.libraryPath,
                   browser.selectedFiles()[0])
Example #5
0
def getSaveFileName(
        *,
        parent,
        title,
        filename,
        filter="",
        default_extension: str = None,
        default_filter: str = None,
        config: 'SimpleConfig',
) -> Optional[str]:
    """Custom wrapper for getSaveFileName that remembers the path selected by the user."""
    directory = config.get('io_dir', os.path.expanduser('~'))
    path = os.path.join(directory, filename)

    file_dialog = QFileDialog(parent, title, path, filter)
    file_dialog.setAcceptMode(QFileDialog.AcceptSave)
    if default_extension:
        # note: on MacOS, the selected filter's first extension seems to have priority over this...
        file_dialog.setDefaultSuffix(default_extension)
    if default_filter:
        assert default_filter in filter, f"default_filter={default_filter!r} does not appear in filter={filter!r}"
        file_dialog.selectNameFilter(default_filter)
    if file_dialog.exec() != QDialog.Accepted:
        return None

    selected_path = file_dialog.selectedFiles()[0]
    if selected_path and directory != os.path.dirname(selected_path):
        config.set_key('io_dir', os.path.dirname(selected_path), True)
    return selected_path
Example #6
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)
Example #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]
         self.saveFile(path, fileFormats[nameFilter])
         self.setWindowTitle(self.fontTitle())
 def new_campaign(self):
     dialog = QFileDialog(self)
     dialog.setDirectory(helper.one_up(self.current_dir))
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.setFileMode(QFileDialog.AnyFile)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     dialog.setWindowTitle('Select folder name')
     if dialog.exec_():
         directory = dialog.selectedFiles()[0]
         qdir = QDir(directory)
         if not qdir.exists():
             self.current_dir = qdir.path()
             for folder_name in resource.folders:
                 qdir.mkpath('./' + folder_name)
             helper.save_json_data(
                 '{}/{}/health{}'.format(self.current_dir,
                                         resource.health_stat.folder,
                                         resource.health_stat.ext),
                 resource.health_stat.default)
             qdir.mkpath('./.settings/std')
             qdir.mkpath('./.settings/debug')
             resource.create_config_files(self.current_dir, qdir.dirName())
             self.refresh_tree_view()
         else:
             helper.display_error('Directory for campaign already exists.'
                                  )  # This shouldn't happen
Example #9
0
 def openXlsx(self, xlsx=None):
     timesheet = self.context.timesheet
     if self._exit_confirm_flag:
         title = self.context.build_settings['app_name']
         text = '上次儲存之後又有新的簽到紀錄。\n仍要重開簽到名單?'
         reply = QMessageBox.question(self, title, text)
         if reply == QMessageBox.No:
             return False
     if xlsx is None:
         dialog = QFileDialog()
         dialog.setAcceptMode(QFileDialog.AcceptOpen)
         dialog.setFileMode(QFileDialog.ExistingFile)
         dialog.setNameFilter('Spreadsheets (*.xlsx)')
         if not dialog.exec_():
             return False
         xlsx = dialog.selectedFiles()[0]
         # xlsx = 'oc13.xlsx'
     timesheet.open(xlsx)
     # View
     self.uiTimesheetFrame.display()
     self.uiInputEdit.setDisabled(False)
     self.uiInputEdit.setFocus()
     self.uiFileSaveBtn.setDisabled(False)
     self.updateSpreadSheet()
     self.updateProgressBar()
     # Spinbox backgrounds
     palette = self.uiBarColSpn.palette()
     palette.setColor(QPalette.Base, BARCODE_COLOR.lighter())
     self.uiBarColSpn.setPalette(palette)
     palette = self.uiGrpColSpn.palette()
     palette.setColor(QPalette.Base, GRPCODE_COLOR.lighter())
     self.uiGrpColSpn.setPalette(palette)
     self.statusbar.showMessage('載入 %d 列資料。' % timesheet.rowCount())
Example #10
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
Example #11
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 #12
0
 def saveFileDialog(self):
     fname = self.filename()
     if fname == None:
         directory = "."
     else:
         directory = QFileInfo(fname).path()
     if util.isWindows():  # required for native looking file window
         fname = QFileDialog.getSaveFileName(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         self.writeDocumentToFile(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         fdialog.setAcceptMode(QFileDialog.AcceptSave)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.filesavedialog = fdialog
         self.filesavedialog.filesSelected.connect(
                                             self.saveFileDialogCallback)
         fdialog.open()
Example #13
0
def file_dialog(dir='', for_open=True, fmt='', is_folder=False):
    """Dialog z eksploratorem Windows. Otwieranie/tworzenie folderów i plików."""
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    options |= QFileDialog.DontUseCustomDirectoryIcons
    dialog = QFileDialog()
    dialog.setOptions(options)
    dialog.setFilter(dialog.filter() | QDir.Hidden)
    if is_folder:  # Otwieranie folderu
        dialog.setFileMode(QFileDialog.DirectoryOnly)
    else:  # Otwieranie pliku
        dialog.setFileMode(QFileDialog.AnyFile)
    # Otwieranie / zapisywanie:
    dialog.setAcceptMode(
        QFileDialog.AcceptOpen) if for_open else dialog.setAcceptMode(
            QFileDialog.AcceptSave)
    # Ustawienie filtrowania rozszerzeń plików:
    if fmt != '' and not is_folder:
        dialog.setDefaultSuffix(fmt)
        dialog.setNameFilters([f'{fmt} (*.{fmt})'])
    # Ścieżka startowa:
    if dir != '':
        dialog.setDirectory(str(dir))
    else:
        dialog.setDirectory(str(os.environ["HOMEPATH"]))
    # Przekazanie ścieżki folderu/pliku:
    if dialog.exec_() == QDialog.Accepted:
        path = dialog.selectedFiles()[0]
        return path
    else:
        return ''
    def seek(self):
        fileName = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("Images (*.png *.gif *.jpg);;All (*)")
        dialog.setWindowTitle(QCoreApplication.translate("SiteSettingsEditor", "Load Image"))
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        if dialog.exec():
            fileName = dialog.selectedFiles()[0]
        del dialog
        if not fileName:
            return

        # copy file to assets dir
        name = os.path.basename(fileName).replace(" ", "_")
        path = os.path.join(self.site.source_path, "assets", "images", name)
        self.logo.setText(os.path.basename(path))
        shutil.copy(fileName, path)

        # also copy file to deploy dir for previews
        dpath = os.path.join(self.site.source_path, self.site.output, "assets", "images", name)
        shutil.copy(fileName, dpath)

        self.image.setImage(QImage(path))
        self.contentChanged("logo changed")
Example #15
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
Example #16
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())
Example #17
0
    def saveAsFile(self):
        widget = self.tab_widget.currentWidget()
        assert isinstance(widget, NodeEditorSpace)

        dialogue = QFileDialog(self, caption="Save Hivemap")
        dialogue.setDefaultSuffix(self._hivemapExtension)
        dialogue.setNameFilter(dialogue.tr("Hivemaps (*.{})".format(self._hivemapExtension)))
        dialogue.setFileMode(QFileDialog.AnyFile)
        dialogue.setAcceptMode(QFileDialog.AcceptSave)

        if not dialogue.exec_():
            return

        file_path = dialogue.selectedFiles()[0]

        widget.save(file_path=file_path)
        widget.setFilePath(file_path)

        # Update tab name
        name = self._getDisplayName(file_path, allow_untitled=False)
        index = self.tab_widget.currentIndex()
        self.tab_widget.setTabText(index, name)

        # Update save UI elements (filename may have changed) filename
        self._updateMenuOptions()

        # Refresh hives
        if self._projectDirectory is not None:
            self.updateLoadedHives()
Example #18
0
    def addImage(self):
        fileName = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("Image Files(*.png *.jpg *.bmp *.gif);;All (*)")
        dialog.setWindowTitle("Load Image")
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        if dialog.exec_():
            fileName = dialog.selectedFiles()[0]
        del dialog
        if not fileName:
            return

        base = os.path.basename(fileName)
        if not os.path.exists(
                os.path.join(self.book.source_path, "images", base)):
            copy(fileName, os.path.join(self.book.source_path, "images"))
        item = QListWidgetItem()
        item.setText(Path(fileName).name)
        item.setData(
            1,
            os.path.join(self.book.source_path, "images",
                         Path(fileName).name))
        self.image_list.addItem(item)
Example #19
0
    def on_actionSaveAs(self):
        dialog = QFileDialog()
        dialog.setAcceptMode(QFileDialog.AcceptSave)

        if dialog.exec():
            with open(dialog.selectedFiles()[0], 'wb') as f:
                self.loaded_case = f.name
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
Example #21
0
    def contextCoverMenu(self, point):
        if len(self.treeFileList.selectedItems()) == 1:
            menu = QMenu()

            actionLoad = menu.addAction(_translate('fb2mobi-gui', 'Load from file...'))
            actionSave = menu.addAction(_translate('fb2mobi-gui', 'Save to file...'))
            actionClear = menu.addAction(_translate('fb2mobi-gui', 'Clear'))

            action = menu.exec_(self.imgBookCover.mapToGlobal(point))

            if action == actionLoad:
                fileDialog = QFileDialog(self, _translate('fb2mobi-gui', 'Select book cover'))
                fileDialog.setFileMode(QFileDialog.ExistingFile)
                fileDialog.setNameFilters([_translate('fb2mobi-gui', 'Image files (*.png *.jpg *.bmp)')])

                if fileDialog.exec_():
                    file_list = fileDialog.selectedFiles()
                    self.loadNewCoverFormFile(file_list[0])
            elif action == actionSave:
                fileDialog = QFileDialog(self, _translate('fb2mobi-gui', 'Save cover as'))
                fileDialog.setAcceptMode(QFileDialog.AcceptSave)
                fileDialog.setFileMode(QFileDialog.AnyFile)
                fileDialog.setNameFilters([_translate('fb2mobi-gui', 'Image files (*.png *.jpg *.bmp)')])

                if fileDialog.exec_():
                    file_list = fileDialog.selectedFiles()  
                    self.book_cover.save(file_list[0], os.path.splitext(file_list[0])[1][1:].upper());

            elif action == actionClear:
                self.book_cover = None
                self.imgBookCover.clear()
Example #22
0
 def write_csv(self):
     dialog = QFileDialog(self, 'Write csv file', '.', '*.csv')
     dialog.setDefaultSuffix('csv')
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.setOptions(QFileDialog.DontConfirmOverwrite)
     if dialog.exec() == QDialog.Accepted:
         name = dialog.selectedFiles()
         fh = open(name[0], 'w')
         f = self.dut.freq
         o = np.interp(f,
                       self.open.freq,
                       self.open.data,
                       period=self.open.period)
         s = np.interp(f,
                       self.short.freq,
                       self.short.data,
                       period=self.short.period)
         l = np.interp(f,
                       self.load.freq,
                       self.load.data,
                       period=self.load.period)
         d = self.dut.data
         fh.write(
             'frequency;open.real;open.imag;short.real;short.imag;load.real;load.imag;dut.real;dut.imag\n'
         )
         for i in range(f.size):
             fh.write(
                 '0.0%.8d;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f\n'
                 % (f[i] * 1000, o.real[i], o.imag[i], s.real[i], s.imag[i],
                    l.real[i], l.imag[i], d.real[i], d.imag[i]))
         fh.close()
Example #23
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
Example #24
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
Example #25
0
def get_folder_filepath(
    parent,
    message: str,
    *,
    show_files: bool = True,
    directory: str = '',
    exists: bool = True,
    native: bool = False,
) -> Path or None:
    options = QFileDialog.DontResolveSymlinks

    if not native:
        options |= QFileDialog.DontUseNativeDialog

    if not show_files:
        options |= QFileDialog.ShowDirsOnly

    dialog = QFileDialog(parent, caption=message, directory=directory)
    dialog.setFileMode(QFileDialog.Directory)
    dialog.setOptions(options)

    if not exists:
        dialog.setAcceptMode(QFileDialog.AcceptSave)

    if dialog.exec_() == QFileDialog.Accepted:
        folder_path = dialog.selectedFiles()[0]

        if folder_path:
            return Path(folder_path)
Example #26
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 #27
0
 def download(self):
     if not empty(self.subtitle.url):
         if self.subtitle.url.endswith('.rar'):
             ext = '.rar'
         elif self.subtitle.url.endswith('.srt'):
             ext = '.srt'
         else:
             ext = '.zip'
     fileDial = QFileDialog(self,
                            'Save "%s" subtitle file' % self.subtitle.name,
                            '%s%s' % (self.subtitle.name, ext),
                            'all files (*)')
     fileDial.setAcceptMode(QFileDialog.AcceptSave)
     fileDial.setLabelText(QFileDialog.Accept, 'Save subtitle file')
     fileDial.setLabelText(QFileDialog.FileName, 'Subtitle file name')
     ok = (fileDial.exec_() == 1)
     if not ok:
         return
     result = fileDial.selectedFiles()
     if len(result) > 0:
         dest = result[0]
         data = self.backend.get_subtitle_file(self.subtitle.id)
         try:
             with open(dest, 'w') as f:
                 f.write(data)
         except IOError as e:
             print('Unable to write subtitle file in "%s": %s' % (dest, e),
                   file=self.stderr)
             return 1
         return
Example #28
0
 def on_btnExportLog_clicked(self):
     """
     Export the contents of the log tab to .csv file
     """
     # get filename to save as
     dlg = QFileDialog()
     dlg.setAcceptMode(QFileDialog.AcceptSave)
     dlg.setDefaultSuffix("csv")
     dlg.setNameFilters(["Log File (*.csv)", "all files (*.*)"])
     dlg.setDirectory(self.parent.settings.value("Default/ProjPath"))
     if dlg.exec_():
         fileNames = dlg.selectedFiles()
         try:
             if fileNames:
                 self.fileName = fileNames[0]
                 # save the file
                 with open(self.fileName, 'w', newline='') as csvfile:
                     csvWriter = csv.writer(csvfile,
                                            delimiter=',',
                                            quotechar='"',
                                            quoting=csv.QUOTE_MINIMAL)
                     for row in range(self.gridLog.model().rowCount()):
                         rowItems = []
                         for col in range(
                                 self.gridLog.model().columnCount()):
                             value = self.gridLog.model().index(
                                 row, col,
                                 QModelIndex()).data(Qt.DisplayRole)
                             rowItems.append(value)
                         csvWriter.writerow(c for c in rowItems)
         except BaseException as e:
             msg = "{} - {} failed.".format("Write CSV", repr(e))
             self.helper.displayErrMsg("Export CSV Error", msg)
Example #29
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 #30
0
    def importAction(self):
        fileDialog = QFileDialog(self)
        fileDialog.setWindowTitle("Import VisualStates File")
        fileDialog.setViewMode(QFileDialog.Detail)
        fileDialog.setNameFilters(['VisualStates File (*.xml)'])
        fileDialog.setDefaultSuffix('.xml')
        fileDialog.setAcceptMode(QFileDialog.AcceptOpen)
        if fileDialog.exec_():
            tempPath = self.fileManager.getFullPath()
            file = self.fileManager.open(fileDialog.selectedFiles()[0])
            if file[0] is not None:
                self.fileManager.setPath(tempPath)
                # if the current active state already has an initial state make sure that
                # there will not be any initial state in the imported state
                if self.activeState.getInitialChild() is not None:
                    for childState in file[0].getChildren():
                        childState.setInitial(False)

                # Update importing Namespaces
                importedState, self.config, self.libraries, self.globalNamespace = self.importManager.updateAuxiliaryData(file, self)
                self.treeModel.loadFromRoot(importedState, self.activeState)
                self.automataScene.displayState(self.activeState)
                self.automataScene.setLastIndexes(self.rootState)
            else:
                self.showWarning("Wrong file selected",
                                 "The selected file is not a valid VisualStates file")
Example #31
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)")

	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)
Example #32
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 #33
0
    def save_dialog(self, text):
        defualtFileName = './resutText.txt'
        try:
            save_dialog = QFileDialog()
            save_dialog.setAcceptMode(QFileDialog.AcceptSave)
            file_path = save_dialog.getSaveFileName(
                self,
                'Save as... File',
                defualtFileName,
                filter='All Files(*.*);; Text Files(*.txt)')

            if file_path[0]:
                self.file_path = file_path
                file_open = open(self.file_path[0], 'w')
                self.file_name = (self.file_path[0].split('/'))[-1]
                self.statusBar().showMessage('Saved at: {}'.format(
                    self.file_path[0]))
                self.setWindowTitle("{} - Notepad".format(self.file_name))
                with file_open:
                    file_open.write(text)
                    # self.need_saving(False)

        except FileNotFoundError as why:
            self.error_box(why)
            pass
Example #34
0
    def export_csv(self):
        """
        Creates and saves a csv file with the table data.
        """
        file_dialog = QFileDialog()
        file_dialog.setWindowTitle('Save File')
        file_dialog.setDirectory(os.getcwd())
        file_dialog.setAcceptMode(QFileDialog.AcceptSave)
        file_dialog.setNameFilter('Csv files (*.csv)')
        file_dialog.setDefaultSuffix('csv')

        if file_dialog.exec_() == QFileDialog.Accepted:
            path = file_dialog.selectedFiles()[0]

            if path:
                with open(path, mode="w", newline='',
                          encoding='utf8') as csv_file:
                    field_names = ["", "Unit", "Vap", "Liq", "Overall"]
                    writer = csv.DictWriter(csv_file, fieldnames=field_names)
                    writer.writeheader()

                    for row in range(self.table.rowCount()):
                        row_data = {}
                        row_data[""] = self.table.verticalHeaderItem(
                            row).text()

                        for col in range(self.table.columnCount()):
                            item = self.table.item(row, col)

                            if item is not None:
                                row_data[field_names[col + 1]] = item.text()
                            else:
                                row_data[field_names[col + 1]] = ''

                        writer.writerow(row_data)
Example #35
0
def conv_save_pressed(P, W):
    head = _translate('HandlerClass', 'Save Error')
    with open(P.fNgc, 'r') as inFile:
        for line in inFile:
            if '(new conversational file)' in line:
                msg0 = _translate('HandlerClass',
                                  'An empty file cannot be saved')
                P.dialog_show_ok(QMessageBox.Warning, '{}'.format(head),
                                 '{}\n'.format(msg0))
                return
    P.vkb_show()
    dlg = QFileDialog(W)
    dlg.setOptions(QFileDialog.DontUseNativeDialog)
    dlg.setAcceptMode(QFileDialog.AcceptSave)
    dlg.setNameFilters(['G-Code Files (*.ngc *.nc *.tap)', 'All Files (*)'])
    dlg.setDefaultSuffix('ngc')
    dlg.setDirectory(P.programPrefix)
    name = ''
    if dlg.exec_():
        name = dlg.selectedFiles()[0]
    if name:
        COPY(P.fNgc, name)
        W.conv_save.setEnabled(False)
        conv_enable_tabs(P, W)
    P.vkb_show(True)
Example #36
0
 def export(self):
     fileDial = QFileDialog(
         self, 'Export "%s" recipe' % self.recipe.title,
         '%s.kreml' % self.recipe.title.replace('/', ','),
         'Krecipe file (*.kreml);;all files (*)')
     fileDial.setAcceptMode(QFileDialog.AcceptSave)
     fileDial.setLabelText(QFileDialog.Accept, 'Export recipe')
     fileDial.setLabelText(QFileDialog.FileName, 'Recipe file name')
     ok = (fileDial.exec_() == 1)
     if not ok:
         return
     result = fileDial.selectedFiles()
     if len(result) > 0:
         dest = result[0]
         if not dest.endswith('.kreml'):
             dest += '.kreml'
         data = self.recipe.toKrecipesXml(author=self.backend.name)
         try:
             with codecs.open(dest, 'w', 'utf-8') as f:
                 f.write(data)
         except IOError as e:
             print('Unable to write Krecipe file in "%s": %s' % (dest, e),
                   file=self.stderr)
             return 1
         return
    def saveFile(self):
        e = TExtension()
        e.name = self.nameEdit.text() or None
        e.version = self.versionEdit.text() or None
        e.developer = self.developerEdit.text() or None
        e.developerURL = self.developerURLEdit.text() or None

        e.resourcesPath = self.resourcesRootBox.currentFolder()
        e.libPath = self.scriptRootBox.currentFolder()

        e.launchAtStartup = self.launchAtStartupBox.isChecked()
        e.mainScript = self.mainScriptDrop.currentText()
        # Note. for now we always do a list.
        addToMenu = []
        for ok, path, name, shortcut in self.addScriptsView.list():
            if not ok:
                continue
            data = dict(path=path, name=name, shortcut=shortcut)
            for k, v in list(data.items()):
                if v is None:
                    del data[k]
            addToMenu.append(data)
        if addToMenu:
            e.addToMenu = addToMenu
        e.tfVersion = self.tfVersionEdit.text() or None

        # TODO: switch to directory on platforms that need it
        dialog = QFileDialog(
            self, self.tr("Save File"), None, "SimpleFont Extension (*.tfExt)")
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        ok = dialog.exec_()
        if ok:
            path = dialog.selectedFiles()[0]
            e.save(path)
    def saveFile(self):
        e = TExtension()
        e.name = self.nameEdit.text() or None
        e.version = self.versionEdit.text() or None
        e.developer = self.developerEdit.text() or None
        e.developerURL = self.developerURLEdit.text() or None

        e.resourcesPath = self.resourcesRootBox.currentFolder()
        e.libPath = self.scriptRootBox.currentFolder()

        e.launchAtStartup = self.launchAtStartupBox.isChecked()
        e.mainScript = self.mainScriptDrop.currentText()
        # Note. for now we always do a list.
        addToMenu = []
        for ok, path, name, shortcut in self.addScriptsView.list():
            if not ok:
                continue
            data = dict(path=path, name=name, shortcut=shortcut)
            for k, v in data.items():
                if v is None:
                    del data[k]
            addToMenu.append(data)
        if addToMenu:
            e.addToMenu = addToMenu
        e.tfVersion = self.tfVersionEdit.text() or None

        # TODO: switch to directory on platforms that need it
        dialog = QFileDialog(self, self.tr("Save File"), None, "TruFont Extension (*.tfExt)")
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        ok = dialog.exec_()
        if ok:
            path = dialog.selectedFiles()[0]
            e.save(path)
Example #39
0
 def on_btnExportTrace_clicked(self):
     """
     Export the contents of the trace tab to .txt file
     """
     # get filename to save as
     dlg = QFileDialog()
     dlg.setAcceptMode(QFileDialog.AcceptSave)
     dlg.setDefaultSuffix("txt")
     dlg.setNameFilters(["Trace File (*.txt)", "all files (*.*)"])
     dlg.setDirectory(self.parent.settings.value("Default/ProjPath"))
     if dlg.exec_():
         fileNames = dlg.selectedFiles()
         if fileNames:
             self.fileName = fileNames[0]
             # save the file
             file = QFile(self.fileName)
             if not file.open(QFile.WriteOnly | QFile.Text):
                 self.helper.displayErrMsg(
                     "Export Trace Error", "Cannot write file {} {}".format(
                         self.fileName, file.errorString()))
                 return
             outstr = QTextStream(file)
             QApplication.setOverrideCursor(Qt.WaitCursor)
             outstr << self.textTrace.toPlainText()
             QApplication.restoreOverrideCursor()
Example #40
0
 async def get_save_filename(parent, title, url, filtr):
     dialog = QFileDialog(parent, title, url, filtr)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     result = await dialog_async_exec(dialog)
     if result == QFileDialog.AcceptSave:
         return dialog.selectedFiles()
     else:
         return []
Example #41
0
 def read_cfg(self):
   dialog = QFileDialog(self, 'Read configuration settings', '.', '*.ini')
   dialog.setDefaultSuffix('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 #42
0
 def addPlugin(self):
     fdialog = QFileDialog(self.widget, "Install Plugin", util.this_path(), "Cadnano Plugins (*.cnp)")
     fdialog.setAcceptMode(QFileDialog.AcceptOpen)
     fdialog.setWindowFlags(Qt.Sheet)
     fdialog.setWindowModality(Qt.WindowModal)
     fdialog.filesSelected.connect(self.addPluginAtPath)
     self.fileopendialog = fdialog
     fdialog.open()
Example #43
0
def openDialog(name, filter):
    """ Create non-native open file dialog. """
    qfd = QFileDialog(getWindow(), name)
    qfd.setNameFilter(filter)
    qfd.setFileMode(QFileDialog.ExistingFile)
    qfd.setOptions(QFileDialog.DontUseNativeDialog)
    qfd.setAcceptMode(QFileDialog.AcceptOpen)
    qfd.setViewMode(QFileDialog.List)
    return qfd
Example #44
0
def saveDialog(name, filter):
    """ Create non-native save file dialog. """
    qfd = QFileDialog(getWindow(), name)
    qfd.setNameFilter(filter)
    qfd.setFileMode(QFileDialog.AnyFile)
    qfd.setOptions(QFileDialog.DontUseNativeDialog)
    qfd.setAcceptMode(QFileDialog.AcceptSave)
    qfd.setViewMode(QFileDialog.List)
    return qfd
Example #45
0
 def on_button_clicked(self):
     caption = 'Vyberte výstupní soubor'
     dialog = QFileDialog(self, caption)
     dialog.setFileMode(QFileDialog.AnyFile)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.setNameFilter('CSV soubory (*.csv)')
     dialog.setDefaultSuffix('csv')
     if dialog.exec_():
         self.setFilename(dialog.selectedFiles()[0])
Example #46
0
    def on_file_browse(self):
        settings = QSettings()

        # look for directory
        path = QgsProject.instance().homePath()
        if path == '':
            path = settings.value("mask/file_dir", '')
            if path == '':
                path = QDir.homePath()

        drivers = QgsVectorFileWriter.ogrDriverList()
        filterList = []
        filterMap = {}
        for ln, n in drivers.items():
            # grrr, driverMetadata is not really consistent
            if n == "ESRI Shapefile":
                ext = "shp"
                glob = "*.shp"
            else:
                md = QgsVectorFileWriter.MetaData()
                if QgsVectorFileWriter.driverMetadata(n, md):
                    ext = md.ext
                    glob = md.glob
                else:
                    continue

            fn = "%s (%s)" % (ln, glob)
            filterMap[fn] = (n, ext, glob)
            filterList += [fn]

        fileFilters = ';;'.join(filterList)
        fd = QFileDialog(None, self.tr("Select a filename to save the mask layer to"),
                         path, fileFilters)
        save_format_name = self.parameters.file_format
        self.save_format = None
        for k, v in filterMap.items():
            if v[0] == save_format_name:
                self.save_format = v
                fd.selectNameFilter(k)
                break

        def on_filter_selected(ff):
            self.save_format = filterMap[ff]

        fd.filterSelected.connect(on_filter_selected)
        fd.setAcceptMode(QFileDialog.AcceptSave)
        r = fd.exec_()
        if r == 1:
            fn = fd.selectedFiles()[0]
            driver, ext, glob = self.save_format
            if not fn.endswith("." + ext):
                fn += "." + ext

            self.ui.filePath.setText(fn)
            self.ui.formatLbl.setText(self.save_format[0])
            self.parameters.file_format = self.save_format[0]
            self.parameters.file_path = fn
Example #47
0
 def saveAsAction(self):
     fileDialog = QFileDialog(self)
     fileDialog.setWindowTitle("Save VisualStates Project")
     fileDialog.setViewMode(QFileDialog.Detail)
     fileDialog.setNameFilters(['VisualStates File (*.xml)'])
     fileDialog.setAcceptMode(QFileDialog.AcceptSave)
     if fileDialog.exec_():
         self.fileManager.setFullPath(fileDialog.selectedFiles()[0])
         self.fileManager.save(self.rootState, self.config, self.libraries)
Example #48
0
 def write_cfg(self):
   dialog = QFileDialog(self, 'Write configuration settings', '.', '*.ini')
   dialog.setDefaultSuffix('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)
 def save(self):
     if not self.file:
         dialog = QFileDialog();
         #dialog.setFileMode(QFileDialog.AnyFile);
         dialog.setAcceptMode(QFileDialog.AcceptSave);
         if (dialog.exec()):
             self.file = (dialog.selectedFiles())[0];
         else:
             return;
     self.mainManager.save(self.file);
Example #50
0
 def saveFileDialog(self):
     saveDialog = QFileDialog()
     saveDialog.setAcceptMode(QFileDialog.AcceptSave)
     saveDialog.setFileMode(QFileDialog.AnyFile)
     saveDialog.setDefaultSuffix('sgf')  # TODO this does not work
     fileName, _ = saveDialog.getSaveFileName(
             self, "Save Game SGF",
             "", "Smart Game Files (*.sgf)",)
     if fileName:
         self.gameW.save(fileName)
Example #51
0
    def actionExportStaplesSlot(self):
        """
        Triggered by clicking Export Staples button. Opens a file dialog to
        determine where the staples should be saved. The callback is
        exportStaplesCallback which collects the staple sequences and exports
        the file.
        """
        # Validate that no staple oligos are loops.
        part = self.activePart()
        if part is None:
            return
        stap_loop_olgs = part.getStapleLoopOligos()
        if stap_loop_olgs:
            from ui.dialogs.ui_warning import Ui_Warning
            dialog = QDialog()
            dialogWarning = Ui_Warning()  # reusing this dialog, should rename
            dialog.setStyleSheet("QDialog { background-image: url(ui/dialogs/images/cadnano2-about.png); background-repeat: none; }")
            dialogWarning.setupUi(dialog)

            locs = ", ".join([o.locString() for o in stap_loop_olgs])
            msg = "Part contains staple loop(s) at %s.\n\nUse the break tool to introduce 5' & 3' ends before exporting. Loops have been colored red; use undo to revert." % locs
            dialogWarning.title.setText("Staple validation failed")
            dialogWarning.message.setText(msg)
            for o in stap_loop_olgs:
                o.applyColor(styles.stapColors[0].name())
            dialog.exec_()
            return

        # Proceed with staple export.
        fname = self.filename()
        if fname == None:
            directory = "."
        else:
            directory = QFileInfo(fname).path()
        if util.isWindows():  # required for native looking file window
            fname = QFileDialog.getSaveFileName(
                            self.win,
                            "%s - Export As" % QApplication.applicationName(),
                            directory,
                            "(*.csv)")
            self.saveStaplesDialog = None
            self.exportStaplesCallback(fname)
        else:  # access through non-blocking callback
            fdialog = QFileDialog(
                            self.win,
                            "%s - Export As" % QApplication.applicationName(),
                            directory,
                            "(*.csv)")
            fdialog.setAcceptMode(QFileDialog.AcceptSave)
            fdialog.setWindowFlags(Qt.Sheet)
            fdialog.setWindowModality(Qt.WindowModal)
            self.saveStaplesDialog = fdialog
            self.saveStaplesDialog.filesSelected.connect(self.exportStaplesCallback)
            fdialog.open()
Example #52
0
def save_as_gpvdm(parent):
	dialog = QFileDialog(parent)
	dialog.setWindowTitle(_("Save a the simulation as"))
	dialog.setNameFilter(_("Directory"))
	dialog.setAcceptMode(QFileDialog.AcceptSave)
	dialog.setOption(QFileDialog.ShowDirsOnly, True) 
	if dialog.exec_() == QDialog.Accepted:
		filename = dialog.selectedFiles()[0]
		return filename
	else:
		return None
    def exportAction(self):
        dialog = QFileDialog(self)
        dialog.setWindowModality(Qt.WindowModal)    # check for mac only
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setWindowTitle(QApplication.translate("MainWindow", "Export Calculation"))
        dialog.setDirectory(os.path.expanduser("~"))
        dialog.setNameFilter(QApplication.translate("MainWindow",
                "PNG files (*.png);;JPG files (*.jpg);;TIFF files (*.tif)"))

        if dialog.exec():
            filename = dialog.selectedFiles()
            self.plotWidget.plotWidget.plotWidget.export(filename.pop())
Example #54
0
    def pick(self):
        dlg = QFileDialog(self, self.title, lastDir, self.filters)
        if self.save:
            # dlg.setDefaultSuffix(self._extension)
            dlg.setAcceptMode(QFileDialog.AcceptSave)
        else:
            dlg.setAcceptMode(QFileDialog.AcceptOpen)
            dlg.setFileMode(QFileDialog.ExistingFile)
        if not dlg.exec():
            return

        self.wtext.setText(dlg.selectedFiles()[0])
Example #55
0
 def _ioDialog(self, mode):
     if mode == QFileDialog.AcceptOpen:
         title = self.tr("Open File")
     else:
         title = self.tr("Save File")
     dialog = QFileDialog(self, title, None, self.tr("Python file (*.py)"))
     dialog.setAcceptMode(mode)
     dialog.setDirectory(self.fileChooser.currentFolder())
     dialog.setFileMode(QFileDialog.ExistingFile)
     ok = dialog.exec_()
     if ok:
         return dialog.selectedFiles()[0]
     return None
Example #56
0
    def _browseForFilepath(self):
        starting_dir = os.path.expanduser("~")
        if self._filepathSlot.ready():
            starting_dir = os.path.split(self._filepathSlot.value)[-1]

        dlg = QFileDialog(self, "Export Location", starting_dir)
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        if not dlg.exec_():
            return

        exportPath = dlg.selectedFiles()[0]
        self._filepathSlot.setValue( exportPath )
        self.filepathEdit.setText( exportPath )
Example #57
0
 def openAction(self):
     fileDialog = QFileDialog(self)
     fileDialog.setWindowTitle("Open VisualStates File")
     fileDialog.setViewMode(QFileDialog.Detail)
     fileDialog.setNameFilters(['VisualStates File (*.xml)'])
     fileDialog.setDefaultSuffix('.xml')
     fileDialog.setAcceptMode(QFileDialog.AcceptOpen)
     if fileDialog.exec_():
         (self.rootState, self.config, self.libraries) = self.fileManager.open(fileDialog.selectedFiles()[0])
         self.treeModel.removeAll()
         self.treeModel.loadFromRoot(self.rootState)
         # set the active state as the loaded state
         self.automataScene.setActiveState(self.rootState)
         self.automataScene.setLastIndexes(self.rootState)
Example #58
0
 def write_s1p(self):
   dialog = QFileDialog(self, 'Write s1p file', '.', '*.s1p')
   dialog.setDefaultSuffix('s1p')
   dialog.setAcceptMode(QFileDialog.AcceptSave)
   dialog.setOptions(QFileDialog.DontConfirmOverwrite)
   if dialog.exec() == QDialog.Accepted:
     name = dialog.selectedFiles()
     fh = open(name[0], 'w')
     gamma = self.gamma()
     size = self.sizeValue.value()
     fh.write('# GHz S MA R 50\n')
     for i in range(0, size):
       fh.write('0.0%.8d   %8.6f %7.2f\n' % (self.xaxis[i], np.absolute(gamma[i]), np.angle(gamma[i], deg = True)))
     fh.close()
Example #59
0
 def write_csv(self):
   dialog = QFileDialog(self, 'Write csv file', '.', '*.csv')
   dialog.setDefaultSuffix('csv')
   dialog.setAcceptMode(QFileDialog.AcceptSave)
   dialog.setOptions(QFileDialog.DontConfirmOverwrite)
   if dialog.exec() == QDialog.Accepted:
     name = dialog.selectedFiles()
     fh = open(name[0], 'w')
     gamma = self.gamma()
     size = self.sizeValue.value()
     fh.write('frequency;open.real;open.imag;short.real;short.imag;load.real;load.imag;dut.real;dut.imag\n')
     for i in range(0, size):
       fh.write('0.0%.8d;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f\n' % (self.xaxis[i], self.open.real[i], self.open.imag[i], self.short.real[i], self.short.imag[i], self.load.real[i], self.load.imag[i], self.dut.real[i], self.dut.imag[i]))
     fh.close()
Example #60
0
 def write_s2p(self, gain):
   dialog = QFileDialog(self, 'Write s2p file', '.', '*.s2p')
   dialog.setDefaultSuffix('s2p')
   dialog.setAcceptMode(QFileDialog.AcceptSave)
   dialog.setOptions(QFileDialog.DontConfirmOverwrite)
   if dialog.exec() == QDialog.Accepted:
     name = dialog.selectedFiles()
     fh = open(name[0], 'w')
     freq = self.dut.freq
     gamma = self.gamma(freq)
     fh.write('# GHz S MA R 50\n')
     for i in range(freq.size):
       fh.write('0.0%.8d   %8.6f %7.2f   %8.6f %7.2f   0.000000    0.00   0.000000    0.00\n' % (freq[i] * 1000, np.absolute(gamma[i]), np.angle(gamma[i], deg = True), np.absolute(gain[i]), np.angle(gain[i], deg = True)))
     fh.close()