Пример #1
0
 def QuestionPopup( message ):
   messageBox = qt.QMessageBox()
   clickedButton = messageBox.question(None, '', message, qt.QMessageBox().Yes | qt.QMessageBox().No, qt.QMessageBox().Yes)
   if clickedButton == qt.QMessageBox.Yes:
     return True
   else:
     return False
Пример #2
0
    def createExtensionModule(self):
        if (self.extensionLocation is None):
            # Action shouldn't be enabled if no extension is selected, but guard
            # against that just in case...
            return

        dlg = CreateComponentDialog("module", self.parent.window())
        dlg.setTemplates(self.templateManager.templates("modules"),
                         default="scripted")
        dlg.showDestination = False

        while dlg.exec_() == qt.QDialog.Accepted:
            name = dlg.componentName

            try:
                self.templateManager.copyTemplate(self.extensionLocation,
                                                  "modules", dlg.componentType,
                                                  name)

            except:
                md = qt.QMessageBox(self.parent.window())
                md.icon = qt.QMessageBox.Critical
                md.text = "An error occurred while trying to create the module."
                md.detailedText = traceback.format_exc()
                md.standardButtons = qt.QMessageBox.Retry | qt.QMessageBox.Close
                if md.exec_() != qt.QMessageBox.Retry:
                    return

                continue

            try:
                self.extensionProject.addModule(name)
                self.extensionProject.save()

            except:
                md = qt.QMessageBox(self.parent.window())
                md.icon = qt.QMessageBox.Critical
                md.text = "An error occurred while adding the module to the extension."
                md.informativeText = "The module has been created, but the extension" \
                                     " CMakeLists.txt could not be updated. In order" \
                                     " to include the module in the extension build," \
                                     " you will need to update the extension" \
                                     " CMakeLists.txt by hand."
                md.detailedText = traceback.format_exc()
                md.standardButtons = qt.QMessageBox.Close
                md.exec_()

            self.loadModules(os.path.join(self.extensionLocation, name),
                             depth=0)
            return
Пример #3
0
    def createExtension(self):
        dlg = CreateComponentDialog("extension", self.parent.window())
        dlg.setTemplates(self.templateManager.templates("extensions"))

        while dlg.exec_() == qt.QDialog.Accepted:
            try:
                path = self.templateManager.copyTemplate(
                    dlg.destination, "extensions", dlg.componentType,
                    dlg.componentName)

            except:
                md = qt.QMessageBox(self.parent.window())
                md.icon = qt.QMessageBox.Critical
                md.text = "An error occurred while trying to create the extension."
                md.detailedText = traceback.format_exc()
                md.standardButtons = qt.QMessageBox.Retry | qt.QMessageBox.Close
                if md.exec_() != qt.QMessageBox.Retry:
                    return

                continue

            if self.selectExtension(path):
                self.editExtensionMetadata()

            return
Пример #4
0
 def setNumDialogs(self, numDialogs=1, dialogType=None):
     """ User can set the amount of dialogs in the
         dialog sequence.
     """
     for x in range(0, numDialogs):
         try:
             #
             # Set dialog based on the 'dialogType' argument.
             #
             self.dialogs.append(dialogType[str(x)])
         except Exception, e:
             #
             # Set default based on the default 'dialogType' argument.
             #
             dialog = qt.QMessageBox()
             self.dialogs.append(dialog)
             self.dialogs[x].connect('buttonClicked(QAbstractButton*)',
                                     self.onButtonClicked)
             self.dialogs[x].setTextFormat(1)
             #
             # NOTE: Need to keep the window modality
             # always in front.  Blocking out
             # all other interactions.
             #
             self.dialogs[x].setWindowModality(2)
Пример #5
0
  def uploadSnapshots(self):
    """Upload the checked snapshots to Picasa (avoiding upload the ones already uploaded).
    Remember that """   
    # Store the albums that must be uploaded    
    ids = []    
     
    # Add to the list of uploads just the ones that are visible, checked and not have been already uploaded
    for key,value in self.snapshotsCached.items():
      cb = value[self.SNAPSHOT_WIDGET]
      if cb.visible and cb.checked and not value[self.SNAPSHOT_UPLOADED]:    
        ids.append(key)

    self.imagesToUploadCount = len(ids)    
    
    if self.imagesToUploadCount == 0:
      # No albums to upload. Display information message
      qt.QMessageBox.warning(slicer.util.mainWindow(), 'Warning', 'There are not any new snapshopts to upload to Picasa at this moment')      
    else:
      self.imagesUploadedCount = 0
      
      # Get the selected album id
      albumId = self.albumNamesComboBox.itemData(self.albumNamesComboBox.currentIndex)
     
      # Get the selected tags (pressed buttons)
      tags = [b.text for b in [btn for btn in self.btnTags if btn.checked]]
                  
      self.progressBar.setMaximum(self.imagesToUploadCount)
      self.progressBar.setValue(0)        
          
      self.progressBar.show()     
          
     
      # Upload
      #self.logic.picasaUploadPictures(ids, albumId, tags, self.onImageUploaded)
      for snapshotNodeId in ids:     
        self.progressBar.labelText = "Uploading %i / %i images..." % (self.imagesUploadedCount + 1, self.imagesToUploadCount)   
        slicer.app.processEvents()
        self.logic.picasaUploadPicture(snapshotNodeId, self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_NAME], self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_DESCRIPTION], albumId, tags)
        self.imagesUploadedCount += 1
        
        # Update the state of the new uploaded snap
        self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_UPLOADED] = True
        self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_WIDGET].toolTip = "%s. Uploaded to Picasa: YES" % self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_DESCRIPTION]
        self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_WIDGET].checked = True
        self.snapshotsCached[snapshotNodeId][self.SNAPSHOT_WIDGET].enabled = False
        slicer.app.processEvents()
        if self.progressBar.wasCanceled:
          # The process was cancelled by the user
          qt.QMessageBox.warning(slicer.util.mainWindow(), 'Warning', 'The process was cancelled, but %i images were uploaded' % self.imagesUploadedCount)
          return 
        
        self.progressBar.setValue(self.imagesUploadedCount)
        #self.progressBar.setFormat("Uploading %i / %i images..." % (self.imagesUploadedCount + 1, self.imagesToUploadCount))
        #self.progressBar.labelText = "Uploading %i / %i images..." % (self.imagesUploadedCount + 1, self.imagesToUploadCount)
        #slicer.app.processEvents()
                
      # Inform the user
      self.msgBox = qt.QMessageBox(qt.QMessageBox.Information, 'Images uploaded', '%i images were uploaded succesfully' % self.imagesUploadedCount)  
      self.msgBox.setModal(True)
      self.msgBox.show()      
Пример #6
0
 def messageBox(self, text, title='DICOM'):
     self.mb = qt.QMessageBox(slicer.util.mainWindow())
     self.mb.setWindowTitle(title)
     self.mb.setText(text)
     self.mb.setWindowModality(1)
     self.mb.exec_()
     return
Пример #7
0
 def genMsg(self, title, text, info, detail, icon=qt.QMessageBox.Warning):
     '''Returns a customised message box object'''
     msg = qt.QMessageBox()
     msg.setIcon(icon)
     msg.setWindowTitle(title)
     msg.setText(text)
     msg.setInformativeText(info)
     msg.setDetailedText(detail)
     return msg
Пример #8
0
 def confirmDialog(self, message):
     self.dialog = qt.QMessageBox()
     self.dialog.setWindowTitle("Editor")
     self.dialog.setText(message)
     self.dialogRejectButton = self.addButton("Cancel", 2)
     self.dialogAcceptButton = self.addButton("Ok", 1)
     # TODO: cannot call the exec() method from the pythonqt
     #self.dialog.exec()
     return True
Пример #9
0
 def __init__(self, parent, helpString = ""):
   self.helpString = helpString
   self.message = qt.QMessageBox()
   self.message.setWindowTitle("Editor Help")
   self.button = qt.QPushButton("?", parent)
   self.button.setMaximumWidth(15)
   self.button.setToolTip("Bring up a help window")
   parent.layout().addWidget(self.button)
   self.button.connect('clicked()', self.showHelp)
Пример #10
0
    def onDownloadButton(self):
        """Click in download button"""
        # Check if there is a Study and Case introduced
        self.CaseId = self.txtCaseId.text.strip()
        if self.CaseId and self.StudyId:
            self.lblDownloading.show()
            slicer.app.processEvents()

            # Get the selected image types and label maps
            imageTypes = [
                self.imageTypes[cb.text] for cb in
                [check for check in self.cbsImageTypes if check.isChecked()]
            ]
            labelMapExtensions = [
                self.labelMapTypes[cb.text] for cb in [
                    check for check in self.cbsLabelMapTypes
                    if check.isChecked()
                ]
            ]

            result = self.logic.loadCase(self.txtServer.text,
                                         self.txtServerpath.text, self.StudyId,
                                         self.txtCaseId.text, imageTypes,
                                         labelMapExtensions,
                                         self.localStoragePath,
                                         self.cbCacheMode.checkState(),
                                         self.rbSSH.isChecked(),
                                         self.txtPrivateKeySSH.text)

            self.lblDownloading.hide()
            if (result == Util.ERROR):
                self.msgBox = qt.QMessageBox(
                    qt.QMessageBox.Warning, 'Error',
                    "There was an error when downloading some of the images of this case. It is possible that some of the selected images where not available in the server. Please review the log console for more details.\nSuggested actions:\n-Empty cache\n-Restart Slicer"
                )
                self.msgBox.show()
        else:
            # Show info messsage
            self.msgBox = qt.QMessageBox(
                qt.QMessageBox.Information, 'Attention',
                "Please make sure that you have selected a study and a case")
            self.msgBox.show()
Пример #11
0
    def createExtension(self):
        dlg = CreateComponentDialog("extension", self.parent.window())
        dlg.setTemplates(self.templateManager.templates("extensions"))

        while dlg.exec_() == qt.QDialog.Accepted:

            # If the selected destination is in a repository then use the root of that repository
            # as destination
            try:
                repo = SlicerWizard.Utilities.getRepo(dlg.destination)

                createInSubdirectory = True
                requireEmptyDirectory = True

                if repo is None:
                    destination = os.path.join(dlg.destination,
                                               dlg.componentName)
                    if os.path.exists(dlg.destination):
                        raise IOError("create extension: refusing to overwrite"
                                      " existing directory '%s'" %
                                      dlg.destination)

                else:
                    destination = SlicerWizard.Utilities.localRoot(repo)
                    cmakeFile = os.path.join(destination, "CMakeLists.txt")
                    createInSubdirectory = False  # create the files in the destination directory
                    requireEmptyDirectory = False  # we only check if no CMakeLists.txt file exists
                    if os.path.exists(cmakeFile):
                        raise IOError(
                            "create extension: refusing to overwrite"
                            " directory containing CMakeLists.txt file at '%s'"
                            % dlg.destination)

                path = self.templateManager.copyTemplate(
                    destination, "extensions", dlg.componentType,
                    dlg.componentName, createInSubdirectory,
                    requireEmptyDirectory)

            except:
                md = qt.QMessageBox(self.parent.window())
                md.icon = qt.QMessageBox.Critical
                md.text = "An error occurred while trying to create the extension."
                md.detailedText = traceback.format_exc()
                md.standardButtons = qt.QMessageBox.Retry | qt.QMessageBox.Close
                if md.exec_() != qt.QMessageBox.Retry:
                    return

                continue

            if self.selectExtension(path):
                self.editExtensionMetadata()

            return
Пример #12
0
    def runPreProcessing(self):
        '''
    '''
        # notify user
        dialog = qt.QMessageBox()
        dialog.setWindowTitle("Please wait")
        dialog.setText("Please wait while pre-processing runs..")
        dialog.setModal(False)
        dialog.show()

        # message = qt.QMessageBox( qt.QMessageBox.NoIcon, "Please wait", "Please wait while pre-processing runs..", qt.QMessageBox.Ignore )
        # message.setModal( False )
        # message.show()
        slicer.app.processEvents()

        # run preprocessing
        returnValue = tcl("::EMSegmenterPreProcessingTcl::Run")

        # message.hide()
        dialog.hide()

        slicer.app.processEvents()

        if not returnValue or int(returnValue) != 0:
            # something went wrong!
            # error message!
            messageBox = qt.QMessageBox.warning(
                self, "Error", "Pre-processing did not execute correctly!")
            return

        workingDataNode = self.mrmlManager().GetWorkingDataNode()

        if workingDataNode:
            # set flags in the mrml nodes
            workingDataNode.SetAlignedTargetNodeIsValid(1)
            workingDataNode.SetAlignedAtlasNodeIsValid(1)

            # show preprocessing output in sliceViews
            volumeCollection = workingDataNode.GetInputTargetNode()
            if volumeCollection:
                outputNode = volumeCollection.GetNthVolumeNode(0)
                # propagate to sliceViews
                selectionNode = slicer.app.applicationLogic().GetSelectionNode(
                )
                selectionNode.SetReferenceActiveVolumeID(outputNode.GetID())
                #selectionNode.SetReferenceSecondaryVolumeID( outputNode.GetID() )
                slicer.app.applicationLogic().PropagateVolumeSelection()

        Helper.Info('=============================================')
        Helper.Info('Pre-processing completed successfully')
        Helper.Info('=============================================')
Пример #13
0
 def onApplyButton(self):
     if self.applyButton.text == "Generate":
         self.applyButton.setText("Cancel")
     else:
         self.reset()
         return
     configPath = self.configPathEdit.currentPath
     targetDirectoryPath = self.targetDirectoryButton.directory
     if configPath == "" or targetDirectoryPath == "":
         self.message.showMessage(
             "Must select config file and and output path")
         self.reset()
         return
     self.logic.configure(configPath, targetDirectoryPath, self.myQObject)
     self.logic.generate()
     forceVal = False
     if self.logic.errorMessage.startswith("AppExists:"):
         targetDirectory = self.logic.errorMessage[len("AppExists:"):]
         answer = self.showErrorMessage(
             "Target Exists", "The application directory exists."
             '\n\n%s\n\nClick Ok to overwrite.' % targetDirectory)
         if answer == qt.QMessageBox.Ok:
             self.logic.configure(configPath,
                                  targetDirectoryPath,
                                  self.myQObject,
                                  force=True)
             self.logic.generate()
             forceVal = True
         else:
             self.reset()
     if self.logic.errorMessage == "Extension Updates available":
         answer = self.showErrorMessage( "Extension Updates available",
                                         "Extension Updates are available. " \
                                         "Click Ok to ignore, or update them manually.")
         if answer == qt.QMessageBox.Ok:
             self.logic.configure(configPath,
                                  targetDirectoryPath,
                                  self.myQObject,
                                  ignoreUpdates=True,
                                  force=forceVal)
             self.logic.generate()
         else:
             self.reset()
     if self.logic.errorMessage:
         qt.QMessageBox().question(slicer.app.activeWindow(),
                                   "CustomSlicerGenerator",
                                   self.logic.errorMessage,
                                   qt.QMessageBox.Ok)
         self.reset(
         )  # Reset only if error found. Otherwise extensions might be installing
Пример #14
0
 def killOtherListeners(self, osName, pid= None):
   msgBox = qt.QMessageBox()
   msgBox.setText('There are other DICOM listeners running.\n Do you want to end them?')
   msgBox.setStandardButtons(qt.QMessageBox.Yes | qt.QMessageBox.No)
   val = msgBox.exec_()
   if(val == qt.QMessageBox.Yes):
     if osName == 'nt':
       os.popen('taskkill /f /im storescp.exe')
     elif osName == 'posix':
       import signal
       os.kill(pid, signal.SIGKILL)
     return True
   else:
     return False
Пример #15
0
    def __init__(self, MODULE):
        """ 
        Init function.

   
        """

        self.MODULE = MODULE
        self.ScenePackager = ScenePackager(self.MODULE)

        #------------------------
        # Set wait window
        #------------------------
        self.waitWindow = qt.QMessageBox(1, "Uploading", \
                                         "Please wait while file uploads...")
Пример #16
0
    def initClearDialog(self):
        """ Initiates/resets dialog for window to clear the current scene.
        """
        try:
            self.clearSceneDialog.delete()
        except:
            pass

        self.clearSceneDialog = qt.QMessageBox()
        self.clearSceneDialog.setStandardButtons(qt.QMessageBox.Yes
                                                 | qt.QMessageBox.No)
        self.clearSceneDialog.setDefaultButton(qt.QMessageBox.No)
        self.clearSceneDialog.setText("In order to run tests " +
                                      "you have to clear the current scene." +
                                      "\nAre you sure you want to clear?")
Пример #17
0
    def __makeDialog(self):
        """
        The Dialog box.  If the user 'OK's the delete
        it calls on 'Workflow_Delete.beginWorkflow'

        @return: The delete dialog.
        @rtype: qt.QMessageBox
        """
        deleteDialog = qt.QMessageBox()
        deleteDialog.setIcon(qt.QMessageBox.Warning)
        deleteDialog.setText("Are you sure you want to delete '%s' from Xnat?"\
                             %(self.MODULE.View.getItemName()))
        deleteDialog.connect('buttonClicked(QAbstractButton*)',
                             self.beginWorkflow)
        deleteDialog.addButton(qt.QMessageBox.Ok)
        deleteDialog.addButton(qt.QMessageBox.Cancel)
        return deleteDialog
Пример #18
0
    def __init__(self, MODULE):
        """ Init function.
        """

        self.MODULE = MODULE
        self.XnatScenePackager = XnatScenePackager(self.MODULE)

        #------------------------
        # Set wait window
        #------------------------
        self.waitWindow = qt.QMessageBox(1, "Uploading",
                                         "Please wait while file uploads...")
        self.waitWindow.setWindowModality(2)

        #
        # Remove the 'OK' button from the wait window.
        #
        self.waitWindow.setStandardButtons(0)
Пример #19
0
    def __init__(self, MODULE, uriName):
        """ Init function.
        """

        #--------------------
        # The MODULE
        #--------------------
        self.MODULE = MODULE

        #--------------------
        # The Dialog box.  If the user 'OK's the delete
        # it calls on 'XnatDeleteWorkflow.beginWorkflow'
        #--------------------
        self.deleteDialog = qt.QMessageBox()
        self.deleteDialog.setIcon(qt.QMessageBox.Warning)
        self.deleteDialog.setText(
            "Are you sure you want to delete the '%s' from Xnat?" % (uriName))
        self.deleteDialog.connect('buttonClicked(QAbstractButton*)',
                                  self.beginWorkflow)
        self.deleteDialog.addButton(qt.QMessageBox.Ok)
        self.deleteDialog.addButton(qt.QMessageBox.Cancel)
Пример #20
0
    def __init__(self, MODULE):
        """ 
        @param MODULE: The XNATSlicer module.
        @type MODULE: XnatSlicerWidget
        """
        self.MODULE = MODULE
        self.loadFile = None
        self.newMRMLFile = None
        self.currRemoteHost = None

        self.skipEmptySceneCheck = False
        self._src = None
        self.loaders = {}

        #--------------------------------
        # Popups
        #--------------------------------
        self.areYouSureDialog = qt.QMessageBox()
        self.areYouSureDialog.setIcon(4)
        self.areYouSureDialog.setText(
            "You are about to load all readable scans from '**HERE**'.\n" +
            "This may take several minutes.\n" +
            "Are you sure you want to continue?")
        self.areYouSureDialog.addButton(qt.QMessageBox.Yes)
        self.areYouSureDialog.addButton(qt.QMessageBox.No)
        self.areYouSureDialog.connect('buttonClicked(QAbstractButton*)',
                                      self.beginWorkflow)

        self.XnatDownloadPopup = XnatDownloadPopup()
        self.XnatDownloadPopup.setCancelCallback(
            self.MODULE.XnatIo.cancelDownload)

        self.clearScenePopup = XnatClearScenePopup()
        self.clearScenePopup.connect('buttonClicked(QAbstractButton*)',
                                     self.__clearSceneButtonClicked)

        self.preDownloadPopup = XnatTextPopup('<b>Checking files...</b>')
        self.postDownloadPopup = XnatTextPopup(
            '<b>Processing.  Data will load automatically.</b>')
Пример #21
0
    def selectExtension(self, path=None):
        if path is None or isinstance(path, bool):
            path = qt.QFileDialog.getExistingDirectory(self.parent.window(),
                                                       "Select Extension...",
                                                       self.extensionLocation)

        if not len(path):
            return False

        # Attempt to open extension
        try:
            repo = SlicerWizard.Utilities.getRepo(path)

            if repo is None:
                xd = SlicerWizard.ExtensionDescription(sourcedir=path)

            else:
                xd = SlicerWizard.ExtensionDescription(repo=repo)
                path = SlicerWizard.Utilities.localRoot(repo)

            xp = SlicerWizard.ExtensionProject(path)

        except:
            md = qt.QMessageBox(self.parent.window())
            md.icon = qt.QMessageBox.Critical
            md.text = "Failed to open extension '%s'." % path
            md.detailedText = traceback.format_exc()
            md.standardButtons = qt.QMessageBox.Close
            md.exec_()
            return False

        # Enable and show edit section
        self.editorCollapsibleButton.enabled = True
        self.editorCollapsibleButton.collapsed = False

        # Populate edit information
        self.extensionNameField.text = xp.project
        self.extensionLocationField.text = path

        if xd.scmurl == "NA":
            if repo is None:
                repoText = "(none)"
            elif hasattr(repo, "remotes"):
                repoText = "(local git repository)"
            else:
                repoText = "(unknown local repository)"

            self.extensionRepositoryField.clear()
            self.extensionRepositoryField.placeholderText = repoText

        else:
            self.extensionRepositoryField.text = xd.scmurl

        ri = self.extensionContentsModel.setRootPath(path)
        self.extensionContentsView.setRootIndex(ri)

        w = self.extensionContentsView.width
        self.extensionContentsView.setColumnWidth(0, (w * 4) / 9)

        # Prompt to load scripted modules from extension
        self.loadModules(path)

        # Store extension location, project and description for later use
        self.extensionProject = xp
        self.extensionDescription = xd
        self.extensionLocation = path
        return True
Пример #22
0
 def showErrorMessage(self, windowTitle, text):
     answer = qt.QMessageBox().question(
         slicer.app.activeWindow(), windowTitle, text,
         qt.QMessageBox.Ok | qt.QMessageBox.Cancel)
     return answer
Пример #23
0
    def setup(self):
        """Init the widget """
        # ScriptedLoadableModuleWidget.setup(self)

        settings = qt.QSettings()

        if (SlicerUtil.IsDevelopment):
            # reload button
            self.reloadButton = qt.QPushButton("Reload")
            self.reloadButton.toolTip = "Reload this module."
            self.reloadButton.name = "Reload"
            self.layout.addWidget(self.reloadButton)
            self.reloadButton.connect('clicked()', self.onBtnReloadClicked)

        self.logic = PicasaSnapLogic()
        self.__addObservers__()

        ######## Credentials
        self.credentialsCollapsibleButton = ctk.ctkCollapsibleButton()
        self.credentialsCollapsibleButton.text = "Credentials"
        self.layout.addWidget(self.credentialsCollapsibleButton)
        self.credentialsLayout = qt.QFormLayout(
            self.credentialsCollapsibleButton)

        self.isUserLogged = False

        self.loginLineEdit = qt.QLineEdit()
        self.credentialsLayout.addRow("Login:   "******"Password:   "******"Remember my credentials")
        self.rememberCredentialsCheckBox.toolTip = "Check for an automatic login when the application starts"
        self.loginButton = qt.QPushButton("Login")
        self.loginButton.toolTip = "Login in Picassa service (Google credentials)"
        self.logoutButton = qt.QPushButton("Logout")
        self.logoutButton.toolTip = "Logout to connect with another user's credentials"
        # Add all the items, they will be shown/hidden in refreshCredentialsUI function
        self.credentialsLayout.addRow(self.rememberCredentialsCheckBox,
                                      self.loginButton)
        self.credentialsLayout.addRow(None, self.logoutButton)

        ######## Snapshots (main frame)
        self.mainCollapsibleButton = ctk.ctkCollapsibleButton()
        self.mainCollapsibleButton.text = "Snapshots"
        self.layout.addWidget(self.mainCollapsibleButton)
        self.mainLayout = qt.QVBoxLayout(self.mainCollapsibleButton)

        ############### Current snapshots
        self.currentSnapshotsFrame = qt.QFrame()
        self.currentSnapshotsLayout = qt.QVBoxLayout()
        self.currentSnapshotsFrame.setLayout(self.currentSnapshotsLayout)
        self.currentSnapshotsFrame.setFrameShape(qt.QFrame.StyledPanel)
        self.mainLayout.addWidget(self.currentSnapshotsFrame)

        self.snapshotsLabel = qt.QLabel("Snapshots to upload:")
        self.snapshotsLabel.setStyleSheet(
            "font-weight:bold; font-size:14px; margin-bottom:10px")
        self.currentSnapshotsLayout.addWidget(self.snapshotsLabel)

        # Subframe that contains the checkbox list
        self.currentSnapshotsInnerFrame = qt.QFrame()
        self.currentSnapshotsInnerLayout = qt.QVBoxLayout()
        self.currentSnapshotsInnerFrame.setLayout(
            self.currentSnapshotsInnerLayout)
        self.currentSnapshotsLayout.addWidget(self.currentSnapshotsInnerFrame)

        self.noItemsLabel = qt.QLabel(
            "(There are not any snapshots at the moment)")
        # Add the label by default. It will be hidden if there is any snapshot
        self.currentSnapshotsInnerLayout.addWidget(self.noItemsLabel)

        self.loadExistingSnapshotsFirstLoad()

        ############### Albums
        # Try to login before getting the albums
        self.login()

        msgBox = None
        if self.isUserLogged:
            # Show message box while loading the data
            msgBox = qt.QMessageBox(qt.QMessageBox.Information, 'Login',
                                    'Connecting with Picasa. Please wait...',
                                    qt.QMessageBox.Cancel)
            msgBox.show()

        try:
            self.albumNameFrame = qt.QFrame()
            self.albumNameLayout = qt.QHBoxLayout()
            self.albumNameFrame.setLayout(self.albumNameLayout)
            self.albumNameFrame.setFrameShape(qt.QFrame.StyledPanel)

            self.albumNameLabel = qt.QLabel("Album name:")
            self.albumNameLabel.setStyleSheet("font-weight:bold;")
            self.albumNamesComboBox = qt.QComboBox()
            self.loadAlbums()
            self.albumNameLayout.addWidget(self.albumNameLabel)
            self.albumNameLayout.addWidget(self.albumNamesComboBox)
            self.mainLayout.addWidget(self.albumNameFrame)

            ############### Tags
            self.tagsFrame = qt.QFrame()
            self.tagsLayout = qt.QGridLayout()
            self.tagsFrame.setLayout(self.tagsLayout)
            self.tagsFrame.setFrameShape(qt.QFrame.StyledPanel)

            self.tagsLabel = qt.QLabel(
                "Tags (select all that apply, you can filter o create new tags):"
            )
            self.tagsLabel.setStyleSheet(
                "font-weight: bold; margin-bottom: 10px; margin-top: 5px")
            self.tagsLayout.addWidget(self.tagsLabel, 0, 0, 1, 3)

            # Add input to filter tags and button to add a new one
            self.tagsFilterLineEdit = qt.QLineEdit()
            self.tagsFilterLineEdit.toolTip = "Type here to filter your tags. If you press the return key all the visible tags will be checked"
            #self.tagsFilterLineEdit.setStyleSheet(style)
            self.tagsLayout.addWidget(self.tagsFilterLineEdit, 1, 0, 1, 2)
            self.newTagButton = qt.QPushButton("New tag")
            #self.newTagButton.setStyleSheet("background-color: #5D74C6; color:white")
            self.newTagButton.setIconSize(qt.QSize(20, 20))
            self.newTagButton.setIcon(
                qt.QIcon(self.CIP_ICON_DIR + "/Plus - 48.png"))
            self.newTagButton.setFixedWidth(75)
            self.newTagButton.toolTip = "Add a new tag (the tag will not be created until you upload any picture with it)"
            self.tagsLayout.addWidget(self.newTagButton, 1, 2)

            self.loadTags()

            ############### Upload snapshots controls
            self.uploadSnapsButtonFrame = qt.QFrame()
            self.uploadSnapsLayout = qt.QHBoxLayout()
            self.uploadSnapsButtonFrame.setLayout(self.uploadSnapsLayout)
            #self(qt.QFrame.HLine)
            self.mainLayout.addWidget(self.uploadSnapsButtonFrame)

            self.uploadSnapshotsButton = qt.QPushButton()
            self.uploadSnapshotsButton.text = "Upload to Picasa!"
            self.uploadSnapshotsButton.toolTip = "Upload selected screenshots to Picassa"
            self.uploadSnapshotsButton.setStyleSheet(
                "background-color: #5D74C6; color: white; font-weight: bold; font-size:14px"
            )
            self.uploadSnapshotsButton.setIcon(
                qt.QIcon(self.CIP_ICON_DIR + "/Upload - 64.png"))
            self.uploadSnapshotsButton.setIconSize(qt.QSize(24, 24))
            self.uploadSnapshotsButton.setFixedSize(170, 35)
            self.uploadSnapsLayout.addWidget(self.uploadSnapshotsButton)

            ############### Progress bar
            self.progressBar = qt.QProgressDialog()
            self.progressBar.setMinimum(0)
            self.progressBar.setMinimumDuration(0)
            self.progressBar.setWindowModality(True)

            # Check for updates in CIP
            #autoUpdate = SlicerUtil.settingGetOrSetDefault("PicasaSnap", "AutoUpdate", 1)
            #uw = AutoUpdateWidget(parent=self.parent, autoUpdate=autoUpdate)
            #uw.addAutoUpdateCheckObserver(self.onAutoUpdateStateChanged)

            #     self.uploadProgressFrame = qt.QFrame()
            #     self.uploadProgressLayout = qt.QVBoxLayout()
            #     self.uploadProgressFrame.setLayout(self.uploadProgressLayout)
            #
            #     # Gif image
            #     self.imUploading = qt.QMovie("%s/loading.gif" % self.CIP_ICON_DIR, qt.QByteArray())
            #     # Label to contain the gif
            #     self.lblImLoading = qt.QLabel()
            #     # Fix the dimensions of the image (by fixing the dimensions of the label that contains it)
            #     self.lblImLoading.setFixedWidth(40)
            #     # Other image parameters
            #     self.imUploading.setCacheMode(qt.QMovie.CacheAll)
            #     self.imUploading.setSpeed(100)
            #     # Assign the label to the image (don't start it yet, it will be started when we are uploading)
            #     self.lblImLoading.setMovie(self.imUploading)
            #     #self.imUploading.start()
            #     self.uploadProgressLayout.addWidget(self.lblImLoading)
            #
            #     # Label that will show the progress
            #     self.lblUploading = qt.QLabel("Uploading %i/%i images...")
            #     self.uploadProgressLayout.addWidget(self.lblUploading)
            #
            # Cancel uploading button
            #     self.btnCancelUpload = qt.QPushButton("Cancel")
            #     self.btnCancelUpload.toolTip = "Cancel the process"
            #     self.btnCancelUpload.setFixedWidth(100)
            #     self.uploadProgressLayout.addWidget(self.btnCancelUpload)
            #     self.mainLayout.addWidget(self.uploadProgressFrame)
            #
            #     # Hide the progress frame
            #     self.uploadProgressFrame.hide()

            ######## Connections
            self.uploadSnapshotsButton.connect(
                'clicked (bool)', self.onUploadSnapshotsButtonClicked)
            self.loginButton.connect('clicked (bool)',
                                     self.onLoginButtonClicked)
            self.logoutButton.connect('clicked (bool)',
                                      self.onLogoutButtonClicked)
            self.loginLineEdit.returnPressed.connect(
                self.onLoginPasswordReturnKeyPressed)
            self.passwordLineEdit.returnPressed.connect(
                self.onLoginPasswordReturnKeyPressed)
            self.albumNamesComboBox.connect("currentIndexChanged (int)",
                                            self.onAlbumsCurrentIndexChanged)
            self.newTagButton.connect('clicked (bool)',
                                      self.onNewTagButtonClicked)
            self.tagsFilterLineEdit.connect('textEdited (QString)',
                                            self.onFilterTagsEdited)
            self.tagsFilterLineEdit.returnPressed.connect(
                self.onFilterTagsReturnKeyPressed)

            # Add vertical spacer
            self.layout.addStretch(1)
        finally:
            # Hide MesageBox if it was visible
            if msgBox:
                msgBox.close()
Пример #24
0
    def onStartStopDicomPeer(self, flag):
        if flag:
            import os
            self.startStopDicomPeerButton.setEnabled(False)
            dicomFilesDirectory = slicer.app.temporaryPath
            configFilePath = dicomFilesDirectory + '/Dcmtk-db/dcmqrscp.cfg'
            processCurrentPath = dicomFilesDirectory + '/Dcmtk-db/'

            msgBox = qt.QMessageBox()
            msgBox.setText(
                'Do you want to choose local DCMTK database folder?')
            msgBox.setStandardButtons(qt.QMessageBox.Yes | qt.QMessageBox.No)
            val = msgBox.exec_()
            if (val == qt.QMessageBox.Yes):
                print 'Yes'
                dicomFilesDirectory = qt.QFileDialog.getExistingDirectory(
                    None, 'Select DCMTK database folder')
                configFilePath = dicomFilesDirectory + '/dcmqrscp.cfg'
                processCurrentPath = dicomFilesDirectory
            else:
                downloads = (
                    ('http://slicer.kitware.com/midas3/download?items=18822',
                     'Dcmtk-db.zip'), )
                print 'Downloading'

                import urllib
                for url, name in downloads:
                    filePath = slicer.app.temporaryPath + '/' + name
                    if not os.path.exists(filePath) or os.stat(
                            filePath).st_size == 0:
                        print 'Requesting download %s from %s...\n' % (name,
                                                                       url)
                        urllib.urlretrieve(url, filePath)
                print 'Finished with download'

                print 'Unzipping'
                qt.QDir().mkpath(dicomFilesDirectory)
                slicer.app.applicationLogic().Unzip(filePath,
                                                    dicomFilesDirectory)

            import subprocess
            dcmqrscpExeOptions = (
                '/bin',
                '/../CTK-build/CMakeExternals/Install/bin',
                '/../DCMTK-install/bin',
                '/../DCMTK-build/bin',
            )

            dcmqrscpExePath = None
            dcmqrscpExeName = '/dcmqrscp'
            if slicer.app.os == 'win':
                dcmqrscpExeName = dcmqrscpExeName + '.exe'
            for path in dcmqrscpExeOptions:
                testPath = slicer.app.slicerHome + path + dcmqrscpExeName
                if os.path.exists(testPath):
                    dcmqrscpExePath = testPath
                    break
            if not dcmqrscpExePath:
                raise (UserWarning("Could not find dcmqrscp executable"))

            args = (dcmqrscpExePath, '-c', configFilePath)
            print 'Start DICOM peer'
            self.popen = subprocess.Popen(args,
                                          stdout=subprocess.PIPE,
                                          cwd=processCurrentPath)
            self.startStopDicomPeerButton.setEnabled(True)
        else:
            print 'Stop DICOM peer'
            self.popen.kill()
Пример #25
0
    def init_fGrowCut(self):

        self.emergencyStopFunc = None
        self.dialogBox = qt.QMessageBox(
        )  #will display messages to draw users attention if he does anything wrong
        self.dialogBox.setWindowTitle("Fast GrowCut Error")
        self.dialogBox.setWindowModality(
            qt.Qt.NonModal
        )  #will allow user to continue interacting with Slicer

        # TODO: check this claim- might be causing leaks
        # set the image, label nodes (this will not change although the user can
        # alter what is bgrnd/frgrnd in editor)
        # Confused about how info propagates UIarray to UIVol, not the other way, NEEDS AUTO TESTS
        self.labelNode = self.editUtil.getLabelVolume(
        )  #labelLogic.GetVolumeNode()
        self.backgroundNode = self.editUtil.getBackgroundVolume(
        )  #backgroundLogic.GetVolumeNode()

        #perform safety check on right images/labels being selected, #set up images
        #if red slice doesnt have a label or image, go no further
        if type(self.backgroundNode) == type(None) or type(
                self.labelNode) == type(None):
            self.dialogBox.setText(
                "Either Image (must be Background Image) or Label not set in slice views."
            )
            self.dialogBox.show()

            if self.emergencyStopFunc:
                self.emergencyStopFunc()
            return

        volumesLogic = slicer.modules.volumes.logic()

        self.labelName = self.labelNode.GetName(
        )  # record name of label so user, cant trick us
        self.imgName = self.backgroundNode.GetName()

        if self.sliceViewMatchEditor(
                self.sliceLogic
        ) == False:  # do nothing, exit function if user has played with images
            if self.emergencyStopFunc:
                self.emergencyStopFunc()
            return

    # fast growcut shortcuts
        resetFGC = qt.QKeySequence(qt.Qt.Key_R)  # reset initialization flag
        runFGC = qt.QKeySequence(qt.Qt.Key_G)  # run fast growcut
        editSeed = qt.QKeySequence(qt.Qt.Key_S)  # edit seed labels

        print " keys for reset init, run GC, edit seed are R,G, S"

        self.qtkeyconnections = []
        self.qtkeydefsGrowcut = [[resetFGC, self.resetFastGrowCutFlag],
                                 [runFGC, self.runFastGrowCut],
                                 [editSeed, self.editGrowCutSeed]]

        for keydef in self.qtkeydefsGrowcut:
            s = qt.QShortcut(keydef[0], slicer.util.mainWindow()
                             )  # connect this qt event to mainWindow focus
            #s.setContext(1)
            s.connect('activated()', keydef[1])
            #s.connect('activatedAmbiguously()', keydef[1])
            self.qtkeyconnections.append(s)

        self.fGCLabelMod_tag = self.sliceLogic.AddObserver(
            "ModifiedEvent", self.FastGrowCutChangeLabelInput
        )  # put test listener on the whole window

        # fast grow cut parameters
        self.bSegmenterInitialized = "no"
        self.bEditGrowCutSeed = True
        self.currentMessage = ""

        seedArray = slicer.util.array(self.labelName)
        self.growCutSeedArray = seedArray.copy()
        self.growCutSegArray = seedArray.copy()
        self.growCutSeedArray[:] = 0
        self.growCutSegArray[:] = 0

        import vtkSlicerFastGrowCutModuleLogicPython

        fastGCMod = vtkSlicerFastGrowCutModuleLogicPython.vtkFastGrowCutSeg()
        fastGCMod.SetSourceVol(self.backgroundNode.GetImageData())
        fastGCMod.SetSeedVol(self.labelNode.GetImageData())
        fastGCMod.Initialization()
        self.fastGCMod = fastGCMod

        self.fastCrowCutCreated = True  #tracks if completed the initializtion (so can do stop correctly) of KSlice
 def ErrorPopup(message):
     messageBox = qt.QMessageBox()
     messageBox.critical(None, '', message)
Пример #27
0
    def init_fCleverSeg(self):
        slicer.util.showStatusMessage("Checking CleverSeg inputs...")

        if not self.areInputsValid():
            logging.warning(self.getInvalidInputsMessage())
            background = self.editUtil.getBackgroundVolume()

            labelInput = self.editUtil.getLabelVolume()
            if not slicer.util.confirmOkCancelDisplay(
                    "Current image type is '{0}' and labelmap type is '{1}'. CleverSeg only works "
                    "reliably with 'short' type.\n\nIf the segmentation result is not satisfactory"
                    ", then cast the image and labelmap to 'short' type (using Cast Scalar Volume "
                    "module) or install CleverSeg extension and use CleverSegEffect editor "
                    "tool.".format(
                        self.editUtil.getBackgroundVolume().GetImageData(
                        ).GetScalarTypeAsString(),
                        self.editUtil.getLabelVolume().GetImageData().
                        GetScalarTypeAsString()),
                    windowTitle='Editor'):
                logging.warning('CleverSeg is cancelled by the user')
                return

        self.emergencyStopFunc = None
        self.dialogBox = qt.QMessageBox(
        )  # will display messages to draw users attention if he does anything wrong
        self.dialogBox.setWindowTitle("CleverSeg Error")
        self.dialogBox.setWindowModality(
            qt.Qt.NonModal
        )  # will allow user to continue interacting with Slicer

        # TODO: check this claim- might be causing leaks
        # set the image, label nodes (this will not change although the user can
        # alter what is bgrnd/frgrnd in editor)
        # Confused about how info propagates UIarray to UIVol, not the other way, NEEDS AUTO TESTS
        self.labelNode = self.editUtil.getLabelVolume(
        )  # labelLogic.GetVolumeNode()
        self.backgroundNode = self.editUtil.getBackgroundVolume(
        )  # backgroundLogic.GetVolumeNode()

        # perform safety check on right images/labels being selected, #set up images
        # if red slice doesnt have a label or image, go no further
        if type(self.backgroundNode) == type(None) or type(
                self.labelNode) == type(None):
            self.dialogBox.setText(
                "Either Image (must be Background Image) or Label not set in slice views."
            )
            self.dialogBox.show()

            if self.emergencyStopFunc:
                self.emergencyStopFunc()
            return

        volumesLogic = slicer.modules.volumes.logic()

        self.labelName = self.labelNode.GetName(
        )  # record name of label so user, cant trick us
        self.imgName = self.backgroundNode.GetName()

        if self.sliceViewMatchEditor(
                self.sliceLogic
        ) == False:  # do nothing, exit function if user has played with images
            if self.emergencyStopFunc:
                self.emergencyStopFunc()
            return

        # CleverSeg shortcuts
        resetCS = qt.QKeySequence(qt.Qt.Key_R)  # reset initialization flag
        runCS = qt.QKeySequence(qt.Qt.Key_C)  # run CleverSeg
        editSeed = qt.QKeySequence(qt.Qt.Key_S)  # edit seed labels

        print " keys for reset init = R, run CS = C, edit seed = S"

        self.qtkeyconnections = []
        self.qtkeydefsCleverSeg = [[resetCS, self.resetCleverSegFlag],
                                   [runCS, self.runCleverSeg],
                                   [editSeed, self.editCleverSegSeed]]

        for keydef in self.qtkeydefsCleverSeg:
            s = qt.QShortcut(keydef[0], slicer.util.mainWindow()
                             )  # connect this qt event to mainWindow focus
            # s.setContext(1)
            s.connect('activated()', keydef[1])
            # s.connect('activatedAmbiguously()', keydef[1])
            self.qtkeyconnections.append(s)

        self.CSLabelMod_tag = self.sliceLogic.AddObserver(
            "ModifiedEvent", self.CleverSegChangeLabelInput
        )  # put test listener on the whole window

        # fast balanced growth parameters
        self.bSegmenterInitialized = "no"
        self.bEditCleverSegSeed = True
        self.currentMessage = ""

        seedArray = slicer.util.array(self.labelName)
        self.CleverSegSeedArray = seedArray.copy()
        self.CleverSegSegArray = seedArray.copy()
        self.CleverSegSeedArray[:] = 0
        self.CleverSegSegArray[:] = 0

        import vtkSlicerCleverSegModuleLogicPython

        cleverSegMod = vtkSlicerCleverSegModuleLogicPython.vtkCleverSeg()

        cleverSegMod.SetSourceVol(self.backgroundNode.GetImageData())
        cleverSegMod.SetSeedVol(self.labelNode.GetImageData())
        cleverSegMod.Initialization()
        self.cleverSegMod = cleverSegMod

        self.cleverSegCreated = True  # tracks if completed the initializtion (so can do stop correctly) of KSlice
    def onEntry(self, comingFrom, transitionType):
        '''
    '''
        super(EMSegmentStartSegmentationStep,
              self).onEntry(comingFrom, transitionType)

        targetNode = self.mrmlManager().GetWorkingDataNode(
        ).GetInputTargetNode()
        alignedAtlasNode = self.mrmlManager().GetWorkingDataNode(
        ).GetAlignedAtlasNode()

        if alignedAtlasNode and not self.mrmlManager(
        ).DoTargetAndAtlasDataTypesMatch(targetNode, alignedAtlasNode):
            # error
            messageBox = qt.QMessageBox.warning(
                self, "Error",
                "Scalar type mismatch for input images; all image scalar types must be the same (including input channels and aligned/resampled/casted atlas images)."
            )
            return

        workingDirectory = self.mrmlManager().GetSaveWorkingDirectory()
        if self.mrmlManager().GetSaveIntermediateResults():
            # if we want to save the results directly, we have to check if the workingDirectory is setup correctly
            if not workingDirectory:
                # workingDirectory was not configured
                messageBox = qt.QMessageBox.warning(
                    self, "Error",
                    "Saving intermediate results is turned on but no intermediate directory is selected."
                )
                return
            elif not os.path.exists(workingDirectory):
                # the workingDirectory path does not exist
                messageBox = qt.QMessageBox.warning(
                    self, "Error",
                    "Saving intermediate results is turned on but the intermediate directory "
                    + workingDirectory + " does not exist!")
                return

        if self.mrmlManager().GetAtlasNumberOfTrainingSamples() <= 0:
            # compute the number of training samples
            self.mrmlManager().ComputeAtlasNumberOfTrainingSamples()

        # create output volumes
        self.logic().CreateOutputVolumeNode()

        # notify user
        # qt.QMessageBox( qt.QMessageBox.NoIcon, "Please wait", "Please wait while the segmentation runs..", qt.QMessageBox.Ignore )
        dialog = qt.QMessageBox()
        dialog.setWindowTitle("Please wait")
        dialog.setText("Please wait while the segmentation runs..")
        dialog.setModal(False)
        dialog.show()

        slicer.app.processEvents()

        # start the segmentation
        returnValue = self.logic().StartSegmentationWithoutPreprocessing(
            slicer.app.applicationLogic())

        dialog.hide()
        slicer.app.processEvents()

        if returnValue != 0:
            # something went wrong!
            # error message!
            messageBox = qt.QMessageBox.warning(
                self, "Error", "Segmentation did not execute correctly!")
            return

        outputNode = self.mrmlManager().GetOutputVolumeNode()

        if not outputNode:
            messageBox = qt.QMessageBox.warning(self, "Error",
                                                "Output node was not found!")
            return

        selectionNode = slicer.app.applicationLogic().GetSelectionNode()
        #selectionNode.SetReferenceActiveVolumeID(bgVolumeID)
        #selectionNode.SetReferenceSecondaryVolumeID( outputNode.GetID() )
        selectionNode.SetReferenceActiveLabelVolumeID(outputNode.GetID())
        slicer.app.applicationLogic().PropagateVolumeSelection()

        # show foreground volume
        numberOfCompositeNodes = slicer.mrmlScene.GetNumberOfNodesByClass(
            'vtkMRMLSliceCompositeNode')
        for n in xrange(numberOfCompositeNodes):
            compositeNode = slicer.mrmlScene.GetNthNodeByClass(
                n, 'vtkMRMLSliceCompositeNode')
            if compositeNode:
                # display a fade of foreground/background
                compositeNode.SetForegroundOpacity(0.5)

        Helper.Debug("All Done!")

        workflow = self.workflow()
        if not workflow:
            Helper.Error("No valid workflow found!")
            return False

        # we go backward to display statistics

        workflow.goBackward()
Пример #29
0
    def checkVisSimTools(self):
        # TODO: optimise this part to download only the missing files
        # Check if elastix exist or download it
        if isfile(self.elastixBinPath.strip()):
            print("elastix binaries are found in " + self.elastixBinPath)
        else:
            print("elastix binaries are missing, trying to download ... ")
            msg = qt.QMessageBox()
            msg.setIcon(qt.QMessageBox.Information)
            msg.setText("elastix binaries are missing!")
            msg.setInformativeText(
                "VisSimTools elastix binaries will be downloaded, this may take some time, please wait!"
            )
            msg.setWindowTitle("VisSimTools")
            msg.exec_()
            try:
                print("Downloading VisSimTools elastix ...")
                #cmd=" wget --no-check-certificate ""https://mtixnat.uni-koblenz.de/owncloud/index.php/s/3bYztVkSrJxdpDz/download"" -O ~/VisSimToolsTmp.zip"
                vissimZip = expanduser("~/VisSimToolsTmp.zip")
                with open(vissimZip, 'wb') as f:
                    uFile = urllib2.urlopen(self.elastixWebLink)
                    chunk = 10024096
                    while 1:
                        data = uFile.read(chunk)
                        f.write(data)
                        if not data:
                            f.close()
                            print "done!"
                            break
                        #endIf
                        print "Reading ...  %s bytes" % len(data)
                    #endWhile
                print("Extracting to user home ")
                zip_ref = zipfile.ZipFile(vissimZip, 'r')
                zip_ref.extractall(expanduser("~/"))
                zip_ref.close()
                #remove the downloaded zip file
                os.remove(vissimZip)
            except Exception as e:
                print(
                    "Error: can not download and extract VisSimTools Elastix ..."
                )
                print(e)
                return -1
            #end try-except
        #endif
        # check if other files exist
        if isfile(self.parsPath.strip()):
            print("Other files are found !")
        else:
            print("Other files are  missing, trying to download ... ")
            msg = qt.QMessageBox()
            msg.setIcon(qt.QMessageBox.Information)
            msg.setText("Other files are missing!")
            msg.setInformativeText(
                "VisSimTools other files will be downloaded, this may take some time, please wait!"
            )
            msg.setWindowTitle("VisSimTools")
            msg.exec_()
            try:
                print("Downloading VisSimTools others ...")
                vissimZip = expanduser("~/VisSimToolsTmp.zip")
                with open(vissimZip, 'wb') as f:
                    uFile = urllib2.urlopen(self.othersWebLink)
                    chunk = 10024096
                    while 1:
                        data = uFile.read(chunk)
                        f.write(data)
                        if not data:
                            f.close()
                            print "done!"
                            break
                        #endIf
                        print "Reading ...  %s bytes" % len(data)
                    #endWhile
                print("Extracting to user home ")
                zip_ref = zipfile.ZipFile(vissimZip, 'r')
                zip_ref.extractall(expanduser("~/"))
                zip_ref.close()
                #remove the downloaded zip file
                os.remove(vissimZip)
                # change permission of bin folder for Linux
                if self.winOS == 0:
                    print("Making binaries executable for Linux ")
                    md = stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH | stat.S_IXGRP | stat.S_IXOTH
                    os.chmod(self.elastixBinPath.strip(), md)
                    os.chmod(self.transformixBinPath.strip(), md)
                    os.chmod(self.elxInvTransBinPath.strip(), md)
                #endif
                msg.setInformativeText(
                    "VisSimTools folder is downloaded and ready to use!")
                msg.exec_()

            except Exception as e:
                print("Error: can not download and extract VisSimTools ...")
                print(e)
                return -1
Пример #30
0
    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(
                        settings.value("Modules/AdditionalPaths"))
                    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",
                                          rawSearchPaths)

                # 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):
                    md = qt.QMessageBox(self.parent.window())
                    md.icon = qt.QMessageBox.Critical
                    md.standardButtons = qt.QMessageBox.Close
                    md.windowTitle = "Module loading failed"

                    if len(failed) > 1:
                        md.text = "The following modules could not be registered:"

                    else:
                        md.text = "The '%s' module could not be registered:" % failed[
                            0].key

                    failedFormat = "<ul><li>%(key)s<br/>(%(path)s)</li></ul>"
                    md.informativeText = "".join(
                        [failedFormat % m.__dict__ for m in failed])

                    md.exec_()
                    return

                # Instantiate and load requested module(s)
                if not factory.loadModules(
                    [module.key for module in modulesToLoad]):
                    md = qt.QMessageBox(self.parent.window())
                    md.icon = qt.QMessageBox.Critical
                    md.standardButtons = qt.QMessageBox.Close
                    md.windowTitle = "Error loading module(s)"
                    md.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.")
                    md.exec_()