def openStrandSequenceFile(self): """ Open (read) the user specified Strand sequence file and enter the sequence in the Strand sequence Text edit. Note that it ONLY reads the FIRST line of the file. @TODO: It only reads in the first line of the file. Also, it doesn't handle any special cases. (Once the special cases are clearly defined, that functionality will be added. """ if self.parentWidget.assy.filename: odir = os.path.dirname(self.parentWidget.assy.filename) else: odir = env.prefs[workingDirectory_prefs_key] self.sequenceFileName = \ str(QFileDialog.getOpenFileName( self, "Load Strand Sequence", odir, "Strand Sequnce file (*.txt);;All Files (*.*);;")) lines = self.sequenceFileName try: lines = open(self.sequenceFileName, "rU").readlines() except: print "Exception occurred to open file: ", self.sequenceFileName return sequence = lines[0] sequence = QString(sequence) sequence = sequence.toUpper() self._updateSequenceAndItsComplement(sequence) return
def import_bookmarks(self): filename = QFileDialog.getOpenFileName(self, _("Import Bookmarks"), '%s' % os.getcwdu(), _("Pickled Bookmarks (*.pickle)")) if not filename: return imported = None with open(filename, 'r') as fileobj: imported = cPickle.load(fileobj) if imported is not None: bad = False try: for bm in imported: if 'title' not in bm: bad = True break except: pass if not bad: bookmarks = self.get_bookmarks() for bm in imported: if bm not in bookmarks: bookmarks.append(bm) self.set_bookmarks([bm for bm in bookmarks if bm['title'] != 'calibre_current_page_bookmark'])
def import_bookmarks(self): filename = QFileDialog.getOpenFileName(self, _("Import Bookmarks"), '%s' % os.getcwdu(), _("Pickled Bookmarks (*.pickle)")) if filename == '': return imported = None with open(filename, 'r') as fileobj: imported = cPickle.load(fileobj) if imported != None: bad = False try: for bm in imported: if len(bm) != 2: bad = True break except: pass if not bad: bookmarks = self._model.bookmarks[:] for bm in imported: if bm not in bookmarks and bm['title'] != 'calibre_current_page_bookmark': bookmarks.append(bm) self.set_bookmarks(bookmarks)
def import_bookmarks(self): filename = QFileDialog.getOpenFileName( self, _("Import Bookmarks"), '%s' % os.getcwdu(), _("Pickled Bookmarks (*.pickle)")) if not filename: return imported = None with open(filename, 'r') as fileobj: imported = cPickle.load(fileobj) if imported is not None: bad = False try: for bm in imported: if len(bm) != 2: bad = True break except: pass if not bad: bookmarks = self.get_bookmarks() for bm in imported: if bm not in bookmarks and bm[ 'title'] != 'calibre_current_page_bookmark': bookmarks.append(bm) self.set_bookmarks(bookmarks)
def openStrandSequenceFile(self): """ Open (read) the user specified Strand sequence file and enter the sequence in the Strand sequence Text edit. Note that it ONLY reads the FIRST line of the file. @TODO: It only reads in the first line of the file. Also, it doesn't handle any special cases. (Once the special cases are clearly defined, that functionality will be added. """ if self.parentWidget.assy.filename: odir = os.path.dirname(self.parentWidget.assy.filename) else: odir = env.prefs[workingDirectory_prefs_key] self.sequenceFileName = \ str(QFileDialog.getOpenFileName( self, "Load Strand Sequence", odir, "Strand Sequnce file (*.txt);;All Files (*.*);;")) lines = self.sequenceFileName try: lines = open(self.sequenceFileName, "rU").readlines() except: print "Exception occurred to open file: ", self.sequenceFileName return sequence = lines[0] sequence = QString(sequence) sequence = sequence.toUpper() self._updateSequenceAndItsComplement(sequence) return
def read_element_rgb_table(self): """ Open file browser to select a file to read from, read the data, update elements color in the selector dialog and also the display models """ # Determine what directory to open. import os if self.w.assy.filename: odir = os.path.dirname(self.w.assy.filename) else: from utilities.prefs_constants import workingDirectory_prefs_key odir = env.prefs[workingDirectory_prefs_key] self.fileName = str( QFileDialog.getOpenFileName( self, "Load Element Color", odir, "Elements color file (*.txt);;All Files (*.*);;" )) if self.fileName: colorTable = readElementColors(self.fileName) if not colorTable: env.history.message(redmsg("Error in element colors file: [" + self.fileName + "]. Colors not loaded.")) else: env.history.message("Element colors loaded from file: [" + self.fileName + "].") for row in colorTable: row[1] /= 255.0; row[2] /= 255.0; row[3] /= 255.0 self.elemTable.setElemColors(colorTable) self._updateModelDisplay() elemNum = self.elementButtonGroup.checkedId() self.setDisplay(elemNum) #After loading a file, reset the flag self.isElementModified = False
def _open_FASTA_File(self): """ Open (read) the user specified FASTA sequence file and load it into the sequence field. @TODO: It only reads in the first line of the file. Also, it doesn't handle any special cases. (Once the special cases are clearly defined, that functionality will be added. @attention: This is not implemented yet. """ #Urmi 20080714: should not this be only fasta file, for both load and save if self.parentWidget.assy.filename: odir = os.path.dirname(self.parentWidget.assy.filename) else: odir = env.prefs[workingDirectory_prefs_key] self.sequenceFileName = \ str(QFileDialog.getOpenFileName( self, "Load FASTA sequence for " + self.current_protein.name, odir, "FASTA file (*.txt);;All Files (*.*);;")) lines = self.sequenceFileName try: lines = open(self.sequenceFileName, "rU").readlines() except: print "Exception occurred to open file: ", self.sequenceFileName return sequence = lines[0] sequence = QString(sequence) sequence = sequence.toUpper() self._setSequence(sequence) return
def LoadAction(self): if not self.MainProgramm.DataSaved : msgbox = QMessageBox(QMessageBox.Question, "Frage", "Soll die vorherige Messung ueberschrieben werden ?", QMessageBox.No| QMessageBox.Yes) if not msgbox.exec_() == QMessageBox.Yes: return filename = QFileDialog.getOpenFileName(self,"Messung laden") if not filename == '': self.MainProgramm.LoadFile(filename) return
def loadControl(self): self.CfileName = QFileDialog.getOpenFileName( self, "Open Points File", "", "All Files (*);;Text Files (*.txt)", "") if self.CfileName: # self.lineEditPoints.setText(fileName) self.treeControl.clear() self.readControlFile(self.CfileName) self.updateControl.setVisible(True)
def loadObs(self): self.CalcProvisionals.setEnabled(True) fileName = QFileDialog.getOpenFileName( self, "Open Points File", "", "All Files (*);;Text Files (*.txt)", "") if fileName: # self.lineEditPoints.setText(fileName) self.treeObs.clear() self.readObsFile(fileName)
def loadObs(self): self.CalcProvisionals.setEnabled(True) fileName = QFileDialog.getOpenFileName(self, "Open Points File", "", "All Files (*);;Text Files (*.txt)", "") if fileName: # self.lineEditPoints.setText(fileName) self.treeObs.clear() self.readObsFile(fileName)
def showOpenFileWin(self): fileDir = QFileDialog.getOpenFileName() myFile = open(fileDir, "r") with myFile: global fileContent fileContent = myFile.read() self.showNodesWin() self.addNode()
def loadControl(self): self.CfileName = QFileDialog.getOpenFileName(self, "Open Points File", "", "All Files (*);;Text Files (*.txt)", "") if self.CfileName: # self.lineEditPoints.setText(fileName) self.treeControl.clear() self.readControlFile(self.CfileName) self.updateControl.setVisible(True)
def _openFileDialog(self): """ Opens the QFileDialog for accepting user input for the input image file path (self._filePath) """ self._filePath = (str( QFileDialog.getOpenFileName( self, "Open Image Path", "", "Image file (*.jpg);;All Files (*.*);;"))) self._filePath = os.path.normpath(self._filePath) self._dialog.inputLineEdit.setText(self._filePath)
def LoadAction(self): if not self.MainProgramm.DataSaved: msgbox = QMessageBox( QMessageBox.Question, "Frage", "Soll die vorherige Messung ueberschrieben werden ?", QMessageBox.No | QMessageBox.Yes) if not msgbox.exec_() == QMessageBox.Yes: return filename = QFileDialog.getOpenFileName(self, "Messung laden") if not filename == '': self.MainProgramm.LoadFile(filename) return
def Open(self): d = QFileDialog(self) s = d.getOpenFileName() self.mt.exit = True f = open(s,"r") l = int(f.readline()) f.close() self.mt.Images = [] for i in xrange(l): self.mt.Images.append(QImage(s+'.'+str(i)+'.png'))
def resize(self): # on a choisi de remplacer la couv, redimesionnement et sauvegarde de la nouvelle image newcouv = QFileDialog.getOpenFileName(None, "Sélectionnez la nouvelle couverture :", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation), "Images (*.png *.gif *.jpg *.jpeg *.bmp)") if not newcouv: return self.suppr_comm() log('\t remplacement de la couverture') newimg = Image.open(newcouv) im = Image.open(self.monepub.imagedecouv) oldwidth, oldheight = im.size newimg = newimg.resize((oldwidth, oldheight)) newimg.save(self.monepub.imagedecouv) self.ccouv.close() return tatoo.suppr_tatoo(self.monepub)
def loadParser(self): thedir = str(".") filename = str( QFileDialog.getOpenFileName(self, caption="%s - Load a parser" % QApplication.applicationName(), directory=thedir, filter=str("XML files (*.xml)"))) if filename: try: parser = ReaderManager.fromXMLFile(filename) message = "Loaded parser from %s" % filename self.setParser(parser) except Exception: message = "Error: Could not load parser from file %s" % filename self.updateStatus(message)
def stepSelect(self, phase=0): if phase == 0: self.setWindowTitle(QString(u'Выбрать архив')) self.progressBar.setValue(30) self.emitStep(self.stepSelect, 1) return # print("archive") self.archiveName = QFileDialog.getOpenFileName(None, u"Выберите архив", u"cps/updates", 'CNC.upd.tar.gz') if (self.archiveName == ""): print("archiveName is null, exit") app.closeAllWindows() print("open " + self.archiveName) # time.sleep(5) self.emitStep(self.stepUpload)
def stepSelect(self, phase = 0): if phase == 0: self.setWindowTitle(QString(u'Выбрать архив')) self.progressBar.setValue(30) self.emitStep(self.stepSelect, 1) return # print("archive") self.archiveName = QFileDialog.getOpenFileName(None, u"Выберите архив", u"cps/updates", 'CNC.upd.tar.gz') if(self.archiveName == ""): print("archiveName is null, exit") app.closeAllWindows() print("open " + self.archiveName) # time.sleep(5) self.emitStep(self.stepUpload)
def openFileChooserDialog(self): """ Prompts the user to choose a file from disk and inserts the full path into the lineEdit widget. """ _dir = getDefaultWorkingDirectory() if self.directory: if os.path.isdir(self.directory): _dir = self.directory fname = QFileDialog.getOpenFileName(self, self.caption, _dir, self.filter) if fname: self.setText(fname) self.lineEdit.emit(SIGNAL("editingFinished()")) return
def get_sync_app_fs(self): ''' Get path to selected sync_app ''' self._log_location() sync_app = unicode(QFileDialog.getOpenFileName( self.gui, "Select sync app", os.path.expanduser("~"), "*.app").toUtf8()) if sync_app: # Populate the filespec edit control self._log(sync_app) self.sync_app_path_le.setText(sync_app) # Populate the putative app name app_name = os.path.basename(sync_app) root_name = app_name.split('.')[0] self.app_name_le.setText(root_name)
def _openFileDialog(self): """ Opens the QFileDialog for accepting user input for the input image file path (self._filePath) """ self._filePath = '' self._filePath = \ str(QFileDialog.getOpenFileName( self, "Open Video File", "", "Video file (*.mpg);;AVI(*.avi);;All Files (*.*);;")) if self._filePath: self._filePath = os.path.normpath(self._filePath) self._dialog.fileLineEdit.setText(self._filePath) self._loadNewMedia()
def openFileChooserDialog(self): """ Prompts the user to choose a file from disk and inserts the full path into the lineEdit widget. """ _dir = getDefaultWorkingDirectory() if self.directory: if os.path.isdir(self.directory): _dir = self.directory fname = QFileDialog.getOpenFileName(self, self.caption, _dir, self.filter) if fname: self.setText(fname) self.lineEdit.emit(SIGNAL("editingFinished()")) return
def LoadImageButtonClicked(self): self.filePath = QFileDialog.getOpenFileName(self, u"选择图片文件", "", "Images (*.bmp)") if self.filePath == "": QMessageBox.warning(self, u"发生错误", u"没有选择可以识别的文件!!") return self.srcImage = QImage(self.filePath) self.grayImage = QImage(self.srcImage.size(), QImage.Format_Indexed8) for i in range(256): self.grayImage.setColor(i, qRgb(i, i, i)) for i in range(self.srcImage.width()): for j in range(self.srcImage.height()): temp = qGray(self.srcImage.pixel(i, j)) self.grayImage.setPixel(i, j, temp) self.srcImage = QImage(self.grayImage) self.resultImage = QImage(self.grayImage) self.imageLabel.setPixmap(QPixmap(self.srcImage))
def on_browseButton_clicked(self, checked=None): """ Called when browse button for selecting the edf file is clicked. Opens a dialog for selecting a file. """ if checked is None: return fileDialog = QFileDialog() self.fName = str(fileDialog.getOpenFileName(self, 'Select a file to convert', '/home/')) if self.fName != '': self.fName = self.fName.replace(" ", "\ ") self.ui.lineEditEdfName.setText(self.fName) splitted = str.split(self.fName, '/') destPath = '/'.join(splitted[:-1]) #destPath = destPath.replace(" ", "\ ") self.ui.lineEditDestPath.setText(destPath) fifName = splitted[-1][:-4] + '.fif' #fifName = fifName.replace(" ", "\ ") self.ui.lineEditFifName.setText(fifName)
def read_element_rgb_table(self): """ Open file browser to select a file to read from, read the data, update elements color in the selector dialog and also the display models """ # Determine what directory to open. import os if self.w.assy.filename: odir = os.path.dirname(self.w.assy.filename) else: from utilities.prefs_constants import workingDirectory_prefs_key odir = env.prefs[workingDirectory_prefs_key] self.fileName = str( QFileDialog.getOpenFileName( self, "Load Element Color", odir, "Elements color file (*.txt);;All Files (*.*);;")) if self.fileName: colorTable = readElementColors(self.fileName) if not colorTable: env.history.message( redmsg("Error in element colors file: [" + self.fileName + "]. Colors not loaded.")) else: env.history.message("Element colors loaded from file: [" + self.fileName + "].") for row in colorTable: row[1] /= 255.0 row[2] /= 255.0 row[3] /= 255.0 self.elemTable.setElemColors(colorTable) self._updateModelDisplay() elemNum = self.elementButtonGroup.checkedId() self.setDisplay(elemNum) #After loading a file, reset the flag self.isElementModified = False
def load_espimage_file(self, choose_new_image=False, parent=None): """ Load the ESP (.png) image file pointed to by self.espimage_file. If the file does not exist, or if choose_new_image is True, the user will be prompted to choose a new image, and if the file chooser dialog is not cancelled, the new image will be loaded and its pathname stored in self.espimage_file. Return value is None if user cancels the file chooser, but is self.espimage_file (which has just been reloaded, and a history message emitted, whether or not it was newly chosen) in all other cases. If self.espimage_file is changed (to a different value), this marks assy as changed. """ #bruce 060207 revised docstring. I suspect this routine has several distinct # purposes which should not be so intimately mixed (i.e. it should be several # routines). Nothing presently uses the return value. old_espimage_file = self.espimage_file if not parent: parent = self.assy.w cmd = greenmsg("Load ESP Image: ") ## print "load_espimage_file(): espimage_file = ", self.espimage_file if choose_new_image or not self.espimage_file: choose_new_image = True elif not os.path.exists(self.espimage_file): msg = "The ESP image file:\n" + self.espimage_file + "\ndoes not exist.\n\nWould you like to select one?" choose_new_image = True QMessageBox.warning( parent, "Choose ESP Image", \ msg, QMessageBox.Ok, QMessageBox.Cancel) #bruce 060207 question: shouldn't we check here whether they said ok or cancel?? Looks like a bug. ####@@@@ if choose_new_image: cwd = self.assy.get_cwd() fn = QFileDialog.getOpenFileName( parent, "Load an ESP Image File", cwd, "Portable Network Graphics (*.png);;All Files (*.*);;" ) #bruce 060212 added All Files option if not fn: env.history.message( cmd + "Cancelled.") #bruce 060212 bugfix: included cmd return None self.espimage_file = str(fn) if old_espimage_file != self.espimage_file: self.changed( ) #bruce 060207 fix of perhaps-previously-unreported bug pass if self.image_mods: self.image_mods.reset() self.changed() self._create_PIL_image_obj_from_espimage_file() self._loadTexture() #bruce 060212 comment: this does gl_update, but when we're called from dialog's open file button, # the glpane doesn't show the new texture until the dialog is closed (which is a bug, IMHO), # even if we call env.call_qApp_processEvents() before returning from this method (load_espimage_file). # I don't know why. # Bug fix 1041-1. Mark 051003 msg = "ESP image loaded: [" + self.espimage_file + "]" env.history.message(cmd + msg) return self.espimage_file
def __init__(self, title=_('Choose Files'), filters=[], add_all_files_filter=True, parent=None, modal=True, name='', mode=QFileDialog.ExistingFiles, default_dir=u'~', no_save_dir=False, combine_file_and_saved_dir=False ): QObject.__init__(self) ftext = '' if filters: for filter in filters: text, extensions = filter extensions = ['*'+(i if i.startswith('.') else '.'+i) for i in extensions] ftext += '%s (%s);;'%(text, ' '.join(extensions)) if add_all_files_filter or not ftext: ftext += 'All files (*)' if ftext.endswith(';;'): ftext = ftext[:-2] self.dialog_name = name if name else 'dialog_' + title self.selected_files = None self.fd = None if combine_file_and_saved_dir: bn = os.path.basename(default_dir) prev = dynamic.get(self.dialog_name, expanduser(u'~')) if os.path.exists(prev): if os.path.isfile(prev): prev = os.path.dirname(prev) else: prev = expanduser(u'~') initial_dir = os.path.join(prev, bn) elif no_save_dir: initial_dir = expanduser(default_dir) else: initial_dir = dynamic.get(self.dialog_name, expanduser(default_dir)) if not isinstance(initial_dir, basestring): initial_dir = expanduser(default_dir) if not initial_dir or (not os.path.exists(initial_dir) and not ( mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))): initial_dir = select_initial_dir(initial_dir) self.selected_files = [] use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ with SanitizeLibraryPath(): opts = QFileDialog.Option() if not use_native_dialog: opts |= QFileDialog.DontUseNativeDialog if mode == QFileDialog.AnyFile: f = unicode(QFileDialog.getSaveFileName(parent, title, initial_dir, ftext, "", opts)) if f: self.selected_files.append(f) elif mode == QFileDialog.ExistingFile: f = unicode(QFileDialog.getOpenFileName(parent, title, initial_dir, ftext, "", opts)) if f and os.path.exists(f): self.selected_files.append(f) elif mode == QFileDialog.ExistingFiles: fs = QFileDialog.getOpenFileNames(parent, title, initial_dir, ftext, "", opts) for f in fs: f = unicode(f) if not f: continue if not os.path.exists(f): # QFileDialog for some reason quotes spaces # on linux if there is more than one space in a row f = unquote(f) if f and os.path.exists(f): self.selected_files.append(f) else: if mode == QFileDialog.Directory: opts |= QFileDialog.ShowDirsOnly f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) if os.path.exists(f): self.selected_files.append(f) if self.selected_files: self.selected_files = [unicode(q) for q in self.selected_files] saved_loc = self.selected_files[0] if os.path.isfile(saved_loc): saved_loc = os.path.dirname(saved_loc) if not no_save_dir: dynamic[self.dialog_name] = saved_loc self.accepted = bool(self.selected_files)
class MainWidget(QWidget): def __init__(self): QWidget.__init__(self) # define periodic table widget for element selection self.periodicTableWidget = widgets.PeriodicTableDialog() # initial molecule Zmatrix (can be empty) # self.inp = [] self.inp = [['H'], ['O', 1, 0.9], ['O', 2, 1.4, 1, 105.], ['H', 3, 0.9, 2, 105., 1, 120.]] self.atomList = [] self.highList = [] self.labelList = [] self.fast = False # define & initialize ZMatModel that will contain Zmatrix data self.ZMatModel = QStandardItemModel(len(self.inp), 7, self) self.ZMatTable = QTableView(self) self.ZMatTable.setModel(self.ZMatModel) self.ZMatTable.setFixedWidth(325) #self.ZMatTable.installEventFilter(self) #self.ZMatModel.installEventFilter(self) self.ZMatModel.setHorizontalHeaderLabels(['atom','','bond','','angle','','dihedral']) for j, width in enumerate([40, 22, 65, 22, 65, 22, 65]): self.ZMatTable.setColumnWidth(j, width) # populate the ZMatModel self.populateZMatModel() #define Menu bar menus and their actions self.menuBar = QMenuBar(self) fileMenu = self.menuBar.addMenu('&File') editMenu = self.menuBar.addMenu('&Edit') viewMenu = self.menuBar.addMenu('&View') measureMenu = self.menuBar.addMenu('&Measure') helpMenu = self.menuBar.addMenu('&Help') readZmatAction = QAction('&Read &ZMat', self) readZmatAction.setShortcut('Ctrl+O') readZmatAction.setStatusTip('Read Zmat from file') readZmatAction.triggered.connect(self.readZmat) fileMenu.addAction(readZmatAction) readXYZAction = QAction('&Read &XYZ', self) readXYZAction.setShortcut('Ctrl+Shift+O') readXYZAction.setStatusTip('Read XYZ from file') readXYZAction.triggered.connect(self.readXYZ) fileMenu.addAction(readXYZAction) readGaussianAction = QAction('&Read &Gaussian log', self) readGaussianAction.setShortcut('Ctrl+G') readGaussianAction.setStatusTip('Read Gaussian log file') readGaussianAction.triggered.connect(self.readGaussian) fileMenu.addAction(readGaussianAction) writeZmatAction = QAction('&Write &ZMat', self) writeZmatAction.setShortcut('Ctrl+S') writeZmatAction.setStatusTip('Write Zmat to file') writeZmatAction.triggered.connect(self.writeZmat) fileMenu.addAction(writeZmatAction) writeXYZAction = QAction('&Write &XYZ', self) writeXYZAction.setShortcut('Ctrl+Shift+S') writeXYZAction.setStatusTip('Write XYZ from file') writeXYZAction.triggered.connect(self.writeXYZ) fileMenu.addAction(writeXYZAction) exitAction = QAction('&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(qApp.quit) fileMenu.addAction(exitAction) addRowAction = QAction('&Add &row', self) addRowAction.setShortcut('Ctrl+R') addRowAction.setStatusTip('Add row to ZMatrix') addRowAction.triggered.connect(self.addRow) editMenu.addAction(addRowAction) deleteRowAction = QAction('&Delete &row', self) deleteRowAction.setShortcut('Ctrl+Shift+R') deleteRowAction.setStatusTip('Delete row from ZMatrix') deleteRowAction.triggered.connect(self.deleteRow) editMenu.addAction(deleteRowAction) addAtomAction = QAction('&Add &atom', self) addAtomAction.setShortcut('Ctrl+A') addAtomAction.setStatusTip('Add atom to ZMatrix') addAtomAction.triggered.connect(self.buildB) editMenu.addAction(addAtomAction) drawModeMenu = QMenu('Draw mode', self) viewMenu.addMenu(drawModeMenu) fastDrawAction = QAction('&Fast draw', self) fastDrawAction.triggered.connect(self.fastDraw) normalDrawAction = QAction('&Normal draw', self) normalDrawAction.triggered.connect(self.normalDraw) drawModeMenu.addAction(normalDrawAction) drawModeMenu.addAction(fastDrawAction) clearHighlightsAction = QAction('&Clear selection', self) clearHighlightsAction.setShortcut('Ctrl+C') clearHighlightsAction.setStatusTip('Clear highlighted atoms') clearHighlightsAction.triggered.connect(self.clearHighlights) viewMenu.addAction(clearHighlightsAction) clearLabelsAction = QAction('&Clear labels', self) clearLabelsAction.setShortcut('Ctrl+Alt+C') clearLabelsAction.setStatusTip('Clear labels') clearLabelsAction.triggered.connect(self.clearLabels) viewMenu.addAction(clearLabelsAction) clearUpdateViewAction = QAction('&Clear selection and labels', self) clearUpdateViewAction.setShortcut('Ctrl+Shift+C') clearUpdateViewAction.setStatusTip('Clear highlighted atoms and labels') clearUpdateViewAction.triggered.connect(self.clearUpdateView) viewMenu.addAction(clearUpdateViewAction) self.showGaussAction = QAction('Show &Gaussian geometry optimization', self) self.showGaussAction.setShortcut('Ctrl+G') self.showGaussAction.setStatusTip('Show Gaussian geometry optimization plots for energy, force and displacement.') self.showGaussAction.setEnabled(False) self.showGaussAction.triggered.connect(self.showGauss) viewMenu.addAction(self.showGaussAction) self.showFreqAction = QAction('Show &IR frequency plot', self) self.showFreqAction.setShortcut('Ctrl+I') self.showFreqAction.setStatusTip('Show Gaussian calculated IR frequency plot.') self.showFreqAction.setEnabled(False) self.showFreqAction.triggered.connect(self.showFreq) viewMenu.addAction(self.showFreqAction) measureDistanceAction = QAction('&Measure &distance', self) measureDistanceAction.setShortcut('Ctrl+D') measureDistanceAction.setStatusTip('Measure distance between two atoms') measureDistanceAction.triggered.connect(self.measureDistanceB) measureMenu.addAction(measureDistanceAction) measureAngleAction = QAction('&Measure &angle', self) measureAngleAction.setShortcut('Ctrl+Shift+D') measureAngleAction.setStatusTip('Measure angle between three atoms') measureAngleAction.triggered.connect(self.measureAngleB) measureMenu.addAction(measureAngleAction) aboutAction = QAction('&About', self) aboutAction.setStatusTip('About this program...') aboutAction.triggered.connect(self.about) helpMenu.addAction(aboutAction) aboutQtAction = QAction('&About Qt', self) aboutQtAction.setStatusTip('About Qt...') aboutQtAction.triggered.connect(self.aboutQt) helpMenu.addAction(aboutQtAction) # define GL widget that displays the 3D molecule model self.window = widgets.MyGLView() self.window.installEventFilter(self) self.window.setMinimumSize(500, 500) #self.window.setBackgroundColor((50, 0, 10)) self.updateView() self.gaussianPlot = GraphicsLayoutWidget() self.gaussianPlot.resize(750, 250) self.gaussianPlot.setWindowTitle('Gaussian geometry optimization') #self.gaussianPlot.setAspectLocked(True) #self.gaussianPlot.addLayout(rowspan=3, colspan=1) self.FreqModel = QStandardItemModel(1, 3, self) self.freqTable = QTableView(self) self.freqTable.setModel(self.FreqModel) self.freqTable.setMinimumWidth(240) self.freqTable.installEventFilter(self) self.FreqModel.installEventFilter(self) self.FreqModel.setHorizontalHeaderLabels(['Frequency','IR Intensity','Raman Intensity']) for j, width in enumerate([80, 80, 80]): self.freqTable.setColumnWidth(j, width) self.freqWidget = QWidget() self.freqWidget.setWindowTitle('IR frequency plot & table') self.freqWidget.resize(800, 400) self.freqWidget.layout = QHBoxLayout(self.freqWidget) self.freqWidget.layout.setSpacing(1) self.freqWidget.layout.setContentsMargins(1, 1, 1, 1) self.freqPlot = GraphicsLayoutWidget() self.freqWidget.layout.addWidget(self.freqPlot) self.freqWidget.layout.addWidget(self.freqTable) self.freqTable.clicked.connect(self.freqCellClicked) # define other application parts self.statusBar = QStatusBar(self) self.fileDialog = QFileDialog(self) # define application layout self.layout = QVBoxLayout(self) self.layout.setSpacing(1) self.layout.setContentsMargins(1, 1, 1, 1) self.layout1 = QHBoxLayout() self.layout1.setSpacing(1) self.layout1.addWidget(self.ZMatTable) self.layout1.addWidget(self.window) self.layout.addWidget(self.menuBar) self.layout.addLayout(self.layout1) self.layout.addWidget(self.statusBar) self.adjustSize() self.setWindowTitle('Moldy') iconPath = 'icon.png' icon = QIcon(iconPath) icon.addFile(iconPath, QSize(16, 16)) icon.addFile(iconPath, QSize(24, 24)) icon.addFile(iconPath, QSize(32, 32)) icon.addFile(iconPath, QSize(48, 48)) icon.addFile(iconPath, QSize(256, 256)) self.setWindowIcon(icon) # start monitoring changes in the ZMatModel self.ZMatModel.dataChanged.connect(self.clearUpdateView) # run and show the application def run(self): self.show() self.ZMatTable.clicked.connect(self.ZMatCellClicked) qt_app.instance().aboutToQuit.connect(self.deleteGLwidget) qt_app.exec_() # fill the ZMatModel with initial data from 'self.inp' def populateZMatModel(self): self.ZMatModel.removeRows(0, self.ZMatModel.rowCount()) for i, row in enumerate(self.inp): for j, cell in enumerate(row): item = QStandardItem(str(cell)) self.ZMatModel.setItem(i, j, item) # some cells should not be editable, they are disabled for i in range(min(len(self.inp), 3)): for j in range(2*i+1, 7): self.ZMatModel.setItem(i, j, QStandardItem()) self.ZMatModel.item(i, j).setBackground(QColor(150,150,150)) self.ZMatModel.item(i, j).setFlags(Qt.ItemIsEnabled) def populateFreqModel(self): self.FreqModel.removeRows(0, self.FreqModel.rowCount()) for i, row in enumerate(zip(self.vibfreqs, self.vibirs, self.vibramans)): for j, cell in enumerate(row): item = QStandardItem(str(cell)) self.FreqModel.setItem(i, j, item) # add a row to the bottom of the ZMatModel def addRow(self): # temporarily stop updating the GL window self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) row = self.ZMatModel.rowCount() self.ZMatModel.insertRow(row) # some cells should not be editable if row < 3: for j in range(2*row+1, 7): self.ZMatModel.setItem(row, j, QStandardItem()) self.ZMatModel.item(row, j).setBackground(QColor(150,150,150)) self.ZMatModel.item(row, j).setFlags(Qt.ItemIsEnabled) # restart GL window updating self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.statusBar.clearMessage() self.statusBar.showMessage('Added 1 row.', 3000) # delete the last row of the ZMatModel def deleteRow(self): xyz = [list(vi) for vi in list(v)] atoms = [str(elements[e]) for e in elems] oldLen = self.ZMatModel.rowCount() idxs = sorted(set(idx.row() for idx in self.ZMatTable.selectedIndexes()), reverse=True) newLen = oldLen - len(idxs) if newLen == oldLen: self.ZMatModel.removeRow(self.ZMatModel.rowCount()-1) else: self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) for idx in idxs: self.ZMatModel.removeRow(idx) if idx < 3: for i in range(idx, min(3, newLen)): for j in range(2*i+1, 7): self.ZMatModel.setItem(i, j, QStandardItem()) self.ZMatModel.item(i, j).setBackground(QColor(150,150,150)) self.ZMatModel.item(i, j).setFlags(Qt.ItemIsEnabled) if len(xyz) > idx: xyz.pop(idx) atoms.pop(idx) self.inp = xyz2zmat(xyz, atoms) self.populateZMatModel() for i in reversed(self.highList): self.window.removeItem(i[1]) self.highList = [] self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.updateView() self.statusBar.clearMessage() if idxs: self.statusBar.showMessage('Deleted row(s): '+str([i+1 for i in idxs]), 3000) else: self.statusBar.showMessage('Deleted last row.', 3000) # show the periodic table widget def periodicTable(self): self.statusBar.clearMessage() self.statusBar.showMessage('Select element from periodic table.') self.periodicTableWidget.exec_() selection = self.periodicTableWidget.selection() return selection # import molecule with zmatrix coordinates def readZmat(self): self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) filename = self.fileDialog.getOpenFileName(self, 'Open file', expanduser('~'), '*.zmat;;*.*') self.inp = [] self.populateZMatModel() if filename: with open(filename, 'r') as f: next(f) next(f) for row in f: self.inp.append(row.split()) f.close() self.populateZMatModel() self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.updateView() self.statusBar.clearMessage() self.statusBar.showMessage('Read molecule from '+filename+'.', 5000) self.showGaussAction.setEnabled(False) self.showFreqAction.setEnabled(False) # import molecule with xyz coordinates def readXYZ(self): self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) filename = self.fileDialog.getOpenFileName(self, 'Open file', expanduser('~'), '*.xyz;;*.*') xyz = [] elems = [] self.inp = [] self.populateZMatModel() if filename: with open(filename, 'r') as f: next(f) next(f) for row in f: rs = row.split() if len(rs) == 4: elems.append(rs[0]) xyz.append([float(f) for f in rs[1:]]) f.close() self.inp = xyz2zmat(xyz, elems) self.populateZMatModel() #print(elems) self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.updateView() self.statusBar.clearMessage() self.statusBar.showMessage('Read molecule from '+filename+'.', 5000) self.showGaussAction.setEnabled(False) self.showFreqAction.setEnabled(False) # import Gaussian log file def readGaussian(self): global vsShifted self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) filename = self.fileDialog.getOpenFileName(self, 'Open file', expanduser('~'), '*.log;;*.*') if filename: self.gaussianPlot.clear() self.inp = [] self.populateZMatModel() file = ccopen(filename) data = file.parse().getattributes() self.natom = data['natom'] self.atomnos = data['atomnos'].tolist() self.atomsymbols = [ str(elements[e]) for e in self.atomnos ] self.atomcoords = data['atomcoords'].tolist() self.scfenergies = data['scfenergies'].tolist() self.geovalues = data['geovalues'].T.tolist() self.geotargets = data['geotargets'].tolist() if 'vibfreqs' in data.keys(): self.vibfreqs = data['vibfreqs'] #print(self.vibfreqs) self.vibirs = data['vibirs'] #print(self.vibirs) #print(data.keys()) if 'vibramans' in data.keys(): self.vibramans = data['vibramans'] else: self.vibramans = [''] * len(self.vibirs) self.vibdisps = data['vibdisps'] #print(self.vibdisps) self.inp = xyz2zmat(self.atomcoords[0], self.atomsymbols) self.populateZMatModel() titles = ['SCF Energies', 'RMS & Max Forces', 'RMS & Max Displacements'] for i in range(3): self.gaussianPlot.addPlot(row=1, col=i+1) plot = self.gaussianPlot.getItem(1, i+1) plot.setTitle(title=titles[i]) if i == 0: c = ['c'] x = [0] y = [self.scfenergies] else: c = ['r', 'y'] x = [0, 0] y = [self.geovalues[2*i-2], self.geovalues[2*i-1]] targety = [self.geotargets[2*i-2], self.geotargets[2*i-1]] plot.clear() plot.maxData = plot.plot(y[0], symbol='o', symbolPen=c[0], symbolBrush=c[0], pen=c[0], symbolSize=5, pxMode=True, antialias=True, autoDownsample=False) plot.highlight=plot.plot(x, [ yy[0] for yy in y ], symbol='o', symbolPen='w', symbolBrush=None, pen=None, symbolSize=15, pxMode=True, antialias=True, autoDownsample=False) plot.maxData.sigPointsClicked.connect(self.gausclicked) if i > 0: for j in range(2): plot.addLine(y=np.log10(targety[j]), pen=mkPen((255, 255*j, 0, int(255/2)), width=1)) plot.RMSData=plot.plot(y[1], symbol='o', symbolPen=c[1], symbolBrush=c[1], pen=c[1], symbolSize=5, pxMode=True, antialias=True, autoDownsample=False) plot.RMSData.sigPointsClicked.connect(self.gausclicked) plot.setLogMode(y=True) self.showGauss() self.updateView() self.statusBar.clearMessage() self.statusBar.showMessage('Read molecule from '+filename+'.', 5000) self.ZMatModel.dataChanged.connect(self.clearUpdateView) if self.natom: self.showGaussAction.setEnabled(True) if 'vibfreqs' in data.keys(): self.showFreqAction.setEnabled(True) # populate the FreqModel self.populateFreqModel() self.freqPlot.clear() irPlot = self.freqPlot.addPlot(row=1, col=1) irPlot.clear() minFreq = np.min(self.vibfreqs) maxFreq = np.max(self.vibfreqs) maxInt = np.max(self.vibirs) x = np.sort(np.concatenate([np.linspace(minFreq-100, maxFreq+100, num=1000), self.vibfreqs])) y = x*0 for f,i in zip(self.vibfreqs, self.vibirs): y += lorentzv(x, f, 2*np.pi, i) #xy = np.array([np.concatenate([x, np.array(self.vibfreqs)]), np.concatenate([y, np.array(self.vibirs)])]).T #xysort = xy[xy[:,0].argsort()] irPlot.maxData = irPlot.plot(x, y, antialias=True) markers = ErrorBarItem(x=self.vibfreqs, y=self.vibirs, top=maxInt/30, bottom=None, pen='r') irPlot.addItem(markers) self.showFreq() #self.vibdisps = np.append(self.vibdisps, [np.mean(self.vibdisps, axis=0)], axis=0) maxt = 100 vsShifted = np.array([ [ vs + self.vibdisps[i]*np.sin(t*2*np.pi/maxt)/3 for t in range(maxt) ] for i in range(len(self.vibfreqs)) ]) else: self.showFreqAction.setEnabled(False) self.freqWidget.hide() def showGauss(self): self.gaussianPlot.show() def showFreq(self): self.freqWidget.show() # export Zmatrix to csv def writeZmat(self): zm = model2list(self.ZMatModel) filename = self.fileDialog.getSaveFileName(self, 'Save file', expanduser('~')+'/'+getFormula(list(list(zip(*zm))[0]))+'.zmat', '*.zmat;;*.*') try: filename except NameError: pass else: if filename: writeOutput(zm, filename) self.statusBar.clearMessage() self.statusBar.showMessage('Wrote molecule to '+filename+'.', 5000) # export XYZ coordinates to csv def writeXYZ(self): xyz = [] zm = model2list(self.ZMatModel) for i in range(len(v)): xyz.append(np.round(v[i], 7).tolist()) xyz[i][:0] = zm[i][0] if len(v) > 0: formula = getFormula(list(list(zip(*xyz))[0])) else: formula = 'moldy_output' filename = self.fileDialog.getSaveFileName(self, 'Save file', expanduser('~')+'/'+formula+'.xyz', '*.xyz;;*.*') try: filename except NameError: pass else: if filename: writeOutput(xyz, filename) self.statusBar.clearMessage() self.statusBar.showMessage('Wrote molecule to '+filename+'.', 5000) # redraw the 3D molecule in GL widget def updateView(self): global r global c global v global vs global elems global nelems data = model2list(self.ZMatModel) try: # create a list with element coordinates v = zmat2xyz(data) except (AssertionError, IndexError, ZMError): pass else: # clear the screen before redraw for item in reversed(self.window.items): self.window.removeItem(item) # create a second coordinate list 'vs' that is centered in the GL view self.atomList = [] if len(v) > 0: shift = np.mean(v, axis=0) vs = np.add(v, -shift) elems = [ 1 + next((i for i, sublist in enumerate(colors) if row[0] in sublist), -1) for row in data ] nelems = len(elems) # define molecule radii and colors r = [] c = [] for i in elems: r.append(elements[i].covalent_radius) c.append(colors[i-1][-1]) # draw atoms for i in range(nelems): addAtom(self.window, i, r, vs, c, fast=self.fast) self.atomList.append([i, self.window.items[-1]]) #print(self.atomList) # draw bonds where appropriate combs = list(itertools.combinations(range(nelems), 2)) bonds = [] for i in combs: bonds.append(addBond(self.window, i[0], i[1], r, vs, c, fast=self.fast)) if self.fast: bondedAtoms = set(filter((None).__ne__, flatten(bonds))) for i in set(range(nelems)) - bondedAtoms: addUnbonded(self.window, i, vs, c) self.atomList[i][1]=self.window.items[-1] #print(self.atomList) for i in self.highList: self.window.addItem(i[1]) for i in self.labelList: self.window.addItem(i) if len(v) > 1: maxDim = float('-inf') for dim in v.T: span = max(dim)-min(dim) if span > maxDim: maxDim = span else: maxDim = 2 self.window.setCameraPosition(distance=maxDim*1.5+1) global index index = 0 def updateFreq(self): global vsShifted, index, r, c index += 1 index = index % len(vsShifted[0]) #print(index) #print(vsShifted[index]) for item in reversed(self.window.items): self.window.removeItem(item) for i in range(nelems): addAtom(self.window, i, r, vsShifted[self.freqIndex, index], c, fast=self.fast) self.atomList.append([i, self.window.items[-1]]) combs = itertools.combinations(range(nelems), 2) bonds = [] for i in combs: bonds.append(addBond(self.window, i[0], i[1], r, vsShifted[self.freqIndex, index], c, fast=self.fast)) if self.fast: bondedAtoms = set(filter((None).__ne__, flatten(bonds))) for i in set(range(nelems)) - bondedAtoms: addUnbonded(self.window, i, vsShifted[self.freqIndex, index], c) self.atomList[i][1]=self.window.items[-1] # detect mouse clicks in GL window and process them def eventFilter(self, obj, event): if obj == self.window: if event.type() == event.MouseButtonPress: itms = obj.itemsAt((event.pos().x()-2, event.pos().y()-2, 4, 4)) if len(itms): self.highlight(obj, [itms[0]]) elif len(self.atomList) == 0: self.build() # also do the default click action return super(MainWidget, self).eventFilter(obj, event) def ZMatCellClicked(self): idxs = sorted(set(idx.row() for idx in self.ZMatTable.selectedIndexes()), reverse=True) itms = [] if self.highList: highIdx = list(np.array(self.highList).T[0]) for idx in idxs: if self.highList and idx in highIdx: itms.append(self.highList[highIdx.index(idx)][1]) elif len(self.atomList) > idx: itms.append(self.atomList[idx][1]) self.highlight(self.window, itms) def freqCellClicked(self): global vsShifted self.timer = QTimer() self.timer.setInterval(30) self.timer.timeout.connect(self.updateFreq) idxs = [ idx.row() for idx in self.freqTable.selectedIndexes() ] if len(idxs) == 1: self.freqIndex = idxs[0] self.timer.stop() self.timer.timeout.connect(self.updateFreq) try: self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) except TypeError: pass self.timer.start() if len(idxs) != 1: self.timer.stop() self.freqTable.clearSelection() self.timer.timeout.disconnect(self.updateFreq) self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.clearUpdateView() def gausclicked(self, item, point): itemdata = item.scatter.data points = [ row[7] for row in itemdata ] idx = points.index(point[0]) for i in range(3): if i == 0: x = [idx] y = [self.scfenergies[idx]] else: x = [idx, idx] y = [self.geovalues[2*i-2][idx], self.geovalues[2*i-1][idx]] plot = self.gaussianPlot.getItem(1, i+1) plot.removeItem(plot.highlight) plot.highlight=plot.plot(x, y, symbol='o', symbolPen='w', symbolBrush=None, pen=None, symbolSize=15, pxMode=True, antialias=True, autoDownsample=False) self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) self.inp = [] self.populateZMatModel() self.inp = xyz2zmat(self.atomcoords[min(idx, len(self.atomcoords)-1)], self.atomsymbols) self.populateZMatModel() self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.updateView() def highlight(self, obj, itms): for itm in itms: idx = next((i for i, sublist in enumerate(self.atomList) if itm in sublist), -1) #print(idx) if idx != -1: addAtom(obj, idx, r, vs, c, opt='highlight', fast=self.fast) self.highList.append([idx, obj.items[-1]]) self.ZMatTable.selectRow(idx) idx = next((i for i, sublist in enumerate(self.highList) if itm in sublist), -1) if idx != -1: obj.removeItem(self.highList[idx][1]) self.highList.pop(idx) self.ZMatTable.clearSelection() self.statusBar.clearMessage() if len(self.highList) > 0: idxs = np.asarray(self.highList).T[0] selected = [] for i in idxs: selected.append(str(i+1)+str(elements[elems[i]])) self.statusBar.showMessage('Selected atoms: '+str(selected), 5000) def buildB(self): try: nelems except NameError: self.build() else: if len(self.highList) <= min(nelems, 3): diff = min(nelems, 3) - len(self.highList) if diff != 0: self.statusBar.clearMessage() self.statusBar.showMessage('Please select '+str(diff)+' more atom(s).') else: self.build() else: self.statusBar.clearMessage() self.statusBar.showMessage('Too many atoms selected.') def build(self): selection = self.periodicTable() row = self.ZMatModel.rowCount() self.addRow() self.ZMatModel.dataChanged.disconnect(self.clearUpdateView) newSymbol = selection[1] newData = [newSymbol] if len(self.highList) >= 1: newBond = round(2.1*gmean([ elements[e].covalent_radius for e in [selection[0], elems[self.highList[0][0]]] ]), 4) newData.append(self.highList[0][0]+1) newData.append(newBond) if len(self.highList) >= 2: newAngle = 109.4712 newData.append(self.highList[1][0]+1) newData.append(newAngle) if len(self.highList) == 3: newDihedral = 120. newData.append(self.highList[2][0]+1) newData.append(newDihedral) for j, cell in enumerate(newData): item = QStandardItem(str(cell)) self.ZMatModel.setItem(row, j, item) self.highList = [] self.ZMatModel.dataChanged.connect(self.clearUpdateView) self.updateView() def measureDistanceB(self): sel = len(self.highList) if sel <= 2: if sel < 2: self.statusBar.clearMessage() self.statusBar.showMessage('Please select '+str(2-sel)+' more atom(s).') else: self.measureDistance() else: self.statusBar.clearMessage() self.statusBar.showMessage('Too many atoms selected.') def measureDistance(self): pts = [] for pt in self.highList: pts.append(vs[pt[0]]) pts = np.array(pts) self.clearHighlights() line = gl.GLLinePlotItem(pos=pts, color=(0., 1., 0., 1.), width=3) self.window.addItem(line) self.labelList.append(line) q = pts[1]-pts[0] dist = round(np.sqrt(np.dot(q, q)), 4) self.window.labelPos.append(np.mean(pts[0:2], axis=0)) self.window.labelText.append(str(dist)) self.statusBar.clearMessage() self.statusBar.showMessage('Measured distance: '+str(dist)+' A.', 3000) def measureAngleB(self): sel = len(self.highList) if sel <= 3: if sel < 3: self.statusBar.clearMessage() self.statusBar.showMessage('Please select '+str(3-sel)+' more atom(s).') else: self.measureAngle() else: self.statusBar.clearMessage() self.statusBar.showMessage('Too many atoms selected.') def measureAngle(self): pts = [] for pt in self.highList: pts.append(vs[pt[0]]) pts = np.array(pts) q = pts[1]-pts[0] r = pts[2]-pts[0] q_u = q / np.sqrt(np.dot(q, q)) r_u = r / np.sqrt(np.dot(r, r)) angle = round(degrees(acos(np.dot(q_u, r_u))), 1) srange = np.array([slerp(q, r, t) for t in np.arange(0.0, 13/12, 1/12)]) self.clearHighlights() for i in range(12): mesh = gl.MeshData(np.array([[0,0,0],srange[i],srange[i+1]])) tri = gl.GLMeshItem(meshdata=mesh, smooth=False, computeNormals=False, color=(0.3, 1., 0.3, 0.5), glOptions=('translucent')) tri.translate(pts[0][0], pts[0][1], pts[0][2]) self.window.addItem(tri) self.labelList.append(tri) self.window.labelPos.append(slerp(q, r, 0.5)+pts[0]) self.window.labelText.append(str(angle)) self.statusBar.clearMessage() self.statusBar.showMessage('Measured angle: '+str(angle)+'°', 3000) def clearLabels(self): self.window.labelPos = [] self.window.labelText = [] self.labelList = [] self.updateView() def clearHighlights(self): for item in reversed(self.highList): self.window.removeItem(item[1]) self.highList = [] self.updateView() def clearUpdateView(self): self.window.labelPos = [] self.window.labelText = [] self.labelList = [] for item in reversed(self.highList): self.window.removeItem(item[1]) self.highList = [] self.updateView() #print(self.highList) def fastDraw(self): if not self.fast: self.fast = True self.updateView() def normalDraw(self): if self.fast: self.fast = False self.updateView() def about(self): QMessageBox.about(self, 'About moldy', 'moldy beta 15. 9. 2015') def aboutQt(self): QMessageBox.aboutQt(self, 'About Qt') def deleteGLwidget(self): self.window.setParent(None) del self.window
def __init__( self, title=_("Choose Files"), filters=[], add_all_files_filter=True, parent=None, modal=True, name="", mode=QFileDialog.ExistingFiles, default_dir="~", no_save_dir=False, ): QObject.__init__(self) ftext = "" if filters: for filter in filters: text, extensions = filter extensions = ["*" + (i if i.startswith(".") else "." + i) for i in extensions] ftext += "%s (%s);;" % (text, " ".join(extensions)) if add_all_files_filter or not ftext: ftext += "All files (*)" if ftext.endswith(";;"): ftext = ftext[:-2] self.dialog_name = name if name else "dialog_" + title self.selected_files = None self.fd = None if no_save_dir: initial_dir = os.path.expanduser(default_dir) else: initial_dir = dynamic.get(self.dialog_name, os.path.expanduser(default_dir)) if not isinstance(initial_dir, basestring): initial_dir = os.path.expanduser(default_dir) self.selected_files = [] use_native_dialog = "CALIBRE_NO_NATIVE_FILEDIALOGS" not in os.environ with SanitizeLibraryPath(): opts = QFileDialog.Option() if not use_native_dialog: opts |= QFileDialog.DontUseNativeDialog if mode == QFileDialog.AnyFile: f = unicode(QFileDialog.getSaveFileName(parent, title, initial_dir, ftext, "", opts)) if f: self.selected_files.append(f) elif mode == QFileDialog.ExistingFile: f = unicode(QFileDialog.getOpenFileName(parent, title, initial_dir, ftext, "", opts)) if f and os.path.exists(f): self.selected_files.append(f) elif mode == QFileDialog.ExistingFiles: fs = QFileDialog.getOpenFileNames(parent, title, initial_dir, ftext, "", opts) for f in fs: f = unicode(f) if not f: continue if not os.path.exists(f): # QFileDialog for some reason quotes spaces # on linux if there is more than one space in a row f = unquote(f) if f and os.path.exists(f): self.selected_files.append(f) else: if mode == QFileDialog.Directory: opts |= QFileDialog.ShowDirsOnly f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) if os.path.exists(f): self.selected_files.append(f) if self.selected_files: self.selected_files = [unicode(q) for q in self.selected_files] saved_loc = self.selected_files[0] if os.path.isfile(saved_loc): saved_loc = os.path.dirname(saved_loc) if not no_save_dir: dynamic[self.dialog_name] = saved_loc self.accepted = bool(self.selected_files)
def do_job(self, options_texte, nb): QtGui.QApplication.processEvents() try: self.epub = self.ar[self.i][0] # chemin complet de l'epub epubname = os.path.basename(self.epub) # nom de l'epub log('\n*************************************** Traitement de : ' + epubname) self.setWindowTitle('Personnalisation de {}'.format(epubname)) self.show() if not zipfile.is_zipfile(self.epub): log('Le format n\'est pas un zip valide.') raise zipfile.BadZipFile try: self.metaname = self.ar[self.i][1] # chemin complet du metadata.opf except: self.metaname = None try: self.covname = self.ar[self.i][2] # couverture de Calibre except: self.covname = None if not 'Ne pas faire de sauvegarde' in options_texte : self.setLabelText('Sauvegarde') QtGui.QApplication.processEvents() log(' (sauvegardé)') self.sauvegarde(self.epub) if 'Tronquer les polices' in options_texte : self.setLabelText('Troncature des polices') QtGui.QApplication.processEvents() font.tronquer(self.epub) self.dezip_epub(self.epub, epubname) if 'Détatouage' in options_texte : fonctions.renomme_fichiers(self.dirtemp.name) self.monepub = container.EpubFile() self.monepub.init_read() self.val = self.i + 1 self.setValue(self.val) QTimer.singleShot(0, self.maj) if 'Corriger les exposants' in options_texte : self.setLabelText('Correction des exposants') QtGui.QApplication.processEvents() fonctions.css_expo(self.monepub) if 'Mettre à jour les métadonnées' in options_texte : self.setLabelText('Mise à jour des métadonnées') QtGui.QApplication.processEvents() self.metac = False self.metacal = False if 'Supprimer meta-content' in options_texte : self.metac = True if 'Garder les séries Calibre' in options_texte : self.metacal = True if 'date publication = copyright'in options_texte : self.copyr = True else: self.copyr = False fonctions.maj_meta(self.monepub, self.metaname, self.metac, self.metacal, self.copyr) QTimer.singleShot(0, self.maj) if 'Insérer une page de garde' in options_texte : self.setLabelText('Insertion d\'une page de garde') QtGui.QApplication.processEvents() fonctions.cree_jaquette(self.monepub, LECHEMIN, insere_jacket=True) if 'Créer un ebook résumé' in options_texte : self.setLabelText('Création d\'un epub résumé') QtGui.QApplication.processEvents() QTimer.singleShot(0, self.maj) fonctions.cree_couv(self.monepub, self.covname, LECHEMIN, self.epub, options_texte) if 'Supprimer les pages de garde (\'jacket\')'in options_texte : self.setLabelText('Suppression des pages de garde') QtGui.QApplication.processEvents() fonctions.supprimer_jacket(self.monepub, self.dirtemp, LECHEMIN) if 'Insérer un logo' in options_texte : self.setLabelText('Insertion d\'un logo') QtGui.QApplication.processEvents() if not self.newimagepath: self.newimagepath = QFileDialog.getOpenFileName(None, "Sélectionnez un logo à insérer :", os.getcwd(), "Images (*.png *.gif *.jpg *.jpeg *.bmp)") self.newimage = QtGui.QImage(self.newimagepath) fonctions.insere_logo(self.monepub, self.newimage, self.newimagepath, LECHEMIN) if 'Convertir les images en JPG' in options_texte: self.setLabelText('Conversion des images') QtGui.QApplication.processEvents() fonctions.convert(self.monepub) if 'Supprimer les polices embarquées' in options_texte: log('Suppression des polices embarquées') font.supprimer_fonts(self.monepub) if 'Epub pour dyslexiques' in options_texte : log('Création d\'un epub pour dyslexiques') font.supprimer_fonts(self.monepub) font.epub_dys(self.monepub, LECHEMIN) if 'Détatouage' in options_texte : logtat('\n\n***********Détatouage de ' + epubname + ' *********') self.setLabelText('Détatouage') QtGui.QApplication.processEvents() self.setup_couv(self.monepub, epubname) if 'Redimensionner les images' in options_texte : self.setLabelText('Redimensionnement des images') QtGui.QApplication.processEvents() fonctions.redim(options_texte, self.monepub) if self.monepub.pagedecouv != 'defaut': fonctions.modifie_titlepage(self.monepub, options_texte) except: self.setLabelText('Erreur de traitement') QtGui.QApplication.processEvents() self.badbook.append(epubname) type, value, tb = sys.exc_info() myexcepthook(type, value, tb) finally: if 'Détatouage' in options_texte : self.rezip_epub2(self.epub) elif 'Epub pour dyslexiques' in options_texte : self.rezip_epub2(self.epub, titre_dialogue="Enregistrer l'epub pour dyslexiques sous :") else: self.rezip_epub(self.epub) self.dirtemp.cleanup() self.i += 1 if self.i >= nb: self.conn.commit() c = self.conn.cursor() c.execute('DROP TABLE if exists ebook') c.execute("create table ebook(epub text, meta text, cover text)") texte = '\n'.join(self.badbook) path = os.path.normpath(LECHEMIN + '/tmp2/bad.txt') f = open(path, mode='w', encoding='utf-8') f.write(texte) f.close() try: os.remove(self.dirtemp.name) except: pass self.do_close(nb) else: # QTimer.singleShot(0, self.do_job) return self.do_job(options_texte, nb)
def browse(self): self.read_file = QFileDialog.getOpenFileName( self, caption="Read File As", filter="Comma Separated Variable(*.csv*)")
def browse(self): self.save_file = QFileDialog.getOpenFileName( self, caption="Read File As", filter="Comma Separated Variable(*.csv*)") self.line_edit.setText(self.save_file)
def fileOpenMovie(self): """ Open a movie file to play. """ # bruce 050327 comment: this is not yet updated for "multiple movie objects" # and bugfixing of bugs introduced by that is in progress (only done in a klugy # way so far). ####@@@@ env.history.message(greenmsg("Open Movie File:")) assert self.w.assy.current_movie # (since (as a temporary kluge) we create an empty one, if necessary, before entering # Movie Mode, of which this is a dashboard method [bruce 050328]) if self.w.assy.current_movie and self.w.assy.current_movie.currentFrame != 0: ###k bruce 060108 comment: I don't know if this will happen when currentFrame != 0 due to bug 1273 fix... #####@@@@@ env.history.message( redmsg( "Current movie must be reset to frame 0 to load a new movie." )) return # Determine what directory to open. [bruce 050427 comment: if no moviefile, we should try assy.filename's dir next ###e] if self.w.assy.current_movie and self.w.assy.current_movie.filename: odir, fil, ext = filesplit(self.w.assy.current_movie.filename) del fil, ext #bruce 050413 else: odir = self.w.currentWorkingDirectory # Fixes bug 291 (comment #4). Mark 060729. fn = QFileDialog.getOpenFileName( self, "Differential Position Bytes Format (*.dpb)", odir) if not fn: env.history.message("Cancelled.") return fn = str(fn) # Check if file with name fn is a movie file which is valid for the current Part # [bruce 050324 made that a function and made it print the history messages # which I've commented out below.] from simulation.movie import _checkMovieFile r = _checkMovieFile(self.w.assy.part, fn) if r == 1: ## msg = redmsg("Cannot play movie file [" + fn + "]. It does not exist.") ## env.history.message(msg) return elif r == 2: ## msg = redmsg("Movie file [" + fn + "] not valid for the current part.") ## env.history.message(msg) if self.w.assy.current_movie and self.w.assy.current_movie.might_be_playable( ): #bruce 050427 isOpen -> might_be_playable() msg = "(Previous movie file [" + self.w.assy.current_movie.filename + "] is still open.)" env.history.message(msg) return #bruce 050427 rewrote the following to use a new Movie object from simulation.movie import find_saved_movie new_movie = find_saved_movie(self.w.assy, fn) if new_movie: new_movie.set_alist_from_entire_part( self.w.assy.part) # kluge? might need changing... if self.w.assy.current_movie: #bruce 050427 no longer checking isOpen here self.w.assy.current_movie._close() self.w.assy.current_movie = new_movie self.w.assy.current_movie.cueMovie(propMgr=self) #Make sure to enable movie control buttons! self.command.enableMovieControls(True) self.updateFrameInformation() self._updateMessageInModePM() else: # should never happen due to _checkMovieFile call, so this msg is ok # (but if someday we do _checkMovieFile inside find_saved_movie and not here, # then this will happen as an error return from find_saved_movie) msg = redmsg("Internal error in fileOpenMovie") self.command.enableMovieControls(False) self._updateMessageInModePM(msg) env.history.message(msg) return
def __init__(self, title=_('Choose Files'), filters=[], add_all_files_filter=True, parent=None, modal=True, name='', mode=QFileDialog.ExistingFiles, default_dir='~'): QObject.__init__(self) ftext = '' if filters: for filter in filters: text, extensions = filter extensions = [ '*' + (i if i.startswith('.') else '.' + i) for i in extensions ] ftext += '%s (%s);;' % (text, ' '.join(extensions)) if add_all_files_filter or not ftext: ftext += 'All files (*)' if ftext.endswith(';;'): ftext = ftext[:-2] self.dialog_name = name if name else 'dialog_' + title self.selected_files = None self.fd = None initial_dir = dynamic.get(self.dialog_name, os.path.expanduser(default_dir)) if not isinstance(initial_dir, basestring): initial_dir = os.path.expanduser(default_dir) self.selected_files = [] with SanitizeLibraryPath(): if mode == QFileDialog.AnyFile: f = unicode( QFileDialog.getSaveFileName(parent, title, initial_dir, ftext, "")) if f: self.selected_files.append(f) elif mode == QFileDialog.ExistingFile: f = unicode( QFileDialog.getOpenFileName(parent, title, initial_dir, ftext, "")) if f and os.path.exists(f): self.selected_files.append(f) elif mode == QFileDialog.ExistingFiles: fs = QFileDialog.getOpenFileNames(parent, title, initial_dir, ftext, "") for f in fs: f = unicode(f) if not f: continue if not os.path.exists(f): # QFileDialog for some reason quotes spaces # on linux if there is more than one space in a row f = unquote(f) if f and os.path.exists(f): self.selected_files.append(f) else: opts = QFileDialog.ShowDirsOnly if mode == QFileDialog.Directory else QFileDialog.Option( ) f = unicode( QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) if os.path.exists(f): self.selected_files.append(f) if self.selected_files: self.selected_files = [unicode(q) for q in self.selected_files] saved_loc = self.selected_files[0] if os.path.isfile(saved_loc): saved_loc = os.path.dirname(saved_loc) dynamic[self.dialog_name] = saved_loc self.accepted = bool(self.selected_files)
def __init__(self, title=_('Choose Files'), filters=[], add_all_files_filter=True, parent=None, modal=True, name='', mode=QFileDialog.ExistingFiles, default_dir='~', no_save_dir=False, combine_file_and_saved_dir=False): QObject.__init__(self) ftext = '' if filters: for filter in filters: text, extensions = filter extensions = [ '*' + (i if i.startswith('.') else '.' + i) for i in extensions ] ftext += '%s (%s);;' % (text, ' '.join(extensions)) if add_all_files_filter or not ftext: ftext += 'All files (*)' if ftext.endswith(';;'): ftext = ftext[:-2] self.dialog_name = name if name else 'dialog_' + title self.selected_files = None self.fd = None if combine_file_and_saved_dir: bn = os.path.basename(default_dir) prev = dynamic.get(self.dialog_name, os.path.expanduser('~')) if os.path.exists(prev): if os.path.isfile(prev): prev = os.path.dirname(prev) else: prev = os.path.expanduser('~') initial_dir = os.path.join(prev, bn) elif no_save_dir: initial_dir = os.path.expanduser(default_dir) else: initial_dir = dynamic.get(self.dialog_name, os.path.expanduser(default_dir)) if not isinstance(initial_dir, basestring): initial_dir = os.path.expanduser(default_dir) if not initial_dir or ( not os.path.exists(initial_dir) and not (mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))): initial_dir = select_initial_dir(initial_dir) self.selected_files = [] use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ with SanitizeLibraryPath(): opts = QFileDialog.Option() if not use_native_dialog: opts |= QFileDialog.DontUseNativeDialog if mode == QFileDialog.AnyFile: f = unicode( QFileDialog.getSaveFileName(parent, title, initial_dir, ftext, "", opts)) if f: self.selected_files.append(f) elif mode == QFileDialog.ExistingFile: f = unicode( QFileDialog.getOpenFileName(parent, title, initial_dir, ftext, "", opts)) if f and os.path.exists(f): self.selected_files.append(f) elif mode == QFileDialog.ExistingFiles: fs = QFileDialog.getOpenFileNames(parent, title, initial_dir, ftext, "", opts) for f in fs: f = unicode(f) if not f: continue if not os.path.exists(f): # QFileDialog for some reason quotes spaces # on linux if there is more than one space in a row f = unquote(f) if f and os.path.exists(f): self.selected_files.append(f) else: if mode == QFileDialog.Directory: opts |= QFileDialog.ShowDirsOnly f = unicode( QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) if os.path.exists(f): self.selected_files.append(f) if self.selected_files: self.selected_files = [unicode(q) for q in self.selected_files] saved_loc = self.selected_files[0] if os.path.isfile(saved_loc): saved_loc = os.path.dirname(saved_loc) if not no_save_dir: dynamic[self.dialog_name] = saved_loc self.accepted = bool(self.selected_files)
def loadFavorite(self): """ Load a favorite file """ # If the file already exists in the favorites folder then the user is # given the option of overwriting it or renaming it env.history.message(greenmsg("Load Favorite File:")) formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory if directory == '': directory= getDefaultWorkingDirectory() fname = QFileDialog.getOpenFileName(self, "Choose a file to load", directory, formats) if not fname: env.history.message("User cancelled loading file.") return else: dir, fil = os.path.split(str(fname)) self.setCurrentWorkingDirectory(dir) canLoadFile=loadFavoriteFile(fname) if canLoadFile == 1: #get just the name of the file for loading into the combobox favName = os.path.basename(str(fname)) name = favName[0:len(favName)-4] indexOfDuplicateItem = self.favoritesComboBox.findText(name) #duplicate exists in combobox if indexOfDuplicateItem != -1: ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Rename", "&Cancel", 0, # Enter == button 0 1 # button 1 ) if ret == 0: self.favoritesComboBox.removeItem(indexOfDuplicateItem) self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) ok2, text = writeProteinDisplayStyleSettingsToFavoritesFile(name) msg = "Overwrote favorite [%s]." % (text) env.history.message(msg) elif ret == 1: # add new item to favorites folder as well as combobox self.addFavorite() else: #reset the display setting values to factory default factoryIndex = self.favoritesComboBox.findText( 'Factory default settings') self.favoritesComboBox.setCurrentIndex(factoryIndex) env.prefs.restore_defaults(proteinDisplayStylePrefsList) env.history.message("Cancelled overwriting favorite file.") return else: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "Loaded favorite [%s]." % (name) env.history.message(msg) self.updateProteinDisplayStyleWidgets() return
def load_espimage_file(self, choose_new_image = False, parent = None): """ Load the ESP (.png) image file pointed to by self.espimage_file. If the file does not exist, or if choose_new_image is True, the user will be prompted to choose a new image, and if the file chooser dialog is not cancelled, the new image will be loaded and its pathname stored in self.espimage_file. Return value is None if user cancels the file chooser, but is self.espimage_file (which has just been reloaded, and a history message emitted, whether or not it was newly chosen) in all other cases. If self.espimage_file is changed (to a different value), this marks assy as changed. """ #bruce 060207 revised docstring. I suspect this routine has several distinct # purposes which should not be so intimately mixed (i.e. it should be several # routines). Nothing presently uses the return value. old_espimage_file = self.espimage_file if not parent: parent = self.assy.w cmd = greenmsg("Load ESP Image: ") ## print "load_espimage_file(): espimage_file = ", self.espimage_file if choose_new_image or not self.espimage_file: choose_new_image = True elif not os.path.exists(self.espimage_file): msg = "The ESP image file:\n" + self.espimage_file + "\ndoes not exist.\n\nWould you like to select one?" choose_new_image = True QMessageBox.warning( parent, "Choose ESP Image", \ msg, QMessageBox.Ok, QMessageBox.Cancel) #bruce 060207 question: shouldn't we check here whether they said ok or cancel?? Looks like a bug. ####@@@@ if choose_new_image: cwd = self.assy.get_cwd() fn = QFileDialog.getOpenFileName( parent, "Load an ESP Image File", cwd, "Portable Network Graphics (*.png);;All Files (*.*);;" ) #bruce 060212 added All Files option if not fn: env.history.message(cmd + "Cancelled.") #bruce 060212 bugfix: included cmd return None self.espimage_file = str(fn) if old_espimage_file != self.espimage_file: self.changed() #bruce 060207 fix of perhaps-previously-unreported bug pass if self.image_mods: self.image_mods.reset() self.changed() self._create_PIL_image_obj_from_espimage_file() self._loadTexture() #bruce 060212 comment: this does gl_update, but when we're called from dialog's open file button, # the glpane doesn't show the new texture until the dialog is closed (which is a bug, IMHO), # even if we call env.call_qApp_processEvents() before returning from this method (load_espimage_file). # I don't know why. # Bug fix 1041-1. Mark 051003 msg = "ESP image loaded: [" + self.espimage_file + "]" env.history.message(cmd + msg) return self.espimage_file
def loadFavorite(self): """ Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to be added to the personal favorites list. """ # If the file already exists in the favorites folder then the user is # given the option of overwriting it or renaming it env.history.message(greenmsg("Load Favorite File:")) formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory if directory == '': directory= getDefaultWorkingDirectory() fname = QFileDialog.getOpenFileName(self, "Choose a file to load", directory, formats) if not fname: env.history.message("User cancelled loading file.") return else: dir, fil = os.path.split(str(fname)) self.setCurrentWorkingDirectory(dir) canLoadFile = loadFavoriteFile(fname) if canLoadFile == 1: #get just the name of the file for loading into the combobox favName = os.path.basename(str(fname)) name = favName[0:len(favName)-4] indexOfDuplicateItem = self.favoritesComboBox.findText(name) #duplicate exists in combobox if indexOfDuplicateItem != -1: ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Rename", "&Cancel", 0, # Enter == button 0 1 # button 1 ) if ret == 0: self.favoritesComboBox.removeItem(indexOfDuplicateItem) self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) ok2, text = writeColorSchemeToFavoritesFile(name) msg = "Overwrote favorite [%s]." % (text) env.history.message(msg) elif ret == 1: # add new item to favorites folder as well as combobox self.addFavorite() else: #reset the display setting values to factory default factoryIndex = self.favoritesComboBox.findText( 'Factory default settings') self.favoritesComboBox.setCurrentIndex(factoryIndex) env.prefs.restore_defaults(colorSchemePrefsList) # set it back to blue sky self.win.glpane.setBackgroundGradient(1) self.win.glpane.gl_update() env.history.message("Cancelled overwriting favorite file.") return else: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "Loaded favorite [%s]." % (name) env.history.message(msg) if env.prefs[backgroundGradient_prefs_key]: self.win.glpane.setBackgroundGradient(env.prefs[backgroundGradient_prefs_key]) else: self.win.glpane.setBackgroundColor(env.prefs[backgroundColor_prefs_key]) self.win.glpane.gl_update() return
def fileOpenMovie(self): """ Open a movie file to play. """ # bruce 050327 comment: this is not yet updated for "multiple movie objects" # and bugfixing of bugs introduced by that is in progress (only done in a klugy # way so far). ####@@@@ env.history.message(greenmsg("Open Movie File:")) assert self.w.assy.current_movie # (since (as a temporary kluge) we create an empty one, if necessary, before entering # Movie Mode, of which this is a dashboard method [bruce 050328]) if self.w.assy.current_movie and self.w.assy.current_movie.currentFrame != 0: ###k bruce 060108 comment: I don't know if this will happen when currentFrame != 0 due to bug 1273 fix... #####@@@@@ env.history.message(redmsg("Current movie must be reset to frame 0 to load a new movie.")) return # Determine what directory to open. [bruce 050427 comment: if no moviefile, we should try assy.filename's dir next ###e] if self.w.assy.current_movie and self.w.assy.current_movie.filename: odir, fil, ext = filesplit(self.w.assy.current_movie.filename) del fil, ext #bruce 050413 else: odir = self.w.currentWorkingDirectory # Fixes bug 291 (comment #4). Mark 060729. fn = QFileDialog.getOpenFileName( self, "Differential Position Bytes Format (*.dpb)", odir) if not fn: env.history.message("Cancelled.") return fn = str(fn) # Check if file with name fn is a movie file which is valid for the current Part # [bruce 050324 made that a function and made it print the history messages # which I've commented out below.] from simulation.movie import _checkMovieFile r = _checkMovieFile(self.w.assy.part, fn) if r == 1: ## msg = redmsg("Cannot play movie file [" + fn + "]. It does not exist.") ## env.history.message(msg) return elif r == 2: ## msg = redmsg("Movie file [" + fn + "] not valid for the current part.") ## env.history.message(msg) if self.w.assy.current_movie and self.w.assy.current_movie.might_be_playable(): #bruce 050427 isOpen -> might_be_playable() msg = "(Previous movie file [" + self.w.assy.current_movie.filename + "] is still open.)" env.history.message(msg) return #bruce 050427 rewrote the following to use a new Movie object from simulation.movie import find_saved_movie new_movie = find_saved_movie( self.w.assy, fn ) if new_movie: new_movie.set_alist_from_entire_part(self.w.assy.part) # kluge? might need changing... if self.w.assy.current_movie: #bruce 050427 no longer checking isOpen here self.w.assy.current_movie._close() self.w.assy.current_movie = new_movie self.w.assy.current_movie.cueMovie(propMgr = self) #Make sure to enable movie control buttons! self.parentMode.enableMovieControls(True) self.updateFrameInformation() self._updateMessageInModePM() else: # should never happen due to _checkMovieFile call, so this msg is ok # (but if someday we do _checkMovieFile inside find_saved_movie and not here, # then this will happen as an error return from find_saved_movie) msg = redmsg("Internal error in fileOpenMovie") self.parentMode.enableMovieControls(False) self._updateMessageInModePM(msg) env.history.message(msg) return