def on_caImportButton_clicked(self):
        """
        Private slot to import server certificates.
        """
        certs = self.__importCertificate()
        if certs:
            caCerts = self.__getSystemCaCertificates()
            for cert in certs:
                if cert in caCerts:
                    if qVersion() >= "5.0.0":
                        commonStr = ", ".join(cert.subjectInfo(QSslCertificate.CommonName))
                    else:
                        commonStr = cert.subjectInfo(QSslCertificate.CommonName)
                    E5MessageBox.warning(
                        self,
                        self.tr("Import Certificate"),
                        self.tr("""<p>The certificate <b>{0}</b> already exists.""" """ Skipping.</p>""").format(
                            Utilities.decodeString(commonStr)
                        ),
                    )
                else:
                    caCerts.append(cert)

            pems = QByteArray()
            for cert in caCerts:
                pems.append(cert.toPem() + "\n")
            Preferences.Prefs.settings.setValue("Help/SystemCertificates", pems)

            self.caCertificatesTree.clear()
            self.__populateCaCertificatesTree()

            self.__updateDefaultConfiguration()
Example #2
0
 def exportCookies(self):
     cookiesArray = QByteArray()
     cookieList = self.allCookies()
     for cookie in cookieList:
         cookiesArray.append( bytes(cookie.toRawForm()).decode('utf-8') + "\n" ) # cookie.ToRawForm() returns ByteArray
     settings = QSettings('quartz-browser', 'cookies', self)
     settings.setValue("Cookies", cookiesArray)
    def doRequestCancelOrder(self):
        # Update the Loading Text
        self.messageLabel.setText("Update Order")
        QCoreApplication.processEvents()

        temp = {
            'paymentID': 0,
            'amount': self.totalPrice,
            'orderStatus': "canceled"
        }

        data = QByteArray()
        data.append(json.dumps(temp))

        # print("DO REQUEST CANCEL ORDER:")
        # print(data)
        self.mylogger.debug("Req Cancel Order: {}".format(data))

        setting = QSettings()
        url = setting.value("baseURL", "")
        url += "/order/" + str(self.orderID) + "/"
        # print("URL: {}".format(url))
        # url = "http://127.0.0.1:8000/api/order/"

        req = QtNetwork.QNetworkRequest(QUrl(url))
        req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader,
                      "application/json")

        reply = self.nam.put(req, data)
        reply.finished.connect(self.handleResponseCancelOrder)
class BufferQueueIO(QIODevice):
    def __init__(self, bufQ, parent):
        super(BufferQueueIO, self).__init__(parent)
        self.buffer = QByteArray()
        self.bufQ = bufQ

    def start(self):
        self.open(QIODevice.ReadOnly)

    def stop(self):
        self.m_pos = 0
        self.close()

    def readData(self, maxlen):
        if self.bufQ.qsize() >= 2:
            self.buffer.append(self.bufQ.get())

        if self.buffer.length() < maxlen:
            # FIXME, return correct length QByteArray of zeros
            return QByteArray(bytearray((0, ) * 10)).data()
        else:
            outp = self.buffer.mid(0, maxlen).data()
            self.buffer.remove(0, maxlen)
            return outp

    def writeData(self, data):
        return 0

    def bytesAvailable(self):
        return self.m_buffer.size() + super(BufferQueueIO,
                                            self).bytesAvailable()
    def doRequestOrderDetail(self):
        # print(self.orderList)

        # Update the Loading Text
        self.messageLabel.setText("Memproses Order (2/2)")
        QCoreApplication.processEvents()

        # Add Order ID value to each of item in orderList
        for item in self.orderList:
            item['orderID'] = str(self.orderID)

        data = QByteArray()
        data.append(json.dumps(self.orderList))

        # print("DO REQUEST ORDER DETAIL:")
        # print(data)
        self.mylogger.debug("Req OrderDetail: {}".format(data))

        setting = QSettings()
        url = setting.value("baseURL", "")
        url += "/orderdetail/"

        req = QtNetwork.QNetworkRequest(QUrl(url))
        req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader,
                      "application/json")

        reply = self.nam.post(req, data)
        reply.finished.connect(self.handleResponseOrderDetail)
 def on_caImportButton_clicked(self):
     """
     Private slot to import server certificates.
     """
     certs = self.__importCertificate()
     if certs:
         caCerts = self.__getSystemCaCertificates()
         for cert in certs:
             if cert in caCerts:
                 if qVersion() >= "5.0.0":
                     commonStr = ", ".join(
                         cert.subjectInfo(QSslCertificate.CommonName))
                 else:
                     commonStr = cert.subjectInfo(
                         QSslCertificate.CommonName)
                 E5MessageBox.warning(
                     self,
                     self.tr("Import Certificate"),
                     self.tr(
                         """<p>The certificate <b>{0}</b> already exists."""
                         """ Skipping.</p>""")
                     .format(Utilities.decodeString(commonStr)))
             else:
                 caCerts.append(cert)
         
         pems = QByteArray()
         for cert in caCerts:
             pems.append(cert.toPem() + '\n')
         Preferences.Prefs.settings.setValue(
             "Help/SystemCertificates", pems)
         
         self.caCertificatesTree.clear()
         self.__populateCaCertificatesTree()
         
         self.__updateDefaultConfiguration()
Example #7
0
    def mimeData(self, indices):
        '''For drag/drop docs into folders'''

        LOGGER.debug('header data = %s' % self.headerdata)
        LOGGER.debug('indices = %s' % indices)

        for idii in indices:
            LOGGER.debug('idii.row() = %s, idii.column() = %s, idii.data() = %s'\
                    %(idii.row(), idii.column(), idii.data()))

        ids = [ii for ii in indices if ii.isValid()]
        LOGGER.debug('ids = %s' % ids)

        rowids = [ii.row() for ii in ids]
        rowids = list(set(rowids))
        LOGGER.debug('rowids = %s' % rowids)

        encode_data = [str(self.arraydata[ii][0]) for ii in rowids]
        encode_data = ', '.join(encode_data)
        LOGGER.debug('encode_data = %s, type() = %s' %
                     (encode_data, type(encode_data)))

        encode_data_array = QByteArray()
        encode_data_array.append(encode_data)

        mimedata = QMimeData()
        mimedata.setData('doc_table_item', encode_data_array)

        return mimedata
Example #8
0
    def upload(self):
        data = {
            "name": self.nameLineEdit.text(),
            "price": int(self.priceLineEdit.text()),
            "category": self.getCategory(),
            "availability": self.availabilityCheckBox.isChecked(),
            "qtyAvailable": int(self.qtyAvailableLineEdit.text()),
            # "qtyOnBooked": int(self.qtyOnBookedLineEdit.text()),
            "sellerID": str(self.setting.value("sellerID", ""))
        }

        url = self.setting.value("baseURL", "")
        url += "/menu/"

        if self.menuItem is not None:
            url += str(self.menuItem.id) + "/"

        path = self.filename

        files = {"image": path}

        multipart = self.construct_multipart(data, files)
        request = QNetworkRequest(QUrl(url))

        mode = QByteArray()
        if not self.menuItem:
            mode.append("POST")
        else:
            mode.append("PATCH")

        reply = self.manager.sendCustomRequest(request, mode, multipart)
        reply.finished.connect(self.handleResponseMenu)
        multipart.setParent(reply)
Example #9
0
class TcpSocket(QTcpSocket):
    getMsgSignal = pyqtSignal(str)  # 获取到一条消息(粘包处理后)

    def __init__(self, parent=None):
        super().__init__(parent)

        self.buffer = QByteArray()  # 接收消息的缓冲区
        self.headLen = 4  # 包头大小
        self.msgLen = 0  # 包身大小

        self.readyRead.connect(self.getMsg)

    # 发送消息
    def writeMsg(self, msg):
        if type(msg) == str:
            sendMsg = QByteArray()
            out = QDataStream(sendMsg, QIODevice.WriteOnly)
            out.setVersion(QDataStream.Qt_5_9)  # 注意发送和接收的版本的一致
            out.writeInt32(len(msg) *
                           2)  # QDataStream写入的QByteArray一个字符占两个字节,双字节占位
            out.writeQString(msg)
            self.write(sendMsg)

    # 获取消息(粘包处理)
    def getMsg(self):
        self.buffer.append(self.readAll())
        totalLen = self.buffer.size()
        while totalLen:
            in_ = QDataStream(self.buffer, QIODevice.ReadOnly)
            in_.setVersion(QDataStream.Qt_5_9)

            if self.msgLen == 0:
                if totalLen >= self.headLen:
                    self.msgLen = in_.readInt32()
                    if totalLen >= self.headLen + self.msgLen:
                        msg = ""
                        msg = in_.readQString()
                        self.getMsgSignal.emit(msg)
                        # 注意4个字节是QDataStream操作QByteArray写入的时候默认写入头部的QByteArray大小,占4个字节
                        self.buffer = self.buffer.right(totalLen -
                                                        self.headLen -
                                                        self.msgLen - 4)
                        self.msgLen = 0
                        totalLen = self.buffer.size()
                    else:
                        break
                else:
                    break
            else:
                if totalLen >= self.headLen + self.msgLen:
                    in_.readInt32()
                    msg = ""
                    msg = in_.readQString()
                    self.getMsgSignal.emit(msg)
                    self.buffer = self.buffer.right(totalLen - self.headLen -
                                                    self.msgLen - 4)
                    self.msgLen = 0
                    totalLen = self.buffer.size()
                else:
                    break
Example #10
0
 def set_is_connected(self):
     username = self.register_dialog.get_username()
     avatar = self.register_dialog.get_avatar()
     qmessage = QByteArray()
     qmessage.append("%s@%d\n" % (username, avatar))
     self.socket.write(qmessage)
     self.register_dialog.setVisible(False)
Example #11
0
 def send_message(self, step):
     print("send")
     message = step.to_string()
     qmessage = QByteArray()
     qmessage.append(message)
     print(message)
     self.socket.write(qmessage)
Example #12
0
class TcpSocket(QTcpSocket):
    getMsgSignal = pyqtSignal(str)  # 粘包处理之后获取的一条完整信息发送出去的信号

    def __init__(self, parent=None):
        super().__init__(parent)

        self.buffer = QByteArray()  # 接收消息缓冲区
        self.headLen = 4  # 包头大小
        self.msgLen = 0  # 包身大小

        self.readyRead.connect(self.getMsg)

    # 发送信息(粘包处理)
    def writeMsg(self, msg):
        if type(msg) == str:
            sendMsg = QByteArray()
            out = QDataStream(sendMsg, QIODevice.WriteOnly)
            out.setVersion(QDataStream.Qt_5_9)
            out.writeInt32(len(msg) * 2)  # 写入包头,内容为后面的消息长
            out.writeQString(msg)  # 写入消息
            self.write(sendMsg)

    # 每当有消息在socket缓冲区内可读取的时候
    # 读取信息包括粘包处理
    def getMsg(self):
        self.buffer.append(self.readAll())
        totalLen = self.buffer.size()
        while totalLen:
            in_ = QDataStream(self.buffer, QIODevice.ReadOnly)
            in_.setVersion(QDataStream.Qt_5_9)

            if self.msgLen == 0:
                if totalLen >= self.headLen:
                    self.msgLen = in_.readInt32()
                    if totalLen >= self.headLen + self.msgLen:
                        msg = ""
                        msg = in_.readQString()
                        self.getMsgSignal.emit(msg)
                        self.buffer = self.buffer.right(totalLen -
                                                        self.headLen -
                                                        self.msgLen - 4)
                        self.msgLen = 0
                        totalLen = self.buffer.size()
                    else:
                        break
                else:
                    break
            else:
                if totalLen >= self.headLen + self.msgLen:
                    in_.readInt32()
                    msg = ""
                    msg = in_.readQString()
                    self.getMsgSignal.emit(msg)
                    self.buffer = self.buffer.right(totalLen - self.headLen -
                                                    self.msgLen - 4)
                    self.msgLen = 0
                    totalLen = self.buffer.size()
                else:
                    break
Example #13
0
 def run_thread(self):
     while True:
         print("while")
         recv_bytes = self.udp_socket.recv(1024)
         if recv_bytes:
             q_recv_array = QByteArray()
             q_recv_array.append(recv_bytes)
             self.sig_udp_agent_recv_network_msg.emit(q_recv_array)
Example #14
0
 def broad_cast(self, step):
     print("broading cast")
     for user_index, socket in enumerate(self.sockets):
         if step.action == "setup user":
             step.work_user = user_index
         qmessage = QByteArray()
         qmessage.append(step.to_string())
         socket.write(qmessage)
Example #15
0
 def mkMimeDez(self, strip):
     racked, index = self._findStripIndex(lambda s: s is strip)
     str_data = '%d %d' % (index.row(),
                           index.column()) if racked else str(index)
     data = QByteArray()
     data.append(str_data.encode('utf8'))
     mime = QMimeData()
     mime.setData(strip_mime_type, data)
     return mime
Example #16
0
 def post_data_to_array(self, post_data):
     post_params = QByteArray()
     for (key, value) in post_data.items():
         if isinstance(value, list):
             for val in value:
                 post_params.append(key + "=" + val + "&")
         else:
             post_params.append(key + "=" + value + "&")
     post_params.remove(post_params.length() - 1, 1)
     return post_params
Example #17
0
class ComPortClass(QObject):
    def __init__(self):

        self.SerialPort = QtSerialPort.QSerialPort()
        self.SerialPort.setBaudRate(115200)
        self.SerialPort.setPortName("COM8")
        self.SerialPort.readyRead.connect(self.ReadData)

        self.DATA_WAIT_SIZE = 0
        self.DATA_BUFFER = QByteArray()
        self.DATA_MESSAGE = QByteArray()
        self.FLAG_WAIT_DATA = False
    def OpenPort(self):
        result = self.SerialPort.open(QtSerialPort.QSerialPort.ReadWrite)
        print(" PORT - ",self.SerialPort.portName()," OPENED")


        #self.Window.ui.ButtonOpenPort.clicked.connect(self.OpenPort)
        #self.Window.ui.ButtonSendData.clicked.connect(self.TestCOMConnection)
        #self.Window.ui.ButStepMotorRight.clicked.connect(lambda: self.MotorControl.MoveStepMotor(NumberMotor=0,Direction=1))
        #self.Window.ui.ButStepMotorLeft.clicked.connect(lambda: self.MotorControl.MoveStepMotor(NumberMotor=1,Direction=-1))


    def TestCOMConnection(self):
        self.HEADER_DATA = bytearray.fromhex("A1 F1 00")
        COMMAND_HEADER = bytearray.fromhex("01")
        self.DATA = COMMAND_HEADER + bytearray("TEST MESSAGE","utf-8")
        self.HEADER_DATA[2] = len(self.DATA)
        result = self.SerialPort.write(self.HEADER_DATA)
        result = self.SerialPort.write(self.DATA)
        print("SEND MESSAGE - ",self.DATA)

    def ClosePort(self):
        result = self.SerialPort.close()

    def ReadData(self):
        New_Data = self.SerialPort.readAll()
        self.DATA_BUFFER.append(New_Data)
        #print("BUFFER -  " ,self.DATA_BUFFER.toHex(),"SIZE - ",self.DATA_BUFFER.length(),"WAIT - ",self.DATA_WAIT_SIZE)

        while(self.DATA_BUFFER.length() >= 3):

            if(self.DATA_BUFFER[0] == b'\xF1' and self.DATA_BUFFER[1] == b'\xA1'):
                self.DATA_WAIT_SIZE = self.DATA_BUFFER[2][0]
                self.DATA_BUFFER.remove(0,3)

            if(self.DATA_BUFFER.length() >= self.DATA_WAIT_SIZE):
                self.DATA_MESSAGE.clear()
                self.DATA_MESSAGE.append(self.DATA_BUFFER)
                self.DATA_BUFFER.remove(0,self.DATA_WAIT_SIZE)
                self.DATA_MESSAGE.truncate(self.DATA_WAIT_SIZE)
                print(self.DATA_BUFFER.toHex())
                self.Window.AddText("    " + self.DATA_MESSAGE.data().decode(encoding="utf-8"),0)
            else:
                break;
Example #18
0
    def readData(self, maxlen):
        data = QByteArray()
        total = 0

        while maxlen > total:
            chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total)
            data.append(self.m_buffer.mid(self.m_pos, chunk))
            self.m_pos = (self.m_pos + chunk) % self.m_buffer.size()
            total += chunk

        return data.data()
Example #19
0
    def readData(self, maxlen):
        data = QByteArray()
        total = 0

        while maxlen > total:
            chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total)
            data.append(self.m_buffer.mid(self.m_pos, chunk))
            self.m_pos = (self.m_pos + chunk) % self.m_buffer.size()
            total += chunk

        return data.data()
Example #20
0
 def testThread(self):
     i = 0
     array = QByteArray()
     while i <= 255:
         array.append('(')
         array.append(chr(i))
         #self.senderMonitor.append("Iterator:  {0}, chr(i):  {1}".format(i, chr(i)))
         self.senderMonitor.append(str(i))
         print("Iterator:  {0}, chr(i):  {1}".format(i, chr(i)))
         monitor.serialWrite(array)
         time.sleep(0.08)
         i += 1
         array.clear()
Example #21
0
    def start_upload(self,save_path,file_path):
        self.upload_file_path = file_path
        self.upload_file_save_path = save_path
        self.is_uploading = True
        data = QByteArray()
        with open(file_path, 'rb') as f:
            data.append(f.read())

        self.upload_start_time = time.time()
        self.upload_http_request = HttpRequest(self,"http://%s/upload"%(self.printer_ip),{},self.on_upload_result,self.on_upload_error, data, self.on_upload_progress)
        self.upload_http_request.set_header("path", save_path)
        self.upload_http_request.run()
        self.dialog_uploading_ui["lb_uploading_filename"].setProperty('text', "Filename: "+os.path.basename(file_path))
Example #22
0
	def ResetArduino(self):
		odp = QMessageBox.question(self,
									"Pytanie", "Czy na pewno? ",
									QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
		if odp == QMessageBox.Yes:
			array = QByteArray()
			array.append('*')
			monitor.serialWrite(array)
			
			time.sleep(3)
			
			thread = threading.Thread(target = self.default)
			#thread = threading.Thread(target = self.test)
			thread.start()
Example #23
0
 def add(self, cookie_dict, scheme, hostname, path="/"):
     cookie_list = []
     for key, value in cookie_dict.items():
         cookie = QNetworkCookie()
         cookie.setDomain(hostname)
         cookie.setPath(path)
         key_b = QByteArray()
         key_b.append(key)
         cookie.setName(key_b)
         value_b = QByteArray()
         value_b.append(value)
         cookie.setValue(value_b)
         cookie_list.append(cookie)
     self._cookie_jar.setCookiesFromUrl(cookie_list, QUrl(str(scheme)))
Example #24
0
 def on_serversDeleteButton_clicked(self):
     """
     Private slot to delete the selected server certificate.
     """
     itm = self.serversCertificatesTree.currentItem()
     res = E5MessageBox.yesNo(
         self,
         self.tr("Delete Server Certificate"),
         self.tr("""<p>Shall the server certificate really be"""
                 """ deleted?</p><p>{0}</p>"""
                 """<p>If the server certificate is deleted, the"""
                 """ normal security checks will be reinstantiated"""
                 """ and the server has to present a valid"""
                 """ certificate.</p>""")
         .format(itm.text(0)))
     if res:
         server = itm.text(1)
         cert = self.serversCertificatesTree.currentItem().data(
             0, self.CertRole)
         
         # delete the selected entry and its parent entry,
         # if it was the only one
         parent = itm.parent()
         parent.takeChild(parent.indexOfChild(itm))
         if parent.childCount() == 0:
             self.serversCertificatesTree.takeTopLevelItem(
                 self.serversCertificatesTree.indexOfTopLevelItem(parent))
         
         # delete the certificate from the user certificate store
         certificateDict = Preferences.toDict(
             Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
         if server in certificateDict:
             certs = QSslCertificate.fromData(certificateDict[server])
             if cert in certs:
                 certs.remove(cert)
             if certs:
                 pems = QByteArray()
                 for cert in certs:
                     pems.append(cert.toPem() + '\n')
                 certificateDict[server] = pems
             else:
                 del certificateDict[server]
         Preferences.Prefs.settings.setValue(
             "Ssl/CaCertificatesDict",
             certificateDict)
         
         # delete the certificate from the default certificates
         self.__updateDefaultConfiguration()
 def on_serversDeleteButton_clicked(self):
     """
     Private slot to delete the selected server certificate.
     """
     itm = self.serversCertificatesTree.currentItem()
     res = E5MessageBox.yesNo(
         self,
         self.tr("Delete Server Certificate"),
         self.tr("""<p>Shall the server certificate really be"""
                 """ deleted?</p><p>{0}</p>"""
                 """<p>If the server certificate is deleted, the"""
                 """ normal security checks will be reinstantiated"""
                 """ and the server has to present a valid"""
                 """ certificate.</p>""")
         .format(itm.text(0)))
     if res:
         server = itm.text(1)
         cert = self.serversCertificatesTree.currentItem().data(
             0, self.CertRole)
         
         # delete the selected entry and its parent entry,
         # if it was the only one
         parent = itm.parent()
         parent.takeChild(parent.indexOfChild(itm))
         if parent.childCount() == 0:
             self.serversCertificatesTree.takeTopLevelItem(
                 self.serversCertificatesTree.indexOfTopLevelItem(parent))
         
         # delete the certificate from the user certificate store
         certificateDict = Globals.toDict(
             Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
         if server in certificateDict:
             certs = QSslCertificate.fromData(certificateDict[server])
             if cert in certs:
                 certs.remove(cert)
             if certs:
                 pems = QByteArray()
                 for cert in certs:
                     pems.append(cert.toPem() + '\n')
                 certificateDict[server] = pems
             else:
                 del certificateDict[server]
         Preferences.Prefs.settings.setValue(
             "Ssl/CaCertificatesDict",
             certificateDict)
         
         # delete the certificate from the default certificates
         self.__updateDefaultConfiguration()
Example #26
0
    def post(self, request, query):
        self.logger.debug('post url=%s query=%s' %
                          (request.url().toString(), query))

        if self.sslSupported and self.sslEnabled:
            request.setSslConfiguration(self.sslConfig)

        bytearray = QByteArray()
        bytearray.append(query)

        reply = self.mgr.post(request, bytearray)

        if self.sslSupported and self.sslEnabled:
            self.mgr.sslErrors.connect(self.handleSSLErrors)

        return reply
Example #27
0
 def handle_input(self, ):
     # send input to external program
     # Note that Qprocess.write() takes bytes input
     if self.ans is None:
         ans = self.input.text()
     else:
         ans = self.ans
     a = QByteArray()
     a.append(ans + '\n')  # input must end with newline
     if self.p:  #process is not finished
         if self.p.state() == 2:  #process is ready
             #self.handle_stdout()
             self.p.write(a)
             self.message(ans + ' is sent to program')
             #--clear entered input
             self.input.clear()
Example #28
0
 def saveFile(self):
     if self.filename is '':
         self.filename = QFileDialog.getSaveFileName(self.piirtoalusta)[0]
     if self.filename is not '':
         items = self.piirtoalusta.scene.items()
         if '.txt' not in self.filename:
             self.filename = "".join((self.filename, '.txt'))
         textfile = QSaveFile(self.filename)
         textfile.open(QIODevice.WriteOnly | QIODevice.Text)
         output = QByteArray()
         items = self.piirtoalusta.scene.items()
         save = Save(items)
         output.append(save.content)
         textfile.write(output)
         textfile.commit()
         return save.content
Example #29
0
    def __export_cells_as_table(self):
        """Copy tasks and time cells as html table."""
        model = self.result_view.model()

        table_text = '<html><head>'
        table_text += '<meta http-equiv="content-type" '
        table_text += 'content="text/html; charset=utf-8">'
        table_text += '</head><body>'
        table_text += '<table cellpadding="0" cellspacing="0" border="0" '
        table_text += 'style="width:100%;">'

        table_text += '<tr>'
        table_text += ('<th style="border:2px solid black;'
                       'margin:0;padding:2px;text-align:center;'
                       'background-color:#ddd;">' + self.tr('Task') + '</th>')
        table_text += ('<th style="border:2px solid black;'
                       'margin:0;padding:2px;text-align:center;'
                       'background-color:#ddd;width:20%;">' + self.tr('Time') +
                       '</th>')
        table_text += '</tr>'

        rows = model.rowCount()
        columns_to_export = (ResultColumn.Task.value, ResultColumn.Time.value)

        for i in range(0, rows):
            table_text += '<tr>'
            for j in columns_to_export:
                content = model.data(model.index(i, j), Qt.DisplayRole)
                if j == 0:
                    table_text += ('<td style="border:2px solid black;'
                                   'margin:0;padding:2px;text-align:left;">'
                                   '{}</td>').format(content)
                else:
                    table_text += ('<td style="border:2px solid black;'
                                   'margin:0;padding:2px;text-align:center;'
                                   'width:20%;">{}</td>').format(content)
            table_text += '</tr>'

        table_text += '</tr></table></body></html>'

        clipboard = QApplication.clipboard()
        mime_data = QMimeData()
        bytes_array = QByteArray()
        bytes_array.append(table_text)
        mime_data.setData('text/html', bytes_array)

        clipboard.setMimeData(mime_data, QClipboard.Clipboard)
Example #30
0
 def selfSend(self):
     dane = self.selfSendLineEdit.text()
     self.senderMonitor.append("Własne: " + dane)
     self.selfSendLineEdit.clear()
     array = QByteArray()
     array.append('(')
     try:
         array.append(dane)
     except UnicodeEncodeError as ex:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Information)
         msg.setText(
             "Wystąpił bład podczas próby wysłania\nPodaj inną wartość\nTreść błędu: "
             + str(ex))
         msg.setStandardButtons(QMessageBox.Ok)
         pom = msg.exec_()
     monitor.serialWrite(array)
Example #31
0
    def doRequest(self):
        print(self.slider.value())

        data = QByteArray()

        data.append("'brightness':")
        data.append(str(self.slider.value()))

        #url = "https://httpbin.org/post"
        url = "https://postman-echo.com/post"
        req = QNetworkRequest(QUrl(url))
        req.setHeader(QNetworkRequest.ContentTypeHeader,
                      '"Content-Type": "application/json; charset=UTF-8"',)

        self.nam = QNetworkAccessManager()
        self.nam.finished.connect(self.handleResponse)
        self.nam.post(req, data)
 def save(self, fileName, selectedFilter):
     if selectedFilter == self.filters[1]:
         img = self.page().mainFrame().evaluateJavaScript("chart.getImageURI()")
         if img:
             ba = QByteArray()
             ba.append(img[22:])
             by = QByteArray.fromBase64(ba)
             image = QImage.fromData(by, "PNG")
             image.save(fileName)
         else:
             QMessageBox.warning(self.parent(),
                         self.tr("Saving"),
                         self.tr("Image not ready. Please try again later"))
     else:
         if selectedFilter == self.filters[0]:
             with open(fileName, 'wb') as f:
                 f.write(bytes(self.html_data, 'utf-8'))
 def save(self, fileName, selectedFilter):
     if selectedFilter == self.filters[1]:
         img = self.page().mainFrame().evaluateJavaScript("chart.getImageURI()")
         if img:
             ba = QByteArray()
             ba.append(img[22:])
             by = QByteArray.fromBase64(ba)
             image = QImage.fromData(by, "PNG")
             image.save(fileName)
         else:
             QMessageBox.warning(self.parent(),
                         self.tr("Saving"),
                         self.tr("Image not ready. Please try again later"))
     else:
         if selectedFilter == self.filters[0]:
             with open(fileName, 'wb') as f:
                 f.write(bytes(self.html_data, 'utf-8'))
Example #34
0
 def reflesh(self):
     self.ui.BtnRef.setEnabled(False)
     msg = struct.pack('<3sIHHH', b'KDS', 6, 5, 0, 0)
     self.s.write(QByteArray(msg))
     self.s.waitForBytesWritten(1000)
     self.s.waitForReadyRead(3000)
     respond = self.s.read(7)
     str, length = struct.unpack('<3sI', respond)
     print(length)
     tmp = QByteArray()
     if str == b'KDS':
         tmp.append(self.s.read(length))
         while len(tmp) < length:
             self.s.waitForReadyRead(10000)
             tmp.append(self.s.read(length - len(tmp)))
         self.treeModel = TreeModel(tmp)
         self.ui.treeView.setModel(self.treeModel)
     self.timer0Id = self.startTimer(2000)
Example #35
0
 def on_serversImportButton_clicked(self):
     """
     Private slot to import server certificates.
     """
     certs = self.__importCertificate()
     if certs:
         server = "*"
         certificateDict = Preferences.toDict(
             Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
         if server in certificateDict:
             sCerts = QSslCertificate.fromData(certificateDict[server])
         else:
             sCerts = []
         
         pems = QByteArray()
         for cert in certs:
             if cert in sCerts:
                 if qVersion() >= "5.0.0":
                     commonStr = ", ".join(
                         cert.subjectInfo(QSslCertificate.CommonName))
                 else:
                     commonStr = cert.subjectInfo(
                         QSslCertificate.CommonName)
                 E5MessageBox.warning(
                     self,
                     self.tr("Import Certificate"),
                     self.tr(
                         """<p>The certificate <b>{0}</b> already exists."""
                         """ Skipping.</p>""")
                     .format(Utilities.decodeString(commonStr)))
             else:
                 pems.append(cert.toPem() + '\n')
         if server not in certificateDict:
             certificateDict[server] = QByteArray()
         certificateDict[server].append(pems)
         Preferences.Prefs.settings.setValue(
             "Ssl/CaCertificatesDict",
             certificateDict)
         
         self.serversCertificatesTree.clear()
         self.__populateServerCertificatesTree()
         
         self.__updateDefaultConfiguration()
Example #36
0
    def sql_2_bytearray(self, val):
        """
        sql string representation to QByteArray
        :param val: {str} sql string representation
        :return: {QByteArray}
        """

        from PyQt5.QtCore import QByteArray

        try:
            elemsList = map(chr, map(int, val.split(',')))
        except:
            print 'CONFIGURATIN: COULD NOT CONVERT SETTING TO QBYTEARRAY'
            elemsList = []

        ba = QByteArray()
        for i in xrange(len(elemsList)):
            ba.append(elemsList[i])

        return ba
Example #37
0
    def decodeLayerData(self, tileLayer, layerData, format):
        if format in [Map.LayerDataFormat.XML, Map.LayerDataFormat.CSV]:
            raise
            
        _layerData = QByteArray()
        _layerData.append(layerData)
        decodedData = QByteArray.fromBase64(_layerData)
        size = (tileLayer.width() * tileLayer.height()) * 4

        if (format == Map.LayerDataFormat.Base64Gzip or format == Map.LayerDataFormat.Base64Zlib):
            decodedData, size = decompress(decodedData, size)

        if (size != decodedData.length()):
            return DecodeError.CorruptLayerData

        data = decodedData.data()
        x = 0
        y = 0

        for i in range(0, size - 3, 4):
            gid = data[i] | data[i + 1] << 8 | data[i + 2] << 16 | data[i + 3] << 24

            result, ok = self.gidToCell(gid)
            if (not ok):
                self.mInvalidTile = gid
                if self.isEmpty():
                    return DecodeError.TileButNoTilesets
                else:
                    return DecodeError.InvalidTile

            tileLayer.setCell(x, y, result)

            x += 1
            if (x == tileLayer.width()):
                x = 0
                y += 1

        return DecodeError.NoError
Example #38
0
    def clickAction_MessagePushButton(self):
        temp = self.messagelineEdit.text()
        self.append_plainTextEdit_3(temp)
        self.append_plainTextEdit_3("\n")
        bArray = QByteArray()

        if self.sysencoding == "cp949":
            bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시
        elif self.sysencoding == "UTF-8":
            bArray.append(temp.encode(encoding='utf-8',errors='ignore'))#pycharm
        else:
            bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시
        bArray.append("\n")
        if( self.process.write(bArray) == -1):
            print("chlidprocess write error")
        self.messagelineEdit.clear()
Example #39
0
 def on_caDeleteButton_clicked(self):
     """
     Private slot to delete the selected CA certificate.
     """
     itm = self.caCertificatesTree.currentItem()
     res = E5MessageBox.yesNo(
         self,
         self.tr("Delete CA Certificate"),
         self.tr(
             """<p>Shall the CA certificate really be deleted?</p>"""
             """<p>{0}</p>"""
             """<p>If the CA certificate is deleted, the browser"""
             """ will not trust any certificate issued by this CA.</p>""")
         .format(itm.text(0)))
     if res:
         cert = self.caCertificatesTree.currentItem().data(0, self.CertRole)
         
         # delete the selected entry and its parent entry,
         # if it was the only one
         parent = itm.parent()
         parent.takeChild(parent.indexOfChild(itm))
         if parent.childCount() == 0:
             self.caCertificatesTree.takeTopLevelItem(
                 self.caCertificatesTree.indexOfTopLevelItem(parent))
         
         # delete the certificate from the CA certificate store
         caCerts = self.__getSystemCaCertificates()
         if cert in caCerts:
             caCerts.remove(cert)
         pems = QByteArray()
         for cert in caCerts:
             pems.append(cert.toPem() + '\n')
         Preferences.Prefs.settings.setValue(
             "Help/SystemCertificates", pems)
         
         # delete the certificate from the default certificates
         self.__updateDefaultConfiguration()
Example #40
0
    def run(self, argv, error_message, in_build_dir=False):
        """ Execute a command and capture the output. """

        if in_build_dir:
            project = self._project

            saved_cwd = os.getcwd()
            build_dir = project.path_from_user(project.build_dir)
            build_dir = QDir.toNativeSeparators(build_dir)
            os.chdir(build_dir)
            self._message_handler.verbose_message(
                    "{0} is now the current directory".format(build_dir))
        else:
            saved_cwd = None

        self._message_handler.verbose_message(
                "Running '{0}'".format(' '.join(argv)))

        QCoreApplication.processEvents()

        process = QProcess()

        process.readyReadStandardOutput.connect(
                lambda: self._message_handler.progress_message(
                        QTextCodec.codecForLocale().toUnicode(
                                process.readAllStandardOutput()).strip()))

        stderr_output = QByteArray()
        process.readyReadStandardError.connect(
                lambda: stderr_output.append(process.readAllStandardError()))

        process.start(argv[0], argv[1:])
        finished = process.waitForFinished()

        if saved_cwd is not None:
            os.chdir(saved_cwd)
            self._message_handler.verbose_message(
                    "{0} is now the current directory".format(saved_cwd))

        if not finished:
            raise UserException(error_message, process.errorString())

        if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0:
            raise UserException(error_message,
                    QTextCodec.codecForLocale().toUnicode(stderr_output).strip())
Example #41
0
    def encodeLayerData(self, tileLayer, format):
        if format in [Map.LayerDataFormat.XML, Map.LayerDataFormat.CSV]:
            raise

        tileData = QByteArray()
        for y in range(tileLayer.height()):
            for x in range(tileLayer.width()):
                gid = self.cellToGid(tileLayer.cellAt(x, y))
                tileData.append(bytes([gid&0xff]))
                tileData.append(bytes([(gid >> 8)&0xff]))
                tileData.append(bytes([(gid >> 16)&0xff]))
                tileData.append(bytes([(gid >> 24)&0xff]))
                
        if len(tileData)%4 != 0:
            raise

        if (format == Map.LayerDataFormat.Base64Gzip):
            tileData = compress(tileData, CompressionMethod.Gzip)
        elif (format == Map.LayerDataFormat.Base64Zlib):
            tileData = compress(tileData, CompressionMethod.Zlib)

        return tileData.toBase64()
Example #42
0
 def sslErrors(self, errors, server, port=-1):
     """
     Public method to handle SSL errors.
     
     @param errors list of SSL errors (list of QSslError)
     @param server name of the server (string)
     @keyparam port value of the port (integer)
     @return tuple indicating to ignore the SSL errors (one of NotIgnored,
         SystemIgnored or UserIgnored) and indicating a change of the
         default SSL configuration (boolean)
     """
     caMerge = {}
     certificateDict = Globals.toDict(
         Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
     for caServer in certificateDict:
         caMerge[caServer] = QSslCertificate.fromData(
             certificateDict[caServer])
     caNew = []
     
     errorStrings = []
     if port != -1:
         server += ":{0:d}".format(port)
     if errors:
         for err in errors:
             if err.error() == QSslError.NoError:
                 continue
             if server in caMerge and err.certificate() in caMerge[server]:
                 continue
             errorStrings.append(err.errorString())
             if not err.certificate().isNull():
                 cert = err.certificate()
                 if cert not in caNew:
                     caNew.append(cert)
     if not errorStrings:
         return E5SslErrorHandler.SystemIgnored, False
     
     errorString = '.</li><li>'.join(errorStrings)
     ret = E5MessageBox.yesNo(
         None,
         self.tr("SSL Errors"),
         self.tr("""<p>SSL Errors for <br /><b>{0}</b>"""
                 """<ul><li>{1}</li></ul></p>"""
                 """<p>Do you want to ignore these errors?</p>""")
         .format(server, errorString),
         icon=E5MessageBox.Warning)
     
     if ret:
         caRet = False
         if len(caNew) > 0:
             certinfos = []
             for cert in caNew:
                 certinfos.append(self.__certToString(cert))
             caRet = E5MessageBox.yesNo(
                 None,
                 self.tr("Certificates"),
                 self.tr(
                     """<p>Certificates:<br/>{0}<br/>"""
                     """Do you want to accept all these certificates?"""
                     """</p>""")
                 .format("".join(certinfos)))
             if caRet:
                 if server not in caMerge:
                     caMerge[server] = []
                 for cert in caNew:
                     caMerge[server].append(cert)
                 
                 sslCfg = QSslConfiguration.defaultConfiguration()
                 caList = sslCfg.caCertificates()
                 for cert in caNew:
                     caList.append(cert)
                 sslCfg.setCaCertificates(caList)
                 sslCfg.setProtocol(QSsl.AnyProtocol)
                 QSslConfiguration.setDefaultConfiguration(sslCfg)
                 
                 certificateDict = {}
                 for server in caMerge:
                     pems = QByteArray()
                     for cert in caMerge[server]:
                         pems.append(cert.toPem() + b'\n')
                     certificateDict[server] = pems
                 Preferences.Prefs.settings.setValue(
                     "Ssl/CaCertificatesDict",
                     certificateDict)
         
         return E5SslErrorHandler.UserIgnored, caRet
     
     else:
         return E5SslErrorHandler.NotIgnored, False
Example #43
0
 def start(self, fn, noEntries=0):
     """
     Public slot to start the svn log command.
     
     @param fn filename to show the log for (string)
     @param noEntries number of entries to show (integer)
     """
     self.errorGroup.hide()
     
     fetchLimit = 10
     
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents()
     
     self.filename = fn
     dname, fname = self.vcs.splitPath(fn)
     
     opts = self.vcs.options['global'] + self.vcs.options['log']
     verbose = "--verbose" in opts
     
     self.activateWindow()
     self.raise_()
     
     locker = QMutexLocker(self.vcs.vcsExecutionMutex)
     cwd = os.getcwd()
     os.chdir(dname)
     try:
         nextRev = 0
         fetched = 0
         logs = []
         limit = noEntries or 9999999
         while fetched < limit:
             flimit = min(fetchLimit, limit - fetched)
             if fetched == 0:
                 revstart = pysvn.Revision(pysvn.opt_revision_kind.head)
             else:
                 revstart = pysvn.Revision(
                     pysvn.opt_revision_kind.number, nextRev)
             allLogs = self.client.log(fname,
                                       revision_start=revstart,
                                       discover_changed_paths=verbose,
                                       limit=flimit + 1,
                                       strict_node_history=False)
             if len(allLogs) <= flimit or self._clientCancelCallback():
                 logs.extend(allLogs)
                 break
             else:
                 logs.extend(allLogs[:-1])
                 nextRev = allLogs[-1]["revision"].number
                 fetched += fetchLimit
         locker.unlock()
         
         self.contents.clear()
         self.__pegRev = None
         for log in logs:
             ver = "{0:d}".format(log["revision"].number)
             dstr = '<b>{0} {1}</b>'.format(self.revString, ver)
             if self.__pegRev is None:
                 self.__pegRev = int(ver)
             try:
                 lv = "{0:d}".format(
                     logs[logs.index(log) + 1]["revision"].number)
                 url = QUrl()
                 url.setScheme("file")
                 url.setPath(self.filename)
                 if qVersion() >= "5.0.0":
                     query = lv + '_' + ver
                     url.setQuery(query)
                 else:
                     query = QByteArray()
                     query.append(lv).append('_').append(ver)
                     url.setEncodedQuery(query)
                 dstr += ' [<a href="{0}" name="{1}">{2}</a>]'.format(
                     url.toString(), query,
                     self.tr('diff to {0}').format(lv)
                 )
             except IndexError:
                 pass
             dstr += '<br />\n'
             self.contents.insertHtml(dstr)
             
             author = log["author"]
             message = log["message"]
             if sys.version_info[0] == 2:
                 author = author.decode('utf-8')
                 message = message.decode('utf-8')
             dstr = self.tr('<i>author: {0}</i><br />\n')\
                 .format(author)
             self.contents.insertHtml(dstr)
             
             dstr = self.tr('<i>date: {0}</i><br />\n')\
                 .format(formatTime(log["date"]))
             self.contents.insertHtml(dstr)
             
             self.contents.insertHtml('<br />\n')
             
             for line in message.splitlines():
                 self.contents.insertHtml(Utilities.html_encode(line))
                 self.contents.insertHtml('<br />\n')
             
             if len(log['changed_paths']) > 0:
                 self.contents.insertHtml('<br />\n')
                 for changeInfo in log['changed_paths']:
                     action = changeInfo["action"]
                     path = changeInfo["path"]
                     if sys.version_info[0] == 2:
                         action = action.decode('utf-8')
                         path = path.decode('utf-8')
                     dstr = '{0} {1}'.format(self.flags[action], path)
                     if changeInfo["copyfrom_path"] is not None:
                         copyfrom_path = changeInfo["copyfrom_path"]
                         if sys.version_info[0] == 2:
                             copyfrom_path = copyfrom_path.decode('utf-8')
                         dstr += self.tr(
                             " (copied from {0}, revision {1})")\
                             .format(copyfrom_path,
                                     changeInfo["copyfrom_revision"].number)
                     dstr += '<br />\n'
                     self.contents.insertHtml(dstr)
             
             self.contents.insertHtml('<hr /><br />\n')
     except pysvn.ClientError as e:
         locker.unlock()
         self.__showError(e.args[0])
     os.chdir(cwd)
     self.__finish()
Example #44
0
class Connection(QTcpSocket):
    """
    Class representing a peer connection.
    
    @signal readyForUse() emitted when the connection is ready for use
    @signal newMessage(user, message) emitted after a new message has
        arrived (string, string)
    @signal getParticipants() emitted after a get participants message has
        arrived
    @signal participants(participants) emitted after the list of participants
        has arrived (list of strings of "host:port")
    """
    WaitingForGreeting = 0
    ReadingGreeting = 1
    ReadyForUse = 2
    
    PlainText = 0
    Ping = 1
    Pong = 2
    Greeting = 3
    GetParticipants = 4
    Participants = 5
    Editor = 6
    Undefined = 99
    
    ProtocolMessage = "MESSAGE"
    ProtocolPing = "PING"
    ProtocolPong = "PONG"
    ProtocolGreeting = "GREETING"
    ProtocolGetParticipants = "GET_PARTICIPANTS"
    ProtocolParticipants = "PARTICIPANTS"
    ProtocolEditor = "EDITOR"
    
    readyForUse = pyqtSignal()
    newMessage = pyqtSignal(str, str)
    getParticipants = pyqtSignal()
    participants = pyqtSignal(list)
    editorCommand = pyqtSignal(str, str, str)
    rejected = pyqtSignal(str)
    
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent referenec to the parent object (QObject)
        """
        super(Connection, self).__init__(parent)
        
        self.__greetingMessage = self.tr("undefined")
        self.__username = self.tr("unknown")
        self.__serverPort = 0
        self.__state = Connection.WaitingForGreeting
        self.__currentDataType = Connection.Undefined
        self.__numBytesForCurrentDataType = -1
        self.__transferTimerId = 0
        self.__isGreetingMessageSent = False
        self.__pingTimer = QTimer(self)
        self.__pingTimer.setInterval(PingInterval)
        self.__pongTime = QTime()
        self.__buffer = QByteArray()
        self.__client = None
        
        self.readyRead.connect(self.__processReadyRead)
        self.disconnected.connect(self.__disconnected)
        self.__pingTimer.timeout.connect(self.__sendPing)
        self.connected.connect(self.__sendGreetingMessage)
    
    def name(self):
        """
        Public method to get the connection name.
        
        @return connection name (string)
        """
        return self.__username
    
    def serverPort(self):
        """
        Public method to get the server port.
        
        @return server port (integer)
        """
        return self.__serverPort
    
    def setClient(self, client):
        """
        Public method to set the reference to the cooperation client.
        
        @param client reference to the cooperation client (CooperationClient)
        """
        self.__client = client
    
    def setGreetingMessage(self, message, serverPort):
        """
        Public method to set the greeting message.
        
        @param message greeting message (string)
        @param serverPort port number to include in the message (integer)
        """
        self.__greetingMessage = "{0}:{1}".format(message, serverPort)
    
    def sendMessage(self, message):
        """
        Public method to send a message.
        
        @param message message to be sent (string)
        @return flag indicating a successful send (boolean)
        """
        if message == "":
            return False
        
        msg = QByteArray(message.encode("utf-8"))
        data = QByteArray("{0}{1}{2}{1}".format(
            Connection.ProtocolMessage, SeparatorToken, msg.size())
            .encode("utf-8")) + msg
        return self.write(data) == data.size()
    
    def timerEvent(self, evt):
        """
        Protected method to handle timer events.
        
        @param evt reference to the timer event (QTimerEvent)
        """
        if evt.timerId() == self.__transferTimerId:
            self.abort()
            self.killTimer(self.__transferTimerId)
            self.__transferTimerId = 0
    
    def __processReadyRead(self):
        """
        Private slot to handle the readyRead signal.
        """
        if self.__state == Connection.WaitingForGreeting:
            if not self.__readProtocolHeader():
                return
            if self.__currentDataType != Connection.Greeting:
                self.abort()
                return
            self.__state = Connection.ReadingGreeting
        
        if self.__state == Connection.ReadingGreeting:
            if not self.__hasEnoughData():
                return
            
            self.__buffer = QByteArray(
                self.read(self.__numBytesForCurrentDataType))
            if self.__buffer.size() != self.__numBytesForCurrentDataType:
                self.abort()
                return
            
            try:
                user, serverPort = \
                    str(self.__buffer, encoding="utf-8").split(":")
            except ValueError:
                self.abort()
                return
            self.__serverPort = int(serverPort)
            
            hostInfo = QHostInfo.fromName(self.peerAddress().toString())
            self.__username = "******".format(
                user,
                hostInfo.hostName(),
                self.peerPort()
            )
            self.__currentDataType = Connection.Undefined
            self.__numBytesForCurrentDataType = 0
            self.__buffer.clear()
            
            if not self.isValid():
                self.abort()
                return
            
            bannedName = "{0}@{1}".format(
                user,
                hostInfo.hostName(),
            )
            Preferences.syncPreferences()
            if bannedName in Preferences.getCooperation("BannedUsers"):
                self.rejected.emit(self.tr(
                    "* Connection attempted by banned user '{0}'.")
                    .format(bannedName))
                self.abort()
                return
            
            if self.__serverPort != self.peerPort() and \
               not Preferences.getCooperation("AutoAcceptConnections"):
                # don't ask for reverse connections or
                # if we shall accept automatically
                res = E5MessageBox.yesNo(
                    None,
                    self.tr("New Connection"),
                    self.tr("""<p>Accept connection from """
                            """<strong>{0}@{1}</strong>?</p>""").format(
                        user, hostInfo.hostName()),
                    yesDefault=True)
                if not res:
                    self.abort()
                    return

            if self.__client is not None:
                chatWidget = self.__client.chatWidget()
                if chatWidget is not None and not chatWidget.isVisible():
                    e5App().getObject(
                        "UserInterface").activateCooperationViewer()
            
            if not self.__isGreetingMessageSent:
                self.__sendGreetingMessage()
            
            self.__pingTimer.start()
            self.__pongTime.start()
            self.__state = Connection.ReadyForUse
            self.readyForUse.emit()
        
        while self.bytesAvailable():
            if self.__currentDataType == Connection.Undefined:
                if not self.__readProtocolHeader():
                    return
            
            if not self.__hasEnoughData():
                return
            
            self.__processData()
    
    def __sendPing(self):
        """
        Private slot to send a ping message.
        """
        if self.__pongTime.elapsed() > PongTimeout:
            self.abort()
            return
        
        self.write("{0}{1}1{1}p".format(
            Connection.ProtocolPing, SeparatorToken))
    
    def __sendGreetingMessage(self):
        """
        Private slot to send a greeting message.
        """
        greeting = QByteArray(self.__greetingMessage.encode("utf-8"))
        data = QByteArray("{0}{1}{2}{1}".format(
            Connection.ProtocolGreeting, SeparatorToken, greeting.size())
            .encode("utf-8")) + greeting
        if self.write(data) == data.size():
            self.__isGreetingMessageSent = True
    
    def __readDataIntoBuffer(self, maxSize=MaxBufferSize):
        """
        Private method to read some data into the buffer.
        
        @param maxSize maximum size of data to read (integer)
        @return size of data read (integer)
        """
        if maxSize > MaxBufferSize:
            return 0
        
        numBytesBeforeRead = self.__buffer.size()
        if numBytesBeforeRead == MaxBufferSize:
            self.abort()
            return 0
        
        while self.bytesAvailable() and self.__buffer.size() < maxSize:
            self.__buffer.append(self.read(1))
            if self.__buffer.endsWith(SeparatorToken):
                break
        
        return self.__buffer.size() - numBytesBeforeRead
    
    def __dataLengthForCurrentDataType(self):
        """
        Private method to get the data length for the current data type.
        
        @return data length (integer)
        """
        if self.bytesAvailable() <= 0 or \
           self.__readDataIntoBuffer() <= 0 or \
           not self.__buffer.endsWith(SeparatorToken):
            return 0
        
        self.__buffer.chop(len(SeparatorToken))
        number = self.__buffer.toInt()[0]
        self.__buffer.clear()
        return number
    
    def __readProtocolHeader(self):
        """
        Private method to read the protocol header.
        
        @return flag indicating a successful read (boolean)
        """
        if self.__transferTimerId:
            self.killTimer(self.__transferTimerId)
            self.__transferTimerId = 0
        
        if self.__readDataIntoBuffer() <= 0:
            self.__transferTimerId = self.startTimer(TransferTimeout)
            return False
        
        self.__buffer.chop(len(SeparatorToken))
        if self.__buffer == Connection.ProtocolPing:
            self.__currentDataType = Connection.Ping
        elif self.__buffer == Connection.ProtocolPong:
            self.__currentDataType = Connection.Pong
        elif self.__buffer == Connection.ProtocolMessage:
            self.__currentDataType = Connection.PlainText
        elif self.__buffer == Connection.ProtocolGreeting:
            self.__currentDataType = Connection.Greeting
        elif self.__buffer == Connection.ProtocolGetParticipants:
            self.__currentDataType = Connection.GetParticipants
        elif self.__buffer == Connection.ProtocolParticipants:
            self.__currentDataType = Connection.Participants
        elif self.__buffer == Connection.ProtocolEditor:
            self.__currentDataType = Connection.Editor
        else:
            self.__currentDataType = Connection.Undefined
            self.abort()
            return False
        
        self.__buffer.clear()
        self.__numBytesForCurrentDataType = \
            self.__dataLengthForCurrentDataType()
        return True
    
    def __hasEnoughData(self):
        """
        Private method to check, if enough data is available.
        
        @return flag indicating availability of enough data (boolean)
        """
        if self.__transferTimerId:
            self.killTimer(self.__transferTimerId)
            self.__transferTimerId = 0
        
        if self.__numBytesForCurrentDataType <= 0:
            self.__numBytesForCurrentDataType = \
                self.__dataLengthForCurrentDataType()
        
        if self.bytesAvailable() < self.__numBytesForCurrentDataType or \
           self.__numBytesForCurrentDataType <= 0:
            self.__transferTimerId = self.startTimer(TransferTimeout)
            return False
        
        return True
    
    def __processData(self):
        """
        Private method to process the received data.
        """
        self.__buffer = QByteArray(
            self.read(self.__numBytesForCurrentDataType))
        if self.__buffer.size() != self.__numBytesForCurrentDataType:
            self.abort()
            return
        
        if self.__currentDataType == Connection.PlainText:
            self.newMessage.emit(
                self.__username, str(self.__buffer, encoding="utf-8"))
        elif self.__currentDataType == Connection.Ping:
            self.write("{0}{1}1{1}p".format(
                Connection.ProtocolPong, SeparatorToken))
        elif self.__currentDataType == Connection.Pong:
            self.__pongTime.restart()
        elif self.__currentDataType == Connection.GetParticipants:
            self.getParticipants.emit()
        elif self.__currentDataType == Connection.Participants:
            msg = str(self.__buffer, encoding="utf-8")
            if msg == "<empty>":
                participantsList = []
            else:
                participantsList = msg.split(SeparatorToken)
            self.participants.emit(participantsList[:])
        elif self.__currentDataType == Connection.Editor:
            hash, fn, msg = \
                str(self.__buffer, encoding="utf-8").split(SeparatorToken)
            self.editorCommand.emit(hash, fn, msg)
        
        self.__currentDataType = Connection.Undefined
        self.__numBytesForCurrentDataType = 0
        self.__buffer.clear()
    
    def sendGetParticipants(self):
        """
        Public method to request a list of participants.
        """
        self.write(
            "{0}{1}1{1}l".format(
                Connection.ProtocolGetParticipants, SeparatorToken)
        )
    
    def sendParticipants(self, participants):
        """
        Public method to send the list of participants.
        
        @param participants list of participants (list of strings of
            "host:port")
        """
        if participants:
            message = SeparatorToken.join(participants)
        else:
            message = "<empty>"
        msg = QByteArray(message.encode("utf-8"))
        data = QByteArray("{0}{1}{2}{1}".format(
            Connection.ProtocolParticipants, SeparatorToken, msg.size())
            .encode("utf-8")) + msg
        self.write(data)
    
    def sendEditorCommand(self, projectHash, filename, message):
        """
        Public method to send an editor command.
        
        @param projectHash hash of the project (string)
        @param filename project relative universal file name of
            the sending editor (string)
        @param message editor command to be sent (string)
        """
        msg = QByteArray("{0}{1}{2}{1}{3}".format(
            projectHash, SeparatorToken, filename, message).encode("utf-8"))
        data = QByteArray("{0}{1}{2}{1}".format(
            Connection.ProtocolEditor, SeparatorToken, msg.size())
            .encode("utf-8")) + msg
        self.write(data)
    
    def __disconnected(self):
        """
        Private slot to handle the connection being dropped.
        """
        self.__pingTimer.stop()
        if self.__state == Connection.WaitingForGreeting:
            self.rejected.emit(self.tr(
                "* Connection to {0}:{1} refused.").format(
                self.peerName(), self.peerPort()))
Example #45
0
 def __procFinished(self, exitCode, exitStatus):
     """
     Private slot connected to the finished signal.
     
     @param exitCode exit code of the process (integer)
     @param exitStatus exit status of the process (QProcess.ExitStatus)
     """
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     self.contents.clear()
     
     lvers = 1
     for s in self.buf:
         rev_match = False
         if self.rx_rev.exactMatch(s):
             ver = self.rx_rev.cap(1)
             author = self.rx_rev.cap(2)
             date = self.rx_rev.cap(3)
             # number of lines is ignored
             rev_match = True
         elif self.rx_rev2.exactMatch(s):
             ver = self.rx_rev2.cap(1)
             author = self.rx_rev2.cap(2)
             date = self.rx_rev2.cap(3)
             # number of lines is ignored
             rev_match = True
         
         if rev_match:
             dstr = '<b>{0} {1}</b>'.format(self.revString, ver)
             try:
                 lv = self.revisions[lvers]
                 lvers += 1
                 url = QUrl()
                 url.setScheme("file")
                 url.setPath(self.filename)
                 if qVersion() >= "5.0.0":
                     query = lv + '_' + ver
                     url.setQuery(query)
                 else:
                     query = QByteArray()
                     query.append(lv).append('_').append(ver)
                     url.setEncodedQuery(query)
                 dstr += ' [<a href="{0}" name="{1}">{2}</a>]'.format(
                     url.toString(), query,
                     self.tr('diff to {0}').format(lv),
                 )
             except IndexError:
                 pass
             dstr += '<br />\n'
             self.contents.insertHtml(dstr)
             
             dstr = self.tr('<i>author: {0}</i><br />\n').format(author)
             self.contents.insertHtml(dstr)
             
             dstr = self.tr('<i>date: {0}</i><br />\n').format(date)
             self.contents.insertHtml(dstr)
         
         elif self.rx_sep.exactMatch(s) or self.rx_sep2.exactMatch(s):
             self.contents.insertHtml('<hr />\n')
         
         elif self.rx_flags.exactMatch(s):
             dstr = self.flags[self.rx_flags.cap(1)]
             dstr += self.rx_flags.cap(2)
             dstr += '<br />\n'
             self.contents.insertHtml(dstr)
         
         elif self.rx_changed.exactMatch(s):
             dstr = '<br />{0}<br />\n'.format(s)
             self.contents.insertHtml(dstr)
         
         else:
             if s == "":
                 s = self.contents.insertHtml('<br />\n')
             else:
                 self.contents.insertHtml(Utilities.html_encode(s))
                 self.contents.insertHtml('<br />\n')
     
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()
Example #46
0
class FileReply(QNetworkReply):
    """
    Class implementing a network reply for directory resources.
    """
    def __init__(self, url, parent=None):
        """
        Constructor
        
        @param url requested FTP URL (QUrl)
        @param parent reference to the parent object (QObject)
        """
        super(FileReply, self).__init__(parent)
        
        self.__content = QByteArray()
        self.__units = ["Bytes", "KB", "MB", "GB", "TB",
                        "PB", "EB", "ZB", "YB"]
        
        if url.path() == "":
            url.setPath("/")
        self.setUrl(url)
        
        QTimer.singleShot(0, self.__loadDirectory)
    
    def abort(self):
        """
        Public slot to abort the operation.
        """
        # do nothing
        pass
    
    def bytesAvailable(self):
        """
        Public method to determined the bytes available for being read.
        
        @return bytes available (integer)
        """
        return self.__content.size()
    
    def isSequential(self):
        """
        Public method to check for sequential access.
        
        @return flag indicating sequential access (boolean)
        """
        return True
    
    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)
        """
        if self.__content.size():
            len_ = min(maxlen, self.__content.size())
            buffer = bytes(self.__content[:len_])
            self.__content.remove(0, len_)
            return buffer
    
    def __cssLinkClass(self, icon, size=32):
        """
        Private method to generate a link class with an icon.
        
        @param icon icon to be included (QIcon)
        @param size size of the icon to be generated (integer)
        @return CSS class string (string)
        """
        cssString = \
            """a.{{0}} {{{{\n"""\
            """  padding-left: {0}px;\n"""\
            """  background: transparent url(data:image/png;base64,{1})"""\
            """ no-repeat center left;\n"""\
            """  font-weight: bold;\n"""\
            """}}}}\n"""
        pixmap = icon.pixmap(size, size)
        imageBuffer = QBuffer()
        imageBuffer.open(QIODevice.ReadWrite)
        if not pixmap.save(imageBuffer, "PNG"):
            # write a blank pixmap on error
            pixmap = QPixmap(size, size)
            pixmap.fill(Qt.transparent)
            imageBuffer.buffer().clear()
            pixmap.save(imageBuffer, "PNG")
        return cssString.format(
            size + 4,
            str(imageBuffer.buffer().toBase64(), encoding="ascii"))
    
    def __loadDirectory(self):
        """
        Private slot loading the directory and preparing the listing page.
        """
        dir = QDir(self.url().toLocalFile())
        dirItems = dir.entryInfoList(
            QDir.AllEntries | QDir.Hidden | QDir.NoDotAndDotDot,
            QDir.Name | QDir.DirsFirst)
        
        u = self.url()
        if not u.path().endswith("/"):
            u.setPath(u.path() + "/")
        
        baseUrl = self.url().toString()
        basePath = u.path()
        
        linkClasses = {}
        iconSize = QWebSettings.globalSettings().fontSize(
            QWebSettings.DefaultFontSize)
        
        parent = u.resolved(QUrl(".."))
        if parent.isParentOf(u):
            icon = UI.PixmapCache.getIcon("up.png")
            linkClasses["link_parent"] = \
                self.__cssLinkClass(icon, iconSize).format("link_parent")
            parentStr = self.tr(
                """  <p><a class="link_parent" href="{0}">"""
                """Change to parent directory</a></p>"""
            ).format(parent.toString())
        else:
            parentStr = ""
        
        row = \
            """    <tr class="{0}">"""\
            """<td class="name"><a class="{1}" href="{2}">{3}</a></td>"""\
            """<td class="size">{4}</td>"""\
            """<td class="modified">{5}</td>"""\
            """</tr>\n"""
        table = self.tr(
            """    <tr>"""
            """<th align="left">Name</th>"""
            """<th>Size</th>"""
            """<th align="left">Last modified</th>"""
            """</tr>\n"""
        )
        
        i = 0
        for item in dirItems:
            name = item.fileName()
            if item.isDir() and not name.endswith("/"):
                name += "/"
            child = u.resolved(QUrl(name.replace(":", "%3A")))
            
            if item.isFile():
                size = item.size()
                unit = 0
                while size:
                    newSize = size // 1024
                    if newSize and unit < len(self.__units):
                        size = newSize
                        unit += 1
                    else:
                        break
                
                sizeStr = self.tr("{0} {1}", "size unit")\
                    .format(size, self.__units[unit])
                linkClass = "link_file"
                if linkClass not in linkClasses:
                    icon = UI.PixmapCache.getIcon("fileMisc.png")
                    linkClasses[linkClass] = \
                        self.__cssLinkClass(icon, iconSize).format(linkClass)
            else:
                sizeStr = ""
                linkClass = "link_dir"
                if linkClass not in linkClasses:
                    icon = UI.PixmapCache.getIcon("dirClosed.png")
                    linkClasses[linkClass] = \
                        self.__cssLinkClass(icon, iconSize).format(linkClass)
            table += row.format(
                i == 0 and "odd" or "even",
                linkClass,
                child.toString(),
                Utilities.html_encode(item.fileName()),
                sizeStr,
                item.lastModified().toString("yyyy-MM-dd hh:mm"),
            )
            i = 1 - i
        
        content = dirListPage_html.format(
            Utilities.html_encode(baseUrl),
            "".join(linkClasses.values()),
            self.tr("Listing of {0}").format(basePath),
            parentStr,
            table
        )
        self.__content = QByteArray(content.encode("utf8"))
        self.__content.append(512 * b' ')
        
        self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
        self.setHeader(
            QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8")
        self.setHeader(
            QNetworkRequest.ContentLengthHeader, self.__content.size())
        self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
        self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
        self.metaDataChanged.emit()
        self.downloadProgress.emit(
            self.__content.size(), self.__content.size())
        self.readyRead.emit()
        self.finished.emit()
Example #47
0
class FtpReply(QNetworkReply):
    """
    Class implementing a network reply for FTP resources.
    """
    def __init__(self, url, accessHandler, parent=None):
        """
        Constructor
        
        @param url requested FTP URL (QUrl)
        @param accessHandler reference to the access handler (FtpAccessHandler)
        @param parent reference to the parent object (QObject)
        """
        super(FtpReply, self).__init__(parent)
        
        self.__manager = parent
        self.__handler = accessHandler
        
        self.__ftp = E5Ftp()
        
        self.__items = []
        self.__content = QByteArray()
        self.__units = ["Bytes", "KB", "MB", "GB", "TB",
                        "PB", "EB", "ZB", "YB"]
        self.__dirLineParser = FtpDirLineParser()
        self.__fileBytesReceived = 0
        
        if url.path() == "":
            url.setPath("/")
        self.setUrl(url)
        
        # do proxy setup
        if not Preferences.getUI("UseProxy"):
            proxyType = E5FtpProxyType.NoProxy
        else:
            proxyType = Preferences.getUI("ProxyType/Ftp")
        if proxyType != E5FtpProxyType.NoProxy:
            self.__ftp.setProxy(
                proxyType,
                Preferences.getUI("ProxyHost/Ftp"),
                Preferences.getUI("ProxyPort/Ftp"))
            if proxyType != E5FtpProxyType.NonAuthorizing:
                self.__ftp.setProxyAuthentication(
                    Preferences.getUI("ProxyUser/Ftp"),
                    Preferences.getUI("ProxyPassword/Ftp"),
                    Preferences.getUI("ProxyAccount/Ftp"))
        
        QTimer.singleShot(0, self.__doFtpCommands)
    
    def abort(self):
        """
        Public slot to abort the operation.
        """
        # do nothing
        pass
    
    def bytesAvailable(self):
        """
        Public method to determined the bytes available for being read.
        
        @return bytes available (integer)
        """
        return self.__content.size()
    
    def isSequential(self):
        """
        Public method to check for sequential access.
        
        @return flag indicating sequential access (boolean)
        """
        return True
    
    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)
        """
        if self.__content.size():
            len_ = min(maxlen, self.__content.size())
            buffer = bytes(self.__content[:len_])
            self.__content.remove(0, len_)
            return buffer
    
    def __doFtpCommands(self):
        """
        Private slot doing the sequence of FTP commands to get the requested
        result.
        """
        retry = True
        try:
            username = self.url().userName()
            password = self.url().password()
            byAuth = False
            
            while retry:
                try:
                    self.__ftp.connect(self.url().host(),
                                       self.url().port(ftplib.FTP_PORT),
                                       timeout=10)
                except E5FtpProxyError as err:
                    self.setError(QNetworkReply.ProxyNotFoundError, str(err))
                    self.error.emit(QNetworkReply.ProxyNotFoundError)
                    self.finished.emit()
                ok, retry = self.__doFtpLogin(username, password, byAuth)
                if not ok and retry:
                    auth = self.__handler.getAuthenticator(self.url().host())
                    if auth and not auth.isNull() and auth.user():
                        username = auth.user()
                        password = auth.password()
                        byAuth = True
                    else:
                        retry = False
            if ok:
                self.__ftp.retrlines("LIST " + self.url().path(),
                                     self.__dirCallback)
                if len(self.__items) == 1 and \
                   self.__items[0].isFile():
                    self.__fileBytesReceived = 0
                    self.__setContent()
                    self.__ftp.retrbinary(
                        "RETR " + self.url().path(), self.__retrCallback)
                    self.__content.append(512 * b' ')
                    self.readyRead.emit()
                else:
                    self.__setListContent()
                self.__ftp.quit()
        except ftplib.all_errors as err:
            if isinstance(err, socket.gaierror):
                errCode = QNetworkReply.HostNotFoundError
            elif isinstance(err, socket.error) and \
                    err.errno == errno.ECONNREFUSED:
                errCode = QNetworkReply.ConnectionRefusedError
            else:
                errCode = QNetworkReply.ProtocolFailure
            self.setError(errCode, str(err))
            self.error.emit(errCode)
        self.finished.emit()
    
    def __doFtpLogin(self, username, password, byAuth=False):
        """
        Private method to do the FTP login with asking for a username and
        password, if the login fails with an error 530.
        
        @param username user name to use for the login (string)
        @param password password to use for the login (string)
        @param byAuth flag indicating that the login data was provided by an
            authenticator (boolean)
        @return tuple of two flags indicating a successful login and
            if the login should be retried (boolean, boolean)
        """
        try:
            self.__ftp.login(username, password)
            return True, False
        except E5FtpProxyError as err:
            code = str(err)[:3]
            if code[1] == "5":
                # could be a 530, check second line
                lines = str(err).splitlines()
                if lines[1][:3] == "530":
                    if "usage" in "\n".join(lines[1:].lower()):
                        # found a not supported proxy
                        self.setError(
                            QNetworkReply.ProxyConnectionRefusedError,
                            self.tr("The proxy type seems to be wrong."
                                    " If it is not in the list of"
                                    " supported proxy types please report"
                                    " it with the instructions given by"
                                    " the proxy.\n{0}").format(
                                "\n".join(lines[1:])))
                        self.error.emit(
                            QNetworkReply.ProxyConnectionRefusedError)
                        return False, False
                    else:
                        from UI.AuthenticationDialog import \
                            AuthenticationDialog
                        info = self.tr(
                            "<b>Connect to proxy '{0}' using:</b>")\
                            .format(Utilities.html_encode(
                                Preferences.getUI("ProxyHost/Ftp")))
                        dlg = AuthenticationDialog(
                            info, Preferences.getUI("ProxyUser/Ftp"), True)
                        dlg.setData(Preferences.getUI("ProxyUser/Ftp"),
                                    Preferences.getUI("ProxyPassword/Ftp"))
                        if dlg.exec_() == QDialog.Accepted:
                            username, password = dlg.getData()
                            if dlg.shallSave():
                                Preferences.setUI("ProxyUser/Ftp", username)
                                Preferences.setUI(
                                    "ProxyPassword/Ftp", password)
                            self.__ftp.setProxyAuthentication(username,
                                                              password)
                            return False, True
            return False, False
        except (ftplib.error_perm, ftplib.error_temp) as err:
            code = err.args[0].strip()[:3]
            if code in ["530", "421"]:
                # error 530 -> Login incorrect
                # error 421 -> Login may be incorrect (reported by some
                # proxies)
                if byAuth:
                    self.__handler.setAuthenticator(self.url().host(), None)
                    auth = None
                else:
                    auth = self.__handler.getAuthenticator(self.url().host())
                if not auth or auth.isNull() or not auth.user():
                    auth = QAuthenticator()
                    self.__manager.authenticationRequired.emit(self, auth)
                    if not auth.isNull():
                        if auth.user():
                            self.__handler.setAuthenticator(self.url().host(),
                                                            auth)
                            return False, True
                    return False, False
                return False, True
            else:
                raise
    
    def __dirCallback(self, line):
        """
        Private slot handling the receipt of directory listings.
        
        @param line the received line of the directory listing (string)
        """
        try:
            urlInfo = self.__dirLineParser.parseLine(line)
        except FtpDirLineParserError:
            # silently ignore parser errors
            urlInfo = None
        
        if urlInfo:
            self.__items.append(urlInfo)
        
        QCoreApplication.processEvents()
    
    def __retrCallback(self, data):
        """
        Private slot handling the reception of data.
        
        @param data data received from the FTP server (bytes)
        """
        self.__content += QByteArray(data)
        self.__fileBytesReceived += len(data)
        self.downloadProgress.emit(
            self.__fileBytesReceived, self.__items[0].size())
        self.readyRead.emit()
        
        QCoreApplication.processEvents()
    
    def __setContent(self):
        """
        Private method to finish the setup of the data.
        """
        mtype, encoding = mimetypes.guess_type(self.url().toString())
        self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
        self.setHeader(QNetworkRequest.ContentLengthHeader,
                       self.__items[0].size())
        if mtype:
            self.setHeader(QNetworkRequest.ContentTypeHeader, mtype)
        self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
        self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
        self.metaDataChanged.emit()
    
    def __cssLinkClass(self, icon, size=32):
        """
        Private method to generate a link class with an icon.
        
        @param icon icon to be included (QIcon)
        @param size size of the icon to be generated (integer)
        @return CSS class string (string)
        """
        cssString = \
            """a.{{0}} {{{{\n"""\
            """  padding-left: {0}px;\n"""\
            """  background: transparent url(data:image/png;base64,{1})"""\
            """ no-repeat center left;\n"""\
            """  font-weight: bold;\n"""\
            """}}}}\n"""
        pixmap = icon.pixmap(size, size)
        imageBuffer = QBuffer()
        imageBuffer.open(QIODevice.ReadWrite)
        if not pixmap.save(imageBuffer, "PNG"):
            # write a blank pixmap on error
            pixmap = QPixmap(size, size)
            pixmap.fill(Qt.transparent)
            imageBuffer.buffer().clear()
            pixmap.save(imageBuffer, "PNG")
        return cssString.format(
            size + 4,
            str(imageBuffer.buffer().toBase64(), encoding="ascii"))
    
    def __setListContent(self):
        """
        Private method to prepare the content for the reader.
        """
        u = self.url()
        if not u.path().endswith("/"):
            u.setPath(u.path() + "/")
        
        baseUrl = self.url().toString()
        basePath = u.path()
        
        linkClasses = {}
        iconSize = QWebSettings.globalSettings().fontSize(
            QWebSettings.DefaultFontSize)
        
        parent = u.resolved(QUrl(".."))
        if parent.isParentOf(u):
            icon = UI.PixmapCache.getIcon("up.png")
            linkClasses["link_parent"] = \
                self.__cssLinkClass(icon, iconSize).format("link_parent")
            parentStr = self.tr(
                """  <p><a class="link_parent" href="{0}">"""
                """Change to parent directory</a></p>"""
            ).format(parent.toString())
        else:
            parentStr = ""
        
        row = \
            """    <tr class="{0}">"""\
            """<td class="name"><a class="{1}" href="{2}">{3}</a></td>"""\
            """<td class="size">{4}</td>"""\
            """<td class="modified">{5}</td>"""\
            """</tr>\n"""
        table = self.tr(
            """    <tr>"""
            """<th align="left">Name</th>"""
            """<th>Size</th>"""
            """<th align="left">Last modified</th>"""
            """</tr>\n"""
        )
        
        i = 0
        for item in self.__items:
            name = item.name()
            if item.isDir() and not name.endswith("/"):
                name += "/"
            child = u.resolved(QUrl(name.replace(":", "%3A")))
            
            if item.isFile():
                size = item.size()
                unit = 0
                while size:
                    newSize = size // 1024
                    if newSize and unit < len(self.__units):
                        size = newSize
                        unit += 1
                    else:
                        break
                
                sizeStr = self.tr("{0} {1}", "size unit")\
                    .format(size, self.__units[unit])
                linkClass = "link_file"
                if linkClass not in linkClasses:
                    icon = UI.PixmapCache.getIcon("fileMisc.png")
                    linkClasses[linkClass] = \
                        self.__cssLinkClass(icon, iconSize).format(linkClass)
            else:
                sizeStr = ""
                linkClass = "link_dir"
                if linkClass not in linkClasses:
                    icon = UI.PixmapCache.getIcon("dirClosed.png")
                    linkClasses[linkClass] = \
                        self.__cssLinkClass(icon, iconSize).format(linkClass)
            table += row.format(
                i == 0 and "odd" or "even",
                linkClass,
                child.toString(),
                Utilities.html_encode(item.name()),
                sizeStr,
                item.lastModified().toString("yyyy-MM-dd hh:mm"),
            )
            i = 1 - i
        
        content = ftpListPage_html.format(
            Utilities.html_encode(baseUrl),
            "".join(linkClasses.values()),
            self.tr("Listing of {0}").format(basePath),
            parentStr,
            table
        )
        self.__content = QByteArray(content.encode("utf8"))
        self.__content.append(512 * b' ')
        
        self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
        self.setHeader(
            QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8")
        self.setHeader(
            QNetworkRequest.ContentLengthHeader, self.__content.size())
        self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
        self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
        self.metaDataChanged.emit()
        self.downloadProgress.emit(
            self.__content.size(), self.__content.size())
        self.readyRead.emit()
Example #48
0
class Generator(QIODevice):

    def __init__(self, format, durationUs, sampleRate, parent):
        super(Generator, self).__init__(parent)

        self.m_pos = 0
        self.m_buffer = QByteArray()

        self.generateData(format, durationUs, sampleRate)

    def start(self):
        self.open(QIODevice.ReadOnly)

    def stop(self):
        self.m_pos = 0
        self.close()

    def generateData(self, format, durationUs, sampleRate):
        pack_format = ''

        if format.sampleSize() == 8:
            if format.sampleType() == QAudioFormat.UnSignedInt:
                scaler = lambda x: ((1.0 + x) / 2 * 255)
                pack_format = 'B'
            elif format.sampleType() == QAudioFormat.SignedInt:
                scaler = lambda x: x * 127
                pack_format = 'b'
        elif format.sampleSize() == 16:
            if format.sampleType() == QAudioFormat.UnSignedInt:
                scaler = lambda x: (1.0 + x) / 2 * 65535
                pack_format = '<H' if format.byteOrder() == QAudioFormat.LittleEndian else '>H'
            elif format.sampleType() == QAudioFormat.SignedInt:
                scaler = lambda x: x * 32767
                pack_format = '<h' if format.byteOrder() == QAudioFormat.LittleEndian else '>h'

        assert(pack_format != '')

        channelBytes = format.sampleSize() // 8
        sampleBytes = format.channelCount() * channelBytes

        length = (format.sampleRate() * format.channelCount() * (format.sampleSize() // 8)) * durationUs // 100000

        self.m_buffer.clear()
        sampleIndex = 0
        factor = 2 * pi * sampleRate / format.sampleRate()

        while length != 0:
            x = sin((sampleIndex % format.sampleRate()) * factor)
            packed = pack(pack_format, int(scaler(x)))

            for _ in range(format.channelCount()):
                self.m_buffer.append(packed)
                length -= channelBytes

            sampleIndex += 1

    def readData(self, maxlen):
        data = QByteArray()
        total = 0

        while maxlen > total:
            chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total)
            data.append(self.m_buffer.mid(self.m_pos, chunk))
            self.m_pos = (self.m_pos + chunk) % self.m_buffer.size()
            total += chunk

        return data.data()

    def writeData(self, data):
        return 0

    def bytesAvailable(self):
        return self.m_buffer.size() + super(Generator, self).bytesAvailable()
Example #49
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     self.contents.clear()
     
     if not self.logEntries:
         self.errors.append(self.tr("No log available for '{0}'")
                            .format(self.filename))
         self.errorGroup.show()
         return
     
     html = ""
     
     if self.initialText:
         for line in self.initialText:
             html += Utilities.html_encode(line.strip())
             html += '<br />\n'
         html += '{0}<br/>\n'.format(80 * "=")
         
     for entry in self.logEntries:
         fileCopies = {}
         if entry["file_copies"]:
             for fentry in entry["file_copies"].split(", "):
                 newName, oldName = fentry[:-1].split(" (")
                 fileCopies[newName] = oldName
         
         rev, hexRev = entry["change"].split(":")
         dstr = '<p><b>{0} {1}</b>'.format(self.revString, entry["change"])
         if entry["parents"]:
             parents = entry["parents"].split()
         else:
             parents = self.__getParents(rev)
         for parent in parents:
             url = QUrl()
             url.setScheme("file")
             url.setPath(self.filename)
             if qVersion() >= "5.0.0":
                 query = parent.split(":")[0] + '_' + rev
                 url.setQuery(query)
             else:
                 query = QByteArray()
                 query.append(parent.split(":")[0]).append('_').append(rev)
                 url.setEncodedQuery(query)
             dstr += ' [<a href="{0}" name="{1}" id="{1}">{2}</a>]'.format(
                 url.toString(), query,
                 self.tr('diff to {0}').format(parent),
             )
         dstr += '<br />\n'
         html += dstr
         
         if "phase" in entry:
             html += self.tr("Phase: {0}<br />\n")\
                 .format(entry["phase"])
         
         html += self.tr("Branch: {0}<br />\n")\
             .format(entry["branches"])
         
         html += self.tr("Tags: {0}<br />\n").format(entry["tags"])
         
         if "bookmarks" in entry:
             html += self.tr("Bookmarks: {0}<br />\n")\
                 .format(entry["bookmarks"])
         
         html += self.tr("Parents: {0}<br />\n")\
             .format(entry["parents"])
         
         html += self.tr('<i>Author: {0}</i><br />\n')\
             .format(Utilities.html_encode(entry["user"]))
         
         date, time = entry["date"].split()[:2]
         html += self.tr('<i>Date: {0}, {1}</i><br />\n')\
             .format(date, time)
         
         for line in entry["description"]:
             html += Utilities.html_encode(line.strip())
             html += '<br />\n'
         
         if entry["file_adds"]:
             html += '<br />\n'
             for f in entry["file_adds"].strip().split(", "):
                 if f in fileCopies:
                     html += self.tr(
                         'Added {0} (copied from {1})<br />\n')\
                         .format(Utilities.html_encode(f),
                                 Utilities.html_encode(fileCopies[f]))
                 else:
                     html += self.tr('Added {0}<br />\n')\
                         .format(Utilities.html_encode(f))
         
         if entry["files_mods"]:
             html += '<br />\n'
             for f in entry["files_mods"].strip().split(", "):
                 html += self.tr('Modified {0}<br />\n')\
                     .format(Utilities.html_encode(f))
         
         if entry["file_dels"]:
             html += '<br />\n'
             for f in entry["file_dels"].strip().split(", "):
                 html += self.tr('Deleted {0}<br />\n')\
                     .format(Utilities.html_encode(f))
         
         html += '</p>{0}<br/>\n'.format(60 * "=")
     
     self.contents.setHtml(html)
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()