def _qfiledialog_wrapper(attr, parent=None, caption='', basedir='', filters='', selectedfilter='', options=None): if options is None: options = QFileDialog.Options(0) # PySide or PyQt >=v4.6 QString = None # analysis:ignore tuple_returned = True try: # PyQt >=v4.6 func = getattr(QFileDialog, attr + 'AndFilter') except AttributeError: # PySide or PyQt <v4.6 func = getattr(QFileDialog, attr) if QString is not None: selectedfilter = QString() tuple_returned = False # Calling QFileDialog static method if sys.platform == "win32": # On Windows platforms: redirect standard outputs _temp1, _temp2 = sys.stdout, sys.stderr sys.stdout, sys.stderr = None, None try: result = func(parent, caption, basedir, filters, selectedfilter, options) except TypeError: # The selectedfilter option (`initialFilter` in Qt) has only been # introduced in Jan. 2010 for PyQt v4.7, that's why we handle here # the TypeError exception which will be raised with PyQt v4.6 # (see Issue 960 for more details) result = func(parent, caption, basedir, filters, options) finally: if sys.platform == "win32": # On Windows platforms: restore standard outputs sys.stdout, sys.stderr = _temp1, _temp2 # Processing output if tuple_returned: # PySide or PyQt >=v4.6 output, selectedfilter = result else: # PyQt <v4.6 (API #1) output = result if QString is not None: # PyQt API #1: conversions needed from QString/QStringList selectedfilter = to_text_string(selectedfilter) if isinstance(output, QString): # Single filename output = to_text_string(output) else: # List of filenames output = [to_text_string(fname) for fname in output] # Always returns the tuple (output, selectedfilter) return output, selectedfilter
def _chooseDirectory(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = PreferencesManager().get( 'DataSelection', 'recent stack directory') if mostRecentStackDirectory is not None: defaultDirectory = os.path.split(mostRecentStackDirectory)[0] else: defaultDirectory = os.path.expanduser('~') options = QFileDialog.Options(QFileDialog.ShowDirsOnly) if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog # Launch the "Open File" dialog directory = QFileDialog.getExistingDirectory(self, "Image Stack Directory", defaultDirectory, options=options) if directory.isNull(): # User cancelled return directory = encode_from_qstring(directory) PreferencesManager().set('DataSelection', 'recent stack directory', directory) self.directoryEdit.setText(decode_to_qstring(directory)) try: globstring = self._getGlobString(directory) except StackFileSelectionWidget.DetermineStackError, e: QMessageBox.warning(self, "Invalid selection", str(e))
def repairFile(self, path, filt=None): """get new path to lost file""" from PyQt4.QtGui import QFileDialog, QMessageBox text = "The file at {} could not be found any more. Do you want to search for it at another directory?".format( path) c = QMessageBox.critical(None, "update external data", text, QMessageBox.Ok | QMessageBox.Cancel) if c == QMessageBox.Cancel: raise RuntimeError("Could not find external data: " + path) options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileName = QFileDialog.getOpenFileName(None, "repair files", path, filt, options=options) if fileName.isEmpty(): raise RuntimeError("Could not find external data: " + path) else: return str(fileName)
def exportRelabeling(self): # Ask for the export path exportPath = QFileDialog.getSaveFileName( self, "Save supervoxel relabeling", "", "Hdf5 Files (*.h5 *.hdf5)", options=QFileDialog.Options(QFileDialog.DontUseNativeDialog)) if exportPath.isNull(): return def handleProgress(progress): # TODO: Hook this up to the progress bar logger.info("Export progress: {}%".format(progress)) op = self.topLevelOperatorView req = op.exportFinalSupervoxels(encode_from_qstring(exportPath), "zyx", handleProgress) self._drawer.exportButton.setEnabled(False) def handleFinish(*args): self._drawer.exportButton.setEnabled(True) req.notify_finished(handleFinish) req.notify_failed(handleFinish)
def save(self): options = QFileDialog.Options() fileName = QFileDialog.getSaveFileName( self, "QFileDialog.getSaveFileName()", "", "All Files (*);;Text Files (*.txt)", options=options) #except: # fileName, _= QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","All Files (*);;Text Files (*.txt)", options=options) if PYQT == 5: fileName = fileName[0] else: pass if fileName: file1 = open(fileName, 'w') #print ('open',fileName) file1.write( 'name, F_0,V_0,K_0,Kprime_0 Debye_0,grueneisen-0,q_0,G_0,Gprime_0, eta_s0 ' ) file1.write('\n') for i in self.Solidsolution: for j in i.parameters(self.Pressure, self.Temperature): file1.write('{:8.8}'.format(j)) file1.write(' ') file1.write('\n') file1.close()
def _chooseDirectory(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = PreferencesManager().get( 'DataSelection', 'recent stack directory') if mostRecentStackDirectory is not None: defaultDirectory = os.path.split(mostRecentStackDirectory)[0] else: defaultDirectory = os.path.expanduser('~') options = QFileDialog.Options(QFileDialog.ShowDirsOnly) if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog # Launch the "Open File" dialog directory = QFileDialog.getExistingDirectory(self, "Image Stack Directory", defaultDirectory, options=options) if directory.isNull(): # User cancelled return directory = encode_from_qstring(directory) PreferencesManager().set('DataSelection', 'recent stack directory', directory) self.directoryEdit.setText(decode_to_qstring(directory)) globstring = self._getGlobString(directory) if globstring: filenames = OpStackLoader.expandGlobStrings(globstring) self._updateFileList(sorted(filenames)) # As a convenience, also show the glob string in the pattern field self.patternEdit.setText(decode_to_qstring(globstring))
def getOpenFileNames(parent=None, caption='', directory='', filter='', selectedFilter='', options=QFileDialogQt4.Options()): return QFileDialogQt4.getOpenFileNamesAndFilter( parent, caption, directory, filter, selectedFilter, options)
def getSaveFileName(parent=None, caption='', directory='', filter='', selectedFilter='', options=OldFileDialog.Options()): return OldFileDialog.getSaveFileNameAndFilter( parent, caption, directory, filter, selectedFilter, options)
def _onSave(self): # If we are actually playing a recording right now, then the "Stop Recording" action gets triggered as the last step. # Ignore it. if self._recorder is None: return self.commentsDisplayEdit.setFocus(True) self._autopaused = False if not self._recorder.paused: self._onPause(False) settings = QSettings("eventcapture", "gui") # Author name is required author_name = str(self.authorEdit.text()) if author_name == '': QMessageBox.critical( self, "Author name required", "Please enter your name as the author of this test case.") return else: # Save as default for next recording. settings.setValue("author_name", author_name) default_dir = self._default_save_dir variant = settings.value("recordings_directory") if not variant.isNull(): default_dir = str(variant.toString()) if default_dir is None: default_dir = '' now = datetime.datetime.now() timestr = "{:04d}{:02d}{:02d}-{:02d}{:02d}".format( now.year, now.month, now.day, now.hour, now.minute) default_script_path = os.path.join( default_dir, "recording-{timestr}.py".format(timestr=timestr)) dlg = QFileDialog(self, "Save Playback Script", default_script_path, "eventcapture scripts (*.py)") dlg.setObjectName("event_recorder_save_dlg") dlg.setAcceptMode(QFileDialog.AcceptSave) dlg.setOptions(QFileDialog.Options(QFileDialog.DontUseNativeDialog)) dlg.exec_() # If the user cancelled, stop now if dlg.result() == QFileDialog.Rejected: return script_path = encode_from_qstring(dlg.selectedFiles()[0]) # Remember the directory as our new default default_dir = os.path.split(script_path)[0] settings.setValue("recordings_directory", default_dir) with open(script_path, 'w') as f: self._recorder.writeScript(f, author_name) self._saved = True
def saveFileLocation(self): """Prompts user where to save the file""" options = QFileDialog.Options() fileName = QFileDialog.getSaveFileName(self, "Save as", "", "CSV(*.csv)", options=options) return str(fileName)
def handleDirectoryButtonClicked(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directoryName = QFileDialog.getExistingDirectory(self, "Base Directory", self.defaultDirectory, options=options) self.ui.directoryInput.setText(directoryName)
def openChooserDialog(categories="Image files (*.jpg);;Video files (*.mp4)"): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog filename = QFileDialog.getOpenFileName(None, "Choose File..", "", categories, options=options) return filename
def _onLineageFileNameButton(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fn = QFileDialog.getSaveFileName(self, 'Save Lineage Trees', os.getenv('HOME'), options=options) if fn is None: logger.info( "cancelled." ) return self._drawer.lineageFileNameEdit.setText(str(fn))
def openMultipleVideoChooserDialog(categories="Video files (*.mp4)"): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog filelist = QFileDialog.getOpenFileNames(None, "Choose File..", "", categories, options=options) return filelist
def openFileLocation(self): """Prompts user to upload a file""" options = QFileDialog.Options() fileName = QFileDialog.getOpenFileName(self, "Open File", "", "All Files (*)", options=options) return str(fileName)
def __selectDirClicked(self): " Selects the script working dir " dirName = QFileDialog.getExistingDirectory( self, "Select the script working directory", self.__dirEdit.text(), QFileDialog.Options(QFileDialog.ShowDirsOnly)) if dirName: self.__dirEdit.setText(os.path.normpath(dirName)) return
def _selectFiles(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = PreferencesManager().get( 'DataSelection', 'recent stack directory') if mostRecentStackDirectory is not None: defaultDirectory = os.path.split(mostRecentStackDirectory)[0] else: defaultDirectory = os.path.expanduser('~') options = QFileDialog.Options(QFileDialog.ShowDirsOnly) if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog # Launch the "Open File" dialog extensions = vigra.impex.listExtensions().split() filt = "Image files (" + ' '.join('*.' + x for x in extensions) + ')' options = QFileDialog.Options() if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileNames = QFileDialog.getOpenFileNames(self, "Select Images for Stack", defaultDirectory, filt, options=options) fileNames = map(encode_from_qstring, fileNames) if len(fileNames) == 0: return if len(fileNames) == 1: msg = 'Cannot create stack: You only chose a single file. ' msg += 'If your stack is contained in a single file (e.g. a multi-page tiff or hdf5 volume),' msg += ' please use the "Add File" button.' QMessageBox.warning(self, "Invalid selection", msg) return None directory = os.path.split(fileNames[0])[0] PreferencesManager().set('DataSelection', 'recent stack directory', directory) self._updateFileList(fileNames)
def __selectDirClicked(self): " The user selects a directory " dirName = QFileDialog.getExistingDirectory( self, "Select directory to search in", self.dirEditCombo.currentText(), QFileDialog.Options(QFileDialog.ShowDirsOnly)) if dirName: self.dirEditCombo.setEditText(os.path.normpath(dirName)) self.__testSearchability() return
def onDirButton( self ): " Displays a directory selection dialog " dirName = QFileDialog.getExistingDirectory( self, "Select project directory", self.dirEdit.text(), QFileDialog.Options( QFileDialog.ShowDirsOnly ) ) if dirName: self.dirEdit.setText( os.path.normpath( dirName ) ) return
def __init__(self, path="", name="", parent=None, confirm_overwrite=False): super(FileWidget, self).__init__(name, parent) layout = QFormLayout(self) browse_button = QPushButton("File Path") self.filename_edit = QLineEdit(path) layout.addRow(browse_button, self.filename_edit) browse_button.clicked.connect(self.set_path) self.dialog_options = QFileDialog.Options() if not confirm_overwrite: self.dialog_options |= QFileDialog.DontConfirmOverwrite self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
def _onExportTifButtonPressed(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog directory = encode_from_qstring(QFileDialog.getExistingDirectory(self, 'Select Directory',os.path.expanduser("~"), options=options)) if directory is None or len(str(directory)) == 0: logger.info( "cancelled." ) return logger.info( 'Saving results as tiffs...' ) label2color = self.mainOperator.label2color lshape = list(self.mainOperator.LabelImage.meta.shape) def _handle_progress(x): self.applet.progressSignal.emit(x) def _export(): num_files = float(len(label2color)) for t, label2color_at in enumerate(label2color): if len(label2color_at) == 0: continue logger.info( 'exporting tiffs for t = ' + str(t) ) roi = SubRegion(self.mainOperator.LabelImage, start=[t,] + 4*[0,], stop=[t+1,] + list(lshape[1:])) labelImage = self.mainOperator.LabelImage.get(roi).wait() relabeled = relabel(labelImage[0,...,0],label2color_at) for i in range(relabeled.shape[2]): out_im = relabeled[:,:,i] out_fn = str(directory) + '/vis_t' + str(t).zfill(4) + '_z' + str(i).zfill(4) + '.tif' vigra.impex.writeImage(np.asarray(out_im,dtype=np.uint32), out_fn) _handle_progress(t/num_files * 100) logger.info( 'Tiffs exported.' ) def _handle_finished(*args): self._drawer.exportTifButton.setEnabled(True) self.applet.progressSignal.emit(100) def _handle_failure( exc, exc_info ): msg = "Exception raised during export. See traceback above.\n" log_exception( logger, msg, exc_info ) self.applet.progressSignal.emit(100) self._drawer.exportTifButton.setEnabled(True) self._drawer.exportTifButton.setEnabled(False) self.applet.progressSignal.emit(0) req = Request( _export ) req.notify_failed( _handle_failure ) req.notify_finished( _handle_finished ) req.submit()
def onUsePrecomputedFeaturesButtonClicked(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog filename = QFileDialog.getOpenFileName(self, 'Open Feature List', '.', options=options) filename = encode_from_qstring(filename) #sanity checks on the given file if not filename: return if not os.path.exists(filename): QMessageBox.critical(self, "Open Feature List", "File '%s' does not exist" % filename) return f = open(filename, 'r') with f: for line in f: line = line.strip() if len(line) == 0: continue if not os.path.exists(line): QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', does not exist" % (line, filename)) return try: h = h5py.File(line, 'r') with h: assert len(h["data"].shape) == 3 except: QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', could not be opened as an HDF5 file or does not contain a 3D dataset called 'data'" % (line, filename)) return self.topLevelOperatorView.FeatureListFilename.setValue(filename) self.topLevelOperatorView._setupOutputs() self.onFeaturesSelectionsChanged() # Notify the workflow that some applets may have changed state now. # (For example, the downstream pixel classification applet can # be used now that there are features selected) self.parentApplet.appletStateUpdateRequested.emit()
def _select_file_with_dialog(self, caption = 'Select file', initialDir = None, filetype_filter = None): '''Show a modal select file dialog to select a file.''' filename = QFileDialog.getOpenFileName(self, caption, initialDir or '', filetype_filter or '', # The remaining attributes are currently unused None, # selectedFilter QFileDialog.Options()) #options return filename
def getProjectPathToOpen(self, defaultDirectory): """ Return the path of the project the user wants to open (or None if he cancels). """ projectFilePath = QFileDialog.getOpenFileName( self, "Open Ilastik Project", defaultDirectory, "Ilastik project files (*.ilp)", options=QFileDialog.Options(QFileDialog.DontUseNativeDialog)) # If the user canceled, stop now if projectFilePath.isNull(): return None return str(projectFilePath)
def onUsePrecomputedFeaturesButtonClicked(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog filenames = QFileDialog.getOpenFileNames(self, 'Open Feature Files', '.', options=options) filenames = map(encode_from_qstring, filenames) # Check if file exists if not filenames: return for filename in filenames: if not os.path.exists(filename): QMessageBox.critical(self, "Open Feature List", "File '%s' does not exist" % filename) return num_lanes = len(self.parentApplet.topLevelOperator.FeatureListFilename) if num_lanes != len(filenames): QMessageBox.critical( self, "Wrong number of feature files", "You must select all pre-computed feature files at once (shift-click).\n" "You selected {} file(s), but there are {} image(s) loaded". format(len(filenames), num_lanes)) return for filename, slot in zip( filenames, self.parentApplet.topLevelOperator.FeatureListFilename): slot.setValue(filename) # Create a dummy SelectionMatrix, just so the operator knows it is configured # This is a little hacky. We should really make SelectionMatrix optional, # and then handle the choice correctly in setupOutputs, probably involving # the Output.meta.NOTREADY flag dummy_matrix = numpy.zeros((6, 7), dtype=bool) dummy_matrix[0, 0] = True self.parentApplet.topLevelOperator.SelectionMatrix.setValue(True) # Notify the workflow that some applets may have changed state now. # (For example, the downstream pixel classification applet can # be used now that there are features selected) self.parentApplet.appletStateUpdateRequested.emit()
def _onSave(self): # If we are actually playing a recording right now, then the "Stop Recording" action gets triggered as the last step. # Ignore it. if self._recorder is None: return self.commentsDisplayEdit.setFocus(True) self._autopaused = False if not self._recorder.paused: self._onPause(False) self.startButton.setEnabled(True) settings = QSettings("Ilastik", "Event Recorder") variant = settings.value("recordings_directory") if not variant.isNull(): default_dir = str( variant.toString() ) else: import ilastik ilastik_module_root = os.path.split(ilastik.__file__)[0] ilastik_repo_root = os.path.split( ilastik_module_root )[0] default_dir = os.path.join( ilastik_repo_root, "tests" ) now = datetime.datetime.now() timestr = "{:04d}{:02d}{:02d}-{:02d}{:02d}".format( now.year, now.month, now.day, now.hour, now.minute ) default_script_path = os.path.join( default_dir, "recording-{timestr}.py".format( timestr=timestr ) ) dlg = QFileDialog(self, "Save Playback Script", default_script_path, "Ilastik event playback scripts (*.py)") dlg.setObjectName("event_recorder_save_dlg") dlg.setAcceptMode(QFileDialog.AcceptSave) dlg.setOptions( QFileDialog.Options(QFileDialog.DontUseNativeDialog) ) dlg.exec_() # If the user cancelled, stop now if dlg.result() == QFileDialog.Rejected: return script_path = str(dlg.selectedFiles()[0]) # Remember the directory as our new default default_dir = os.path.split(script_path)[0] settings.setValue( "recordings_directory", default_dir ) with open(script_path, 'w') as f: self._recorder.writeScript(f) self._saved = True
def getImageFileNamesToOpen(self, defaultDirectory): """ Launch an "Open File" dialog to ask the user for one or more image files. """ extensions = OpDataSelection.SupportedExtensions filt = "Image files (" + ' '.join('*.' + x for x in extensions) + ')' options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileNames = QFileDialog.getOpenFileNames(self, "Select Images", defaultDirectory, filt, options=options) # Convert from QtString to python str fileNames = [str(s) for s in fileNames] return fileNames
def getProjectPathToCreate(self, defaultPath=None, caption="Create Ilastik Project"): """ Ask the user where he would like to create a project file. """ if defaultPath is None: defaultPath = os.path.expanduser("~/MyProject.ilp") fileSelected = False while not fileSelected: projectFilePath = QFileDialog.getSaveFileName( self, caption, defaultPath, "Ilastik project files (*.ilp)", options=QFileDialog.Options(QFileDialog.DontUseNativeDialog)) # If the user cancelled, stop now if projectFilePath.isNull(): return None projectFilePath = str(projectFilePath) fileSelected = True # Add extension if necessary fileExtension = os.path.splitext(projectFilePath)[1].lower() if fileExtension != '.ilp': projectFilePath += ".ilp" if os.path.exists(projectFilePath): # Since we changed the file path, we need to re-check if we're overwriting an existing file. message = "A file named '" + projectFilePath + "' already exists in this location.\n" message += "Are you sure you want to overwrite it?" buttons = QMessageBox.Yes | QMessageBox.Cancel response = QMessageBox.warning( self, "Overwrite existing project?", message, buttons, defaultButton=QMessageBox.Cancel) if response == QMessageBox.Cancel: # Try again... fileSelected = False return projectFilePath
def onUsePrecomputedFeaturesButtonClicked(self): options = QFileDialog.Options() if ilastik_config.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog filename = QFileDialog.getOpenFileName(self, 'Open Feature List', '.', options=options) #sanity checks on the given file if not filename: return if not os.path.exists(filename): QMessageBox.critical(self, "Open Feature List", "File '%s' does not exist" % filename) return f = open(filename, 'r') with f: for line in f: line = line.strip() if len(line) == 0: continue if not os.path.exists(line): QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', does not exist" % (line, filename)) return try: h = h5py.File(line, 'r') with h: assert len(h["data"].shape) == 3 except: QMessageBox.critical( self, "Open Feature List", "File '%s', referenced in '%s', could not be opened as an HDF5 file or does not contain a 3D dataset called 'data'" % (line, filename)) return self.topLevelOperatorView.FeatureListFilename.setValue(filename) self.topLevelOperatorView._setupOutputs() self.onFeaturesSelectionsChanged()
def exportFinalSegmentation(self): # Ask for the export path exportPath = QFileDialog.getSaveFileName( self, "Save final segmentation", "", "Hdf5 Files (*.h5 *.hdf5)", options=QFileDialog.Options(QFileDialog.DontUseNativeDialog) ) if exportPath.isNull(): return def handleProgress(progress): # TODO: Hook this up to the progress bar print "Export progress: {}%".format( progress ) op = self.topLevelOperatorView req = op.exportFinalSegmentation( str(exportPath), "zyx", handleProgress ) self._drawer.exportButton.setEnabled(False) def handleFinish(*args): self._drawer.exportButton.setEnabled(True) req.notify_finished( handleFinish ) req.notify_failed( handleFinish )