Exemplo n.º 1
0
    def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                "Unable to attach to shared memory segment.\nLoad an "
                "image first.")
            return

        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
class ShareServiceInteractor:
    def __init__(self, view):
        self.view = view
        self.buffer = QBuffer()

        self.network_manager = QNetworkAccessManager(self.view)
        self.network_manager.finished.connect(self.on_received_response)

    def on_received_response(self, reply: QNetworkReply):
        if reply.error() != QNetworkReply.NoError:
            error_msg = "Unable to create new print share: {}".format(reply.errorString())
            logging.error(error_msg)
            app_settings.app_data_writer.signals.exchange_share_failed.emit(error_msg)
            return

        share_location = reply.rawHeader(QByteArray(bytes("Location", encoding="utf-8")))
        app_settings.app_data_writer.signals.exchange_share_created.emit(share_location.data().decode())
        reply.deleteLater()
        self.buffer.close()

    def create_document(self, raw_html):
        app_config = app_settings.load_configuration()
        url: QUrl = QUrl(app_config.print_server + "/prints")
        base64_encoded = str_to_base64_encoded_bytes(raw_html)
        jdoc = {"document": bytes_to_str(base64_encoded)}
        jdoc_str = json.dumps(jdoc)
        self.buffer.setData(str_to_bytes(jdoc_str))
        network_request = QNetworkRequest(url)
        network_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
        in_progress_reply = self.network_manager.post(network_request, self.buffer)
        self.view.finished.connect(in_progress_reply.abort)
Exemplo n.º 3
0
    def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                    "Unable to attach to shared memory segment.\nLoad an "
                    "image first.")
            return
 
        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
Exemplo n.º 4
0
    def add_request(self, request):
        if len(self.requests_in_flight) > self.max_in_flight:
            self.evict_timed_out_requests()

        self.requests_in_flight[id(request)] = request
        log = [request, 0]
        performed_requests.append(log)

        # qt_request is managed by QNetworkAccessManager, so we don't have to
        qt_request = QNetworkRequest(QUrl(request.url))
        qt_request.setPriority(request.priority)
        qt_request.setHeader(QNetworkRequest.ContentTypeHeader,
                             "application/x-www-form-urlencoded")
        qt_request.setRawHeader(b'X-Api-Key', self.key)

        buf = QBuffer()
        if request.raw_data:
            buf.setData(request.raw_data)
        buf.open(QIODevice.ReadOnly)

        request.reply = self.sendCustomRequest(qt_request,
                                               request.method.encode("utf8"),
                                               buf)
        buf.setParent(request.reply)

        connect(request.reply.finished, lambda: request.on_finished(request))
Exemplo n.º 5
0
    def pydoc(self, job, url):
        from pygments.formatters import HtmlFormatter
        from pygments.lexers.python import Python3Lexer
        from pygments import highlight

        modname = url.path().lstrip("/")
        query = QUrlQuery(url)
        extras = {}
        if query.hasQueryItem("hl_lines"):
            start, end = query.queryItemValue("hl_lines").split("-")
            extras["hl_lines"] = list(range(int(start), int(end) + 1))

        mod = importlib.import_module(modname)
        filepath = inspect.getsourcefile(mod)

        formatter = HtmlFormatter(title="Module %s" % modname,
                                  full=True,
                                  lineanchors="line",
                                  **extras)

        with open(filepath) as f:
            code = highlight(f.read(), Python3Lexer(), formatter)

        buffer = QBuffer(self)
        buffer.setData(code.encode("utf-8"))
        job.reply(b"text/html", buffer)
Exemplo n.º 6
0
 def fromByteArray(self, data):
     self.mError = ''
     buffer = QBuffer()
     buffer.setData(data)
     buffer.open(QBuffer.ReadOnly)
     reader = EditorMapReader()
     map = reader.readMap(buffer)
     if (not map):
         self.mError = reader.errorString()
     return map
Exemplo n.º 7
0
    def requestStarted(self, req):
        if req.requestMethod() != b'GET':
            ENGINE_LOGGER.debug('prevented non-GET to cid: resource')
            return req.fail(req.RequestFailed)

        path = req.requestUrl().path()
        try:
            part = self.parts[path]
        except KeyError:
            return req.fail(req.UrlNotFound)

        qbuf = QBuffer(parent=req)
        # XXX decode=True: decodes message ASCII to bytes
        qbuf.setData(QByteArray(part.get_payload(decode=True)))
        req.reply(part.get_content_type().encode('ascii'), qbuf)
Exemplo n.º 8
0
    def perform_delete(self, endpoint, data, url):
        """
        Perform an HTTP DELETE request.

        :param endpoint: the name of the Tribler endpoint.
        :param data: the data/body to send with the request.
        :param url: the url to send the request to.
        """
        buf = QBuffer()
        buf.setData(data)
        buf.open(QIODevice.ReadOnly)
        delete_request = QNetworkRequest(QUrl(url))
        reply = self.sendCustomRequest(delete_request, "DELETE", buf)
        buf.setParent(reply)
        return reply
Exemplo n.º 9
0
    def perform_delete(self, endpoint, data, url):
        """
        Perform an HTTP DELETE request.

        :param endpoint: the name of the Tribler endpoint.
        :param data: the data/body to send with the request.
        :param url: the url to send the request to.
        """
        buf = QBuffer()
        buf.setData(data)
        buf.open(QIODevice.ReadOnly)
        delete_request = QNetworkRequest(QUrl(url))
        reply = self.sendCustomRequest(delete_request, "DELETE", buf)
        buf.setParent(reply)
        return reply
Exemplo n.º 10
0
    def perform_patch(self, endpoint, data, url):
        """
        Perform an HTTP PATCH request.

        :param endpoint: the name of the Tribler endpoint.
        :param data: the data/body to send with the request.
        :param url: the url to send the request to.
        """
        buf = QBuffer()
        buf.setData(data)
        buf.open(QIODevice.ReadOnly)
        patch_request = QNetworkRequest(QUrl(url))
        reply = self.sendCustomRequest(patch_request, "PATCH", buf)
        buf.setParent(reply)
        performed_requests.append([endpoint, "PATCH", data, time(), lambda: self.get_status_code(reply)])
        return reply
Exemplo n.º 11
0
    def perform_delete(self, endpoint, data, url):
        """
        Perform an HTTP DELETE request.

        :param endpoint: the name of the Tribler endpoint.
        :param data: the data/body to send with the request.
        :param url: the url to send the request to.
        """
        performed_requests.append(
            [endpoint, "DELETE", data,
             time(), self.get_status_code])
        buf = QBuffer()
        buf.setData(data)
        buf.open(QIODevice.ReadOnly)
        delete_request = QNetworkRequest(QUrl(url))
        self.reply = self.sendCustomRequest(delete_request, "DELETE", buf)
        buf.setParent(self.reply)
Exemplo n.º 12
0
    def createRequest(self, op, originalReq, outgoingData):
        """创建请求
        :param op:           操作类型见http://doc.qt.io/qt-5/qnetworkaccessmanager.html#Operation-enum
        :param originalReq:  原始请求
        :param outgoingData: 输出数据
        """
        url = originalReq.url().toString()
        if url.find('pos.baidu.com') > -1 and url.find('ltu=') > -1:
            # 拦截百度联盟的广告
            print('block:', url)
            originalReq.setUrl(QUrl())
        if op == self.PostOperation and outgoingData:
            # 拦截或者修改post数据
            # 读取后要重新设置,不然网站接收不到请求
            data = outgoingData.readAll().data()
            print('post data:', data)
            # 修改data后重新设置
            outgoingData = QBuffer(self)
            outgoingData.setData(data)

        return super(RequestInterceptor, self).createRequest(op, originalReq, outgoingData)
Exemplo n.º 13
0
    def requestStarted(self, job):
        url = job.requestUrl()
        request = url.authority()

        if request not in PAGES:
            path = url.path()
            if path.startswith("/js/"):
                js_path = os.path.join(THIS_DIR, "js", path[4:])
                if os.path.isfile(js_path):
                    f = QFile(js_path, self)
                    job.reply(b"application/javascript", f)

            return

        template = self.env.get_template(request + ".html")

        fn = PAGES[request]

        buffer = QBuffer(self)
        buffer.setData(template.render(**fn(self)).encode("utf-8"))
        job.reply(b"text/html", buffer)
Exemplo n.º 14
0
    def load_from_memory(self):  # consumer slot
        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        if True:  # first variant (much simpler / shorter, more robust)
            try:
                from prodcon_ipc.consumer_ipc import ScopedConsumer
                with ScopedConsumer(self.consumer_ipc) as sc:
                    buf.setData(sc.data())
                    buf.open(QBuffer.ReadOnly)
                    ins >> image
            except Exception as err:
                self.ui.label.setText(str(err))

        else:  # second variant, using begin()...end() manually
            try:
                data = self.consumer_ipc.begin()
            except RuntimeError as err:
                self.ui.label.setText(str(err))
                return

            # Read from the shared memory:
            try:
                buf.setData(data)
                buf.open(QBuffer.ReadOnly)
                ins >> image
            except Exception as err:
                logzero.logger.error(str(err))

            try:
                self.consumer_ipc.end()
            except RuntimeError as err:
                self.ui.label.setText(str(err))
                return

        if not image.isNull():
            self.ui.label.setPixmap(QPixmap.fromImage(image))
        else:
            logzero.logger.error("Image data was corrupted.")
Exemplo n.º 15
0
    def perform_request(self,
                        endpoint,
                        read_callback,
                        data="",
                        method='GET',
                        capture_errors=True):
        """
        Perform a HTTP request.
        :param endpoint: the endpoint to call (i.e. "statistics")
        :param read_callback: the callback to be called with result info when we have the data
        :param data: optional POST data to be sent with the request
        :param method: the HTTP verb (GET/POST/PUT/PATCH)
        :param capture_errors: whether errors should be handled by this class (defaults to True)
        """
        performed_requests[self.request_id] = [
            endpoint, method, data, time(), -1
        ]
        performed_requests_ids.append(self.request_id)
        if len(performed_requests_ids) > 200:
            del performed_requests[performed_requests_ids.pop(0)]
        url = self.base_url + endpoint

        if method == 'GET':
            buf = QBuffer()
            buf.setData(data)
            buf.open(QIODevice.ReadOnly)
            get_request = QNetworkRequest(QUrl(url))
            self.reply = self.sendCustomRequest(get_request, "GET", buf)
            buf.setParent(self.reply)
        elif method == 'PATCH':
            buf = QBuffer()
            buf.setData(data)
            buf.open(QIODevice.ReadOnly)
            patch_request = QNetworkRequest(QUrl(url))
            self.reply = self.sendCustomRequest(patch_request, "PATCH", buf)
            buf.setParent(self.reply)
        elif method == 'PUT':
            request = QNetworkRequest(QUrl(url))
            request.setHeader(QNetworkRequest.ContentTypeHeader,
                              "application/x-www-form-urlencoded")
            self.reply = self.put(request, data)
        elif method == 'DELETE':
            buf = QBuffer()
            buf.setData(data)
            buf.open(QIODevice.ReadOnly)
            delete_request = QNetworkRequest(QUrl(url))
            self.reply = self.sendCustomRequest(delete_request, "DELETE", buf)
            buf.setParent(self.reply)
        elif method == 'POST':
            request = QNetworkRequest(QUrl(url))
            request.setHeader(QNetworkRequest.ContentTypeHeader,
                              "application/x-www-form-urlencoded")
            self.reply = self.post(request, data)

        if read_callback:
            self.received_json.connect(read_callback)

        self.finished.connect(
            lambda reply: self.on_finished(reply, capture_errors))
Exemplo n.º 16
0
 def _close(self, request):
     buffer = QBuffer(self)
     buffer.setData(
         b"<html><head><script>window.close();</script></head></html>")
     request.reply(b"text/html", buffer)
     self.parent().close()
Exemplo n.º 17
0
class EricSchemeReply(QIODevice):
    """
    Class implementing a reply for a requested eric: page.
    
    @signal closed emitted to signal that the web engine has read
        the data
    """
    closed = pyqtSignal()

    _speedDialPage = ""

    def __init__(self, job, parent=None):
        """
        Constructor
        
        @param job reference to the URL request
        @type QWebEngineUrlRequestJob
        @param parent reference to the parent object
        @type QObject
        """
        super(EricSchemeReply, self).__init__(parent)

        self.__loaded = False
        self.__job = job
        self.__mutex = QMutex()

        self.__pageName = self.__job.requestUrl().path()
        self.__buffer = QBuffer()

        self.__loadPage()

    def __loadPage(self):
        """
        Private method to load the requested page.
        """
        if self.__loaded:
            return

        lock = QMutexLocker(self.__mutex)

        if self.__pageName == "adblock":
            contents = self.__adBlockPage()
        elif self.__pageName in ["home", "start", "startpage"]:
            contents = self.__startPage()
        elif self.__pageName == "speeddial":
            contents = self.__speedDialPage()
        else:
            contents = ""

        self.__buffer.setData(contents.encode("utf-8"))
        self.__buffer.open(QIODevice.ReadOnly)
        self.open(QIODevice.ReadOnly)
        lock.unlock()

        self.readyRead.emit()

        self.__loaded = True

    def bytesAvailable(self):
        """
        Public method to get the number of available bytes.
        
        @return number of available bytes
        @rtype int
        """
        lock = QMutexLocker(self.__mutex)  # __IGNORE_WARNING__
        return self.__buffer.bytesAvailable()

    def readData(self, maxlen):
        """
        Public method to retrieve data from the reply object.
        
        @param maxlen maximum number of bytes to read (integer)
        @return string containing the data (bytes)
        """
        lock = QMutexLocker(self.__mutex)  # __IGNORE_WARNING__
        return self.__buffer.read(maxlen)

    def close(self):
        """
        Public method used to cloase the reply.
        """
        super(EricSchemeReply, self).close()
        self.closed.emit()

    def __adBlockPage(self):
        """
        Private method to build the AdBlock page.
        
        @return built AdBlock page
        @rtype str
        """
        query = QUrlQuery(self.__job.requestUrl())
        rule = query.queryItemValue("rule")
        subscription = query.queryItemValue("subscription")
        title = self.tr("Content blocked by AdBlock Plus")
        message = self.tr("Blocked by rule: <i>{0} ({1})</i>").format(
            rule, subscription)

        page = readAllFileContents(":/html/adblockPage.html")
        page = page.replace("@FAVICON@", "qrc:icons/adBlockPlus16.png")
        page = page.replace("@IMAGE@", "qrc:icons/adBlockPlus64.png")
        page = page.replace("@TITLE@", title)
        page = page.replace("@MESSAGE@", message)

        return page

    def __startPage(self):
        """
        Private method to build the Start page.
        
        @return built Start page
        @rtype str
        """
        page = readAllFileContents(":/html/startPage.html")
        page = page.replace("@FAVICON@", "qrc:icons/ericWeb16.png")
        page = page.replace("@IMAGE@", "qrc:icons/ericWeb32.png")
        page = page.replace("@TITLE@",
                            self.tr("Welcome to eric6 Web Browser!"))
        page = page.replace("@ERIC_LINK@", self.tr("About eric6"))
        page = page.replace("@HEADER_TITLE@", self.tr("eric6 Web Browser"))
        page = page.replace("@SUBMIT@", self.tr("Search!"))
        if qApp.isLeftToRight():
            ltr = "LTR"
        else:
            ltr = "RTL"
        page = page.replace("@QT_LAYOUT_DIRECTION@", ltr)

        return page

    def __speedDialPage(self):
        """
        Private method to create the Speeddial page.
        
        @return prepared speeddial page (QByteArray)
        """
        if not self._speedDialPage:
            page = readAllFileContents(":/html/speeddialPage.html")
            page = page.replace("@FAVICON@", "qrc:icons/ericWeb16.png")
            page = page.replace("@IMG_PLUS@", "qrc:icons/plus.png")
            page = page.replace("@IMG_CLOSE@", "qrc:icons/close.png")
            page = page.replace("@IMG_EDIT@", "qrc:icons/edit.png")
            page = page.replace("@IMG_RELOAD@", "qrc:icons/reload.png")
            page = page.replace("@IMG_SETTINGS@", "qrc:icons/setting.png")
            page = page.replace("@LOADING-IMG@", "qrc:icons/loading.gif")
            page = page.replace("@BOX-BORDER@",
                                "qrc:icons/box-border-small.png")

            page = page.replace("@JQUERY@", "qrc:javascript/jquery.js")
            page = page.replace("@JQUERY-UI@", "qrc:javascript/jquery-ui.js")

            page = page.replace("@SITE-TITLE@", self.tr("Speed Dial"))
            page = page.replace("@URL@", self.tr("URL"))
            page = page.replace("@TITLE@", self.tr("Title"))
            page = page.replace("@APPLY@", self.tr("Apply"))
            page = page.replace("@CLOSE@", self.tr("Close"))
            page = page.replace("@NEW-PAGE@", self.tr("New Page"))
            page = page.replace("@TITLE-EDIT@", self.tr("Edit"))
            page = page.replace("@TITLE-REMOVE@", self.tr("Remove"))
            page = page.replace("@TITLE-RELOAD@", self.tr("Reload"))
            page = page.replace(
                "@TITLE-WARN@",
                self.tr("Are you sure to remove this"
                        " speed dial?"))
            page = page.replace(
                "@TITLE-WARN-REL@",
                self.tr("Are you sure you want to reload"
                        " all speed dials?"))
            page = page.replace("@TITLE-FETCHTITLE@",
                                self.tr("Load title from page"))
            page = page.replace("@SETTINGS-TITLE@",
                                self.tr("Speed Dial Settings"))
            page = page.replace("@ADD-TITLE@", self.tr("Add New Page"))
            page = page.replace("@TXT_NRROWS@",
                                self.tr("Maximum pages in a row:"))
            page = page.replace("@TXT_SDSIZE@",
                                self.tr("Change size of pages:"))
            page = page.replace(
                "@JAVASCRIPT_DISABLED@",
                self.tr("SpeedDial requires enabled"
                        " JavaScript."))

            self._speedDialPage = page

        from WebBrowser.WebBrowserWindow import WebBrowserWindow
        dial = WebBrowserWindow.speedDial()
        page = (self._speedDialPage.replace(
            "@INITIAL-SCRIPT@", dial.initialScript()).replace(
                "@ROW-PAGES@",
                str(dial.pagesInRow())).replace("@SD-SIZE@",
                                                str(dial.sdSize())))

        return page
Exemplo n.º 18
0
class HelpSchemeReply(QIODevice):
    """
    Class implementing a reply for a requested qthelp: page.

    The Qt signal *closed* is emitted to signal that the web engine has read the data.

    see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py
    All credits for this class go to:
    Detlev Offenbach, the developer of The Eric Python IDE(https://eric-ide.python-projects.org)

    """
    closed = pyqtSignal()

    def __init__(self, job, engine, parent=None):
        """
        Constructor

        :param job: reference to the URL request
        :type job: QWebEngineUrlRequestJob
        :param engine: reference to the help engine
        :type engine: QHelpEngine
        :param parent: reference to the parent object
        :type parent: QObject
        """
        super(HelpSchemeReply, self).__init__(parent)

        url = job.requestUrl()
        strUrl = url.toString()

        self.__buffer = QBuffer()

        # For some reason the url to load maybe wrong (passed from web engine)
        # though the css file and the references inside should work that way.
        # One possible problem might be that the css is loaded at the same
        # level as the html, thus a path inside the css like
        # (../images/foo.png) might cd out of the virtual folder
        if not engine.findFile(url).isValid():
            if strUrl.startswith(QtHelp_DOCROOT):
                newUrl = job.requestUrl()
                if not newUrl.path().startswith("/qdoc/"):
                    newUrl.setPath("/qdoc" + newUrl.path())
                    url = newUrl
                    strUrl = url.toString()

        self.__mimeType = mimetypes.guess_type(strUrl)[0]
        if self.__mimeType is None:
            # do our own (limited) guessing
            self.__mimeType = self.__mimeFromUrl(url)

        if engine.findFile(url).isValid():
            data = engine.fileData(url)
        else:
            data = QByteArray(self.tr(
                """<html>"""
                """<head><title>Error 404...</title></head>"""
                """<body><div align="center"><br><br>"""
                """<h1>The page could not be found</h1><br>"""
                """<h3>'{0}'</h3></div></body>"""
                """</html>""").format(strUrl)
                              .encode("utf-8"))

        self.__buffer.setData(data)
        self.__buffer.open(QIODevice.ReadOnly)
        self.open(QIODevice.ReadOnly)

    def bytesAvailable(self):
        """
        Public method to get the number of available bytes.

        :returns: number of available bytes
        :rtype: int
        """
        return self.__buffer.bytesAvailable()

    def readData(self, maxlen):
        """
        Public method to retrieve data from the reply object.

        :param maxlen: maximum number of bytes to read (integer)
        :returns: string containing the data (bytes)
        """
        return self.__buffer.read(maxlen)

    def close(self):
        """
        Public method used to close the reply.
        """
        super(HelpSchemeReply, self).close()
        self.closed.emit()

    def __mimeFromUrl(self, url):
        """
        Private method to guess the mime type given an URL.

        :param url: URL to guess the mime type from (QUrl)
        :returns: mime type for the given URL (string)
        """
        path = url.path()
        ext = os.path.splitext(path)[1].lower()
        if ext in ExtensionMap:
            return ExtensionMap[ext]
        else:
            return "application/octet-stream"

    def mimeType(self):
        """
        Public method to get the reply mime type.

        :returns: mime type of the reply
        :rtype: bytes
        """
        return self.__mimeType.encode("utf-8")
Exemplo n.º 19
0
class AudioWidget(QWidget):
    def __init__(self, parent=None):

        QWidget.__init__(self, parent)

        self.format = None
        self.output = None
        self.buffer = QBuffer()

        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(10)
        self.volumeSlider.setPageStep(1)
        self.volumeSlider.setValue(5)

        self.playButton = QPushButton()
        self.playButton.setIcon(QIcon("icons/play.png"))

        self.stopButton = QPushButton()
        self.stopButton.setIcon(QIcon("icons/stop.png"))

        self.volumeSlider.valueChanged.connect(self.change_volume)
        self.playButton.clicked.connect(self.play_pause)
        self.stopButton.clicked.connect(self.stop)

        layout = QHBoxLayout(self)
        layout.addWidget(self.playButton)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.volumeSlider)
        layout.addStretch()

    def stop(self):
        if self.output:
            if self.output.state() != QAudio.StoppedState:
                self.output.stop()

    def set_data(self, mono_sig, sr):
        # if not self.format:
        self.format = QAudioFormat()
        self.format.setChannelCount(1)
        self.format.setSampleRate(sr)
        #numpy is in bites, qt in bits
        self.format.setSampleSize(mono_sig.dtype.itemsize * 8)
        self.format.setCodec("audio/pcm")
        self.format.setByteOrder(QAudioFormat.LittleEndian)
        self.format.setSampleType(QAudioFormat.Float)
        self.output = QAudioOutput(self.format, self)
        self.output.stateChanged.connect(self.audio_state_changed)
        #change the content without stopping playback
        p = self.buffer.pos()
        if self.buffer.isOpen():
            self.buffer.close()

        self.data = mono_sig.tobytes()
        self.buffer.setData(self.data)
        self.buffer.open(QIODevice.ReadWrite)
        self.buffer.seek(p)

    def audio_state_changed(self, new_state):
        #adjust the button icon
        if new_state != QAudio.ActiveState:
            self.playButton.setIcon(QIcon("icons/play.png"))
        else:
            self.playButton.setIcon(QIcon("icons/pause.png"))

    def cursor(self, t):
        #seek towards the time t
        #todo: handle EOF case
        try:
            if self.format:
                t = max(0, t)
                b = self.format.bytesForDuration(t * 1000000)
                self.buffer.seek(b)
        except:
            print("cursor error")

    def play_pause(self):
        if self.output:
            #(un)pause the audio output, keeps the buffer intact
            if self.output.state() == QAudio.ActiveState:
                self.output.suspend()
            elif self.output.state() == QAudio.SuspendedState:
                self.output.resume()
            else:
                self.buffer.seek(0)
                self.output.start(self.buffer)

    def change_volume(self, value):
        if self.output:
            #need to wrap this because slider gives not float output
            self.output.setVolume(value / 10)
Exemplo n.º 20
0
 def reply_template(self, job, tpl_name, data):
     template = self.env.get_template(tpl_name + ".html")
     buffer = QBuffer(self)
     buffer.setData(template.render(**data).encode("utf-8"))
     job.reply(b"text/html", buffer)
Exemplo n.º 21
0
    def receiveMessage(self):
        stream = QTextStream(self.conn)
        if stream.atEnd():
            return
        data = stream.readAll()

        for json_str in data.split("\n")[:-1]:
            obj = json.loads(json_str)
            msgType = obj["type"]
            if msgType == self.TYPE_NOTIFICATION:
                self.log("Notification Received. code: {0}".format(
                    obj["params"].get("code")))
                if obj["params"].get("code") == self.N_DATA_RECEIVED:
                    memKey = obj["params"]["memoryKey"]
                    mem = self._mem[memKey]
                    if mem.isAttached():
                        mem.detach()
                        self.log(
                            "Shared memory detached: key={0}".format(memKey))
                    del self._mem[memKey]
                else:
                    self.notified.emit(obj["params"])

            elif msgType == self.TYPE_REQUEST:
                self.log(
                    "Request Received. dataType: {0}, renderId: {1}".format(
                        obj["params"].get("dataType"),
                        obj["params"].get("renderId")))
                self.requestReceived.emit(obj["params"])

            elif msgType == self.TYPE_RESPONSE:
                self.log(
                    "Response Received. dataType: {0}, renderId: {1}".format(
                        obj["meta"].get("dataType"),
                        obj["meta"].get("renderId")))
                mem = QSharedMemory(obj["memoryKey"])
                if not mem.attach(QSharedMemory.ReadOnly):
                    self.log(
                        "Cannot attach this process to the shared memory segment: {0}"
                        .format(mem.errorString()))
                    return

                size = mem.size()
                self.log("Size of memory segment is {0} bytes.".format(size))

                mem.lock()
                ba = QByteArray()
                buffer = QBuffer(ba)
                buffer.setData(mem.constData())
                mem.unlock()
                mem.detach()

                data = ba.data()
                lines = data.split(b"\n")
                for line in lines[:5]:
                    self.log(line[:76])
                if len(lines) > 5:
                    self.log("--Total {0} Lines Received--".format(len(lines)))

                self.notify({
                    "code": self.N_DATA_RECEIVED,
                    "memoryKey": obj["memoryKey"]
                })
                self.responseReceived.emit(data, obj["meta"])
Exemplo n.º 22
0
class HelpSchemeReply(QIODevice):
    """
    Class implementing a reply for a requested qthelp: page.

    @signal closed emitted to signal that the web engine has read
        the data

    see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py
    All credits for this class go to:
    Detlev Offenbach, the developer of The Eric Python IDE(https://eric-ide.python-projects.org)

    """
    closed = pyqtSignal()

    def __init__(self, job, engine, parent=None):
        """
        Constructor

        @param job reference to the URL request
        @type QWebEngineUrlRequestJob
        @param engine reference to the help engine
        @type QHelpEngine
        @param parent reference to the parent object
        @type QObject
        """
        super(HelpSchemeReply, self).__init__(parent)

        url = job.requestUrl()
        strUrl = url.toString()

        self.__buffer = QBuffer()

        # For some reason the url to load maybe wrong (passed from web engine)
        # though the css file and the references inside should work that way.
        # One possible problem might be that the css is loaded at the same
        # level as the html, thus a path inside the css like
        # (../images/foo.png) might cd out of the virtual folder
        if not engine.findFile(url).isValid():
            if strUrl.startswith(QtHelp_DOCROOT):
                newUrl = job.requestUrl()
                if not newUrl.path().startswith("/qdoc/"):
                    newUrl.setPath("/qdoc" + newUrl.path())
                    url = newUrl
                    strUrl = url.toString()

        self.__mimeType = mimetypes.guess_type(strUrl)[0]
        if self.__mimeType is None:
            # do our own (limited) guessing
            self.__mimeType = self.__mimeFromUrl(url)

        if engine.findFile(url).isValid():
            data = engine.fileData(url)
        else:
            data = QByteArray(self.tr(
                """<html>"""
                """<head><title>Error 404...</title></head>"""
                """<body><div align="center"><br><br>"""
                """<h1>The page could not be found</h1><br>"""
                """<h3>'{0}'</h3></div></body>"""
                """</html>""").format(strUrl)
                              .encode("utf-8"))

        self.__buffer.setData(data)
        self.__buffer.open(QIODevice.ReadOnly)
        self.open(QIODevice.ReadOnly)

    def bytesAvailable(self):
        """
        Public method to get the number of available bytes.

        @return number of available bytes
        @rtype int
        """
        return self.__buffer.bytesAvailable()

    def readData(self, maxlen):
        """
        Public method to retrieve data from the reply object.

        @param maxlen maximum number of bytes to read (integer)
        @return string containing the data (bytes)
        """
        return self.__buffer.read(maxlen)

    def close(self):
        """
        Public method used to cloase the reply.
        """
        super(HelpSchemeReply, self).close()
        self.closed.emit()

    def __mimeFromUrl(self, url):
        """
        Private method to guess the mime type given an URL.

        @param url URL to guess the mime type from (QUrl)
        @return mime type for the given URL (string)
        """
        path = url.path()
        ext = os.path.splitext(path)[1].lower()
        if ext in ExtensionMap:
            return ExtensionMap[ext]
        else:
            return "application/octet-stream"

    def mimeType(self):
        """
        Public method to get the reply mime type.

        @return mime type of the reply
        @rtype bytes
        """
        return self.__mimeType.encode("utf-8")
Exemplo n.º 23
0
class Window(QWidget):
    def __init__(self, parent=None):

        QWidget.__init__(self, parent)

        format = QAudioFormat()
        format.setChannelCount(1)
        format.setSampleRate(22050)
        format.setSampleSize(16)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)
        self.output = QAudioOutput(format, self)

        self.frequency = 440
        self.volume = 0
        self.buffer = QBuffer()
        self.data = QByteArray()

        self.deviceLineEdit = QLineEdit()
        self.deviceLineEdit.setReadOnly(True)
        self.deviceLineEdit.setText(
            QAudioDeviceInfo.defaultOutputDevice().deviceName())

        self.pitchSlider = QSlider(Qt.Horizontal)
        self.pitchSlider.setMaximum(100)
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(32767)
        self.volumeSlider.setPageStep(1024)

        self.playButton = QPushButton(self.tr("&Play"))

        self.pitchSlider.valueChanged.connect(self.changeFrequency)
        self.volumeSlider.valueChanged.connect(self.changeVolume)
        self.playButton.clicked.connect(self.play)

        formLayout = QFormLayout()
        formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
        formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
        formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)

        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.playButton)
        buttonLayout.addStretch()

        horizontalLayout = QHBoxLayout(self)
        horizontalLayout.addLayout(formLayout)
        horizontalLayout.addLayout(buttonLayout)

        self.play()
        self.createData()

    def changeFrequency(self, value):

        self.frequency = 440 + (value * 2)
        self.createData()

    def play(self):

        if self.output.state() == QAudio.ActiveState:
            self.output.stop()

        if self.buffer.isOpen():
            self.buffer.close()

        if self.output.error() == QAudio.UnderrunError:
            self.output.reset()

        self.buffer.setData(self.data)
        self.buffer.open(QIODevice.ReadOnly)
        self.buffer.seek(0)

        self.output.start(self.buffer)

    def changeVolume(self, value):

        self.volume = value
        self.createData()

    def createData(self):

        self.data.clear()
        for i in range(2 * 22050):
            t = i / 22050.0
            value = int(self.volume * sin(2 * pi * self.frequency * t))
            self.data.append(struct.pack("<h", value))