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)
def exportContours(self): """Export defined contours.""" itab = self.itabs.currentIndex() ic0 = self.ici[itab] ih0 = self.ihi[itab] if ic0.contour is not None: if ic0.title in ['Flux', 'Coverage map', 'Flux [no atm. corr.]']: source = self.specCube.instrument else: source = ic0.title info = [('source', source), ('levels', ih0.levels)] data = OrderedDict(info) # Open a dialog fd = QFileDialog() fd.setLabelText(QFileDialog.Accept, "Export as") fd.setNameFilters(["Json Files (*.json)", "All Files (*)"]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) if (fd.exec()): filenames = fd.selectedFiles() filename = filenames[0] if filename[-5:] != '.json': filename += '.json' print("Exporting contour levels to file: ", filename) with io.open(filename, mode='w') as f: str_ = json.dumps(data, indent=2, separators=(',', ': '), ensure_ascii=False, cls=MyEncoder) f.write(str_) self.sb.showMessage("Aperture exported in file " + filename, 3000) else: return
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
def on_saveButton_clicked(self): if PATH.IS_SCREEN: DIR = PATH.SCREENDIR else: DIR = PATH.PANELDIR dialog = QFileDialog(self) options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog dialog.setOptions(options) dialog.setDirectory(DIR) dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("style files (*.qss *.style);;All files (*.*)") dialog.setWindowTitle('Save StyleSheet') dialog.setLabelText(QFileDialog.Accept, "Save") # sidebar links urls = [] urls.append(QUrl.fromLocalFile(os.path.expanduser('~'))) urls.append(QUrl.fromLocalFile(DIR)) urls.append( QUrl.fromLocalFile( os.path.join(os.getcwd(), 'qtvcp/screens', PATH.BASENAME))) dialog.setSidebarUrls(urls) result = dialog.exec_() if result: fileName = dialog.selectedFiles()[0] self.saveStyleSheet(fileName)
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()
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
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
def openLocalCube(self): """ Open local spectral cube.""" # Open a dialog fd = QFileDialog() fd.setLabelText(QFileDialog.Accept, "Import") fd.setNameFilters(["Fits Files (*.fits)", "All Files (*)"]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) fd.setFileMode(QFileDialog.ExistingFile) if (fd.exec()): filenames = fd.selectedFiles() cube_file = filenames[0] print("File selected is: ", filenames[0]) try: print('opening ', cube_file) self.data = specCube(cube_file) self.wcs = self.data.wcs # Check if coordinates are inside the image x, y = self.wcs.wcs_world2pix(self.lon, self.lat, 0) print('x y ', x, y) if x >= 0 and x <= self.data.nx and y >= 0 and y <= self.data.ny: print('Source inside the FITS cube') else: self.data = None self.wcs = None print('The selected FITS is not a valid file') except: self.data = None self.wcs = None print('The selected FITS is not a valid file')
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
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
def showOpenFile(self): dlg = QFileDialog(self) dlg.setWindowTitle(self.tr("Open Video Files")) dlg.setWindowModality(Qt.WindowModal) mimeFilters = [ "video/mp4", "video/quicktime", "video/x-msvideo", "video/x-ms-wmv" ] globPatterns = [] db = QMimeDatabase() for m in mimeFilters: mimeType = db.mimeTypeForName(m) if not mimeType.isValid(): logger.warn("Invalid MIME type: {}".format(m)) continue globPatterns.extend(mimeType.globPatterns()) globText = ' '.join(globPatterns) logger.debug("Video glob patterns: {}".format(globText)) dlg.setNameFilters([ self.tr("Video Files ({})").format(globText), self.tr("All Files (*)") ]) dlg.setAcceptMode(QFileDialog.AcceptOpen) dlg.setOption(QFileDialog.ReadOnly, True) dlg.setOption(QFileDialog.DontUseCustomDirectoryIcons, True) dlg.setLabelText(QFileDialog.Accept, self.tr("Open Movie")) dlg.setFileMode(QFileDialog.ExistingFiles) if dlg.exec_(): filenames = dlg.selectedFiles() self.processVideoFiles(filenames)
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 readMap(filename=None): """ Import alternate map file. """ if filename is None: fd = QFileDialog(None, "Load map file") fd.setLabelText(QFileDialog.Accept, "Import") fd.setNameFilters(["Map Files (*.txt)", "All Files (*)"]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) fd.setFileMode(QFileDialog.ExistingFile) if fd.exec(): fileNames = fd.selectedFiles() filename = fileNames[0] else: pass numlines = sum(1 for line in open(filename)) if numlines < 2: print('Map file is empty.') return else: print('Map has ', numlines, ' lines.') # read the first line - target coords in HH:MM:SS.SS, DD:MM:SS.SS file = open(filename) line = file.readline() if len(line.split()) != 6: print('File is not a map file.') return file.close() mapListPath = filename numMapPoints = numlines - 1 return numMapPoints, mapListPath
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
def export_account(self): # Testable way of using a QFileDialog export_dialog = QFileDialog(self) export_dialog.setObjectName('ExportFileDialog') export_dialog.setWindowTitle(self.tr("Export an account")) export_dialog.setNameFilter(self.tr("All account files (*.acc)")) export_dialog.setLabelText(QFileDialog.Accept, self.tr('Export')) export_dialog.setOption(QFileDialog.DontUseNativeDialog, True) export_dialog.accepted.connect(self.export_account_accepted) export_dialog.show()
def export_account(self): # Testable way of using a QFileDialog export_dialog = QFileDialog(self.widget) export_dialog.setObjectName('ExportFileDialog') export_dialog.setWindowTitle(self.tr("Export an account")) export_dialog.setNameFilter(self.tr("All account files (*.acc)")) export_dialog.setLabelText(QFileDialog.Accept, self.tr('Export')) export_dialog.setOption(QFileDialog.DontUseNativeDialog, True) export_dialog.accepted.connect(self.export_account_accepted) export_dialog.show()
def showDlg_path(self): dir_path = ".." dlg_files = QFileDialog() dlg_files.setFileMode(QFileDialog.Directory) dlg_files.setLabelText(QFileDialog.LookIn, 'Открыть каталог с демультиплексированными файлами ...') dlg_files.setAcceptMode(QFileDialog.AcceptOpen) dlg_files.setDirectory(dir_path) dlg_files.setOption(QFileDialog.ShowDirsOnly) if dlg_files.exec_(): self.fnames = dlg_files.selectedFiles() self.lbl_path.setText(self.fnames[0]) self.btn_start.setEnabled(True)
def selectFile(self, label): fd = QFileDialog() fd.setWindowTitle('Open ' + label + ' File') fd.setLabelText(QFileDialog.Accept, "Select " + label) fd.setNameFilters(["Fits Files (*.fit* *.FIT*)"]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) if (fd.exec()): fileNames = fd.selectedFiles() return fileNames[0] else: return None print("No file selected")
def show_dlg_path(self): index = self.btn_open_files.index(self.sender()) dir_path = '..' dlg_files = QFileDialog() dlg_files.setFileMode(QFileDialog.AnyFile) dlg_files.setLabelText(QFileDialog.LookIn, 'Выберите файл ТМП ...') dlg_files.setAcceptMode(QFileDialog.AcceptOpen) dlg_files.setDirectory(dir_path) if dlg_files.exec_(): dir_, self.fnames[index] = os.path.split( dlg_files.selectedFiles()[0]) self.lbl_path[index].setText(self.fnames[index]) self.fpath[index] = dlg_files.selectedFiles()[0] self.update_set_graph()
def openLocalCube(self): """ Open local spectral cube.""" # Open a dialog fd = QFileDialog() fd.setLabelText(QFileDialog.Accept, "Import") fd.setNameFilters([ "Fits Files (*.fit*)", "WXY fits files (*WXY*.fits*)", "All Files (*)" ]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) fd.setFileMode(QFileDialog.ExistingFile) if (fd.exec()): filenames = fd.selectedFiles() cube_file = filenames[0] print("File selected is: ", filenames[0]) try: print('opening ', cube_file) try: self.data = specCube(cube_file) except: self.data = specCubeAstro(cube_file) self.wcs = self.data.wcs newpixel = self.data.pixscale pixel = self.pixscale ratio = (pixel / newpixel)**2 print('area ratio: ', ratio) self.data.flux *= ratio # Check if coordinates are inside the image # This should be modified to check if the cube is inside the axes #x, y = self.wcs.wcs_world2pix(self.lon, self.lat, 0) #print('x y ', x, y) #if x >= 0 and x <= self.data.nx and y >= 0 and y <= self.data.ny: # print('Source inside the FITS cube') # # At this point the fluxes are rescaled to the pixel size # # of the original cube # newpixel = self.data.pixscale # pixel = self.specCube.pixscale # ratio = (newpixel/pixel)**2 # self.data.flux *= ratio #else: # self.data = None # self.wcs = None # print('The selected FITS is not a valid file') except: self.data = None self.wcs = None print('The selected FITS is not a valid file')
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
def saveAllCsv(self): """Save data for all currently plotted lines""" #Harsha: Plots were saved in GUI folder instead provided QFileDialog box to save to #user choose fileDialog2 = QFileDialog(self) fileDialog2.setFileMode(QFileDialog.Directory) fileDialog2.setWindowTitle('Select Directory to save plots') fileDialog2.setOptions(QFileDialog.ShowDirsOnly) fileDialog2.setLabelText(QFileDialog.Accept, self.tr("Save")) targetPanel = QFrame(fileDialog2) targetPanel.setLayout(QVBoxLayout()) layout = fileDialog2.layout() layout.addWidget(targetPanel) if fileDialog2.exec_(): directory = fileDialog2.directory().path() for line in list(self.lineToDataSource.keys()): self.saveCsv(line, directory)
def importContours(self): """Import defined contours.""" # Open a dialog fd = QFileDialog() fd.setLabelText(QFileDialog.Accept, "Import") fd.setNameFilters(["Json Files (*.json)", "All Files (*)"]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) fd.setFileMode(QFileDialog.ExistingFile) if (fd.exec()): filenames = fd.selectedFiles() print("Loading contour levels from file: ", filenames[0]) with open(filenames[0], 'r') as f: data = json.load(f) if self.contours == 'on': self.removeContours() self.drawContours(data['levels']) self.contours = 'on'
def browseLogFile(self): dialog = QFileDialog(self) #logFile = dialog.getSaveFileName(self, "Select log file", # DATADIR, "log file (*.log)") dialog.setLabelText(QFileDialog.Accept, "Select") dialog.setWindowTitle("Select path and enter name for log file") if dialog.exec(): logFile = dialog.selectedFiles() logFileFinal = logFile[0] if logFile == '': return if ("." not in logFile[0]): logFileFinal = logFile[0] + ".log" else: return self.ui.logfileEdit.setText(logFileFinal)
def loadTemplate(self): """Load a sct file.""" fd = QFileDialog(None, "Load Scan Template") fd.setLabelText(QFileDialog.Accept, "Import") fd.setDirectory(self.sctpath) fd.setNameFilters(["Scan Template (*.sct)", "All Files (*)"]) fd.setOptions(QFileDialog.DontUseNativeDialog) fd.setViewMode(QFileDialog.List) fd.setFileMode(QFileDialog.ExistingFile) if fd.exec(): fileName = fd.selectedFiles() sctfile = fileName[0] self.title = 'Observation maker for FIFI-LS [' + sctfile + ']' self.setWindowTitle(self.title) # Default settings self.TW.setDefaults() # Load template and update table widget self.TW.update_status('Loading ' + sctfile + "\n") self.TW.sctfile = sctfile self.aorParameters = readSct(sctfile) # self.TW.update_status(errmsg) self.TW.update_gui(self.aorParameters) self.sctpath = os.path.dirname(os.path.abspath(sctfile)) # self.TW.sctdir.setText(sctpath) Initiliaze with path of read file mapfile = os.path.basename(self.TW.mapListPath) self.TW.pathFile = self.sctpath self.TW.mapListPath = os.path.join(self.sctpath, mapfile) mapfile = self.TW.mapListPath print('mapfile ', mapfile) self.TW.update_status("mapfile: " + mapfile + "\n") if len(mapfile) > 0: try: noMapPoints, mapListPath = readMap(mapfile) print('map path ', mapListPath) self.TW.mapListPath = mapListPath self.TW.noMapPoints.setText(str(noMapPoints)) print('map loaded') # self.TW.update_status("Map loaded. \n") except: print('Invalid map file.') # First build print('First build ') self.TW.buildObs()
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
def download(self): fileDial = QFileDialog(self, 'Save "%s" torrent file' % self.torrent.name, '%s.torrent' % self.torrent.name, 'Torrent file (*.torrent);;all files (*)') fileDial.setAcceptMode(QFileDialog.AcceptSave) fileDial.setLabelText(QFileDialog.Accept, 'Save torrent file') fileDial.setLabelText(QFileDialog.FileName, 'Torrent file name') ok = (fileDial.exec_() == 1) if not ok: return result = fileDial.selectedFiles() if len(result) > 0: dest = result[0] data = self.backend.get_torrent_file(self.torrent.id) try: with open(unicode(dest), 'w') as f: f.write(data) except IOError as e: print('Unable to write .torrent in "%s": %s' % (dest, e), file=self.stderr) return 1 return
def instalar_biblioteca(self): caminho_bibliotecas = os.path.join(get_caminho_padrao(), "bibliotecas") dialogo = QFileDialog() dialogo.setWindowTitle("Escolher biblioteca") dialogo.setLabelText(QFileDialog.FileName, "Arquivo:") dialogo.setLabelText(QFileDialog.LookIn, "Buscar em:") dialogo.setLabelText(QFileDialog.FileType, "Tipo de arquivo:") dialogo.setLabelText(QFileDialog.Accept, "Escolher") dialogo.setLabelText(QFileDialog.Reject, "Cancelar") dialogo.setFileMode(QFileDialog.DirectoryOnly) dialogo.setDirectory(get_caminho_padrao()) if dialogo.exec_() == QFileDialog.Accepted: caminho = dialogo.selectedUrls()[0].path() if (caminho.startswith("/") and os.name == 'nt'): caminho = caminho[1:] # Testa se o arquivo existe if os.path.exists(caminho): try: shutil.copytree( caminho, os.path.join(caminho_bibliotecas, os.path.basename(caminho))) # Directories are the same except shutil.Error as e: print('Directory not copied. Error: %s' % e) # Any error saying that the directory doesn't exist except OSError as e: print('Directory not copied. Error: %s' % e) else: QMessageBox(QMessageBox.Warning, "Erro", "O arquivo não existe", QMessageBox.NoButton, self).show() else: return
def export(self): fileDial = QFileDialog(self, u'Export "%s" recipe' % self.recipe.title, u'%s.kreml' % self.recipe.id, '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 = recipe_to_krecipes_xml(self.recipe, author=self.backend.name) try: with codecs.open(dest, 'w', 'utf-8') as f: f.write(data) except IOError as e: print(u'Unable to write Krecipe file in "%s": %s' % (dest, e), file=self.stderr) return 1 return
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
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 show_dlg_path(self): dir_path = '..' dlg_files = QFileDialog() dlg_files.setFileMode(QFileDialog.AnyFile) dlg_files.setLabelText(QFileDialog.LookIn, 'Открыть файл канала режимов ...') dlg_files.setAcceptMode(QFileDialog.AcceptOpen) dlg_files.setDirectory(dir_path) if dlg_files.exec_(): self.table_cycl.clear() self.table_cycl.setRowCount(0) self.table_cycl.setColumnCount(3) self.table_cycl.setHorizontalHeaderLabels(["№", "Время", "Характеристика"]) self.fname = dlg_files.selectedFiles()[0] self.lbl_path.setText(self.fname) if self.thread is not None: self.thread.disconnect() self.thread = None self.num_order = self.get_numord() self.setStatusTip('Идет обработка...') self.thread = CyclogrModeThread(self.fname, self.num_order, self.grafik) self.thread.s_error[str].connect(self.showDlgErr) self.thread.finished.connect(self.finished_cyclogr_mode_thread) self.thread.s_mode.connect(self.update_table) self.thread.start()
def criar_dialogo_arquivo(titulo, acao): """ Cria dialogo personalizado para buscar arquivos :param titulo: Titulo de aba :param acao: Texto do botao de selecionar :return dialogo: dialogo """ dialogo = QFileDialog() dialogo.setWindowTitle(titulo) dialogo.setLabelText(QFileDialog.FileName, "Arquivo:") dialogo.setLabelText(QFileDialog.LookIn, "Buscar em:") dialogo.setLabelText(QFileDialog.FileType, "Tipo de arquivo:") dialogo.setLabelText(QFileDialog.Accept, acao) dialogo.setLabelText(QFileDialog.Reject, "Cancelar") dialogo.setNameFilters(["Rascunhos Br.ino (*.brpp)", "Rascunhos Arduino (*.ino)"]) dialogo.selectNameFilter("Rascunhos Br.ino (*.brpp)") dialogo.setDirectory(get_caminho_padrao()) return dialogo
def _get_files() -> list: # setup settings dialog = QFileDialog(parent=parent, caption=lang['ADD_NEW']['caption'], filter=lang['ADD_NEW']['filter'], directory=sys.path[0]) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setWindowIcon(QIcon(ZIP)) # setup labels dialog.setLabelText(QFileDialog.FileName, lang['ADD_NEW']['names']) dialog.setLabelText(QFileDialog.FileType, lang['ADD_NEW']['types']) dialog.setLabelText(QFileDialog.Accept, lang['ADD_NEW']['open']) dialog.setLabelText(QFileDialog.Reject, lang['ADD_NEW']['cancel']) # show dialog.show() if dialog.exec() == QFileDialog.Accepted: return dialog.selectedFiles() else: return []
class TermEditor(QWidget): signal_term_was_changed = pyqtSignal(Term) signal_stopped_editing_new_term = pyqtSignal(Term) # Undo, redo signal_can_undo = pyqtSignal(bool) signal_can_redo = pyqtSignal(bool) signal_undo_event = pyqtSignal() signal_redo_event = pyqtSignal() # sent when term links have been changed: add_links_to_term = pyqtSignal(Term, list) remove_links_from_term = pyqtSignal(Term, list) signal_current_term_is_valid = pyqtSignal(bool) def __init__(self, parent=None): super().__init__(parent) self._redo_text_edit = False self._undo_text_edit = False self.ui = Ui_TermEditor() self.ui.setupUi(self) # This is used for detecting if the term content has changed: self._old_term = Term() # Dialogs: self.term_chooser = StrChooser(self) self.term_remover = StrChooser(self) self.file_chooser = QFileDialog() self.file_remover = StrChooser(self) self.file_remover.set_title("Unlinkable files") self.term_chooser.set_title("Linkable terms") self.term_remover.set_title("Unlinkable terms") self.file_chooser.setLabelText(QFileDialog.Accept, "Link") self.file_chooser.setWindowTitle("Choose files to link.") # We add term linker at the botom of this widget: self.term_linker = TermLinker() self.ui.verticalLayout.addWidget(self.term_linker) self._init_actions() self.ui.lineEditTitle.text = "" self._current_term = Term() self._current_term_has_changed = False # Hook into undo/redo of term_editor self.eventFilter = KeyPressEater(QKeySequence.Undo, self) self.eventFilter2 = KeyPressEater(QKeySequence.Redo, self) self.ui.textEditContent.installEventFilter(self.eventFilter) self.ui.textEditContent.installEventFilter(self.eventFilter2) self.ui.lineEditTitle.installEventFilter(self.eventFilter) self.ui.lineEditTitle.installEventFilter(self.eventFilter2) self._init_term_linker() self._init_signals() def set_term(self, term: Term): """ Sets the current term to be edited. :param term: Term to edit """ self.clear() self._current_term = copy.copy(term) self._check_undo_redo() self._old_term = term if self._old_term.term is "": logging.debug("new term") self.signal_current_term_is_valid.emit(False) self.term_linker.term_linking_enabled(False) self.ui.lineEditTitle.setFocus() else: logging.debug("old term") self.term_linker.update_links(term) self.term_linker.term_linking_enabled(True) self.ui.lineEditTitle.setText(term.term) self.ui.textEditContent.setText(term.description) self.ui.textEditContent.setFocus() def show(self): """ Hooks in to the super class show method and enables file linking and unlinking actions when term editor is shown. """ self.act_link_files.setEnabled(True) self.act_unlink_files.setEnabled(True) super().show() def hide(self): """ When term editor is hidden the changes need to be saved. In other words this is the place, that updates the content of a term or sends a new term to the TermController. A new term object is always emitted when editing a new term stops and the term has non empty term string (Term.term). If we are editing already existing term, term editor sets a _current_term_has_changed to True if the content, term string or linked things have changed. Signal signal_term_was_changed(Term) is emitted if the term has changed. Also the undo-redo history of the editing session is forgotten and the undo is set to the version of the term that existed before the start of the editing session. Before hiding term editing related actions are enabled (undo, redo, linking/unlinking of files and linking/unlinking of terms). """ if self._old_term.term is "" and \ self.ui.lineEditTitle.displayText() is not "": self._current_term = self._fill_term(self._current_term) self.signal_stopped_editing_new_term.emit(self._current_term) self.clear() else: self._increment_term_version() if self._current_term_has_changed: self._old_term.next_term = self._current_term self._current_term.next_term = None self.signal_term_was_changed.emit(self._current_term) self.clear() self.act_undo.setEnabled(False) self.act_redo.setEnabled(False) self.act_link_files.setEnabled(False) self.act_unlink_files.setEnabled(False) self.term_linker.term_linking_enabled(False) super().hide() def _increment_term_version(self, force: bool=False): """ This creates a new Term object of current term, if the content of the term (eg. term string or description of the term) have changed or if the increment is forced. :param force: increments version anyway if True :return: True if the version was incremented. """ if (self.ui.lineEditTitle.displayText() != self._old_term.term or self.ui.textEditContent.toPlainText() != self._old_term.description or force): self._current_term.initialize_next_term() self._current_term = self._current_term.next_term self._fill_term(self._current_term) self._current_term_has_changed = True return True return False def clear(self): """ This method clears all the text in term editor, linked things in term_linker and set's _current_term to an empty Term object. """ self.ui.lineEditTitle.clear() self.ui.textEditContent.clear() self.term_linker.clear() self._current_term = Term() self._old_term = Term() self._current_term_has_changed = False def _fill_term(self, term: Term): """ This method read the content of Term.term input field and Term.description editor to a Term object. :param term: Term to fill :return: filled term """ logging.debug("Filling the term") term.term = self.ui.lineEditTitle.displayText() text = self.ui.textEditContent.toPlainText() white_space_removed = list() for line in text.splitlines(): white_space_removed.append(line.rstrip()) term.description = os.linesep.join(white_space_removed) return term def _trigger_event(self, sequence: QKeySequence): """ This is triggered when KeyPressEater filter has caught undo or redo key combination on term line editor or term description editor and delegates the undo/redo action to this class's undo/redo methods. :param sequence: captured key combination as QKeySequence """ if sequence is QKeySequence.Undo: self.undo() if sequence is QKeySequence.Redo: self.redo() @pyqtSlot() def _validate_term(self): """ This slot checks the validity of the filled term on term editor e.g. it ensures that the filled value for Term.term is not "". If Term is valid signal_current_term_is_valid(True) is emitted and if it's not signal_current_term_is_valid(False) is emitted. """ if self.ui.lineEditTitle.displayText() is "": self.signal_current_term_is_valid.emit(False) else: self.signal_current_term_is_valid.emit(True) ######## # TAGS # ######## @pyqtSlot(str, str) def _add_tag(self, item_str: str, group_name: str): """ This is triggered when an item in term linker is activated. We set in _init_term_linker method the different item groups for the term linker. So we can add the appropriate tag based on the group name we have given. """ if group_name == "Image": self.add_image_tag( self._current_term.get_non_project_file_path(item_str)) @pyqtSlot() def add_image_tag(self, path: Path=Path("/path/to/image"), str_title: str="Image title"): """ This adds an image tag to term description editor at the current position of the caret. :param path: Optional parameter. Path to the image to show. :param str_title: Caption for the image. """ self.ui.textEditContent.insertPlainText('#img("' + str(path) + '","' + str_title + '")') @pyqtSlot() def add_title_tag(self, str_title: str="Title"): """ This adds an title tag to term description editor at the current position of the caret. :param str_title: text for title. """ self.ui.textEditContent.insertPlainText( "##" + str_title + "##" + os.linesep + os.linesep) @pyqtSlot() def add_bullet_list_tag(self): """ Add Bullet list tag to editor """ self.ui.textEditContent.insertPlainText( os.linesep + "##LIST##" + os.linesep + "item1" + os.linesep + "item2" + os.linesep + "item3" + os.linesep + "##END##" + os.linesep ) @pyqtSlot() def add_ASCII_tag(self): """ Add ASCII tag to editor """ self.ui.textEditContent.insertPlainText( os.linesep + "##ASCII##" + os.linesep + "+---+" + os.linesep + "| |" + os.linesep + "+---+" + os.linesep + "##END##" + os.linesep ) ############################## # LINKING OF TERMS AND FILES # ############################## @pyqtSlot() def link_terms(self): """ A slot that invokes linking of terms to current term. When raised term_chooser dialog (StrChooser) is accepted execution continues from _link_terms_accepted method. """ a_list = self.parent().term_str_browser.get_list() black_list = [] if self._current_term.term: black_list.append(self._current_term.term) if self._current_term.related_terms: for term_str in self._current_term.related_terms: black_list.append(term_str) [a_list.remove(item) for item in black_list] self.term_chooser.set_list(a_list) self.term_chooser.show() @pyqtSlot(list) def _link_terms_accepted(self, str_list): """ Links terms given as a list of strings to current term. When list of terms to add is given the linking is delegated by emitting add_links_to_term(Term, str_list of terms) signal. When terms have been linked the list of linked things is updated by invoking term_linker.update_links(current_term). :param str_list: list of terms as a string to link """ if len(str_list) > 0: self._increment_term_version(True) self.add_links_to_term.emit(self._current_term, str_list) self.term_linker.update_links(self._current_term) @pyqtSlot() def unlink_terms(self): """ A slot that invokes unlinking of terms from current term. When raised term_remover dialog (StrChooser) is accepted execution continues from _unlink_terms_accepted method. """ self.term_remover.set_list(self._current_term.related_terms) self.term_remover.show() @pyqtSlot(list) def _unlink_terms_accepted(self, str_list): """ Unlinks terms given as a list of strings to current term. When list of terms to remove is given the unlinking is delegated by emitting remove_links_from_term(Term, str_list of terms) signal. When terms have been un linked the list of linked things is updated by invoking term_linker.update_links(current_term). :param str_list: list of terms as a string to link """ if len(str_list) > 0: self._increment_term_version(True) self.remove_links_from_term.emit(self._current_term, str_list) self.term_linker.update_links(self._current_term) @pyqtSlot() def unlink_files(self): """ A slot that invokes unlinking of files from current term. When raised file_remover dialog (StrChooser) is accepted execution continues from _unlink_files_accepted method. """ all_files = list() [all_files.append(file.name) for file in self._current_term.linked_files] [all_files.append(image.name) for image in self._current_term.linked_images] self.file_remover.set_list(all_files) self.file_remover.show() @pyqtSlot(list) def _unlink_files_accepted(self, str_list): """ Unlinks files given as a list of strings containing the filename from current term. When files have been removed the list of linked things is updated by invoking term_linker.update_links(current_term). :param str_list: list of file names as a string to unlink. """ logging.debug("Unlink files accepted with: " + str(str_list)) if len(str_list) > 0: self._increment_term_version(True) for str_file in str_list: self._current_term.unlink_file(Path(str_file)) self.term_linker.update_links(self._current_term) @pyqtSlot() def link_files(self): """ A slot that invoke linking of files to current term. After the files have been linked to current term the term_linker is updated by invoking term_linker.update_links(current_term) method. """ file_names = self.file_chooser.getOpenFileNames( self, "Select a file", '', "All Files (*)", '') if file_names is not None and file_names[0] is not None: self._increment_term_version(True) for file_name in file_names[0]: self._current_term.link_file(Path(file_name)) self.term_linker.update_links(self._current_term) #################################### # UNDO - REDO and COPY, CUT, PASTE # #################################### @pyqtSlot() def _copy(self): """ This slot routes copying to right widget when copy action is invoked (when copy is chosen from main window menu). """ if self.ui.textEditContent.hasFocus(): self.ui.textEditContent.copy() if self.ui.lineEditTitle.hasFocus(): self.ui.lineEditTitle.copy() @pyqtSlot() def _paste(self): """ This slot routes paste to right widget when paste action is invoked (when paste is chosen from main window menu). """ if self.ui.textEditContent.hasFocus(): self.ui.textEditContent.paste() if self.ui.lineEditTitle.hasFocus(): self.ui.lineEditTitle.paste() @pyqtSlot() def _cut(self): """ This slot routes cut to right widget when cut action is invoked (when cut is chosen from main window menu). """ if self.ui.textEditContent.hasFocus(): self.ui.textEditContent.cut() if self.ui.lineEditTitle.hasFocus(): self.ui.lineEditTitle.cut() @pyqtSlot() def undo(self): """ Undoes edit. If undo is available in text editor for term content, it is undone. If undo is not available in text editor for content it is checked if the title field for Term.term has undo available. If it has, term title edits are undone. When term field runs out of undoes it is checked if the term it self has older version linked to it. When we run out of undo for current term signal_can_undo(False) is emitted. """ if self._undo_text_edit: self.ui.textEditContent.undo() elif self.ui.lineEditTitle.isUndoAvailable(): self.ui.lineEditTitle.undo() elif not self._current_term or not self._current_term.can_undo: self.act_undo.setEnabled(False) else: self.set_term(self._current_term.previous_term) self.check_if_can_undo() @pyqtSlot() def redo(self): """ Redoes undone edit. If redo is available in term title field for term, it is redone. If redo is not available in term title field for Term.term, it is checked if the term text editor for term content has redo available. If it has, content edits are redone. When term text editor runs out of redoes it is checked if the term it self has newer version linked to it. When we run out of redo for current term signal_can_redo(False) is emitted. """ if self.ui.lineEditTitle.isRedoAvailable(): self.ui.lineEditTitle.redo() elif self._redo_text_edit: self.ui.textEditContent.redo() elif not self._current_term or not self._current_term.can_redo: self.act_redo.setEnabled(False) else: self.set_term(self._current_term.next_term) self.check_if_can_redo() @pyqtSlot(bool) def _redo_available_in_text_edit(self, boolean): """ This slot is triggered from term content editor when it runs out of redo (boolean=False) or becomes able to redo (boolean=True). :param boolean: True if textEditContent can redo, False if can't. """ self._redo_text_edit = boolean self.check_if_can_redo() @pyqtSlot(bool) def _undo_available_in_text_edit(self, boolean): """ This slot is triggered from term content editor when it runs out of undo (boolean=False) or becomes able to undo (boolean=True). :param boolean: True if textEditContent can undo, False if can't. """ self._undo_text_edit = boolean self.check_if_can_undo() @pyqtSlot() def _check_undo_redo(self): """ This is a helper method to check if there are undoes and redoes left. """ self.check_if_can_undo() self.check_if_can_redo() def check_if_can_undo(self): """ If term text editor or term title line edit can undo undo (action act_undo) is enabled. if they can't undo it is checked if the current term is None and if so undo action is disabled. If current term is not None the term is queried if undo is available and the boolean value for the query is set for action undo availability. """ if self._undo_text_edit or self.ui.lineEditTitle.isUndoAvailable(): self.act_undo.setEnabled(True) else: self.act_undo.setEnabled(self._current_term.can_undo) def check_if_can_redo(self): """ If term text editor or term title line edit can redo action act_redo for redo is enabled. if they can't redo it is checked if the current term is None and if so the redo action is disabled. If current term is not None the term is queried if redo is available and the boolean value for the query set as the value of availability of redo. """ if self._redo_text_edit or self.ui.lineEditTitle.isRedoAvailable(): self.act_redo.setEnabled(True) else: self.act_redo.setEnabled(self._current_term.can_redo) ########################## # INITIALIZATION METHODS # ########################## def _init_actions(self): # Edit self.act_copy = make_action_helper( self, "Copy", "Copy to clipboard", QKeySequence.Copy, QIcon.fromTheme('edit-copy')) self.act_copy.triggered.connect(self._copy) self.act_paste = make_action_helper( self, "Paste", "Paste from clipboard", QKeySequence.Paste, QIcon.fromTheme('edit-paste')) self.act_paste.triggered.connect(self._paste) self.act_cut = make_action_helper( self, "Cut", "Cut to clipboard", QKeySequence.Cut, QIcon.fromTheme('edit-cut')) self.act_cut.triggered.connect(self._cut) self.act_undo = make_action_helper( self, "Undo", "Undo previous change", QKeySequence.Undo, QIcon.fromTheme('edit-undo')) self.act_undo.triggered.connect(self.undo) self.act_redo = make_action_helper( self, "Redo", "Redo undone change", QKeySequence.Redo, QIcon.fromTheme('edit-redo')) self.act_redo.triggered.connect(self.redo) # Linking of files self.act_link_files = make_action_helper( self, "Link &files", "Link files to current term", "ctrl+l", QIcon.fromTheme('list-add')) self.act_link_files.triggered.connect(self.link_files) self.act_unlink_files = make_action_helper( self, "U&nlink files", "Unlink files from current term", "ctrl+u", QIcon.fromTheme('list-remove')) self.act_unlink_files.triggered.connect(self.unlink_files) def _init_term_linker(self): self.term_linker.ui_link_list.add_item_group("Term", "Yellow", "Black") self.term_linker.ui_link_list.add_item_group("Image", "Cyan", "Black") self.term_linker.ui_link_list.add_item_group( "File", "Magenta", "Black") def _init_signals(self): # Editing self.ui.addImageToolButton.clicked.connect(self.add_image_tag) self.ui.addTitleToolButton.clicked.connect(self.add_title_tag) self.ui.addASCIIToolButton.clicked.connect(self.add_ASCII_tag) self.ui.addBulletListToolButton.clicked.connect( self.add_bullet_list_tag) self.ui.lineEditTitle.textChanged.connect(self._validate_term) self.ui.lineEditTitle.textChanged.connect(self._check_undo_redo) self.ui.textEditContent.textChanged.connect(self._check_undo_redo) self.ui.textEditContent.redoAvailable.connect( self._redo_available_in_text_edit) self.ui.textEditContent.undoAvailable.connect( self._undo_available_in_text_edit) # Linking of terms self.term_linker.linkTermsClicked.connect(self.link_terms) self.term_linker.unlinkTermsClicked.connect(self.unlink_terms) self.term_chooser.str_list_accepted.connect(self._link_terms_accepted) self.term_remover.str_list_accepted.connect( self._unlink_terms_accepted) # Linking of files self.term_linker.add_file.connect(self.link_files) self.term_linker.remove_files.connect(self.unlink_files) self.file_remover.str_list_accepted.connect( self._unlink_files_accepted) self.term_linker.ui_link_list.signal_item_activated.connect( self._add_tag)
class MainWindow(QMainWindow, Ui_MainWindow): ''' classdocs ''' def __init__(self, app): """ Init :param cutecoin.core.app.Application app: application :type: cutecoin.core.app.Application """ # Set up the user interface from Designer. super().__init__() self.setupUi(self) QApplication.setWindowIcon(QIcon(":/icons/cutecoin_logo")) self.app = app logging.debug(app.thread()) logging.debug(self.thread()) self.password_asker = None self.initialized = False self.busybar = QProgressBar(self.statusbar) self.busybar.setMinimum(0) self.busybar.setMaximum(0) self.busybar.setValue(-1) self.statusbar.addWidget(self.busybar) self.busybar.hide() self.app.version_requested.connect(self.latest_version_requested) self.app.get_last_version() self.combo_referential = QComboBox(self) self.combo_referential.setEnabled(False) self.combo_referential.currentIndexChanged.connect(self.referential_changed) self.status_label = QLabel("", self) self.status_label.setTextFormat(Qt.RichText) self.label_time = QLabel("", self) self.statusbar.addPermanentWidget(self.status_label, 1) self.statusbar.addPermanentWidget(self.label_time) self.statusbar.addPermanentWidget(self.combo_referential) self.update_time() self.loader = Loader(self.app) self.loader.loaded.connect(self.loader_finished) self.loader.connection_error.connect(self.display_error) self.homescreen = HomeScreenWidget(self.app) self.centralWidget().layout().addWidget(self.homescreen) self.homescreen.button_new.clicked.connect(self.open_add_account_dialog) self.homescreen.button_import.clicked.connect(self.import_account) self.open_ucoin_info = lambda: QDesktopServices.openUrl(QUrl("http://ucoin.io/theoretical/")) self.homescreen.button_info.clicked.connect(self.open_ucoin_info) self.import_dialog = None self.export_dialog = None # TODO: There are too much refresh() calls on startup self.refresh() def open_add_account_dialog(self): dialog = ProcessConfigureAccount(self.app, None) result = dialog.exec_() if result == QDialog.Accepted: self.action_change_account(self.app.current_account.name) @pyqtSlot(str) def display_error(self, error): QMessageBox.critical(self, ":(", error, QMessageBox.Ok) @pyqtSlot(str) def referential_changed(self, index): if self.app.current_account: self.app.current_account.set_display_referential(index) if self.currencies_tabwidget.currentWidget(): self.currencies_tabwidget.currentWidget().referential_changed() @pyqtSlot() def update_time(self): date = QDate.currentDate() self.label_time.setText("{0}".format(date.toString("dd/MM/yyyy"))) next_day = date.addDays(1) current_time = QDateTime().currentDateTime().toMSecsSinceEpoch() next_time = QDateTime(next_day).toMSecsSinceEpoch() timer = QTimer() timer.timeout.connect(self.update_time) timer.start(next_time - current_time) @pyqtSlot() def delete_contact(self): contact = self.sender().data() self.app.current_account.contacts.remove(contact) self.refresh_contacts() @pyqtSlot() def edit_contact(self): index = self.sender().data() dialog = ConfigureContactDialog(self.app.current_account, self, None, index) result = dialog.exec_() if result == QDialog.Accepted: self.window().refresh_contacts() def action_change_account(self, account_name): def loading_progressed(value, maximum): logging.debug("Busybar : {:} : {:}".format(value, maximum)) self.busybar.setValue(value) self.busybar.setMaximum(maximum) QApplication.processEvents() if self.app.current_account: self.app.save_cache(self.app.current_account) self.app.current_account = None self.refresh() QApplication.setOverrideCursor(Qt.BusyCursor) self.app.loading_progressed.connect(loading_progressed) self.busybar.setMinimum(0) self.busybar.setMaximum(0) self.busybar.setValue(-1) self.busybar.show() self.status_label.setText(self.tr("Loading account {0}").format(account_name)) self.loader.set_account_name(account_name) QTimer.singleShot(10, self.loader.load) self.homescreen.button_new.hide() self.homescreen.button_import.hide() @pyqtSlot() def loader_finished(self): logging.debug("Finished loading") self.refresh() self.busybar.hide() QApplication.setOverrideCursor(Qt.ArrowCursor) try: self.app.disconnect() except: logging.debug("Disconnect of app failed") self.app.monitor.start_network_watchers() QApplication.processEvents() def open_transfer_money_dialog(self): dialog = TransferMoneyDialog(self.app.current_account, self.password_asker) dialog.accepted.connect(self.refresh_wallets) if dialog.exec_() == QDialog.Accepted: currency_tab = self.currencies_tabwidget.currentWidget() currency_tab.tab_history.table_history.model().sourceModel().refresh_transfers() def open_certification_dialog(self): dialog = CertificationDialog(self.app.current_account, self.password_asker) dialog.exec_() def open_add_contact_dialog(self): dialog = ConfigureContactDialog(self.app.current_account, self) result = dialog.exec_() if result == QDialog.Accepted: self.window().refresh_contacts() def open_configure_account_dialog(self): dialog = ProcessConfigureAccount(self.app, self.app.current_account) result = dialog.exec_() if result == QDialog.Accepted: if self.app.current_account: self.action_change_account(self.app.current_account.name) else: self.refresh() def open_preferences_dialog(self): dialog = PreferencesDialog(self.app) result = dialog.exec_() def open_about_popup(self): """ Open about popup window """ aboutDialog = QDialog(self) aboutUi = Ui_AboutPopup() aboutUi.setupUi(aboutDialog) latest = self.app.available_version version_info = "" version_url = "" if not latest[0]: version_info = self.tr("Latest release : {version}") \ .format(version=latest[1]) version_url = latest[2] new_version_text = """ <p><b>{version_info}</b></p> <p><a href="{version_url}">{link_text}</a></p> """.format(version_info=version_info, version_url=version_url, link_text=self.tr("Download link")) else: new_version_text = "" text = self.tr(""" <h1>Cutecoin</h1> <p>Python/Qt uCoin client</p> <p>Version : {:}</p> {new_version_text} <p>License : MIT</p> <p><b>Authors</b></p> <p>inso</p> <p>vit</p> <p>canercandan</p> """).format(__version__, new_version_text=new_version_text) aboutUi.label.setText(text) aboutDialog.show() @pyqtSlot() def latest_version_requested(self): latest = self.app.available_version logging.debug("Latest version requested") if not latest[0]: version_info = self.tr("Please get the latest release {version}") \ .format(version=latest[1]) version_url = latest[2] toast.display("Cutecoin", """<p>{version_info}</br> <a href={version_url}>Download link</a></p>""".format( version_info=version_info, version_url=version_url)) def refresh_wallets(self): currency_tab = self.currencies_tabwidget.currentWidget() if currency_tab: currency_tab.refresh_wallets() def refresh_communities(self): logging.debug("CLEAR") self.currencies_tabwidget.clear() if self.app.current_account: for community in self.app.current_account.communities: tab_currency = CurrencyTabWidget(self.app, community, self.password_asker, self.status_label) tab_currency.refresh() self.currencies_tabwidget.addTab(tab_currency, QIcon(":/icons/currency_icon"), community.name) def refresh_accounts(self): self.menu_change_account.clear() signal_mapper = QSignalMapper(self) for account_name in sorted(self.app.accounts.keys()): action = QAction(account_name, self) self.menu_change_account.addAction(action) signal_mapper.setMapping(action, account_name) action.triggered.connect(signal_mapper.map) signal_mapper.mapped[str].connect(self.action_change_account) def refresh_contacts(self): self.menu_contacts_list.clear() if self.app.current_account: for index, contact in enumerate(self.app.current_account.contacts): contact_menu = self.menu_contacts_list.addMenu(contact['name']) edit_action = contact_menu.addAction(self.tr("Edit")) edit_action.triggered.connect(self.edit_contact) edit_action.setData(index) delete_action = contact_menu.addAction(self.tr("Delete")) delete_action.setData(contact) delete_action.triggered.connect(self.delete_contact) def refresh(self): ''' Refresh main window When the selected account changes, all the widgets in the window have to be refreshed ''' logging.debug("Refresh started") self.refresh_accounts() if self.app.current_account is None: self.currencies_tabwidget.hide() self.homescreen.show() self.setWindowTitle(self.tr("CuteCoin {0}").format(__version__)) self.menu_account.setEnabled(False) self.action_configure_parameters.setEnabled(False) self.action_set_as_default.setEnabled(False) self.combo_referential.setEnabled(False) self.status_label.setText(self.tr("")) self.password_asker = None else: logging.debug("Show currencies loading") self.currencies_tabwidget.show() logging.debug("Hide homescreen") self.homescreen.hide() self.password_asker = PasswordAskerDialog(self.app.current_account) self.combo_referential.blockSignals(True) self.combo_referential.clear() for ref in self.app.current_account.referentials: self.combo_referential.addItem(QCoreApplication.translate('Account', ref[4])) self.combo_referential.setEnabled(True) self.combo_referential.blockSignals(False) logging.debug(self.app.preferences) self.combo_referential.setCurrentIndex(self.app.preferences['ref']) self.menu_account.setEnabled(True) self.action_configure_parameters.setEnabled(True) self.setWindowTitle(self.tr("CuteCoin {0} - Account : {1}").format(__version__, self.app.current_account.name)) self.refresh_communities() self.refresh_wallets() self.refresh_contacts() def import_account(self): self.import_dialog = ImportAccountDialog(self.app, self) self.import_dialog.accepted.connect(self.import_account_accepted) self.import_dialog.exec_() def import_account_accepted(self): # open account after import self.action_change_account(self.import_dialog.edit_name.text()) def export_account(self): # Testable way of using a QFileDialog self.export_dialog = QFileDialog(self) self.export_dialog.setObjectName('ExportFileDialog') self.export_dialog.setWindowTitle(self.tr("Export an account")) self.export_dialog.setNameFilter(self.tr("All account files (*.acc)")) self.export_dialog.setLabelText(QFileDialog.Accept, self.tr('Export')) self.export_dialog.accepted.connect(self.export_account_accepted) self.export_dialog.show() def export_account_accepted(self): selected_file = self.export_dialog.selectedFiles() if selected_file: if selected_file[0][-4:] == ".acc": path = selected_file[0] else: path = selected_file[0] + ".acc" self.app.export_account(path, self.app.current_account) def closeEvent(self, event): if self.app.current_account: self.app.save_cache(self.app.current_account) self.app.save_persons() super().closeEvent(event) def showEvent(self, event): super().showEvent(event) if not self.initialized: # if default account in preferences... if self.app.preferences['account'] != "": logging.debug("Loading default account") self.action_change_account(self.app.preferences['account']) # no default account... else: # if at least one account exists, set it as default... if len(self.app.accounts) > 0: # capture names sorted alphabetically names = list(self.app.accounts.keys()) names.sort() # set first name in list as default in preferences self.app.preferences['account'] = names[0] self.app.save_preferences(self.app.preferences) # open it logging.debug("No default account in preferences. Set %s as default account." % names[0]) self.action_change_account(self.app.preferences['account']) self.initialized = True
class Dialog(): def __init__(self, mainform): self.__mainform = mainform self.__dialog = QFileDialog() self.__directory = '' self.__filename = ['', '', ''] self.__filters = [] self.__default_filter_index = 0 self.__path = '' @property def path(self): return self.__path @property def filename(self): return self.__filename @property def directory(self): return self.__directory @directory.setter def directory(self, value): self.__directory = value @property def filters(self): return self.__filters @filters.setter def filters(self, value): self.__filters = value @property def default_filter_index(self): return self.__default_filter_index @default_filter_index.setter def default_filter_index(self, value): self.__default_filter_index = value def exec(self, load =True): self.__dialog.setNameFilters(self.__filters) self.__dialog.selectNameFilter(self.__filters[self.__default_filter_index]) self.__dialog.setDirectory(self.__directory) if load == True: self.__dialog.setLabelText(QFileDialog.Accept, 'Yes') self.__dialog.setWindowTitle('Yes') else: self.__dialog.setLabelText(QFileDialog.Accept, 'Save as') self.__dialog.setWindowTitle('Save as') if self.__dialog.exec() == QDialog.Accepted: self.__path = self.__dialog.selectedFiles()[0] fn = os.path.split(self.__path) ex = os.path.splitext(self.__path)[1] self.__filename = [fn[0], fn[1], ex[1:len(ex)]] print(self.__filename) print(os.pathsep)