Exemple #1
0
    def local_upload(self, package):
        # abs_path = os.path.join(package.data.local_path, package.data.name)
        for flag, item in tools.list_dir_all(package.data.local_path,
                                             package.data.name):
            self.show_progress.emit()
            if flag == 0:  # 需要创建目录
                write_to = self.get_comboBox_first_item(
                    self.fmt_pack(self.RemoteComboBox))
                self.set_progress.emit(
                    Dict(operation="创建目录",
                         name=item,
                         progress=100,
                         detail="创建完毕",
                         speed="---",
                         elapsed_time="00:00:00",
                         remaining_time="00:00:00"))
                QApplication.processEvents()
                self.remote_table_func.os_mkdir(os.path.join(write_to, item))
                print(f"创建目录:{item}")
            else:  # 发送文件
                abs_path = os.path.join(package.data.local_path, item)
                base_write_to = self.get_comboBox_first_item(
                    self.fmt_pack(self.RemoteComboBox))
                write_to = os.path.dirname(os.path.join(base_write_to, item))
                try:
                    self.remote_table_func.send_files([abs_path], write_to,
                                                      self.set_progress)
                except Exception as e:
                    print("1111", e)

        self.hide_progress.emit()
        self.remote_reload(package)
Exemple #2
0
 def __enter__(self):
     self.stacks.setCurrentIndex(0)
     self.busy.setVisible(True)
     self.busy.pi.startAnimation()
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents
                                | QEventLoop.ExcludeSocketNotifiers)
Exemple #3
0
 def add_image_diff(self, left_data, right_data):
     def load(data):
         p = QPixmap()
         p.loadFromData(bytes(data))
         if data and p.isNull():
             p = self.failed_img
         return p
     left_img, right_img = load(left_data), load(right_data)
     change = []
     # Let any initial resizing of the window finish in case this is the
     # first diff, to avoid the expensive resize calculation later
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
     for v, img, size in ((self.left, left_img, len(left_data)), (self.right, right_img, len(right_data))):
         c = v.textCursor()
         c.movePosition(c.End)
         start = c.block().blockNumber()
         lines, w = self.get_lines_for_image(img, v)
         c.movePosition(c.StartOfBlock)
         if size > 0:
             c.beginEditBlock()
             c.insertText(_('Size: {0} Resolution: {1}x{2}').format(human_readable(size), img.width(), img.height()))
             for i in xrange(lines + 1):
                 c.insertBlock()
         change.extend((start, c.block().blockNumber()))
         c.insertBlock()
         c.endEditBlock()
         v.images[start] = (img, w, lines)
     change.append('replace' if left_data and right_data else 'delete' if left_data else 'insert')
     self.left.changes.append((change[0], change[1], change[-1]))
     self.right.changes.append((change[2], change[3], change[-1]))
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
Exemple #4
0
 def fix_errors(self, container, errors):
     with BusyCursor():
         self.show_busy(_('Running fixers, please wait...'))
         QApplication.processEvents()
         changed = fix_errors(container, errors)
     self.run_checks(container)
     return changed
Exemple #5
0
 def fix_errors(self, container, errors):
     with BusyCursor():
         self.show_busy(_('Running fixers, please wait...'))
         QApplication.processEvents()
         changed = fix_errors(container, errors)
     self.run_checks(container)
     return changed
Exemple #6
0
 def log_outputted(self, txt):
     self.textBrowser.moveCursor(QTextCursor.End)
     text = (u'<pre style="margin-top:0px; margin-bottom:0px;">'
             + txt + u'</pre>')
     self.textBrowser.insertHtml(text)
     self.textBrowser.moveCursor(QTextCursor.End)
     self.textBrowser.repaint()
     QApplication.processEvents()
Exemple #7
0
    def dispatcher(self):
        container = self.current_container  # The book being edited as a container object
        if not container:
            return info_dialog(self.gui, _('No book open'),
                        _('Need to have a book open first.'), show=True)

        self.filesChanged = False
        self.changed_files = []

        from calibre_plugins.horver.dialogs import ConversionDialog
        from calibre_plugins.horver.resources.dialogs import ResultsDialog

        dlg = ConversionDialog(self.gui)
        if dlg.exec_():
            criteria = dlg.getCriteria()
            # Ensure any in progress editing the user is doing is present in the container
            self.boss.commit_all_editors_to_container()
            self.boss.add_savepoint(_('Before: Text Conversion'))

            try:
                conversion = get_configuration(criteria)
                if conversion == 'None':
                    info_dialog(self.gui, _('No Changes'),
                    _('The output configuration selected is not supported.\n Please use a different input/output style combination'), show=True)
                else:
                    QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                    QApplication.processEvents()
                    if conversion != 'no_conversion':
                        self.converter.set_conversion(get_configuration(criteria))
                    self.process_files(criteria)
                    QApplication.restoreOverrideCursor()
            except Exception:
                QApplication.restoreOverrideCursor()
                # Something bad happened report the error to the user
                import traceback
                error_dialog(self.gui, _('Failed'),
                    _('Failed to convert Chinese, click "Show details" for more info'),
                    det_msg=traceback.format_exc(), show=True)
                # Revert to the saved restore point
                self.boss.revert_requested(self.boss.global_undo.previous_container)
            else:
                if self.filesChanged:
                    # Show the user what changes we have made,
                    # allowing then to revert them if necessary
                    accepted = ResultsDialog(self.gui, self.changed_files).exec_()
                    if accepted == QDialog.Accepted:
                        self.boss.show_current_diff()
                    # Update the editor UI to take into account all the changes we
                    # have made
                    self.boss.apply_container_update_to_gui()
                elif conversion != 'None':
                    info_dialog(self.gui, _('No Changes'),
                                _('No text meeting your criteria was found to change.\nNo changes made.'), show=True)
Exemple #8
0
 def run(self):    
     while not self.shutdown_flag.is_set():
         self.control_tab.updateRPCstatus(self.ctrl_obj)
         QApplication.processEvents()
         self.control_tab.updateRPCled()
         
         if not self.control_tab.rpcConnected:
             sleep(self.timer_off)
         else:
             sleep(self.timer_on)
         
     printOK("Exiting Rpc Watchdog Thread")
Exemple #9
0
 def show_error(self, is_syntax_err, tb, controller=None):
     if self.prompt_frame is not None:
         # At a prompt, so redirect output
         return prints(tb, end='')
     try:
         self.buf.append(tb)
         if is_syntax_err:
             self.formatter.render_syntax_error(tb, self.cursor)
         else:
             self.formatter.render(self.tb_lexer.get_tokens(tb), self.cursor)
     except:
         prints(tb, end='')
     self.ensureCursorVisible()
     QApplication.processEvents()
    def send_files(self, file_list, write_to, set_progress=None):
        for file_path in file_list:
            file_name = os.path.basename(file_path)
            size, unit, bytes_size = tools.file_size(file_path)
            with open(file_path, 'rb') as fp:
                protocol = dict(code=100,
                                msg='',
                                size=os.path.getsize(file_path),
                                write_path=os.path.join(write_to, file_name))
                self.before_send(protocol)
                b_data = fp.read(self.file_group_len)
                last_s = int(time.time())
                last_s_send_group = int()
                send_group = int()
                start_time = int(time.time())
                while b_data:
                    if self.base_socket.send_all(b_data):
                        send_group += 1
                        last_s_send_group += 1
                        b_data = fp.read(self.file_group_len)
                        # 如果设置了回调函数,每秒钟调用并且传递回调函数
                        if int(time.time()
                               ) != last_s and set_progress:  # 说明过去了一秒
                            QApplication.processEvents()
                            d = tools.Dict(
                                operation="传送中",
                                name=file_name,
                                progress=int(send_group * self.file_group_len /
                                             bytes_size * 100),
                                speed=tools.bytes_to_speed(
                                    last_s_send_group * self.file_group_len),
                                detail=tools.bytes_to_speed(
                                    send_group * self.file_group_len) + "/" +
                                str(size) + unit,
                                elapsed_time=tools.second_to_time(
                                    int(time.time()) - start_time),
                                remaining_time=tools.second_to_time(
                                    (bytes_size -
                                     send_group * self.file_group_len) /
                                    (last_s_send_group * self.file_group_len)))
                            last_s_send_group = int()
                            last_s = int(time.time())
                            set_progress.emit(d)

                    else:
                        print("scoket异常 文件发送停止。")
                        return False
            print("文件发送完毕", file_name)
        return True
Exemple #11
0
 def displayMNStatus(self, currMN):
     statusData = None
     for mn in self.all_masternodes.get('masternodes'):
         #if mn.get('addr') == currMN['collateral'].get('address'):
         if mn.get('txhash') == currMN['collateral'].get('txid') and mn.get('outidx') == currMN['collateral'].get('txidn'):
             statusData = mn
             if statusData is not None:   
                 try:
                     statusData['balance'] = self.caller.apiClient.getBalance(mn.get('addr'))
                 except Exception as e:
                     err_msg = "error getting balance of %s" % mn.get('addr')
                     printException(getCallerName(), getFunctionName(), err_msg, e)
     
     masternode_alias = currMN['name']               
     self.ui.btn_details[masternode_alias].disconnect()
     self.ui.btn_details[masternode_alias].clicked.connect(lambda: self.onDisplayStatusDetails(masternode_alias, statusData))
     self.ui.btn_details[masternode_alias].show()
 
     if statusData is None:
         printOK("%s Not Found" % (masternode_alias))
         self.ui.mnLed[masternode_alias].setPixmap(self.caller.ledGrayV_icon)
         msg = "<b>Masternode not found.</b>"
         self.ui.mnStatusLabel[masternode_alias].setText(msg)
         self.ui.mnStatusLabel[masternode_alias].show()
         self.ui.btn_details[masternode_alias].setEnabled(False)
     else:
         display_text = ""
         if statusData['balance'] is not None:
             self.ui.mnBalance[masternode_alias].setText('&nbsp;<span style="color:purple">%s PIV</span>' % str(statusData['balance']))
             self.ui.mnBalance[masternode_alias].show()
         printOK("Got status %s for %s" % (statusData['status'], masternode_alias))
         if statusData['status'] == 'ENABLED':
             self.ui.mnLed[masternode_alias].setPixmap(self.caller.ledGreenV_icon)
             display_text += '<span style="color:green">%s</span>&nbsp;&nbsp;' % statusData['status']
             position = statusData.get('queue_pos')
             total_count = len(self.all_masternodes.get('masternodes'))
             display_text += '%d/%d' % (position, total_count) 
             
             self.ui.mnStatusProgress[masternode_alias].setRange(0, total_count)
             self.ui.mnStatusProgress[masternode_alias].setValue(total_count-position)
             self.ui.mnStatusProgress[masternode_alias].show()
         else:
             self.ui.mnLed[masternode_alias].setPixmap(self.caller.ledRedV_icon)
             display_text += '<span style="color:red">%s</span>&nbsp;&nbsp;' % statusData['status']
    
         self.ui.mnStatusLabel[masternode_alias].setText(display_text)
         self.ui.mnStatusLabel[masternode_alias].show()
         self.ui.btn_details[masternode_alias].setEnabled(True)
     QApplication.processEvents()     
Exemple #12
0
 def show_error(self, is_syntax_err, tb, controller=None):
     if self.prompt_frame is not None:
         # At a prompt, so redirect output
         return prints(tb, end='')
     try:
         self.buf.append(tb)
         if is_syntax_err:
             self.formatter.render_syntax_error(tb, self.cursor)
         else:
             self.formatter.render(self.tb_lexer.get_tokens(tb),
                                   self.cursor)
     except:
         prints(tb, end='')
     self.ensureCursorVisible()
     QApplication.processEvents()
Exemple #13
0
 def on_load_data(self, byte, title):
     if byte is None:
         self.on_load_info()
         return
     QApplication.processEvents()
     image = QImage()
     image.loadFromData(byte)
     bitmap = QPixmap(image)
     self.title.show()
     self.title.setText(title)
     self.avatar.setPixmap(bitmap)
     self.dow_mp3.setEnabled(True)
     self.dow_mp4.setEnabled(True)
     self.download_msg.setText(
         "<html><body><center>Ready to download</center></body></html>")
Exemple #14
0
 def run(self):
     while True:
         if not self.send_queue.empty():
             try:
                 asyncore.loop(count=40)
                 print('getting response')
             except asyncore.ExitNow:
                 pass
         if not self.receive_queue.empty():
             data = self.receive_queue.get()
             if data == b'ok':
                 self.image_response.emit(b'ok')
             else:
                 self.trajectory_response.emit(data)
         QApplication.processEvents()
 def connectToStream(self):
     self.videoLabel.setText("  Stream Loading...  ")
     self.videoLabel.setVisible(True)
     # Disable resolution combobox, ip lineEdit and connect button
     self.updateControls(True)
     # Get ip address from line edit
     ip = self.ip_lineEdit.text().strip()
     port = None
     # If a port was provided, set as port attribute and remove it from the ip string
     if ':' in ip:
         try:
             port = int(ip[ip.find(':') + 1:])
         except ValueError:
             self.showMessage(
                 "Cannot read port entered. Enter as format: [IP address]:[Port Number].",
                 "Port Read Error")
             self.disconnectPressed()
             return
         ip = ip[:ip.find(':')]
     # Video stream
     try:
         self.video = VideoWorker(ip, port)
         self.videoThread = QtCore.QThread()
         #self.videoThread.started.connect(self.video.run)
         self.video.moveToThread(self.videoThread)
         self.video.newImage.connect(self.setFrame)
         self.videoThread.finished.connect(self.video.deleteLater)
         self.videoThread.start()
         QtCore.QTimer.singleShot(1, self.video.run)
         # Wait for video stream to connect
         startWait = time.time()
         while self.video.connectionSuccess is None:
             if time.time() - startWait > CONNECT_MAX_WAIT_SECONDS:
                 raise Exception(
                     "Timeout while waiting for connection to camera stream server."
                 )
             QApplication.processEvents()
     except Exception as e:
         pass
     finally:
         if self.video and not self.video.connectionSuccess:
             if not port:
                 port = DEFAULT_PORT
             self.showMessage(
                 "Unable to connect to Pi camera stream server at {}:{}.".
                 format(ip, port), "Connection Error")
             self.disconnectPressed()
Exemple #16
0
    def run_checks(self, container):
        with BusyCursor():
            self.show_busy()
            QApplication.processEvents()
            errors = run_checks(container)
            self.hide_busy()

        for err in sorted(errors, key=lambda e:(100 - e.level, e.name)):
            i = QListWidgetItem('%s\xa0\xa0\xa0\xa0[%s]' % (err.msg, err.name), self.items)
            i.setData(Qt.UserRole, err)
            i.setIcon(icon_for_level(err.level))
        if errors:
            self.items.setCurrentRow(0)
            self.current_item_changed()
            self.items.setFocus(Qt.OtherFocusReason)
        else:
            self.clear_help()
Exemple #17
0
    def show_output(self, raw, which='stdout', controller=None):
        def do_show():
            try:
                self.buf.append(raw)
                self.formatter.render_raw(raw, self.cursor)
            except:
                import traceback
                prints(traceback.format_exc())
                prints(raw, end='')

        if self.prompt_frame is not None:
            with Prepender(self):
                do_show()
        else:
            do_show()
        self.ensureCursorVisible()
        QApplication.processEvents()
Exemple #18
0
def save_dialog_raise():
    """Вызывает диалоговое окно, оповещающее об успешном сохранении игры"""

    from Model import logic_model

    logic_model.IsSaved = True
    logic_model.WasSaveInThisGame = True

    text = "Game has been saved!"
    dialog_window = QMessageBox()

    dialog_create(dialog_window, text)
    dialog_window.setStandardButtons(QMessageBox.Ok)
    dialog_window.setDefaultButton(QMessageBox.Ok)

    dialog_window.exec()
    QApplication.processEvents()
Exemple #19
0
    def run_checks(self, container):
        with BusyCursor():
            self.show_busy()
            QApplication.processEvents()
            errors = run_checks(container)
            self.hide_busy()

        for err in sorted(errors, key=lambda e:(100 - e.level, e.name)):
            i = QListWidgetItem('%s\xa0\xa0\xa0\xa0[%s]' % (err.msg, err.name), self.items)
            i.setData(Qt.UserRole, err)
            i.setIcon(icon_for_level(err.level))
        if errors:
            self.items.setCurrentRow(0)
            self.current_item_changed()
            self.items.setFocus(Qt.OtherFocusReason)
        else:
            self.clear_help()
Exemple #20
0
    def onCheckAllMN(self):
        try:
            printOK("Check-All pressed")
            for masternode in self.caller.masternode_list:
                self.curr_masternode_address = masternode['collateral'].get(
                    'address')
                self.curr_masternode_alias = masternode['name']
                printOK(
                    "Checking %s (%s)..." %
                    (self.curr_masternode_alias, self.curr_masternode_address))
                self.checkMN(None)
                self.displayMNStatus()
                QApplication.processEvents()

        except Exception as e:
            err_msg = "error in checkAllMN"
            printException(getCallerName(), getFunctionName(), err_msg, e)
Exemple #21
0
    def show_output(self, raw, which='stdout', controller=None):
        def do_show():
            try:
                self.buf.append(raw)
                self.formatter.render_raw(raw, self.cursor)
            except:
                import traceback
                prints(traceback.format_exc())
                prints(raw, end='')

        if self.prompt_frame is not None:
            with Prepender(self):
                do_show()
        else:
            do_show()
        self.ensureCursorVisible()
        QApplication.processEvents()
Exemple #22
0
    def add_image_diff(self, left_data, right_data):
        def load(data):
            p = QPixmap()
            p.loadFromData(as_bytes(data))
            try:
                dpr = self.devicePixelRatioF()
            except AttributeError:
                dpr = self.devicePixelRatio()
            p.setDevicePixelRatio(dpr)
            if data and p.isNull():
                p = self.failed_img
            return p

        left_img, right_img = load(left_data), load(right_data)
        change = []
        # Let any initial resizing of the window finish in case this is the
        # first diff, to avoid the expensive resize calculation later
        QApplication.processEvents(
            QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents
            | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers)
        for v, img, size in ((self.left, left_img, len(left_data)),
                             (self.right, right_img, len(right_data))):
            c = v.textCursor()
            c.movePosition(c.End)
            start = c.block().blockNumber()
            lines, w = self.get_lines_for_image(img, v)
            c.movePosition(c.StartOfBlock)
            if size > 0:
                c.beginEditBlock()
                c.insertText(
                    _('Size: {0} Resolution: {1}x{2}').format(
                        human_readable(size), img.width(), img.height()))
                for i in range(lines + 1):
                    c.insertBlock()
            change.extend((start, c.block().blockNumber()))
            c.insertBlock()
            c.endEditBlock()
            v.images[start] = (img, w, lines)
        change.append('replace' if left_data and right_data else
                      'delete' if left_data else 'insert')
        self.left.changes.append((change[0], change[1], change[-1]))
        self.right.changes.append((change[2], change[3], change[-1]))
        QApplication.processEvents(
            QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents
            | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers)
Exemple #23
0
 def scroll_to_cfi(self, cfi):
     if cfi:
         jid = self.cfi_job_id
         self.cfi_job_id += 1
         cfi = json.dumps(cfi)
         self.pending_scrolls.add(jid)
         self.document.mainFrame().evaluateJavaScript(
                 'paged_display.jump_to_cfi(%s, %d)' % (cfi, jid))
         # jump_to_cfi is async, so we wait for it to complete
         st = time.time()
         WAIT = 1  # seconds
         while jid in self.pending_scrolls and time.time() - st < WAIT:
             QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
             time.sleep(0.01)
         if jid in self.pending_scrolls:
             self.pending_scrolls.discard(jid)
             if DEBUG:
                 print(('jump_to_cfi() failed to complete after %s seconds' % WAIT))
Exemple #24
0
 def scroll_to_cfi(self, cfi):
     if cfi:
         jid = self.cfi_job_id
         self.cfi_job_id += 1
         cfi = json.dumps(cfi)
         self.pending_scrolls.add(jid)
         self.document.mainFrame().evaluateJavaScript(
                 'paged_display.jump_to_cfi(%s, %d)' % (cfi, jid))
         # jump_to_cfi is async, so we wait for it to complete
         st = time.time()
         WAIT = 1  # seconds
         while jid in self.pending_scrolls and time.time() - st < WAIT:
             QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
             time.sleep(0.01)
         if jid in self.pending_scrolls:
             self.pending_scrolls.discard(jid)
             if DEBUG:
                 print ('jump_to_cfi() failed to complete after %s seconds' % WAIT)
Exemple #25
0
 def remove_dirs(self, package):
     del_count = len(package.data.removes_list)
     package.data.title = "考虑清楚了吗?"
     package.data.text = f"批量删除 {del_count}个对象,删除后不可撤回!"
     if self.aer_you_sure(package):
         self.show_progress.emit()
         for i in package.data.removes_list:
             if self.set_progress:
                 progress_data = tools.Dict(operation="批量删除",
                                            name=os.path.basename(i),
                                            progress=100,
                                            speed="---",
                                            detail="",
                                            elapsed_time="00:00:00",
                                            remaining_time="00:00:00")
                 self.set_progress.emit(progress_data)
             QApplication.processEvents()
             self.local_table_func.remove(i)
         self.hide_progress.emit()
         self.local_reload_table()
Exemple #26
0
    def accept(self):
        folder = self.ui.LoadFolderPath.text()

        if not (os.path.exists(folder) and (os.path.isdir(folder))):
            QtWidgets.QMessageBox.information(
                None, "エラー", "指定したフォルダ「" + folder + "」が見つかりませんでした。",
                QMessageBox.Ok)
            return

        filelist = glob.glob(folder + "\*.zip")
        if len(filelist) == 0:
            QtWidgets.QMessageBox.information(None, "エラー",
                                              "zipファイルは見つかりませんでした。",
                                              QMessageBox.Ok)
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            for z in filelist:
                with zipfile.ZipFile(z, 'r') as zf:
                    decomp = zf.namelist()
                    if len(decomp) == 0:
                        self.ui.LogViewer.append("「" + zipfilename +
                                                 "」内にファイルが見つかりませんでした。")
                        continue
                    for dfile in decomp:
                        with zf.open(dfile, 'r') as file:
                            gmldem = JpGisGML()
                            text = file.read().decode('utf_8')
                            gmldem.ReadText(text)
                            gmldem.ToGeoTiff(folder)

                        self.ui.LogViewer.append(dfile + " :終了")
                        QApplication.processEvents(
                            QEventLoop.ExcludeUserInputEvents)
        finally:
            QApplication.restoreOverrideCursor()
            QtWidgets.QMessageBox.information(None, "終了", "終了しました。",
                                              QMessageBox.Ok)
Exemple #27
0
 def run(self):
     data_path = r'C:\repositories\autonomic_car\selfie_car\data_intake3'
     data_path = r'C:\repositories\autonomic_car\selfie_car\data_intake3'
     df_path = r"C:\repositories\rgb.txt"
     dataframe = pd.read_csv(df_path,
                             skiprows=[0, 1, 2],
                             names=['timestamp', 'filename'],
                             sep=' ')
     time.sleep(3)
     i = 0
     prev = None
     print('running')
     for i, (timestamp, filename) in dataframe.iterrows():
         impath = os.path.join(data_path, filename)
         img = cv2.imread(impath)
         assert img is not None, "Error while reading image {}".format(
             impath)
         #logger.debug("Sending with timestamp {}".format(timestamp))
         self.qscm.image_to_send.emit(img, timestamp)
         print(filename, timestamp)
         while self.semaphore_image:
             QApplication.processEvents()
             time.sleep(0.05)
         self.semaphore_image = True
         if prev is None:
             time.sleep(0.5)
             prev = timestamp
         else:
             #time.sleep(timestamp-prev)
             prev = timestamp
         if i % 50 == 0:
             self.qscm.trajectory_request.emit()
             while self.semaphore_trajectory:
                 QApplication.processEvents()
                 time.sleep(0.05)
             print("****TRAJ***************************")
             print(self.response_data)
             print("*************************************")
             self.semaphore_trajectory = True
Exemple #28
0
    def onCheckAllMN(self):
        if not self.caller.rpcConnected:
            self.caller.myPopUp2(
                QMessageBox.Critical, 'SPMT - hw device check',
                "RPC server must be connected to perform this action.")
            printDbg("Unable to connect: %s" % self.caller.rpcStatusMess)
            return
        try:
            printOK("Check-All pressed")
            self.updateAllMasternodes()
            for masternode in self.caller.masternode_list:
                self.curr_masternode_alias = masternode['name']
                self.curr_masternode_address = masternode['collateral'].get(
                    'address')
                printOK(
                    "Checking %s (%s)..." %
                    (self.curr_masternode_alias, self.curr_masternode_address))
                self.displayMNStatus()
                QApplication.processEvents()

        except Exception as e:
            err_msg = "error in checkAllMN"
            printException(getCallerName(), getFunctionName(), err_msg, e)
Exemple #29
0
 def updateProgressPercent(self, percent):
     self.ui.loadingLinePercent.setValue(percent)
     QApplication.processEvents()
Exemple #30
0
    def SendRewards(self, useSwiftX, inputs=None, gui=None):
        # Default slots on tabRewards
        if gui is None:
            gui = self

        # re-connect signals
        try:
            self.caller.hwdevice.api.sigTxdone.disconnect()
        except:
            pass
        try:
            self.caller.hwdevice.api.sigTxabort.disconnect()
        except:
            pass
        try:
            self.caller.hwdevice.api.tx_progress.disconnect()
        except:
            pass
        self.caller.hwdevice.api.sigTxdone.connect(gui.FinishSend)
        self.caller.hwdevice.api.sigTxabort.connect(gui.AbortSend)
        self.caller.hwdevice.api.tx_progress.connect(gui.updateProgressPercent)

        # Check destination Address
        if not checkPivxAddr(self.dest_addr, self.caller.isTestnetRPC):
            myPopUp_sb(self.caller, "crit", 'SPMT - PIVX address check', "The destination address is missing, or invalid.")
            return None

        if inputs is None:
            # send from single path
            num_of_inputs = len(self.selectedRewards)
        else:
            # bulk send
            num_of_inputs = sum([len(x['utxos']) for x in inputs])
        ans = checkTxInputs(self.caller, num_of_inputs)
        if ans is None or ans == QMessageBox.No:
            # emit sigTxAbort and return
            self.caller.hwdevice.api.sigTxabort.emit()
            return None

        # LET'S GO
        if inputs is None:
            printDbg("Sending from PIVX address  %s  to PIVX address  %s " % (self.curr_addr, self.dest_addr))
        else:
            printDbg("Sweeping rewards to PIVX address %s " % self.dest_addr)
        printDbg("Preparing transaction. Please wait...")
        self.ui.loadingLine.show()
        self.ui.loadingLinePercent.show()
        QApplication.processEvents()

        # save last destination address and swiftxCheck to cache and persist to settings
        self.caller.parent.cache["lastAddress"] = persistCacheSetting('cache_lastAddress', self.dest_addr)
        self.caller.parent.cache["useSwiftX"] = persistCacheSetting('cache_useSwiftX', useSwiftX)

        try:
            self.txFinished = False
            if inputs is None:
                # send from single path
                self.caller.hwdevice.prepare_transfer_tx(self.caller,
                                                         self.curr_hwpath,
                                                         self.selectedRewards,
                                                         self.dest_addr,
                                                         self.currFee,
                                                         useSwiftX,
                                                         self.caller.isTestnetRPC)
            else:
                # bulk send
                self.caller.hwdevice.prepare_transfer_tx_bulk(self.caller,
                                                              inputs,
                                                              self.dest_addr,
                                                              self.currFee,
                                                              useSwiftX,
                                                              self.caller.isTestnetRPC)

        except DisconnectedException as e:
            self.caller.hwStatus = 0
            self.caller.updateHWleds()

        except Exception as e:
            err_msg = "Error while preparing transaction. <br>"
            err_msg += "Probably Blockchain wasn't synced when trying to fetch raw TXs.<br>"
            err_msg += "<b>Wait for full synchronization</b> then hit 'Clear/Reload'"
            printException(getCallerName(), getFunctionName(), err_msg, e.args)
Exemple #31
0
            elif req[0] == "sync":
                log.info("Sync reports with server started")
                self._do_sync()
                log.info("Sync reports with server finished")
            else:
                log.error(DEBUG_REPORTMGR, "reportmgr thread, unknown command %s" % req[0])


if __name__ == '__main__':
    """
    Unit test
    """
    import time
    import logging
    from PyQt5.Qt import QApplication
    
    log.setLevel(logging.DEBUG)
    app = createQApplication()

    localdb = util.openLocalDatabase2(":memory:")
    
    reportMgr = ReportMgr(localdb=localdb)
    reportMgr.init()
    reportMgr.sync()
    reportMgr.stop()

    while not reportMgr.toThreadQ.empty():
        QApplication.processEvents()
        time.sleep(0.5)
Exemple #32
0
    def add_text_diff(self, left_text, right_text, context, syntax, beautify=False):
        left_text = unicodedata.normalize('NFC', left_text)
        right_text = unicodedata.normalize('NFC', right_text)
        if beautify and syntax in {'xml', 'html', 'css'}:
            left_text, right_text = beautify_text(left_text, syntax), beautify_text(right_text, syntax)
            if len(left_text) == len(right_text) and left_text == right_text:
                for v in (self.left, self.right):
                    c = v.textCursor()
                    c.movePosition(c.End)
                    c.insertText('[%s]\n\n' % _('The files are identical after beautifying'))
                return

        left_lines = self.left_lines = left_text.splitlines()
        right_lines = self.right_lines = right_text.splitlines()

        cruncher = get_sequence_matcher()(None, left_lines, right_lines)

        left_highlight, right_highlight = get_highlighter(self.left, left_text, syntax), get_highlighter(self.right, right_text, syntax)
        cl, cr = self.left_cursor, self.right_cursor = self.left.textCursor(), self.right.textCursor()
        cl.beginEditBlock(), cr.beginEditBlock()
        cl.movePosition(cl.End), cr.movePosition(cr.End)
        self.left_insert = partial(self.do_insert, cl, left_highlight, self.left.line_number_map)
        self.right_insert = partial(self.do_insert, cr, right_highlight, self.right.line_number_map)

        self.changes = []

        if context is None:
            for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
                getattr(self, tag)(alo, ahi, blo, bhi)
                QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
        else:
            def insert_boundary():
                self.changes.append(Change(
                    ltop=cl.block().blockNumber()-1, lbot=cl.block().blockNumber(),
                    rtop=cr.block().blockNumber()-1, rbot=cr.block().blockNumber(), kind='boundary'))
                self.left.line_number_map[self.changes[-1].ltop] = '-'
                self.right.line_number_map[self.changes[-1].rtop] = '-'

            ahi = bhi = 0
            for i, group in enumerate(cruncher.get_grouped_opcodes(context)):
                for j, (tag, alo, ahi, blo, bhi) in enumerate(group):
                    if j == 0 and (i > 0 or min(alo, blo) > 0):
                        insert_boundary()
                    getattr(self, tag)(alo, ahi, blo, bhi)
                    QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
                cl.insertBlock(), cr.insertBlock()
            if ahi < len(left_lines) - 1 or bhi < len(right_lines) - 1:
                insert_boundary()

        cl.endEditBlock(), cr.endEditBlock()
        del self.left_lines
        del self.right_lines
        del self.left_insert
        del self.right_insert

        self.coalesce_changes()

        for ltop, lbot, rtop, rbot, kind in self.changes:
            if kind != 'equal':
                self.left.changes.append((ltop, lbot, kind))
                self.right.changes.append((rtop, rbot, kind))

        del self.changes
Exemple #33
0
    def load_ebook(self, pathtoebook, open_at=None, reopen_at=None):
        if self.iterator is not None:
            self.save_current_position()
            self.iterator.__exit__()
        self.iterator = EbookIterator(pathtoebook, copy_bookmarks_to_file=self.view.document.copy_bookmarks_to_file)
        self.history.clear()
        self.open_progress_indicator(_('Loading ebook...'))
        worker = Worker(target=partial(self.iterator.__enter__, view_kepub=True))
        worker.start()
        while worker.isAlive():
            worker.join(0.1)
            QApplication.processEvents()
        if worker.exception is not None:
            if isinstance(worker.exception, DRMError):
                from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                DRMErrorMessage(self).exec_()
            else:
                r = getattr(worker.exception, 'reason', worker.exception)
                error_dialog(self, _('Could not open ebook'),
                        as_unicode(r) or _('Unknown error'),
                        det_msg=worker.traceback, show=True)
            self.close_progress_indicator()
        else:
            self.metadata.show_opf(self.iterator.opf,
                    self.iterator.book_format)
            self.view.current_language = self.iterator.language
            title = self.iterator.opf.title
            if not title:
                title = os.path.splitext(os.path.basename(pathtoebook))[0]
            if self.iterator.toc:
                self.toc_model = TOC(self.iterator.spine, self.iterator.toc)
                self.toc.setModel(self.toc_model)
                if self.show_toc_on_open:
                    self.action_table_of_contents.setChecked(True)
            else:
                self.toc_model = TOC(self.iterator.spine)
                self.toc.setModel(self.toc_model)
                self.action_table_of_contents.setChecked(False)
            if isbytestring(pathtoebook):
                pathtoebook = force_unicode(pathtoebook, filesystem_encoding)
            vh = vprefs.get('viewer_open_history', [])
            try:
                vh.remove(pathtoebook)
            except:
                pass
            vh.insert(0, pathtoebook)
            vprefs.set('viewer_open_history', vh[:50])
            self.build_recent_menu()

            self.footnotes_dock.close()
            self.action_table_of_contents.setDisabled(not self.iterator.toc)
            self.current_book_has_toc = bool(self.iterator.toc)
            self.current_title = title
            self.setWindowTitle(title + ' [%s]'%self.iterator.book_format + ' - ' + self.base_window_title)
            self.pos.setMaximum(sum(self.iterator.pages))
            self.pos.setSuffix(' / %d'%sum(self.iterator.pages))
            self.vertical_scrollbar.setMinimum(100)
            self.vertical_scrollbar.setMaximum(100*sum(self.iterator.pages))
            self.vertical_scrollbar.setSingleStep(10)
            self.vertical_scrollbar.setPageStep(100)
            self.set_vscrollbar_value(1)
            self.current_index = -1
            QApplication.instance().alert(self, 5000)
            previous = self.set_bookmarks(self.iterator.bookmarks)
            if reopen_at is not None:
                previous = reopen_at
            if open_at is None and previous is not None:
                self.goto_bookmark(previous)
            else:
                if open_at is None:
                    self.next_document()
                else:
                    if open_at > self.pos.maximum():
                        open_at = self.pos.maximum()
                    if open_at < self.pos.minimum():
                        open_at = self.pos.minimum()
                    self.goto_page(open_at, loaded_check=False)
 def _check():
     from PyQt5.Qt import QApplication
     QApplication.processEvents()
     f(*args, **kwds)
Exemple #35
0
 def __enter__(self):
     self.stacks.setCurrentIndex(0)
     self.busy.setVisible(True)
     self.busy.pi.startAnimation()
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
Exemple #36
0
    def add_text_diff(self, left_text, right_text, context, syntax, beautify=False):
        left_text = unicodedata.normalize('NFC', left_text)
        right_text = unicodedata.normalize('NFC', right_text)
        if beautify and syntax in {'xml', 'html', 'css'}:
            left_text, right_text = beautify_text(left_text, syntax), beautify_text(right_text, syntax)
            if len(left_text) == len(right_text) and left_text == right_text:
                for v in (self.left, self.right):
                    c = v.textCursor()
                    c.movePosition(c.End)
                    c.insertText('[%s]\n\n' % _('The files are identical after beautifying'))
                return

        left_lines = self.left_lines = left_text.splitlines()
        right_lines = self.right_lines = right_text.splitlines()

        cruncher = get_sequence_matcher()(None, left_lines, right_lines)

        left_highlight, right_highlight = get_highlighter(self.left, left_text, syntax), get_highlighter(self.right, right_text, syntax)
        cl, cr = self.left_cursor, self.right_cursor = self.left.textCursor(), self.right.textCursor()
        cl.beginEditBlock(), cr.beginEditBlock()
        cl.movePosition(cl.End), cr.movePosition(cr.End)
        self.left_insert = partial(self.do_insert, cl, left_highlight, self.left.line_number_map)
        self.right_insert = partial(self.do_insert, cr, right_highlight, self.right.line_number_map)

        self.changes = []

        if context is None:
            for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
                getattr(self, tag)(alo, ahi, blo, bhi)
                QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
        else:
            def insert_boundary():
                self.changes.append(Change(
                    ltop=cl.block().blockNumber()-1, lbot=cl.block().blockNumber(),
                    rtop=cr.block().blockNumber()-1, rbot=cr.block().blockNumber(), kind='boundary'))
                self.left.line_number_map[self.changes[-1].ltop] = '-'
                self.right.line_number_map[self.changes[-1].rtop] = '-'

            ahi = bhi = 0
            for i, group in enumerate(cruncher.get_grouped_opcodes(context)):
                for j, (tag, alo, ahi, blo, bhi) in enumerate(group):
                    if j == 0 and (i > 0 or min(alo, blo) > 0):
                        insert_boundary()
                    getattr(self, tag)(alo, ahi, blo, bhi)
                    QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers)
                cl.insertBlock(), cr.insertBlock()
            if ahi < len(left_lines) - 1 or bhi < len(right_lines) - 1:
                insert_boundary()

        cl.endEditBlock(), cr.endEditBlock()
        del self.left_lines
        del self.right_lines
        del self.left_insert
        del self.right_insert

        self.coalesce_changes()

        for ltop, lbot, rtop, rbot, kind in self.changes:
            if kind != 'equal':
                self.left.changes.append((ltop, lbot, kind))
                self.right.changes.append((rtop, rbot, kind))

        del self.changes
Exemple #37
0
    def onSendRewards(self):
        self.dest_addr = self.ui.destinationLine.text().strip()

        # Check HW device
        if self.caller.hwStatus != 2:
            myPopUp_sb(self.caller, "crit", 'PET4L - hw device check',
                       "Connect to HW device first")
            printDbg(
                "Unable to connect to hardware device. The device status is: %d"
                % self.caller.hwStatus)
            return None

        # Check destination Address
        if not checkPivxAddr(self.dest_addr, self.caller.isTestnetRPC):
            myPopUp_sb(self.caller, "crit", 'PET4L - PIVX address check',
                       "The destination address is missing, or invalid.")
            return None

        # LET'S GO
        if self.selectedRewards:
            printDbg("Sending from PIVX address  %s  to PIVX address  %s " %
                     (self.curr_addr, self.dest_addr))
            printDbg("Preparing transaction. Please wait...")
            try:
                self.ui.loadingLine.show()
                self.ui.loadingLinePercent.show()
                QApplication.processEvents()
                self.currFee = self.ui.feeLine.value() * 1e8

                # save last destination address and swiftxCheck to cache and persist to settings
                self.caller.parent.cache["lastAddress"] = persistCacheSetting(
                    'cache_lastAddress', self.dest_addr)
                self.caller.parent.cache["useSwiftX"] = persistCacheSetting(
                    'cache_useSwiftX', self.useSwiftX())

                self.currFee = self.ui.feeLine.value() * 1e8
                # re-connect signals
                try:
                    self.caller.hwdevice.api.sigTxdone.disconnect()
                except:
                    pass
                try:
                    self.caller.hwdevice.api.sigTxabort.disconnect()
                except:
                    pass
                try:
                    self.caller.hwdevice.api.tx_progress.disconnect()
                except:
                    pass
                self.caller.hwdevice.api.sigTxdone.connect(self.FinishSend)
                self.caller.hwdevice.api.sigTxabort.connect(self.AbortSend)
                self.caller.hwdevice.api.tx_progress.connect(
                    self.updateProgressPercent)

                try:
                    self.txFinished = False
                    self.caller.hwdevice.prepare_transfer_tx(
                        self.caller, self.curr_path,
                        self.selectedRewards, self.dest_addr, self.currFee,
                        self.useSwiftX(), self.caller.isTestnetRPC)
                except DisconnectedException as e:
                    self.caller.hwStatus = 0
                    self.caller.updateHWleds()

                except Exception as e:
                    err_msg = "Error while preparing transaction. <br>"
                    err_msg += "Probably Blockchain wasn't synced when trying to fetch raw TXs.<br>"
                    err_msg += "<b>Wait for full synchronization</b> then hit 'Clear/Reload'"
                    printException(getCallerName(), getFunctionName(), err_msg,
                                   e.args)
            except Exception as e:
                print(e)
        else:
            myPopUp_sb(self.caller, "warn", 'Transaction NOT sent',
                       "No UTXO to send")
 def setFrame(self, frame):
     self.videoLabel.setPixmap(frame)
     self.pixmap = frame
     QApplication.processEvents()
Exemple #39
0
    def load_ebook(self, pathtoebook, open_at=None, reopen_at=None):
        if self.iterator is not None:
            self.save_current_position()
            self.iterator.__exit__()
        self.iterator = EbookIterator(pathtoebook, copy_bookmarks_to_file=self.view.document.copy_bookmarks_to_file)
        self.history.clear()
        self.open_progress_indicator(_('Loading ebook...'))
        worker = Worker(target=partial(self.iterator.__enter__, view_kepub=True))
        worker.path_to_ebook = pathtoebook
        worker.start()
        while worker.isAlive():
            worker.join(0.1)
            QApplication.processEvents()
        if worker.exception is not None:
            tb = worker.traceback.strip()
            if tb and tb.splitlines()[-1].startswith('DRMError:'):
                from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                DRMErrorMessage(self).exec_()
            else:
                r = getattr(worker.exception, 'reason', worker.exception)
                error_dialog(self, _('Could not open ebook'),
                        as_unicode(r) or _('Unknown error'),
                        det_msg=tb, show=True)
            self.close_progress_indicator()
        else:
            self.metadata.show_opf(self.iterator.opf,
                    self.iterator.book_format)
            self.view.current_language = self.iterator.language
            title = self.iterator.opf.title
            if not title:
                title = os.path.splitext(os.path.basename(pathtoebook))[0]
            if self.iterator.toc:
                self.toc_model = TOC(self.iterator.spine, self.iterator.toc)
                self.toc.setModel(self.toc_model)
                if self.show_toc_on_open:
                    self.action_table_of_contents.setChecked(True)
            else:
                self.toc_model = TOC(self.iterator.spine)
                self.toc.setModel(self.toc_model)
                self.action_table_of_contents.setChecked(False)
            if isbytestring(pathtoebook):
                pathtoebook = force_unicode(pathtoebook, filesystem_encoding)
            vh = vprefs.get('viewer_open_history', [])
            try:
                vh.remove(pathtoebook)
            except:
                pass
            vh.insert(0, pathtoebook)
            vprefs.set('viewer_open_history', vh[:50])
            self.build_recent_menu()

            self.footnotes_dock.close()
            self.action_table_of_contents.setDisabled(not self.iterator.toc)
            self.current_book_has_toc = bool(self.iterator.toc)
            self.current_title = title
            self.setWindowTitle(title + ' [%s]'%self.iterator.book_format + ' - ' + self.base_window_title)
            self.pos.setMaximum(sum(self.iterator.pages))
            self.pos.setSuffix(' / %d'%sum(self.iterator.pages))
            self.vertical_scrollbar.setMinimum(100)
            self.vertical_scrollbar.setMaximum(100*sum(self.iterator.pages))
            self.vertical_scrollbar.setSingleStep(10)
            self.vertical_scrollbar.setPageStep(100)
            self.set_vscrollbar_value(1)
            self.current_index = -1
            QApplication.instance().alert(self, 5000)
            previous = self.set_bookmarks(self.iterator.bookmarks)
            if reopen_at is not None:
                previous = reopen_at
            if open_at is None and previous is not None:
                self.goto_bookmark(previous)
            else:
                if open_at is None:
                    self.next_document()
                else:
                    if open_at > self.pos.maximum():
                        open_at = self.pos.maximum()
                    if open_at < self.pos.minimum():
                        open_at = self.pos.minimum()
                    if self.resize_in_progress:
                        self.pending_goto_page = open_at
                    else:
                        self.goto_page(open_at, loaded_check=False)
Exemple #40
0
    def do_POST(self):

        # Unpack metadata
        content_type = self.headers['Content-Type']
        content_length = int(self.headers['Content-Length'])
        file_type = self.headers['File-Type']
        device_type = self.headers['Device-Type']
        device_name = self.headers['Device-Name']
        file_path = self.headers['File-Path']
        file_name = self.headers['File-Name']

        if content_type != 'cdrv-cmd/File-Upload':
            self.streamer.add_log.emit(
                "Commande non-acceptée: " + content_type,
                LogTypes.LOGTYPE_WARNING)
            self.send_response(400)
            self.end_headers()
            return

        if None in [file_type, device_type, device_name, file_path, file_name]:
            self.streamer.add_log.emit("Requête mal-formattée. Refusée.",
                                       LogTypes.LOGTYPE_ERROR)
            self.streamer.file_error_occured.emit(
                file_name, "Requête mal formattée. Refusée.")
            self.send_response(400)
            self.end_headers()
            return

        destination_dir = (self.streamer.server_save_path + '/' + device_name + '/' + file_path + '/').replace('//', '/') \
            .replace('/', os.sep)
        destination_path = destination_dir + file_name

        file_name = device_name + file_path + '/' + file_name
        self.streamer.add_log.emit(
            "Réception en cours: " + file_name + " (" + str(content_length) +
            " octets)", LogTypes.LOGTYPE_INFO)

        # Check if file exists and size matches
        file_infos = Path(destination_path)
        if file_infos.exists():
            file_infos = os.stat(destination_path)
            if file_infos.st_size < content_length:
                self.streamer.add_log.emit(
                    "Fichier existant, mais incomplet (" +
                    str(file_infos.st_size) + "/" + str(content_length) +
                    " octets) - retransfert.", LogTypes.LOGTYPE_WARNING)
            else:
                self.streamer.add_log.emit("Fichier existant - ignoré.",
                                           LogTypes.LOGTYPE_WARNING)
                self.streamer.update_progress.emit(file_name, "", 100, 100)
                self.send_response(200)
                self.send_header('Content-type', 'file-transfer/ack')
                self.end_headers()
                return

        # Destination directory if it doesn't exist
        Path(destination_dir).mkdir(parents=True, exist_ok=True)

        # Gets the data and save to file
        buffer_size = 4 * 1024
        content_size_remaining = content_length
        last_pc = -1

        # Supported file type?
        if file_type.lower() in ['data', 'dat', 'csv', 'txt', 'oimi']:

            if file_type.lower() in ['data', 'dat']:
                # Binary file
                fh = open(destination_path, 'wb')
                text_format = False
            else:
                # Text file
                fh = open(destination_path, 'w')
                text_format = True

            while content_size_remaining > 0 and self.streamer.server_running:
                QApplication.processEvents()
                if buffer_size > content_size_remaining:
                    buffer_size = content_size_remaining
                data = self.rfile.read(buffer_size)
                if text_format:
                    fh.write(data.decode())
                else:
                    fh.write(data)
                content_size_remaining -= buffer_size
                content_received = (content_length - content_size_remaining)
                pc = math.floor((content_received / content_length) * 100)
                if pc != last_pc:
                    self.streamer.update_progress.emit(
                        file_name, " (" + str(content_received) + "/ " +
                        str(content_length) + ")",
                        (content_length - content_size_remaining),
                        content_length)
                    last_pc = pc
            fh.close()
        else:
            self.streamer.add_log.emit(
                "Type de fichier non-supporté: " + file_type.lower(),
                LogTypes.LOGTYPE_ERROR)
            self.streamer.file_error_occured.emit(
                file_name,
                "Type de fichier non-supporté: " + file_type.lower())
            self.send_response(400)
            self.send_header('Content-type', 'file-transfer/invalid-file-type')
            self.end_headers()
            return

        # Check if everything was received correctly
        file_infos = os.stat(destination_path)
        if file_infos.st_size < content_length:
            # Missing data?!?!
            error = "Erreur de transmission:  " + str(
                file_infos.st_size) + " octets reçus sur " + str(
                    content_length)
            self.streamer.add_log.emit(error, LogTypes.LOGTYPE_ERROR)
            self.streamer.file_error_occured.emit(file_name, error)
        else:
            # All is good!
            self.streamer.add_log.emit("Complété", LogTypes.LOGTYPE_DONE)
        self.send_response(200)
        self.send_header('Content-type', 'file-transfer/ack')
        self.end_headers()