Exemple #1
0
    def process_signals_for_widget(self, node, widget, signals):
        """
        Process new signals for the OWBaseWidget.
        """
        # This replaces the old OWBaseWidget.processSignals method

        if sip.isdeleted(widget):
            log.critical("Widget %r was deleted. Cannot process signals",
                         widget)
            return

        app = QCoreApplication.instance()

        for signal in signals:
            link = signal.link
            value = signal.value

            # Check and update the dynamic link state
            if link.is_dynamic():
                link.dynamic_enabled = can_enable_dynamic(link, value)
                if not link.dynamic_enabled:
                    # Send None instead
                    value = None

            handler = link.sink_channel.handler
            if handler.startswith("self."):
                handler = handler.split(".", 1)[1]

            handler = getattr(widget, handler)

            if link.sink_channel.single:
                args = (value,)
            else:
                args = (value, signal.id)

            log.debug("Process signals: calling %s.%s (from %s with id:%s)",
                      type(widget).__name__, handler.__name__, link, signal.id)

            app.setOverrideCursor(Qt.WaitCursor)
            try:
                handler(*args)
            except Exception:
                sys.excepthook(*sys.exc_info())
                log.exception("Error calling '%s' of '%s'",
                              handler.__name__, node.title)
            finally:
                app.restoreOverrideCursor()

        app.setOverrideCursor(Qt.WaitCursor)
        try:
            widget.handleNewSignals()
        except Exception:
            sys.excepthook(*sys.exc_info())
            log.exception("Error calling 'handleNewSignals()' of '%s'",
                          node.title)
        finally:
            app.restoreOverrideCursor()
Exemple #2
0
    def process_signals_for_widget(self, node, widget, signals):
        """
        Process new signals for the OWBaseWidget.
        """
        # This replaces the old OWBaseWidget.processSignals method

        if sip.isdeleted(widget):
            log.critical("Widget %r was deleted. Cannot process signals",
                         widget)
            return

        app = QCoreApplication.instance()

        for signal in signals:
            link = signal.link
            value = signal.value

            # Check and update the dynamic link state
            if link.is_dynamic():
                link.dynamic_enabled = can_enable_dynamic(link, value)
                if not link.dynamic_enabled:
                    # Send None instead
                    value = None

            handler = link.sink_channel.handler
            if handler.startswith("self."):
                handler = handler.split(".", 1)[1]

            handler = getattr(widget, handler)

            if link.sink_channel.single:
                args = (value, )
            else:
                args = (value, signal.id)

            log.debug("Process signals: calling %s.%s (from %s with id:%s)",
                      type(widget).__name__, handler.__name__, link, signal.id)

            app.setOverrideCursor(Qt.WaitCursor)
            try:
                handler(*args)
            except Exception:
                sys.excepthook(*sys.exc_info())
                log.exception("Error calling '%s' of '%s'", handler.__name__,
                              node.title)
            finally:
                app.restoreOverrideCursor()

        app.setOverrideCursor(Qt.WaitCursor)
        try:
            widget.handleNewSignals()
        except Exception:
            sys.excepthook(*sys.exc_info())
            log.exception("Error calling 'handleNewSignals()' of '%s'",
                          node.title)
        finally:
            app.restoreOverrideCursor()
    def __call__(self, exc_type, exc_value, tb):
        if self._stream:
            header = exc_type.__name__ + ' Exception'
            if QThread.currentThread() != QCoreApplication.instance().thread():
                header += " (in non-GUI thread)"
            text = traceback.format_exception(exc_type, exc_value, tb)
            text.insert(0, '{:-^79}\n'.format(' ' + header + ' '))
            text.append('-' * 79 + '\n')
            self._stream.writelines(text)

        self.handledException.emit((exc_type, exc_value, tb))
Exemple #4
0
    def __call__(self, exc_type, exc_value, tb):
        if self._stream:
            header = exc_type.__name__ + ' Exception'
            if QThread.currentThread() != QCoreApplication.instance().thread():
                header += " (in non-GUI thread)"
            text = traceback.format_exception(exc_type, exc_value, tb)
            text.insert(0, '{:-^79}\n'.format(' ' + header + ' '))
            text.append('-' * 79 + '\n')
            self._stream.writelines(text)

        self.handledException.emit((exc_type, exc_value, tb))
    def __call__(self, exc_type, exc_value, tb):
        if self._stream:
            header = exc_type.__name__ + " Exception"
            if QThread.currentThread() != QCoreApplication.instance().thread():
                header += " (in non-GUI thread)"
            text = traceback.format_exception(exc_type, exc_value, tb)
            text.insert(0, "{:-^79}\n".format(" " + header + " "))
            text.append("-" * 79 + "\n")
            self._stream.writelines(text)

        self.handledException.emit(((exc_type, exc_value, tb), self._canvas))
Exemple #6
0
    def init(self):
        """
        Initialize the QCoreApplication.organizationDomain, applicationName,
        applicationVersion and the default settings format.

        Should only be run once at application startup.
        """
        QCoreApplication.setOrganizationDomain(self.OrganizationDomain)
        QCoreApplication.setApplicationName(self.ApplicationName)
        QCoreApplication.setApplicationVersion(self.ApplicationVersion)
        QSettings.setDefaultFormat(QSettings.IniFormat)
        app = QCoreApplication.instance()
        if app is not None:
            QCoreApplication.sendEvent(app, QEvent(QEvent.PolishRequest))
    def _fetch_indicators(self, progress=lambda val: None):
        """Background task for fetching indicators."""
        progress(0)

        def row_item(display_value, item_values=None):
            """Generate a cell item for a given row."""
            if not item_values:
                item_values = {}
            item = QtGui.QStandardItem()
            item.setData(display_value, Qt.DisplayRole)
            for role, value in item_values.items():
                item.setData(value, role)
            return item

        progress(10)
        filter_ = self._main_widget.basic_indicator_filter()
        data = self._api.get_indicators(filter_=filter_)
        self._indicator_data = {ind["id"]: ind for ind in data}
        progress(70)

        indicators = [[""] + row
                      for row in self._api.get_indicator_list(filter_=filter_)]

        model = QtGui.QStandardItemModel()
        model.setHorizontalHeaderLabels(indicators[0])
        for row in indicators[1:]:
            search_string = " | ".join(row).lower()
            row_data = [row_item(item) for item in row]
            row_data[0].setData(search_string, TEXTFILTERROLE)
            row_data[1].setData(self._get_link(row[1]), gui.LinkRole)
            model.appendRow(row_data)

        progress(100)
        if QThread.currentThread() is not QCoreApplication.instance().thread():
            model.moveToThread(QCoreApplication.instance().thread())
        return model
Exemple #8
0
    def wrapper(*args):
        app = QCoreApplication.instance()
        self = args[0]

        def execWithArgs():
            self.qpart.show()
            QTest.qWaitForWindowExposed(self.qpart)
            _processPendingEvents(app)

            try:
                func(*args)
            finally:
                _processPendingEvents(app)
                app.quit()

        QTimer.singleShot(0, execWithArgs)

        app.exec_()
    def __call__(self, exc_type, exc_value, tb):
        if self.stream is None:
            stream = sys.stderr
        else:
            stream = self.stream
        if stream is not None:
            header = exc_type.__name__ + ' Exception'
            if QThread.currentThread() != QCoreApplication.instance().thread():
                header += " (in non-GUI thread)"
            text = traceback.format_exception(exc_type, exc_value, tb)
            text.insert(0, '{:-^79}\n'.format(' ' + header + ' '))
            text.append('-' * 79 + '\n')
            stream.writelines(text)
            try:
                stream.flush()
            except Exception:
                pass

        self.handledException.emit((exc_type, exc_value, tb))
    def process_signals_for_widget(self, node, widget, signals):
        # type: (SchemeNode, OWBaseWidget, List[Signal]) -> None
        """
        Process new signals for the OWBaseWidget.
        """
        app = QCoreApplication.instance()
        try:
            app.setOverrideCursor(Qt.WaitCursor)
            for signal in signals:
                link = signal.link
                value = signal.value
                handler = link.sink_channel.handler
                if handler.startswith("self."):
                    handler = handler.split(".", 1)[1]

                handler = getattr(widget, handler)

                if link.sink_channel.single:
                    args = (value, )
                else:
                    args = (value, signal.id)

                log.debug(
                    "Process signals: calling %s.%s (from %s with id:%s)",
                    type(widget).__name__, handler.__name__, link, signal.id)

                try:
                    handler(*args)
                except Exception:
                    log.exception("Error calling '%s' of '%s'",
                                  handler.__name__, node.title)
                    raise

            try:
                widget.handleNewSignals()
            except Exception:
                log.exception("Error calling 'handleNewSignals()' of '%s'",
                              node.title)
                raise
        finally:
            app.restoreOverrideCursor()
def get_event_loop() -> asyncio.AbstractEventLoop:
    """
    Get the asyncio.AbstractEventLoop for the main Qt application thread.

    The QCoreApplication instance must already have been created.
    Must only be called from the main Qt application thread.
    """
    try:
        # Python >= 3.7
        get_running_loop = asyncio.get_running_loop  # type: ignore
    except AttributeError:
        get_running_loop = asyncio._get_running_loop  # type: ignore
    app = QCoreApplication.instance()
    if app is None:
        raise RuntimeError("QCoreApplication is not running")
    if app.thread() is not QThread.currentThread():
        raise RuntimeError("Called from non-main thread")
    loop: Optional[asyncio.AbstractEventLoop]
    try:
        loop = get_running_loop()
    except RuntimeError:
        loop = None
    else:
        if loop is not None:
            return loop

    qt_api = os.environ.get("QT_API", "").lower()
    if qt_api == "pyqt5":
        os.environ["QT_API"] = "PyQt5"
    elif qt_api == "pyside2":
        os.environ["QT_API"] = "PySide2"
    import qasync

    if loop is None:
        loop = qasync.QEventLoop(app)
        # Do not use qasync.QEventLoop's default executor which uses QThread
        # based pool and exhibits https://github.com/numpy/numpy/issues/11551
        loop.set_default_executor(futures.ThreadPoolExecutor())
    return loop
Exemple #12
0
 def setUp(self) -> None:
     self.app = QCoreApplication.instance()
     if self.app is None:
         self.app = QCoreApplication([])
     super().setUp()
Exemple #13
0
 def setUp(self):
     self.app = QCoreApplication.instance()
     if self.app is None:
         self.app = QCoreApplication([])
Exemple #14
0
def get_gds_model(progress=lambda val: None):
    """
    Initialize and return a GDS datasets model.

    :param progress: A progress callback.
    :rval tuple:
        A tuple of (QStandardItemModel, geo.GDSInfo, [geo.GDS])

    .. note::
        The returned QStandardItemModel's thread affinity is set to
        the GUI thread.

    """
    progress(1)
    info = geo.GDSInfo()
    search_keys = ["dataset_id", "title", "platform_organism", "description"]
    cache_dir = serverfiles.localpath(geo.DOMAIN)
    gds_link = "http://www.ncbi.nlm.nih.gov/sites/GDSbrowser?acc={0}"
    pm_link = "http://www.ncbi.nlm.nih.gov/pubmed/{0}"
    gds_list = []

    def is_cached(gds):
        return os.path.exists(
            os.path.join(cache_dir, gds["dataset_id"]) + ".soft.gz")

    def item(displayvalue, item_values={}):
        item = QStandardItem()
        item.setData(displayvalue, Qt.DisplayRole)
        for role, value in item_values.items():
            item.setData(value, role)
        return item

    def gds_to_row(gds):
        #: Text for easier full search.
        search_text = " | ".join(
            [gds.get(key, "").lower() for key in search_keys])
        row = [
            item(" " if is_cached(gds) else "", {TextFilterRole: search_text}),
            item(gds["dataset_id"],
                 {LinkRole: gds_link.format(gds["dataset_id"])}),
            item(gds["title"]),
            item(gds["platform_organism"]),
            item(len(gds["samples"])),
            item(gds["feature_count"]),
            item(gds["gene_count"]),
            item(len(gds["subsets"])),
            item(
                gds.get("pubmed_id", ""), {
                    LinkRole:
                    pm_link.format(gds["pubmed_id"])
                    if gds.get("pubmed_id") else None
                })
        ]
        return row

    model = QStandardItemModel()
    model.setHorizontalHeaderLabels([
        "", "ID", "Title", "Organism", "Samples", "Features", "Genes",
        "Subsets", "PubMedID"
    ])
    progress(20)
    for gds in info.values():
        model.appendRow(gds_to_row(gds))

        gds_list.append(gds)

    progress(50)

    if QThread.currentThread() is not QCoreApplication.instance().thread():
        model.moveToThread(QCoreApplication.instance().thread())
    return model, info, gds_list
Exemple #15
0
 def do_work(self):
     self.function()
     self.moveToThread(QCoreApplication.instance().thread())
     self.done.emit()
def get_gds_model(progress=lambda val: None):
    """
    Initialize and return a GDS datasets model.

    :param progress: A progress callback.
    :rval tuple:
        A tuple of (QStandardItemModel, geo.GDSInfo, [geo.GDS])

    .. note::
        The returned QStandardItemModel's thread affinity is set to
        the GUI thread.

    """
    progress(1)
    info = geo.GDSInfo()
    search_keys = ["dataset_id", "title", "platform_organism", "description"]
    cache_dir = serverfiles.localpath(geo.DOMAIN)
    gds_link = "http://www.ncbi.nlm.nih.gov/sites/GDSbrowser?acc={0}"
    pm_link = "http://www.ncbi.nlm.nih.gov/pubmed/{0}"
    gds_list = []

    def is_cached(gds):
        return os.path.exists(os.path.join(cache_dir, gds["dataset_id"]) +
                              ".soft.gz")

    def item(displayvalue, item_values={}):
        item = QStandardItem()
        item.setData(displayvalue, Qt.DisplayRole)
        for role, value in item_values.items():
            item.setData(value, role)
        return item

    def gds_to_row(gds):
        #: Text for easier full search.
        search_text = " | ".join([gds.get(key, "").lower()
                                  for key in search_keys])
        row = [
            item(" " if is_cached(gds) else "",
                 {TextFilterRole: search_text}),
            item(gds["dataset_id"],
                 {LinkRole: gds_link.format(gds["dataset_id"])}),
            item(gds["title"]),
            item(gds["platform_organism"]),
            item(len(gds["samples"])),
            item(gds["feature_count"]),
            item(gds["gene_count"]),
            item(len(gds["subsets"])),
            item(gds.get("pubmed_id", ""),
                 {LinkRole: pm_link.format(gds["pubmed_id"])
                            if gds.get("pubmed_id")
                            else None})
        ]
        return row

    model = QStandardItemModel()
    model.setHorizontalHeaderLabels(
        ["", "ID", "Title", "Organism", "Samples", "Features",
         "Genes", "Subsets", "PubMedID"]
    )
    progress(20)
    for gds in info.values():
        model.appendRow(gds_to_row(gds))

        gds_list.append(gds)

    progress(50)

    if QThread.currentThread() is not QCoreApplication.instance().thread():
        model.moveToThread(QCoreApplication.instance().thread())
    return model, info, gds_list
 def setUp(self):
     self.app = QCoreApplication.instance()
     if self.app is None:
         self.app = QCoreApplication([])