Ejemplo n.º 1
0
class Clock(QLabel):
    def __init__(self):
        super().__init__()
        self.time_left = QTime(0, 0)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)

        self.is_paused = True
        self.is_set = False

    def set_time(self, minutes, seconds=0):
        self.stop()
        self.time_left = QTime(0, minutes, seconds)
        self.setText(self.time_left.toString('mm:ss'))
        self.is_set = True
        self.setStyleSheet('')

    def start(self):
        if self.is_paused and self.is_set:
            self.timer.start(1000)
            self.is_paused = False

    def stop(self):
        if not self.is_paused:
            self.timer.stop()
            self.is_paused = True

    def update_time(self):
        self.time_left = self.time_left.addSecs(-1)
        if self.time_left.minute() == 0 and self.time_left.second() == 0:
            self.stop()
            self.is_set = False
            self.setStyleSheet('QLabel { color: red}')
        self.setText(self.time_left.toString('mm:ss'))
Ejemplo n.º 2
0
 def timerEvent(self):
     global time
     timer = QTimer()
     time = QTime(0, 0, 0)
     prev_time = QTime(0, 0, 0)
     prev_time = time
     time = time.addSecs(1)
     print(time.toString("hh:mm:ss"))
     print("Entered")
     timer.start(100)
     timer.setInterval(2000)
     timer.timeout.connect(self.timerEvent)
Ejemplo n.º 3
0
 def utc(self, rise_set, what):
     ''' Convert sun rise/set from UTC to local time
         'rise_set' is 'Sunrise' or 'Sunset when it is for weatherdata
         or the index of hour in day forecast when dayforecast'''
     listtotime = ''
     # Create a list ['h', 'm', 's'] and pass it to QTime
     if what == 'weatherdata':
         listtotime = self.weatherdata[rise_set].split('T')[1].split(':')
     elif what == 'dayforecast':
         listtotime = self.tree_day[4][rise_set].get('from').split(
             'T')[1].split(':')
     suntime = QTime(int(listtotime[0]), int(listtotime[1]), int(
         listtotime[2]))
     # add the diff UTC-local in seconds
     utc_time = suntime.addSecs(time.localtime().tm_gmtoff)
     utc_time_str = utc_time.toString()
     return utc_time_str
Ejemplo n.º 4
0
class Timer(QLCDNumber):
    textChanged = pyqtSignal(str)
    started = pyqtSignal()
    stopped = pyqtSignal()
    reset_ = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.reset()

    def start(self):
        self.timer.start(1000)
        self.started.emit()

    def stop(self):
        self.timer.stop()
        self.stopped.emit()

    def reset(self):
        self.time = QTime(0, 0)
        self.display(self.time.toString())
        self.reset_.emit()

    def isRunning(self):
        return self.timer.isActive()

    def text(self):
        if self.time.hour() == 0:
            return self.time.toString('mm:ss')
        else:
            return self.time.toString('h:mm:ss')

    def seconds(self):
        return self.time.hour() * 3600 + self.time.minute() * 60 + self.time.second()

    def tick(self):
        self.time = self.time.addSecs(1)
        text = self.text()
        if len(text) != self.digitCount():
            self.setDigitCount(len(text))
        self.display(text)
        self.textChanged.emit(text)
Ejemplo n.º 5
0
 def utc(self, rise_set, what):
     ''' Convert sun rise/set from UTC to local time
         'rise_set' is 'Sunrise' or 'Sunset' when it is for weatherdata
         or the index of hour in day forecast when dayforecast'''
     listtotime = ''
     # Create a list ['h', 'm', 's'] and pass it to QTime
     if what == 'weatherdata':
         listtotime = self.weatherdata[rise_set].split('T')[1].split(':')
     elif what == 'dayforecast':
         if not self.json_data_bool:
             listtotime = self.tree_day[4][rise_set].get('from').split(
                 'T')[1].split(':')
         else:
             listtotime = self.tree_day['list'][rise_set]['dt_txt'][
                 10:].split(':')
     suntime = QTime(int(listtotime[0]), int(listtotime[1]),
                     int(listtotime[2]))
     # add the diff UTC-local in seconds
     utc_time = suntime.addSecs(time.localtime().tm_gmtoff)
     utc_time_str = utc_time.toString()
     return utc_time_str
Ejemplo n.º 6
0
    class Interval_timer:
        def __init__(self, main_time, label, tray, outer_class, rpc, subject):
            self.outer_class = outer_class
            self.tray = tray
            self.label = label
            self.main_time = main_time
            self.time = QTime(0, main_time, 0)
            self.RPC = rpc
            self.subject = subject

        def timerEvent(self):
            self.time = self.time.addSecs(-1)
            self.label.setText(self.time.toString("mm:ss"))
            if self.time.secsTo(QTime(0, 0, 0)) == 0:

                print("Break timer stopped")
                self.tray.showMessage("Tomatime", "Break time's up",
                                      self.tray.icon(), 4000)

                self.clearTimer()
                self.outer_class.timer.timeout.disconnect(self.timerEvent)
                self.outer_class.timer.timeout.connect(
                    self.outer_class.timerEvent)
                print("Returning to focus timer")
                self.outer_class.round += 1
                self.outer_class.updateDiscord("Studying")

            return print(self.time.toString("mm:ss"), "   Break timer")

        def startTimer(self):
            print("Starting secondary timer")
            self.outer_class.timer.timeout.connect(self.timerEvent)
            self.outer_class.updateDiscord("Taking a break")

        def clearTimer(self):
            print("Clearing break timer")
            self.time = QTime(0, self.main_time, 0)
            self.label.setText(self.time.toString("mm:ss"))
Ejemplo n.º 7
0
class PomoTimer:
    def __init__(self, times, label, tray, rpc, subject):
        self.subject = subject
        self.tray = tray
        self.label = label
        self.main_time = times[0]
        self.time = QTime(0, self.main_time, 0)
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.timerEvent)
        self.rep = 0
        self.RPC = rpc
        self.short_break = self.Interval_timer(times[1], self.label, self.tray,
                                               self, self.RPC, self.subject)
        self.long_break = self.Interval_timer(times[2], self.label, self.tray,
                                              self, self.RPC, self.subject)
        self.round = 1

    class Interval_timer:
        def __init__(self, main_time, label, tray, outer_class, rpc, subject):
            self.outer_class = outer_class
            self.tray = tray
            self.label = label
            self.main_time = main_time
            self.time = QTime(0, main_time, 0)
            self.RPC = rpc
            self.subject = subject

        def timerEvent(self):
            self.time = self.time.addSecs(-1)
            self.label.setText(self.time.toString("mm:ss"))
            if self.time.secsTo(QTime(0, 0, 0)) == 0:

                print("Break timer stopped")
                self.tray.showMessage("Tomatime", "Break time's up",
                                      self.tray.icon(), 4000)

                self.clearTimer()
                self.outer_class.timer.timeout.disconnect(self.timerEvent)
                self.outer_class.timer.timeout.connect(
                    self.outer_class.timerEvent)
                print("Returning to focus timer")
                self.outer_class.round += 1
                self.outer_class.updateDiscord("Studying")

            return print(self.time.toString("mm:ss"), "   Break timer")

        def startTimer(self):
            print("Starting secondary timer")
            self.outer_class.timer.timeout.connect(self.timerEvent)
            self.outer_class.updateDiscord("Taking a break")

        def clearTimer(self):
            print("Clearing break timer")
            self.time = QTime(0, self.main_time, 0)
            self.label.setText(self.time.toString("mm:ss"))

    def timerEvent(self):
        self.time = self.time.addSecs(-1)
        self.label.setText(self.time.toString("mm:ss"))
        if self.time.secsTo(QTime(0, 0, 0)) == 0:
            self.rep += 1

            self.timer.timeout.disconnect(self.timerEvent)
            self.clearTimer()

            print("Focus time's up")
            self.tray.showMessage("Tomatime", "Focus time's up",
                                  self.tray.icon(), 4000)
            if self.rep == 3:
                self.rep = 0

                self.long_break.startTimer()
                return print("Starting long break timer")

            else:

                self.short_break.startTimer()
                return print("Starting short break timer")

        return print(self.time.toString("mm:ss"), ("   Focus Timer Ticking"))

    def startTimer(self):
        self.timer.start()
        print(self.timer.interval())
        self.updateDiscord("Studying")

    def clearTimer(self):
        self.time = QTime(0, self.main_time, 0)

    def pauseTimer(self):
        self.timer.stop()
        try:
            self.RPC.update(state=f"Studying - Round {self.round}",
                            details="Paused",
                            large_image="fsidfsd")
        except:
            print("No Discord app running")

    def resetTimer(self):
        self.pauseTimer()
        self.short_break.clearTimer()
        self.long_break.clearTimer()
        self.clearTimer()
        self.label.setText(str(self.main_time) + ":00")
        try:
            self.timer.timeout.disconnect(self.short_break.timerEvent)
        except:
            pass

        try:
            self.timer.timeout.disconnect(self.long_break.timerEvent)
        except:
            pass
        try:
            self.timer.timeout.disconnect(self.timerEvent)
        except:
            pass
        self.timer.timeout.connect(self.timerEvent)

    def epochTime(self, mins, second):
        orig = datetime.datetime.fromtimestamp(time.time())
        new = orig + datetime.timedelta(minutes=mins, seconds=second)
        return time.mktime(new.timetuple())

    def updateDiscord(self, info):
        try:
            self.RPC.update(
                state=f"Studying {self.subject} - Round {self.round}",
                details=info,
                large_image="fsidfsd",
                end=self.epochTime(self.time.minute(), self.time.second()))
        except:
            print("No Discord app running")
Ejemplo n.º 8
0
class Trainer(QWidget):
    num = 0
    max_num = 0
    correct = 0
    dfn = ''
    res = ''
    ans = ''
    wl1 = []
    wl2 = []
    ms = '00:00:00'
    filename = ''
    revl = ''

    #processing
    def processing(self):
        #setup variables
        self.num = 0
        self.max_num = 0
        self.correct = 0
        self.ms = '00:00:00'
        self.wl1 = []
        self.filename = ''
        self.revl = ''

        with open(f_path + 'test.csv', 'r', encoding='utf-8') as f2:
            reader2 = csv.reader(f2)
            for row in reader2:
                word = ''
                word = row[0]

                hint = ''
                hint = row[1]
                self.dfn = hint

                self.wl1.append([word, hint])
                self.max_num += 1

    #review
    def reviewing(self):
        #setup variables
        self.num = 0
        self.max_num = 0
        self.correct = 0
        self.ms = '00:00:00'
        self.wl2 = []
        self.filename = ''
        self.revl = ''

        with open(f_path + 'review_test.csv', 'r', encoding='utf-8') as f3:
            reader3 = csv.reader(f3)
            for row in reader3:
                word = ''
                word = row[0]

                hint = ''
                hint = row[1]
                self.dfn = hint

                self.wl2.append([word, hint])
                self.max_num += 1

    #next question
    def nextQ1(self, i):
        if i < self.max_num:
            self.dfn = self.wl1[i][1]
            self.ans = self.wl1[i][0]
            self.label1.setText(str(self.dfn))
            self.label2.setText('')
            self.label_d.setText(str(self.num + 1) + '/' + str(self.max_num))
        else:
            #setup result
            self.max_n.setText(str(self.max_num))
            self.corr.setText(str(self.correct))
            self.percentage()
            self.min_sec.setText(str(self.ms))

            #print result
            self.rt = self.per.text() + '%'
            self.tm = self.min_sec.text()
            b.close()
            self.msgbox = QMessageBox.about(
                self, 'Results',
                'Accuracy: ' + self.rt + '\n' + 'Time: ' + self.tm)
            self.time = QTime(0, 0, 0)
            #reboot
            b.close()
            subprocess.Popen([sys.executable, filename])

    #next question
    def nextQ2(self, i):
        if i < self.max_num:
            self.dfn = self.wl2[i][1]
            self.ans = self.wl2[i][0]
            self.label1.setText(str(self.dfn))
            self.label2.setText('')
            self.label_d.setText(str(self.num + 1) + '/' + str(self.max_num))
        else:
            #setup result
            self.max_n.setText(str(self.max_num))
            self.corr.setText(str(self.correct))
            self.percentage()
            self.min_sec.setText(str(self.ms))

            #print result
            self.rt = self.per.text() + '%'
            self.tm = self.min_sec.text()
            b.close()
            self.msgbox = QMessageBox.about(
                self, 'Results',
                'Accuracy: ' + self.rt + '\n' + 'Time: ' + self.tm)
            self.time = QTime(0, 0, 0)
            #reboot
            b.close()
            subprocess.Popen([sys.executable, filename])

        #calculate
    def percentage(self):
        c = self.correct
        t = self.max_num
        if (int(c) > 0 and int(t) > 0):
            p = float(c) / float(t) * 100
        else:
            p = 0.0
        self.per.setText(str(round(p, 2)))

    #initiate
    def __init__(self):
        super().__init__()

        #setup icon
        self.setWindowIcon(QIcon(scriptDir + os.path.sep + 'icon.png'))

        self.initUI()

        #center/size & show
        width = QDesktopWidget().width() * 0.4
        height = QDesktopWidget().height() * 0.4
        self.setMinimumSize(width, height)
        self.center()
        self.setWindowTitle('Vocab Trainer' + self.filename)

    #initiate function
    def initUI(self):
        #textbox & sizing font
        self.textbox1 = QLineEdit()
        self.font0 = self.textbox1.font()
        self.font0.setPointSize(18)
        self.textbox1.setFont(self.font0)

        #text
        self.label1 = QLabel(self.dfn)
        self.label1.setFont(self.font0)
        self.label1.setWordWrap(True)
        self.label1.setStyleSheet('background-color: #F5F5F5')

        self.label2 = QLabel('')
        self.label2.setFont(self.font0)
        self.label2.setStyleSheet('color: #FF0000')

        #variable
        self.max_n = QLabel()
        self.corr = QLabel()
        self.per = QLabel()
        self.min_sec = QLabel()

        #button
        self.btn = QPushButton('Enter')
        self.btn.setFont(self.font0)

        self.textbox1.returnPressed.connect(self.btn.click)

        #timer & display
        self.label_t = QLabel(self.ms)
        self.label_t.setFont(Main().font1)
        self.label_d = QLabel()
        self.label_d.setFont(Main().font1)
        self.label_d.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.timer = QTimer()

        self.time = QTime(0, 0, 0)
        self.timer.timeout.connect(self.timerEvent)
        self.timer.start(1000)

        #timer & display
        hbox = QHBoxLayout()
        hbox.addWidget(self.label_t, 0)
        hbox.addWidget(self.label_d, 0)

        #setup grid
        grid1 = QGridLayout()
        grid1.setSpacing(50)
        grid1.addLayout(hbox, 1, 0, 1, 0)
        grid1.addWidget(self.label1)
        grid1.addWidget(self.label2)
        grid1.addWidget(self.textbox1)
        grid1.addWidget(self.btn)
        self.setLayout(grid1)

    #setup timer
    def timerEvent(self):
        if self.isVisible(): self.time = self.time.addSecs(1)
        self.ms = self.time.toString('hh:mm:ss')
        self.label_t.setText(self.ms)

    #center gui
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    #leave confirm
    def closeEvent(self, event):
        if self.num < self.max_num:
            reply = QMessageBox.question(self, 'Vocab Trainer' + self.filename,
                                         "Are you sure to quit?",
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)

            if reply == QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

    def keyPressEvent(self, event):
        #Close application from escape key.
        if event.key() == Qt.Key_Escape:
            #reboot
            b.close()
            subprocess.Popen([sys.executable, filename])

    #pressed enter
    def on_click1(self):
        self.res = self.textbox1.text()

        if self.res != self.ans:
            self.textbox1.clear()
            self.label2.setText(self.ans)
        else:
            if self.label2.text() == '':
                self.correct += 1
            else:
                self.correct += 0
                with open(wl_path + 'review.csv', 'w', encoding='utf-8') as f3:
                    self.revl += (self.ans + ',' + self.dfn + '\n')
                    f3.write(self.revl)
            self.textbox1.clear()
            self.label2.setText('')
            self.num += 1
            self.nextQ1(self.num)

    #pressed enter
    def on_click2(self):
        self.res = self.textbox1.text()

        if self.res != self.ans:
            self.textbox1.clear()
            self.label2.setText(self.ans)
        else:
            if self.label2.text() == '':
                self.correct += 1
            else:
                self.correct += 0
                with open(wl_path + 'review.csv', 'w', encoding='utf-8') as f3:
                    self.revl += (self.ans + ',' + self.dfn + '\n')
                    f3.write(self.revl)
            self.textbox1.clear()
            self.label2.setText('')
            self.num += 1
            self.nextQ2(self.num)
Ejemplo n.º 9
0
class MainWidget(QWidget):
    show_msg = pyqtSignal()

    def __init__(self, formation):
        super().__init__()

        self.formation = formation

        layout = QGridLayout()

        self.show_msg.connect(self.show_message)
        self.final_string = None

        self.table = QTableWidget()
        self.table.setFixedWidth(COLUMNS_WIDTH * 4 + 2)
        self.table.horizontalHeader().hide()
        self.table.verticalHeader().hide()

        self.table.setStyleSheet(
            "QTableWidget { background-color: #808080; color: white; }")

        self.table.setColumnCount(4)
        if formation:
            self.table.setRowCount(6)
        else:
            self.table.setRowCount(5)
        for i in range(self.table.colorCount()):
            self.table.setColumnWidth(i, COLUMNS_WIDTH)

        self.timer = QTimer()
        self.time = QTime(0, 0)
        self.timer.timeout.connect(self.timer_event)
        self.timer.start(1000)

        timer_item = QTableWidgetItem("00:00")
        timer_item.setData(Qt.FontRole, QFont("", 20))
        timer_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        timer_item.setFlags(Qt.NoItemFlags)
        self.table.setSpan(0, 0, 1, 4)
        self.table.setItem(0, 0, timer_item)

        fees_item = QTableWidgetItem("Штрафы")
        fees_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        fees_item.setFlags(Qt.NoItemFlags)
        self.table.setSpan(1, 0, 1, 4)
        self.table.setItem(1, 0, fees_item)

        coll_it = QTableWidgetItem("Столкновения")
        coll_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(2, 0, coll_it)
        coll_it = QTableWidgetItem("0")
        coll_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(2, 1, coll_it)

        if formation:
            out_it = QTableWidgetItem("Вылеты")
            out_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(2, 2, out_it)
            out_it = QTableWidgetItem("0")
            out_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(2, 3, out_it)
        else:
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(2, 2, unu_it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(2, 3, unu_it)
            self.table.item(2, 2).setBackground(COLOR_UNUSED)
            self.table.item(2, 3).setBackground(COLOR_UNUSED)

        self.table.setSpan(3, 0, 1, 4)
        zones_it = QTableWidgetItem("Зоны")
        zones_it.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        zones_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(3, 0, zones_it)

        if formation:
            self.table.setSpan(4, 0, 2, 1)
            self.table.setSpan(4, 1, 2, 1)
            self.table.setSpan(4, 2, 2, 1)
            self.table.setSpan(4, 3, 2, 1)
            n_it = QTableWidgetItem("N")
            n_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 0, n_it)
            sco_cur_it = QTableWidgetItem("СКО\nтекущее")
            sco_cur_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 1, sco_cur_it)
            sco_mean_it = QTableWidgetItem("СКО\nсреднее")
            sco_mean_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 2, sco_mean_it)
            t_it = QTableWidgetItem("Время\nперестроения")
            t_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 3, t_it)
        else:
            # self.table.setSpan(4, 1, 2, 1)
            # self.table.setSpan(4, 2, 2, 1)
            # self.table.setSpan(4, 3, 2, 1)
            n_it = QTableWidgetItem("N")
            n_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 0, n_it)
            t_it = QTableWidgetItem("Время")
            t_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 1, t_it)
            f_it = QTableWidgetItem("Штраф")
            f_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 2, f_it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(4, 3, unu_it)
            self.table.item(4, 3).setBackground(COLOR_UNUSED)

        layout.addWidget(self.table)

        self.setLayout(layout)
        self.add_row()

    def timer_event(self):
        self.time = self.time.addSecs(1)
        timer_item = QTableWidgetItem(self.time.toString("mm:ss"))
        timer_item.setData(Qt.FontRole, QFont("", 20))
        timer_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        timer_item.setFlags(Qt.NoItemFlags)
        self.table.setItem(0, 0, timer_item)

    def add_row(self):
        rc = self.table.rowCount()
        self.table.insertRow(rc)
        if self.formation:
            it = QTableWidgetItem(str(rc - 5))
            it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 0, it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 1, unu_it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 2, unu_it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 3, unu_it)
        else:
            it = QTableWidgetItem(str(rc - 4))
            it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 0, it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 1, unu_it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 2, unu_it)
            unu_it = QTableWidgetItem()
            unu_it.setFlags(Qt.NoItemFlags)
            self.table.setItem(rc, 3, unu_it)
            self.table.item(rc, 3).setBackground(COLOR_UNUSED)

    def update_collisions(self, data):
        data_it = QTableWidgetItem(str(data))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(2, 1, data_it)

    def update_side_time(self, data):
        data_it = QTableWidgetItem(str(round(float(data), 2)))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(2, 3, data_it)

    def update_msd_current(self, data):
        data_it = QTableWidgetItem(str(round(float(data), 2)))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(self.table.rowCount() - 1, 1, data_it)

    def update_msd_overall(self, data):
        data_it = QTableWidgetItem(str(round(float(data), 2)))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(self.table.rowCount() - 1, 2, data_it)

    def update_reformation(self, data):
        data_it = QTableWidgetItem(str(round(float(data), 2)))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(self.table.rowCount() - 1, 3, data_it)

    def update_times(self, data):
        data_it = QTableWidgetItem(str(round(float(data), 2)))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(self.table.rowCount() - 1, 1, data_it)

    def update_passes(self, data):
        data_it = QTableWidgetItem(str(round(float(data), 2)))
        data_it.setFlags(Qt.NoItemFlags)
        self.table.setItem(self.table.rowCount() - 1, 2, data_it)

    def collisions_cb(self, data):
        self.update_collisions(data.data)

    def side_time_cb(self, data):
        self.update_side_time(data.data)

    def msd_current_cb(self, data):
        self.update_msd_current(data.data)

    def msd_overall_cb(self, data):
        self.update_msd_overall(data.data)
        self.add_row()

    def reformation_cb(self, data):
        self.update_reformation(data.data)

    def passes_cb(self, data):
        self.update_passes(data.data)

    def times_cb(self, data):
        self.update_times(data.data)
        self.add_row()

    # noinspection PyMethodMayBeStatic
    def final_cb(self, data):
        dds = data.data.split('::')
        if len(dds) == 4:
            string = "FINAL SCORE: {} \n" \
                     "___________________________ \n" \
                     "NOMINATIONS\n" \
                     "SYNCHRONICITY: {} \n" \
                     "EFFICIENCY: {} \n" \
                     "SPEED: {}".format(*tuple(dds))
        elif len(dds) == 3:
            string = "FINAL SCORE: {} \n" \
                     "___________________________ \n" \
                     "NOMINATIONS\n" \
                     "ACCURACY: {} \n" \
                     "SPEED: {}".format(*tuple(dds))
        else:
            string = "BAD DATA"
        # print(string)
        self.final_string = string
        self.show_msg.emit()

    def show_message(self):
        QMessageBox.information(self.parent(), "RESULT", self.final_string,
                                QMessageBox.Ok)
Ejemplo n.º 10
0
class Timer(QWidget):
    """
    Timer component. Contains a label and a button
    """
    paused = False

    def __init__(self, timer_data, style=Style()):
        """
        Initialize styling and create its components
        :param timer_data: timer value from JSON
        :param style: styling object
        """

        super().__init__()

        # Styling and main layout
        self.styles = style
        self.box_layout = QHBoxLayout()
        self.box_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.box_layout)

        # Label (displays the timer value)
        self.label = QLabel()
        self.label.setStyleSheet(self.styles.timer_label)
        self.label.setText("00:00:00")
        self.box_layout.addWidget(self.label)

        # Button pause/continue
        self.button = QPushButton()
        self.button.setIconSize(QSize(50, 50))
        self.button.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPause")))
        self.button.setStyleSheet(self.styles.timer_button)
        self.button.clicked.connect(self.btnClicked)
        self.box_layout.addWidget(self.button)

        # Initialize the clock
        self.curr_time = QTime(timer_data[0], timer_data[1], timer_data[2])
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)

    def updateTime(self):
        """
        Timers callback (called every second to update the timer value)
        """

        self.curr_time = self.curr_time.addSecs(1)
        self.label.setText(self.curr_time.toString("hh:mm:ss"))

    def btnClicked(self):
        """
        Pause or continue the timer depending of its status
        """

        if self.paused:
            self.timer.start()
            self.paused = False
            self.button.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPause")))
        else:
            self.timer.stop()
            self.paused = True
            self.button.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPlay")))
Ejemplo n.º 11
0
class Device:
    def __init__(self, s, d, c, i):
        self.media_listener = MediaListener()
        self.media_listener._self = s
        self.media_listener.index = i
        self.status_listener = StatusListener()
        self.status_listener._self = s
        self.status_listener.index = i
        self.connection_listener = ConnectionListener()
        self.connection_listener._self = s
        self.cast = c
        self.index = i
        self._self = s
        self.device = d
        self.live = False
        self.muted = False
        self.unmute_volume = 0
        self.disconnect_volume = 0
        self.paused = True
        self.playing = False
        self.stopping = False
        self.rebooting = False
        self.catt_process = None
        self.directory = None
        self.filename = None
        self.playback_starting = False
        self.playback_just_started = False
        self.stopping_timer = QTimer()
        self.starting_timer = QTimer()
        self.just_started_timer = QTimer()
        self.progress_clicked = False
        self.catt_read_thread = None
        self.progress_timer = QTimer()
        self.time = QTime(0, 0, 0)
        self.stopping_timer.timeout.connect(lambda: s.on_stopping_timeout(self))
        self.starting_timer.timeout.connect(lambda: s.on_starting_timeout(self))
        self.just_started_timer.timeout.connect(lambda: s.on_just_started_timeout(self))
        self.stopping_timer.setSingleShot(True)
        self.starting_timer.setSingleShot(True)
        self.just_started_timer.setSingleShot(True)
        self.progress_timer.timeout.connect(self.on_progress_tick)

    def on_progress_tick(self):
        s = self._self
        self.time = self.time.addSecs(1)
        duration = self.device._cast.media_controller.status.duration
        if duration and duration != 0 and time_to_seconds(self.time) >= int(duration):
            # If progress is at the end, stop the device progress timer
            self.set_state_idle(self.index)
            if s.combo_box.currentIndex() == self.index:
                # If it is the currently selected device, update the ui
                self.update_ui_idle()
        if s.combo_box.currentIndex() == self.index:
            # Update the ui elements using current progress time
            s.progress_label.setText(self.time.toString("hh:mm:ss"))
            s.set_progress(time_to_seconds(self.time))

    def set_state_playing(self, i, time):
        s = self._self
        s.set_time(i, int(time))
        self.paused = False
        self.playing = True
        if self.live:
            s.stop_timer.emit(i)
            self.time.setHMS(0, 0, 0)
        else:
            s.start_timer.emit(i)

    def update_ui_playing(self, time, duration):
        s = self._self
        if duration != None:
            s.progress_slider.setMaximum(duration)
        if self.live:
            s.skip_forward_button.setEnabled(False)
            s.progress_slider.setEnabled(False)
            s.progress_label.setText("LIVE")
            s.set_icon(s.play_button, "SP_MediaPlay")
        else:
            s.skip_forward_button.setEnabled(True)
            s.progress_slider.setEnabled(True)
            s.set_icon(s.play_button, "SP_MediaPause")
        s.set_progress(time)
        s.progress_label.setText(self.time.toString("hh:mm:ss"))
        self.update_text()

    def set_state_paused(self, i, time):
        s = self._self
        s.set_time(i, int(time))
        s.stop_timer.emit(i)
        self.paused = True
        self.playing = True

    def update_ui_paused(self, time, duration):
        s = self._self
        if duration != None:
            s.progress_slider.setMaximum(duration)
        s.set_progress(time)
        s.skip_forward_button.setEnabled(True)
        s.progress_slider.setEnabled(True)
        s.set_icon(s.play_button, "SP_MediaPlay")
        s.progress_label.setText(self.time.toString("hh:mm:ss"))
        self.update_text()

    def set_state_idle(self, i):
        s = self._self
        s.stop_timer.emit(i)
        self.time.setHMS(0, 0, 0)
        self.playing = False
        self.paused = True
        self.live = False

    def update_ui_idle(self):
        s = self._self
        s.set_progress(0)
        s.skip_forward_button.setEnabled(False)
        s.progress_slider.setEnabled(False)
        s.progress_label.setText(self.time.toString("hh:mm:ss"))
        s.set_icon(s.play_button, "SP_MediaPlay")
        self.update_text()

    def set_dial_value(self):
        s = self._self
        v = self.device._cast.status.volume_level * 100
        s.dial.valueChanged.disconnect(s.on_dial_moved)
        if v != 0:
            self.unmute_volume = v
        s.dial.setValue(v)
        s.set_volume_label(v)
        s.dial.valueChanged.connect(s.on_dial_moved)

    def split_seconds(self, s):
        hours = s // 3600
        minutes = (s - (hours * 3600)) // 60
        seconds = s - ((hours * 3600) + (minutes * 60))
        return hours, minutes, seconds

    def set_text(self, s, status_text, title):
        prefix = ""
        if self.live:
            prefix = "Streaming"
        if prefix and (status_text or title):
            prefix = prefix + " - "
        if status_text and title:
            if status_text in title:
                s.status_label.setText(prefix + title)
            elif title in status_text:
                s.status_label.setText(prefix + status_text)
            else:
                s.status_label.setText(prefix + status_text + " - " + title)
        elif status_text:
            s.status_label.setText(prefix + status_text)
        elif title:
            s.status_label.setText(prefix + title)
        elif prefix:
            s.status_label.setText(prefix)
        elif self.filename == None:
            s.status_label.setText("Idle")

    def update_text(self):
        title = self.device._cast.media_controller.title
        status_text = self.device._cast.status.status_text
        s = self._self
        if not self.playing:
            if self.stopping:
                s.status_label.setText("Stopping..")
            elif self.rebooting:
                s.status_label.setText("Rebooting..")
            elif (
                self.playback_starting == False and self.playback_just_started == False
            ) or s.status_label.text() == "Stopping..":
                s.status_label.setText("Idle")
                s.set_icon(s.play_button, "SP_MediaPlay")
            else:
                self.set_text(s, status_text, title)
            return
        self.set_text(s, status_text, title)

    def kill_catt_process(self):
        if self.catt_process == None:
            return
        if self.catt_read_thread != None:
            self.catt_read_thread.cancel()
        try:
            os.kill(self.catt_process.pid, signal.SIGINT)
            self.catt_process.wait()
        except:
            pass
        self.catt_process = None
Ejemplo n.º 12
0
    def populateForm(self, title): #title is the primary key
        listArray = queries("""SELECT title, status, style, duration, description,
        location, project, variation_another_song, timestamp from songs WHERE title = ?""", (title,))
        print(listArray)
        if len(listArray) != 0:
            title = listArray[0][0]
            status = listArray[0][1]

            styles = []
            styleArray = listArray[0][2]
            if styleArray != None:
                if "," in styleArray:
                    styles = styleArray.split(",")
                else:
                    styles.append(styleArray)
            duration = listArray[0][3]
            description = listArray[0][4]
            location = listArray[0][5]
            project = listArray[0][6]
            variation_another_song = listArray[0][7]
            timestamp = listArray[0][8]
        else:
            title = None
            status = None
            styles = None
            duration = None
            description = None
            location = None
            project = None
            variation_another_song = None
            timestamp = None

        if title != None: self.titleEdit.setText(title)

        self.statusBox.addItems(["Select...", "Demo", "WIP", "Idea", "Unfinished song", "EQ", "Master", "Finished"])
        if status != None: self.statusBox.setCurrentText(status)
        if timestamp != None: self.dateEdit.setDateTime(datetime.strptime(timestamp, '%d/%m/%Y %H:%M'))
        else: self.dateEdit.setDateTime(datetime.now())#default

        styleArray = queries("select style from songs where style is not null")

        """
        print(styleArray)
        if styleArray != None:
            styleArray = styleArray[0][0]
            if "," in styleArray:
                styles = styleArray.split(",")
            else:
                styles.append(styleArray)"""

        stylesArray = []

        query = queries("select style from songs where style is not null")
        if len(query) != 0:
            for style in query:
                stylesMiniArray = style[0].split(",")
                stylesMiniArray = list(filter(None, stylesMiniArray))
                for item in stylesMiniArray:
                    if item not in stylesArray:
                        if item != '':
                            stylesArray.append(item)

        self.x = 0
        self.y = 0

        if len(stylesArray) != 0:
            for style in stylesArray:
                    print("style", style)
                    checkBox = QCheckBox(style)
                    self.styleLayout.addWidget(checkBox, self.x, self.y)
                    self.checkBoxPositionAsignment()
        self.addStyle()

        if styles!= None:
            if len(styles) != 0:
                for style in styles:
                    for checkbox in self.styleGroupBox.children():
                        if isinstance(checkbox, QCheckBox):
                            if checkbox.text() == style:
                                checkbox.setChecked(True)

        if duration != None:
                time = QTime(0,0,0)
                self.durationLine.setTime(time.addSecs(duration))

        projectsArray = ["Select..."]
        projectsArrayQuery = queries("SELECT project from songs")
        if len(projectsArrayQuery) != 0:
            for project in projectsArrayQuery[0]:
                if project not in projectsArray:
                    projectsArray.append(project)
        if project != None: self.projectComboBox.setCurrentText(project)

        if variation_another_song != None: self.variationLine.setText(variation_another_song)
        if description != None: self.descriptionTextEdit.setText(description)

        available = False
        if location != None:
            self.locationLine.setText(location)
        if len(self.locationLine.text()) != 0:
            try:
                self.playlist = QMediaPlaylist()
                self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(location)))
                self.mediaPlayer.setPlaylist(self.playlist)
            except:
                pass
            available = True#I know this is stupid but just in case

        self.slider.setVisible(available)
        self.playButton.setVisible(available)
        self.stopButton.setVisible(available)
Ejemplo n.º 13
0
class Board(QFrame):
    """
    Everything to handle the game: Drawing pieces and the board, Handling the mouse and the game logic
    """
    msg2Statusbar = pyqtSignal(str)

    # todo set the board with and height in square
    boardWidth = 8
    boardHeight = 8
    Speed = 300

    def __init__(self, parent):
        super().__init__(parent)
        self.init()

    def init(self):
        """
        Initialise all values

        :return:
        """
        self.boardArray = [[0, 3, 0, 3, 0, 3, 0, 3],
                           [3, 0, 3, 0, 3, 0, 3, 0],
                           [0, 3, 0, 3, 0, 3, 0, 3],
                           [1, 0, 1, 0, 1, 0, 1, 0],
                           [0, 1, 0, 1, 0, 1, 0, 1],
                           [2, 0, 2, 0, 2, 0, 2, 0],
                           [0, 2, 0, 2, 0, 2, 0, 2],
                           [2, 0, 2, 0, 2, 0, 2, 0]]
        # Timer initialization

        self.timer = QTimer()
        self.time = QTime(0, 0, 0)
        self.timer.timeout.connect(self.timerEventGame)

        self.timerPlayer = QTimer()
        self.timePlayer = QTime(0, 1, 0)
        self.timer.timeout.connect(self.timerEventPlayer)

        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        # image de la piece de base m'voyez
        self.image = QImage(WHITE_PIECE)
        # self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.reset_game()
        self.selected_piece = [-1, -1]
        self.player_turn = 1
        # nombre de piece = [nb de piece joueur 1, nb de piece jour 2]
        self.playersRemaining = [12, 12]
        # nombre de jump = [nb de jump joueur 1, nb de jump jour 2]
        self.playersJumps = [0, 0]
        self.scoreBoard = None
        self.status = FPLAYER
        # si le temps du joueur a timeout
        self.timePassed = False
        self.startTime = 0
        self.interval = 0
        # pour changer l'affichage si on jou contre une AI
        self.isAI = False
        self.winner = -1
        self.aiDifficulties = 2

    def timerEventGame(self):
        """
        This function allows to update the game timer and update the scoreBoard.

        :return: Nothing
        """
        # Update the game timer
        self.time = self.time.addSecs(1)
        # Update de UI of the scoreBoard
        self.scoreBoard.updateUI()

    def initPlayerTimer(self):
        """
        Init the player timer when the player begin his turn.

        :return: Nothing
        """
        self.timerPlayer = QTimer()
        self.timePlayer = QTime(0, 1, 0)

    def startTimerInter(self, interval):
        """
        Start the player timer with an given interval.

        :param interval: The interval from which time must resume
        :return: Nothing
        """
        self.timerPlayer.start(interval)

    def startTimerPlayer(self):
        """"
        Function to start a player timer with an interval of 1000.
        """
        self.interval = 1000
        self.startTime = time.time()
        self.timerPlayer.start(1000)

    def timerEventPlayer(self):
        """
        This function allows to update the timer of the player one.

        :return: Nothing
        """
        self.timePlayer = self.timePlayer.addSecs(-1)
        if self.timerPlayer.isActive():
            if self.timePlayer.minute() * 60 + self.timePlayer.second() < 1:
                self.timePassed = True
                self.timerPassedEndGame()
        self.scoreBoard.updateUI()

    def setScoreBoard(self, scoreBoard):
        """
        This function allows to get the scoreBoard class to use it later in the code.

        :param scoreBoard: The class scoreBoard
        :return: Nothing
        """
        self.scoreBoard = scoreBoard

    def print_board_array(self):
        """
        Prints the boardArray in an attractive way

        :return: Nothing
        """

        print("boardArray:")
        print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in self.boardArray]))

    def mouse_pos_to_col_row(self, event):
        """
        Convert the mouse click event to a row and column.

        :param event: The click event
        :return: The click's position with the following format: [x, y] (Example: [3, 4])
        """

        return [int(event.x() / self.square_width()), int(event.y() / self.square_height())]

    def square_width(self):
        """
        This function allows to return the width of one square in the board.

        :return: The width of one square in the board.
        """
        return self.contentsRect().width() / Board.boardWidth

    def square_height(self):
        """
        This function allows to return the height of one square in the board.

        :return: The height of one square in the board
        """

        return self.contentsRect().height() / Board.boardHeight

    def start(self):
        """starts game"""
        if self.isPaused:
            return

        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.reset_game()
        self.timer.start(1000)
        self.startTimerPlayer()
        # self.timerPlayer.start(1000)

    def pause(self):
        """pauses game"""

        if not self.isStarted:
            return

        self.isPaused = not self.isPaused

        if self.isPaused:
            self.timerPlayer.stop()
            self.timer.stop()
            self.status = "Game paused"
            elapsedTime = self.startTime - time.time()
            self.startTime -= elapsedTime
            self.interval -= int(elapsedTime * 1000)

        else:
            self.timer.start()
            self.startTimerInter(self.interval)
            if self.player_turn == 1:
                self.status = FPLAYER
            elif self.isAI:
                self.status = AIPLAYER
            else:
                self.status = SPLAYER
            self.scoreBoard.updateUI()

        self.update()

    def paintEvent(self, event):
        """paints the board and the pieces of the game"""
        painter = QPainter(self)
        self.draw_board_squares(painter)
        self.draw_pieces(painter)

    def new_place(self, turn, row, col, change):
        """
        Change the piece place

        :param turn:
        :param row:
        :param col:
        :param change:
        :return:
        """
        self.boardArray[row][col] = self.boardArray[self.selected_piece[1]][self.selected_piece[0]]
        if (row == 0 and self.boardArray[row][col] == 2) or (row == 7 and self.boardArray[row][col] == 3):
            self.boardArray[row][col] += 2
        self.boardArray[self.selected_piece[1]][self.selected_piece[0]] = 1
        if change == 1:
            self.selected_piece = [-1, -1]
        else:
            self.selected_piece = [col, row]
        self.player_turn = turn
        self.scoreBoard.updateUI()

    def first_player_take(self, row, col):
        """
        Take a piece for the first player

        :param row:
        :param col:
        :return:
        """
        p = 2
        change = 1
        b = 0
        r = self.selected_piece[1]
        c = self.selected_piece[0]
        if self.boardArray[r][c] == 2 and r > 1 and c > 1 and self.boardArray[r - 2][c - 2] == 1 and \
                        self.boardArray[r - 1][c - 1] == 3:
            b = 1
        elif self.boardArray[r][c] == 2 and r > 1 and c < 6 and self.boardArray[r - 2][c + 2] == 1 and \
                        self.boardArray[r - 1][c + 1] == 3:
            b = 1
        if b == 0 and self.player_turn == 1 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] - 1 \
                and (col == self.selected_piece[0] + 1 or col == self.selected_piece[0] - 1):
            self.new_place(2, row, col, change)
        elif self.player_turn == 1 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] - 2 \
                and col == self.selected_piece[0] + 2 and self.boardArray[row + 1][col - 1] == 3:
            self.boardArray[row + 1][col - 1] = 1
            self.playersRemaining[1] -= 1
            if self.playersRemaining[1] == 0:
                self.timePassed = True
                self.player_turn = 2
                self.timerPassedEndGame()
            self.playersJumps[0] += 1
            if row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                p = 1
                change = 0
            elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                p = 1
                change = 0
            self.new_place(p, row, col, change)
        elif self.player_turn == 1 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] - 2 \
                and col == self.selected_piece[0] - 2 and self.boardArray[row + 1][col + 1] == 3:
            self.boardArray[row + 1][col + 1] = 1
            self.playersRemaining[1] -= 1
            if self.playersRemaining[1] == 0:
                self.timePassed = True
                self.player_turn = 2
                self.timerPassedEndGame()
            self.playersJumps[0] += 1
            if row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                p = 1
                change = 0
            elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                p = 1
                change = 0
            self.new_place(p, row, col, change)

    def second_player_take(self, row, col):
        """
        Take a piece for the second player

        :param row:
        :param col:
        :return:
        """
        p = 1
        change = 1
        b = 0
        r = self.selected_piece[1]
        c = self.selected_piece[0]
        if self.boardArray[r][c] == 3 and r < 6 and c > 1 and self.boardArray[r + 2][c - 2] == 1 and \
                        self.boardArray[r + 1][c - 1] == 2:
            b = 1
        elif self.boardArray[r][c] == 3 and r < 6 and c < 6 and self.boardArray[r + 2][c + 2] == 1 and \
                        self.boardArray[r + 1][c + 1] == 2:
            b = 1
        if b == 0 and self.player_turn == 2 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] + 1 \
                and (col == self.selected_piece[0] + 1 or col == self.selected_piece[0] - 1):
            self.new_place(p, row, col, change)
        elif self.player_turn == 2 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] + 2 \
                and col == self.selected_piece[0] + 2 and self.boardArray[row - 1][col - 1] == 2:
            self.boardArray[row - 1][col - 1] = 1
            self.playersRemaining[0] -= 1
            if self.playersRemaining[0] == 0:
                self.timePassed = True
                self.player_turn = 1
                self.timerPassedEndGame()
            self.playersJumps[1] += 1
            if row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                p = 2
                change = 0
            elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                p = 2
                change = 0
            self.new_place(p, row, col, change)
        elif self.player_turn == 2 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] + 2 \
                and col == self.selected_piece[0] - 2 and self.boardArray[row - 1][col + 1] == 2:
            self.boardArray[row - 1][col + 1] = 1
            self.playersRemaining[0] -= 1
            if self.playersRemaining[0] == 0:
                self.timePassed = True
                self.player_turn = 1
                self.timerPassedEndGame()
            self.playersJumps[1] += 1
            if row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                p = 2
                change = 0
            elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                p = 2
                change = 0
            self.new_place(p, row, col, change)

    def mousePressEvent(self, event):
        """
        Get the pos clicked and call the game logic
        :param event:
        :return:
        """
        if not self.isPaused:
            clicked = self.mouse_pos_to_col_row(event)
            if clicked:
                self.logicGame(clicked)

    def AI(self):
        """
        Creates the AI class with the array board.
        Then, it get the positions choosed by the AI.
        Finally it call the logic Game to move the piece.

        :return: Nothing
        """

        self.selected_piece = [-1, -1]
        self.ai = AI(self.boardArray)
        positions = self.ai.MinMaxDecision(self.aiDifficulties)
        self.logicGame([positions[0][1], positions[0][0]])
        self.logicGame([positions[1][1], positions[1][0]])

    def timerPassedEndGame(self):
        """
        When a player take a lot of time to play (1 minutes)

        :return: -1 (value for the end of the game)
        """
        self.status = ENDGAME
        self.timerPlayer.stop()
        self.timer.stop()
        if self.player_turn == 1:
            if not self.isAI:
                self.winner = 2
            else:
                self.winner = 3
        else:
            self.winner = 1
        # self.scoreBoard.updateUI()
        # self.init()
        return -1

    def logicGame(self, positions):
        """
        Game logic to manage pieces moves
        :param positions:
        :return:
        """
        row = positions[1]
        col = positions[0]
        if self.timePassed:
            return self.timerPassedEndGame()
        if self.player_turn == 1:
            self.status = FPLAYER
        elif self.isAI:
            self.status = AIPLAYER
        else:
            self.status = SPLAYER

        if self.selected_piece == [-1, -1]:
            if self.player_turn == 1:
                b = 0
                for r in range(0, len(self.boardArray)):
                    for c in range(0, len(self.boardArray[0])):
                        if self.boardArray[r][c] == 2 and r > 1 and c > 1 and self.boardArray[r - 2][c - 2] == 1 and self.boardArray[r - 1][c - 1] == 3:
                            b = 1
                        elif self.boardArray[r][c] == 2 and r > 1 and c < 6 and self.boardArray[r - 2][c + 2] == 1 and self.boardArray[r - 1][c + 1] == 3:
                            b = 1
                if self.boardArray[row][col] == self.player_turn + 1:
                    if (b == 0 and row > 0 and col > 0 and self.boardArray[row - 1][col - 1] == 1) \
                            or (b == 0 and row > 0 and col < 7 and self.boardArray[row - 1][col + 1] == 1):
                        self.selected_piece = positions
                    elif row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                        self.selected_piece = positions
                    elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                        self.selected_piece = positions
            elif self.player_turn == 2:
                b = 0
                for r in range(0, len(self.boardArray)):
                    for c in range(0, len(self.boardArray[0])):
                        if self.boardArray[r][c] == 3 and r < 6 and c > 1 and self.boardArray[r + 2][c - 2] == 1 and self.boardArray[r + 1][c - 1] == 2:
                            b = 1
                        elif self.boardArray[r][c] == 3 and r < 6 and c < 6 and self.boardArray[r + 2][c + 2] == 1 and self.boardArray[r + 1][c + 1] == 2:
                            b = 1
                if self.boardArray[row][col] == self.player_turn + 1:
                    if (b == 0 and row < 7 and col > 0 and self.boardArray[row + 1][col - 1] == 1) \
                        or (b == 0 and row < 7 and col < 7 and self.boardArray[row + 1][col + 1] == 1):
                        self.selected_piece = positions
                    elif row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                        self.selected_piece = positions
                    elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                        self.selected_piece = positions

        else:
            if self.selected_piece == positions:
                self.selected_piece = [-1,-1]
                return
            self.first_player_take(row, col)
            self.second_player_take(row, col)
            if self.player_turn == 1:
                self.status = FPLAYER
            else:
                self.status = SPLAYER
            self.initPlayerTimer()
            self.startTimerPlayer()
            if self.player_turn == 2 and self.isAI:
                self.AI()

    def keyPressEvent(self, event):
        """processes key press events if you would like to do any"""
        if not self.isStarted or self.curPiece.shape() == Piece.NoPiece:
            super(Board, self).keyPressEvent(event)
            return
        key = event.key()
        if key == Qt.Key_P:
            self.pause()
            return
        if self.isPaused:
            return
        elif key == Qt.Key_Left:
            self.try_move(self.curPiece, self.curX - 1, self.curY)
        elif key == Qt.Key_Right:
            self.try_move(self.curPiece, self.curX + 1, self.curY)
        elif key == Qt.Key_Down:
            self.try_move(self.curPiece.rotateRight(), self.curX, self.curY)
        elif key == Qt.Key_Up:
            self.try_move(self.curPiece.rotateLeft(), self.curX, self.curY)
        elif key == Qt.Key_Space:
            self.dropDown()
        elif key == Qt.Key_D:
            self.oneLineDown()
        else:
            super(Board, self).keyPressEvent(event)

    def timerEvent(self, event):
        """handles timer event"""

        #todo adapter this code to handle your timers
        if event.timerId() == self.timer.timerId():
            pass
        else:
            super(Board, self).timerEvent(event)

    def reset_game(self):
        """clears pieces from the board"""

        # 2d int/Piece array to story the state of the game
        # 2 pion blanc, 3 pion noir
        self.boardArray = [[0, 3, 0, 3, 0, 3, 0, 3],
                           [3, 0, 3, 0, 3, 0, 3, 0],
                           [0, 3, 0, 3, 0, 3, 0, 3],
                           [1, 0, 1, 0, 1, 0, 1, 0],
                           [0, 1, 0, 1, 0, 1, 0, 1],
                           [2, 0, 2, 0, 2, 0, 2, 0],
                           [0, 2, 0, 2, 0, 2, 0, 2],
                           [2, 0, 2, 0, 2, 0, 2, 0]]
        self.selected_piece = [-1, -1]
        # self.print_board_array()

    def try_move(self, new_x, new_y):
        """tries to move a piece"""

    def draw_board_squares(self, painter):
        """
        This function allows to draw all the square on the board.

        :param painter: The painter
        :return: Nothing
        """

        # todo set the default colour of the brush
        images = [QImage(WHITE_SQUARE), QImage(BLACK_SQUARE)]
        idx = 0
        for row in range(0, Board.boardHeight):
            for col in range(0, Board.boardWidth):
                #painter.save()
                # Todo set this value equal the transformation you would like in the column direction (x)
                colTransformation = col * self.square_width()

                # Todo set this value equal the transformation you would like in the column direction (y)
                row_transformation = row * self.square_height()

                final_image = images[idx].scaled(self.square_width(), self.square_height())
                painter.drawImage(colTransformation, row_transformation, final_image)
                #painter.restore()
                idx = 1 if idx == 0 else 0
            idx = 1 if idx == 0 else 0

    def color_brush_white(self, row, col, i):
        """
        Set the brush color for white pieces
        :param row:
        :param col:
        :param i:
        :return:
        """
        brush_color = Qt.black
        if self.player_turn == 1 and self.selected_piece[1] == row and self.selected_piece[0] == col:
            brush_color = QColor.fromRgb(100, 255, 100)
        elif self.player_turn == 1 and self.selected_piece == [-1, -1]:
            if i > 0 and row > 0 and col > 0 and self.boardArray[row - 1][col - 1] == 1:
                brush_color = Qt.white
            elif i > 0 and row > 0 and col < 7 and self.boardArray[row - 1][col + 1] == 1:
                brush_color = Qt.white
            elif row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                brush_color = Qt.white
            elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                brush_color = Qt.white
        return brush_color

    def color_brush_black(self, row, col, i):
        """
        Set the brush color for black pieces
        :param row:
        :param col:
        :param i:
        :return:
        """
        brush_color = Qt.black
        if self.player_turn == 2 and self.selected_piece[1] == row and self.selected_piece[0] == col:
            brush_color = QColor.fromRgb(100, 100, 255)
        elif self.player_turn == 2 and self.selected_piece == [-1, -1]:
            if i > 0 and row < 7 and col > 0 and self.boardArray[row + 1][col - 1] == 1:
                brush_color = QColor.fromRgb(255, 0, 255)
            elif i > 0 and row < 7 and col < 7 and self.boardArray[row + 1][col + 1] == 1:
                brush_color = QColor.fromRgb(255, 0, 255)
            elif row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                brush_color = QColor.fromRgb(255, 0, 255)
            elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                brush_color = QColor.fromRgb(255, 0, 255)
        return brush_color

    def draw_pieces(self, painter):
        """draw the prices on the board"""
        brush_color = QColor.fromRgb(200, 200, 200)
        images = [QImage(WHITE_PIECE), QImage(BLACK_PIECE), QImage(WHITE_KING), QImage(BLACK_KING), QImage(BLACK_SQUARE)]
        idx = 0
        i = 0
        y = 1
        while i < 2:
            for row in range(0, len(self.boardArray)):
                for col in range(0, len(self.boardArray[0])):
                    #painter.save()
                    col_transformation = col * self.square_width()
                    row_transformation = row * self.square_height()
                    ## Todo victoire quand bloquer

                    if self.boardArray[row][col] == 2:
                        brush_color = self.color_brush_white(row, col, i)
                        idx = 0
                    elif self.boardArray[row][col] == 1:
                        brush_color = Qt.black
                        idx = 4
                    elif self.boardArray[row][col] == 3:
                        brush_color = self.color_brush_black(row, col, i)
                        idx = 1
                    elif self.boardArray[row][col] == 4:
                        brush_color = self.color_brush_white(row, col, i)
                        idx = 2
                    elif self.boardArray[row][col] == 5:
                        brush_color = self.color_brush_black(row, col, i)
                        idx = 3
                    elif self.boardArray[row][col] == 6:
                        brush_color = QColor.fromRgb(128, 128, 128)
                    if self.boardArray[row][col] != 0:
                        painter.setPen(brush_color)
                        if brush_color == Qt.white or brush_color == QColor.fromRgb(255, 0, 255):
                            y = 2
                        # Todo draw some the pieces as eclipses
                        radius_width = (self.square_width() / 10 * 8) / 2
                        radius_height = (self.square_height() / 10 * 8) / 2
                        center = QPoint(col_transformation + (self.square_width() / 2),
                                        row_transformation + (self.square_height() / 2))
                        if idx != 4:
                            painter.drawEllipse(center, radius_width, radius_height)
                            self.image = images[idx].scaled(radius_width * 2, radius_height * 2)
                            painter.drawImage(center.x() - radius_width, center.y() - radius_height, self.image)
                        #painter.restore()
                        self.update()
            i += y
Ejemplo n.º 14
0
class TimerWindow(QWidget):

    #Button control functions
    def handleStartBtn(self):
        global isStarted
        isStarted = True
        self.statusInput.setText("Timer Started!")
        self.statusInput.setStyleSheet('color: grey')

    def handleStopBtn(self):
        global isStarted
        if isStarted:
            isStarted = False
            self.statusInput.setText("Reset Timer?")
            self.statusInput.setStyleSheet('color: blue')

    def handleResetBtn(self):
        global isStarted
        global elapseHours
        isStarted = False
        elapseHours = 0
        self.stopwatchTime = QTime(0, 0, 0, 0)
        self.curElapse.setText("00:00:00:000 ms")
        self.updateTimer()

    def handleCloseBtn(self):
        print("Close Button Pressed!")
        self.hide()

    def formatTime(self):
        #Find current time
        timeNow = QTime.currentTime()
        fullTime = timeNow.toString("hh:mm:ss:zzz 'ms'")
        return fullTime

    def formatElapse(self):
        global elapseHours
        if self.stopwatchTime.hour() == 1:
            elapseHours += 1
            self.stopwatchTime = self.stopwatchTime.addSecs(-3600)
        if elapseHours < 10:
            elapseHoursS = "0" + str(elapseHours)
        else:
            elapseHoursS = str(elapseHours)
        fullElapseS = elapseHoursS + ":" + self.stopwatchTime.toString(
            "mm:ss:zzz 'ms'")
        return fullElapseS

    def deductTimer(self):
        global totalMSecRemain
        totalMSecRemain -= 87

    def formatTimer(self):

        global totalMSecRemain
        global isInfoShown

        #Return zeros if miliseconds remaining are negative
        if totalMSecRemain <= 0:
            if not isInfoShown:
                showInfo("Time is Up!")
                isInfoShown = True
            return "00:00:00:000 ms"

        #Calculate timer values
        totalHours = int(totalMSecRemain / 3600000)
        totalMin = int((totalMSecRemain % 3600000) / 60000)
        totalSec = int(((totalMSecRemain % 3600000) % 60000) / 1000)
        totalMilSec = int(((totalMSecRemain % 3600000) % 60000) % 1000)

        #Update timer label
        if totalHours == 0:
            totalHoursS = "00"
        elif totalHours < 10:
            totalHoursS = "0" + str(totalHours)
        else:
            totalHoursS = str(totalHours)

        if totalMin == 0:
            totalMinS = "00"
        elif totalMin < 10:
            totalMinS = "0" + str(totalMin)
        else:
            totalMinS = str(totalMin)

        if totalSec == 0:
            totalSecS = "00"
        elif totalSec < 10:
            totalSecS = "0" + str(totalSec)
        else:
            totalSecS = str(totalSec)

        if totalMilSec == 0:
            totalMilSecS = "000"
        elif totalMilSec < 10:
            totalMilSecS = "00" + str(totalMilSec)
        elif totalMilSec < 100:
            totalMilSecS = "0" + str(totalMilSec)
        else:
            totalMilSecS = str(totalMilSec)

        fullTimerS = totalHoursS + ":" + totalMinS + ":" + totalSecS + ":" + totalMilSecS + " ms"
        return fullTimerS

    def updateTime(self):
        #Update of cur time clock
        self.curTime.setText(self.formatTime())
        #Update next two clocks if started
        if isStarted == True:
            #Update of elapsed time
            self.stopwatchTime = self.stopwatchTime.addMSecs(87)
            self.curElapse.setText(self.formatElapse())
            #Update of timer clock
            self.deductTimer()
            self.curTimer.setText(self.formatTimer())

    def updateTimer(self):
        if isStarted:
            return

        global totalMSecRemain
        global isInfoShown

        inputPresent = False
        isAccepted = False

        #Value validation
        try:
            if self.hourInputFeild.text() != "":
                hourInputNum = int(float(self.hourInputFeild.text()))
                inputPresent = True
                isAccepted = True
            else:
                hourInputNum = 0
            if self.minInputFeild.text() != "":
                minInputNum = int(float(self.minInputFeild.text()))
                inputPresent = True
                isAccepted = True
            else:
                minInputNum = 0
            if self.secInputFeild.text() != "":
                secInputNum = int(float(self.secInputFeild.text()))
                inputPresent = True
                isAccepted = True
            else:
                secInputNum = 0
            self.statusInput.setText("Input Accepted!")
            self.statusInput.setStyleSheet('color: green')
        except ValueError:
            isAccepted = False
            inputPresent = True
            self.statusInput.setText("Input Declined")
            self.statusInput.setStyleSheet('color: red')

        if (inputPresent == False) or ((hourInputNum == 0) and
                                       (minInputNum == 0) and
                                       (secInputNum == 0)):
            totalMSecRemain = 1
            isAccepted = False
            self.curTimer.setText("00:00:00:000 ms")
            self.statusInput.setText("Awaiting Input!")
            self.statusInput.setStyleSheet('color: orange')

        #Update timer variable if value accepted
        if (isAccepted == True):
            #Calculate timer values
            isInfoShown = False
            totalMSecRemain = (hourInputNum * 3600000) + (
                minInputNum * 60000) + (secInputNum * 1000)
            fullTimerS = self.formatTimer()

            self.curTimer.setText(fullTimerS)

    def initWindow(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

    def horLine(self):
        hLine = QFrame()
        hLine.setFrameShape(QFrame.HLine)
        hLine.setFrameShadow(QFrame.Sunken)
        return hLine

    def __init__(self, screenW, screenH):

        super().__init__()
        self.title = "Simple Timer"
        self.width = 640
        self.height = 480
        self.left = (screenW / 2) - (self.width / 2)
        self.top = (screenH / 2) - (self.height / 2)

        #Create button horizontal layout
        btnBox = QHBoxLayout()
        btnBox.addStretch(.5)
        #Create button instaces
        self.startBtn = QPushButton('Start', self)
        self.startBtn.clicked.connect(self.handleStartBtn)
        self.stopBtn = QPushButton('Stop', self)
        self.stopBtn.clicked.connect(self.handleStopBtn)
        self.resetBtn = QPushButton('Reset', self)
        self.resetBtn.clicked.connect(self.handleResetBtn)
        self.closeBtn = QPushButton('Close', self)
        self.closeBtn.clicked.connect(self.handleCloseBtn)
        #Add buttons to layout
        btnBox.addWidget(self.startBtn)
        btnBox.addWidget(self.stopBtn)
        btnBox.addWidget(self.resetBtn)
        btnBox.addWidget(self.closeBtn)
        btnBox.addStretch(.5)

        #Create Update Calls for All Clocks
        self.curTimeTimer = QTimer(self)
        self.curTimeTimer.timeout.connect(self.updateTime)
        self.curTimeTimer.start(87)

        #Create Three Info Clocks
        timeFont = QFont("Ariel", 40)
        #Set the initial current time at start
        curTimeBox = QHBoxLayout()
        curTimeBox.addStretch(.5)
        self.curTime = QLabel(self.formatTime(), self)
        self.curTime.setFont(timeFont)
        curTimeBox.addWidget(self.curTime)
        curTimeBox.addStretch(.5)
        #Set the initial timer time at start
        curTimerBox = QHBoxLayout()
        curTimerBox.addStretch(.5)
        self.curTimer = QLabel("00:00:00:000 ms", self)
        self.curTimer.setFont(timeFont)
        curTimerBox.addWidget(self.curTimer)
        curTimerBox.addStretch(.5)
        #Set the initial elapsed time at start
        self.stopwatchTime = QTime(0, 0, 0, 0)
        curElapseBox = QHBoxLayout()
        curElapseBox.addStretch(.5)
        self.curElapse = QLabel("00:00:00:000 ms", self)
        self.curElapse.setFont(timeFont)
        curElapseBox.addWidget(self.curElapse)
        curElapseBox.addStretch(.5)

        #Create timer input feilds
        inputBox = QHBoxLayout()
        self.introInput = QLabel('Set timer to -', self)
        self.hourInput = QLabel(' Hours:', self)
        self.hourInputFeild = QLineEdit()
        self.minInput = QLabel(' Minutes:', self)
        self.minInputFeild = QLineEdit()
        self.secInput = QLabel(' Seconds:', self)
        self.secInputFeild = QLineEdit()
        self.statusInput = QLabel('Awaiting Input!', self)
        self.statusInput.setStyleSheet('color: orange')
        inputBox.addStretch(.2)
        inputBox.addWidget(self.introInput)
        inputBox.addStretch(.3)
        inputBox.addWidget(self.hourInput)
        inputBox.addWidget(self.hourInputFeild)
        inputBox.addWidget(self.minInput)
        inputBox.addWidget(self.minInputFeild)
        inputBox.addWidget(self.secInput)
        inputBox.addWidget(self.secInputFeild)
        inputBox.addStretch(.3)
        inputBox.addWidget(self.statusInput)
        inputBox.addStretch(.2)

        #Connect input signals to the apropriate function
        self.hourInputFeild.textChanged.connect(self.updateTimer)
        self.minInputFeild.textChanged.connect(self.updateTimer)
        self.secInputFeild.textChanged.connect(self.updateTimer)

        #Create all static labels
        titleFont = QFont("Courier", 20)
        self.curTimeTitle = QLabel('Current Time:', self)
        self.curTimeTitle.setFont(titleFont)
        self.curTimerTitle = QLabel('Time Remaining:', self)
        self.curTimerTitle.setFont(titleFont)
        self.curElapseTitle = QLabel('Elapsed Time:', self)
        self.curElapseTitle.setFont(titleFont)

        #Create and populate root layout
        rootBox = QVBoxLayout()
        rootBox.addWidget(self.curTimeTitle)
        rootBox.addLayout(curTimeBox)
        rootBox.addStretch(.165)
        rootBox.addWidget(self.horLine())
        rootBox.addStretch(.165)
        rootBox.addWidget(self.curTimerTitle)
        rootBox.addLayout(curTimerBox)
        rootBox.addStretch(.165)
        rootBox.addWidget(self.horLine())
        rootBox.addStretch(.165)
        rootBox.addWidget(self.curElapseTitle)
        rootBox.addLayout(curElapseBox)
        rootBox.addStretch(.165)
        rootBox.addWidget(self.horLine())
        rootBox.addStretch(.165)
        rootBox.addLayout(inputBox)
        rootBox.addLayout(btnBox)

        self.setLayout(rootBox)

        self.initWindow()
Ejemplo n.º 15
0
class TimeFrame(BaseFrame):
    time_hacked = pyqtSignal()

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

        # Setup frame
        self.label.setText("Time:")
        zulu_label = QLabel("ZULU")
        zulu_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.time_edit = QTimeEdit()
        self.time_edit.setDisplayFormat("HH:mm:ss")
        self.hack_btn = QPushButton("Hack")
        self.hack_btn.setAutoDefault(False)
        if is_mission:
            self.hack_btn.setStyleSheet("background-color: red; color: white;")
        else:
            self.hack_btn.setStyleSheet(
                "background-color: gray; color: white;")
        self.sys_time_btn = QPushButton("Use System Time")
        self.sys_time_btn.setAutoDefault(False)

        if not is_mission:
            self.time_edit.setEnabled(False)
            self.hack_btn.setEnabled(False)
            self.sys_time_btn.setEnabled(False)

        self.layout.addWidget(self.label)
        self.layout.addWidget(self.time_edit)
        self.layout.addWidget(zulu_label)
        self.layout.addWidget(self.hack_btn)
        self.layout.addWidget(self.sys_time_btn)
        self.setLayout(self.layout)

        # Setup behavior
        self.time = QTime()
        self.hack_timer = QTimer()
        self.hack_timer.setTimerType(Qt.VeryCoarseTimer)
        self.hack_timer.setInterval(1000)
        self.hack_timer.timeout.connect(self.inc_time)
        self.hack_btn.clicked.connect(self.hack_time)
        self.sys_time_btn.clicked.connect(self.set_sys_time)

    @pyqtSlot()
    def hack_time(self, sys_time=None):
        if not self.hack_timer.isActive():
            self.time = self.time_edit.time() if not sys_time else sys_time
            self.hack_timer.start()
            self.time_edit.setTime(self.time)
            self.hack_btn.setStyleSheet(
                "background-color: green; color: white;")
            self.hack_btn.setText("Hacked!")
            self.time_edit.setEnabled(False)
            self.sys_time_btn.setEnabled(False)
        else:
            self.hack_btn.setStyleSheet("background-color: red; color: white;")
            self.hack_btn.setText("Hack")
            self.hack_timer.stop()
            self.time_edit.setEnabled(True)
            self.sys_time_btn.setEnabled(True)
        self.time_hacked.emit()

    @pyqtSlot()
    def set_sys_time(self):
        self.hack_time(QTime().currentTime())

    @pyqtSlot()
    def inc_time(self):
        self.time = self.time.addSecs(1)
        self.time_edit.setTime(self.time)
Ejemplo n.º 16
0
class ArithmeticWidget(QWidget):
    stop_signal = pyqtSignal()

    def __init__(self, operand_range: tuple, operators: tuple, parent=None):
        super(ArithmeticWidget, self).__init__(parent)

        self.operator_dict = {
            '+': self.add,
            '-': self.sub,
            '*': self.mul,
            '//': self.floordiv
        }

        self.operand_range = operand_range
        self.operators = operators
        self.operand_left = None
        self.operand_right = None
        self.correct_answer = None
        self.counter = 0

        main_box = QVBoxLayout()

        # backend timer
        self.time = QTime(0, 0, 0)
        self.timer = QTimer()
        self.timer.start(1000)
        self.timer.timeout.connect(self.change_time)

        # counter examples and timer
        self.counter_label = QLabel(str(self.counter))
        self.counter_label.setAlignment(Qt.AlignLeft)
        self.time_label = QLabel('0:00:00')
        self.time_label.setAlignment(Qt.AlignRight)
        h_box = QHBoxLayout()
        h_box.setContentsMargins(50, 20, 50, 0)
        h_box.addWidget(self.counter_label)
        h_box.addWidget(self.time_label)
        main_box.addLayout(h_box)

        # labels of nums and sign
        self.num_1_label = QLabel()
        self.num_1_label.setAlignment(Qt.AlignRight)
        self.num_2_label = QLabel()
        self.num_2_label.setAlignment(Qt.AlignLeft)
        self.sign_label = QLabel()
        self.sign_label.setFixedWidth(20)
        self.sign_label.setAlignment(Qt.AlignHCenter)
        h_box = QHBoxLayout()
        h_box.setContentsMargins(80, 0, 80, 0)
        h_box.addWidget(self.num_1_label)
        h_box.addWidget(self.sign_label)
        h_box.addWidget(self.num_2_label)
        main_box.addLayout(h_box)

        # answer field
        self.answer_field = QLineEdit()
        self.answer_field.returnPressed.connect(self.check_answer)
        self.answer_field.setAlignment(Qt.AlignCenter)
        self.answer_field.setValidator(QIntValidator())
        h_box = QHBoxLayout()
        h_box.setContentsMargins(80, 0, 80, 0)
        h_box.addWidget(self.answer_field)
        main_box.addLayout(h_box)

        # buttons
        self.confirm_btn = MyButton(btn_text='Enter',
                                    bg_color='rgb(138, 226, 52)',
                                    text_color='black',
                                    delay=False)
        self.confirm_btn.clicked.connect(self.check_answer)
        h_box = QHBoxLayout()
        h_box.addWidget(self.confirm_btn)
        main_box.addLayout(h_box)

        self.skip_btn = MyButton(btn_text='Skip',
                                 bg_color='rgb(252, 233, 79)',
                                 text_color='black',
                                 delay=False)
        self.skip_btn.clicked.connect(self.show_next_example)

        self.stop_btn = MyButton(btn_text='Stop',
                                 bg_color='red',
                                 text_color='white')
        self.stop_btn.clicked.connect(self.stop_session)
        h_box = QHBoxLayout()
        h_box.addWidget(self.skip_btn)
        h_box.addWidget(self.stop_btn)
        main_box.addLayout(h_box)

        self.setLayout(main_box)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.show_next_example()

    def change_time(self):
        self.time = self.time.addSecs(1)
        text = self.time.toString('h:mm:ss')
        self.time_label.setText(text)

    def show_next_example(self):
        operand_left = random.randint(*self.operand_range)
        operand_right = random.randint(*self.operand_range)
        operator = random.choice(self.operators)
        func = self.operator_dict[operator]
        func(operand_left, operand_right)
        self.num_1_label.setText(str(self.operand_left))
        self.num_2_label.setText(str(self.operand_right))
        self.sign_label.setText(operator)
        self.answer_field.clear()
        self.answer_field.setFocus(True)

    def check_answer(self):
        answer = self.answer_field.text()
        cur_pos = self.answer_field.cursorPosition()
        if len(answer) and int(answer) == self.correct_answer:
            self.show_next_example()
            self.counter += 1
            self.counter_label.setText(str(self.counter))
            return
        self.answer_field.setFocus(True)
        self.answer_field.setCursorPosition(cur_pos)

    def stop_session(self):
        """Show results of session and emmit stop signal"""
        self.timer.stop()
        result_window = QMessageBox(self)
        time = QTime(0, 0).secsTo(self.time)
        counter = self.counter
        average_time = '--undefined--'
        if counter and time:
            average_time = f'{round(time / counter, 1)}'

        result_window.setText(
            f'time: {self.time.toString()}\n\n'
            f'total examples: {counter}\n\n'
            f'Average time for arithmetic operation {average_time} second(s)')
        result_window.exec()
        self.stop_signal.emit()

    def add(self, a: int, b: int):
        self.operand_left = a
        self.operand_right = b
        self.correct_answer = self.operand_left + self.operand_right

    def mul(self, a: int, b: int):
        self.operand_left = a
        self.operand_right = b
        self.correct_answer = self.operand_left * self.operand_right

    def sub(self, a: int, b: int):
        self.operand_left = a + b
        self.operand_right = b
        self.correct_answer = self.operand_left - self.operand_right

    def floordiv(self, a: int, b: int):
        self.operand_left = a * b
        self.operand_right = b
        self.correct_answer = self.operand_left // self.operand_right
Ejemplo n.º 17
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        settings = QSettings()
        self.setup_trayicon()
        self.setup_ui()
        self.update_work_end_time()
        self.update_rest_end_time()
        self.setup_connections()
        self.timeFormat = "hh:mm:ss"
        self.time = QTime(0, 0, 0, 0)
        self.workTime = QTime(0, 0, 0, 0)
        self.restTime = QTime(0, 0, 0, 0)
        self.totalTime = QTime(0, 0, 0, 0)
        self.currentMode = Mode.work
        self.maxRepetitions = -1
        self.currentRepetitions = 0
        self.show()

    def leaveEvent(self, event):
        super(MainWindow, self).leaveEvent(event)
        self.tasksTableWidget.clearSelection()

    def closeEvent(self, event):
        super(MainWindow, self).closeEvent(event)
        settings = QSettings()
        settings.setValue("timer/work/hours", self.workHoursSpinBox.value())
        settings.setValue("timer/work/minutes",
                          self.workMinutesSpinBox.value())
        settings.setValue("timer/work/seconds",
                          self.workSecondsSpinBox.value())
        settings.setValue("timer/rest/hours", self.restHoursSpinBox.value())
        settings.setValue("timer/rest/minutes",
                          self.restMinutesSpinBox.value())
        settings.setValue("timer/rest/seconds",
                          self.restSecondsSpinBox.value())

        tasks = []
        for i in range(self.tasksTableWidget.rowCount()):
            item = self.tasksTableWidget.item(i, 0)
            if not item.font().strikeOut():
                tasks.append(item.text())
        settings.setValue("tasks/tasks", tasks)

    def start_timer(self):
        try:
            if not self.timer.isActive():
                self.create_timer()
        except:
            self.create_timer()

    def create_timer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_time)
        self.timer.timeout.connect(self.maybe_change_mode)
        self.timer.setInterval(1000)
        self.timer.setSingleShot(False)
        self.timer.start()

    def pause_timer(self):
        try:
            self.timer.stop()
            self.timer.disconnect()
        except:
            pass

    def reset_timer(self):
        try:
            self.pause_timer()
            self.time = QTime(0, 0, 0, 0)
            self.display_time()
        except:
            pass

    def maybe_start_timer(self):
        if self.currentRepetitions != self.maxRepetitions:
            self.start_timer()
            started = True
        else:
            self.currentRepetitions = 0
            started = False
        return started

    def update_work_end_time(self):
        self.workEndTime = QTime(self.workHoursSpinBox.value(),
                                 self.workMinutesSpinBox.value(),
                                 self.workSecondsSpinBox.value())

    def update_rest_end_time(self):
        self.restEndTime = QTime(self.restHoursSpinBox.value(),
                                 self.restMinutesSpinBox.value(),
                                 self.restSecondsSpinBox.value())

    def update_current_mode(self, mode: str):
        self.currentMode = Mode.work if mode == "work" else Mode.rest

    def update_time(self):
        self.time = self.time.addSecs(1)
        self.totalTime = self.totalTime.addSecs(1)
        if self.modeComboBox.currentText() == "work":
            self.workTime = self.workTime.addSecs(1)
        else:
            self.restTime = self.restTime.addSecs(1)
        self.display_time()

    def update_max_repetitions(self, value):
        if value == 0:
            self.currentRepetitions = 0
            self.maxRepetitions = -1
        else:
            self.maxRepetitions = 2 * value

    def maybe_change_mode(self):
        if self.currentMode is Mode.work and self.time >= self.workEndTime:
            self.reset_timer()
            self.modeComboBox.setCurrentIndex(1)
            self.increment_current_repetitions()
            started = self.maybe_start_timer()
            self.show_window_message(
                Status.workFinished if started else Status.repetitionsReached)
        elif self.currentMode is Mode.rest and self.time >= self.restEndTime:
            self.reset_timer()
            self.modeComboBox.setCurrentIndex(0)
            self.increment_current_repetitions()
            started = self.maybe_start_timer()
            self.show_window_message(
                Status.restFinished if started else Status.repetitionsReached)

    def increment_current_repetitions(self):
        if self.maxRepetitions > 0:
            self.currentRepetitions += 1

    def insert_task(self):
        task = self.taskTextEdit.toPlainText()
        self.insert_tasks(task)

    def insert_tasks(self, *tasks):
        for task in tasks:
            if task:
                rowCount = self.tasksTableWidget.rowCount()
                self.tasksTableWidget.setRowCount(rowCount + 1)
                self.tasksTableWidget.setItem(rowCount, 0,
                                              QTableWidgetItem(task))
                self.tasksTableWidget.resizeRowsToContents()
                self.taskTextEdit.clear()

    def delete_task(self):
        selectedIndexes = self.tasksTableWidget.selectedIndexes()
        if selectedIndexes:
            self.tasksTableWidget.removeRow(selectedIndexes[0].row())

    def mark_task_as_finished(self, row, col):
        item = self.tasksTableWidget.item(row, col)
        font = self.tasksTableWidget.item(row, col).font()
        font.setStrikeOut(False if item.font().strikeOut() else True)
        item.setFont(font)

    def display_time(self):
        self.timeDisplay.display(self.time.toString(self.timeFormat))
        self.statisticsRestTimeDisplay.display(
            self.restTime.toString(self.timeFormat))
        self.statisticsWorkTimeDisplay.display(
            self.workTime.toString(self.timeFormat))
        self.statisticsTotalTimeDisplay.display(
            self.totalTime.toString(self.timeFormat))

    def show_window_message(self, status):
        if status is Status.workFinished:
            self.trayIcon.showMessage("Break", choice(work_finished_phrases),
                                      QIcon("icons/tomato.png"))
        elif status is Status.restFinished:
            self.trayIcon.showMessage("Work", choice(rest_finished_phrases),
                                      QIcon("icons/tomato.png"))
        else:
            self.trayIcon.showMessage("Finished",
                                      choice(pomodoro_finished_phrases),
                                      QIcon("icons/tomato.png"))
            self.resetButton.click()

    def setup_connections(self):
        self.playButton.clicked.connect(self.start_timer)
        self.playButton.clicked.connect(
            lambda: self.playButton.setDisabled(True))
        self.playButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(False))
        self.playButton.clicked.connect(
            lambda: self.resetButton.setDisabled(False))

        self.pauseButton.clicked.connect(self.pause_timer)
        self.pauseButton.clicked.connect(
            lambda: self.playButton.setDisabled(False))
        self.pauseButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(True))
        self.pauseButton.clicked.connect(
            lambda: self.resetButton.setDisabled(False))

        self.resetButton.clicked.connect(self.reset_timer)
        self.resetButton.clicked.connect(
            lambda: self.playButton.setDisabled(False))
        self.resetButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(True))
        self.resetButton.clicked.connect(
            lambda: self.resetButton.setDisabled(True))

        self.workHoursSpinBox.valueChanged.connect(self.update_work_end_time)
        self.workMinutesSpinBox.valueChanged.connect(self.update_work_end_time)
        self.workSecondsSpinBox.valueChanged.connect(self.update_work_end_time)

        self.restHoursSpinBox.valueChanged.connect(self.update_rest_end_time)
        self.restMinutesSpinBox.valueChanged.connect(self.update_rest_end_time)
        self.restSecondsSpinBox.valueChanged.connect(self.update_rest_end_time)

        self.modeComboBox.currentTextChanged.connect(self.update_current_mode)
        self.repetitionsSpinBox.valueChanged.connect(
            self.update_max_repetitions)

        self.acceptTaskButton.pressed.connect(self.insert_task)
        self.deleteTaskButton.pressed.connect(self.delete_task)

        self.tasksTableWidget.cellDoubleClicked.connect(
            self.mark_task_as_finished)

    def setup_ui(self):
        settings = QSettings()

        self.size_policy = sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding)
        #TABWIDGET
        self.tabWidget = QTabWidget()

        self.pomodoroWidget = QWidget(self)

        self.pomodoroWidgetLayout = QVBoxLayout(self.pomodoroWidget)
        self.pomodoroWidget.setLayout(self.pomodoroWidgetLayout)
        # work
        self.workGroupBox = QGroupBox("Work")
        self.workGroupBoxLayout = QHBoxLayout(self.workGroupBox)
        self.workGroupBox.setLayout(self.workGroupBoxLayout)
        self.workHoursSpinBox = QSpinBox(minimum=0,
                                         maximum=24,
                                         value=settings.value(
                                             "timer/work/hours", 0),
                                         suffix="h",
                                         sizePolicy=self.size_policy)
        self.workMinutesSpinBox = QSpinBox(minimum=0,
                                           maximum=60,
                                           value=settings.value(
                                               "timer/work/minutes", 25),
                                           suffix="m",
                                           sizePolicy=self.size_policy)
        self.workSecondsSpinBox = QSpinBox(minimum=0,
                                           maximum=60,
                                           value=settings.value(
                                               "timer/work/seconds", 0),
                                           suffix="s",
                                           sizePolicy=self.size_policy)
        self.workGroupBoxLayout.addWidget(self.workHoursSpinBox)
        self.workGroupBoxLayout.addWidget(self.workMinutesSpinBox)
        self.workGroupBoxLayout.addWidget(self.workSecondsSpinBox)
        # rest
        self.restGroupBox = QGroupBox("Rest")
        self.restGroupBoxLayout = QHBoxLayout(self.restGroupBox)
        self.restGroupBox.setLayout(self.restGroupBoxLayout)
        self.restHoursSpinBox = QSpinBox(minimum=0,
                                         maximum=24,
                                         value=settings.value(
                                             "timer/rest/hours", 0),
                                         suffix="h",
                                         sizePolicy=self.size_policy)
        self.restMinutesSpinBox = QSpinBox(minimum=0,
                                           maximum=60,
                                           value=settings.value(
                                               "timer/rest/minutes", 5),
                                           suffix="m",
                                           sizePolicy=self.size_policy)
        self.restSecondsSpinBox = QSpinBox(minimum=0,
                                           maximum=60,
                                           value=settings.value(
                                               "timer/rest/seconds", 0),
                                           suffix="s",
                                           sizePolicy=self.size_policy)
        self.restGroupBoxLayout.addWidget(self.restHoursSpinBox)
        self.restGroupBoxLayout.addWidget(self.restMinutesSpinBox)
        self.restGroupBoxLayout.addWidget(self.restSecondsSpinBox)
        #OTHER
        self.otherGroupBox = QGroupBox("Other")
        self.otherGroupBoxLayout = QHBoxLayout(self.otherGroupBox)
        self.otherGroupBox.setLayout(self.otherGroupBoxLayout)
        self.repetitionsLabel = QLabel("Repetitions",
                                       sizePolicy=self.size_policy)
        self.repetitionsSpinBox = QSpinBox(minimum=0,
                                           maximum=10000,
                                           value=0,
                                           sizePolicy=self.size_policy,
                                           specialValueText="∞")
        self.modeLabel = QLabel("Mode", sizePolicy=self.size_policy)
        self.modeComboBox = QComboBox()
        self.modeComboBox.addItems(["work", "rest"])
        self.otherGroupBoxLayout.addWidget(self.repetitionsLabel)
        self.otherGroupBoxLayout.addWidget(self.repetitionsSpinBox)
        self.otherGroupBoxLayout.addWidget(self.modeLabel)
        self.otherGroupBoxLayout.addWidget(self.modeComboBox)
        #LCDDISPLAY
        self.lcdDisplayGroupBox = QGroupBox("Time")
        self.lcdDisplayGroupBoxLayout = QHBoxLayout(self.lcdDisplayGroupBox)
        self.lcdDisplayGroupBox.setLayout(self.lcdDisplayGroupBoxLayout)
        self.timeDisplay = QLCDNumber(8, sizePolicy=self.size_policy)
        self.timeDisplay.setFixedHeight(100)
        self.timeDisplay.display("00:00:00")
        self.lcdDisplayGroupBoxLayout.addWidget(self.timeDisplay)

        #BUTTONS
        self.buttonWidget = QWidget()
        self.buttonWidgetLayout = QHBoxLayout(self.buttonWidget)
        self.buttonWidget.setLayout(self.buttonWidgetLayout)
        self.playButton = self.make_button("start", disabled=False)
        self.resetButton = self.make_button("reset")
        self.pauseButton = self.make_button("pause")
        self.buttonWidgetLayout.addWidget(self.pauseButton)
        self.buttonWidgetLayout.addWidget(self.playButton)
        self.buttonWidgetLayout.addWidget(self.resetButton)

        #CENTRALWIDGET
        self.pomodoroWidgetLayout.addWidget(self.workGroupBox)
        self.pomodoroWidgetLayout.addWidget(self.restGroupBox)
        self.pomodoroWidgetLayout.addWidget(self.otherGroupBox)
        self.pomodoroWidgetLayout.addWidget(self.lcdDisplayGroupBox)
        self.pomodoroWidgetLayout.addWidget(self.buttonWidget)
        #CREATE TASKS TAB
        self.tasksWidget = QWidget(self.tabWidget)
        self.tasksWidgetLayout = QVBoxLayout(self.tasksWidget)
        self.tasksWidget.setLayout(self.tasksWidgetLayout)
        self.inputWidget = QWidget()
        self.inputWidget.setFixedHeight(50)
        self.inputWidgetLayout = QHBoxLayout(self.inputWidget)
        self.inputWidgetLayout.setContentsMargins(0, 0, 0, 0)
        self.inputWidget.setLayout(self.inputWidgetLayout)
        self.taskTextEdit = QTextEdit(
            placeholderText="Describe your task briefly.",
            undoRedoEnabled=True)
        self.inputButtonContainer = QWidget()
        self.inputButtonContainerLayout = QVBoxLayout(
            self.inputButtonContainer)
        self.inputButtonContainerLayout.setContentsMargins(0, 0, 0, 0)
        self.inputButtonContainer.setLayout(self.inputButtonContainerLayout)
        self.acceptTaskButton = QToolButton(icon=QIcon("icons/check.png"))
        self.deleteTaskButton = QToolButton(icon=QIcon("icons/trash.png"))
        self.inputButtonContainerLayout.addWidget(self.acceptTaskButton)
        self.inputButtonContainerLayout.addWidget(self.deleteTaskButton)

        self.inputWidgetLayout.addWidget(self.taskTextEdit)
        self.inputWidgetLayout.addWidget(self.inputButtonContainer)
        self.tasksTableWidget = QTableWidget(0, 1)
        self.tasksTableWidget.setHorizontalHeaderLabels(["Tasks"])
        self.tasksTableWidget.horizontalHeader().setStretchLastSection(True)
        self.tasksTableWidget.verticalHeader().setVisible(False)
        self.tasksTableWidget.setWordWrap(True)
        self.tasksTableWidget.setTextElideMode(Qt.ElideNone)
        self.tasksTableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tasksTableWidget.setSelectionMode(
            QAbstractItemView.SingleSelection)
        self.insert_tasks(*settings.value("tasks/tasks", []))

        self.tasksWidgetLayout.addWidget(self.inputWidget)
        self.tasksWidgetLayout.addWidget(self.tasksTableWidget)
        #CREATE STATISTICS TAB
        self.statisticsWidget = QWidget()
        self.statisticsWidgetLayout = QVBoxLayout(self.statisticsWidget)
        self.statisticsWidget.setLayout(self.statisticsWidgetLayout)

        self.statisticsWorkTimeGroupBox = QGroupBox("Work Time")
        self.statisticsWorkTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsWorkTimeGroupBox.setLayout(
            self.statisticsWorkTimeGroupBoxLayout)
        self.statisticsWorkTimeDisplay = QLCDNumber(8)
        self.statisticsWorkTimeDisplay.display("00:00:00")
        self.statisticsWorkTimeGroupBoxLayout.addWidget(
            self.statisticsWorkTimeDisplay)

        self.statisticsRestTimeGroupBox = QGroupBox("Rest Time")
        self.statisticsRestTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsRestTimeGroupBox.setLayout(
            self.statisticsRestTimeGroupBoxLayout)
        self.statisticsRestTimeDisplay = QLCDNumber(8)
        self.statisticsRestTimeDisplay.display("00:00:00")
        self.statisticsRestTimeGroupBoxLayout.addWidget(
            self.statisticsRestTimeDisplay)

        self.statisticsTotalTimeGroupBox = QGroupBox("Total Time")
        self.statisticsTotalTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsTotalTimeGroupBox.setLayout(
            self.statisticsTotalTimeGroupBoxLayout)
        self.statisticsTotalTimeDisplay = QLCDNumber(8)
        self.statisticsTotalTimeDisplay.display("00:00:00")
        self.statisticsTotalTimeGroupBoxLayout.addWidget(
            self.statisticsTotalTimeDisplay)

        self.statisticsWidgetLayout.addWidget(self.statisticsTotalTimeGroupBox)
        self.statisticsWidgetLayout.addWidget(self.statisticsWorkTimeGroupBox)
        self.statisticsWidgetLayout.addWidget(self.statisticsRestTimeGroupBox)

        #ADD TABS
        self.timerTab = self.tabWidget.addTab(self.pomodoroWidget,
                                              QIcon("icons/timer.png"),
                                              "Timer")
        self.tasksTab = self.tabWidget.addTab(self.tasksWidget,
                                              QIcon("icons/tasks.png"),
                                              "Tasks")
        self.statisticsTab = self.tabWidget.addTab(
            self.statisticsWidget, QIcon("icons/statistics.png"), "Statistics")

        self.setCentralWidget(self.tabWidget)

    def make_button(self, text, iconPath=None, disabled=True):
        button = QPushButton(text, sizePolicy=self.size_policy)
        if iconPath:
            button.setIcon(QIcon(iconPath))
        button.setDisabled(disabled)
        return button

    def setup_trayicon(self):
        self.trayIcon = QSystemTrayIcon(QIcon("icons/tomato.png"))
        self.trayIcon.setContextMenu(QMenu())
        self.quitAction = self.trayIcon.contextMenu().addAction(
            QIcon("icons/exit.png"), "Quit", self.exit)
        self.quitAction.triggered.connect(self.exit)
        self.trayIcon.activated.connect(self.onActivate)
        self.trayIcon.show()

    def exit(self):
        self.close()
        app = QApplication.instance()
        if app:
            app.quit()

    def onActivate(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            self.show()
Ejemplo n.º 18
0
class ButtonPane(QWidget):

    manage_ranking = pyqtSignal(str)

    def __init__(self, width, height, bombs, diff, matrix, m_sum, path_matrix,
                 saving, restoring, on_configure):
        super().__init__()

        self.diff = diff  # Difficoltà
        self.saving = saving
        self.restoring = restoring

        self.setStyleSheet("font: 16px Andale Mono")

        QVLayout = QVBoxLayout(self)

        area_info = QWidget()
        area_info.setStyleSheet(
            "background-color: gray; border: 1px solid black")
        QHLayout = QHBoxLayout(area_info)

        self.label_1 = QLabel(str(bombs))
        self.label_1.setFixedSize(QSize(80, 30))
        self.label_1.setAlignment(Qt.AlignCenter)
        self.label_1.setStyleSheet(
            "background-color: black; color: red; border-radius: 5px; border: 1px solid black"
        )

        label_2 = QPushButton()
        label_2.setFixedSize(QSize(60, 60))
        label_2.setIcon(QIcon(sys.path[0] + '/Images/sun-smile.png'))
        label_2.setIconSize(QSize(60, 60))
        label_2.clicked.connect(on_configure)

        self.label_3 = QLabel('Tempo')
        self.label_3.setFixedSize(QSize(80, 30))
        self.label_3.setAlignment(Qt.AlignCenter)
        self.label_3.setStyleSheet(
            "background-color: black; color: red; border-radius: 5px; border: 1px solid black"
        )

        self.curr_time = QTime(00, 00, 00)
        self.timer = QTimer()
        self.timer.timeout.connect(self.timerEvent)

        area_game = QWidget()
        area_game.setStyleSheet("border: 1px solid black")
        buttons_layout = QGridLayout(area_game)
        buttons_layout.setSpacing(0)
        self.btn_matrix = [[0 for _ in range(height)] for _ in range(width)]
        # Generazione della griglia di gioco
        for i in range(width):
            for j in range(height):
                btn = MinesweeperButton(row=i,
                                        col=j,
                                        bombs=bombs,
                                        diff=diff,
                                        matrix=matrix,
                                        m_sum=m_sum,
                                        path_matrix=path_matrix,
                                        bomb_label=self.label_1,
                                        img=label_2)
                buttons_layout.addWidget(btn, i, j)
                btn.update_button.connect(self.update_game)
                btn.defeat_signal.connect(self.manage_defeat)
                btn.win_signal.connect(self.manage_win)
                self.btn_matrix[i][j] = btn

        QHLayout.addWidget(self.label_1)
        QHLayout.addWidget(label_2)
        QHLayout.addWidget(self.label_3)

        self.name_zone = QWidget()
        horizontal_layout = QHBoxLayout(self.name_zone)
        label_name = QLabel('Nome:')
        self.name = QLineEdit()
        self.submit_btn = QPushButton('Go!')

        horizontal_layout.addWidget(label_name)
        horizontal_layout.addWidget(self.name)
        horizontal_layout.addWidget(self.submit_btn)
        self.name_zone.hide()

        QVLayout.addWidget(area_info)
        QVLayout.addWidget(area_game)

        QVLayout.addWidget(self.name_zone)

    def update_game(
        self, game_over
    ):  # Aggiornamento dello stato delle caselle componenti la griglia
        for index_row, row in enumerate(self.btn_matrix):
            for index_col, col in enumerate(row):
                self.btn_matrix[index_row][index_col].update(game_over)

    def timerEvent(self):  # Aggiormamento del timer
        self.curr_time = self.curr_time.addSecs(1)
        self.label_3.setText(self.curr_time.toString("hh:mm:ss"))

    def manage_win(self):  # Gestione del segnale indicante la vittoria
        self.timer.stop()
        self.saving.setDisabled(True)
        self.restoring.setDisabled(True)
        self.manage_ranking.emit(self.curr_time.toString("hh:mm:ss"))
        if (os.path.isfile(sys.path[0] + '/Temp/objs.pkl')):
            os.remove(sys.path[0] + '/Temp/objs.pkl')

    def manage_defeat(self):  # Gestione del segnale indicante la sconfitta
        self.timer.stop()
        self.saving.setDisabled(True)
        self.restoring.setDisabled(True)
        if (os.path.isfile(sys.path[0] + '/Temp/objs.pkl')):
            os.remove(sys.path[0] + '/Temp/objs.pkl')
Ejemplo n.º 19
0
class Timer(QWidget):
    def __init__(self):
        super().__init__()
        
        self.widget = QWidget(self)
        self.widget.setObjectName("main")
        self.widget.setStyleSheet("""
                    QWidget#main{
                        border:1px solid #148CD2;
                        border-radius:10px;
                        margin:0
                    }
        """)

        layout = QVBoxLayout()
        
        fnt = QFont('Open Sans', 60, QFont.Bold)
        self.lbl = QLabel()
        self.lbl.setAlignment(Qt.AlignCenter)
 
        self.currentTime = QTime(0,0,0)
        self.lbl.setFont(fnt)
        
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000) # update every second

        self.btnStart = QPushButton('Start', self)
        self.btnStart.setStyleSheet(
            """
            QPushButton
            {
                margin-right:20px;
            }
            QPushButton:hover
            {
                background-color:#148CD2;
                border:none;
            }
            """)
        line = QFormLayout()
        line.setContentsMargins(0,20,0,0)
        self.msg = QLabel("Elapsed Time")
        fnt2 = QFont('Open Sans', 28)
        self.msg.setFont(fnt2)

        self.btnStart.setFixedSize(100,50)
        self.btnStart.clicked.connect(self.startProgress) 

        self.showTime()
        self.timerStatus = False

        line.addRow(self.btnStart,self.msg)

        layout.addWidget(self.lbl)
        layout.addItem(line) 

        self.widget.setLayout(layout)
        self.widget.setFixedSize(400,200)


        Classifiertimer = QTimer(self)
        Classifiertimer.timeout.connect(self.ClassifierRunner)
        Classifiertimer.start(60*1000) # update every minute


    def showTime(self):
        if self.btnStart.text() == 'Stop':
            self.currentTime = self.currentTime.addSecs(1)
            displayTxt = self.currentTime.toString('hh:mm:ss')
            self.lbl.setText(displayTxt)
        else:
            displayTxt = self.currentTime.toString('hh:mm:ss')
            self.lbl.setText(displayTxt)

    def startProgress(self):
        if self.btnStart.text() == 'Start':
            self.btnStart.setText('Stop')
            self.timerStatus = True
        else:
            self.btnStart.setText('Start')
            self.currentTime = QTime(0,0,0)
            self.timerStatus = False
            
    def ClassifierRunner(self):
        Classifier(self.timerStatus)
Ejemplo n.º 20
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.backlogMgr = BacklogMgr()

        self.initUI()

    def initUI(self):

        self.setWindowTitle("TurboClock")

        self.resize(400, 300)
        self.setWindowIcon(QIcon('Images//clock.png'))

        self.icon = QSystemTrayIcon(self)
        self.icon.setIcon(QIcon('Images//clock.png'))
        self.icon.setVisible(True)

        self.lcdNumber = QLCDNumber()
        self.lcdNumber.setNumDigits(8)

        self.btnStartPause = QPushButton('', self)
        self.btnStartPause.setIcon(QIcon('Images//play_icon.png'))
        self.btnStartPause.clicked.connect(self.manageStartPauseClickedEvent)

        self.btnDutyDetails = QPushButton('Duty details...')
        self.btnDutyDetails.clicked.connect(self.manageDutyDetailsClickedEvent)

        self.btnAddTfsTask = QPushButton('', self)
        self.btnAddTfsTask.setIcon(QIcon('Images//plus_icon.png'))
        self.btnAddTfsTask.clicked.connect(self.manageEditTasksOptions)

        self.progressBar = QProgressBar()
        self.progressBar.setValue(0)

        self.dutyTimeCompLbl = QLabel()

        self.currTaskItemRow = 0
        self.taskTFSCb = QComboBox(self)
        self.initTFSTaskCombobox()

        mainLayout = QVBoxLayout(self)

        layoutTimer = QVBoxLayout()
        layoutTimer.addWidget(self.lcdNumber)

        fieldsInputLayout = QHBoxLayout()

        layoutInputCodes = QVBoxLayout()
        layoutInputCodes.addWidget(self.taskTFSCb)

        layoutAddBtn = QVBoxLayout()
        layoutAddBtn.addWidget(self.btnAddTfsTask)

        fieldsInputLayout.addLayout(layoutInputCodes)
        fieldsInputLayout.addLayout(layoutAddBtn)

        layoutDutyStat = QHBoxLayout()
        layoutDutyStat.addWidget(self.dutyTimeCompLbl)

        layoutProgressBar = QHBoxLayout()
        layoutProgressBar.addWidget(self.progressBar)

        mainLayout.addLayout(layoutTimer)
        mainLayout.addLayout(fieldsInputLayout)
        mainLayout.addWidget(self.btnStartPause)
        mainLayout.addWidget(self.btnDutyDetails)
        mainLayout.addWidget(self.progressBar)
        mainLayout.addLayout(layoutDutyStat)

        self.timer = QTimer(self)
        self.deltaTimer = 0
        self.currTimeLCD = QTime(0, 0, 0)
        self.currTimeDuty = QTime(0, 0, 0)

        self.timer.timeout.connect(self.incrementTimer)

        self.updateTimeLCD()
        self.updateDutyTimeDisp()
        self.updateProgressBarDisplay()

        self.startTime = 0
        self.stopTime = 0

        self.editTasksGUI = EditTasksOptionsGUI(self, self.backlogMgr)

    def initTFSTaskCombobox(self):

        self.updateTaskCombobox()

        self.taskTFSCb.currentIndexChanged.connect(self.manageCbTFSIndexChange)

    def updateProgressBarDisplay(self):

        estimatedTime = self.backlogMgr.backlogData.currTask.estimatedTime

        if estimatedTime == 0:
            return

        ratioFromTimer = (self.deltaTimer / estimatedTime) * 100

        totalCompletionRatio = self.backlogMgr.getCompletionRatio(
            self.backlogMgr.backlogData.currTaskIndex) + ratioFromTimer

        if totalCompletionRatio <= 100:
            self.progressBar.setValue(totalCompletionRatio)
        else:
            self.progressBar.setValue(100)

    def updateTaskCombobox(self):

        currTaskIndex = self.currTaskItemRow

        self.taskTFSCb.clear()

        taskList = self.backlogMgr.getTasksFromGUI()

        for currTask in taskList:

            taskDesc = currTask.title + ' (' + currTask.prjCode + ')'

            self.taskTFSCb.addItem(taskDesc)

        self.taskTFSCb.setCurrentIndex(currTaskIndex)

        self.backlogMgr.setCurrentTaskFromGUI(currTaskIndex)

    def manageCbTFSIndexChange(self):

        self.currTaskItemRow = self.taskTFSCb.currentIndex()

        if self.currTaskItemRow >= 0:
            self.backlogMgr.manageTaskChangeFromGUI(self.currTaskItemRow)

        self.updateTimeLCD()

        self.deltaTimer = 0
        self.updateProgressBarDisplay()

    def updateTimeLCD(self):

        currTaskTime_split = self.backlogMgr.getCompletedTimeCurrTaskFromGUI(
        ).split(':')

        h = int(currTaskTime_split[0])
        m = int(currTaskTime_split[1])
        s = int(currTaskTime_split[2])

        self.currTimeLCD = QTime(h, m, s)
        self.lcdNumber.display(self.currTimeLCD.toString('hh:mm:ss'))

    def updateDutyTimeDisp(self):

        currTaskTime_split = self.backlogMgr.getCurrDutyTimeCompletedFromGUI(
        ).split(':')

        h = int(currTaskTime_split[0])
        m = int(currTaskTime_split[1])
        s = int(currTaskTime_split[2])

        self.currTimeDuty = QTime(h, m, s)
        self.dutyTimeCompLbl.setText('Daily time completed: ' +
                                     self.currTimeDuty.toString('hh:mm:ss'))

    def incrementTimer(self):

        self.currTimeLCD = self.currTimeLCD.addSecs(1)
        self.lcdNumber.display(self.currTimeLCD.toString('hh:mm:ss'))

        self.currTimeDuty = self.currTimeDuty.addSecs(1)
        self.dutyTimeCompLbl.setText('Daily time completed: ' +
                                     self.currTimeDuty.toString('hh:mm:ss'))

        self.deltaTimer += 1

        self.updateProgressBarDisplay()

    def manageStartPauseClickedEvent(self):

        self.backlogMgr.manageClickButtonFromGUI()
        self.deltaTimer = 0

        if self.timer.isActive():
            self.timer.stop()
            self.btnStartPause.setIcon(QIcon('Images//play_icon.png'))
        else:
            self.timer.start(1000)
            self.btnStartPause.setIcon(QIcon('Images//pause_icon.png'))

    def manageDutyDetailsClickedEvent(self):

        ex = DutyDetailsWindow(self, self.backlogMgr.backlogData)
        ex.show()

    def manageEditTasksOptions(self):

        self.editTasksGUI.exec_()

        self.updateTaskCombobox()

    def closeEvent(self, event):

        event.accept()
Ejemplo n.º 21
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupTrayicon()
        self.setupVariables()
        self.setupUi()
        self.setupConnections()
        self.show()

    def setupVariables(self):
        settings = QSettings()
        self.workEndTime = QTime(
            int(settings.value(workHoursKey, 0)),
            int(settings.value(workMinutesKey, 25)),
            int(settings.value(workSecondsKey, 0)),
        )
        self.restEndTime = QTime(
            int(settings.value(restHoursKey, 0)),
            int(settings.value(restMinutesKey, 5)),
            int(settings.value(restSecondsKey, 0)),
        )
        self.timeFormat = "hh:mm:ss"
        self.time = QTime(0, 0, 0, 0)
        self.workTime = QTime(0, 0, 0, 0)
        self.restTime = QTime(0, 0, 0, 0)
        self.totalTime = QTime(0, 0, 0, 0)
        self.currentMode = Mode.work
        self.maxRepetitions = -1
        self.currentRepetitions = 0

    def setupConnections(self):
        """ Create button connections """
        self.startButton.clicked.connect(self.startTimer)
        self.startButton.clicked.connect(
            lambda: self.startButton.setDisabled(True))
        self.startButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(False))
        self.startButton.clicked.connect(
            lambda: self.resetButton.setDisabled(False))
        self.pauseButton.clicked.connect(self.pauseTimer)
        self.pauseButton.clicked.connect(
            lambda: self.startButton.setDisabled(False))
        self.pauseButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(True))
        self.pauseButton.clicked.connect(
            lambda: self.resetButton.setDisabled(False))
        self.pauseButton.clicked.connect(
            lambda: self.startButton.setText("continue"))
        self.resetButton.clicked.connect(self.resetTimer)
        self.resetButton.clicked.connect(
            lambda: self.startButton.setDisabled(False))
        self.resetButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(True))
        self.resetButton.clicked.connect(
            lambda: self.resetButton.setDisabled(True))
        self.resetButton.clicked.connect(
            lambda: self.startButton.setText("start"))
        self.acceptTaskButton.pressed.connect(self.insertTask)
        self.deleteTaskButton.pressed.connect(self.deleteTask)
        """ Create spinbox  connections """
        self.workHoursSpinBox.valueChanged.connect(self.updateWorkEndTime)
        self.workMinutesSpinBox.valueChanged.connect(self.updateWorkEndTime)
        self.workSecondsSpinBox.valueChanged.connect(self.updateWorkEndTime)
        self.restHoursSpinBox.valueChanged.connect(self.updateRestEndTime)
        self.restMinutesSpinBox.valueChanged.connect(self.updateRestEndTime)
        self.restSecondsSpinBox.valueChanged.connect(self.updateRestEndTime)
        self.repetitionsSpinBox.valueChanged.connect(self.updateMaxRepetitions)
        """ Create combobox connections """
        self.modeComboBox.currentTextChanged.connect(self.updateCurrentMode)
        """ Create tablewidget connections """
        self.tasksTableWidget.cellDoubleClicked.connect(
            self.markTaskAsFinished)

    def setupUi(self):
        self.size_policy = sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding)
        """ Create tabwidget """
        self.tabWidget = QTabWidget()
        """ Create tab widgets """
        timerWidget = self.setupTimerTab()
        tasksWidget = self.setupTasksTab()
        statisticsWidget = self.setupStatisticsTab()
        """ add tab widgets to tabwidget"""
        self.timerTab = self.tabWidget.addTab(timerWidget, makeIcon("timer"),
                                              "Timer")
        self.tasksTab = self.tabWidget.addTab(tasksWidget, makeIcon("tasks"),
                                              "Tasks")
        self.statisticsTab = self.tabWidget.addTab(statisticsWidget,
                                                   makeIcon("statistics"),
                                                   "Statistics")
        """ Set mainwindows central widget """
        self.setCentralWidget(self.tabWidget)

    def setupTimerTab(self):
        settings = QSettings()
        self.timerContainer = QWidget(self)
        self.timerContainerLayout = QVBoxLayout(self.timerContainer)
        self.timerContainer.setLayout(self.timerContainerLayout)
        """ Create work groupbox"""
        self.workGroupBox = QGroupBox("Work")
        self.workGroupBoxLayout = QHBoxLayout(self.workGroupBox)
        self.workGroupBox.setLayout(self.workGroupBoxLayout)
        self.workHoursSpinBox = QSpinBox(
            minimum=0,
            maximum=24,
            value=int(settings.value(workHoursKey, 0)),
            suffix="h",
            sizePolicy=self.size_policy,
        )
        self.workMinutesSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(workMinutesKey, 25)),
            suffix="m",
            sizePolicy=self.size_policy,
        )
        self.workSecondsSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(workSecondsKey, 0)),
            suffix="s",
            sizePolicy=self.size_policy,
        )
        """ Create rest groupbox"""
        self.restGroupBox = QGroupBox("Rest")
        self.restGroupBoxLayout = QHBoxLayout(self.restGroupBox)
        self.restGroupBox.setLayout(self.restGroupBoxLayout)
        self.restHoursSpinBox = QSpinBox(
            minimum=0,
            maximum=24,
            value=int(settings.value(restHoursKey, 0)),
            suffix="h",
            sizePolicy=self.size_policy,
        )
        self.restMinutesSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(restMinutesKey, 5)),
            suffix="m",
            sizePolicy=self.size_policy,
        )
        self.restSecondsSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(restSecondsKey, 0)),
            suffix="s",
            sizePolicy=self.size_policy,
        )
        self.restGroupBoxLayout.addWidget(self.restHoursSpinBox)
        self.restGroupBoxLayout.addWidget(self.restMinutesSpinBox)
        self.restGroupBoxLayout.addWidget(self.restSecondsSpinBox)
        """ Create other groupbox"""
        self.otherGroupBox = QGroupBox("Other")
        self.otherGroupBoxLayout = QHBoxLayout(self.otherGroupBox)
        self.otherGroupBox.setLayout(self.otherGroupBoxLayout)
        self.repetitionsLabel = QLabel("Repetitions")
        self.repetitionsSpinBox = QSpinBox(
            minimum=0,
            maximum=10000,
            value=0,
            sizePolicy=self.size_policy,
            specialValueText="∞",
        )
        self.modeLabel = QLabel("Mode")
        self.modeComboBox = QComboBox(sizePolicy=self.size_policy)
        self.modeComboBox.addItems(["work", "rest"])
        self.otherGroupBoxLayout.addWidget(self.repetitionsLabel)
        self.otherGroupBoxLayout.addWidget(self.repetitionsSpinBox)
        self.otherGroupBoxLayout.addWidget(self.modeLabel)
        self.otherGroupBoxLayout.addWidget(self.modeComboBox)
        """ Create timer groupbox"""
        self.lcdDisplayGroupBox = QGroupBox("Time")
        self.lcdDisplayGroupBoxLayout = QHBoxLayout(self.lcdDisplayGroupBox)
        self.lcdDisplayGroupBox.setLayout(self.lcdDisplayGroupBoxLayout)
        self.timeDisplay = QLCDNumber(8, sizePolicy=self.size_policy)
        self.timeDisplay.setFixedHeight(100)
        self.timeDisplay.display("00:00:00")
        self.lcdDisplayGroupBoxLayout.addWidget(self.timeDisplay)
        """ Create pause, start and reset buttons"""
        self.buttonContainer = QWidget()
        self.buttonContainerLayout = QHBoxLayout(self.buttonContainer)
        self.buttonContainer.setLayout(self.buttonContainerLayout)
        self.startButton = self.makeButton("start", disabled=False)
        self.resetButton = self.makeButton("reset")
        self.pauseButton = self.makeButton("pause")
        """ Add widgets to container """
        self.workGroupBoxLayout.addWidget(self.workHoursSpinBox)
        self.workGroupBoxLayout.addWidget(self.workMinutesSpinBox)
        self.workGroupBoxLayout.addWidget(self.workSecondsSpinBox)
        self.timerContainerLayout.addWidget(self.workGroupBox)
        self.timerContainerLayout.addWidget(self.restGroupBox)
        self.timerContainerLayout.addWidget(self.otherGroupBox)
        self.timerContainerLayout.addWidget(self.lcdDisplayGroupBox)
        self.buttonContainerLayout.addWidget(self.pauseButton)
        self.buttonContainerLayout.addWidget(self.startButton)
        self.buttonContainerLayout.addWidget(self.resetButton)
        self.timerContainerLayout.addWidget(self.buttonContainer)
        return self.timerContainer

    def setupTasksTab(self):
        settings = QSettings()
        """ Create vertical tasks container """
        self.tasksWidget = QWidget(self.tabWidget)
        self.tasksWidgetLayout = QVBoxLayout(self.tasksWidget)
        self.tasksWidget.setLayout(self.tasksWidgetLayout)
        """ Create horizontal input container """
        self.inputContainer = QWidget()
        self.inputContainer.setFixedHeight(50)
        self.inputContainerLayout = QHBoxLayout(self.inputContainer)
        self.inputContainerLayout.setContentsMargins(0, 0, 0, 0)
        self.inputContainer.setLayout(self.inputContainerLayout)
        """ Create text edit """
        self.taskTextEdit = QTextEdit(
            placeholderText="Describe your task briefly.",
            undoRedoEnabled=True)
        """ Create vertical buttons container """
        self.inputButtonContainer = QWidget()
        self.inputButtonContainerLayout = QVBoxLayout(
            self.inputButtonContainer)
        self.inputButtonContainerLayout.setContentsMargins(0, 0, 0, 0)
        self.inputButtonContainer.setLayout(self.inputButtonContainerLayout)
        """ Create buttons """
        self.acceptTaskButton = QToolButton(icon=makeIcon("check"))
        self.deleteTaskButton = QToolButton(icon=makeIcon("trash"))
        """ Create tasks tablewidget """
        self.tasksTableWidget = QTableWidget(0, 1)
        self.tasksTableWidget.setHorizontalHeaderLabels(["Tasks"])
        self.tasksTableWidget.horizontalHeader().setStretchLastSection(True)
        self.tasksTableWidget.verticalHeader().setVisible(False)
        self.tasksTableWidget.setWordWrap(True)
        self.tasksTableWidget.setTextElideMode(Qt.ElideNone)
        self.tasksTableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tasksTableWidget.setSelectionMode(
            QAbstractItemView.SingleSelection)
        self.insertTasks(*settings.value(tasksKey, []))
        """ Add widgets to container widgets """
        self.inputButtonContainerLayout.addWidget(self.acceptTaskButton)
        self.inputButtonContainerLayout.addWidget(self.deleteTaskButton)
        self.inputContainerLayout.addWidget(self.taskTextEdit)
        self.inputContainerLayout.addWidget(self.inputButtonContainer)
        self.tasksWidgetLayout.addWidget(self.inputContainer)
        self.tasksWidgetLayout.addWidget(self.tasksTableWidget)
        return self.tasksWidget

    def setupStatisticsTab(self):
        """ Create statistics container """
        self.statisticsContainer = QWidget()
        self.statisticsContainerLayout = QVBoxLayout(self.statisticsContainer)
        self.statisticsContainer.setLayout(self.statisticsContainerLayout)
        """ Create work time groupbox """
        self.statisticsWorkTimeGroupBox = QGroupBox("Work Time")
        self.statisticsWorkTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsWorkTimeGroupBox.setLayout(
            self.statisticsWorkTimeGroupBoxLayout)
        self.statisticsWorkTimeDisplay = QLCDNumber(8)
        self.statisticsWorkTimeDisplay.display("00:00:00")
        self.statisticsWorkTimeGroupBoxLayout.addWidget(
            self.statisticsWorkTimeDisplay)
        """ Create rest time groupbox """
        self.statisticsRestTimeGroupBox = QGroupBox("Rest Time")
        self.statisticsRestTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsRestTimeGroupBox.setLayout(
            self.statisticsRestTimeGroupBoxLayout)
        self.statisticsRestTimeDisplay = QLCDNumber(8)
        self.statisticsRestTimeDisplay.display("00:00:00")
        self.statisticsRestTimeGroupBoxLayout.addWidget(
            self.statisticsRestTimeDisplay)
        """ Create total time groupbox """
        self.statisticsTotalTimeGroupBox = QGroupBox("Total Time")
        self.statisticsTotalTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsTotalTimeGroupBox.setLayout(
            self.statisticsTotalTimeGroupBoxLayout)
        self.statisticsTotalTimeDisplay = QLCDNumber(8)
        self.statisticsTotalTimeDisplay.display("00:00:00")
        self.statisticsTotalTimeGroupBoxLayout.addWidget(
            self.statisticsTotalTimeDisplay)
        """ Add widgets to container """
        self.statisticsContainerLayout.addWidget(
            self.statisticsTotalTimeGroupBox)
        self.statisticsContainerLayout.addWidget(
            self.statisticsWorkTimeGroupBox)
        self.statisticsContainerLayout.addWidget(
            self.statisticsRestTimeGroupBox)
        return self.statisticsContainer

    def setupTrayicon(self):
        self.trayIcon = QSystemTrayIcon(makeIcon("tomato"))
        self.trayIcon.setContextMenu(QMenu())
        self.quitAction = self.trayIcon.contextMenu().addAction(
            makeIcon("exit"), "Quit", self.exit)
        self.quitAction.triggered.connect(self.exit)
        self.trayIcon.activated.connect(self.onActivate)
        self.trayIcon.show()

    def leaveEvent(self, event):
        super(MainWindow, self).leaveEvent(event)
        self.tasksTableWidget.clearSelection()

    def closeEvent(self, event):
        super(MainWindow, self).closeEvent(event)
        settings = QSettings()
        settings.setValue(workHoursKey, self.workHoursSpinBox.value())
        settings.setValue(
            workMinutesKey,
            self.workMinutesSpinBox.value(),
        )
        settings.setValue(
            workSecondsKey,
            self.workSecondsSpinBox.value(),
        )
        settings.setValue(restHoursKey, self.restHoursSpinBox.value())
        settings.setValue(
            restMinutesKey,
            self.restMinutesSpinBox.value(),
        )
        settings.setValue(
            restSecondsKey,
            self.restSecondsSpinBox.value(),
        )

        tasks = []
        for i in range(self.tasksTableWidget.rowCount()):
            item = self.tasksTableWidget.item(i, 0)
            if not item.font().strikeOut():
                tasks.append(item.text())
        settings.setValue(tasksKey, tasks)

    def startTimer(self):
        try:
            if not self.timer.isActive():
                self.createTimer()
        except:
            self.createTimer()

    def createTimer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateTime)
        self.timer.timeout.connect(self.maybeChangeMode)
        self.timer.setInterval(1000)
        self.timer.setSingleShot(False)
        self.timer.start()

    def pauseTimer(self):
        try:
            self.timer.stop()
            self.timer.disconnect()
        except:
            pass

    def resetTimer(self):
        try:
            self.pauseTimer()
            self.time = QTime(0, 0, 0, 0)
            self.displayTime()
        except:
            pass

    def maybeStartTimer(self):
        if self.currentRepetitions != self.maxRepetitions:
            self.startTimer()
            started = True
        else:
            self.currentRepetitions = 0
            started = False
        return started

    def updateWorkEndTime(self):
        self.workEndTime = QTime(
            self.workHoursSpinBox.value(),
            self.workMinutesSpinBox.value(),
            self.workSecondsSpinBox.value(),
        )

    def updateRestEndTime(self):
        self.restEndTime = QTime(
            self.restHoursSpinBox.value(),
            self.restMinutesSpinBox.value(),
            self.restSecondsSpinBox.value(),
        )

    def updateCurrentMode(self, mode: str):
        self.currentMode = Mode.work if mode == "work" else Mode.rest

    def updateTime(self):
        self.time = self.time.addSecs(1)
        self.totalTime = self.totalTime.addSecs(1)
        if self.modeComboBox.currentText() == "work":
            self.workTime = self.workTime.addSecs(1)
        else:
            self.restTime = self.restTime.addSecs(1)
        self.displayTime()

    def updateMaxRepetitions(self, value):
        if value == 0:
            self.currentRepetitions = 0
            self.maxRepetitions = -1
        else:
            self.maxRepetitions = 2 * value

    def maybeChangeMode(self):
        if self.currentMode is Mode.work and self.time >= self.workEndTime:
            self.resetTimer()
            self.modeComboBox.setCurrentIndex(1)
            self.incrementCurrentRepetitions()
            started = self.maybeStartTimer()
            self.showWindowMessage(
                Status.workFinished if started else Status.repetitionsReached)
        elif self.currentMode is Mode.rest and self.time >= self.restEndTime:
            self.resetTimer()
            self.modeComboBox.setCurrentIndex(0)
            self.incrementCurrentRepetitions()
            started = self.maybeStartTimer()
            self.showWindowMessage(
                Status.restFinished if started else Status.repetitionsReached)

    def incrementCurrentRepetitions(self):
        if self.maxRepetitions > 0:
            self.currentRepetitions += 1

    def insertTask(self):
        task = self.taskTextEdit.toPlainText()
        self.insertTasks(task)

    def insertTasks(self, *tasks):
        for task in tasks:
            if task:
                rowCount = self.tasksTableWidget.rowCount()
                self.tasksTableWidget.setRowCount(rowCount + 1)
                self.tasksTableWidget.setItem(rowCount, 0,
                                              QTableWidgetItem(task))
                self.tasksTableWidget.resizeRowsToContents()
                self.taskTextEdit.clear()

    def deleteTask(self):
        selectedIndexes = self.tasksTableWidget.selectedIndexes()
        if selectedIndexes:
            self.tasksTableWidget.removeRow(selectedIndexes[0].row())

    def markTaskAsFinished(self, row, col):
        item = self.tasksTableWidget.item(row, col)
        font = self.tasksTableWidget.item(row, col).font()
        font.setStrikeOut(False if item.font().strikeOut() else True)
        item.setFont(font)

    def displayTime(self):
        self.timeDisplay.display(self.time.toString(self.timeFormat))
        self.statisticsRestTimeDisplay.display(
            self.restTime.toString(self.timeFormat))
        self.statisticsWorkTimeDisplay.display(
            self.workTime.toString(self.timeFormat))
        self.statisticsTotalTimeDisplay.display(
            self.totalTime.toString(self.timeFormat))

    def showWindowMessage(self, status):
        if status is Status.workFinished:
            self.trayIcon.showMessage("Break", choice(work_finished_phrases),
                                      makeIcon("tomato"))
        elif status is Status.restFinished:
            self.trayIcon.showMessage("Work", choice(rest_finished_phrases),
                                      makeIcon("tomato"))
        else:
            self.trayIcon.showMessage("Finished",
                                      choice(pomodoro_finished_phrases),
                                      makeIcon("tomato"))
            self.resetButton.click()

    def makeButton(self, text, iconName=None, disabled=True):
        button = QPushButton(text, sizePolicy=self.size_policy)
        if iconName:
            button.setIcon(makeIcon(iconName))
        button.setDisabled(disabled)
        return button

    def exit(self):
        self.close()
        app = QApplication.instance()
        if app:
            app.quit()

    def onActivate(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            self.show()
Ejemplo n.º 22
0
class MyMainWindow(QMainWindow, Ui_AudioTool):
    def __init__(self, parent=None, backend=None, convolutioner=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)

        self.backend = backend
        self.backend.finished.connect(self.fin)
        self.backend.track_done.connect(self.progress_count)
        self.media_player = convolutioner
        self.media_player.custom_processing_callback(self.audio_callback)

        self.working = False
        self.audio_available = False
        self.playing = False
        self.old_preview = None
        self.synthesis_stage = True
        """ Hide samples """
        self.progress_bar.hide()
        self.track_0.hide()
        self.effect_0.hide()
        self.root = ''
        """ Set up sintesis enviroment """
        self.track_manager = []
        self.instrument_panel = InstrumentsPopUp()
        self.select_file.clicked.connect(self.open_midi)
        self.sintetizar.clicked.connect(self.create_tracks)
        self.sintetizar.setDisabled(True)  # No synthesis whitout midi
        self.available_to_play = []
        """ Media player buttons """
        self.media_buttons_widget.play.clicked.connect(self.play)
        self.media_buttons_widget.stop.clicked.connect(self.stop)
        """ Effects enviroment """
        self.working_tracks = []  # To store on working EditedTrackWidget
        self.current_track = -1
        self.old_effect_prop = []
        self.current_effects_properties = []
        self.choose_effect.addItem('')
        self.effects = []
        for i in Effects:
            self.effects.append(i.value)
            self.choose_effect.addItem(i.value[0])
        self.choose_effect.currentIndexChanged.connect(self.renew_effect)
        self.to_song.clicked.connect(self.effect_to_song)
        self.discard_effect.clicked.connect(self.clean_current_effect)

        self.disable_effect_enviroment()
        """ Reproduction thing """
        self.all_tracks = []
        self.all_callbacks = []
        self.eddited_song = []
        """ Timer things """
        self.inner_timer = QTimer()
        self.inner_timer.timeout.connect(self.count_down_callback)
        self.song_time = QTime()
        """ Spectrogram things """
        self.spectrogrammer = Spectrogrammer()
        self.plot_work.clicked.connect(self.sepectro_plot)
        self.prev_plot = None
        self.prev_nav = None
        """ Notes """
        for i in Instruments:
            self.note_instrument.addItem(i.value[0])
        self.note_add.clicked.connect(self.add_note)
        self.note_play.clicked.connect(self.play_notes)
        self.all_notes = []

        self.save.clicked.connect(self.save_wav)

    def save_wav(self):
        to_save = None
        if self.audio_available:
            to_save = self.media_player.output_array.copy()
        else:
            sum = np.sum(self.all_tracks, axis=0)
            max = np.max(sum)
            if max != 0:
                to_save = sum / max
            else:
                to_save = sum

        file = self.root + '.wav'
        write(file, 44100, np.int16(to_save * 32767))

    def play_notes(self):
        notas = []
        for i in self.all_notes:
            i, l, v, ins, f = i.get_data()
            notas.append(note(i, l, v, ins, f))

        self.backend.create_chord(notas)

    def add_note(self):
        init = self.note_time.value()
        long = self.note_duration.value()
        velocity = self.note_volume.value()
        instrument = self.note_instrument.currentText()
        freq = self.note_freq.value()
        note = NoteWidget(freq, instrument, velocity, init, long, self)
        note.delete.connect(functools.partial(self.remove_note, note))
        self.all_notes.append(note)
        self.note_area.layout().addWidget(note)

    def remove_note(self, note: NoteWidget):
        self.all_notes.remove(note)
        note.close()

    def sepectro_plot(self):
        source = self.plot_track.currentText()
        data = []
        if source == '':
            """ Incomplete """
            return
        elif source == 'Plain Song':
            data = np.sum(self.all_tracks, axis=0)
        elif source == 'Edited Song':
            data = np.sum(self.media_player.output_array.copy(), axis=0)
        else:
            track_num = int(source.split()[-1])
            useful_index = self.available_to_play.index(track_num - 1)
            data = self.all_tracks[useful_index]
        """ Ya tenemos los datos ahora hay que cortar el tramo de tiempo que se quiera """

        title = source + ' init: ' + str(self.plot_time.time().minute()) + ':' + str(self.plot_time.time().second()) + \
                ' + ' + str(self.plot_long.value()) + 's'
        init = 44100 * self.plot_time.time().minute(
        ) * 60 + self.plot_time.time().second()
        fin = init + (self.plot_long.value() * 44100)

        song = data[init:fin]
        time_array = np.arange(init,
                               init + song.size / 44100.0,
                               1 / 44100.0,
                               dtype=song.dtype)
        self.spectrogrammer.compute_audio_array(time_array, song)
        self.spectrogrammer.calculate_FFTs()

        mag = self.spectrogrammer.get_FFTs_magnitude()
        time = self.spectrogrammer.get_resampled_time_array()
        freq = self.spectrogrammer.get_FFTs_freq()

        plotter = PyQtPlotter()
        plotter.spectrogram(time, freq, mag, title, f_bottom=20, f_top=20000)
        util_canvas = plotter.canvas

        if self.prev_plot is not None:
            """ remove previous plot """
            self.plot_space.removeWidget(self.prev_plot)

        i = self.plot_space.addWidget(util_canvas)
        self.plot_space.setCurrentIndex(i)

        nav = NavegationToolBar(util_canvas, self)
        if self.prev_nav is not None:
            self.tool_bar.removeWidget(self.prev_nav)
        i = self.tool_bar.addWidget(nav)
        self.tool_bar.setCurrentIndex(i)

    def count_down_callback(self):
        if self.media_player.processing():
            self.song_time = self.song_time.addSecs(-1)
            self.count_down.setText(self.song_time.toString("m:ss"))
        else:
            self.playing = False
            self.plot_track.addItem('Edited Song')

            song_len = len(self.all_tracks[0])
            song_len = np.ceil(song_len / 44100.0)
            self.song_time.setHMS(0, int(song_len / 60.0), int(song_len % 60))
            self.count_down.setText(self.song_time.toString("m:ss"))

            self.media_player.terminate_processing()
            self.eddited_song = self.media_player.output_array.copy()
            self.media_player.clear_output()
            self.inner_timer.stop()
            self.media_buttons_widget.play.toggle()
            for i in self.working_tracks:
                i.reset()

    def disable_effect_enviroment(self):
        self.plot_track.clear()

        self.working = False
        self.audio_available = False
        self.old_preview = None
        self.synthesis_stage = True

        self.media_buttons_widget.play.setDisabled(True)
        self.media_buttons_widget.stop.setDisabled(True)

        self.to_track.hide()
        self.to_song.hide()
        self.choose_effect.setDisabled(True)
        self.discard_effect.hide()
        self.work_track.setText('')

        for tracks in self.track_manager:  # Closing old midi tracks
            tracks.close()

        self.track_manager = []

        for track_edits in self.working_tracks:
            track_edits.close_all(
            )  # Clean up old work / be careful with convolutioner!!!

    def enable_effects(self):
        self.synthesis_stage = False
        self.media_buttons_widget.play.setDisabled(False)
        self.media_buttons_widget.stop.setDisabled(False)
        #self.to_track.show()
        #self.to_song.show()

    def clean_current_effect(self):
        """ First change the callback to use, then reapear and to finish clean everything """
        track = self.working_tracks[self.current_track].track_num - 1
        useful_index = self.available_to_play.index(track)
        if useful_index < 0:
            print('Fatal ERROR')
        self.all_callbacks[useful_index] = self.nothing  # Setting new callback
        self.track_manager[track].show()  # Reapear in tracks
        self.work_track.setText("Track ...")
        self.choose_effect.setDisabled(True)

        self.working_tracks[self.current_track].close_all()
        self.working_tracks[self.current_track].close()
        self.working_tracks.pop(self.current_track)
        self.current_track = -1

    def get_back_effect(self, track_number):
        who = -1
        j = 0
        for i in self.working_tracks:
            if i.track_num == track_number:
                who = j
                break
            else:
                j += 1
        if who == self.current_track:
            """ Nothing to do """
            return

        if self.current_track >= 0:
            self.working_tracks[self.current_track].go_backstage()
            self.choose_effect.setCurrentIndex(0)

        self.choose_effect.setDisabled(False)
        self.work_track.setText("Track " + str(track_number))
        self.discard_effect.show()

        self.current_track = who
        self.working_tracks[who].show_properties()

    def audio_callback(self, sample):
        foo = []
        for i in range(0, len(sample)):
            foo.append((sample[i], self.all_callbacks[i]))

        out = np.array(list(map(self.effects_to_apply, foo)))
        return out[:, 0], out[:, 1]

    def effects_to_apply(self, var):
        func = var[1]
        return func(var[0])

    def effect_to_song(self):
        print('hola')

    def select_track(self, index):
        if not (not self.synthesis_stage and index in self.available_to_play):
            """ If synthesis is not ready, effects are not possible """
            return

        if self.current_track >= 0:
            self.working_tracks[self.current_track].go_backstage()
            self.choose_effect.setCurrentIndex(0)

        self.track_manager[index].hide()
        self.choose_effect.setDisabled(False)
        self.work_track.setText("Track " + str(index + 1))
        self.discard_effect.show()

        temp = EditedTrackWidget(self, self.effect_container.layout(),
                                 index + 1)
        self.working_tracks.append(temp)
        self.working_effects.layout().addWidget(temp)
        self.current_track = self.working_tracks.index(temp)
        temp.update_effect.connect(
            functools.partial(self.audio_procesing, index + 1))
        temp.clicked.connect(self.get_back_effect)
        """
        plot = PyQtPlotter()
        data = self.all_tracks[self.available_to_play.index(index)]
        time = np.arange(len(data))/44100.0
        plot.x_vs_y(time, data,"Track "+str(index+1))

        util_canvas = plot.canvas

        if self.prev_wave is not None:
            
            self.waveform.removeWidget(self.prev_wave)

        i = self.waveform.addWidget(util_canvas)
        self.waveform.setCurrentIndex(i)
        """

    def audio_procesing(self, track_num):
        index = 0
        for i in range(0, len(self.working_tracks)):
            if self.working_tracks[i].me(track_num):
                index = i
                break
        index_2 = self.available_to_play.index(track_num - 1)
        print(index)
        print(self.working_tracks)
        self.all_callbacks[index_2] = self.working_tracks[index].get_callback()

    def tracks_audio_prcesing(self, state: bool, index: int):
        index = index - 1
        useful_index = self.available_to_play.index(index)
        if useful_index >= 0:
            """ Available ones """
            if state:
                self.all_callbacks[useful_index] = self.mute
            else:
                self.all_callbacks[useful_index] = self.nothing

    def renew_effect(self, index):
        layout = self.effect_container.layout()

        if index > 0:
            self.old_effect_prop = []

            efecto = self.effects[index - 1]
            propiedades = efecto[1]
            for prop, valor in propiedades.items():
                my_item = EffectPropertyWidget(self, prop, valor[0][1],
                                               valor[1])
                layout.addWidget(my_item)
                self.old_effect_prop.append(my_item)
            self.working_tracks[self.current_track].set_effect(
                efecto[2](), self.old_effect_prop)

    def open_midi(self):
        layout = self.track_setter.layout()
        self.plot_track.clear()
        """ Go to find new """
        filename, _ = QFileDialog.getOpenFileName(self, 'Open File', '',
                                                  'Midi (*.mid)')
        """ If no file is selected quit """
        if filename == '':
            return
        self.progress_bar.setValue(0)
        """ Clear previous things"""
        self.disable_effect_enviroment()
        self.root = filename.split('.')[0]
        name = filename.split('/')[-1]
        self.midi_name.setText(name)
        self.backend.load_midi_file(filename)
        tracks = self.backend.get_track_list()

        for i in range(0, len(tracks)):
            aux_track = TrackConfigWidget(self, str(i + 1),
                                          self.instrument_panel)
            aux_track.clicked.connect(functools.partial(self.select_track, i))
            """ Aca deberia agarrar el doble ckick !!!!"""
            self.track_manager.append(aux_track)
            layout.addWidget(self.track_manager[i])
            # i += 1
        self.label.setText(
            'Seleccione los instrumentos, y al sintetizar espere a que se pongan verdes los tracks'
        )

        self.sintetizar.setDisabled(False)

    def create_tracks(self):
        """ working is a bool to avoid  conflicts while synthesizing """
        if not self.working:

            fin = len(self.track_manager)
            """ May be good looking to start a timer and do something meanwhile.. """
            self.working = True
            absents = []
            all_num = []

            for i in range(0, fin):
                all_num.append(i)
                volume, instrument = self.track_manager[i].get_data()
                active = True
                if volume == 0 or instrument == '':
                    absents.append(i)
                    active = False
                self.backend.assign_instrument_to_track(
                    i, instrument, volume / 100.0, active)

            if len(absents) == len(self.track_manager):
                print('Compilando vacio')
                return

            for a in self.track_manager:  # This may be useful in future
                a.setStyleSheet(
                    'QWidget { border-style: solid; background-color: rgbrgb(81, 76, 149); border-radius: 5px;}'
                )

            self.available_to_play = list(
                set(all_num).difference(set(absents)))
            self.progress_bar.setMaximum(len(self.available_to_play))
            self.progress_bar.setValue(0)
            self.progress_bar.show()

            self.backend.start()

    def progress_count(self, a):
        self.progress_bar.setValue(self.progress_bar.value() + 1)
        self.track_manager[a].setStyleSheet(
            'QWidget { border-style: solid; background-color: rgb(31, 172, 102); border-radius: 5px;}'
        )

    def fin(self):
        #self.progress_bar.hide()
        self.enable_effects()
        self.plot_track.addItem('Plain Song')
        self.plot_track.addItems(
            ['Track ' + str(i + 1) for i in self.available_to_play])
        self.working = False
        all_tracks = []
        """ Load tracks """
        for i in range(0, len(self.available_to_play)):
            song = np.load(path + 'BackEnd/Tracks/' + 'track' + str(i) +
                           '.npy')
            all_tracks.append(song)
            self.all_callbacks.append(
                self.nothing)  # Adding functions with all ones
        if self.media_player is not None:
            """ Send input to convolutioner """
            self.media_player.update_input(np.array(all_tracks),
                                           np.dtype('float32'))

        self.all_tracks = all_tracks.copy()
        """ Set timer """
        song_len = len(all_tracks[0])
        song_len = np.ceil(song_len / 44100.0)
        self.song_time.setHMS(0, int(song_len / 60.0), int(song_len % 60))
        self.count_down.setText(self.song_time.toString("m:ss"))
        self.label.setText(
            'Ahora puede poner play, haciendo click sobre un track podrá seleccionalo para agregar efectos'
        )

    def play(self):
        if self.media_buttons_widget.stop.isChecked():
            self.media_buttons_widget.stop.toggle()

        if self.playing:
            self.media_player.terminate_processing()
            self.media_player.clear_output()
            song_len = len(self.all_tracks[0])
            song_len = np.ceil(song_len / 44100.0)
            self.song_time.setHMS(0, int(song_len / 60.0), int(song_len % 60))
            self.count_down.setText(self.song_time.toString("m:ss"))
            self.inner_timer.stop()
            for i in self.working_tracks:
                i.reset()
        self.playing = True

        self.media_player.start_non_blocking_processing()
        self.inner_timer.start(1000)

    def stop(self):
        if self.media_buttons_widget.play.isChecked():
            self.media_buttons_widget.play.toggle()
        if not self.playing:
            return
        self.playing = False
        self.media_player.terminate_processing()
        self.media_player.clear_output()
        song_len = len(self.all_tracks[0])
        song_len = np.ceil(song_len / 44100.0)
        self.song_time.setHMS(0, int(song_len / 60.0), int(song_len % 60))
        self.count_down.setText(self.song_time.toString("m:ss"))
        self.inner_timer.stop()
        for i in self.working_tracks:
            i.reset()

    def preview_adjust(self, track_number):
        if self.old_preview is not None:
            if self.old_preview != track_number:
                """ Clear previous select """
                self.track_manager[self.old_preview].setStyleSheet(
                    'QWidget { border-style: solid; background-color: rgb(81, 76, 149); border-radius: 5px;}'
                )
                self.track_manager[self.old_preview].preview.toggle()
                """ Mark new track"""
                self.track_manager[track_number].setStyleSheet(
                    'QWidget { border-style: solid; background-color: rgb(31, 172, 102); border-radius: 5px;}'
                )
                self.old_preview = track_number
            else:
                """ Unselect track """
                self.track_manager[self.old_preview].setStyleSheet(
                    'QWidget { border-style: solid; background-color: rgb(81, 76, 149); border-radius: 5px;}'
                )
                self.old_preview = None
        else:
            self.track_manager[track_number].setStyleSheet(
                'QWidget { border-style: solid; background-color: rgb(31, 172, 102); border-radius: 5px;}'
            )
            self.old_preview = track_number

    @staticmethod
    def nothing(sample):
        """ All deltas response, for no effect output """
        return (sample, sample)

    @staticmethod
    def mute(sample):
        """ All deltas response, for no effect output """
        out = np.array([np.zeros(len(sample))])
        return (out, out)
Ejemplo n.º 23
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # Set window properties.
        self.setWindowTitle("Speed Typer")
        self.my_font = QFont("Helvetica [Cronyx]", 20, QFont.Bold)

        self.my_style = "color: rgb(255, 215, 0)"

        self.create_widgets()
        self.setGeometry(200, 200, 1000, 500)

        # Window color.
        self.p = self.palette()
        self.p.setColor(self.backgroundRole(), QtCore.Qt.black)
        self.setPalette(self.p)

        # Random sentence from dictionary.
        self.sentence = ""

    def create_widgets(self):
        """ 
        Method: Intialize all UI widgets.  
        """

        # Button to generate sentence from dictionary.
        self.getSent = QPushButton("Start", self)
        self.getSent.setGeometry(440, 20, 100, 45)
        self.getSent.clicked.connect(self.generate_S)
        self.getSent.setFont(self.my_font)

        # Button to close application.
        self.closeBtn = QPushButton("Quit", self)
        self.closeBtn.setGeometry(440, 300, 100, 45)
        self.closeBtn.clicked.connect(self.close)
        self.closeBtn.setFont(self.my_font)

        # User attempt to type sentence.
        self.usrAttempt = QLineEdit(self)
        self.usrAttempt.setGeometry(180, 175, 600, 30)
        self.usrAttempt.returnPressed.connect(self.fireTimer)

        # Submit user attempt.
        self.subBtn = QPushButton("submit", self)
        self.subBtn.setGeometry(780, 170, 100, 45)
        self.subBtn.clicked.connect(self.getAccuracy)
        self.subBtn.setFont(self.my_font)

        # Label to show random sentence.
        self.sentLabel = QLabel("", self)
        self.sentLabel.setGeometry(140, 120, 800, 50)
        self.sentLabel.setFont(self.my_font)
        self.sentLabel.setStyleSheet(self.my_style)

        self.disclaimer = QLabel(
            "Once you press start, you will display a sentence and be timed. Be ready!",
            self)
        self.disclaimer.setGeometry(140, 60, 700, 50)
        self.disclaimer.setFont(self.my_font)
        self.disclaimer.setStyleSheet(self.my_style)

        # Labels to show accuracy and time results.
        self.accLabel = QLabel("", self)
        self.accLabel.setGeometry(250, 200, 200, 50)
        self.accLabel.setFont(self.my_font)
        self.accLabel.setStyleSheet(self.my_style)

        self.timerLabel = QLabel("", self)
        self.timerLabel.setGeometry(500, 200, 200, 50)
        self.timerLabel.setFont(self.my_font)
        self.timerLabel.setStyleSheet(self.my_style)

        # Timer object to record time it took for user to type.
        self.curr_time = QTime(00, 00, 00)
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.fireTimer)

    def generate_S(self):
        """  
        Method: Get random sentence from dictionary. 
        """

        self.disclaimer.hide()
        self.accLabel.hide()
        self.timerLabel.hide()

        self.timer.start()

        self.sentence = sentences[random.randrange(0, len(sentences) - 1)]
        self.sentence = self.sentence.rstrip()

        self.sentLabel.setText(self.sentence)

        self.usrAttempt.setText("")

    def getAccuracy(self):
        """
        Method: Get user's attempt from UI and compute accuracy. 
        """

        self.timer.stop()
        attempt = self.usrAttempt.text()

        # Compute string comparison accuracy with SequenceMatcher func from difflib library.
        acc = difflib.SequenceMatcher(None, attempt, self.sentence)
        result = acc.ratio() * 100
        result = str(round(result, 2))

        # Update result labels.
        self.accLabel.setText(f'Accuracy: {result}%')
        self.timerLabel.setText(f'Time: {self.curr_time.toString("hh:mm:ss")}')
        self.accLabel.show()
        self.timerLabel.show()

        # Reset time for label and reset value for user-attempt line edit.
        self.curr_time.setHMS(00, 00, 00)

    def fireTimer(self):
        """  
        Method: Fire timer when user starts typing. 
        """

        self.curr_time = self.curr_time.addSecs(1)
Ejemplo n.º 24
0
class LiveTab(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(LiveTab, self).__init__(*args, **kwargs)
        uic.loadUi(os.path.join(sys.path[0], 'UI/MainWindow.ui'), self)

        # self.ViewGraph.setEnabled(False) # Enabled when there is enough data
        self.setFocus()
        self.gameTime = QTime(0, 0, 0)

        self.redData = list()
        self.blueData = list()

        self.StartGame.clicked.connect(self.startGame)
        self.ViewGraph.clicked.connect(self.showGraph)

        self.badStyle = f'background:{badColor}; padding: 5px;'
        self.goodStyle = f'background:{highlightColor}; padding: 5px;'

        # Status monitors for website statuses, None means 'Loading...'
        self.streamUp = None
        self.teams = None
        self.statsUp = None

        self.graphWindow = None  # Defined early so we have a reference if never created
        self.gameOver = False  # Stop data from being collected
        self.accurateSides = None  # Keeps track if teams have swapped sides during a series

        # Create and run the selenium browser to gather data every second about the status and stats
        self.browserThread = BrowserThread(self)
        self.browserThread.start()

    def setStreamStatus(self, status):
        if self.streamUp == status:
            return
        self.streamUp = status
        if status:
            self.StreamStatusLabel.setText('LIVE')
            self.StreamStatusLabel.setStyleSheet(self.goodStyle)
        else:
            self.StreamStatusLabel.setText('Not Available')
            self.StreamStatusLabel.setStyleSheet(self.badStyle)

    def setTeams(self, teamList, blueTeam=None, redTeam=None):
        self.blueTeam = blueTeam
        self.redTeam = redTeam
        if self.teams == teamList:
            return
        self.teams = teamList
        if len(teamList) > 0:
            self.GameStatusLabel.setText(f'{teamList[0]} vs {teamList[1]}')
            self.GameStatusLabel.setStyleSheet(self.goodStyle)
        else:
            self.GameStatusLabel.setText('No Games Available')
            self.GameStatusLabel.setStyleSheet(self.badStyle)
        self.teams = teamList

    def setDataShown(self, dataShown):
        if dataShown is self.statsUp:
            return

        self.statsUp = dataShown
        if dataShown:
            self.StatsStatusLabel.setText('Stats Recording')
            self.StatsStatusLabel.setStyleSheet(self.goodStyle)
        else:
            self.StatsStatusLabel.setText('No Stats Available')
            self.StatsStatusLabel.setStyleSheet(self.badStyle)
        self.dataShown = dataShown

    def addData(self, red, blue):
        # Add data and increase the game clock unless the game is over
        if self.gameOver:
            return
        self.redData.append(red)
        self.blueData.append(blue)
        self.updateTime(1)

        if len(self.blueData) > 3:
            self.ViewGraph.setEnabled(True)

    def showStats(self, x):
        print(f'showing stats: {x}')

    def showGraph(self):
        print('showing graph')
        self.graphWindow = GraphWindow(self)
        self.graphWindow.show()
        self.ViewGraph.setEnabled(False)

    def saveGraph(self):
        print('saving graph')

    def updateTime(self, changeAmt=0):
        self.gameTime = self.gameTime.addSecs(changeAmt)

    def endGame(self):
        # Prevent data from being colleted
        self.gameOver = True
        self.StartGame.setEnabled(True)

    def startGame(self):
        # Clears the data and allows data to be collected again
        self.gameOver = False
        self.StartGame.setEnabled(False)
        self.redData = list()
        self.blueData = list()

    def closeEvent(self, *args, **kwargs):
        super(LiveTab, self).closeEvent(*args, **kwargs)
        try:
            self.graphWindow.close()
        except Exception:
            pass  # The window failed to close because it was already closed
        self.browserThread.closeBrowser()
        self.browserThread.quit()
Ejemplo n.º 25
0
class Game(QMainWindow, Ui_GameWindow):
    def __init__(self):
        super().__init__()
        super().setupUi(self)
        self.setFixedSize(500, 400)
        # внетренняя переменная сколько сек живет кнопка
        self.t = TIME_OUT
        self.timer = QTimer()
        self.time = QTime(0, 0, self.t)
        # кнопка-бегунок
        self.runner.hide()
        # переменная сложности для размера кнопки-бегунка
        self.d = SIZE_OF_RUNNER * LEVELS[0][1]
        self.runner.resize(self.d, self.d)
        # таймер в окне
        self.label.setText('00:20')
        # сообзщение перед запуском
        # message = QInputDialog.getItem(self, 'Сообщение', 'Обязательно посмотрите раздел О программе', 'OK', 0, False)
        self.initUi()
        # свои настройки
        self.man_set = Man_Set()
        self.is_dark = False

    def initUi(self):
        # просто случайный смайл в статусбаре ¯\(⌒‿⌒)/¯
        self.statusBar().showMessage(choice(SMLS))
        # кнопка старта
        self.beginbtn.clicked.connect(self.run)
        # меню сложности
        self.Menu_Difficulty.triggered.connect(self.Difficulty)
        # меню своих настроек
        self.Manual_Settings.triggered.connect(self.Man_Set)
        # меню справки
        self.About_program.triggered.connect(self.About)
        # темная тема
        self.dark.clicked.connect(self.dark_phone)

    # TODO: -----
    def dark_phone(self):
        if not self.is_dark:
            self.is_dark = True
            self.setStyleSheet('background-color: black')
            self.beginbtn.setStyleSheet('background-color: gray')
            self.label.setStyleSheet('background-color: gray')
            self.dark.setStyleSheet('background-color: gray')
        else:
            self.is_dark = False
            self.beginbtn.setStyleSheet('background-color: white')
            self.label.setStyleSheet('background-color: white')
            self.dark.setStyleSheet('background-color: white')
            self.setStyleSheet('background-color: white')
        if not col:
            self.runner.setStyleSheet('background-color: grey')

    # злополучный таймер, там же применение своих настроек
    def run(self):
        print('run timer')
        # свои настройки
        self.run_color()
        self.timer = QTimer()
        self.time = QTime(0, 0, self.t)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timerEvent)

    # события связанные с таймером
    def timerEvent(self):
        print(self.t)
        # меняет время в окне в QLabel
        self.label.setText(self.time.toString("mm:ss"))
        # таймер до 0
        if self.time != QTime(0, 0, 0):
            print('!')
            self.runner.show()
            self.beginbtn.hide()
            self.runner.clicked.connect(self.change_pos)
            self.time = self.time.addSecs(-1)
        else:
            print('else')
            self.runner.hide()
            self.beginbtn.show()
            self.label.setText('00:20')
            self.timer.stop()

    # проблемный метод изменения позиции "бегуна", меняет столько раз, сколько прошло секунд... (не знаю как исправить)
    def change_pos(self):
        # случайный цвет
        if col == 'rm_col':
            self.runner.setStyleSheet(
                "background-color: rgb({}, {}, {})".format(
                    randint(0, 255), randint(0, 255), randint(0, 255)))
            # красный цвет
        elif col == 'red_col':
            self.runner.setStyleSheet("background-color: red")
        # зеленый цвет
        elif col == 'green_col':
            self.runner.setStyleSheet("background-color: green")
        # синий цвет
        elif col == 'blue_col':
            self.runner.setStyleSheet("background-color: blue")
        self.runner.move(randint(100,
                                 self.width() - 200),
                         randint(100,
                                 self.height() - 200))
        self.runner.repaint()

    # метод вызывающий окно выбора сложности
    def Difficulty(self):
        diff, okBtnPressed = QInputDialog.getItem(
            self, "Difficulty", 'Выберите сложность, с которой хотите играть.',
            ('easy', 'normal', 'hard'), 0, False)

        # постановка сложности
        if okBtnPressed:
            if diff == 'easy':
                self.d = SIZE_OF_RUNNER * LEVELS[0][1]
            elif diff == 'normal':
                self.d = SIZE_OF_RUNNER * LEVELS[1][1]
            elif diff == 'hard':
                self.d = SIZE_OF_RUNNER * LEVELS[2][1]
        self.runner.resize(self.d, self.d)

    # метод окна своих настроек
    def Man_Set(self):
        print('Man_Set')
        self.man_set.setFixedSize(400, 300)
        self.man_set.show()

    # осуществление своих настроек
    def run_color(self):
        # случайный цвет
        if col == 'rm_col':
            self.runner.setStyleSheet(
                "background-color: rgb({}, {}, {})".format(
                    randint(0, 255), randint(0, 255), randint(0, 255)))
        # красный цвет
        elif col == 'red_col':
            self.runner.setStyleSheet("background-color: red")
        # зеленый цвет
        elif col == 'green_col':
            self.runner.setStyleSheet("background-color: green")
        # синий цвет
        elif col == 'blue_col':
            self.runner.setStyleSheet("background-color: blue")
        # выбрать цвет самостоятельно
        elif col == 'manual_col':
            color = QColorDialog.getColor()
            if color.isValid():
                self.runner.setStyleSheet("background-color: {}".format(
                    color.name()))

    # метод окна справки
    def About(self):
        QInputDialog.getItem(
            self, 'About',
            'Эта программа создана для проверки и улучшения реакции.\nЕсть несколько '
            'режимов сложности, они влияют на размер\nкнопки.\nЕще можно менять цвет в своих '
            'настройках, обязательно\nзагляните туда!\nЖелаю хорошо провести время!\n'
            '---------------------------------------------------------------------------------------\n'
            'И кстати, пожалуйста, перезапускайте программу хотябы через каждые 5 стартов.\n'
            '---------------------------------------------------------------------------------------\n',
            ('ок', 'хорошо', 'нормально', 'спасибо))0)00))0)))'), 3, False)

    # Метод кнопочек
    def keyPressEvent(self, event):
        # Esc >> exit
        if event.key() == Qt.Key_Escape:
            self.close()

    # Метод вызывающий окно с подтверждением выхода
    def closeEvent(self, event):
        res = QMessageBox.question(self, "Confirm exit",
                                   "Are you sure you want to exit?",
                                   QMessageBox.Yes | QMessageBox.No,
                                   QMessageBox.No)
        if res == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.backlog = Backlog()

        self.backlog.load(
            "C:\\Users\\Patrick\\Documents\\Python\\Giro\\turboClock\\Data\\tasksData.dat"
        )

        self.currTask = Task()

        self.currPiece = Piece()

        self.currDuty = Duty()

        self.currTaskItemRow = 0

        self.isTimerRunning = False

        self.editTasksGUI = EditBacklogGUI(self, self.backlog)

        self.initUI()

    def initUI(self):

        self.setWindowTitle("TurboClock")

        self.resize(400, 300)
        self.setWindowIcon(QIcon('Images//clock.png'))

        self.icon = QSystemTrayIcon(self)
        self.icon.setIcon(QIcon('Images//clock.png'))
        self.icon.setVisible(True)

        self.lcdNumber = QLCDNumber()
        self.lcdNumber.setNumDigits(8)

        self.btnStartPause = QPushButton('', self)
        self.btnStartPause.setIcon(QIcon('Images//play_icon.png'))
        self.btnStartPause.clicked.connect(self.manageStartPauseClickButton)

        self.btnDutyDetails = QPushButton('Duty details...')
        self.btnDutyDetails.clicked.connect(self.manageDutyDetailsClickedEvent)

        self.btnAddTfsTask = QPushButton('', self)
        self.btnAddTfsTask.setIcon(QIcon('Images//plus_icon.png'))
        self.btnAddTfsTask.clicked.connect(self.manageEditTasksOptions)

        self.progressBar = QProgressBar()
        self.progressBar.setValue(0)

        self.dutyTimeCompLbl = QLabel()

        self.taskCb = QComboBox(self)
        self.initTaskCombobox()

        mainLayout = QVBoxLayout(self)

        layoutTimer = QVBoxLayout()
        layoutTimer.addWidget(self.lcdNumber)

        fieldsInputLayout = QHBoxLayout()

        layoutInputCodes = QVBoxLayout()
        layoutInputCodes.addWidget(self.taskCb)

        layoutAddBtn = QVBoxLayout()
        layoutAddBtn.addWidget(self.btnAddTfsTask)

        fieldsInputLayout.addLayout(layoutInputCodes)
        fieldsInputLayout.addLayout(layoutAddBtn)

        layoutDutyStat = QHBoxLayout()
        layoutDutyStat.addWidget(self.dutyTimeCompLbl)

        layoutProgressBar = QHBoxLayout()
        layoutProgressBar.addWidget(self.progressBar)

        mainLayout.addLayout(layoutTimer)
        mainLayout.addLayout(fieldsInputLayout)
        mainLayout.addWidget(self.btnStartPause)
        mainLayout.addWidget(self.btnDutyDetails)
        mainLayout.addWidget(self.progressBar)
        mainLayout.addLayout(layoutDutyStat)

        self.timer = QTimer(self)
        self.deltaTimer = 0
        self.currTimeLCD = QTime(0, 0, 0)
        self.currTimeDuty = QTime(0, 0, 0)

        self.timer.timeout.connect(self.incrementTimer)

        self.updateTimeLCD()
        self.updateDutyTimeDisp()
        self.updateProgressBarDisplay()

    def initTaskCombobox(self):

        self.updateTaskCombobox()

        self.taskCb.currentIndexChanged.connect(self.manageCbIndexChange)

    def updateProgressBarDisplay(self):

        estimatedTime = self.currTask.estimatedTime

        if estimatedTime == 0:
            return

        ratioFromTimer = (self.deltaTimer / estimatedTime)

        totalCompletionPerc = int(
            (self.currTask.completionRatio + ratioFromTimer) * 100)

        if totalCompletionPerc <= 100:
            self.progressBar.setValue(totalCompletionPerc)
        else:
            self.progressBar.setValue(100)

    def updateTaskCombobox(self):

        currTaskIndex = 0

        self.taskCb.clear()

        tasks = self.backlog.tasks

        for currTask in tasks:

            taskDesc = currTask.title + ' - ' + currTask.prjCode
            self.taskCb.addItem(taskDesc)

        self.taskCb.setCurrentIndex(currTaskIndex)

        self.manageSelectedTaskChange(self.taskCb.currentText())

    def manageCbIndexChange(self):

        self.currTaskItemRow = self.taskCb.currentIndex()

        if self.currTaskItemRow >= 0 and self.currTaskItemRow <= self.taskCb.count(
        ):

            currTextCb = self.taskCb.currentText()
            self.manageSelectedTaskChange(currTextCb)

        self.updateTimeLCD()

        self.deltaTimer = 0
        self.updateProgressBarDisplay()

    def updateTimeLCD(self):

        currTaskTimeStr = str(
            datetime.timedelta(seconds=self.currTask.completedTime))
        currTaskTime_split = str(currTaskTimeStr).split(':')

        h = int(currTaskTime_split[0])
        m = int(currTaskTime_split[1])
        s = int(currTaskTime_split[2])

        self.currTimeLCD = QTime(h, m, s)
        self.lcdNumber.display(self.currTimeLCD.toString('hh:mm:ss'))

    def updateDutyTimeDisp(self):

        currDutyTimeStr = str(
            datetime.timedelta(seconds=self.currDuty.totalTimeCompleted))
        currDutyTime_split = currDutyTimeStr.split(':')

        h = int(currDutyTime_split[0])
        m = int(currDutyTime_split[1])
        s = int(currDutyTime_split[2])

        self.currTimeDuty = QTime(h, m, s)
        self.dutyTimeCompLbl.setText('Daily time completed: ' +
                                     self.currTimeDuty.toString('hh:mm:ss'))

    def incrementTimer(self):

        self.currTimeLCD = self.currTimeLCD.addSecs(1)
        self.lcdNumber.display(self.currTimeLCD.toString('hh:mm:ss'))

        self.currTimeDuty = self.currTimeDuty.addSecs(1)
        self.dutyTimeCompLbl.setText('Daily time completed: ' +
                                     self.currTimeDuty.toString('hh:mm:ss'))

        self.deltaTimer += 1

        self.updateProgressBarDisplay()

    def manageSelectedTaskChange(self, iCbbText):

        splitCurrTextCb = iCbbText.split(' - ')

        title = splitCurrTextCb[0]
        prjCode = splitCurrTextCb[1]

        indexBacklogCurrTask = self.backlog.getIndexFromTask(
            Task(prjCode, title))

        if indexBacklogCurrTask != None:

            if self.isTimerRunning:

                self.endPiece()
                self.startPiece()

            self.currTask = self.backlog.tasks[indexBacklogCurrTask]

        else:
            return

    def startPiece(self):

        self.currPiece = Piece(self.currTask, datetime.datetime.now())
        self.isTimerRunning = True

    def endPiece(self):

        self.currPiece.setEndDateTime(datetime.datetime.now())

        self.currDuty.addPiece(self.currPiece)

        self.currTask.addCompletedTime(self.currPiece.task.completedTime)

        self.isTimerRunning = False

    def manageStartPauseClickButton(self):

        if self.currTask:

            self.deltaTimer = 0

            if self.isTimerRunning:
                self.timer.stop()
                self.endPiece()
                self.btnStartPause.setIcon(QIcon('Images//play_icon.png'))
            else:
                self.timer.start(1000)
                self.startPiece()
                self.btnStartPause.setIcon(QIcon('Images//pause_icon.png'))

    def manageDutyDetailsClickedEvent(self):
        pass

    def manageEditTasksOptions(self):

        self.editTasksGUI.exec_()
Ejemplo n.º 27
0
class IntervalTimerGui(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.counter = 0
        self.time_left = DURATION
        self.time = QTime(0, 0, 0)  # h m s ms
        self.setup_UI()

    def setup_UI(self):
        wid = QWidget()
        self.time = self.time.addSecs(self.time_left)
        self.time_label = QLabel(self.time.toString())
        self.time_descr_label = QLabel("Time")
        self.counter_descr_label = QLabel("Counter:")
        self.counter_label = QLabel(str(self.counter))

        self.start_stop_btn = QPushButton("Start")
        self.start_stop_btn.clicked.connect(self.pressed_start)
        self.done_btn = QPushButton("Done")
        self.done_btn.setEnabled(False)
        self.done_btn.clicked.connect(self.pressed_done)

        hbox_1 = QHBoxLayout()
        hbox_1.addWidget(self.time_descr_label)
        hbox_1.addWidget(self.time_label)
        hbox_1.addWidget(self.start_stop_btn)

        hbox_2 = QHBoxLayout()
        hbox_2.addWidget(self.counter_descr_label)
        hbox_2.addWidget(self.counter_label)
        hbox_2.addWidget(self.done_btn)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox_1)
        vbox.addLayout(hbox_2)
        wid.setLayout(vbox)
        self.setCentralWidget(wid)

        title = "Interval Timer"
        self.setWindowTitle(title)

    def pressed_start(self):
        self.start_stop_btn.disconnect()
        self.start_stop_btn.setText("Stop")
        self.start_stop_btn.clicked.connect(self.pressed_stop)
        self.count_down()

    def pressed_stop(self):
        self.start_stop_btn.disconnect()
        self.start_stop_btn.setText("Start")
        self.start_stop_btn.clicked.connect(self.pressed_start)
        self.worker.stop()

    def pressed_done(self):
        self.done_btn.setEnabled(False)
        self.counter += 1
        self.counter_label.setText(str(self.counter))
        self.start_stop_btn.setEnabled(True)
        self.pressed_stop()
        self.reset_timer()

    def reset_timer(self):
        self.time = QTime(0, 0, 0)
        self.time_left = DURATION
        self.time = self.time.addSecs(self.time_left)
        self.time_label.setText(self.time.toString())

    def update_time_label(self):
        self.time_left -= 1
        self.time = self.time.addSecs(-1)
        self.time_label.setText(self.time.toString())

    def count_down(self):
        self.worker = CountdownThread(self.time_left)
        self.worker.time_signal.update.connect(self.update_time_label)
        self.worker.time_signal.stop.connect(self.reset_timer)
        self.worker.time_signal.finished.connect(self.alarm)
        self.worker.start()

    def alarm(self):
        self.done_btn.setEnabled(True)
        self.start_stop_btn.setEnabled(False)
        Thread(target=self.play_sound).start()
        self.show_dialog()

    def show_dialog(self):
        dialog = QDialog()
        dialog.setWindowTitle = "Time for your reps!"
        dialog_label = QLabel("Timer abgelaufen!", dialog)
        dialog_button = QPushButton("Ok", dialog)
        dialog_button.clicked.connect(dialog.accept)

        vbox = QVBoxLayout(dialog)
        vbox.addWidget(dialog_label)
        vbox.addWidget(dialog_button)
        dialog.setLayout(vbox)

        dialog.exec()

    def play_sound(self):
        playsound('src/media/shen.mp3')
Ejemplo n.º 28
0
class DialogoCargando(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.dibujar_IU()

    def dibujar_IU(self):
        self.setWindowTitle("Calculando...")
        self.setWindowModality(Qt.ApplicationModal)
        self.setSizeGripEnabled(False)
        self.setContentsMargins(10, 10, 10, 10)
        self.setFixedSize(QSize(500, 300))
        self.animacion = AnimacionCargando()
        self.texto_informativo = QLabel("")
        self.texto_informativo.setAlignment(Qt.AlignCenter)
        self.texto_informativo.setWordWrap(True)
        self.texto_tiempo = QLabel("00:00:00")
        self.texto_tiempo.setAlignment(Qt.AlignCenter)
        self.texto_tiempo.setWordWrap(True)
        self.caja_horizontal = QHBoxLayout()
        self.caja_horizontal.addStretch(1)
        self.caja_horizontal.addWidget(self.animacion)
        self.caja_horizontal.addStretch(1)
        self.caja = QVBoxLayout()
        self.caja.setAlignment(Qt.AlignCenter)
        self.caja.addStretch(4)
        self.caja.addWidget(self.texto_informativo)
        self.caja.addStretch(1)
        self.caja.addLayout(self.caja_horizontal)
        self.caja.addWidget(self.texto_tiempo)
        self.caja.addStretch(2)
        grupo = QGroupBox()
        grupo.setLayout(self.caja)
        hola = QVBoxLayout()
        hola.addWidget(grupo)
        self.setLayout(hola)
        self.reloj = QTime(0, 0, 0, 0)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.actualizar_reloj)
        self.timer.start(1000)
        self.boton_confirmar = QPushButton(QIcon("iconos/right-arrow.png"), "",
                                           self)
        self.boton_confirmar.clicked.connect(self.accept)
        self.boton_confirmar.setDefault(True)
        self.boton_confirmar.setMinimumSize(50, 22)
        self.boton_confirmar.setMaximumSize(50, 22)
        self.boton_confirmar.setVisible(False)
        self.boton_confirmar.move(400, 240)

    def setear_texto(self, texto):
        self.texto_informativo.setText(texto)

    def actualizar_reloj(self):
        self.reloj = self.reloj.addSecs(1)
        self.texto_tiempo.setText(self.reloj.toString("hh:mm:ss"))

    def mostrar_boton_confirmar(self):
        self.texto_tiempo.setVisible(False)
        self.animacion.setVisible(False)
        self.setear_texto(
            "Proceso terminado exitosamente en {0}\nA continuación podrá consultar los resultados finales"
            .format(self.reloj.toString("hh:mm:ss")))
        self.boton_confirmar.setVisible(True)

    #Es para evitar que se cierre el Dilog con la tecla ESC
    def reject(self):
        self.close()

    def closeEvent(self, event):
        event.ignore()
Ejemplo n.º 29
0
class DroneGUI(QDialog):
    global l, w

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

        # creates the terminal
        self.create_terminal()

        # create tabs
        self.create_tabs()

        # set the size policy
        self.set_size_policy()

        # palette background setting, style
        self.create_palette()

        # adds the arm, kill, unarm buttons
        # self.create_arm_kill_buttons()

        # adds the PID insert text boxes
        self.create_PID_insert()

        # adds the log
        self.create_log()

        # stream for the command line output to fill the log
        sys.stdout = Stream(newText=self.onUpdateText)

        # adds the data monitor
        self.create_data_monitor()

        # installs the event filter for 'space bar' and 'a'
        qApp.installEventFilter(self)

        # creates a button to deliver a live motor output plot graph
        self.motor_output_plot_graph_is_open = False
        self.create_motor_output_plot_button()

        # create the flight motion labels
        self.create_flight_motion_labels()

        # shows the current information of the drone
        self.drone_information()

        # add logo
        self.set_logo()

        # set up about tab
        self.show_about_info()

        # commands currently allowed in the terminal
        self.accepted_commands = {"connect", "arm", "kill", "forward",
                                  "altitude", "vehicle status", "pi status", "square"}

        # accepted IPs for the Raspberry Pi
        self.accepted_ips = {"192.168.1.1"}

        self.ssh_client = None


    def eventFilter(self, obj, event):
        if event.type() == QEvent.KeyPress:
            if event.key() == Qt.Key_Return:
                x = self.term.toPlainText().strip()
                split = x.split(' ')
                if split[0] in self.accepted_commands:
                        if split[0] == "connect":
                            if len(split) > 1:
                                if split[1] in self.accepted_ips:
                                    print("> Connecting RPi...")
                                    print("=> " + split[1])
                                    self.ssh_client = self.connect_to_pi(split[1], 22, 'admin')
                        elif split[0] == "arm":
                            print("> Arming...")
                            # self.executeCommand(self.ssh_client, 'python ./RPi_FC.py')
                self.term.clear()
        return super(DroneGUI, self).eventFilter(obj, event)


    # filters space bar to allow it to be a killswitch only
    # filters 'a' to allow it to arm the drone only
    #def eventFilter(self, obj, event):
    #     if event.type() == QEvent.KeyPress:
    #         if event.key() == Qt.Key_Space:
    #             if self.arm_button.isChecked():
    #                 print("KILL SWITCH ACTIVATED")
    #                 self.arm_button.toggle()
    #                 self.arm_button.setEnabled(False)
    #                 self.undo_killswitch_button.setEnabled(True)
    #                 self.undo_killswitch_button.setStyleSheet("background-color: yellow; color:black")
    #                 self.arm_button.setStyleSheet("background-color: Gray")
    #                 self.killswitch_button.setEnabled(False)
    #                 self.killswitch_button.setStyleSheet("background-color: Darkred; color:black")
    #                 self.curr_status.setStyleSheet("background-color: #922B3E;")
    #                 self.curr_status.setText("Inactive")
    #                 self.flight_timer.stop()
    #                 # fc.receiver.ARM = False
    #                 return True
    #             else:
    #                 return True
    #         if event.key() == Qt.Key_A:
    #             if not(self.arm_button.isChecked()):
    #                 print()
    #                 print("Initialize Arming Process...")
    #                 self.arm_button.setStyleSheet("background-color: Green")
    #                 self.undo_killswitch_button.setEnabled(False)
    #                 self.killswitch_button.setEnabled(True)
    #                 self.killswitch_button.setStyleSheet("background-color: red")
    #                 self.undo_killswitch_button.setStyleSheet("background-color:rgb(53,53,53);")
    #                 self.arm_button.setEnabled(False)
    #                 self.arm_button.setChecked(True)
    #                 self.curr_status.setStyleSheet("background-color: #507D2A")
    #                 self.curr_status.setText("Active")
    #                 self.flight_timer.start(1000)
    #                 # Since we're skipping the unlock arm button,
    #                 # fc.run()
    #                 return True
    #             else:
    #                 return True
    #     return super(DroneGUI, self).eventFilter(obj, event)

    # Connects to the IP using a port, username, and password via SSH.
    def connect_to_pi(self, ip, port, username, password="******"):
        sshClient = paramiko.SSHClient()
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        sshClient.load_system_host_keys()
        try:
            sshClient.connect(ip, port, username, password, timeout=10)
        except Exception as e:
            print(e)
            sshClient.connect(ip + ".local", port, username, password)

        return sshClient

    # Takes in an sshClient and sends the command to it
    def executeCommand(sshClient, command):
        stdin, stdout, stderr = sshClient.exec_command(command)
        print("> COMMAND:", command)

    # creates a log for the command line output
    def create_terminal(self):
        self.term = QTextEdit(self)
        self.term.move(l-260, 20)
        self.term.setFixedSize(260,22)
        self.term.setFixedHeight(18)
        self.term.moveCursor(QTextCursor.Start)
        self.term.setReadOnly(False)
        self.term.setCursorWidth(4)

    # resizes the GUI
    def set_size_policy(self):
        self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.sizePolicy.setHorizontalStretch(0)
        self.sizePolicy.setVerticalStretch(0)
        self.sizePolicy.setHeightForWidth(self.sizePolicy.hasHeightForWidth())
        self.setSizePolicy(self.sizePolicy)
        self.setMaximumSize(l, w)
        self.setMinimumSize(l, w)

    # Creates the tabs
    def create_tabs(self):
        self.tabWidget = QTabWidget(self)
        self.tabWidget.setGeometry(QRect(0, 150, l-260,w-100 ))
        self.tabWidget.setMaximumSize(QSize(l, w-100))
        self.tabWidget.setTabPosition(QTabWidget.North)
        self.tabWidget.setTabShape(QTabWidget.Rounded)
        self.tabWidget.setElideMode(Qt.ElideRight)
        self.tabWidget.setUsesScrollButtons(False)
        self.tabWidget.setDocumentMode(True)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setMovable(False)
        self.tabWidget.setTabBarAutoHide(False)
        self.data_tab = QWidget()
        self.settings_tab = QWidget()
        self.flight_pattern_tab = QWidget()
        self.about_tab = QWidget()
        self.tabWidget.addTab(self.settings_tab, "Settings")
        self.tabWidget.addTab(self.data_tab, "Data")
        self.tabWidget.addTab(self.flight_pattern_tab, "Flight Pattern")
        self.tabWidget.addTab(self.about_tab, "About")
        self.tabWidget.show()

    # Defines the palette colors
    def create_palette(self):
        self.setWindowTitle("Flight Controller")
        app.setStyle("Fusion")
        app.setFont(QFont("Helvetica"))
        dark_palette = QPalette()
        dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.WindowText, Qt.white)
        dark_palette.setColor(QPalette.Base, QColor(25, 25, 25))
        dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
        dark_palette.setColor(QPalette.ToolTipText, Qt.white)
        dark_palette.setColor(QPalette.Text, Qt.white)
        dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.ButtonText, Qt.white)
        dark_palette.setColor(QPalette.BrightText, Qt.red)
        dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.HighlightedText, Qt.black)
        app.setPalette(dark_palette)

    # # create buttons to arm, and kill, and un-kill the drone
    # def create_arm_kill_buttons(self):
    #     # button to arm the drone
    #     self.arm_button = QPushButton('ARM', self)
    #     self.arm_button.setDefault(False)
    #     self.arm_button.setAutoDefault(False)
    #     self.arm_button.setStyleSheet("background-color: green")
    #     self.arm_button.move(0, 0)
    #     self.arm_button.resize(70, 43)
    #     self.arm_button.setFont(QFont("Helvetica", 17.5))
    #     self.arm_button.setCheckable(True)
    #     self.arm_button.setEnabled(True)
    #     self.arm_button.clicked.connect(self.arm_drone)
    #     self.arm_button.setShortcut("A")
    #
    #     # button to kill the drone
    #     self.killswitch_button = QPushButton('KILL SWITCH', self)
    #     self.killswitch_button.move(l-110, 0)
    #     self.killswitch_button.setDefault(False)
    #     self.killswitch_button.setAutoDefault(False)
    #     self.killswitch_button.setFont(QFont("Helvetica", 17.0))
    #     self.killswitch_button.resize(110, 60)
    #     self.killswitch_button.clicked.connect(self.kill_motor)
    #     self.killswitch_button.setStyleSheet("background-color: red")
    #     self.killswitch_button.setEnabled(False)
    #     self.killswitch_button.setShortcut("Space")
    #
    #     # button to undo kill switch
    #     self.undo_killswitch_button = QPushButton('Unlock ARM', self)
    #     self.undo_killswitch_button.setDefault(False)
    #     self.undo_killswitch_button.setAutoDefault(False)
    #     self.undo_killswitch_button.move(l-110, 62)
    #     self.undo_killswitch_button.setFont(QFont("Helvetica", 12))
    #     self.undo_killswitch_button.resize(75, 30)
    #     self.undo_killswitch_button.clicked.connect(self.undo_killswitch)
    #     self.undo_killswitch_button.setStyleSheet("background-color:rgb(53,53,53);")
    #     self.undo_killswitch_button.setEnabled(False)
    #
    #     # button to exit the application
    #     self.exit_app_button = QPushButton('exit', self)
    #     self.exit_app_button.resize(0,0)
    #     self.exit_app_button.setShortcut("Shift+Q")
    #     self.exit_app_button.clicked.connect(self.exit_application)


    # killswitch for the drone
    def kill_motor(self):
        if self.arm_button.isChecked():
            print("KILL SWITCH ACTIVATED")
            self.flight_timer.stop()
            self.arm_button.toggle()
            self.arm_button.setEnabled(False)
            self.undo_killswitch_button.setEnabled(True)
            self.undo_killswitch_button.setStyleSheet("background-color: yellow; color:black")
            self.killswitch_button.setEnabled(False)
            self.killswitch_button.setStyleSheet("background-color: Darkred; color:black")
            self.arm_button.setStyleSheet("background-color: Gray")
            self.curr_status.setStyleSheet("background-color: #922B3E;")
            self.curr_status.setText("Inactive")
            # fc.receiver.ARM = False

    # allows the drone to be armed again
    def undo_killswitch(self):
        print("Arm button unlocked")
        self.arm_button.setEnabled(True)
        self.undo_killswitch_button.setEnabled(False)
        self.killswitch_button.setStyleSheet("background-color: red")
        self.undo_killswitch_button.setStyleSheet("background-color: Gold")
        self.arm_button.setStyleSheet("background-color: Green")
        # fc.receiver.ARM = True

    # arms the drone
    def arm_drone(self):
        print()
        print("Initialize Arming Process...")
        self.flight_timer.start(1000)
        self.undo_killswitch_button.setEnabled(False)
        self.killswitch_button.setEnabled(True)
        self.undo_killswitch_button.setStyleSheet("background-color:rgb(53,53,53);")
        self.arm_button.setEnabled(False)
        self.curr_status.setStyleSheet("background-color: #507D2A")
        self.curr_status.setText("Active")
        # fc.run()

    # displays current drone information
    def drone_information(self):
        # widget for the drone status section
        self.drone_status = QWidget(self.settings_tab)
        self.drone_status.resize(180,110)
        self.drone_status.move(92,200)

        self.state_label = QPushButton("Drone Status", self.drone_status)
        self.state_label.setCheckable(False)
        self.state_label.setEnabled(False)
        self.state_label.setStyleSheet("background: #333332; color: white")
        self.state_label.move(0, 0)
        self.state_label.show()
        self.state_label.resize(80,20)
        self.curr_status = QPushButton("Inactive", self.drone_status)
        self.curr_status.setIcon(QIcon("Images/Icons/drone.png"))
        self.curr_status.setDefault(False)
        self.curr_status.setEnabled(False)
        self.curr_status.setStyleSheet("background-color: #922B3E;")
        self.curr_status.move(81,0)
        self.curr_status.resize(70,20)
        self.curr_P = QLineEdit(self.drone_status)
        self.curr_P.setReadOnly(True)
        self.curr_P_label = QLabel(self.drone_status)
        self.curr_P_label.move(2, 25)
        self.curr_P_label.setText("Proportional:")
        self.curr_P_label.show()
        self.curr_P.setText(str(fc.Kp))  # " ", str(fc.Ki), " ", str(fc.Kd))
        self.curr_P.move(80, 25)
        self.curr_P.resize(90,12)
        self.curr_P.show()
        self.curr_I_label = QLabel(self.drone_status)
        self.curr_I_label.move(2, 40)
        self.curr_I_label.setText("       Integral:")
        self.curr_I_label.show()
        self.curr_I = QLineEdit(self.drone_status)
        self.curr_I.setReadOnly(True)
        self.curr_I.setText(str(fc.Ki))  # " ", str(fc.Ki), " ", str(fc.Kd))
        self.curr_I.move(80, 40)
        self.curr_I.resize(90,12)
        self.curr_I.show()
        self.curr_D_label = QLabel(self.drone_status)
        self.curr_D_label.move(2, 55)
        self.curr_D_label.setText("   Derivative:")
        self.curr_D_label.show()
        self.curr_D = QLineEdit(self.drone_status)
        self.curr_D.setReadOnly(True)
        self.curr_D.setText(str(fc.Kd))  # " ", str(fc.Ki), " ", str(fc.Kd))
        self.curr_D.move(80, 55)
        self.curr_D.resize(90, 12)
        self.curr_D.show()
        self.flight_time_label = QLabel("Flight Time:", self.drone_status)
        self.flight_time_label.move(5, 85)
        self.flight_time = QLineEdit(self.drone_status)
        self.flight_time.setReadOnly(True)
        self.flight_time.move(80, 80)
        self.flight_time.setFont(QFont("Helvetica", 15))
        self.flight_time.resize(50,18)
        self.flight_timer = QTimer()
        self.time = QTime(0,0)
        self.flight_timer.timeout.connect(self.update_timer)

        self.hard_wired_button = QPushButton("Hard Wired Inputs", self.settings_tab)
        self.hard_wired_button.move(l-365,2)
        self.hard_wired_button.setStyleSheet("background-color:#002366;")
        self.hard_wired_button.clicked.connect(self.show_hard_wire_connections)

    # gets the current updated PID values
    def get_PID_value(self):
        # try:
        #     fc.Kp = np.array([float(self.Kp0_textbox.text()), float(self.Kp1_textbox.text()), float(self.Kp2_textbox.text())])
        #     fc.Ki = np.array([float(self.Ki0_textbox.text()), float(self.Ki1_textbox.text()), float(self.Ki2_textbox.text())])
        #     fc.Kd = np.array([float(self.Kd0_textbox.text()), float(self.Kd1_textbox.text()), float(self.Kd2_textbox.text())])
        # except(ValueError):
        #     print("Error: Must input values into each coordinate.")
        # else:
        #     print()
        #     print(time.strftime("   %H:%M:%S %Z"))
        #     print("Update PID Gains")
        #     print("P:    ", fc.Kp[0], " ", fc.Kp[1], " ", fc.Kp[2])
        #     print("I :    ", fc.Ki[0], " ", fc.Ki[1], " ", fc.Ki[2])
        #     print("D:    ", fc.Kd[0], " ", fc.Kd[1], " ", fc.Kd[2])
            print()

    # creates the PID text boxes, button for updating PID values
    def create_PID_insert(self):
        print()
        # widget for PID insertion
        # self.PID_widget = QWidget(self.settings_tab)
        # self.PID_widget.resize(300,200)
        # self.PID_widget.move(10,20)
        # # proportional text
        # self.onlyDouble = QDoubleValidator()
        # self.Kp0_textbox = QLineEdit(self.PID_widget)
        # self.Kp0_textbox.clearFocus()
        # self.Kp0_textbox.setValidator(self.onlyDouble)
        # self.Kp0_textbox.resize(50, 23)
        # self.Kp0_textbox.setText(str(fc.Kp[0]))
        # self.Kp1_textbox = QLineEdit(self.PID_widget)
        # self.Kp1_textbox.setValidator(self.onlyDouble)
        # self.Kp1_textbox.resize(50, 23)
        # self.Kp1_textbox.move(50,0)
        # self.Kp1_textbox.setText(str(fc.Kp[1]))
        # self.Kp2_textbox = QLineEdit(self.PID_widget)
        # self.Kp2_textbox.setValidator(self.onlyDouble)
        # self.Kp2_textbox.resize(50, 23)
        # self.Kp2_textbox.move(100, 0)
        # self.Kp2_textbox.setText(str(fc.Kp[2]))
        # # proportional label
        # self.Kp_label = QLabel(self.PID_widget)
        # self.Kp_label.setText('Proportional')
        # self.Kp_label.move(150, 0)
        # self.Kp_label.resize(85, 23)
        # self.Kp_label.setFrameShape(QFrame.Panel)
        # self.Kp_label.setFrameShadow(QFrame.Sunken)
        # self.Kp_label.setLineWidth(3)
        # self.Kp_label.setStyleSheet("background-color:rgb(53,53,53);")
        #
        # # integral text
        # self.Ki0_textbox = QLineEdit(self.PID_widget)
        # self.Ki0_textbox.move(0, 27)
        # self.Ki0_textbox.resize(50, 23)
        # self.Ki0_textbox.setValidator(self.onlyDouble)
        # self.Ki0_textbox.setText(str(fc.Ki[0]))
        # self.Ki1_textbox = QLineEdit(self.PID_widget)
        # self.Ki1_textbox.move(50, 27)
        # self.Ki1_textbox.resize(50, 23)
        # self.Ki1_textbox.setValidator(self.onlyDouble)
        # self.Ki1_textbox.setText(str(fc.Ki[1]))
        # self.Ki2_textbox = QLineEdit(self.PID_widget)
        # self.Ki2_textbox.move(100, 27)
        # self.Ki2_textbox.resize(50, 23)
        # self.Ki2_textbox.setValidator(self.onlyDouble)
        # self.Ki2_textbox.setText(str(fc.Ki[2]))
        # # integral label
        # self.Ki_label = QLabel(self.PID_widget)
        # self.Ki_label.setText('Integral')
        # self.Ki_label.move(150, 27)
        # self.Ki_label.resize(85, 23)
        # self.Ki_label.setFrameShape(QFrame.Panel)
        # self.Ki_label.setFrameShadow(QFrame.Sunken)
        # self.Ki_label.setLineWidth(3)
        # self.Ki_label.setStyleSheet("background-color:rgb(53,53,53);")
        #
        # # derivative text
        # self.Kd0_textbox = QLineEdit(self.PID_widget)
        # self.Kd0_textbox.move(0, 54)
        # self.Kd0_textbox.resize(50, 23)
        # self.Kd0_textbox.setValidator(self.onlyDouble)
        # self.Kd0_textbox.setText(str(fc.Kd[0]))
        # self.Kd1_textbox = QLineEdit(self.PID_widget)
        # self.Kd1_textbox.move(50, 54)
        # self.Kd1_textbox.resize(50, 23)
        # self.Kd1_textbox.setValidator(self.onlyDouble)
        # self.Kd1_textbox.setText(str(fc.Kd[1]))
        # self.Kd2_textbox = QLineEdit(self.PID_widget)
        # self.Kd2_textbox.move(100, 54)
        # self.Kd2_textbox.resize(50, 23)
        # self.Kd2_textbox.setValidator(self.onlyDouble)
        # self.Kd2_textbox.setText(str(fc.Kd[2]))
        # # derivative label
        # self.Kd_label = QLabel(self.PID_widget)
        # self.Kd_label.resize(85, 23)
        # self.Kd_label.setText('Derivative')
        # self.Kd_label.move(150, 54)
        # self.Kd_label.setFrameShape(QFrame.Panel)
        # self.Kd_label.setFrameShadow(QFrame.Sunken)
        # self.Kd_label.setLineWidth(3)
        # self.Kd_label.setStyleSheet("background-color:rgb(53,53,53);")
        #
        # # button to insert new PID values
        # self.insert_PID_values = QPushButton("Insert PID Gains", self.PID_widget)
        # self.insert_PID_values.setStyleSheet("background-color:	#002366;")
        # self.insert_PID_values.move(150, 80)
        # self.insert_PID_values.resize(85, 25)
        # self.insert_PID_values.setFont(QFont("Helvetica", 11.5))
        # self.insert_PID_values.setCheckable(True)
        # self.insert_PID_values.setEnabled(True)
        # self.insert_PID_values.clicked.connect(self.get_PID_value)
        #
        # # label for Roll, Pitch, Yaw
        # self.RPY = QLabel(self.PID_widget)
        # self.RPY.move(0,80)
        # self.RPY.setText(' Roll        Pitch         Yaw  ')
        # self.RPY.setFrameShape(QFrame.Panel)
        # self.RPY.setFrameShadow(QFrame.Sunken)
        # self.RPY.setLineWidth(3)
        # self.RPY.setStyleSheet("background-color:rgb(53,53,53);")

    def onUpdateText(self, text):
        cursor = self.log.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.log.setTextCursor(cursor)
        self.log.ensureCursorVisible()

    def __del__(self):
        sys.stdout = sys.__stdout__

    # creates a log for the command line output
    def create_log(self):
        self.log = QTextEdit(self)
        self.log.move(l-260, w-465)
        self.log.resize(260, w-175)
        self.log.moveCursor(QTextCursor.Start)
        self.log.ensureCursorVisible()
        self.log.setLineWrapMode(QTextEdit.FixedPixelWidth)
        self.log.setReadOnly(True)
        self.log.setLineWrapColumnOrWidth(250)
        try:
            sys.stdout = Stream(newText=self.onUpdateText)
        except AttributeError as error:
            print(error)

    # creates data monitor
    def create_data_monitor(self):
        # make QTimer
        self.qTimer = QTimer(self)


        # pi connection status
        self.pi_connection_status_is_clicked = False
        self.pi_connection_label = QPushButton("Pi Connection", self)
        self.pi_connection_label.setCheckable(False)
        self.pi_connection_label.setEnabled(False)
        self.pi_connection_label.setStyleSheet("background: #333332; color: white")
        self.pi_connection_label.move(2, 96)
        self.pi_connection_label.show()
        self.pi_connection_label.resize(80, 20)
        self.pi_connection_status = QPushButton("Offline", self)
        self.pi_connection_status.move(2,115)
        self.pi_connection_status.setDefault(False)
        self.pi_connection_status.setEnabled(False)
        self.pi_connection_status.setIcon(QIcon('Images/Icons/connection.png'))
        self.pi_connection_status.setStyleSheet("background-color: #922B3E;")

        # set interval to update
        self.qTimer.setInterval(250)

        # connect timeout signal to signal handler
        self.qTimer.timeout.connect(self.get_sensor_value)

        self.qTimer.start()

    # creates the plot graph button
    def create_motor_output_plot_button(self):
        self.plot_button = QPushButton("Motor Output Plot Graph", self.data_tab)
        self.plot_button.setStyleSheet("background-color:#002366;")
        self.plot_button.setIcon(QIcon("Images/Icons/line_graph.png"))
        self.plot_button.clicked.connect(self.create_motor_output_plot)
        self.plot_button.move(2,20)
        # time stamp for the graph's delta time initialization
        self.timestamp = time.time()

    # function to start the timer for QTimer
    def start_timer(self):
        if self.timer.isActive():
            # sets the Y Range for the graph
            self.pw.setYRange(-2, 2)
            print("Graph is already updating at ", self.timer.interval(), " ms between data retrievals")
        else:
            self.timer.start()
            # sets the Y Range for the graph
            self.pw.setYRange(-2, 2)

    # create a live motor output plot graph
    def create_motor_output_plot(self):
        self.motor_output_plot_graph_is_open = True
        # widget for the motor output graph
        self.motor_output_graph_widget = QWidget(self.data_tab)
        self.motor_output_graph_widget.resize(l - 260, w - 100)
        self.motor_output_graph_widget.show()
        # motor 1 output title
        self.motor_1_output_title = QPushButton("Motor 1 Output", self.motor_output_graph_widget)
        self.motor_1_output_title.move(l - 400, 60)
        self.motor_1_output_title.setStyleSheet("background: black; color: gray;")
        self.motor_1_output_title.setEnabled(False)
        self.motor_1_output_title.setCheckable(False)
        self.motor_1_output_title.setFixedSize(90, 13)
        self.motor_1_output_title.setFont(QFont("Helvetica", 11.5))
        self.motor_1_output_title.show()

        self.motor_1_output_title_color = QLabel(self.motor_output_graph_widget)
        self.motor_1_output_title_color.setPixmap(QPixmap('Images/Icons/red_square.png'))
        self.motor_1_output_title_color.move(l - 413, 60)
        self.motor_1_output_title_color.show()

        # motor 2 output title
        self.motor_2_output_title = QPushButton("Motor 2 Output", self.motor_output_graph_widget)
        self.motor_2_output_title_color = QLabel(self.motor_output_graph_widget)
        self.motor_2_output_title_color.setPixmap(QPixmap('Images/Icons/blue_square.png'))
        self.motor_2_output_title_color.move(l - 413, 90)
        self.motor_2_output_title_color.show()
        self.motor_2_output_title.move(l - 400, 90)
        self.motor_2_output_title.setStyleSheet("background: black; color: gray;")
        self.motor_2_output_title.setEnabled(False)
        self.motor_2_output_title.setCheckable(False)
        self.motor_2_output_title.setFixedSize(90, 13)
        self.motor_2_output_title.setFont(QFont("Helvetica", 11.5))
        self.motor_2_output_title.show()

        # motor 3 output title
        self.motor_3_output_title = QPushButton("Motor 3 Output", self.motor_output_graph_widget)
        self.motor_3_output_title_color = QLabel(self.motor_output_graph_widget)
        self.motor_3_output_title_color.setPixmap(QPixmap('Images/Icons/yellow_square.png'))
        self.motor_3_output_title_color.move(l - 413, 120)
        self.motor_3_output_title_color.show()
        self.motor_3_output_title.move(l - 400, 120)
        self.motor_3_output_title.setStyleSheet("background: black; color: gray;")
        self.motor_3_output_title.setEnabled(False)
        self.motor_3_output_title.setCheckable(False)
        self.motor_3_output_title.setFixedSize(90, 13)
        self.motor_3_output_title.setFont(QFont("Helvetica", 11.5))
        self.motor_3_output_title.show()

        # motor 4 output title
        self.motor_4_output_title = QPushButton("Motor 4 Output", self.motor_output_graph_widget)
        self.motor_4_output_title_color = QLabel(self.motor_output_graph_widget)
        self.motor_4_output_title_color.setPixmap(QPixmap('Images/Icons/purple_square.png'))
        self.motor_4_output_title_color.move(l - 413, 150)
        self.motor_4_output_title_color.show()
        self.motor_4_output_title.move(l - 400, 150)
        self.motor_4_output_title.setStyleSheet("background: black; color: gray;")
        self.motor_4_output_title.setEnabled(False)
        self.motor_4_output_title.setCheckable(False)
        self.motor_4_output_title.setFixedSize(90, 13)
        self.motor_4_output_title.setFont(QFont("Helvetica", 11.5))
        self.motor_4_output_title.show()

        # motor 1 output
        self.motor_1_output = QLabel(str(fc.motor_output[0]), self.motor_output_graph_widget)
        self.motor_1_output.move(l - 395, 75)
        self.motor_1_output.resize(70, 12)
        self.motor_1_output.show()

        # motor 2 output
        self.motor_2_output = QLabel(str(fc.motor_output[1]), self.motor_output_graph_widget)
        self.motor_2_output.move(l - 395, 105)
        self.motor_2_output.resize(70, 12)
        self.motor_2_output.show()

        # motor 3 output
        self.motor_3_output = QLabel(str(fc.motor_output[2]), self.motor_output_graph_widget)
        self.motor_3_output.move(l - 395, 135)
        self.motor_3_output.resize(70, 12)
        self.motor_3_output.show()

        # motor 4 output
        self.motor_4_output = QLabel(str(fc.motor_output[3]), self.motor_output_graph_widget)
        self.motor_4_output.move(l - 395, 165)
        self.motor_4_output.resize(70, 12)
        self.motor_4_output.show()


        self.pw = pg.PlotWidget(self.motor_output_graph_widget)
        self.pw.showGrid(x=True,y=True)
        self.pw.setTitle('Live Update Graph (demonstration with sin function)')
        self.pw.move(0,20)
        self.pw.resize(l/2,w/2)
        self.pw.show()
        self.pw.setLabel('left', 'Motor Output')
        self.pw.setLabel('bottom', 'Time', units='s')
        self.pw.setAntialiasing(True)
        # sets the Y Range for the graph
        self.pw.setYRange(-2,2)
        self.timer = pg.QtCore.QTimer(self)

        self.stop_plot_button = QPushButton("Pause", self.motor_output_graph_widget)
        self.stop_plot_button.setStyleSheet("background-color:#002366;")
        self.stop_plot_button.setIcon(QIcon('Images/Icons/stop.png'))
        self.stop_plot_button.clicked.connect(self.timer.stop)
        self.stop_plot_button.resize(80,20)
        self.stop_plot_button.move(20, 0)
        self.stop_plot_button.show()

        self.start_plot_button = QPushButton("Start", self.motor_output_graph_widget)
        self.start_plot_button.setIcon(QIcon('Images/Icons/play.png'))
        self.start_plot_button.resize(80,20)
        self.start_plot_button.setStyleSheet("background-color:#002366;")
        self.start_plot_button.clicked.connect(self.start_timer)
        self.start_plot_button.move(l/2-110,0)
        self.start_plot_button.show()

        # buffer size for the data
        self.buffer = 200
        # queue to get the current delta time and values
        self.queue = Queue(self.buffer)
        # deque containing the values
        self.values_1 = deque([], maxlen=self.buffer)
        self.values_2 = deque([], maxlen=self.buffer)
        self.values_3 = deque([], maxlen = self.buffer)
        self.values_4 = deque([], maxlen=self.buffer)
        self.values_5 = deque([], maxlen=self.buffer)

        # deque containing the delta times
        self.times = deque([], maxlen=self.buffer)

        def update():
            # current delta time
            t = time.time() - self.timestamp

            # value(s) that we want to track
            v1 = fc.motor_output[0]
            v2 = fc.motor_output[1]
            v3 = fc.motor_output[2]
            v4 = fc.motor_output[3]
            # demonstration
            v5 = np.sin(t)


            # put the data into queue
            self.queue.put([t,v1,v2,v3,v4,v5])

            # get the data from the queue. Will wait until item is available
            data = self.queue.get(True, None)

            # append data in each deque
            self.times.append(data[0])
            self.values_1.append(data[1])
            self.values_2.append(data[2])
            self.values_3.append(data[3])
            self.values_4.append(data[4])
            self.values_5.append(data[5])


            # draw the incoming data
            self.pw.clear()
            self.pw.plot(x=list(self.times)[-self.buffer:], y=list(self.values_1)[-self.buffer:],pen='r')
            self.pw.plot(x=list(self.times)[-self.buffer:], y=list(self.values_2)[-self.buffer:],pen='b')
            self.pw.plot(x=list(self.times)[-self.buffer:], y=list(self.values_3)[-self.buffer:],pen='y')
            self.pw.plot(x=list(self.times)[-self.buffer:], y=list(self.values_4)[-self.buffer:], pen='m')
            self.pw.plot(x=list(self.times)[-self.buffer:], y=list(self.values_5)[-self.buffer:], pen='w')

        self.timer.timeout.connect(update)
        # length between updates (in ms)
        self.timer.start(2)

        # gets the sensor's value

    def get_sensor_value(self):

        # get's the motor output values
        if self.motor_output_plot_graph_is_open is True:
            self.motor_1_output.setText(str(fc.motor_output[0]))
            self.motor_2_output.setText(str(fc.motor_output[1]))
            self.motor_3_output.setText(str(fc.motor_output[2]))
            self.motor_4_output.setText(str(fc.motor_output[3]))

        # determines the status of the pi connection
        if fc.pi_online:
            self.pi_connection_status.setStyleSheet("background-color: #507D2A")
            self.pi_connection_status.setText("Online")
            self.pi_connection_status_is_clicked = True
        elif not fc.pi_online and self.pi_connection_status_is_clicked:
            self.pi_connection_status.setStyleSheet("background-color: #922B3E")
            self.pi_connection_status.setText("Offline")
            self.pi_connection_status_is_clicked = False

        # gets the current PID
        self.curr_P.setText(str(fc.Kp))
        self.curr_I.setText(str(fc.Ki))
        self.curr_D.setText(str(fc.Kd))

    # creates labels for the flight motion patterns
    def create_flight_motion_labels(self):
        # Widget for the flight pattern buttons
        self.flight_pattern_widget = QWidget(self.flight_pattern_tab)
        self.flight_pattern_widget.resize(200,200)

        self.flight_motion_label = QLabel(self.flight_pattern_widget)
        self.flight_motion_label.setFrameShape(QFrame.StyledPanel)
        self.flight_motion_label.setFrameShadow(QFrame.Raised)
        self.flight_motion_label.move(2,20)
        self.flight_motion_label.setText("Flight Motion Pattern")

        self.square_pattern = QPushButton("Square", self.flight_pattern_widget)
        self.square_pattern.setIcon(QIcon('Images/Icons/square.png'))
        self.square_pattern.move(2,35)
        self.square_pattern.clicked.connect(self.do_square_pattern)
        self.square_pattern.setStyleSheet("background-color:#002366;")

    # conducts the square pattern
    def do_square_pattern(self):
        print("Completing Square Flight Motion Pattern...")
        print("[Currently Under Development]")

    # exits the application
    def exit_application(self):
        DroneGUI.close(self)

    # updates the flight timer
    def update_timer(self):
        self.time = self.time.addSecs(1)
        self.flight_time.setText(self.time.toString("mm:ss"))

    # sets the logos for ARC and raspberry pi
    def set_logo(self):
        self.arc_logo = QLabel(self)
        self.arc_logo.setPixmap(QPixmap('Images/CUARClogo.png'))
        self.arc_logo.move(l-600,0)

        self.pi_logo = QLabel(self)
        self.pi_logo.setPixmap(QPixmap('Images/Icons/raspberry_pi_logo.png'))
        self.pi_logo.move(87,105)

    # shows pop up for the hard wire connections
    def show_hard_wire_connections(self):
        self.window = QDialog(self.settings_tab)
        self.window.setWindowTitle("Settings")
        self.window.resize(145,405)
        self.window.move(l - 408, 247)
        self.window.show()

        self.gpio_label = QPushButton("GPIO Reference", self.window)
        self.gpio_label.setCheckable(False)
        self.gpio_label.setEnabled(False)
        self.gpio_label.move(24,1)
        self.gpio_label.show()
        self.gpio_label.setStyleSheet("background: #333332; color: white")

        self.motor_1_label_pic = QLabel(self.window)
        self.motor_1_label_pic.setPixmap((QPixmap('Images/Icons/gear.png')))
        self.motor_1_label_pic.move(1,28)
        self.motor_1_label_pic.show()
        self.motor_1_label = QLabel("Motor 1:", self.window)
        self.motor_1_label.move(18,30)
        self.motor_1_label.show()

        self.motor_1_gpio = QLineEdit(self.window)
        self.motor_1_gpio.setReadOnly(True)
        self.motor_1_gpio.move(90,28)
        self.motor_1_gpio.resize(30,12)
        self.motor_1_gpio.show()
        self.motor_1_gpio.setText(str(fc.motor.MOTOR1))

        self.motor_2_label_pic = QLabel(self.window)
        self.motor_2_label_pic.setPixmap((QPixmap('Images/Icons/gear.png')))
        self.motor_2_label_pic.move(1, 48)
        self.motor_2_label_pic.show()
        self.motor_2_label = QLabel("Motor 2:", self.window)
        self.motor_2_label.move(18, 50)
        self.motor_2_label.show()

        self.motor_2_gpio = QLineEdit(self.window)
        self.motor_2_gpio.setReadOnly(True)
        self.motor_2_gpio.move(90, 48)
        self.motor_2_gpio.resize(30, 12)
        self.motor_2_gpio.show()
        self.motor_2_gpio.setText(str(fc.motor.MOTOR2))

        self.motor_3_label_pic = QLabel(self.window)
        self.motor_3_label_pic.setPixmap((QPixmap('Images/Icons/gear.png')))
        self.motor_3_label_pic.move(1, 68)
        self.motor_3_label_pic.show()
        self.motor_3_label = QLabel("Motor 3:", self.window)
        self.motor_3_label.move(18, 70)
        self.motor_3_label.show()

        self.motor_3_gpio = QLineEdit(self.window)
        self.motor_3_gpio.setReadOnly(True)
        self.motor_3_gpio.move(90, 68)
        self.motor_3_gpio.resize(30, 12)
        self.motor_3_gpio.show()
        self.motor_3_gpio.setText(str(fc.motor.MOTOR3))

        self.motor_4_label_pic = QLabel(self.window)
        self.motor_4_label_pic.setPixmap((QPixmap('Images/Icons/gear.png')))
        self.motor_4_label_pic.move(1, 88)
        self.motor_4_label_pic.show()
        self.motor_4_label = QLabel("Motor 4:", self.window)
        self.motor_4_label.move(18, 90)
        self.motor_4_label.show()

        self.motor_4_gpio = QLineEdit(self.window)
        self.motor_4_gpio.setReadOnly(True)
        self.motor_4_gpio.move(90, 88)
        self.motor_4_gpio.resize(30, 12)
        self.motor_4_gpio.show()
        self.motor_4_gpio.setText(str(fc.motor.MOTOR4))

        self.receiver_1_label = QLabel("Receiver 1:", self.window)
        self.receiver_1_label.move(18, 110)
        self.receiver_1_label.show()
        self.receiver_1_label_pic = QLabel(self.window)
        self.receiver_1_label_pic.setPixmap((QPixmap("Images/Icons/receiver.png")))
        self.receiver_1_label_pic.move(1, 107)
        self.receiver_1_label_pic.show()

        self.receiver_1_gpio = QLineEdit(self.window)
        self.receiver_1_gpio.setReadOnly(True)
        self.receiver_1_gpio.move(90,108)
        self.receiver_1_gpio.resize(30,12)
        self.receiver_1_gpio.show()
        self.receiver_1_gpio.setText(str(fc.receiver.RECEIVER_CH1))

        self.receiver_2_label = QLabel("Receiver 2:", self.window)
        self.receiver_2_label.move(18, 130)
        self.receiver_2_label.show()
        self.receiver_2_label_pic = QLabel(self.window)
        self.receiver_2_label_pic.setPixmap((QPixmap("Images/Icons/receiver.png")))
        self.receiver_2_label_pic.move(1, 127)
        self.receiver_2_label_pic.show()

        self.receiver_2_gpio = QLineEdit(self.window)
        self.receiver_2_gpio.setReadOnly(True)
        self.receiver_2_gpio.move(90, 128)
        self.receiver_2_gpio.resize(30, 12)
        self.receiver_2_gpio.show()
        self.receiver_2_gpio.setText(str(fc.receiver.RECEIVER_CH2))

        self.receiver_3_label = QLabel("Receiver 3:", self.window)
        self.receiver_3_label.move(18, 150)
        self.receiver_3_label.show()
        self.receiver_3_label_pic = QLabel(self.window)
        self.receiver_3_label_pic.setPixmap((QPixmap("Images/Icons/receiver.png")))
        self.receiver_3_label_pic.move(1, 147)
        self.receiver_3_label_pic.show()

        self.receiver_3_gpio = QLineEdit(self.window)
        self.receiver_3_gpio.setReadOnly(True)
        self.receiver_3_gpio.move(90, 148)
        self.receiver_3_gpio.resize(30, 12)
        self.receiver_3_gpio.show()
        self.receiver_3_gpio.setText(str(fc.receiver.RECEIVER_CH3))

        self.receiver_4_label = QLabel("Receiver 4:", self.window)
        self.receiver_4_label.move(18, 170)
        self.receiver_4_label.show()
        self.receiver_4_label_pic = QLabel(self.window)
        self.receiver_4_label_pic.setPixmap((QPixmap("Images/Icons/receiver.png")))
        self.receiver_4_label_pic.move(1, 167)
        self.receiver_4_label_pic.show()

        self.receiver_4_gpio = QLineEdit(self.window)
        self.receiver_4_gpio.setReadOnly(True)
        self.receiver_4_gpio.move(90, 168)
        self.receiver_4_gpio.resize(30, 12)
        self.receiver_4_gpio.show()
        self.receiver_4_gpio.setText(str(fc.receiver.RECEIVER_CH4))

        self.receiver_5_label = QLabel("Receiver 5:", self.window)
        self.receiver_5_label.move(18, 190)
        self.receiver_5_label.show()
        self.receiver_5_label_pic = QLabel(self.window)
        self.receiver_5_label_pic.setPixmap((QPixmap("Images/Icons/receiver.png")))
        self.receiver_5_label_pic.move(1, 187)
        self.receiver_5_label_pic.show()

        self.receiver_5_gpio = QLineEdit(self.window)
        self.receiver_5_gpio.setReadOnly(True)
        self.receiver_5_gpio.move(90, 188)
        self.receiver_5_gpio.resize(30, 12)
        self.receiver_5_gpio.show()
        self.receiver_5_gpio.setText(str(fc.receiver.RECEIVER_CH5))

        self.gpio_label = QPushButton("PWM Frequency (Hz)", self.window)
        self.gpio_label.setCheckable(False)
        self.gpio_label.setEnabled(False)
        self.gpio_label.move(2, 210)
        self.gpio_label.show()
        self.gpio_label.setStyleSheet("background: #333332; color: white")

        self.hz_pic = QLabel(self.window)
        self.hz_pic.setPixmap(QPixmap("Images/Icons/freq.png"))
        self.hz_pic.move(70,234)
        self.hz_pic.show()
        self.hz_count = QLineEdit(self.window)
        self.hz_count.setReadOnly(True)
        self.hz_count.move(84, 235)
        self.hz_count.resize(40, 12)
        self.hz_count.show()
        self.hz_count.setText(str(fc.motor.PWM_frequency))

        self.gpio_label = QPushButton("MPU6050 Address", self.window)
        self.gpio_label.setCheckable(False)
        self.gpio_label.setEnabled(False)
        self.gpio_label.move(18, 350)
        self.gpio_label.show()
        self.gpio_label.setStyleSheet("background: #333332; color: white")

        self.imu_pic = QLabel(self.window)
        self.imu_pic.setPixmap(QPixmap("Images/Icons/imu.png"))
        self.imu_pic.move(81, 374)
        self.imu_pic.show()

        self.mpu_address = QLineEdit(self.window)
        self.mpu_address.setReadOnly(True)
        self.mpu_address.move(95, 374)
        self.mpu_address.resize(30, 12)
        self.mpu_address.show()
        self.mpu_address.setText(str(fc.imu.mpu6050_handle))

        # sample time
        self.sample_time_label = QPushButton("Sample Time (ms)", self.window)
        self.sample_time_label.setCheckable(False)
        self.sample_time_label.setEnabled(False)
        self.sample_time_label.move(20, 300)
        self.sample_time_label.show()
        self.sample_time = QLineEdit(self.window)
        self.sample_time.setReadOnly(True)
        self.sample_time.resize(50, 12)
        self.sample_time.move(75, 324)
        self.sample_time.show()
        self.sample_time.setText(str(fc.imu.sample_time))
        self.sample_time_label.setStyleSheet("background: #333332; color: white")
        self.sample_time_pic = QLabel(self.window)
        self.sample_time_pic.setPixmap(QPixmap("Images/Icons/clock.png"))
        self.sample_time_pic.move(58, 323)
        self.sample_time_pic.show()

        # PID input/output limitations
        self.io_lim_label = QPushButton("PID Output Limits", self.window)
        self.io_lim_label.setCheckable(False)
        self.io_lim_label.setEnabled(False)
        self.io_lim_label.move(23, 258)
        self.io_lim_label.show()

        self.io_lim_lower = QLineEdit(self.window)
        self.io_lim_lower.setReadOnly(True)
        self.io_lim_lower.resize(38,12)
        self.io_lim_lower.move(24, 282)
        self.io_lim_lower.show()
        self.io_lim_lower.setText(str(fc.imu.output_min))
        self.io_lim_pic_dwn = QLabel(self.window)
        self.io_lim_pic_dwn.setPixmap(QPixmap("Images/Icons/down_arrow.png"))
        self.io_lim_pic_dwn.move(9, 280)
        self.io_lim_pic_dwn.show()

        self.io_lim_hi = QLineEdit(self.window)
        self.io_lim_hi.setReadOnly(True)
        self.io_lim_hi.resize(38, 12)
        self.io_lim_hi.move(87, 282)
        self.io_lim_hi.show()
        self.io_lim_hi.setText(str(fc.imu.output_max))
        self.io_lim_pic_up = QLabel(self.window)
        self.io_lim_pic_up.setPixmap(QPixmap("Images/Icons/up_arrow.png"))
        self.io_lim_pic_up.move(72, 280)
        self.io_lim_pic_up.show()

    def show_about_info(self):
        self.about_websites = QWidget(self.about_tab)
        self.about_websites.move(10,10)
        self.about_arc_label = QPushButton("ARC", self.about_websites)
        self.about_arc_label.setCheckable(False)
        self.about_arc_label.setEnabled(False)
        self.about_arc_label.move(0, 10)
        self.about_arc_label.show()
        self.arc_website = QLabel(self.about_websites)
        self.arc_website.move(2,36)
        self.arc_website.setText('<a href="http://CUAerialRobotics.github.io/">Aerial Robotics Team</a>')
        self.arc_website.setOpenExternalLinks(True)
        self.arc_website.show()
        self.arc_img = QLabel(self.about_websites)
        self.arc_img.setPixmap(QPixmap('Images/CUARC_about_logo.png'))
        self.arc_img.move(130,0)
        self.arc_img.show()

        self.about_git_label = QPushButton("GitHub", self.about_websites)
        self.about_git_label.setCheckable(False)
        self.about_git_label.setEnabled(False)
        self.about_git_label.move(0, 100)
        self.about_git_label.show()
        self.arc_website_git = QLabel(self.about_websites)
        self.arc_website_git.move(2, 126)
        self.arc_website_git.setText(
            '<a href="https://github.com/CornellAerialRobotics/">GitHub</a>')
        self.arc_website_git.setOpenExternalLinks(True)
        self.arc_website_git.show()
        self.git_img = QLabel(self.about_websites)
        self.git_img.setPixmap(QPixmap('Images/GitHub_logo.png'))
        self.git_img.move(130, 82)
        self.git_img.show()

        self.about_comp_label = QPushButton("Competition", self.about_websites)
        self.about_comp_label.setCheckable(False)
        self.about_comp_label.setEnabled(False)
        self.about_comp_label.move(0, 180)
        self.about_comp_label.show()
        self.comp_website = QLabel(self.about_websites)
        self.comp_website.move(2, 204)
        self.comp_website.setText(
            '<a href="http://www.aerialroboticscompetition.org/">IARC</a>')
        self.comp_website.setOpenExternalLinks(True)
        self.comp_website.show()
        self.comp_website_rules = QLabel(self.about_websites)
        self.comp_website_rules.move(2, 224)
        self.comp_website_rules.setText(
            '<a href="http://www.aerialroboticscompetition.org/rules.php">Mission 8 Rules</a>')
        self.comp_website_rules.setOpenExternalLinks(True)
        self.comp_website_rules.show()
        self.iarc_img = QLabel(self.about_websites)
        self.iarc_img.setPixmap(QPixmap('Images/IARC_logo.png'))
        self.iarc_img.move(130, 174)
        self.iarc_img.show()

        self.about_school_label = QPushButton("School", self.about_websites)
        self.about_school_label.setCheckable(False)
        self.about_school_label.setEnabled(False)
        self.about_school_label.move(0, 274)
        self.about_school_label.show()
        self.school_website = QLabel(self.about_websites)
        self.school_website.move(2, 298)
        self.school_website.setText(
            '<a href="https://www.cornell.edu/">Cornell University</a>')
        self.school_website.setOpenExternalLinks(True)
        self.school_website.show()
        self.cu_img = QLabel(self.about_websites)
        self.cu_img.setPixmap(QPixmap('Images/CU_logo.png'))
        self.cu_img.move(130, 260)
        self.cu_img.show()
Ejemplo n.º 30
0
class StationView(QMainWindow):
    def __init__(self, model: StationModel, station_controller: StationController, frame_drawer: FrameDrawer,
                 config: dict):
        self.__config = config

        self.model = model
        self.station_controller = station_controller
        self.frame_drawer = frame_drawer

        self.ui = uic.loadUi(Path(self.__config['resources_path']['ui']))
        self.time = QTime(0, 0, 0, 0)
        self.update_timer = QTimer()
        self.update_timer.start(100)
        self.update_timer.timeout.connect(self.update)

        self.ui.StartButton.clicked.connect(self.start_robot)
        self.ui.StartButton.clicked.connect(self.__display_start_label)
        self.ui.StopButton.clicked.connect(self.stop_robot)

        super(StationView, self).__init__()

    def start_robot(self):
        self.station_controller.start_robot()

    def stop_robot(self):
        subprocess.run(['ssh', '[email protected]', 'pkill', 'python3'])

    def update(self):
        self.station_controller.update()

        self.__draw_environment(self.model.frame)

        # update ui with model
        self.__update_timer_display()

        if self.model.world_camera_is_on:
            self.__display_world_camera_image()

        if self.model.country_code is not None:
            self.__display_flag()
            self.__display_country_name()
            self.__display_next_cube_color()

        if self.model.current_state == State.FINISHED:
            self.__display_done_label()
            self.update_timer.stop()

    def __update_timer_display(self):
        t = self.time.addSecs(self.model.passed_time)
        display_time = t.toString()
        self.ui.lcdNumber.display(display_time)

    def __display_start_label(self):
        self.ui.StartedLabel.setText("Go")
        self.ui.StartedLabel.setStyleSheet('font: 32pt;')

    def __display_done_label(self):
        self.ui.StartedLabel.setText("Done")

    def __display_world_camera_image(self):
        resized_image = cv2.resize(self.model.frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
        image = QtGui.QImage(resized_image, resized_image.shape[1], resized_image.shape[0],
                             resized_image.shape[1] * resized_image.shape[2],
                             QtGui.QImage.Format_RGB888)
        pixmap = QtGui.QPixmap()
        pixmap.convertFromImage(image.rgbSwapped())
        self.ui.videoLabel.setPixmap(pixmap)

    def __display_flag(self):
        image_path: Path = Path(self.__config['resources_path']['country_flag']
                                .format(country=self.model.country.name))

        flag_pixmap = QtGui.QPixmap(str(image_path))
        self.ui.flagPicture.setPixmap(flag_pixmap)
        self.ui.flagPicture.setMask(flag_pixmap.mask())
        self.ui.flagPicture.show()

    def __display_country_name(self):
        self.ui.CountryName.setText(self.model.country.name)

    def __display_next_cube_color(self):
        if self.model.next_cube is None:
            self.ui.cube_label.setStyleSheet('background-color:' + Color.TRANSPARENT.name.lower() + ';')
        else:
            self.ui.cube_label.setStyleSheet('background-color:' + self.model.next_cube.color.name.lower() + ';')
        self.ui.cube_label.show()

    def __draw_environment(self, frame):
        if self.__config['user_interface']['draw_vision_cubes']:
            if self.model.vision_environment is not None:
                self.frame_drawer.draw_vision_environment(frame, self.model.vision_environment)

        if self.model.real_world_environment is not None:
            self.frame_drawer.draw_real_world_environment(frame, self.model.real_world_environment)

        if self.model.real_path is not None and self.model.real_path:
            self.frame_drawer.draw_real_path(frame, self.model.real_path)

        if self.model.original_planned_path is not None and self.model.original_planned_path:
            self.frame_drawer.draw_original_planned_path(frame, self.model.original_planned_path)

        if self.model.revised_planned_path is not None and self.model.revised_planned_path:
            self.frame_drawer.draw_revised_planned_path(frame, self.model.revised_planned_path)

        if self.model.robot is not None:
            self.frame_drawer.draw_robot(frame, self.model.robot)
Ejemplo n.º 31
0
class MyTrackGui(base_1, form_1):
    def __init__(self):
        super(base_1, self).__init__()
        state_valve1 = False
        state_valve2 = False
        state_valve3 = False
        state_valve4 = False
        self.setupUi(self)
        self.task_start.clicked.connect(self.clicked_task_start)
        self.task_stop.clicked.connect(self.clicked_task_stop)
        self.trial_total.setText('90')
        # Connect valves
        self.valve1.clicked.connect(self.clicked_valve1)
        self.valve2.clicked.connect(self.clicked_valve2)
        self.valve3.clicked.connect(self.clicked_valve3)
        self.valve4.clicked.connect(self.clicked_valve4)
        # self.valve2.setChecked(True)
        # self.valve4.setChecked(True)
        # Connect clock
        self.task_timer.setNumDigits(6)
        self.currentTime = QTime(0, 0, 0)
        self.task_timer.display(self.currentTime.toString("mm:ss"))
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.clock_tick)
        # Connect laser state
        self.laser_state.setText(str('OFF'))
        # Video
        self.timer_video = QTimer(self)
        self.timer_video.timeout.connect(self.update_frame)
        self.window_video = OwnImageWidget(self.window_video)
        self.window_width = self.window_video.frameSize().width()
        self.window_height = self.window_video.frameSize().height()

    def clock_tick(self):
        self.currentTime = self.currentTime.addSecs(1)
        self.task_timer.display(self.currentTime.toString('mm:ss'))

    def update_frame(self):
        if not q.empty():
            frame = q.get()
            img = frame["img"]
            img_height, img_width, img_colors = img.shape
            # scale_w = float(self.window_width) / float(img_width)
            # scale_h = float(self.window_height) / float(img_height)
            scale_w = 240 / float(img_width)
            scale_h = 141 / float(img_height)
            scale = min([scale_w, scale_h])
            if scale == 0:
                scale = 1
            img = cv2.resize(img,
                             None,
                             fx=scale,
                             fy=scale,
                             interpolation=cv2.INTER_CUBIC)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            height, width, bpc = img.shape
            bpl = bpc * width
            image = QtGui.QImage(img.data, width, height, bpl,
                                 QtGui.QImage.Format_RGB888)
            self.window_video.setImage(image)

    def clicked_task_start(self):
        global state, trial_current, idx_sensor, running
        # video
        running = True
        capture_thread.start()
        self.timer_video.start(1)
        # clock
        self.timer_clock.start(1000)
        # maze parameters
        trial_total = float(self.trial_total.text())
        time_high = float(self.laser_hightime.text())
        time_low = float(self.laser_lowtime.text())
        sensor_on = float(self.laser_on.text())
        sensor_off = float(self.laser_off.text())
        self.laser_state.setText(str('IDLE'))

        # main arduino code
        if state:
            read_sensor()
            if 30 <= trial_current < 60:
                while True:
                    self.laser_state.setText(str('ON'))
                    if sensor_on <= idx_sensor <= sensor_off:
                        trigger_laser(time_high, time_low)
                    break

            if trial_current == trial_total:
                state = 0
            self.task_stop.clicked.connect(self.clicked_task_stop)

    def clicked_task_stop(self):
        global state
        state = 0
        self.timer_clock.stop()
        self.timer_video.stop()
        self.laser_state.setText(str('OFF'))
        return state

    def clicked_valve1(self):
        global state_valve1
        state_valve1 = True
        return state_valve1

    def clicked_valve2(self):
        global state_valve2
        state_valve2 = True
        return state_valve2

    def clicked_valve3(self):
        global state_valve3
        state_valve3 = True
        return state_valve3

    def clicked_valve4(self):
        global state_valve4
        state_valve4 = True
        return state_valve4
Ejemplo n.º 32
0
class Main_Page(QMainWindow, Ui_MainWindow, QWidget):
    def __init__(self, h, m, s, window): 
        super().__init__()
        self.setWindowTitle('Таймер')
        
        with open("changes.txt", "rt", encoding="utf8") as f:
            text = f.read().split(';')
        color = text[0].replace('(', '').replace(')', '')
        self.note = text[1]
        color = [int(i) for i in color.split(', ')]
        current_color = QColor(color[0], color[1], color[2], color[3])
        self.setStyleSheet("QMainWindow { background-color: %s }" % 
                           current_color.name())
        
        self.h = h
        self.m = m
        self.s = s
        self.window = window
        self.play_check = False 
        self.setupUi(self)
        self.setGeometry(300, 100, 800, 600)        
        self.current_timer = QTimer(self)
        self.current_timer.setSingleShot(True)
        self.current_timer.timeout.connect(self.runTime)
        self.current_timer.start(100)
        self.Pause.clicked.connect(self.pauseTime)
        self.Stop.clicked.connect(self.stopTime)
        self.Melody.clicked.connect(self.open_mel_win)
 
    def runTime(self):
        self.t1 = QTime(self.h, self.m, self.s, 0)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showTime)
        self.timer.start(1000) 
        self.showTime()
        
    def showTime(self):
        if [self.t1.hour(), self.t1.minute(), self.t1.second()] == [0, 0, 0]:
            self.timer.stop()
            self.Melody.setEnabled(False)
            if self.note != '':
                self.Melody.setText(self.note)
            self.Pause.setEnabled(False)
            mixer.init()
            mixer.music.load(self.window.mel.ringtone)
            self.play_check = True
            mixer.music.play(-1)
        text = self.t1.toString('hh:mm:ss')
        if (self.t1.second() % 2) != 0:
            text = text[:2] + ' ' + text[3:5] + ' ' + text[6:]
        self.t1 = self.t1.addSecs(-1)
        self.Time.display(text)
    
    def pauseTime(self):
        if self.timer.isActive():
            self.timer.stop()
            self.Pause.setText('Дальше')
        else:
            self.Pause.setText('Пауза')
            milisec_timer = QTimer(self)
            milisec_timer.setSingleShot(True)
            self.h = self.t1.hour()
            self.m = self.t1.minute()
            self.s = self.t1.second()
            milisec_timer.start(500)
            milisec_timer.timeout.connect(self.runTime)
    
    def stopTime(self):
        if self.play_check:
            mixer.music.stop()
        self.timer.stop()
        self.Pause.setDisabled(False)
        self.Melody.setDisabled(False)
        self.current_timer.stop()
        self.hide()
        self.window.show()
    
    def open_mel_win(self):
        self.window.mel.show()