Exemplo n.º 1
0
def main():
    import sys

    app = QCoreApplication(sys.argv)  # noqa: F841
    f = QFile()
    f.open(sys.stdout.fileno(), QIODevice.WriteOnly)
    out = QTextStream(f)
    serialPortInfos = QSerialPortInfo.availablePorts()

    out << "Total number of ports available: " << len(serialPortInfos) << "\n"

    blankString = "N/A"
    description = ""
    manufacturer = ""
    serialNumber = ""

    for serialPortInfo in serialPortInfos:
        description = serialPortInfo.description()
        manufacturer = serialPortInfo.manufacturer()
        serialNumber = serialPortInfo.serialNumber()
        out << "\nPort: " << serialPortInfo.portName(
        ) << "\nLocation: " << serialPortInfo.systemLocation(
        ) << "\nDescription: " << (  # noqa: E501
            description if description else blankString
        ) << "\nManufacturer: " << (
            manufacturer
            if manufacturer else blankString) << "\nSerial number: " << (
                serialNumber if serialNumber else blankString
            ) << "\nVendor Identifier: " << (
                QByteArray.number(serialPortInfo.vendorIdentifier(), 16)
                if serialPortInfo.hasVendorIdentifier() else blankString
            ) << "\nProduct Identifier: " << (
                QByteArray.number(serialPortInfo.productIdentifier(), 16) if
                serialPortInfo.hasProductIdentifier() else blankString) << "\n"
Exemplo n.º 2
0
def embeded_image_scale_to_width(src_path, width_scalar):
    qimage = QImage(src_path)
    new_width = width_scalar * qimage.width()
    qimage = qimage.scaledToWidth(new_width, Qt.SmoothTransformation)
    data = QByteArray()
    buffer = QBuffer(data)
    buffer.open(QIODevice.WriteOnly)
    qimage.save(buffer, "JPG")
    base64_data = data.toBase64().data().decode('ascii')
    return "data:image/jpeg;base64,{base64_data}".format(
        base64_data=base64_data)
Exemplo n.º 3
0
    def requestStarted(self, job: QWebEngineUrlRequestJob) -> None:
        webUiOrigin = QUrl(SCHEMENAME + ":")
        GET: QByteArray = QByteArray(b"GET")
        POST: QByteArray = QByteArray(b"POST")

        method = job.requestMethod()
        url = job.requestUrl()
        initiator = job.initiator()
        if method == GET and url == WebUiHandler.aboutUrl:
            f = QFile(":/about.html", job)
            f.open(QIODevice.ReadOnly)
            job.reply(b"text/html", f)
        elif (method == POST and url == WebUiHandler.aboutUrl
              and initiator == webUiOrigin):
            job.fail(QWebEngineUrlRequestJob.RequestAborted)
            QApplication.exit()
        else:
            job.fail(QWebEngineUrlRequestJob.UrlNotFound)
Exemplo n.º 4
0
    def startDrag(self, supported_actions):
        """
        Function that is called when we start dragging an item
        This function set ups the mime data and creates a copy of the image
        of the item that is show in cursor position while dragging action
        is enabled
        """

        index = self.currentIndex()
        model = self.model()
        item = model.itemFromIndex(index)
        drag = QDrag(self)
        mime_data = QMimeData()
        mime_data.setData('item_text', QByteArray(str(item.text())))
        mime_data.setData('item_size', QByteArray('%.1f %.1f' % (item.size.width(), item.size.height())))
        url = QUrl.fromLocalFile(item.text())
        mime_data.setUrls(url)
        drag.setMimeData(mime_data)
        pixmap = item.icon().pixmap(50, 50)
        drag.setDragCursor(pixmap, Qt.CopyAction)
        drag.start()
Exemplo n.º 5
0
    def updateClientProgress(self, numBytes):
        self.bytesWritten += int(numBytes)

        if self.bytesToWrite > 0 and self.tcpClient.bytesToWrite() <= 4 * PAYLOAD_SIZE:
            self.bytesToWrite -= self.tcpClient.write(
                QByteArray(min(self.bytesToWrite, PAYLOAD_SIZE), "@")
            )

        self.clientProgressBar.setMaximum(TOTAL_BYTES)
        self.clientProgressBar.setValue(self.bytesWritten)
        self.clientStatusLabel.setText(
            self.tr("Sent %dMB" % (self.bytesWritten / (1024 * 1024),))
        )
Exemplo n.º 6
0
def base64_to_image(base64_string, image_format='PNG'):
    """
    Converts base64 to QImage
    :param base64_string: str
    :param image_format: str
    :return: QImage
    """

    try:
        ba = QByteArray.fromBase64(base64_string)
        image = QImage.fromData(ba, image_format)
        return image
    except Exception:
        return None
Exemplo n.º 7
0
    def sendFortune(self):
        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_5_10)

        message = random.choice(self.fortunes)
        out.writeUInt32(len(message))
        out.writeQString(message)

        clientConnection = self.server.nextPendingConnection()
        clientConnection.disconnected.connect(clientConnection.deleteLater)

        clientConnection.write(block)
        clientConnection.flush()
        clientConnection.disconnectFromServer()
Exemplo n.º 8
0
    def _render_svg(self, svg_path, replace_color=None):
        if issubclass(self._cls, QIcon) and not replace_color:
            return QIcon(svg_path)

        with open(svg_path, 'r+') as f:
            data_content = f.read()
            if replace_color is not None:
                data_content = data_content.replace('#555555', replace_color)
                self._render.load(QByteArray(data_content))
                pix = QPixmap(128, 128)
                pix.fill(Qt.transparent)
                painter = QPainter(pix)
                self._render.render(painter)
                painter.end()
                if issubclass(self._cls, QPixmap):
                    return pix
                else:
                    return self._cls(pix)
Exemplo n.º 9
0
    def _write(self, reply_dict):
        try:
            json_reply = json.dumps(reply_dict)
        except Exception:
            msg = 'Error while serializing data: "{}"'.format(
                traceback.format_exc())
            logger.error(msg)
            json_dict = {
                'result': None,
                'success': False,
                'msg': msg,
                'cmd': reply_dict.get('cmd', 'unknown')
            }
            json_reply = json.dumps(json_dict)

        if self._socket and self._socket.state() == QTcpSocket.ConnectedState:
            header = '{0}'.format(len(json_reply.encode())).zfill(
                DccServer.HEADER_SIZE)
            data = QByteArray('{}{}'.format(header, json_reply).encode())
            self._socket.write(data)

        return json_reply
Exemplo n.º 10
0
 def startTransfer(self):
     # called when the TCP client connected to the loopback server
     self.bytesToWrite = TOTAL_BYTES - int(
         self.tcpClient.write(QByteArray(PAYLOAD_SIZE, "@"))
     )
     self.clientStatusLabel.setText(self.tr("Connected"))
Exemplo n.º 11
0
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                try:
                    result[key] = chr(int(obj[key], 16))
                except ValueError:
                    if int(obj[key], 16) > 0xffff:
                        # ignoring unsupported code in Python 2.7 32bit Windows
                        # ValueError: chr() arg not in range(0x10000)
                        pass
                    else:
                        raise FontError(u'Failed to load character '
                                        '{0}:{1}'.format(key, obj[key]))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            with open(os.path.join(directory, ttf_filename),
                      'rb') as font_data:
                id_ = QFontDatabase.addApplicationFontFromData(
                    QByteArray(font_data.read()))
            font_data.close()

            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)

            if loadedFontFamilies:
                self.fontids[prefix] = id_
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                ttf_hash = MD5_HASHES.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                            os.path.join(directory, ttf_filename)))