Пример #1
0
    def _show_backup_decision(self, error=None):
        text = '<p>{0}</p><p>{1}</p>'.format(
            self.BACKUP_INTRO_TEXT if error is None else error,
            self.BACKUP_PROMPT_TEXT,
        )

        dialog = QMessageBox(
            QMessageBox.Question if error is None else QMessageBox.Critical,
            self.BACKUP_DIALOG_CAPTION if error is None else self.BACKUP_DIALOG_ERROR_CAPTION,
            text,
        )

        revert_button = dialog.addButton(self.REVERT_BACKUP_BUTTON_TEXT, QMessageBox.AcceptRole)
        delete_button = dialog.addButton(self.DELETE_BACKUP_BUTTON_TEXT, QMessageBox.DestructiveRole)
        examine_button = dialog.addButton(self.EXAMINE_BACKUP_BUTTON_TEXT, QMessageBox.ActionRole)
        dialog.addButton(self.QUIT_BUTTON_TEXT, QMessageBox.RejectRole)

        dialog.exec()
        clicked_button = dialog.clickedButton()

        if clicked_button == examine_button:
            QMetaObject.invokeMethod(self, '_examine_backup', Qt.QueuedConnection)
        elif clicked_button == revert_button:
            self._progress_dialog = QProgressDialog(None)
            self._progress_dialog.setLabelText(self.REVERT_BACKUP_PROGRESS_TEXT)
            self._progress_dialog.setCancelButton(None)
            self._progress_dialog.setRange(0, 0)
            self._progress_dialog.forceShow()

            self.request_revert_backup.emit()
        elif clicked_button == delete_button:
            self.request_delete_backup.emit()
        else:
            self.quit()
Пример #2
0
    def run(self):
        """
        Reimplemented from `QRunnable.run`
        """
        self.eventLoop = QEventLoop()
        self.eventLoop.processEvents()

        # Move the task to the current thread so it's events, signals, slots
        # are triggered from this thread.
        assert isinstance(self.task.thread(), _TaskDepotThread)
        QMetaObject.invokeMethod(self.task.thread(), "transfer",
                                 Qt.BlockingQueuedConnection,
                                 Q_ARG(object, self.task),
                                 Q_ARG(object, QThread.currentThread()))

        self.eventLoop.processEvents()

        # Schedule task.run from the event loop.
        self.task.start()

        # Quit the loop and exit when task finishes or is cancelled.
        # TODO: If the task encounters an critical error it might not emit
        # these signals and this Runnable will never complete.
        self.task.finished.connect(self.eventLoop.quit)
        self.task.cancelled.connect(self.eventLoop.quit)
        self.eventLoop.exec_()
Пример #3
0
    def run(self):
        """
        Reimplemented from `QRunnable.run`
        """
        self.eventLoop = QEventLoop()
        self.eventLoop.processEvents()

        # Move the task to the current thread so it's events, signals, slots
        # are triggered from this thread.
        assert isinstance(self.task.thread(), _TaskDepotThread)
        QMetaObject.invokeMethod(
            self.task.thread(), "transfer", Qt.BlockingQueuedConnection,
            Q_ARG(object, self.task),
            Q_ARG(object, QThread.currentThread())
        )

        self.eventLoop.processEvents()

        # Schedule task.run from the event loop.
        self.task.start()

        # Quit the loop and exit when task finishes or is cancelled.
        # TODO: If the task encounters an critical error it might not emit
        # these signals and this Runnable will never complete.
        self.task.finished.connect(self.eventLoop.quit)
        self.task.cancelled.connect(self.eventLoop.quit)
        self.eventLoop.exec_()
Пример #4
0
    def run(self):
        """
        Reimplemented from `QRunnable.run`
        """
        self.eventLoop = QEventLoop()
        self.eventLoop.processEvents()

        # Move the task to the current thread so it's events, signals, slots
        # are triggered from this thread.
        assert self.task.thread() is _TaskDepotThread.instance()

        QMetaObject.invokeMethod(
            self.task.thread(), "transfer", Qt.BlockingQueuedConnection,
            Q_ARG(object, self.task),
            Q_ARG(object, QThread.currentThread())
        )

        self.eventLoop.processEvents()

        # Schedule task.run from the event loop.
        self.task.start()

        # Quit the loop and exit when task finishes or is cancelled.
        self.task.finished.connect(self.eventLoop.quit)
        self.task.cancelled.connect(self.eventLoop.quit)
        self.eventLoop.exec_()
Пример #5
0
 def run(self):
     ret = None
     try:
         if self.object is not None and self.method is not None:
             # TODO Get return value.
             QMetaObject.invokeMethod(self.object, self.method, self.connection)
     except Exception, e:
         self.error.emit(e, traceback.format_exc())
Пример #6
0
 def done(self):
     self.timer.stop()
     self.popup.hide()
     self.editor.setFocus()
     item = self.popup.currentItem()
     if item:
         self.editor.setText(item.text(0))
         QMetaObject.invokeMethod(self.editor, "returnPressed")
Пример #7
0
 def doneCompletion(self):
     self.timer.stop()
     self.ui.popup.hide()
     self.ui.editor.setFocus()
     item = self.ui.popup.currentItem()
     if item != None:
         self.currentItem = self.ui.popup.currentItem().data(0, 0)
         self.ui.editor.setText(item.text(self.textplacetoeditor))
         QMetaObject.invokeMethod(self.ui.editor, "returnPressed")
Пример #8
0
 def doneCompletion(self):
     self.timer.stop()
     self.ui.popup.hide()
     self.ui.editor.setFocus()
     item = self.ui.popup.currentItem()
     if item != None:
         self.currentItem = self.ui.popup.currentItem().data(0,0)
         self.ui.editor.setText(item.text(self.textplacetoeditor))
         QMetaObject.invokeMethod(self.ui.editor, "returnPressed");
Пример #9
0
 def run(self):
     self.eventLoop = QEventLoop()
     self.eventLoop.processEvents()
     QObject.connect(self._call, SIGNAL("finished(QString)"),
                     lambda str: self.eventLoop.quit())
     QMetaObject.invokeMethod(
         self._call, "moveToAndInit", Qt.QueuedConnection,
         Q_ARG("PyQt_PyObject", QThread.currentThread()))
     self.eventLoop.processEvents()
     self.eventLoop.exec_()
 def run(self):
     self.eventLoop = QEventLoop()
     self.eventLoop.processEvents()
     QObject.connect(self._call, SIGNAL("finished(QString)"),
                     lambda str: self.eventLoop.quit())
     QMetaObject.invokeMethod(self._call, "moveToAndInit",
                              Qt.QueuedConnection,
                              Q_ARG("PyQt_PyObject",
                                    QThread.currentThread()))
     self.eventLoop.processEvents()
     self.eventLoop.exec_()
Пример #11
0
 def run(self):
     try:
         result = self.func(*(self.args), **(self.kwargs))
     except Exception as e:
         logger.exception("deferToThread caught exception: %r", e)
         QMetaObject.invokeMethod(DeferCallThread.mainThreadStub, "_slot_errback", Qt.QueuedConnection,
                 Q_ARG("PyQt_PyObject", self.done), Q_ARG("PyQt_PyObject", e))
     else:
         QMetaObject.invokeMethod(DeferCallThread.mainThreadStub, "_slot_callback", Qt.QueuedConnection,
                 Q_ARG("PyQt_PyObject", self.done), Q_ARG("PyQt_PyObject", result))
     finally:
         del self.func, self.done, self.args, self.kwargs
Пример #12
0
        def func():
            try:
                QMetaObject.invokeMethod(self, "_on_start", Qt.QueuedConnection)
                if allow_partial_results:
                    kwargs['should_break'] = should_break
                res = method(self, *args, on_progress=on_progress, **kwargs)
            except StopExecution:
                res = None

            QMetaObject.invokeMethod(self, "_on_result", Qt.QueuedConnection,
                                     Q_ARG(object, res))
            self.running = False
Пример #13
0
    def shutdown(self, wait=True):
        """
        Shutdown the executor and free all resources. If `wait` is True then
        wait until all pending futures are executed or cancelled.
        """
        if self._depot_thread is not None:
            QMetaObject.invokeMethod(
                self._depot_thread, "quit", Qt.AutoConnection)

        if wait:
            self._threadPool.waitForDone()
            if self._depot_thread:
                self._depot_thread.wait()
                self._depot_thread = None
Пример #14
0
    def shutdown(self, wait=True):
        """
        Shutdown the executor and free all resources. If `wait` is True then
        wait until all pending futures are executed or cancelled.
        """
        if self._depot_thread is not None:
            QMetaObject.invokeMethod(self._depot_thread, "quit",
                                     Qt.AutoConnection)

        if wait:
            self._threadPool.waitForDone()
            if self._depot_thread:
                self._depot_thread.wait()
                self._depot_thread = None
Пример #15
0
    def handleRequest(self):
        request = WebServerRequest(self)
        response = WebServerResponse(self)

        for server in servers:
            # verify which server this request is for
            if self.server == server.httpd:
                connectionType = Qt.BlockingQueuedConnection
                if QThread.currentThread() == server.thread():
                    connectionType = Qt.DirectConnection

                QMetaObject.invokeMethod(server, 'newRequest', connectionType,
                                         Q_ARG(WebServerRequest, request),
                                         Q_ARG(WebServerResponse, response))
                break
Пример #16
0
    def cardScanned(self, card):
        self.statusLabel.setText("Loading ...")

        userid = self.uf.read(card)[1]
        user = InternetClient.getUserDetails(userid)
        status = InternetClient.getUserStatus(userid, 0)
        statusDetails = None
        if status == "in":
            statusDetails = InternetClient.getUserStatus(userid, 1)
        QMetaObject.invokeMethod(self.parent, "startLogin",
                                 Qt.QueuedConnection, Q_ARG(QString, userid),
                                 Q_ARG(QString, user["realname"]),
                                 Q_ARG(QString, status),
                                 Q_ARG(QString, user["last_visit"]))

        self.statusLabel.setText("")
Пример #17
0
 def run(self):
     try:
         result = self.func(*(self.args), **(self.kwargs))
     except Exception as e:
         logger.exception("deferToThread caught exception: %r", e)
         QMetaObject.invokeMethod(DeferCallThread.mainThreadStub,
                                  "_slot_errback", Qt.QueuedConnection,
                                  Q_ARG("PyQt_PyObject", self.done),
                                  Q_ARG("PyQt_PyObject", e))
     else:
         QMetaObject.invokeMethod(DeferCallThread.mainThreadStub,
                                  "_slot_callback", Qt.QueuedConnection,
                                  Q_ARG("PyQt_PyObject", self.done),
                                  Q_ARG("PyQt_PyObject", result))
     finally:
         del self.func, self.done, self.args, self.kwargs
Пример #18
0
  def fetchFiles(self, urls, renderContext):
    downloader = Downloader(None, self.maxConnections, self.cacheExpiry, self.userAgent)
    downloader.moveToThread(QgsApplication.instance().thread())
    downloader.timer.moveToThread(QgsApplication.instance().thread())

    self.logT("TileLayer.fetchFiles() starts")
    # create a QEventLoop object that belongs to the current worker thread
    eventLoop = QEventLoop()
    downloader.allRepliesFinished.connect(eventLoop.quit)
    if self.iface:
      # for download progress
      downloader.replyFinished.connect(self.networkReplyFinished)
      self.downloader = downloader

    # create a timer to watch whether rendering is stopped
    watchTimer = QTimer()
    watchTimer.timeout.connect(eventLoop.quit)

    # fetch files
    QMetaObject.invokeMethod(self.downloader, "fetchFilesAsync", Qt.QueuedConnection, Q_ARG(list, urls), Q_ARG(int, self.plugin.downloadTimeout))

    # wait for the fetch to finish
    tick = 0
    interval = 500
    timeoutTick = self.plugin.downloadTimeout * 1000 / interval
    watchTimer.start(interval)
    while tick < timeoutTick:
      # run event loop for 0.5 seconds at maximum
      eventLoop.exec_()
      if downloader.unfinishedCount() == 0 or renderContext.renderingStopped():
        break
      tick += 1
    watchTimer.stop()

    if downloader.unfinishedCount() > 0:
      downloader.abort(False)
      if tick == timeoutTick:
        downloader.errorStatus = Downloader.TIMEOUT_ERROR
        self.log("fetchFiles(): timeout")

    # watchTimer.timeout.disconnect(eventLoop.quit)
    # downloader.allRepliesFinished.disconnect(eventLoop.quit)

    self.logT("TileLayer.fetchFiles() ends")
    return downloader.fetchedFiles
Пример #19
0
 def wrapper(obj, *args):
     # XXX: support kwargs?
     qargs = [Q_ARG(t, v) for t, v in zip(self.args, args)]
     invoke_args = [obj._instance, self.name]
     invoke_args.append(Qt.DirectConnection)
     rtype = self.returnType
     if rtype:
         invoke_args.append(Q_RETURN_ARG(rtype))
     invoke_args.extend(qargs)
     try:
         result = QMetaObject.invokeMethod(*invoke_args)
         error_msg = str(qApp.property("MIKRO_EXCEPTION").toString())
         if error_msg:
             # clear message
             qApp.setProperty("MIKRO_EXCEPTION", QVariant())
             raise Error(error_msg)
     except RuntimeError, e:
         raise TypeError, \
             "%s.%s(%r) call failed: %s" % (obj, self.name, args, e)
Пример #20
0
 def wrapper(obj, *args):
     # XXX: support kwargs?
     qargs = [Q_ARG(t, v) for t, v in zip(self.args, args)]
     invoke_args = [obj._instance, self.name]
     invoke_args.append(Qt.DirectConnection)
     rtype = self.returnType
     if rtype:
         invoke_args.append(Q_RETURN_ARG(rtype))
     invoke_args.extend(qargs)
     try:
         result = QMetaObject.invokeMethod(*invoke_args)
         error_msg = str(qApp.property("MIKRO_EXCEPTION").toString())
         if error_msg:
             # clear message
             qApp.setProperty("MIKRO_EXCEPTION", QVariant())
             raise Error(error_msg)
     except RuntimeError, e:
         raise TypeError, \
             "%s.%s(%r) call failed: %s" % (obj, self.name, args, e)
Пример #21
0
 def stop(self):
     QMetaObject.invokeMethod(self.player, 'stop')
Пример #22
0
 def seek(self, pos):
     QMetaObject.invokeMethod(self.player, 'seek', Q_ARG("qlonglong", pos))
Пример #23
0
 def wakeUp(self):
     QMetaObject.invokeMethod(self, "_timerSlot", Qt.QueuedConnection)
Пример #24
0
 def pause(self):
     QMetaObject.invokeMethod(self.player, 'pause')
Пример #25
0
 def call(*args):
     args = [Q_ARG(atype, arg) for atype, arg in zip(sig, args)]
     return QMetaObject.invokeMethod(obj, name, conntype, *args)
Пример #26
0
 def call(*args):
     args = [Q_ARG(atype, arg) for atype, arg in zip(sig, args)]
     return QMetaObject.invokeMethod(obj, name, conntype, *args)
Пример #27
0
 def update(f):
     QMetaObject.invokeMethod(
         self, "_update_info", Qt.QueuedConnection)
Пример #28
0
 def __call__(self, *args):
     args = [Q_ARG(atype, arg) for atype, arg in zip(self.arg_types, args)]
     QMetaObject.invokeMethod(
         self.obj, self.method, Qt.QueuedConnection,
         *args
     )
Пример #29
0
 def setCurrentItem(self, item):
     print('setCurrentItem: ', item)
     self.currentItem = item
     self.ui.editor.setText(item.stringList()[self.textplacetoeditor])
     QMetaObject.invokeMethod(self.ui.editor, "returnPressed")
Пример #30
0
 def setVolumeFactor(self, volume):
     """ Change the volume factor (0 - 20) """
     QMetaObject.invokeMethod(self.player,
         'setVolumeFactor', Q_ARG("double", volume / 10.0))
Пример #31
0
 def _report_updated_status(self):
     # This mechanism will cause a status update to only be emitted after the core has finished processing all other
     # events
     self._defer_status_update_level += 1
     QMetaObject.invokeMethod(self, '_report_updated_status_impl', Qt.QueuedConnection)
Пример #32
0
    def paintEvent(self, event):
        option = QStyleOption()
        option.initFrom(self)

        contents_rect = self.style().subElementRect(QStyle.SE_FrameContents, option, self) or self.contentsRect() # the SE_FrameContents rect is Null unless the stylesheet defines decorations

        if self.graphStyle == self.BarStyle:
            graph_width = self.__dict__['graph_width'] = int(ceil(float(contents_rect.width()) / self.horizontalPixelsPerUnit))
        else:
            graph_width = self.__dict__['graph_width'] = int(ceil(float(contents_rect.width() - 1) / self.horizontalPixelsPerUnit) + 1)

        max_value = self.__dict__['max_value'] = max(chain([0], *(islice(reversed(graph.data), graph_width) for graph in self.graphs if graph.enabled)))

        if self.graphHeight == self.AutomaticHeight or self.graphHeight < 0:
            graph_height = self.__dict__['graph_height'] = max(self.scaler.get_height(max_value), self.minHeight)
        else:
            graph_height = self.__dict__['graph_height'] = max(self.graphHeight, self.minHeight)

        if self.graphStyle == self.BarStyle:
            height_scaling = float(contents_rect.height()) / graph_height
        else:
            height_scaling = float(contents_rect.height() - self.lineThickness) / graph_height

        painter = QStylePainter(self)
        painter.drawPrimitive(QStyle.PE_Widget, option)

        painter.setClipRect(contents_rect)

        painter.save()
        painter.translate(contents_rect.x() + contents_rect.width() - 1, contents_rect.y() + contents_rect.height() - 1)
        painter.scale(-1, -1)

        painter.setRenderHint(QStylePainter.Antialiasing, self.graphStyle != self.BarStyle)

        for graph in (graph for graph in self.graphs if graph.enabled and graph.data):
            if self.boundary is not None and 0 < self.boundary < graph_height:
                boundary_width = min(5.0/height_scaling, self.boundary-0, graph_height-self.boundary)
                pen_color = QLinearGradient(0, (self.boundary - boundary_width) * height_scaling, 0, (self.boundary + boundary_width) * height_scaling)
                pen_color.setColorAt(0, graph.color)
                pen_color.setColorAt(1, graph.over_boundary_color)
                brush_color = QLinearGradient(0, (self.boundary - boundary_width) * height_scaling, 0, (self.boundary + boundary_width) * height_scaling)
                brush_color.setColorAt(0, self.color_with_alpha(graph.color, self.fillTransparency))
                brush_color.setColorAt(1, self.color_with_alpha(graph.over_boundary_color, self.fillTransparency))
            else:
                pen_color = graph.color
                brush_color = self.color_with_alpha(graph.color, self.fillTransparency)
            dataset = islice(reversed(graph.data), graph_width)
            if self.graphStyle == self.BarStyle:
                lines = [QLine(x*self.horizontalPixelsPerUnit, 0, x*self.horizontalPixelsPerUnit, y*height_scaling) for x, y in enumerate(dataset)]
                painter.setPen(QPen(pen_color, self.lineThickness))
                painter.drawLines(lines)
            else:
                painter.translate(0, +self.lineThickness/2 - 1)

                if self.smoothEnvelope and self.smoothFactor > 0:
                    min_value = 0
                    max_value = graph_height * height_scaling
                    cx_offset = self.horizontalPixelsPerUnit / 3.0
                    smoothness = self.smoothFactor

                    last_values = deque(3*[dataset.next() * height_scaling], maxlen=3) # last 3 values: 0 last, 1 previous, 2 previous previous

                    envelope = QPainterPath()
                    envelope.moveTo(0, last_values[0])
                    for x, y in enumerate(dataset, 1):
                        x = x * self.horizontalPixelsPerUnit
                        y = y * height_scaling * (1 - smoothness) + last_values[0] * smoothness
                        last_values.appendleft(y)
                        c1x = x - cx_offset * 2
                        c2x = x - cx_offset
                        c1y = limit((1 + smoothness) * last_values[1] - smoothness * last_values[2], min_value, max_value) # same gradient as previous previous value to previous value
                        c2y = limit((1 - smoothness) * last_values[0] + smoothness * last_values[1], min_value, max_value) # same gradient as previous value to last value
                        envelope.cubicTo(c1x, c1y, c2x, c2y, x, y)
                else:
                    envelope = QPainterPath()
                    envelope.addPolygon(QPolygonF([QPointF(x*self.horizontalPixelsPerUnit, y*height_scaling) for x, y in enumerate(dataset)]))

                if self.fillEnvelope or graph.fill_envelope:
                    first_element = envelope.elementAt(0)
                    last_element = envelope.elementAt(envelope.elementCount() - 1)
                    fill_path = QPainterPath()
                    fill_path.moveTo(last_element.x, last_element.y)
                    fill_path.lineTo(last_element.x + 1, last_element.y)
                    fill_path.lineTo(last_element.x + 1, -self.lineThickness)
                    fill_path.lineTo(-self.lineThickness, -self.lineThickness)
                    fill_path.lineTo(-self.lineThickness, first_element.y)
                    fill_path.connectPath(envelope)
                    painter.fillPath(fill_path, brush_color)

                painter.strokePath(envelope, QPen(pen_color, self.lineThickness, join=Qt.RoundJoin))

                painter.translate(0, -self.lineThickness/2 + 1)

        if self.boundary is not None and self.boundaryColor:
            painter.setRenderHint(QStylePainter.Antialiasing, False)
            painter.setPen(QPen(self.boundaryColor, 1.0))
            painter.drawLine(0, self.boundary*height_scaling, contents_rect.width(), self.boundary*height_scaling)

        painter.restore()

        # queue the 'updated' signal to be emited after returning to the main loop
        QMetaObject.invokeMethod(self, 'updated', Qt.QueuedConnection)
Пример #33
0
 def trigger(self):
     self.set_data(True)
     QMetaObject.invokeMethod(self, '_untrigger', Qt.QueuedConnection)
Пример #34
0
 def __call__(self, *args):
     args = [Q_ARG(atype, arg) for atype, arg in zip(self.arg_types, args)]
     QMetaObject.invokeMethod(self.obj, self.method, Qt.QueuedConnection,
                              *args)
Пример #35
0
 def _start_core(self):
     QMetaObject.invokeMethod(self._core, 'start', Qt.QueuedConnection)
Пример #36
0
 def setCurrentItem(self, item):
     print('setCurrentItem: ',item)
     self.currentItem = item
     self.ui.editor.setText(item.stringList()[self.textplacetoeditor])
     QMetaObject.invokeMethod(self.ui.editor, "returnPressed")
Пример #37
0
    def _load(self):
        url = self._url
        config = get_config()
        searcher_hp = self._searcher_hp
        searcher_de = self._searcher_de
        mime = None
        error = False

        if url.scheme() == 'static':
            try:
                self._data = _load_static_data(url.path().lstrip('/'))
            except EnvironmentError:
                self._data = '<h2>Static File Not Found</h2>'
                mime = 'text/html'
                error = True

        elif url.scheme() == 'dict':
            try:
                path = url.path().split('#', 1)[0]
                ldoce5 = LDOCE5(config.get('dataDir', ''), config.filemap_path)
                (self._data, mime) = ldoce5.get_content(path)
            except NotFoundError:
                self._data = '<h2>Content Not Found</h2>'
                mime = 'text/html'
                error = True
            except FilemapError:
                self._data = '<h2>File-Location Map Not Available</h2>'
                mime = 'text/html'
                error = True
            except ArchiveError:
                self._data = '<h2>Dictionary Data Not Available</h2>'
                mime = 'text/html'
                error = True

        elif url.scheme() == 'search':
            if searcher_hp and searcher_de:
                try:
                    self._data = enc_utf8(search_and_render(
                        url, searcher_hp, searcher_de))
                    mime = 'text/html'
                except:
                    s = u"<h2>Error</h2><div>{0}</div>".format(
                        '<br>'.join(traceback.format_exc().splitlines()))
                    self._data = enc_utf8(s)
                    mime = 'text/html'
                    error = True
            else:
                mime = 'text/html'
                self._data = ("""<p>The full-text search index """
                              """has not been created yet or broken.</p>""")
                error = True

        if mime:
            self.setHeader(QNetworkRequest.ContentTypeHeader, mime)
        self.setHeader(QNetworkRequest.ContentLengthHeader, len(self._data))
        self.setOpenMode(self.ReadOnly | self.Unbuffered)

        if error:
            nwerror = QNetworkReply.ContentNotFoundError
            error_msg = u'Content Not Found'
            self.setError(nwerror, error_msg)
            QMetaObject.invokeMethod(
                self, 'error', Qt.QueuedConnection,
                Q_ARG(QNetworkReply.NetworkError, nwerror))

        QMetaObject.invokeMethod(self, 'metaDataChanged', Qt.QueuedConnection)
        QMetaObject.invokeMethod(self, 'downloadProgress', Qt.QueuedConnection,
                                 Q_ARG('qint64', len(self._data)),
                                 Q_ARG('qint64', len(self._data)))
        QMetaObject.invokeMethod(self, 'readyRead', Qt.QueuedConnection)
        QMetaObject.invokeMethod(self, 'finished', Qt.QueuedConnection)

        self._finished = True
Пример #38
0
 def on_progress(i):
     if not self.running and not allow_partial_results:
         raise StopExecution
     QMetaObject.invokeMethod(self, "_on_progress", Qt.QueuedConnection,  Q_ARG(float, i))
Пример #39
0
    def _load(self):
        url = self._url
        config = get_config()
        searcher_hp = self._searcher_hp
        searcher_de = self._searcher_de
        mime = None
        error = False

        if url.scheme() == 'static':
            try:
                self._data = _load_static_data(url.path().lstrip('/'))
            except EnvironmentError:
                self._data = '<h2>Static File Not Found</h2>'
                mime = 'text/html'
                error = True

        elif url.scheme() == 'dict':
            try:
                path = url.path().split('#', 1)[0]
                ldoce5 = LDOCE5(config.get('dataDir', ''), config.filemap_path)
                (self._data, mime) = ldoce5.get_content(path)
            except NotFoundError:
                self._data = '<h2>Content Not Found</h2>'
                mime = 'text/html'
                error = True
            except FilemapError:
                self._data = '<h2>File-Location Map Not Available</h2>'
                mime = 'text/html'
                error = True
            except ArchiveError:
                self._data = '<h2>Dictionary Data Not Available</h2>'
                mime = 'text/html'
                error = True

        elif url.scheme() == 'search':
            if searcher_hp and searcher_de:
                try:
                    self._data = enc_utf8(
                        search_and_render(url, searcher_hp, searcher_de))
                    mime = 'text/html'
                except:
                    s = u"<h2>Error</h2><div>{0}</div>".format('<br>'.join(
                        traceback.format_exc().splitlines()))
                    self._data = enc_utf8(s)
                    mime = 'text/html'
                    error = True
            else:
                mime = 'text/html'
                self._data = ("""<p>The full-text search index """
                              """has not been created yet or broken.</p>""")
                error = True

        if mime:
            self.setHeader(QNetworkRequest.ContentTypeHeader, mime)
        self.setHeader(QNetworkRequest.ContentLengthHeader, len(self._data))
        self.setOpenMode(self.ReadOnly | self.Unbuffered)

        if error:
            nwerror = QNetworkReply.ContentNotFoundError
            error_msg = u'Content Not Found'
            self.setError(nwerror, error_msg)
            QMetaObject.invokeMethod(
                self, 'error', Qt.QueuedConnection,
                Q_ARG(QNetworkReply.NetworkError, nwerror))

        QMetaObject.invokeMethod(self, 'metaDataChanged', Qt.QueuedConnection)
        QMetaObject.invokeMethod(self, 'downloadProgress', Qt.QueuedConnection,
                                 Q_ARG('qint64', len(self._data)),
                                 Q_ARG('qint64', len(self._data)))
        QMetaObject.invokeMethod(self, 'readyRead', Qt.QueuedConnection)
        QMetaObject.invokeMethod(self, 'finished', Qt.QueuedConnection)

        self._finished = True
Пример #40
0
 def wakeUp(self):
     QMetaObject.invokeMethod(self, "_timerSlot", Qt.QueuedConnection)
Пример #41
0
 def _handle_frame(self, frame):
     self._image = QImage(frame.data, frame.width, frame.height, QImage.Format_ARGB32)
     if self._clock is None:
         QMetaObject.invokeMethod(self, 'update', Qt.QueuedConnection)
Пример #42
0
 def update(f):
     QMetaObject.invokeMethod(self, "_update_info",
                              Qt.QueuedConnection)
Пример #43
0
 def play(self):
     QMetaObject.invokeMethod(self.player, 'play')
Пример #44
0
 def _handle_frame(self, frame):
     self._image = QImage(frame.data, frame.width, frame.height,
                          QImage.Format_ARGB32)
     if self._clock is None:
         QMetaObject.invokeMethod(self, 'update', Qt.QueuedConnection)
Пример #45
0
    def paintEvent(self, event):
        option = QStyleOption()
        option.initFrom(self)

        contents_rect = self.style().subElementRect(QStyle.SE_FrameContents, option, self) or self.contentsRect() # the SE_FrameContents rect is Null unless the stylesheet defines decorations

        if self.graphStyle == self.BarStyle:
            graph_width = self.__dict__['graph_width'] = int(ceil(float(contents_rect.width()) / self.horizontalPixelsPerUnit))
        else:
            graph_width = self.__dict__['graph_width'] = int(ceil(float(contents_rect.width() - 1) / self.horizontalPixelsPerUnit) + 1)

        max_value = self.__dict__['max_value'] = max(chain([0], *(islice(reversed(graph.data), graph_width) for graph in self.graphs if graph.enabled)))

        if self.graphHeight == self.AutomaticHeight or self.graphHeight < 0:
            graph_height = self.__dict__['graph_height'] = max(self.scaler.get_height(max_value), self.minHeight)
        else:
            graph_height = self.__dict__['graph_height'] = max(self.graphHeight, self.minHeight)

        if self.graphStyle == self.BarStyle:
            height_scaling = float(contents_rect.height()) / graph_height
        else:
            height_scaling = float(contents_rect.height() - self.lineThickness) / graph_height

        painter = QStylePainter(self)
        painter.drawPrimitive(QStyle.PE_Widget, option)

        painter.setClipRect(contents_rect)

        painter.save()
        painter.translate(contents_rect.x() + contents_rect.width() - 1, contents_rect.y() + contents_rect.height() - 1)
        painter.scale(-1, -1)

        painter.setRenderHint(QStylePainter.Antialiasing, self.graphStyle != self.BarStyle)

        for graph in (graph for graph in self.graphs if graph.enabled and graph.data):
            if self.boundary is not None and 0 < self.boundary < graph_height:
                boundary_width = min(5.0/height_scaling, self.boundary-0, graph_height-self.boundary)
                pen_color = QLinearGradient(0, (self.boundary - boundary_width) * height_scaling, 0, (self.boundary + boundary_width) * height_scaling)
                pen_color.setColorAt(0, graph.color)
                pen_color.setColorAt(1, graph.over_boundary_color)
                brush_color = QLinearGradient(0, (self.boundary - boundary_width) * height_scaling, 0, (self.boundary + boundary_width) * height_scaling)
                brush_color.setColorAt(0, self.color_with_alpha(graph.color, self.fillTransparency))
                brush_color.setColorAt(1, self.color_with_alpha(graph.over_boundary_color, self.fillTransparency))
            else:
                pen_color = graph.color
                brush_color = self.color_with_alpha(graph.color, self.fillTransparency)
            dataset = islice(reversed(graph.data), graph_width)
            if self.graphStyle == self.BarStyle:
                lines = [QLine(x*self.horizontalPixelsPerUnit, 0, x*self.horizontalPixelsPerUnit, y*height_scaling) for x, y in enumerate(dataset)]
                painter.setPen(QPen(pen_color, self.lineThickness))
                painter.drawLines(lines)
            else:
                painter.translate(0, +self.lineThickness/2 - 1)

                if self.smoothEnvelope and self.smoothFactor > 0:
                    min_value = 0
                    max_value = graph_height * height_scaling
                    cx_offset = self.horizontalPixelsPerUnit / 3.0
                    smoothness = self.smoothFactor

                    last_values = deque(3*[dataset.next() * height_scaling], maxlen=3) # last 3 values: 0 last, 1 previous, 2 previous previous

                    envelope = QPainterPath()
                    envelope.moveTo(0, last_values[0])
                    for x, y in enumerate(dataset, 1):
                        x = x * self.horizontalPixelsPerUnit
                        y = y * height_scaling * (1 - smoothness) + last_values[0] * smoothness
                        last_values.appendleft(y)
                        c1x = x - cx_offset * 2
                        c2x = x - cx_offset
                        c1y = limit((1 + smoothness) * last_values[1] - smoothness * last_values[2], min_value, max_value) # same gradient as previous previous value to previous value
                        c2y = limit((1 - smoothness) * last_values[0] + smoothness * last_values[1], min_value, max_value) # same gradient as previous value to last value
                        envelope.cubicTo(c1x, c1y, c2x, c2y, x, y)
                else:
                    envelope = QPainterPath()
                    envelope.addPolygon(QPolygonF([QPointF(x*self.horizontalPixelsPerUnit, y*height_scaling) for x, y in enumerate(dataset)]))

                if self.fillEnvelope or graph.fill_envelope:
                    first_element = envelope.elementAt(0)
                    last_element = envelope.elementAt(envelope.elementCount() - 1)
                    fill_path = QPainterPath()
                    fill_path.moveTo(last_element.x, last_element.y)
                    fill_path.lineTo(last_element.x + 1, last_element.y)
                    fill_path.lineTo(last_element.x + 1, -self.lineThickness)
                    fill_path.lineTo(-self.lineThickness, -self.lineThickness)
                    fill_path.lineTo(-self.lineThickness, first_element.y)
                    fill_path.connectPath(envelope)
                    painter.fillPath(fill_path, brush_color)

                painter.strokePath(envelope, QPen(pen_color, self.lineThickness, join=Qt.RoundJoin))

                painter.translate(0, -self.lineThickness/2 + 1)

        if self.boundary is not None and self.boundaryColor:
            painter.setRenderHint(QStylePainter.Antialiasing, False)
            painter.setPen(QPen(self.boundaryColor, 1.0))
            painter.drawLine(0, self.boundary*height_scaling, contents_rect.width(), self.boundary*height_scaling)

        painter.restore()

        # queue the 'updated' signal to be emited after returning to the main loop
        QMetaObject.invokeMethod(self, 'updated', Qt.QueuedConnection)