Ejemplo n.º 1
0
    def spawn_worker_thread(self, worker, **signals):
        # Setup worker and its thread
        thread = QThread(self.parent)
        thread.setTerminationEnabled(True)
        worker.moveToThread(thread)
        thread.started.connect(worker.run)
        thread.worker = worker # TODO: needed?

        # Connect log and any extra signals
        worker.log_signal.connect(self.log_append)
        for signal_name in signals:
            getattr(worker, signal_name).connect(signals[signal_name])

        thread.start()

        self.current_worker_thread = thread
Ejemplo n.º 2
0
class QtCodeGen(QtWidgets.QDialog):
    # Folgende Widgets stehen zur Verfügung:
    def __init__(self, kontaktdaten: dict, ROOT_PATH: str, parent = None):
        super().__init__(parent)
        uic.loadUi(os.path.join(PATH, "ui_qtcodegen.ui"), self)
        self.setupUi(self, ROOT_PATH)
        
        self.parent = parent
        self._hardClose = False
        
        # Attribute erstellen
        self.kontaktdaten = kontaktdaten
        self.ROOT_PATH = ROOT_PATH

        # std.out & error auf das Textfeld umleiten
        sys.stdout = EigenerStream(text_schreiben=self.update_ausgabe)
        sys.stderr = EigenerStream(text_schreiben=self.update_ausgabe)

        # Entsprechend Konfigurieren
        self.setup_thread()
        self.thread.start()
        
        # show gui
        self.show()
  
    def __del__(self):
        print("QtCodeGen destruct")
        
    def setupUi(self, QtCodeGen, ROOT_PATH):
        self.setObjectName("QtCodeGen")
        self.setWindowModality(QtCore.Qt.WindowModal)
        self.setModal(False)
        self.resize(700, 300)
        self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint);
        self.setWindowIcon(QIcon(os.path.join(ROOT_PATH, "images/spritze.ico")))

    def setup_thread(self):
        """
        Thread + Worker erstellen und Konfigurieren
        """
        self.thread = QThread(parent=self)
        self.thread.setTerminationEnabled(True)
        self.worker = Worker(self.kontaktdaten, self.ROOT_PATH)
        
        # Worker und Thread verbinden
        self.worker.moveToThread(self.thread)
        
        # Signale setzen
        self.thread.started.connect(self.worker.code_gen)
        self.worker.signalShowInput.connect(self.showInputDlg)
        self.worker.signalShowDlg.connect(self.showDlg)


    def update_ausgabe(self, text):
        """
        Fügt den übergeben Text dem textAusgabe hinzu

        Args:
            text (str): Text welcher hinzukommen soll
        """

        # Austausch der Farbcodes / Ascii Zeichen aus der Shell
        listeCodes = ['\033[95m', '\033[91m', '\033[33m', '\x1b[0m', '\033[94m', '\033[32m', '\033[0m']
        for farbcode in listeCodes:
            if farbcode in text:
                if farbcode == '\033[95m' or farbcode == '\033[91m':
                    text = f"<div style='color:red'>{text}</div>"
                elif farbcode == '\033[33m':
                    text = f"<div style='color:orange'>{text}</div>"
                elif farbcode == '\x1b[0m':
                    text = f"<div>{text}</div>"
                elif farbcode == '\033[94m':
                    text = f"<div style='color:blue'>{text}</div>"
                elif farbcode == '\033[32m':
                    text = f"<div style='color:green'>{text}</div>"
                text = text.replace(farbcode, '')

        cursor = self.textAusgabe.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertHtml(str(text))
        cursor.insertText(str("\n"))
        self.textAusgabe.setTextCursor(cursor)
        self.textAusgabe.ensureCursorVisible()

    def showInputDlg(self, dlgType):
        
        if dlgType == "GEBURTSDATUM":
           while True:
                try:
                    text, ok = QtWidgets.QInputDialog.getText(self, 'Geburtsdatum', 'Bitte trage nachfolgend dein Geburtsdatum im Format DD.MM.YYYY ein.\n'
                        'Beispiel: 02.03.1982\n')
                    if ok:
                        geburtsdatum = str(text)
                        validate_datum(geburtsdatum)
                        self.worker.signalUpdateData.emit("GEBURTSDATUM",geburtsdatum)
                        break
                    else:
                        self.hardClose()
                        break
                except ValidationError as exc:
                    QtWidgets.QMessageBox.critical(self, "Geburtsdatum ungültiges Format", "Das Datum entspricht nicht dem richtigen Format (DD.MM.YYYY).")
 
        elif dlgType == "SMSCODE_OK":
            ret = QtWidgets.QMessageBox.information(self, "Erfolgreich", "Code erfolgreich generiert. Du kannst jetzt mit der Terminsuche fortfahren.",QMessageBox.StandardButton.Ok)
            if ret == QMessageBox.StandardButton.Ok:
                self.worker.signalUpdateData.emit("SMSCODE_OK","")
                self.hardClose()
            
    def showDlg(self, strMode, strTxt):
        if strMode == "MISSING_KONTAKT":
            ret = QtWidgets.QMessageBox.critical(self, "Kontaktdaten ungültig",
                "Die Kontakdaten sind nicht korrekt!.\n\nBitte Datei neu erstellen!", QMessageBox.StandardButton.Ok)
            if ret == QMessageBox.StandardButton.Ok:
                self.hardClose()
        elif strMode == "CRITICAL_CLOSE":
            ret = QtWidgets.QMessageBox.critical(self, "Error", strTxt, QMessageBox.StandardButton.Ok)
            if ret == QMessageBox.StandardButton.Ok:
                self.hardClose()

                
    # force to close the dialog without confirmation
    def hardClose(self):
        self._hardClose = True
        self.close()
         
    def closeEvent(self, event):
        """
        Wird aufgerufen, wenn die Anwendung geschlossen wird
        """

        if self.thread.isRunning():
            if self._hardClose is False:
                res = QtWidgets.QMessageBox.warning(self, "Suche beenden", "Suche wirklich beenden?\n",
                                                    (QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel))

                if res != QMessageBox.StandardButton.Ok:
                    event.ignore()
                    return
                
            
        #exit

        #stop worker
        self.worker.stop()
        self.worker.deleteLater()

        #stop thread
        self.thread.quit()
        self.thread.wait(3000)
        self.thread.terminate()

        # Streams wieder korrigieren, damit kein Fehler kommt
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

        self.deleteLater()
        event.accept()

    @staticmethod
    def start_code_gen(kontaktdaten: dict,  ROOT_PATH: str):
        app = QtWidgets.QApplication(list())
        window = QtCodeGen(kontaktdaten, ROOT_PATH)
        app.exec_()
Ejemplo n.º 3
0
class ExampleThread(Qt.QWidget):
    def __init__(self, parent=None):
        super(ExampleThread, self).__init__(parent)

        layout = Qt.QVBoxLayout(self)
        self.lbl = Qt.QLabel("Start")
        layout.addWidget(self.lbl)
        self.btnA = Qt.QPushButton("Запустить AThread(QThread)")
        layout.addWidget(self.btnA)
        self.btnB = Qt.QPushButton("Запустить SomeObject(QObject)")
        layout.addWidget(self.btnB)
        self.btnC = Qt.QPushButton("Запустить Worker(QRunnable)")
        layout.addWidget(self.btnC)
        self.progressBar = Qt.QProgressBar()
        self.progressBar.setProperty("value", 0)
        layout.addWidget(self.progressBar)

        self.setGeometry(550, 65, 300, 300)
        self.setWindowTitle('3 разных и простых способа работы с потоками.')

        self.btnA.clicked.connect(self.using_q_thread)
        self.btnB.clicked.connect(self.using_move_to_thread)
        self.btnC.clicked.connect(self.using_q_runnable)

        self.msg = MsgBoxAThread()
        self.thread = None

        self.msgSomeObject = MsgBoxSomeObject()
        self.objThread = None

        self.counter = 0
        self.timer = Qt.QTimer()
        self.timer.setInterval(1000)
        # -------- timeout -------> def recurring_timer(self):
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()

        self.threadpool = QThreadPool()
        print("Max потоков, кот. будут использоваться=`%d`" % self.threadpool.maxThreadCount())
        self.msgWorker = MsgBoxWorker()

        self.threadtest = QThread(self)
        self.idealthreadcount = self.threadtest.idealThreadCount()
        print("Ваша машина может обрабатывать `{}` потокa оптимально.".format(self.idealthreadcount))

    def recurring_timer(self):
        self.counter += 1
        self.lbl.setText("СЧЁТЧИК цикл GUI: %d" % self.counter)

    # ---- AThread(QThread) -----------#
    def using_q_thread(self):
        if self.thread is None:
            self.thread = AThread()
            self.thread.threadSignalAThread.connect(self.on_threadSignalAThread)
            self.thread.finished.connect(self.finishedAThread)
            self.thread.start()
            self.btnA.setText("Stop AThread(QThread)")
        else:
            self.thread.terminate()
            self.thread = None
            self.btnA.setText("Start AThread(QThread)")

    def finishedAThread(self):
        self.thread = None
        self.btnA.setText("Start AThread(QThread)")

    def on_threadSignalAThread(self, value):
        self.msg.label.setText(str(value))
        # Восстанавливаем визуализацию потокового окна, если его закрыли. Поток работает.
        # .setVisible(true) или .show() устанавливает виджет в видимое состояние,
        # если видны все его родительские виджеты до окна.
        if not self.msg.isVisible():
            self.msg.show()

    # --END-- AThread(QThread) -------------------#

    # ---- SomeObject(QObject) -------------------#
    def using_move_to_thread(self):
        if self.objThread is None:
            self.objThread = QThread()
            self.obj = SomeObject()
            self.obj.moveToThread(self.objThread)  # Переместить в поток для выполнения

            self.obj.threadSignalSomeObject.connect(self.on_threadSignalSomeObject)
            self.obj.finishedSomeObject.connect(self.finishedSomeObject)
            self.objThread.started.connect(self.obj.long_running)
            self.objThread.start()

            self.btnB.setText("Wait SomeObject(QObject)")
            self.btnB.setEnabled(False)
        else:
            pass

    def finishedSomeObject(self):
        self.objThread.terminate()
        self.objThread.wait(1)

        self.objThread = None
        self.btnB.setEnabled(True)
        self.btnB.setText("Start SomeObject(QObject)")

    def on_threadSignalSomeObject(self, value):
        self.msgSomeObject.label.setText(str(value))
        # Восстанавливаем визуализацию потокового окна, если его закрыли. Поток работает.
        if not self.msgSomeObject.isVisible():
            self.msgSomeObject.show()

    # --END-- SomeObject(QObject) -------------------#

    # ---- Worker(QRunnable) ------------------------#
    def using_q_runnable(self):
        # Передайте функцию для выполнения
        # Любые другие аргументы, kwargs передаются функции run
        worker = Worker(self.execute_this_fn)
        worker.signals.result.connect(self.print_output)
        worker.signals.finish.connect(self.thread_complete)
        worker.signals.progress.connect(self.progress_fn)
        self.threadpool.start(worker)

    def progress_fn(self, n):
        self.progressBar.setValue(n)
        self.msgWorker.label.setText(str(n))
        # Восстанавливаем визуализацию потокового окна, если его закрыли. Поток работает.
        if not self.msgWorker.isVisible():
            self.msgWorker.show()

    def execute_this_fn(self, progress_callback):
        for n in range(0, 11):
            Qt.QThread.msleep(600)
            progress_callback.emit(n * 100 / 10)
        return "Готово."

    def print_output(self, s):
        print("\ndef print_output(self, s):", s)

    def thread_complete(self):
        print("\nTHREAD ЗАВЕРШЕН!, self->", self)

    # --END-- Worker QRunnable) -------------------#

    # ==============================================###
    # потоки или процессы должны быть завершены    ###
    def closeEvent(self, event):
        reply = Qt.QMessageBox.question \
            (self, 'Информация',
             "Вы уверены, что хотите закрыть приложение?",
             Qt.QMessageBox.Yes,
             Qt.QMessageBox.No)
        if reply == Qt.QMessageBox.Yes:
            if self.thread:
                self.thread.quit()
            del self.thread
            self.msg.close()

            if self.objThread:
                self.objThread.setTerminationEnabled(True)
                self.objThread.terminate()
                self.objThread.wait(1)
            self.msgSomeObject.close()

            # закрыть поток Worker(QRunnable)
            self.msgWorker.close()

            super(ExampleThread, self).closeEvent(event)
        else:
            event.ignore()
class GeneratorDialog(QDialog):
    """Generator Dialog"""
    def __init__(self, version, iconPath, addonDir, mediaDir):

        super().__init__()
        self.mediaDir = mediaDir
        self.iconPath = iconPath

        # Paths
        self.ankiCsvPath = join(addonDir, Constant.ANKI_DECK)

        # Create Generator GUI
        self.ui = UiGenerator()
        self.ui.setupUi(self, version, iconPath)
        self.ui.cancelBtn.setDisabled(True)

        # Create Importer Instance
        self.importer = ImporterDialog(version, iconPath, addonDir, mediaDir)
        self.importer.keyPressed.connect(self.importer.on_key)

        # Set Total Input Word count
        self.ui.inputTxt.textChanged.connect(self.input_text_changed)

        # Set Completed Output Card count
        self.ui.outputTxt.textChanged.connect(self.output_text_changed)

        # Set Failures Word count
        self.ui.failureTxt.textChanged.connect(self.failure_text_changed)

        # Handle clicks on Generate button
        self.ui.generateBtn.clicked.connect(self.btn_generate_clicked)

        # Handle clicks on Progress bar
        self.ui.importBtn.clicked.connect(self.btn_importer_clicked)

        self.get_supported_languages()
        # Handle user clicks on translation
        self.ui.source1.clicked.connect(self.get_supported_languages)
        self.ui.source2.clicked.connect(self.get_supported_languages)
        self.ui.source3.clicked.connect(self.get_supported_languages)
        self.ui.source4.clicked.connect(self.get_supported_languages)

    def close_event(self, event):
        logging.shutdown()

    def input_text_changed(self):

        words = self.ui.inputTxt.toPlainText().split("\n")
        # Filter words list, only get non-empty words
        self.words = list(filter(None, words))
        self.ui.totalLbl.setText("Total: {}".format(len(self.words)))

    def output_text_changed(self):

        cards = self.ui.outputTxt.toPlainText().split("\n")
        # Filter cards list, only get non-empty cards
        self.cards = list(filter(None, cards))
        self.cardCount = len(self.cards)
        self.ui.completedLbl.setText("Completed: {}".format(len(self.cards)))

    def failure_text_changed(self):

        failures = self.ui.failureTxt.toPlainText().split("\n")
        # Filter failures list, only get non-empty failures
        self.failures = list(filter(None, failures))
        self.failureCount = len(self.failures)
        self.ui.failureLbl.setText("Failure: {}".format(len(self.failures)))

    def btn_generate_clicked(self):

        # Validate if input text empty?
        inputText = self.ui.inputTxt.toPlainText()

        if not inputText:
            AnkiHelper.message_box("Info",
                                   "No input words available for generating.",
                                   "Please check your input words!",
                                   self.iconPath)
            return

        # Increase to 2% as a processing signal to user
        self.ui.generateProgressBar.setValue(2)
        self.ui.generateBtn.setDisabled(True)

        # Clean up output before generating cards
        self.ui.outputTxt.setPlainText("")
        self.ui.failureTxt.setPlainText("")

        # Get translation options
        source = self.selected_radio(self.ui.sourceBox)
        target = self.selected_radio(self.ui.translatedToBox)
        self.translation = Translation(source, target)

        # Get generating options
        self.allWordTypes = self.ui.allWordTypes.isChecked()
        self.isOnline = self.ui.isOnline.isChecked()

        # Initialize Generator based on translation
        self.generator = Worker.initialize_generator(self.translation)

        # Step 2: Create a QThread object
        self.bgThread = QThread(self)
        self.bgThread.setTerminationEnabled(True)

        # Step 3: Create a worker object
        self.worker = Worker(self.generator, self.words, self.translation,
                             self.mediaDir, self.isOnline, self.allWordTypes,
                             self.ankiCsvPath)

        # Step 4: Move worker to the thread
        self.worker.moveToThread(self.bgThread)

        # Step 5: Connect signals and slots
        self.bgThread.started.connect(self.worker.generate_cards_background)

        self.worker.finished.connect(self.bgThread.quit)
        self.bgThread.finished.connect(self.bgThread.deleteLater)

        self.worker.finished.connect(self.worker.deleteLater)
        self.worker.progress.connect(self.report_progress)

        self.worker.cardStr.connect(self.report_card)
        self.worker.failureStr.connect(self.report_failure)

        # Step 6: Start the thread
        self.bgThread.start()
        self.ui.cancelBtn.setEnabled(True)
        self.ui.generateBtn.setDisabled(True)

        # Handle cancel background task
        self.isCancelled = False

        receiversCount = self.ui.cancelBtn.receivers(self.ui.cancelBtn.clicked)
        if receiversCount > 0:
            logging.info(
                "Already connected before...{}".format(receiversCount))
            self.ui.cancelBtn.clicked.disconnect()

        self.ui.cancelBtn.clicked.connect(self.cancel_background_task)

        # Final resets
        self.bgThread.finished.connect(self.finished_generation_progress)

    def cancel_background_task(self):

        logging.info("Canceling background task...")
        self.bgThread.requestInterruption()
        self.bgThread.quit()

        self.ui.outputTxt.setPlainText("")
        self.isCancelled = True

        AnkiHelper.message_box("Info",
                               "Flashcards generation process stopped!",
                               "Restart by clicking Generate button.",
                               self.iconPath)

    def finished_generation_progress(self):

        self.ui.cancelBtn.setDisabled(True)
        self.ui.generateBtn.setEnabled(True)

        # Return if thread is cancelled
        if self.isCancelled:
            self.ui.outputTxt.setPlainText("")
            return

        if self.ui.outputTxt.toPlainText():
            btnSelected = AnkiHelper.message_box_buttons(
                "Info",
                "Finished generating flashcards.\nThanks for using AnkiFlash!",
                "Do you want to import generated flashcards now?\n\nProgress completed 100%\n- Input: {}\n- Output: {}\n- Failure: {}"
                .format(len(self.words), self.cardCount,
                        self.failureCount), QMessageBox.No | QMessageBox.Yes,
                QMessageBox.Yes, self.iconPath)
            if btnSelected == QMessageBox.Yes:
                self.btn_importer_clicked()
        else:
            AnkiHelper.message_box_buttons(
                "Info",
                "Finished generating flashcards.\nThanks for using AnkiFlash!",
                "No output flashcards available for importing.\n\nProgress completed 100%\n- Input: {}\n- Output: {}\n- Failure: {}"
                .format(len(self.words), self.cardCount, self.failureCount),
                QMessageBox.Close, QMessageBox.Close, self.iconPath)

    def report_progress(self, percent):

        # Return if thread is interrupted
        if self.bgThread.isInterruptionRequested():
            return

        self.ui.generateProgressBar.setValue(percent)

    def report_card(self, cardStr):

        # Return if thread is interrupted
        if self.bgThread.isInterruptionRequested():
            return

        currentText = self.ui.outputTxt.toPlainText()
        if currentText:
            currentText += "\n"
        self.ui.outputTxt.setPlainText("{}{}".format(currentText, cardStr))

    def report_failure(self, failureStr):

        # Return if thread is interrupted
        if self.bgThread.isInterruptionRequested():
            return

        currentText = self.ui.failureTxt.toPlainText()
        if currentText:
            currentText += "\n"
        self.ui.failureTxt.setPlainText("{}{}".format(currentText, failureStr))

    def btn_importer_clicked(self):
        if self.ui.outputTxt.toPlainText():
            self.importer.ui.importProgressBar.setValue(0)
            self.importer.show()
        else:
            AnkiHelper.message_box(
                "Info", "No output flashcards available for importing.",
                "Please check your input words!", self.iconPath)

    def get_supported_languages(self):
        source = self.selected_radio(self.ui.sourceBox)
        supportTranslations = {
            Constant.ENGLISH: [
                Constant.ENGLISH, Constant.VIETNAMESE, Constant.CHINESE_TD,
                Constant.CHINESE_SP, Constant.FRENCH, Constant.JAPANESE
            ],
            Constant.VIETNAMESE: [
                Constant.ENGLISH, Constant.FRENCH, Constant.JAPANESE,
                Constant.VIETNAMESE
            ],
            Constant.FRENCH: [Constant.ENGLISH, Constant.VIETNAMESE],
            Constant.JAPANESE: [Constant.ENGLISH, Constant.VIETNAMESE]
        }

        targetLanguages = supportTranslations.get(source)
        logging.info("targetLanguages {}".format(targetLanguages))

        radioBtns = [
            radio for radio in self.ui.translatedToBox.children()
            if isinstance(radio, QRadioButton)
        ]

        for radio in radioBtns:
            if radio.text() == Constant.ENGLISH:
                radio.click()

            if radio.text() in targetLanguages:
                radio.setEnabled(True)
                self.change_radio_color(radio, True)
            else:
                radio.setEnabled(False)
                self.change_radio_color(radio, False)

    def change_radio_color(self, radio: QRadioButton, isEnabled: bool):
        if isEnabled:
            radio.setStyleSheet(self.ui.source1.styleSheet())
        else:
            radio.setStyleSheet("color:gray")

    def selected_radio(self, groupBox: QGroupBox) -> str:
        # Get all radio buttons
        radioBtns = [
            radio for radio in groupBox.children()
            if isinstance(radio, QRadioButton)
        ]
        # Find choosen radio and return text
        for radio in radioBtns:
            if radio.isChecked():
                return radio.text()
Ejemplo n.º 5
0
class main_principal(QWidget):
    fecha_actual = datetime.datetime.now(
    )  # datetime es la libreria que nos ayuda con las fechas horas minutos y hsta segundos
    #en este caso nos referimos a que nos de la fecha actual
    contador_hilo = 1
    cursor = None
    lista_hilos = []

    def banner_anonymous(self):
        #banner un bannner es solo un mensaje de texto
        #el       \32 es para indicarle que queremos un espacio en blanco
        #puedes ver que hay muchos \32 en este paratado eso es debido a que
        #se necesitan espacios para imprimir bien el banner
        self.textarea_proceso.append(
            "$$$$$\32$\32\32\32\32$\32\32$$$$$\32$\32\32\32\32\32$$$$$$$\32\32\32\32\32\32######\32#####\32######\32##\32\32\32##"
        )
        self.textarea_proceso.append(
            "$\32\32\32\32\32\32\32\32$\32\32\32\32$\32\32\32\32\32$\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32\32#\32\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "$$$$$\32\32\32$\32\32\32\32\32$$$$$\32$\32\32\32\32\32$\32\32\32\32\32$||||||\32\32\32\32\32######\32#####\32######\32#\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "$\32\32\32\32\32\32$\32\32$\32\32\32$\32\32\32\32\32$\32\32\32\32\32$\32\32\32\32\32\32$\32\32\32\32\32\32\32\32\32\32\32#|#\32\32\32\32\32#\32\32\32\32#\32#\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "$$$$$\32$\32\32\32\32$\32\32$\32\32\32\32\32$$$$$\32$$$$$$$\32\32\32\32\32\32######\32#\32\32\32\32\32#\32\32\32\32#\32#\32\32\32\32\32#"
        )
        self.textarea_proceso.append(
            "Autor: Aldair Martinez Alias Hans Krammler Junior"
        )  # Aqui declaramos mi nombre jajaj XD

    def spam_uno_a_uno(self):
        self.banner_anonymous()
        print(self.fecha_actual)

    def spam_uno_a_varios(self):
        self.banner_anonymous()
        print(self.fecha_actual)
        print(Fore.GREEN + "HAZ ELEGIDO ENVIAR DESDE TU COREO A OTROS CORREO")

    def mensaje(self):
        print("SE TERMINO EL HILO")

    contador_hilo_aux = 0
    lista_hilos = []
    workers = []
    threads = []

    def incializa_hilos(self):
        if self.contador_hilo == 1:
            self.thread = QThread()
            self.thread.setObjectName("Hilo_1")
            self.worker = Worker(self.contador_hilo, self.textarea_proceso,
                                 self.label_proceso_verificacion, None)
            self.worker.moveToThread(self.thread)
            self.thread.setTerminationEnabled(True)
            self.thread.started.connect(self.worker.run)
            self.worker.finished.connect(self.terminado)
            self.thread.finished.connect(
                lambda: self.verificar_resultado_hilo(self.thread))
            self.worker.progressed.connect(
                lambda: self.reportProgress(self.worker))
            self.worker.siguiente.connect(
                lambda: self.siguiente_hilo(self.thread))
            self.thread.finished.connect(self.thread.quit)
            self.lista_hilos.append(self.thread)
            return self.lista_hilos
        else:
            self.lista_hilos = []
            self.threads.append(QThread())
            self.threads[self.contador_hilo_aux].setObjectName("Hilo_2")
            if self.contador_hilo == 2:
                print("Aqui tambien funciona")
                self.workers.append(
                    Worker(self.contador_hilo, self.textarea_proceso, None,
                           self.label_proceso_verificacion2))
            elif self.contador_hilo == 3:
                self.workers.append(
                    Worker(self.contador_hilo, self.textarea_proceso, None,
                           self.label_proceso_verificacion3))
            self.workers[self.contador_hilo_aux].moveToThread(
                self.threads[self.contador_hilo_aux])
            self.threads[self.contador_hilo_aux].started.connect(
                self.workers[self.contador_hilo_aux].run)
            self.workers[self.contador_hilo_aux].finished.connect(
                self.terminado)
            print("Pasando terminado")
            self.threads[self.contador_hilo_aux].finished.connect(
                lambda: self.verificar_resultado_hilo(self.threads[
                    self.contador_hilo_aux]))
            print("Pasando verificar resultado")
            self.workers[self.contador_hilo_aux].progressed.connect(
                lambda: self.reportProgress(self.workers[self.contador_hilo_aux
                                                         ]))
            print("Pasando reportprogress")
            self.workers[self.contador_hilo_aux].siguiente.connect(
                lambda: self.siguiente_hilo(self.threads[self.contador_hilo_aux
                                                         ]))
            self.threads[self.contador_hilo_aux].finished.connect(
                self.threads[self.contador_hilo_aux].quit)
            print("Pasando quit")
            self.lista_hilos.append(self.threads[self.contador_hilo_aux])
            return self.lista_hilos
        return None

    def siguiente_hilo(self, hilo):
        if self.contador_hilo == 1:
            if hilo.isRunning() == False:
                if hilo.isFinished() == True:
                    print("si funciono")
                    hilo.finished.connect(hilo.deleteLater)
                    hilo.finished.connect(hilo.terminate)
                    self.contador_hilo = self.contador_hilo + 1
                    self.incializa_hilos()[0].start()
        elif self.contador_hilo > 1:
            if self.get_verificado() == -1:
                return -1
            elif self.get_verificado() == -2:
                return -2
            else:
                return -3
            if hilo.isRunning() == False:
                if hilo.isFinished() == True:
                    self.contador_hilo = self.contador_hilo + 1
                    self.contador_hilo_aux = self.contador_hilo_aux + 1
                    self.incializa_hilos()[0].start()

        return 0

    cursor = None
    estado_hilo_x = 0
    lista_verificado = []

    def set_verificado(self, estado):
        self.estado_hilo_x = estado

    def get_verificado(self):
        self.lista_verificado.append(self.estado_hilo_x)
        print("get.lista.verificado" + str(self.lista_verificado[0]))
        return int(self.lista_verificado[0])

    def terminado(self):
        if self.contador_hilo == 1:
            print("TRABAJO TERMINADO")
            self.thread.finished.emit()
        elif self.contador_hilo > 1:
            self.threads[self.contador_hilo_aux].finished.emit()

    def verificar_resultado_hilo(self, thread):
        if self.contador_hilo == 1:
            if self.thread.isRunning() == False:
                print("EL HILO 1 HA TERMINADO SU TAREA")
            if self.thread.isFinished() == True:
                print("EL HILI 1 TERMINO CON EXITO")
                self.worker.progressed.emit()
        elif self.contador_hilo > 1:
            print(str(self.contador_hilo_aux))
            if thread.isRunning() == False:
                print("EL HILO" + str(self.contador_hilo_aux) +
                      "ESTA CORRIENDO")
            if thread.isFinished() == True:
                print("EL HILO" + str(self.contador_hilo_aux) + "HA TERMINADO")
                self.workers[self.contador_hilo_aux].progressed.emit()

    porcentaje = 10
    _i = 0
    lista_progreso = ["INICIANDO HILO DE EJECUCION......"]

    def reportProgress(self, worker):
        print(self.contador_hilo)
        if self.contador_hilo == 1:
            print("REPORTANDO HILO")
            #print("POSICION ACTUAL DEL CURSOR"+str(int(self.textarea_proceso.textCursor().position())))
            worker.siguiente.emit()
        else:
            if self.contador_hilo == 2:
                email = self.line_edit_user_email.text()
                password = self.line_edit_user_password.text()
                longitud_email = len(email)
                longitud_password = len(password)
                if longitud_email == 0 or longitud_password == 0:

                    self.set_verificado(-1)
            elif self.contador_hilo == 3:
                email = self.line_edit_user_email.text()
                email_to_list = list(email)
                contador = 1
                for _x in len(email):
                    if email_to_list[_x] == "@":
                        contador = contador + 1
                if contador > 1:
                    self.set_verificado(-2)
            elif self.contador_hilo == 4:
                contador = 1
                email_dominio = email.split(".")
                textarea_proceso.append("DIVIDIENDO TU EMAIL--->" +
                                        email_dominio)
                longitud_dominio_email = len(email_dominio)
                textarea_proceso.append(
                    "VERIFICANDO COINCIDENCIA DE DOMINIO DE EMAIL....")
                dominios = [
                    "gmail.com", "outlook.com", "outlook.es", "hotmail.com",
                    "hotmail.mx", "hotmail.es"
                ]
                longitud_dominio_gmail = len(dominios[0])
                longitud_dominio_outlook_com = len(dominios[1])
                longitud_dominio_outlook_es = len(dominios[2])
                longitud_dominio_hotmail_com = len(dominios[3])
                longitud_dominio_hotmail_mx = len(dominios[4])
                longitud_dominio_hotmail_es = len(dominios[5])
                for _i in range(longitud_dominio_email):
                    for _j in (range(longitud_dominio_gmail)
                               or range(longitud_dominio_outlook_com)
                               or range(longitud_dominio_outlook_es)
                               or range(longitud_dominio_hotmail_com)
                               or range(longitud_dominio_hotmail_mx)
                               or range(longitud_dominio_hotmail_es)):
                        if _j < longitud_dominio_gmail:
                            if dominios[0][_j] == email_dominio[1][_j]:
                                print(dominios[0][j])
                                contador = contador + 1
                        elif _j < longitud_dominio_outlook_com:
                            if dominios[1][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_outlook_es:
                            if dominios[2][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_hotmail_com:
                            if dominios[3][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_hotmail_mx:
                            if dominios[4][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                        elif _j < longitud_dominio_hotmail_es:
                            if dominios[5][_j] == email_dominio[1][_j]:
                                contador = contador + 1
                    if contador > longitud_dominio_gmail:
                        return -3
                    else:
                        contador = 1
            print("AQUI MEN")
            posicion_textarea = len(self.lista_progreso[self._i])
            self.cursor = self.textarea_proceso.textCursor()
            print("CURSOR ACTUAL" + str(self.cursor))
            print("POSICION CURSOR ACTUAL++" + str(self.cursor.position()))
            if self.cursor.atEnd() == True:
                print("FIN DEL CURSOR True")
                print("TEXTO SELECCIONADO ANTES" + self.cursor.selectedText())
                posicion_inicial = (self.cursor.position() -
                                    1) - (posicion_textarea - 1) + 1
                print("posicion inicial" + str(posicion_inicial))
                time.sleep(0.4)
                self.cursor.setPosition(posicion_inicial,
                                        QTextCursor.KeepAnchor)
                print("TEXTO SELECCIONADO AHORA" + self.cursor.selectedText())
                print("POSICION CURSOR ACTUAL--" + str(self.cursor.position()))
                self.progreso = self.cursor.selectedText() + str(
                    self.porcentaje)
                self.porcentaje = self.porcentaje + 10
                self.textarea_proceso.append(self.progreso)
                print("POSICION CURSOR ACTUAL++" + str(self.cursor.position()))
            self._i = self._i + 1
            worker.siguiente.emit()

    def verificar_opcion(self):
        pass

    def validar_oprciones(self):
        if self.checkbox_opcion_spam_uno_a_uno.isChecked(
        ) == True and self.checkbox_opcion_spam_uno_a_varios.isChecked():
            self.label_estado_proceso.setText(
                Fore.RED +
                "LO SIENTO NO PUEDES SELECCIONAR DOS OPCIONES A LA VEZ")
            return False
        else:
            return True

    def escannear_red(self):
        scan = nmap.PortScanner()
        informacion_sistema = os.uname()

    def presionado(self):
        resultado_validar_opciones = self.validar_oprciones()
        if resultado_validar_opciones == True:
            self.inciar_hilo_principal()
            self.resultado_verificacion_email = 0
            if self.resultado_verificacion_email == 0:
                print("PASANDO AL SIGUIENTE HILO DE EJECUCION")
            if self.resultado_verificacion_email == 1:
                if self.checkbox_opcion_spam_uno_a_uno.isChecked() == True:
                    print(
                        "LAS OCPIONES SELECCIONADAAS EN LOS CASILLA SON VALIDAS"
                    )
            else:
                if self.resultado_verificacion_email == -1 or self.resultado_verificacion_email == -2 or self.resultado_verificacion_email == -3:
                    if self.resultado_verificacion_email == -1:
                        self.label_estado_proceso.setText(
                            "NO HAS INGRESADO NADA EN EL PRIMER CAMPO")
                        self.textarea_proceso.append(
                            "ERROR NO HAS INGRESADO NADA EN EL PRIMER CAMPO")
                    elif self.resultado_verificacion_email == -2:
                        self.label_estado_proceso.setText(
                            "HAS MAS DE UN ARROBA EN TU CORREO")
                        self.textarea_proceso.append(
                            "ERROR HAY MAS DE UN ARROBA EN TU CORREO")
                    elif self.resultado_verificacion_email == -3:
                        self.label_estado_proceso.setText(
                            "TERMINACION DE CORREO NO VALIDA")

        else:
            self.textarea_proceso.append(
                "INTENTE DE NUEVO RELLENAR LOS CAMPOS ADECUADAMENTE")

    def __init__(self, parent=None):
        #Parte de intefaz grafica
        super().__init__(parent)

        self.color = QColor(0, 0, 0, 0.5)
        self.setGeometry(550, 100, 1500, 500)
        self.pallette = QPalette(self.color)
        self.pallette.setColor(QPalette.Text, Qt.cyan)

        self.titulo_ventana = "ENVIO DE CORREO PARA HACER SPAM"
        self.setWindowTitle(self.titulo_ventana)
        self.setStyleSheet(
            "border-color: cyan; border-style: dashed; border-width: 2px; color:white"
        )
        self.setPalette(self.pallette)
        self.checkbox_opcion_spam_uno_a_uno = QCheckBox(
            "REALIZAR SPAM UNO A UN CORREO")
        self.checkbox_opcion_spam_uno_a_uno.clicked.connect(
            self.spam_uno_a_uno)
        self.checkbox_opcion_spam_uno_a_varios = QCheckBox(
            "REALIZAR SPAM UNO A VARIOS COOREOS")
        self.checkbox_opcion_spam_uno_a_varios.clicked.connect(
            self.spam_uno_a_varios)

        self.label_user_email = QLabel("Ingresa tu direccion de correo: ")
        self.label_user_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_email.setStyleSheet("color: white")

        self.line_edit_user_email = QLineEdit(self)
        self.line_edit_user_email.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_user_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.line_edit_user_email.setStyleSheet("color : black")

        self.label_user_password = QLabel("Ingresa tu password de correo")
        self.label_user_password.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_password.setStyleSheet("color: white")

        self.line_edit_user_password = QLineEdit(self)
        self.line_edit_user_password.setPlaceholderText(
            "Ingresa tu password de tu correo:")
        self.line_edit_user_password.setFont(
            QFont("Times", 14, QFont.Bold, True))
        self.line_edit_user_password.setStyleSheet("color : black")

        self.label_victima_email = QLabel(
            "Ingresa direccion de correo destinatario: ")
        self.label_victima_email.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_victima_email.setStyleSheet("color: white")

        self.line_edit_victima_email = QLineEdit(self)
        self.line_edit_victima_email.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_victima_email.setFont(
            QFont("Times", 14, QFont.Bold, True))
        self.line_edit_victima_email.setStyleSheet("color : black")

        self.label_user_asunto = QLabel("Ingresa el asunto ")
        self.label_user_asunto.setFont(QFont("Times", 14, QFont.Bold, True))
        self.label_user_asunto.setStyleSheet("color: white")

        self.line_edit_user_asunto = QLineEdit(self)
        self.line_edit_user_asunto.setPlaceholderText(
            "Ingresa tu direccion de cooreo:")
        self.line_edit_user_asunto.setFont(QFont("Times", 14, QFont.Bold,
                                                 True))
        self.line_edit_user_asunto.setStyleSheet("color : black")

        self.pushbutton_enviar = QPushButton("ENVIAR SPAM")
        self.pushbutton_enviar.setFont(QFont("Times", 14, QFont.Bold, True))
        self.pushbutton_enviar.setPalette(self.pallette)

        self.label_estado_proceso = QLabel("")
        self.label_estado_proceso.setText("ESPERANDO DATOS....")

        self.label_proceso = QLabel("Estado verificacion email y password")
        self.label_proceso_verificacion = QLabel("")
        self.label_proceso2 = QLabel(
            "Estado verificacion arroba de email origen y destino")
        self.label_proceso_verificacion2 = QLabel("")
        self.label_proceso3 = QLabel(
            "Estado verificacion terminacion correo origen y destino")
        self.label_proceso_verificacion3 = QLabel("")
        self.combobox_dominios_from = QComboBox()
        self.combobox_dominios_from.addItem("Gmail.com")
        self.combobox_dominios_from.insertSeparator(1)
        self.combobox_dominios_from.addItem("Outlook.com")
        self.combobox_dominios_from.addItem("Outlook.es")
        self.combobox_dominios_from.insertSeparator(4)
        self.combobox_dominios_from.addItem("Hotmail.com")
        self.combobox_dominios_from.addItem("Hotmail.es")
        self.combobox_dominios_from.addItem("Hotmail.mx")
        self.combobox_dominios_from.setStyleSheet(
            "background-color:black; color: cyan")

        self.combobox_dominios_to = QComboBox()
        self.combobox_dominios_to.addItem("Gmail.com")
        self.combobox_dominios_to.insertSeparator(1)
        self.combobox_dominios_to.addItem("Outlook.com")
        self.combobox_dominios_to.addItem("Outlook.es")
        self.combobox_dominios_to.insertSeparator(4)
        self.combobox_dominios_to.addItem("Hotmail.com")
        self.combobox_dominios_to.addItem("Hotmail.es")
        self.combobox_dominios_to.addItem("Hotmail.mx")
        self.combobox_dominios_to.setStyleSheet(
            "background-color:black; color: cyan")

        self.combobox_dominios_from.currentTextChanged.connect(
            self.verificar_opcion)
        self.combobox_dominios_to.currentTextChanged.connect(
            self.verificar_opcion)
        self.pushbutton_enviar.clicked.connect(self.presionado)

        self.layout_main = QHBoxLayout(self)

        self.layout_principal = QVBoxLayout()
        self.layout_principal.addWidget(self.label_user_email)
        self.layout_principal.addWidget(self.line_edit_user_email)
        self.layout_principal.addWidget(self.label_user_password)
        self.layout_principal.addWidget(self.line_edit_user_password)
        self.layout_principal.addWidget(self.label_victima_email)
        self.layout_principal.addWidget(self.line_edit_victima_email)
        self.layout_principal.addWidget(self.label_user_asunto)
        self.layout_principal.addWidget(self.line_edit_user_asunto)
        self.layout_principal.addWidget(self.checkbox_opcion_spam_uno_a_uno)
        self.layout_principal.addWidget(self.checkbox_opcion_spam_uno_a_varios)
        self.layout_principal.addWidget(self.pushbutton_enviar)
        self.layout_principal.addWidget(self.label_estado_proceso)
        self.layout_principal.addWidget(self.combobox_dominios_from)
        self.layout_principal.addWidget(self.combobox_dominios_to)
        self.layout_principal.addWidget(self.label_proceso)
        self.layout_principal.addWidget(self.label_proceso_verificacion)
        self.layout_principal.addWidget(self.label_proceso2)
        self.layout_principal.addWidget(self.label_proceso_verificacion2)
        self.layout_principal.addWidget(self.label_proceso3)
        self.layout_principal.addWidget(self.label_proceso_verificacion3)

        self.layout_secundario = QVBoxLayout()
        self.textarea_proceso = QTextEdit()
        self.textarea_proceso.setPlaceholderText("ESPERANDO PARA PROCESAR")
        self.textarea_proceso.setFont(QFont("Times", 14, QFont.Bold, True))
        self.textarea_proceso.setGeometry(0, 0, 500, 400)
        self.textarea_proceso.setStyleSheet(
            "color: yellow; background-color:black; border-style:solid")
        self.textarea_proceso.setReadOnly(False)
        self.textarea_proceso.setOverwriteMode(QTextEdit.WidgetWidth)
        self.layout_secundario.addWidget(self.textarea_proceso)

        self.layout_main.addLayout(self.layout_principal, 4)
        self.layout_main.addLayout(self.layout_secundario, 4)

    def inciar_hilo_principal(self):
        self.incializa_hilos()[0].start()
        return 0
Ejemplo n.º 6
0
class SerialUI(QMainWindow):

    global ser
    global bpm
    global samplingrate
    global serialcmd
    ser = serial.Serial()
    global flag
    flag = True
    wrong = 0
    stopper = pyqtSignal()
    starter = pyqtSignal()

    def __init__(self):
        super(SerialUI, self).__init__()
        self.InitUI()

    def InitUI(self):
        # QMainWindow settings
        self.setWindowTitle('Heart Monitor')
        self.setStyleSheet("background-color: beige")
        self.setGeometry(10, 10, 1100, 750)
        self.move(500, 300)

        # Create push button
        self.b1 = QPushButton('Start', self)
        self.b1.move(350, 650)
        self.b1.setStyleSheet("background-color: white")
        self.b1.clicked.connect(self.start_call)

        self.b2 = QPushButton('BPM', self)
        self.b2.move(500, 650)
        self.b2.setStyleSheet("background-color: white")
        self.b2.clicked.connect(self.get_bpm)

        self.b3 = QPushButton('Plot', self)
        self.b3.move(650, 650)
        self.b3.setStyleSheet("background-color: white")

        self.lb5 = QLabel(self)
        self.lb5.resize(100, 50)
        self.lb5.move(10, 50)
        self.lb5.setText("COMPORT:")

        # Create textbox
        self.tb1 = QLineEdit(self)  # COMPORT
        self.tb1.resize(150, 70)
        self.tb1.setStyleSheet("background-color: white")
        self.tb1.move(100, 50)

        self.lb6 = QLabel(self)
        self.lb6.resize(100, 50)
        self.lb6.move(260, 50)
        self.lb6.setText("BAUDRATE:")

        self.tb2 = QLineEdit(self)  # BAUDRATE
        self.tb2.resize(150, 70)
        self.tb2.setStyleSheet("background-color: white")
        self.tb2.move(360, 50)

        self.lb7 = QLabel(self)
        self.lb7.resize(130, 50)
        self.lb7.move(520, 50)
        self.lb7.setText("SAMPLINGRATE:")

        # Create textbox
        self.tb4 = QLineEdit(self)  # Sampling Rate
        self.tb4.resize(150, 70)
        self.tb4.setStyleSheet("background-color: white")
        self.tb4.move(650, 50)

        self.lb8 = QLabel(self)
        self.lb8.resize(130, 50)
        self.lb8.move(810, 50)
        self.lb8.setText("SAMPLINGTIME:")

        # Create textbox
        self.tb5 = QLineEdit(self)  # Time
        self.tb5.resize(150, 70)
        self.tb5.setStyleSheet("background-color: white")
        self.tb5.move(940, 50)

        # Create label
        self.lb1 = QLabel(self)
        self.lb1.setFont(QFont('SansSerif', 15))
        self.lb1.setStyleSheet("color: black")
        self.lb1.resize(200, 50)
        self.lb1.move(300, 160)
        self.lb1.setText("Terminal:")

        self.tb3 = QTextEdit(self)
        self.tb3.setFont(QFont('SansSerif', 15))
        self.tb3.setStyleSheet("color: black")
        self.tb3.setStyleSheet("background-color: white")
        self.tb3.resize(500, 400)
        self.tb3.move(300, 230)

        self.thread = QThread()
        self.worker = runThread()
        self.stopper.connect(self.worker.stop)
        self.worker.plot.connect(self.plot)
        self.worker.moveToThread(self.thread)
        #self.worker.end.connect(self.thread.quit)
        #self.worker.end.connect(self.worker.deleteLater)
        #self.worker.end.connect(self.thread.deleteLater)
        self.worker.displayText.connect(self.display)
        self.thread.started.connect(self.worker.work)
        #self.thread.finished.connect(self.worker.stop)
        self.b3.clicked.connect(self.stop_call)
        self.starter.connect(self.worker.start)
        self.show()

    def stop_call(self):
        self.stopper.emit()

    def get_bpm(self):
        self.tb3.append("BPM: " + self.bpm)

    def display(self, heart):
        if (heart != ""):
            if heart[0] != "B":
                self.tb3.append(heart)
            else:
                self.bpm = heart[5:-2]

    def plot(self):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.plot(xs, ys)
        plt.xticks(rotation=45, ha='right')
        plt.subplots_adjust(bottom=0.30)
        plt.title('Heart Beat')
        plt.ylabel('ECG Output')
        plt.ylabel('Count')
        plt.show()

    @pyqtSlot()
    def start_call(self):
        xs.clear()
        ys.clear()
        # # Serial settings
        ser.close()
        try:
            self.thread.terminate()
        except:
            ser.close()
        try:
            ser.port = self.tb1.text()
            ser.baudrate = self.tb2.text()

            if ser.is_open is not True:  # Check the serial port again whether it is open or not.
                ser.open()

            try:
                serialcmd = self.tb5.text()
                userInput = int(serialcmd)
                for x in range(len(serialcmd)):
                    ser.write(serialcmd[x].encode())
                ser.write("\r".encode())

                self.samplingrate = self.tb4.text()
                serialcmd = self.samplingrate
                userInput = int(serialcmd)
                for x in range(len(serialcmd)):
                    ser.write(serialcmd[x].encode())
                ser.write("\r".encode())
                self.thread.setTerminationEnabled(True)
                self.thread.start()
            except ValueError:
                self.tb3.append("Invalid Sampling Rate")
        except:
            self.tb3.append("Invalid Serial Port")
Ejemplo n.º 7
0
class Gui(QWidget):
    def __init__(self):
        super().__init__()
        self.foldername = None
        self.server = None
        self.initUI()

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        self.addr_frame = QFrame()
        addr_layout = QGridLayout()
        self.addr_frame.setLayout(addr_layout)

        lbl_host = QLabel('Host:', self)
        lbl_port = QLabel('Port:', self)
        lbl_msg = QLabel('Msg:', self)
        lbl_spin = QLabel('Group number:', self)
        self.lbl_msg_wr = QLabel('', self)
        self.lbl_err = QLabel('', self)
        self.edit_host = QLineEdit()
        self.edit_port = QLineEdit('9090')
        self.btn_run = QPushButton('Run server', self)
        self.btn_stop = QPushButton('Stop server', self)
        self.btn_dir = QPushButton('Open folder', self)
        self.btn_ext = QPushButton('Quit', self)
        self.spin = QSpinBox()
        self.spin.setRange(0, 99)

        addr_layout.addWidget(lbl_host, 0, 0)
        addr_layout.addWidget(self.edit_host, 0, 1)
        addr_layout.addWidget(lbl_port, 0, 2)
        addr_layout.addWidget(self.edit_port, 0, 3)
        addr_layout.addWidget(self.lbl_err, 1, 0, 1, 4)

        grid.addWidget(self.addr_frame, 0, 0, 2, 4)
        grid.addWidget(lbl_spin, 2, 1, 1, 2)
        grid.addWidget(self.spin, 2, 3)
        grid.addWidget(lbl_msg, 3, 0)
        grid.addWidget(self.lbl_msg_wr, 3, 1, 1, 3)
        grid.addWidget(self.btn_run, 4, 0, 1, 4)
        grid.addWidget(self.btn_stop, 5, 0, 1, 4)
        grid.addWidget(self.btn_dir, 6, 3)
        grid.addWidget(self.btn_ext, 6, 0)

        self.btn_ext.clicked.connect(QCoreApplication.instance().quit)
        self.btn_run.clicked.connect(self.start)
        self.btn_dir.clicked.connect(self.get_filename)
        self.btn_stop.clicked.connect(self.stop)
        self.btn_stop.setDisabled(True)
        self.spin.valueChanged.connect(self.set_group)

        self.thread = QThread()
        self.thread.started.connect(lambda: self.disable_btn(True))
        self.thread.finished.connect(lambda: self.disable_btn(False))

        self.setWindowTitle('TCP Server')
        self.center()
        self.show()

    def get_filename(self):
        self.foldername = QFileDialog.getExistingDirectory(
            self, "Set folder", ".")

    @pyqtSlot(str)
    def show_msg(self, string):
        self.lbl_msg_wr.setText(string)

    def set_group(self, value):
        if self.server:
            self.server.group_number = str(value).rjust(2, '0')

    def disable_btn(self, value):
        self.btn_run.setDisabled(value)
        self.btn_stop.setEnabled(value)
        self.btn_dir.setDisabled(value)
        self.btn_ext.setDisabled(value)
        self.addr_frame.setDisabled(value)

    def start(self):
        file_patch = self.foldername + '/log.csv' if self.foldername else 'log.csv'
        self.server = Server(str(self.spin.value()).rjust(2, '0'), file_patch)
        self.server.show_string.connect(self.show_msg)
        port = self.edit_port.text()
        if port:
            self.server.create(int(port))
            self.server.loop = True
            self.server.moveToThread(self.thread)
            self.thread.started.connect(self.server.run)
            self.thread.setTerminationEnabled()
            self.thread.start()

        else:
            self.lbl_err.setText('Error!')

    def stop(self):
        if self.server:
            self.server.loop = False
            self.thread.terminate()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
class CameraDisplay(QWidget):
    frame_updated = pyqtSignal()
    # ~~~~~~~~~~~~~~~~~~~~~~~~ #
    def __init__(self, camera=None, log=None, fps=10.):
        super().__init__()
        # ---  --- #
        if log != None:
            self.log = log
        else:
            self.log = LogDisplay()
        #self.log.show()
        # --- default --- #
        self.fps       = fps
        self.normalise_hist = True
        self.cmap      = 'jet'
        # --- main attriute --- #
        self.camera    = camera
        self.contview  = ContinuousView(fps=self.fps)
        self.timer     = pg.QtCore.QTimer() #QTimer()# pg.QtCore.QTimer()
        self.qlabl_max = QLabel()
        self.isOn      = False
        self.frame     = None
        # --- color acuisition --- #
        self.initColorDic()
        # ---  --- #
        self.initUI()
        self.initCamera(camera)
        # ---  --- #
        self.camera.setExposure( self.exposure.value() )

    def initUI(self):
        # ---  --- #
        self.layout      = QVBoxLayout(self)
        self.initView()
        # --- button widget --- #
        self.button_startstop = QPushButton('Start/Stop')
        self.button_startstop.setStyleSheet("background-color: red")
        self.button_nextFrame = QPushButton('Next frame')
        # ---  --- #
        self.fps_input     = QSpinBox()
        self.fps_input.setRange(1, 48)
        self.fps_input.setValue(self.fps)
        self.exposure      = QDoubleSpinBox()
        self.exposure.setSingleStep(0.01)
        self.cam_framerate = QDoubleSpinBox()
        self.exposure.setSingleStep(0.01)
        self.pixelclock    = QDoubleSpinBox()
        self.which_camera  = QComboBox()
        self.which_camera.addItem('USB camera')
        self.which_camera.addItem('From Image Dir.')
        # --- set default --- #
        self.exposure.setRange(0.10, 99.0)
        self.exposure.setValue(12.5)
        self.cam_framerate.setRange(1.00, 15.0)
        self.cam_framerate.setValue( 10.0 )
        self.pixelclock.setRange(5, 30)
        self.pixelclock.setValue(20)
        # --- connections --- #
        self.button_startstop.clicked.connect(self.startStop_continuous_view)
        self.fps_input.valueChanged.connect(self.setFPS)
        self.button_nextFrame.clicked.connect( self.nextFrame )
        self.exposure.valueChanged.connect( self.update_exposure )
        self.cam_framerate.valueChanged.connect( self.update_camFPS )
        self.pixelclock.valueChanged.connect( self.update_pixelClock )
        self.which_camera.currentIndexChanged.connect( self.changeCameraStyle )
        # --- layout --- #
        label_1 = QLabel('fps :')
        label_1.setWordWrap(True)
        label_2 = QLabel('value max:') 
        label_2.setWordWrap(True)
        label_3 = QLabel('Which camera')
        label_3.setWordWrap(True)
        label_4 = QLabel('Exposure (ms):')
        label_4.setWordWrap(True)
        label_5 = QLabel('Camera fps:')
        label_5.setWordWrap(True)
        label_6 = QLabel('Pixel clock (MHz):')
        label_6.setWordWrap(True)
        grid = QGridLayout()
        grid.addWidget( self.button_startstop, 0,0)
        grid.addWidget( self.button_nextFrame, 0,1)
        grid.addWidget( label_1              , 0,2)
        grid.addWidget( self.fps_input       , 0,3)
        grid.addWidget( label_2              , 0,4)
        grid.addWidget( self.qlabl_max       , 0,5)
        grid.addWidget(QVLine()              , 0,6 , 2,1)
        grid.addWidget(label_3               , 0,7)
        grid.addWidget( self.which_camera    , 1,7 , 2,1)
        grid.addWidget(label_4               , 1,0)
        grid.addWidget( self.exposure        , 1,1)
        grid.addWidget(label_5               , 1,2)
        grid.addWidget( self.cam_framerate   , 1,3)
        grid.addWidget(label_6               , 1,4)
        grid.addWidget( self.pixelclock      , 1,5)
        self.layout.addLayout(grid)
        self.layout.addWidget(self.image_view)
        self.setLayout(self.layout)

    def initColorDic(self):
        self.colordic = {}
        # --- jet-like cmap --- #
        alpha     = 1.0
        positions = [0.2, 0.5, 0.75, 1.0]
        colors    = [[0,0,1.,alpha],[0,1.,1.,alpha],[1.,1.,0,alpha],[170/255,0,0,alpha]] #colors    = ['#0000ff', '#00ffff', '#ffff00', '#aa0000']
        self.colordic['jet'] = pg.ColorMap(positions, colors)
        # --- jet reversed cmap --- #
        positions_r = [1-p_ for p_ in positions]
        self.colordic['jet_r'] = pg.ColorMap(positions_r, colors)
        # --- plasma cmap --- #
        self.colordic['plasma'] = generatePgColormap('plasma')

    def initView(self):
        self.image_view     = pg.ImageView()
        # ---  --- #
        self.image_view.setColorMap(self.colordic[self.cmap])
        self.image_view.setLevels(0,255)
        self.image_view.getHistogramWidget().item.setHistogramRange(0,255)
        # ---  --- #
        self.image_view.setMinimumWidth(800)
        self.image_view.setMinimumHeight(600)

    def initCamera(self, camera):
        self.default_camera = camera
        self.simu_camera    = SimuCamera(directory_path=os.getcwd(), log=self.log)
        # ---  --- #
        self.camera = self.default_camera
        if not self.camera.isCameraInit:
            self.camera.__init__()

    def hideHistogram(self):
        self.image_view.ui.histogram.hide()

    def hidePlotButtons(self):
        self.image_view.ui.roiBtn.hide()
        self.image_view.ui.menuBtn.hide()

    def setFPS(self):
        self.fps = self.fps_input.value()
        self.contview.setFPS( self.fps )
        self.timer.setInterval(1e3/self.fps)

    def update_frame(self):
        self.frame = self.camera.get_frame()
        self.qlabl_max.setText( str(np.max(self.frame)) )
        self.image_view.setImage(self.frame.T, autoHistogramRange=False, autoLevels=False)
        self.frame_updated.emit()

    def update_exposure(self):
        self.camera.setExposure( self.exposure.value() )
        self.log.addText( 'New exposure: {}ms'.format( self.camera.getExposure() ) )
        # ---  --- #
        new_pixelclock = self.camera.getPixelClock()
        self.pixelclock.setValue( new_pixelclock )
        new_camFPS     = self.camera.getFrameRate()
        self.cam_framerate.setValue( new_camFPS )

    def update_camFPS(self):
        newfps = self.camera.setFrameRate( self.cam_framerate.value() )
        self.log.addText('New camera fps: {:.3f}'.format( self.camera.getFrameRate() ) )
        self.cam_framerate.setValue(newfps)
        # ---  --- #
        new_pixelclock = self.camera.getPixelClock()
        self.pixelclock.setValue( new_pixelclock )
        new_exposure   = self.camera.getExposure()
        self.exposure.setValue( new_exposure )

    def update_pixelClock(self):
        self.camera.setPixelClock( int(self.pixelclock.value()) )
        self.log.addText( 'New pixel clock: {}Mhz'.format( self.camera.getPixelClock() ))
        # ---  --- #
        new_camFPS     = self.camera.getFrameRate()
        self.cam_framerate.setValue( new_camFPS )
        new_exposure   = self.camera.getExposure()
        self.exposure.setValue( new_exposure )

    def nextFrame(self):
        wasOn = self.isOn
        if not self.isOn:
            self.camera.capture_video()
        # ---  --- #
        self.update_frame()
        # ---  --- #
        if not wasOn:
            self.camera.capture_video()

    def startStop_continuous_view(self):
        if  self.isOn:
            self.stop_continuous_view()
            self.button_startstop.setStyleSheet("background-color: red")
            self.button_nextFrame.setFlat(False)
            self.button_nextFrame.setEnabled(True)
        else:
            self.start_continuous_view()
            self.button_startstop.setStyleSheet("background-color: green")
            self.button_nextFrame.setFlat(True)
            self.button_nextFrame.setEnabled(False)

    def start_continuous_view(self):
        self.camera.capture_video()
        if   True:
            self.start_continuous_view_qtimer()
        elif False:
            self.start_continuous_view_qthread()
        # ---  --- #
        self.isOn = True

    def stop_continuous_view(self):
        self.camera.stop_video()
        if   True:
            self.stop_continuous_view_qtimer()
        elif False:
            self.stop_continuous_view_qthread()
        # ---  --- #
        self.isOn = False

    def start_continuous_view_qthread(self):
        # ---  --- #
        self.thread = QThread()
        self.thread.setTerminationEnabled(True)
        # --- connect --- #
        self.contview.moveToThread(self.thread)
        self.thread.started.connect(self.contview.startFeed)
        self.contview.newshot.connect(self.update_image)
        self.contview.finished.connect(self.thread.quit)
        # ---  --- #
        self.thread.start()

    def stop_continuous_view_qthread(self):
        self.contview.stopFeed()

    def start_continuous_view_qtimer(self):
        # ---  --- #
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(1e3/self.fps) #ms

    def stop_continuous_view_qtimer(self):
        self.timer.stop()

    def changeCameraStyle(self):
        self.camera.stop_video()
        # ---  --- #
        indx = self.which_camera.currentIndex()
        if   indx == 0:
            self.camera = self.default_camera
            # ---  --- #
            self.exposure.setEnabled(True)
            self.cam_framerate.setEnabled(True)
            self.pixelclock.setEnabled(True)
        elif indx == 1:
            self.camera.stop_video()
            dir_path    = QFileDialog().getExistingDirectory()
            self.log.addText('NEW DIR PATH: {}'.format(dir_path))
            self.simu_camera.setDirectoryPath( dir_path )
            self.simu_camera.initialize()
            self.camera = self.simu_camera
            # ---  --- #
            self.exposure.setEnabled(False)
            self.cam_framerate.setEnabled(False)
            self.pixelclock.setEnabled(False)
Ejemplo n.º 9
0
class SimulationView(QWidget, Ui_simulationView):
    SIGNAL_toggled_plot_indicator = "indicator"

    def __init__(self, model=None, controller=None):
        super(SimulationView, self).__init__()
        self.model = model
        self.allPlotsDict = {}
        self.setupUi(self)
        self.connect_buttons()
        self.connect_signals()
        self.connect_checkbox()
        self.create_plots()
        self.initialize_view()

    def initialize_view(self):
        self.cb_isInfected.setChecked(True)

    def connect_buttons(self):
        self.pb_simulate.clicked.connect(self.launch_simulation)
        log.info("Connecting simulationView GUI...")

    def connect_checkbox(self):
        self.cb_isInfected.stateChanged.connect(
            lambda: self.toggle_plot("isInfected", caller=self.cb_isInfected))
        self.cb_isInfectious.stateChanged.connect(lambda: self.toggle_plot(
            "isInfectious", caller=self.cb_isInfectious))
        self.cb_isAlive.stateChanged.connect(
            lambda: self.toggle_plot("isAlive", caller=self.cb_isAlive))
        self.cb_isRecovered.stateChanged.connect(lambda: self.toggle_plot(
            "isRecovered", caller=self.cb_isRecovered))
        self.cb_isHospitalized.stateChanged.connect(lambda: self.toggle_plot(
            "isHospitalized", caller=self.cb_isHospitalized))
        self.cb_hasSymptoms.stateChanged.connect(lambda: self.toggle_plot(
            "hasSymptoms", caller=self.cb_hasSymptoms))

    def connect_signals(self):
        log.info("Connecting simulationView Signals...")
        self.model.simulatorObject.s_data_changed.connect(self.update_graph)

    def create_plots(self):
        for indicator in Person().indicators:
            self.allPlotsDict[indicator] = {
                "plotItem": PlotItem(),
                "displayed": 0
            }
        for indicator in Person().indicators:
            self.allPlotsDict[indicator]["plotDataItem"] = {}
            for ageGroup in Person().ageGroupsList:
                dataPlotItem = self.allPlotsDict[indicator]["plotItem"].plot()
                self.allPlotsDict[indicator]["plotDataItem"][
                    ageGroup] = dataPlotItem
                # self.allPlotsDict[indicator]["plotDataItem"][ageGroup].setDownsampling()
            self.allPlotsDict[indicator]["plotItem"].setTitle(indicator)
        print(self.allPlotsDict)

    def toggle_plot(self, indicator, caller=None):
        if caller.checkState() == 2:
            self.allPlotsDict[indicator]["displayed"] = 1
            self.update_plots_position()
            dispatcher.send(signal=SIGNAL_PLOT_TOGGLED,
                            sender=self,
                            **{"indicator": indicator})

        elif caller.checkState() == 0:
            self.pyqtgraphWidget.removeItem(
                self.allPlotsDict["{}".format(indicator)]["plotItem"])
            self.allPlotsDict[indicator]["displayed"] = 0
            self.update_plots_position()

        else:
            pass

    def update_plots_position(self):
        self.pyqtgraphWidget.clear()
        sideLength = math.ceil(
            math.sqrt(
                sum(self.allPlotsDict[ind]["displayed"] == 1
                    for ind in self.allPlotsDict.keys())))
        tempPlotDict = {
            key: value
            for (key, value) in self.allPlotsDict.items()
            if value["displayed"] == 1
        }
        indicatorList = list(tempPlotDict.keys())
        listIndex = 0
        for i in range(sideLength):
            for j in range(sideLength):
                try:
                    self.pyqtgraphWidget.addItem(
                        tempPlotDict[indicatorList[listIndex]]["plotItem"], i,
                        j)
                    listIndex += 1
                except:
                    pass

    @pyqtSlot(dict)
    def update_graph(self, simPlotData):
        # all plot are updated, but could verify which one is active and only update those
        #print(simPlotData)
        for indicator in Person().indicators:
            for ageGroup in Person().ageGroupsList:
                try:
                    kwargs = simPlotData[indicator][ageGroup]
                    #print(ageGroup)
                    self.allPlotsDict[indicator]["plotDataItem"][
                        ageGroup].setData(**kwargs)
                except:
                    log.info("null")

    def unfold_plot_data(self, foldedData):
        unfoldedData = []
        xdata = foldedData[0]
        for ydata in foldedData[1]:
            unfoldedData.append([xdata, ydata])
        return unfoldedData

    def load_simulation_parameters(self):
        pass

    def update_plot(self):
        pass

    def initialize_simulation(self):
        pass

    def launch_simulation(self):
        self.pb_simulate.setEnabled(False)
        self.pb_simulate.clicked.disconnect()
        self.pb_simulate.clicked.connect(self.stop_simulation)
        self.pb_simulate.setText("Stop")
        self.pb_simulate.setEnabled(True)
        args = [
            self.model.populationSize, self.model.initialInfected,
            self.model.simulationTime
        ]
        log.info("Population Size:{}".format(self.model.populationSize))
        log.info("Population: {}".format(
            self.model.simulatorObject.population))
        log.info("Parameters: {}".format(
            self.model.simulatorObject.parameters))
        log.info("Initially Infected: {}".format(self.model.initialInfected))
        self.simulationWorker = Worker(
            self.model.simulatorObject.simulate_from_gui, *args)
        self.simulationThread = QThread()
        self.simulationWorker.moveToThread(self.simulationThread)
        self.simulationThread.started.connect(self.simulationWorker.run)
        self.simulationThread.start()

    def stop_simulation(self):
        self.pb_simulate.setEnabled(False)
        self.pb_simulate.setText("Resume")
        self.simulationThread.setTerminationEnabled(True)
        self.simulationThread.terminate()
        self.pb_simulate.clicked.disconnect()
        self.pb_simulate.clicked.connect(self.resume_simulation)
        self.pb_simulate.setEnabled(True)

    def resume_simulation(self):
        pass
Ejemplo n.º 10
0
class MenuChat(Menu):
    def __init__(self):
        Menu.__init__(self, "Chat")

        self.widget = QWidget()

        self.hosts = {}

        qtMainLayout = QGridLayout(self.widget)
        qtText = QTextBrowser()
        qtInput = QLineEdit()

        qtConfigLayout = QVBoxLayout()

        qtPeers = QGroupBox("Recipients")
        qtPeersLayout = QVBoxLayout(qtPeers)

        def onBroadcastChange(state):
            self.setBroadcast(state > 0)

        qtBroadcast = QCheckBox("Broadcast")
        qtBroadcast.stateChanged.connect(onBroadcastChange)

        qtNetworkBox = QGroupBox("Network")
        qtNetworkLayout = QVBoxLayout(qtNetworkBox)

        def onNetworkChange():
            if self.qtNetworkTcp.isChecked():
                self.qtPeers.setEnabled(True)

                self.qtBroadcast.setEnabled(False)
                self.qtBroadcast.setCheckState(0)
            elif self.qtNetworkUdp.isChecked():
                self.qtBroadcast.setEnabled(True)

        qtNetworkTcp = QRadioButton("TCP")
        qtNetworkUdp = QRadioButton("UDP")
        qtNetworkBox.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))

        qtNetworkLayout.addWidget(qtNetworkTcp)
        qtNetworkLayout.addWidget(qtNetworkUdp)

        qtNetworkUdp.toggle()

        qtConfigLayout.addWidget(qtBroadcast)
        qtConfigLayout.addWidget(qtPeers)
        qtConfigLayout.addWidget(qtNetworkBox)

        qtMainLayout.addWidget(qtText, 0, 0, 1, 1)
        qtMainLayout.addWidget(qtInput, 1, 0, 1, 1)
        qtMainLayout.addLayout(qtConfigLayout, 0, 1, 2, 1)

        qtText.setText("")

        qtSettingsLayout = QGridLayout()

        qtNameLabel = QLabel("Name")
        qtName = QLineEdit()
        qtNameLabel.setMaximumWidth(40)
        qtName.setMaximumWidth(100)

        qtAesLabel = QLabel("AES")
        qtAes = QLineEdit()
        qtAesLabel.setMaximumWidth(40)
        qtAes.setMaximumWidth(100)

        qtSettingsLayout.addWidget(qtNameLabel, 0, 0, 1, 1)
        qtSettingsLayout.addWidget(qtName, 0, 1, 1, 1)
        #qtSettingsLayout.addWidget(qtAesLabel,1,0,1,1)
        #qtSettingsLayout.addWidget(qtAes,1,1,1,1)

        qtConfigLayout.addLayout(qtSettingsLayout)

        self.qtInput = qtInput
        self.qtText = qtText
        self.qtPeers = qtPeers
        self.qtNetworkBox = qtNetworkBox
        self.qtNetworkTcp = qtNetworkTcp
        self.qtNetworkUdp = qtNetworkUdp
        self.qtPeersLayout = qtPeersLayout
        self.qtBroadcast = qtBroadcast
        self.qtName = qtName

        def onReturn():
            msg = self.qtInput.text().strip()
            if (msg):
                self.onInput(msg)
            self.qtInput.setText("")

        qtInput.returnPressed.connect(onReturn)
        qtNetworkTcp.toggled.connect(onNetworkChange)
        qtNetworkUdp.toggled.connect(onNetworkChange)

        def aes_update():
            self.aes_key = self.qtAes.text()
            self.chatUdp.loop.call_soon_threadsafe(self.chatUdp.update_aes,
                                                   self.aes_key)

        qtName.editingFinished.connect(
            lambda: self.setName(self.qtName.text().strip()))
        qtAes.editingFinished.connect(aes_update)

        qtBroadcast.setCheckState(2)

        self.local_peer = ChatPeer(local=True)
        self.peers = {}
        self.peers_checkboxes = {}
        self.peers[self.local_peer.uuid] = self.local_peer
        self.aes_key = ""

        self.setupTcp()
        self.setupUdp()

        qtName.setText(socket.gethostname())
        self.local_peer.name = socket.gethostname()

    def setupTcp(self):
        self.chatTcp = ChatTcp(('0.0.0.0', 5012),
                               peers=self.peers,
                               local_peer=self.local_peer)
        self.chatTcp.sig_peer_data.connect(
            lambda peer, data: self.peer_data(peer, data))

        self.chatTcp_thread = QThread()
        self.chatTcp_thread.setTerminationEnabled(False)

        self.chatTcp_thread.started.connect(self.chatTcp.started)
        self.chatTcp_thread.finished.connect(self.chatTcp_thread.deleteLater)

        self.chatTcp.moveToThread(self.chatTcp_thread)

        self.chatTcp_thread.start()

    def tcpSend(self, peer, msg):
        logging.info("tcpSend ")
        self.chatTcp.loop.call_soon_threadsafe(self.chatTcp.message, msg, peer)

    def setupUdp(self):
        self.chatUdp = ChatUdp(('0.0.0.0', 5011),
                               peers=self.peers,
                               local_peer=self.local_peer)
        #self.chatUdp.sig_received.connect(lambda peer, msg: self.encryptedMessage(peer, msg))
        self.chatUdp.sig_peer_new.connect(lambda peer: self.peer_new(peer))
        self.chatUdp.sig_peer_name.connect(
            lambda peer, name: self.peer_name(peer, name))
        self.chatUdp.sig_peer_data.connect(
            lambda peer, data: self.peer_data(peer, data))

        self.chatUdp_thread = QThread()
        self.chatUdp_thread.setTerminationEnabled(False)

        self.chatUdp_thread.started.connect(self.chatUdp.started)
        self.chatUdp_thread.finished.connect(self.chatUdp_thread.deleteLater)

        self.chatUdp.moveToThread(self.chatUdp_thread)

        self.chatUdp_thread.start()

    def udpSend(self, msg, peer=None):
        logging.info("udpSend() ")
        self.chatUdp.loop.call_soon_threadsafe(self.chatUdp.message, msg, peer)

    def setBroadcast(self, state):
        self.qtPeers.setEnabled(not state)
        if state:
            self.qtNetworkUdp.toggle()

    def addMessage(self, peer, msg):
        self.qtText.moveCursor(QTextCursor.End)
        self.qtText.setTextColor(
            QColor(0, 0, 255) if peer ==
            self.local_peer else QColor(255, 0, 0))
        self.qtText.insertPlainText("[{}] ".format(peer.name))
        self.qtText.setTextColor(QColor(0, 0, 0))
        self.qtText.insertPlainText(msg)
        self.qtText.insertPlainText("\n")
        self.qtText.moveCursor(QTextCursor.End)

    def encrytedMessage(self, peer, msg):
        self.addMessage(peer, msg)

    def onInput(self, msg):

        self.addMessage(self.local_peer, msg)

        if self.qtNetworkTcp.isChecked():
            for uuid, peer in self.peers.items():
                if uuid in self.peers_checkboxes and self.peers_checkboxes[
                        uuid].checkState() == 2:
                    self.tcpSend(peer, msg)
        elif self.qtNetworkUdp.isChecked():
            if self.qtBroadcast.checkState() == 2:
                self.udpSend(msg)
            else:
                for uuid, peer in self.peers.items():
                    if uuid in self.peers_checkboxes and self.peers_checkboxes[
                            uuid].checkState() == 2:
                        self.udpSend(msg, peer)

    def setName(self, name):
        logging.info("New name: {}".format(name))
        self.local_peer.name = name
        self.chatUdp.loop.call_soon_threadsafe(self.chatUdp.announce)

    def addHost(self, host, alias=None, ip=None):
        if not alias:
            alias = host

        self.hosts[host] = {
            'host': host,
            'alias': alias,
            'checkbox': checkbox,
            'ip': ip,
        }

    def peer_new(self, peer):
        checkbox = QCheckBox(peer.name)
        self.qtPeersLayout.addWidget(checkbox)
        self.peers[peer.uuid] = peer
        self.peers_checkboxes[peer.uuid] = checkbox

    def peer_name_changed(self, peer):
        if peer.uuid in self.peers_checkboxes:
            self.peers_checkboxes[peer.uuid].setText(peer.name)

    def peer_data(self, peer, data):
        if not peer.uuid in self.peers:
            self.peer_new(peer)

        cmd, *opts = data.decode().split(' ', 1)
        cmd = cmd.upper()
        opts = opts[0] if opts else None

        def CMD_MSG(opts):
            self.addMessage(peer, opts)

        def CMD_ANNOUNCE(opts):
            if opts:
                old_name = peer.name
                peer.name = opts
                if old_name != peer.name:
                    self.peer_name_changed(peer)

        commands = {
            'MSG': CMD_MSG,
            'ANNOUNCE': CMD_ANNOUNCE,
        }

        if cmd in commands:
            commands[cmd](opts)