def configure(self):
        d = ConfigureDialog(self._state)
        d.setModal(True)
        if d.exec_():
            self.serialize(self._location)
            self._state = d.getState()
            # When a PMR location is given we need to translate that into a
            # local path for passing into the ImageSourceData class
            local_dir = self._state.location()
            pmr_location = self._state.pmrLocation()
            if pmr_location and not len(local_dir):
                # Get login details:
                local_dir = os.path.join(self._location, self._state.identifier())
                if not os.path.exists(local_dir):
                    os.mkdir(local_dir)

                self._state.setLocation(local_dir)
                d.setState(self._state)

            if pmr_location and os.path.exists(local_dir):
                pmr_tool = PMRTool()
                pmr_tool.cloneWorkspace(pmr_location, local_dir)

            self._configured = d.validate()
            if self._configuredObserver is not None:
                self._configuredObserver()
예제 #2
0
 def test_make_session_no_access(self):
     pmr_info = PMR()
     tool = PMRTool(pmr_info)
     session = tool.make_session()
     self.assertFalse(isinstance(session, OAuth1Session))
     # Make sure this really is a requests.Session
     self.assertTrue(isinstance(session, Session))
예제 #3
0
class SearchWidget(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(SearchWidget, self).__init__(parent)
        self._ui = Ui_SearchWidget()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmrTool = PMRTool(pmr_info)
        self._annotationTool = AnnotationTool()

        self._makeConnections()

    def setPMRInfo(self, info):
        self._pmrTool.set_info(info)

    def setUseExternalGit(self, use_external_git):
        self._pmrTool.set_use_external_git(use_external_git)

    def _makeConnections(self):
        self._ui.searchButton.clicked.connect(self._searchClicked)
        self._ui.searchResultsListWidget.itemClicked.connect(self._itemClicked)

    def _itemClicked(self, item):
        data = item.data(QtCore.Qt.UserRole)
        if 'target' in data:
            self._ui.targetEdit.setText(data['target'])

    @handle_runtime_error
    @set_wait_cursor
    def _searchClicked(self):
        # Set pmrlib to go
        self._ui.searchResultsListWidget.clear()

        # fix up known terms to be full blown uri
        search_text = self._ui.searchLineEdit.text()
        search_terms = search_text.split()
        for term in search_terms:
            rdfterm = self._annotationTool.rdfFormOfTerm(term)
            if rdfterm:
                search_text = search_text + ' ' + rdfterm[1:-1]

        try:
            results = self._pmrTool.search(search_text)

            for r in results:
                if 'title' in r and r['title']:
                    item = QtWidgets.QListWidgetItem(r['title'], self._ui.searchResultsListWidget)
                else:
                    item = QtWidgets.QListWidgetItem(r['target'], self._ui.searchResultsListWidget)
                item.setData(QtCore.Qt.UserRole, r)
        except PMRToolError as e:
            message = convertExceptionToMessage(e)
            logger.warning('PMR Tool exception raised')
            logger.warning('Reason: {0}'.format(message))

    def getSelectedWorkspace(self):
        items = self._ui.searchResultsListWidget.selectedItems()
        for item in items:
            return item.data(QtCore.Qt.UserRole)
예제 #4
0
    def _updateFromPMR(self):
        m = self._main_window.model().workflowManager()
        om = self._main_window.model().optionsManager()
        pmr_info = PMR()
        pmr_tool = PMRTool(pmr_info, use_external_git=om.getOption(USE_EXTERNAL_GIT))

        pmr_tool.pullFromRemote(m.location())
    def configure(self):
        d = ConfigureDialog(self._state, QtGui.QApplication.activeWindow().currentWidget())
        d.setWorkflowLocation(self._location)
        d.setModal(True)
        if d.exec_():
            self._state = d.getState()
            # When a PMR location is given we need to translate that into a
            # local path for passing into the ImageSourceData class
            local_dir = self._state.location()
            pmr_location = self._state.pmrLocation()
            if pmr_location and not len(local_dir):
                # Get login details:
                local_dir = self._location
                if not os.path.exists(local_dir):
                    os.mkdir(local_dir)

                self._state.setLocation(local_dir)
                d.setState(self._state)

            if pmr_location and os.path.exists(local_dir):
                pmr_info = PMR()
                pmr_tool = PMRTool(pmr_info)
                pmr_tool.cloneWorkspace(pmr_location, local_dir)

            self._configured = d.validate()
            if self._configuredObserver is not None:
                self._configuredObserver()
 def test_make_session_with_access(self):
     tool = PMRTool()
     info = PMRInfo()
     info.update_token('test', 'token')
     session = tool.make_session()
     self.assertTrue(isinstance(session, OAuth1Session))
     info.update_token('', '')
    def __init__(self, use_external_git, parent=None):
        super(PMRWorkflowWidget, self).__init__(parent)
        self._ui = Ui_PMRWorkflowWidget()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmrTool = PMRTool(pmr_info, use_external_git)

        self._termLookUpLimit = 32

        self._timer = QtCore.QTimer()
        self._timer.setInterval(500)

        self._busy_waiting = False
        self._ontological_search = False

        word_list = ['pending ...']
        self._list_model = OWLTermsListModel(word_list)

#         self._client = Client(site=pmr_target, use_default_headers=True)

        self._makeConnections()

        self._ui.comboBoxSearch.clear()
        self._ui.comboBoxSearch.addItems(search_domains)

        self._updateUi()
예제 #8
0
 def test_make_session_with_access(self):
     pmr_info = PMR()
     tool = PMRTool(pmr_info)
     info = PMR()
     info.update_token('test', 'token')
     session = tool.make_session()
     self.assertTrue(isinstance(session, OAuth1Session))
     info.update_token('', '')
예제 #9
0
    def _cloneFromPMR(self, workspace_url, workflowDir):
        om = self._main_window.model().optionsManager()
        pmr_info = PMR()
        pmr_tool = PMRTool(pmr_info, use_external_git=om.getOption(USE_EXTERNAL_GIT))

        pmr_tool.cloneWorkspace(
            remote_workspace_url=workspace_url,
            local_workspace_dir=workflowDir,
        )
예제 #10
0
    def commitChanges(self, workflowDir):
        om = self._main_window.model().optionsManager()
        pmr_info = PMR()
        pmr_tool = PMRTool(pmr_info, use_external_git=om.getOption(USE_EXTERNAL_GIT))
        if not pmr_tool.hasDVCS(workflowDir):
            # nothing to commit.
            return True

        return self._commitChanges(workflowDir, 'Workflow saved.')
예제 #11
0
    def __init__(self, parent=None):
        super(SearchWidget, self).__init__(parent)
        self._ui = Ui_SearchWidget()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmrTool = PMRTool(pmr_info)
        self._annotationTool = AnnotationTool()

        self._makeConnections()
    def _setIndexerFile(self, workflow_dir):
        pmr_tool = PMRTool()

        if not pmr_tool.hasDVCS(workflow_dir):
            return
        try:
            pmr_tool.addFileToIndexer(workflow_dir, DEFAULT_WORKFLOW_ANNOTATION_FILENAME)
#             pmr_tool.commitFiles(local_workspace_dir, message, files)
        except ClientRuntimeError:
            # handler will deal with this.
            raise
    def __init__(self, external_git, parent=None):
        super(PMRRegisterDialog, self).__init__(parent)
        self._ui = Ui_RegisterDialog()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmr_tool = PMRTool(pmr_info, external_git)

        self._makeConnections()

        self._updateUi()
    def make_tool(self, endpoints=None):
        if endpoints is None:
            endpoints = self.endpoints

        def make_session(pmr_info=None):
            session = TestSession()
            for url, adapter in endpoints:
                session.mount(url, adapter)
            return session
        tool = PMRTool()
        tool.make_session = make_session
        return tool
예제 #15
0
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self._ui = Ui_PMRSearchDialog()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmrTool = PMRTool(pmr_info)
        self._annotationTool = AnnotationTool()

        self._makeConnections()

        self._updateUi()
예제 #16
0
    def __init__(self, parent=None):
        super(SettingsWidget, self).__init__(parent)
        self._ui = Ui_SettingsWidget()
        self._ui.setupUi(self)

        self._pmr_tool = PMRTool()
        self._model = QtGui.QStandardItemModel()
        self._updateModel()

        self._ui.hostListView.setModel(self._model)

        self._updateUi()
        self._makeConnections()
예제 #17
0
    def _setIndexerFile(self, workflow_dir):
        om = self._main_window.model().optionsManager()
        pmr_info = PMR()
        pmr_tool = PMRTool(pmr_info, use_external_git=om.getOption(USE_EXTERNAL_GIT))

        if not pmr_tool.hasDVCS(workflow_dir):
            return
        try:
            pmr_tool.addFileToIndexer(workflow_dir, DEFAULT_WORKFLOW_ANNOTATION_FILENAME)
#             pmr_tool.commitFiles(local_workspace_dir, message, files)
        except ClientRuntimeError:
            # handler will deal with this.
            raise
예제 #18
0
    def __init__(self, use_external_git, parent=None):
        super(PMRDialog, self).__init__(parent)
        self._ui = Ui_PMRDialog()
        self._ui.setupUi(self)
        self._ui.searchWidget.setUseExternalGit(use_external_git)
        self._ui.settingsWidget.setUseExternalGit(use_external_git)
        
        pmr_info = PMR()
        self._pmr_tool = PMRTool(pmr_info, use_external_git)

        self._makeConnections()

        self._updateUi()
예제 #19
0
    def make_tool(self, endpoints=None):
        if endpoints is None:
            endpoints = self.endpoints

        def make_session(pmr_info=None):
            session = TestSession()
            for url, adapter in endpoints:
                session.mount(url, adapter)
            return session

        pmr_info = PMR()
        tool = PMRTool(pmr_info)
        tool.make_session = make_session
        return tool
    def test_hasAccess(self):
        # update tokens using another instance
        info = PMRInfo()
        t = PMRTool()

        # Fresh token should have no access
        self.assertFalse(t.hasAccess())

        info.update_token('test', 'token')
        # Now it's true
        self.assertTrue(t.hasAccess())

        # revoke access again.
        info.update_token('', '')
        # Now it's false again.
        self.assertFalse(t.hasAccess())
    def __init__(self, parent=None):
        '''
        Constructor
        '''
        super(PMRWorkflowWidget, self).__init__(parent)
        self._ui = Ui_PMRWorkflowWidget()
        self._ui.setupUi(self)

        self._pmrTool = PMRTool()

        self._termLookUpLimit = 32

        self._timer = QtCore.QTimer()
        self._timer.setInterval(500)

        self._busy_waiting = False
        self._ontological_search = False

        word_list = ['pending ...']
        self._list_model = OWLTermsListModel(word_list)

#         self._client = Client(site=pmr_target, use_default_headers=True)

        self._makeConnections()

        self._ui.comboBoxSearch.clear()
        self._ui.comboBoxSearch.addItems(search_domains)

        self._updateUi()
예제 #22
0
    def test_hasAccess(self):
        # update tokens using another instance
        info = PMR()
        t = PMRTool(info)

        # Fresh token should have no access
        self.assertFalse(t.hasAccess())

        info.update_token('test', 'token')
        # Now it's true
        self.assertTrue(t.hasAccess())

        # revoke access again.
        info.update_token('', '')
        # Now it's false again.
        self.assertFalse(t.hasAccess())
    def _importFromPMR(self, workspace_url, workflowDir):
        pmr_tool = PMRTool()

        pmr_tool.cloneWorkspace(
            remote_workspace_url=workspace_url,
            local_workspace_dir=workflowDir,
        )

        logger.info('Analyze first before attempting load ...')
        try:
            m = self._mainWindow.model().workflowManager()
            m.load(workflowDir)
            m.setPreviousLocation(workflowDir)
            self._graphicsScene.updateModel()
            self._updateUi()
        except:
            self.close()
            raise
    def commitChanges(self, workflowDir):
        pmr_tool = PMRTool()
        if not pmr_tool.hasDVCS(workflowDir):
            # nothing to commit.
            return True

        dlg = PMRHgCommitDialog(self)
        dlg.setModal(True)
        if dlg.exec_() == QtGui.QDialog.Rejected:
            return False

        action = dlg.action()
        if action == QtGui.QDialogButtonBox.Ok:
            return True
        elif action == QtGui.QDialogButtonBox.Save:
            return self._commitChanges(workflowDir, dlg.comment(), commit_local=True)

        return self._commitChanges(workflowDir, dlg.comment())
예제 #25
0
class PMRDialog(QtGui.QDialog):
    
    def __init__(self, use_external_git, parent=None):
        super(PMRDialog, self).__init__(parent)
        self._ui = Ui_PMRDialog()
        self._ui.setupUi(self)
        self._ui.searchWidget.setUseExternalGit(use_external_git)
        self._ui.settingsWidget.setUseExternalGit(use_external_git)
        
        pmr_info = PMR()
        self._pmr_tool = PMRTool(pmr_info, use_external_git)

        self._makeConnections()

        self._updateUi()

    def accept(self, *args, **kwargs):
        self._ui.settingsWidget.transferModel()
        return QtGui.QDialog.accept(self, *args, **kwargs)
    
    def _updateUi(self):
        pmr_info = PMR()
        self._pmr_tool.set_info(pmr_info)
        if self._pmr_tool.isActive():
            if self._pmr_tool.hasAccess():
                self._ui.loginStackedWidget.setCurrentIndex(1)
            else:
                self._ui.loginStackedWidget.setCurrentIndex(0)
        else:
            self._ui.loginStackedWidget.setCurrentIndex(2)

    def _makeConnections(self):
        self._ui.registerLabel.linkActivated.connect(self.register)
        self._ui.deregisterLabel.linkActivated.connect(self.deregister)
        self._ui.settingsWidget.hostChanged.connect(self._hostChanged)

    def _hostChanged(self, index):
        self._updateUi()
        
    def register(self, link):
        if link != 'mapclient.register':
            return

        dlg = AuthoriseApplicationDialog(self)
        dlg.setModal(True)
        dlg.exec_()

        self._updateUi()

    def deregister(self):
        pmr_info = PMR()
        self._pmr_tool.set_info(pmr_info)
        self._pmr_tool.deregister()
        self._updateUi()
    def _commitChanges(self, workflowDir, comment, commit_local=False):
        committed_changes = False
        pmr_tool = PMRTool()
        try:
            pmr_tool.commitFiles(workflowDir, comment,
                [workflowDir + '/%s' % (DEFAULT_WORKFLOW_PROJECT_FILENAME),
                 workflowDir + '/%s' % (DEFAULT_WORKFLOW_ANNOTATION_FILENAME)])  # XXX make/use file tracker
            if not commit_local:
                pmr_tool.pushToRemote(workflowDir)
            committed_changes = True
        except ClientRuntimeError:
            # handler will deal with this.
            raise
        except Exception:
            logger.exception('Error')
            raise ClientRuntimeError(
                'Error Saving', 'The commit to PMR did not succeed')

        return committed_changes
예제 #27
0
    def _createNewWorkflow(self, workflow_dir, pmr):
        m = self._main_window.model().workflowManager()
        om = self._main_window.model().optionsManager()
        m.new(workflow_dir)
        m.setPreviousLocation(workflow_dir)

        if pmr:
            pmr_info = PMR()
            pmr_tool = PMRTool(pmr_info, use_external_git=om.getOption(USE_EXTERNAL_GIT))
            if pmr_tool.hasAccess():
                dir_name = os.path.basename(workflow_dir)
                try:
                    repourl = pmr_tool.addWorkspace('Workflow: ' + dir_name, None)
                    pmr_tool.linkWorkspaceDirToUrl(workflow_dir, repourl)
                except HTTPError as e:
                    logger.exception('Error creating new')
                    self.close()
                    raise ClientRuntimeError(
                        'Error Creating New', e)
            else:
                raise ClientRuntimeError('Error Creating New', "Client doesn't have access to PMR")

        self._undoStack.clear()
        self._ui.graphicsView.setLocation(workflow_dir)
        self._graphicsScene.updateModel()
        self._update_ui()
예제 #28
0
    def _commitChanges(self, workflowDir, comment, commit_local=False):
        committed_changes = False
        om = self._main_window.model().optionsManager()
        pmr_info = PMR()
        pmr_tool = PMRTool(pmr_info, use_external_git=om.getOption(USE_EXTERNAL_GIT))
        try:
            workflow_files = [workflowDir + '/%s' % (DEFAULT_WORKFLOW_PROJECT_FILENAME),
                              workflowDir + '/%s' % (DEFAULT_WORKFLOW_ANNOTATION_FILENAME)]
            for f in os.listdir(workflowDir):
                if f.endswith(".conf"):
                    full_filename = os.path.join(workflowDir, f)
                    if full_filename not in workflow_files:
                        workflow_files.append(full_filename)

            pmr_tool.commitFiles(workflowDir, comment, workflow_files)
#                 [workflowDir + '/%s' % (DEFAULT_WORKFLOW_PROJECT_FILENAME),
#                  workflowDir + '/%s' % (DEFAULT_WORKFLOW_ANNOTATION_FILENAME)])  # XXX make/use file tracker
            if not commit_local:
                pmr_tool.pushToRemote(workflowDir)
            committed_changes = True
        except ClientRuntimeError:
            # handler will deal with this.
            raise
        except Exception:
            logger.exception('Error')
            raise ClientRuntimeError(
                'Error Saving', 'The commit to PMR did not succeed')

        return committed_changes
class PMRRegisterDialog(QtGui.QDialog):
    def __init__(self, external_git, parent=None):
        super(PMRRegisterDialog, self).__init__(parent)
        self._ui = Ui_RegisterDialog()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmr_tool = PMRTool(pmr_info, external_git)

        self._makeConnections()

        self._updateUi()

    def _updateUi(self):
        pmr_info = PMR()
        self._pmr_tool.set_info(pmr_info)
        if self._pmr_tool.isActive():
            self._ui.pushButtonRegister.setEnabled(True)
            if self._pmr_tool.hasAccess():
                self._ui.stackedWidgetRegister.setCurrentIndex(1)
            else:
                self._ui.stackedWidgetRegister.setCurrentIndex(0)
        else:
            self._ui.pushButtonRegister.setEnabled(False)
            self._ui.stackedWidgetRegister.setCurrentIndex(0)

    def _makeConnections(self):
        self._ui.pushButtonRegister.clicked.connect(self._register)
        self._ui.pushButtonDeregister.clicked.connect(self._deregister)
        self._ui.settingsWidget.hostChanged.connect(self._hostChanged)

    def _register(self):
        dlg = AuthoriseApplicationDialog(self)
        dlg.setModal(True)
        dlg.exec_()

        self._updateUi()

    def _deregister(self):
        pmr_info = PMR()
        self._pmr_tool.set_info(pmr_info)
        self._pmr_tool.deregister()
        self._updateUi()

    def _hostChanged(self, index):
        self._updateUi()

    def accept(self, *args, **kwargs):
        self._ui.settingsWidget.transferModel()
        return QtGui.QDialog.accept(self, *args, **kwargs)
예제 #30
0
    def __init__(self, parent=None):
        """
        Constructor
        """
        QtGui.QDialog.__init__(self, parent)
        self._ui = Ui_PMRSearchDialog()
        self._ui.setupUi(self)

        self._pmrTool = PMRTool()
        self._annotationTool = AnnotationTool()

        self._makeConnections()

        self._updateUi()
    def _createNewWorkflow(self, workflowDir, pmr):
        m = self._mainWindow.model().workflowManager()
        m.new(workflowDir)
        m.setPreviousLocation(workflowDir)

        if pmr:
            pmr_tool = PMRTool()
            if pmr_tool.hasAccess():
                dir_name = os.path.basename(workflowDir)
                try:
                    repourl = pmr_tool.addWorkspace('Workflow: ' + dir_name, None)
                    pmr_tool.linkWorkspaceDirToUrl(workflowDir, repourl)
                except HTTPError as e:
                    logger.exception('Error creating new')
                    self.close()
                    raise ClientRuntimeError(
                        'Error Creating New', e.message)
            else:
                raise ClientRuntimeError('Error Creating New', "Client doesn't have access to PMR")

        self._undoStack.clear()
        self._ui.graphicsView.setLocation(workflowDir)
        self._graphicsScene.updateModel()
        self._updateUi()
예제 #32
0
class PMRSearchDialog(QtGui.QDialog):
    """
    Dialog for managing interaction with PMR.
    """
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self._ui = Ui_PMRSearchDialog()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmrTool = PMRTool(pmr_info)
        self._annotationTool = AnnotationTool()

        self._makeConnections()

        self._updateUi()

    def _updateUi(self):
        if self._pmrTool.hasAccess():
            self._ui.loginStackedWidget.setCurrentIndex(1)
        else:
            self._ui.loginStackedWidget.setCurrentIndex(0)

    def _makeConnections(self):
        self._ui.searchButton.clicked.connect(self._searchClicked)
        self._ui.registerLabel.linkActivated.connect(self.register)
        self._ui.deregisterLabel.linkActivated.connect(self.deregister)

    @handle_runtime_error
    @set_wait_cursor
    def _searchClicked(self):
        # Set pmrlib to go
        self._ui.searchResultsListWidget.clear()

        # fix up known terms to be full blown uri
        search_text = self._ui.searchLineEdit.text()
        search_terms = search_text.split()
        for term in search_terms:
            rdfterm = self._annotationTool.rdfFormOfTerm(term)
            if rdfterm:
                search_text = search_text + ' ' + rdfterm[1:-1]

        try:
            results = self._pmrTool.search(search_text)

            for r in results:
                if 'title' in r and r['title']:
                    item = QtGui.QListWidgetItem(
                        r['title'], self._ui.searchResultsListWidget)
                else:
                    item = QtGui.QListWidgetItem(
                        r['target'], self._ui.searchResultsListWidget)
                item.setData(QtCore.Qt.UserRole, r)
        except PMRToolError as e:
            message = convertExceptionToMessage(e)
            logger.warn('PMR Tool exception raised')
            logger.warn('Reason: {0}'.format(message))

    def getSelectedWorkspace(self):
        items = self._ui.searchResultsListWidget.selectedItems()
        for item in items:
            return item.data(QtCore.Qt.UserRole)

    def register(self, link):
        if link != 'mapclient.register':
            return

        dlg = AuthoriseApplicationDialog(self)
        dlg.setModal(True)
        dlg.exec_()

        self._updateUi()

    def deregister(self):
        self._pmrTool.deregister()
        self._updateUi()
class PMRWorkflowWidget(QtGui.QWidget):
    """
    A Widget for importing and exporting to and from PMR.
    """

    def __init__(self, use_external_git, parent=None):
        super(PMRWorkflowWidget, self).__init__(parent)
        self._ui = Ui_PMRWorkflowWidget()
        self._ui.setupUi(self)

        pmr_info = PMR()
        self._pmrTool = PMRTool(pmr_info, use_external_git)

        self._termLookUpLimit = 32

        self._timer = QtCore.QTimer()
        self._timer.setInterval(500)

        self._busy_waiting = False
        self._ontological_search = False

        word_list = ['pending ...']
        self._list_model = OWLTermsListModel(word_list)

#         self._client = Client(site=pmr_target, use_default_headers=True)

        self._makeConnections()

        self._ui.comboBoxSearch.clear()
        self._ui.comboBoxSearch.addItems(search_domains)

        self._updateUi()

    def _updateUi(self):
        if self._pmrTool.hasAccess():
            self._ui.labelLink.setText('<a href="mapclient.deregister">deregister</a>')
        else:
            self._ui.labelLink.setText('<a href="mapclient.register">register</a>')

    def _makeConnections(self):
        self._ui.pushButtonSearch.clicked.connect(self._searchClicked)
        self._ui.pushButtonImport.clicked.connect(self._importClicked)
        self._ui.pushButtonExport.clicked.connect(self._exportClicked)
        self._ui.labelLink.linkActivated.connect(self._linkActivated)
        self._ui.listWidgetResults.itemClicked.connect(self._searchResultClicked)
        self._ui.lineEditSearch.textEdited.connect(self._searchTextEdited)
        self._timer.timeout.connect(self._queryRepository)
        self._ui.comboBoxSearch.currentIndexChanged.connect(self._searchTypeChanged)

    def _initialiseCompleter(self):
        completer = QtGui.QCompleter(self._ui.lineEditSearch)
        completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setModel(self._list_model)
        completer.setCompletionColumn(0)
        completer.setCompletionRole(QtCore.Qt.DisplayRole)

        return completer

    def _searchTypeChanged(self, index):
        text = self._ui.comboBoxSearch.currentText()
        if text == ontological_search_string:
            self._ontological_search = True
            completer = self._initialiseCompleter()
            self._ui.lineEditSearch.setCompleter(completer)
        else:
            self._ontological_search = False
            self._ui.lineEditSearch.setCompleter(None)

    def _searchTextEdited(self, new_text):
        if self._ontological_search and len(new_text) and not self._busy_waiting:
            if self._timer.isActive():
                QtGui.QApplication.restoreOverrideCursor()
            QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
            self._timer.start()

    def _queryRepository(self):
        self._timer.stop()
        self._busy_waiting = True
        search_text = self._ui.lineEditSearch.text()
        pmr_target = general.PMR().host()
        target = pmr_target + '/pmr2_ricordo/owlterms' + '/%s/%d' % (search_text, self._termLookUpLimit)
        client = Client(site=pmr_target, use_default_headers=True)
        state = client(target=target)  # , data=json.dumps({'actions': {'search': 1}, 'fields': {'simple_query': 'femur'}}))  # , endpoint='ricordo', data='femur')
        response = state.value()
        descriptions = ['%s [%s]' % (line[0], line[1].split('#')[-1]) for line in response['results']]
        self._list_model.removeRows(0, self._list_model.rowCount())
        self._list_model.insertRows(0, len(descriptions), descriptions)
        self._busy_waiting = False

    def _searchResultClicked(self, item):
        r = item.data(QtCore.Qt.UserRole)
        if 'source' in r:
            self._ui.lineEditWorkspace.setText(r['source'])
        elif 'href' in r:
            self._ui.lineEditWorkspace.setText(r['href'])

    def _linkActivated(self, link):
        if link == 'mapclient.register':
            dlg = AuthoriseApplicationDialog(self)
            dlg.setModal(True)
            dlg.exec_()
            self._updateUi()
        elif link == 'mapclient.deregister':
            self._pmrTool.deregister()
            self._updateUi()

    def _searchClicked(self):
        self._doSearch(self._ui.comboBoxSearch.currentText())

    def _importClicked(self):
        pass

    def _exportClicked(self):
        pass

    def setSearchDomain(self, domain=['all', ]):
        self._domain = []
        if type(domain) is not list:
            domain = [domain]

        if len(domain) and domain[0] == 'all':
            domain = search_domains

        for subdomain in domain:
            if subdomain in search_domains:
                self._domain.append(subdomain)

        if len(self._domain):
            self._ui.comboBoxSearch.clear()
            for subdomain in self._domain:
                self._ui.comboBoxSearch.addItem(subdomain)

    def setExport(self, visible=True):
        if visible:
            self._ui.pushButtonExport.show()
        else:
            self._ui.pushButtonExport.hide()

    def setImport(self, visible=True):
        if visible:
            self._ui.pushButtonImport.show()
        else:
            self._ui.pushButtonImport.hide()

    def workspaceUrl(self):
        return self._ui.lineEditWorkspace.text()

    def setWorkspaceUrl(self, url):
        self._ui.lineEditWorkspace.setText(url)

    @handle_runtime_error
    @set_wait_cursor
    def _doSearch(self, search_type):
        # Set pmrlib to go
        self._ui.listWidgetResults.clear()

        # fix up known terms to be full blown uri
        search_text = self._ui.lineEditSearch.text()
        if True:
            search_text = self._ui.lineEditSearch.text()
            label_re = re.compile('\[([\w_\d]+)\]')
            re_result = label_re.search(search_text)
            if re_result:
                search_text = re_result.group(1)
#         search_terms = search_text.split()
#         for term in search_terms:
#             rdfterm = self._annotationTool.rdfFormOfTerm(term)
#             if rdfterm:
#                 search_text = search_text + ' ' + rdfterm[1:-1]
        results = self._pmrTool.search(search_text, search_type)

        if search_type == workflow_search_string:
            results_list = results['results']
            for r in results_list:
                item = QtGui.QListWidgetItem(r['obj']['title'], self._ui.listWidgetResults)
                item.setData(QtCore.Qt.UserRole, r)
        elif search_type == ontological_search_string:
            if type(results) is dict:
                return

            for r in results:
                label = r['label']
                for sr in r['items']:
                    item = QtGui.QListWidgetItem(sr['title'] + ' [%s, %s]' % (sr['value'], label), self._ui.listWidgetResults)
                    tool_tip = 'Workspace title: %s, Ontological term: %s, Target: %s' % (sr['title'], label, sr['href'])
                    item.setToolTip(tool_tip)
                    item.setData(QtCore.Qt.UserRole, sr)

        else:
            for r in results:
                if 'title' in r and r['title']:
                    item = QtGui.QListWidgetItem(r['title'], self._ui.listWidgetResults)
                else:
                    item = QtGui.QListWidgetItem(r['target'], self._ui.listWidgetResults)
                item.setData(QtCore.Qt.UserRole, r)
예제 #34
0
class SettingsWidget(QtGui.QWidget):

    hostChanged = QtCore.Signal(int)

    def __init__(self, parent=None):
        super(SettingsWidget, self).__init__(parent)
        self._ui = Ui_SettingsWidget()
        self._ui.setupUi(self)

        self._pmr_tool = PMRTool()
        self._model = QtGui.QStandardItemModel()
        self._updateModel()

        self._ui.hostListView.setModel(self._model)

        self._updateUi()
        self._makeConnections()

    def _makeConnections(self):
        self._ui.addPushButton.clicked.connect(self._addClicked)
        self._ui.removePushButton.clicked.connect(self._removeClicked)
        self._ui.hostListView.clicked.connect(
            self._updateUi
        )  # We are making clicking to be synonymous with selecting, OK I think for single selection mode
        self._ui.hostListView.addAction(self._ui.actionAddHost)
        self._ui.actionAddHost.triggered.connect(self._addClicked)
        self._model.itemChanged.connect(self._hostChanged)

    def _updateUi(self):
        self._ui.removePushButton.setEnabled(
            len(self._ui.hostListView.selectedIndexes()))

    def _updateModel(self):
        pmr_info = PMR()
        for instance in pmr_info.hosts():
            self.addHost(instance, instance == pmr_info.activeHost())

    def setUseExternalGit(self, use_external_git):
        self._pmr_tool.set_use_external_git(use_external_git)

    def transferModel(self):
        """
        Transfer the current status of the model into the PMR
        information object.
        """
        pmr_info = PMR()
        hosts = pmr_info.hosts()
        host_names_remove = [name for name in hosts]
        host_names_new = []
        active_host = None

        index = 0
        current_item = self._model.item(index)
        while current_item:
            current_host = current_item.text()
            if current_host in host_names_remove:
                host_names_remove.remove(current_host)
            else:
                host_names_new.append(current_host)

            if current_item.checkState() == QtCore.Qt.Checked:
                active_host = current_host

            index += 1
            current_item = self._model.item(index)

        pmr_info.setActiveHost(active_host)
        for host in host_names_remove:
            pmr_info.removeHost(host)
        for host in host_names_new:
            pmr_info.addHost(host)

    def _addClicked(self):
        dlg = AddHostDialog(self)

        dlg.setModal(True)
        if dlg.exec_():
            self.addHost(dlg.getHost())

    def _removeClicked(self):
        indexes = self._ui.hostListView.selectedIndexes()
        rm_index = indexes.pop()
        item = self._model.itemFromIndex(rm_index)
        pmr_info = PMR()
        pmr_info.removeHost(item.text())
        self._model.removeRow(rm_index.row())
#         item = self._model.takeItem(rm_index.row())

    def _whichHostChecked(self):
        index = 0
        current_item = self._model.item(index)
        while current_item:
            if current_item.checkState():
                return index
            index += 1
            current_item = self._model.item(index)

        return -1

    def _hostChanged(self, item):
        pmr_info = PMR()
        if not item.checkState():
            pmr_info.setActiveHost(None)
            self.hostChanged.emit(item.row())
            return

        index = 0
        current_item = self._model.item(index)
        self.blockSignals(True)
        while current_item:
            if current_item.checkState() and (current_item.row() !=
                                              item.row()):
                current_item.setCheckState(QtCore.Qt.Unchecked)
            index += 1
            current_item = self._model.item(index)

        self.blockSignals(False)
        pmr_info.setActiveHost(item.text())
        self.hostChanged.emit(item.row())

    @handle_runtime_error
    @set_wait_cursor
    def addHost(self, host, active=False):
        try:
            # Look for duplicates
            host_item = QtGui.QStandardItem(host)
            same_items = self._model.findItems(host)
            if len(same_items):
                raise Exception('Host "{0}" already exists'.format(host))

            if self._pmr_tool.isValidHost(host):
                host_item.setCheckable(True)
                host_item.setCheckState(
                    QtCore.Qt.Checked if active else QtCore.Qt.Unchecked)
                self._model.appendRow(host_item)
        except Exception as e:
            raise ClientRuntimeError('Error Adding Host', str(e))
class PMRWorkflowWidget(QtGui.QWidget):
    '''
    A Widget for importing and exporting to and from PMR.
    '''

    def __init__(self, parent=None):
        '''
        Constructor
        '''
        super(PMRWorkflowWidget, self).__init__(parent)
        self._ui = Ui_PMRWorkflowWidget()
        self._ui.setupUi(self)

        self._pmrTool = PMRTool()

        self._termLookUpLimit = 32

        self._timer = QtCore.QTimer()
        self._timer.setInterval(500)

        self._busy_waiting = False
        self._ontological_search = False

        word_list = ['pending ...']
        self._list_model = OWLTermsListModel(word_list)

#         self._client = Client(site=pmr_target, use_default_headers=True)

        self._makeConnections()

        self._ui.comboBoxSearch.clear()
        self._ui.comboBoxSearch.addItems(search_domains)

        self._updateUi()

    def _updateUi(self):
        if self._pmrTool.hasAccess():
            self._ui.labelLink.setText('<a href="mapclient.deregister">deregister</a>')
        else:
            self._ui.labelLink.setText('<a href="mapclient.register">register</a>')

    def _makeConnections(self):
        self._ui.pushButtonSearch.clicked.connect(self._searchClicked)
        self._ui.pushButtonImport.clicked.connect(self._importClicked)
        self._ui.pushButtonExport.clicked.connect(self._exportClicked)
        self._ui.labelLink.linkActivated.connect(self._linkActivated)
        self._ui.listWidgetResults.itemClicked.connect(self._searchResultClicked)
        self._ui.lineEditSearch.textEdited.connect(self._searchTextEdited)
        self._timer.timeout.connect(self._queryRepository)
        self._ui.comboBoxSearch.currentIndexChanged.connect(self._searchTypeChanged)

    def _initialiseCompleter(self):
        completer = QtGui.QCompleter(self._ui.lineEditSearch)
        completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setModel(self._list_model)
        completer.setCompletionColumn(0)
        completer.setCompletionRole(QtCore.Qt.DisplayRole)

        return completer

    def _searchTypeChanged(self, index):
        text = self._ui.comboBoxSearch.currentText()
        if text == ontological_search_string:
            self._ontological_search = True
            completer = self._initialiseCompleter()
            self._ui.lineEditSearch.setCompleter(completer)
        else:
            self._ontological_search = False
            self._ui.lineEditSearch.setCompleter(None)

    def _searchTextEdited(self, new_text):
        if self._ontological_search and len(new_text) and not self._busy_waiting:
            if self._timer.isActive():
                QtGui.QApplication.restoreOverrideCursor()
            QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
            self._timer.start()

    def _queryRepository(self):
        self._timer.stop()
        self._busy_waiting = True
        search_text = self._ui.lineEditSearch.text()
        pmr_target = info.PMRInfo().ipaddress
        target = pmr_target + '/pmr2_ricordo/owlterms' + '/%s/%d' % (search_text, self._termLookUpLimit)
        client = Client(site=pmr_target, use_default_headers=True)
        state = client(target=target)  # , data=json.dumps({'actions': {'search': 1}, 'fields': {'simple_query': 'femur'}}))  # , endpoint='ricordo', data='femur')
        response = state.value()
        descriptions = ['%s [%s]' % (line[0], line[1].split('#')[-1]) for line in response['results']]
        self._list_model.removeRows(0, self._list_model.rowCount())
        self._list_model.insertRows(0, len(descriptions), descriptions)
        self._busy_waiting = False
        QtGui.QApplication.restoreOverrideCursor()

    def _searchResultClicked(self, item):
        r = item.data(QtCore.Qt.UserRole)
        if 'source' in r:
            self._ui.lineEditWorkspace.setText(r['source'])
        elif 'href' in r:
            self._ui.lineEditWorkspace.setText(r['href'])

    def _linkActivated(self, link):
        if link == 'mapclient.register':
            dlg = AuthoriseApplicationDialog(self)
            dlg.setModal(True)
            dlg.exec_()
            self._updateUi()
        elif link == 'mapclient.deregister':
            self._pmrTool.deregister()
            self._updateUi()

    def _searchClicked(self):
        self._doSearch(self._ui.comboBoxSearch.currentText())

    def _importClicked(self):
        pass

    def _exportClicked(self):
        pass

    def setSearchDomain(self, domain=['all', ]):
        self._domain = []
        if type(domain) is not list:
            domain = [domain]

        if len(domain) and domain[0] == 'all':
            domain = search_domains

        for subdomain in domain:
            if subdomain in search_domains:
                self._domain.append(subdomain)

        if len(self._domain):
            self._ui.comboBoxSearch.clear()
            for subdomain in self._domain:
                self._ui.comboBoxSearch.addItem(subdomain)

    def setExport(self, visible=True):
        if visible:
            self._ui.pushButtonExport.show()
        else:
            self._ui.pushButtonExport.hide()

    def setImport(self, visible=True):
        if visible:
            self._ui.pushButtonImport.show()
        else:
            self._ui.pushButtonImport.hide()

    def workspaceUrl(self):
        return self._ui.lineEditWorkspace.text()

    def setWorkspaceUrl(self, url):
        self._ui.lineEditWorkspace.setText(url)

    @handle_runtime_error
    @set_wait_cursor
    def _doSearch(self, search_type):
        # Set pmrlib to go
        self._ui.listWidgetResults.clear()

        # fix up known terms to be full blown uri
        search_text = self._ui.lineEditSearch.text()
        if True:
            search_text = self._ui.lineEditSearch.text()
            label_re = re.compile('\[([\w_\d]+)\]')
            re_result = label_re.search(search_text)
            if re_result:
                search_text = re_result.group(1)
#         search_terms = search_text.split()
#         for term in search_terms:
#             rdfterm = self._annotationTool.rdfFormOfTerm(term)
#             if rdfterm:
#                 search_text = search_text + ' ' + rdfterm[1:-1]
        results = self._pmrTool.search(search_text, search_type)

        if search_type == workflow_search_string:
            results_list = results['results']
            for r in results_list:
                item = QtGui.QListWidgetItem(r['obj']['title'], self._ui.listWidgetResults)
                item.setData(QtCore.Qt.UserRole, r)
        elif search_type == ontological_search_string:
            if type(results) is dict:
                return

            for r in results:
                label = r['label']
                for sr in r['items']:
                    item = QtGui.QListWidgetItem(sr['title'] + ' [%s, %s]' % (sr['value'], label), self._ui.listWidgetResults)
                    tool_tip = 'Workspace title: %s, Ontological term: %s, Target: %s' % (sr['title'], label, sr['href'])
                    item.setToolTip(tool_tip)
                    item.setData(QtCore.Qt.UserRole, sr)

        else:
            for r in results:
                if 'title' in r and r['title']:
                    item = QtGui.QListWidgetItem(r['title'], self._ui.listWidgetResults)
                else:
                    item = QtGui.QListWidgetItem(r['target'], self._ui.listWidgetResults)
                item.setData(QtCore.Qt.UserRole, r)
예제 #36
0
class PMRSearchDialog(QtGui.QDialog):
    """
    Dialog for managing interaction with PMR.
    """

    def __init__(self, parent=None):
        """
        Constructor
        """
        QtGui.QDialog.__init__(self, parent)
        self._ui = Ui_PMRSearchDialog()
        self._ui.setupUi(self)

        self._pmrTool = PMRTool()
        self._annotationTool = AnnotationTool()

        self._makeConnections()

        self._updateUi()

    def _updateUi(self):
        if self._pmrTool.hasAccess():
            self._ui.loginStackedWidget.setCurrentIndex(1)
        else:
            self._ui.loginStackedWidget.setCurrentIndex(0)

    def _makeConnections(self):
        self._ui.searchButton.clicked.connect(self._searchClicked)
        self._ui.registerLabel.linkActivated.connect(self.register)
        self._ui.deregisterLabel.linkActivated.connect(self.deregister)

    @handle_runtime_error
    @set_wait_cursor
    def _searchClicked(self):
        # Set pmrlib to go
        self._ui.searchResultsListWidget.clear()

        # fix up known terms to be full blown uri
        search_text = self._ui.searchLineEdit.text()
        search_terms = search_text.split()
        for term in search_terms:
            rdfterm = self._annotationTool.rdfFormOfTerm(term)
            if rdfterm:
                search_text = search_text + " " + rdfterm[1:-1]

        results = self._pmrTool.search(search_text)

        for r in results:
            if "title" in r and r["title"]:
                item = QtGui.QListWidgetItem(r["title"], self._ui.searchResultsListWidget)
            else:
                item = QtGui.QListWidgetItem(r["target"], self._ui.searchResultsListWidget)
            item.setData(QtCore.Qt.UserRole, r)

    def getSelectedWorkspace(self):
        items = self._ui.searchResultsListWidget.selectedItems()
        for item in items:
            return item.data(QtCore.Qt.UserRole)

    def register(self, link):
        if link != "mapclient.register":
            return

        dlg = AuthoriseApplicationDialog(self)
        dlg.setModal(True)
        dlg.exec_()

        self._updateUi()

    def deregister(self):
        self._pmrTool.deregister()
        self._updateUi()
 def test_make_session_no_access(self):
     tool = PMRTool()
     session = tool.make_session()
     self.assertFalse(isinstance(session, OAuth1Session))
     # Make sure this really is a requests.Session
     self.assertTrue(isinstance(session, Session))