def __init__(self, parent): ScriptedLoadableModuleWidget.__init__(self, parent) self.logic = ProcessesLogic() thisPath = qt.QFileInfo(__file__).path() self.defaultPath = os.path.join(thisPath, "Resources", "ProcessScripts", "filter.slicer.py") self.nodeObserverTag = None
def registerSlicerURLHandler(): """ Registers file associations and applicationName:// protocol (e.g., Slicer://) with this executable. This allows Kheops (https://demo.kheops.online) open images selected in the web browser directly in Slicer. For now, only implemented on Windows. """ if os.name == 'nt': launcherPath = qt.QDir.toNativeSeparators( qt.QFileInfo( slicer.app.launcherExecutableFilePath).absoluteFilePath()) reg = qt.QSettings(f"HKEY_CURRENT_USER\\Software\\Classes", qt.QSettings.NativeFormat) reg.setValue(f"{slicer.app.applicationName}/.", f"{slicer.app.applicationName} supported file") reg.setValue(f"{slicer.app.applicationName}/URL protocol", "") reg.setValue(f"{slicer.app.applicationName}/shell/open/command/.", f"\"{launcherPath}\" \"%1\"") reg.setValue(f"{slicer.app.applicationName}/DefaultIcon/.", f"{slicer.app.applicationName}.exe,0") for ext in ['mrml', 'mrb']: reg.setValue(f".{ext}/.", f"{slicer.app.applicationName}") reg.setValue(f".{ext}/Content Type", f"application/x-{ext}") else: raise NotImplementedError()
def test_VolumeProcesses(self): self.delayDisplay("Starting the Volume test") import SampleData volumeNode = SampleData.downloadSample("MRHead") def onProcessesCompleted(testClass): # when test finishes, we succeeded! testClass.delayDisplay('Test passed!') logic = ProcessesLogic( completedCallback=lambda: onProcessesCompleted(self)) thisPath = qt.QFileInfo(__file__).path() scriptPath = os.path.join(thisPath, "Resources", "ProcessScripts", "volumeFilter.slicer.py") for radius in range(5): filterProcess = VolumeFilterProcess(scriptPath, volumeNode, radius * 5) logic.addProcess( VolumeFilterProcess(scriptPath, volumeNode, radius)) logic.run() logic.waitForFinished() # Optional
def createTempDirectory(self): tempDir = qt.QDir(self.getTempDirectoryBase()) tempDirName = qt.QDateTime().currentDateTime().toString("yyyyMMdd_hhmmss_zzz") fileInfo = qt.QFileInfo(qt.QDir(tempDir), tempDirName) dirPath = fileInfo.absoluteFilePath() qt.QDir().mkpath(dirPath) return dirPath
def getTempDirectoryBase(self, bySlicer=True): if bySlicer: import qt, slicer tempDir = qt.QDir(slicer.app.temporaryPath) fileInfo = qt.QFileInfo(qt.QDir(tempDir), "RadPathFusion") dirPath = fileInfo.absoluteFilePath() qt.QDir().mkpath(dirPath) return dirPath
def pathsFromMimeData(mimeData): filesToAdd = [] acceptedFileExtensions = ['jpg', 'jpeg', 'tif', 'tiff', 'png', 'bmp'] if mimeData.hasFormat('text/uri-list'): urls = mimeData.urls() for url in urls: localPath = url.toLocalFile() # convert QUrl to local path pathInfo = qt.QFileInfo() pathInfo.setFile(localPath) # information about the path if pathInfo.isDir( ): # if it is a directory we add the files to the dialog directory = qt.QDir(localPath) nameFilters = [ '*.' + ext for ext in acceptedFileExtensions ] filenamesInFolder = directory.entryList( nameFilters, qt.QDir.Files, qt.QDir.Name) for filenameInFolder in filenamesInFolder: filesToAdd.append( directory.absoluteFilePath(filenameInFolder)) else: ext = pathInfo.suffix().lower() if ext in acceptedFileExtensions: filesToAdd.append(localPath) # Filter out files that are known to cause complications # Currently, there is only one rule, but it is expected that more filtering rules wil be added in the future. filteredFilesToAdd = [] for filePath in filesToAdd: fileName = qt.QFileInfo(filePath).fileName() # Ignore cone-beam image in Bruker Skyscan folder # such as `left_side_damaged__rec_spr.bmp` if fileName.endswith("spr.bmp"): # skip this file logging.debug( f"Skipping {filePath} - it looks like a Bruker Skyscan cone-beam image, not an image slice" ) continue filteredFilesToAdd.append(filePath) return filteredFilesToAdd
def foldersFromMimeData(mimeData, acceptFiles=False): directoriesToAdd = [] if mimeData.hasFormat('text/uri-list'): urls = mimeData.urls() for url in urls: localPath = url.toLocalFile() # convert QUrl to local path pathInfo = qt.QFileInfo() pathInfo.setFile(localPath) # information about the path if pathInfo.isDir(): # if it is a directory we add the files to the dialog directoriesToAdd.append(localPath) elif acceptFiles: directoriesToAdd.append(pathInfo.absolutePath()) return directoriesToAdd
def isMimeDataAccepted(self): """Checks the dropped data and returns true if it is one or more directories""" self.directoriesToAdd = [] mimeData = self.qSlicerFileDialog.mimeData() if mimeData.hasFormat('text/uri-list'): urls = mimeData.urls() for url in urls: localPath = url.toLocalFile() # convert QUrl to local path pathInfo = qt.QFileInfo() pathInfo.setFile(localPath) # information about the path if pathInfo.isDir(): # if it is a directory we add the files to the dialog self.directoriesToAdd.append(localPath) self.qSlicerFileDialog.acceptMimeData(len(self.directoriesToAdd) != 0)
def tempDirectory(self,key='__SlicerTestTemp__',tempDir=None,includeDateTime=False): """Come up with a unique directory name in the temp dir and make it and return it # TODO: switch to QTemporaryDir in Qt5. Note: this directory is not automatically cleaned up """ if not tempDir: tempDir = qt.QDir(slicer.app.temporaryPath) tempDirName = key if includeDateTime: key += qt.QDateTime().currentDateTime().toString("yyyy-MM-dd_hh+mm+ss.zzz") fileInfo = qt.QFileInfo(qt.QDir(tempDir), tempDirName) dirPath = fileInfo.absoluteFilePath() qt.QDir().mkpath(dirPath) return dirPath
def downloadFile(self, dlUrl): import urllib # Set download directory to a folder in Slicer cache destinationDir = slicer.mrmlScene.GetCacheManager().GetRemoteCacheDirectory() fileInfo = qt.QFileInfo(dlUrl.path()) destinationFilePath = destinationDir + "/" + fileInfo.fileName() logging.info("Downloading model file: {0}".format(destinationFilePath)) self.downloadProgressBar.show() urllib.urlretrieve(dlUrl.toString(), destinationFilePath, self.reportProgress) self.downloadProgressBar.close() return destinationFilePath
def createTempDirectory(self, bySlicer=True): if bySlicer: import qt, slicer tempDir = qt.QDir(self.getTempDirectoryBase(bySlicer)) tempDirName = qt.QDateTime().currentDateTime().toString( "yyyyMMdd_hhmmss_zzz") fileInfo = qt.QFileInfo(qt.QDir(tempDir), tempDirName) dirPath = fileInfo.absoluteFilePath() qt.QDir().mkpath(dirPath) # Write inputs inputDir = os.path.join(dirPath, 'input') qt.QDir().mkpath(inputDir) resultTransformDir = os.path.join(dirPath, 'result-transform') qt.QDir().mkpath(resultTransformDir) resultResampleDir = os.path.join(dirPath, 'result-resample') qt.QDir().mkpath(resultResampleDir) return dirPath, inputDir, resultTransformDir, resultResampleDir
def test_ModelProcesses(self): self.delayDisplay("Starting the Model test") layoutManager = slicer.app.layoutManager() layoutManager.setLayout( slicer.vtkMRMLLayoutNode.SlicerLayoutOneUp3DView) modelNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLModelNode") modelNode.CreateDefaultDisplayNodes() sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(10) sphereSource.SetThetaResolution(50) sphereSource.SetPhiResolution(50) sphereSource.Update() modelNode.SetAndObservePolyData(sphereSource.GetOutputDataObject(0)) def onProcessesCompleted(testClass): # when first test finishes, run second test testClass.delayDisplay('Test passed!') testClass.setUp() testClass.test_VolumeProcesses() logic = ProcessesLogic( completedCallback=lambda: onProcessesCompleted(self)) thisPath = qt.QFileInfo(__file__).path() scriptPath = os.path.join(thisPath, "Resources", "ProcessScripts", "modelFilter.slicer.py") for iteration in range(50): filterProcess = ModelFilterProcess(scriptPath, modelNode, iteration) logic.addProcess(filterProcess) logic.run()
def getTempDirectoryBase(self): tempDir = qt.QDir(slicer.app.temporaryPath) fileInfo = qt.QFileInfo(qt.QDir(tempDir), "Elastix") dirPath = fileInfo.absoluteFilePath() qt.QDir().mkpath(dirPath) return dirPath
def loadModules(self, path, depth=1): # Get list of modules in specified path modules = ModuleInfo.findModules(path, depth) # Determine which modules in above are not already loaded factory = slicer.app.moduleManager().factoryManager() loadedModules = factory.instantiatedModuleNames() candidates = [m for m in modules if m.key not in loadedModules] # Prompt to load additional module(s) if len(candidates): dlg = LoadModulesDialog(self.parent.window()) dlg.setModules(candidates) if dlg.exec_() == qt.QDialog.Accepted: modulesToLoad = dlg.selectedModules # Add module(s) to permanent search paths, if requested if dlg.addToSearchPaths: settings = slicer.app.revisionUserSettings() rawSearchPaths = list( _settingsList(settings, "Modules/AdditionalPaths", convertToAbsolutePaths=True)) searchPaths = [qt.QDir(path) for path in rawSearchPaths] modified = False for module in modulesToLoad: rawPath = os.path.dirname(module.path) path = qt.QDir(rawPath) if not path in searchPaths: searchPaths.append(path) rawSearchPaths.append(rawPath) modified = True if modified: settings.setValue( "Modules/AdditionalPaths", slicer.app.toSlicerHomeRelativePaths( rawSearchPaths)) # Enable developer mode (shows Reload&Test section, etc.), if requested if dlg.enableDeveloperMode: qt.QSettings().setValue('Developer/DeveloperMode', 'true') # Register requested module(s) failed = [] for module in modulesToLoad: factory.registerModule(qt.QFileInfo(module.path)) if not factory.isRegistered(module.key): failed.append(module) if len(failed): if len(failed) > 1: text = "The following modules could not be registered:" else: text = "The '%s' module could not be registered:" % failed[ 0].key failedFormat = "<ul><li>%(key)s<br/>(%(path)s)</li></ul>" detailedInformation = "".join( [failedFormat % m.__dict__ for m in failed]) slicer.util.errorDisplay( text, parent=self.parent.window(), windowTitle="Module loading failed", standardButtons=qt.QMessageBox.Close, informativeText=detailedInformation) return # Instantiate and load requested module(s) if not factory.loadModules( [module.key for module in modulesToLoad]): text = ("The module factory manager reported an error. " "One or more of the requested module(s) and/or " "dependencies thereof may not have been loaded.") slicer.util.errorDisplay( text, parent=self.parent.window(), windowTitle="Error loading module(s)", standardButtons=qt.QMessageBox.Close)