class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.showMaximized()
        self.setWindowTitle('Barbequer')
        self.setWindowIcon(QIcon('BBQ.png'))
        self.init()

    def init(self):

        self.size_policy = (QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.font = QFont()
        self.font.setPointSize(16)

        self.temp_display_label = QLabel(self)
        self.temp_display_label.setText('Current Temperature:')
        self.temp_display_label.setSizePolicy(self.size_policy[0],
                                              self.size_policy[1])
        self.temp_display_label.setFont(self.font)
        #        self.temp_display_label.setAlignment(Qt.AlignRight)

        self.temp_display = QLCDNumber(self)
        self.temp_display.setSizePolicy(self.size_policy[0],
                                        self.size_policy[1])
        self.temp_display.setFont(self.font)

        self.temp_set_label = QLabel(self)
        self.temp_set_label.setText('Set Temperature:')
        self.temp_set_label.setSizePolicy(self.size_policy[0],
                                          self.size_policy[1])
        self.temp_set_label.setFont(self.font)
        #        self.temp_set_label.setAlignment(Qt.AlignRight)

        self.temp_set = QLCDNumber(self)
        self.temp_set.setSizePolicy(self.size_policy[0], self.size_policy[1])
        self.temp_set.setFont(self.font)

        self.temp_dial = QDial(self)
        self.temp_dial.setSizePolicy(self.size_policy[0], self.size_policy[1])
        self.temp_dial.setProperty('value', 0)
        self.temp_dial.setSliderPosition(0)
        self.temp_dial.setNotchesVisible(True)
        self.temp_dial.setMaximum(600)
        self.temp_dial.setToolTip('Set Desired Temperature in Fahrenheit')
        self.temp_dial.valueChanged.connect(self.update_temperature)

        self.exhasut_fan = QRadioButton('&Enable Exhaust Fan')
        self.exhasut_fan.setSizePolicy(self.size_policy[0],
                                       self.size_policy[1])
        self.exhasut_fan.setFont(self.font)
        self.exhasut_fan.setToolTip('Enable exhaust fan')

        self.intake_fan = QRadioButton('&Enable Intake Fan')
        self.intake_fan.setSizePolicy(self.size_policy[0], self.size_policy[1])
        self.intake_fan.setFont(self.font)
        self.intake_fan.setToolTip('Enable intake fan')

        self.start_button = QPushButton('Start', self)
        self.start_button.setSizePolicy(self.size_policy[0],
                                        self.size_policy[1])
        self.start_button.setFont(self.font)
        self.start_button.setToolTip('Start Maintaining Temperature')
        self.start_button.clicked.connect(self.maintain_temperature)

        self.timer_button = QPushButton('Timer', self)
        self.timer_button.setSizePolicy(self.size_policy[0],
                                        self.size_policy[1])
        self.timer_button.setFont(self.font)
        self.timer_button.setToolTip('Cook Time')

        qp = QPainter()
        qp.begin(self)
        qp.setPen(QPen(QColor(255, 80, 0), 3))
        qp.setBrush(QColor(255, 80, 0))
        qp.drawEllipse(QPoint(50, 60), 30, 30)
        qp.end()

        #add the grid layout to the interface
        self.layout = QGridLayout(self)
        self.layout.addWidget(self.temp_dial, 0, 0, 2, 2)
        self.layout.addWidget(self.temp_set_label, 2, 0)
        self.layout.addWidget(self.temp_set, 2, 1, 1, 2)
        self.layout.addWidget(self.temp_display_label, 3, 0)
        self.layout.addWidget(self.temp_display, 3, 1)
        self.layout.addWidget(self.exhasut_fan, 4, 0)
        self.layout.addWidget(self.intake_fan, 4, 1)
        self.layout.addWidget(self.start_button, 5, 0)
        self.layout.addWidget(self.timer_button, 5, 1)


#        self.layout.addWidget(qp,6,1)

    def update_temperature(self):
        self.temp_set.display(str(self.temp_dial.sliderPosition()))
        try:
            self.start_button.setEnabled(True)
            self.Temp.stop()
        except:
            '''do nothing here'''

    def maintain_temperature(self):
        self.Temp = temp_operation(self)
        self.start_button.setDisabled(True)
        self.Temp.isRunning = False
        time.sleep(1)
        if self.Temp.isRunning == False:
            self.Temp.isRunning = True
            self.Temp.set_temp = self.temp_dial.sliderPosition()
            self.Temp.display_update.connect(self.temp_display.display)
            self.Temp.start()
            print(self.Temp.isRunning)
class Start(QMainWindow):
    def __init__(self):
        super(Start, self).__init__()
        self.titles = "Media Player"
        self.left = 500
        self.top = 300
        self.width = 400
        self.height = 200
        self.window_main()
        self.adding_menus()

    def openMultipleFile(self):
        dialogs = QFileDialog(self)
        self.fnames, _ = dialogs.getOpenFileNames(
            self, 'Open Media Files', QDir.homePath(),
            "Videos (*.mp4 *.mkv *.3pg)")
        if self.fnames != '':
            self.playlist = QMediaPlaylist(self)
            self.fnamelist = []
            for playlst in self.fnames:
                self.fnamelist.append(
                    QMediaContent(QUrl.fromLocalFile(playlst)))
            self.playlist.addMedia(self.fnamelist)
            self.playlist.setCurrentIndex(1)
            self.videoWidget = QVideoWidget(self)

            self.mediaPlayer.setVideoOutput(self.videoWidget)
            #        self.videoWidget.setAspectRatioMode(60, 60,Qt.KeepAspectRatioByExpanding)

            self.mediaPlayer.setPlaylist(self.playlist)
            self.playlist.currentIndexChanged.connect(self.mediaNameChange)
            self.mediaPlayer.play()
            self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
            self.play.setEnabled(True)
            self.stop.setEnabled(True)
            self.loop.setEnabled(True)
            if (len(self.fnamelist) > 1):
                self.forw.setEnabled(True)
                self.shuffl.setEnabled(True)
            self.l1.setText("00:00")
            mediaName = self.fnames[0].rsplit('/', 1)[-1]
            self.fulltitle = mediaName + " - " + self.titles
            self.setWindowTitle(self.fulltitle)
            self.mediaPlayer.durationChanged.connect(self.sliderDuration)

    def openFile(self):
        self.fname, _ = QFileDialog.getOpenFileName(
            self, 'Open Media Files', QDir.homePath(),
            "Videos (*.mp4 *.mkv *.3pg)")

        if self.fname != '':
            mediaName = self.fname.rsplit('/', 1)[-1]
            self.fulltitle = mediaName + " - " + self.titles
            self.setWindowTitle(self.fulltitle)
            self.playlist = QMediaPlaylist(self)
            self.playlist.addMedia(
                QMediaContent(QUrl.fromLocalFile(self.fname)))
            self.playlist.setCurrentIndex(1)
            self.mediaPlayer.setPlaylist(self.playlist)
            self.playlist.currentIndexChanged.connect(self.mediaNameChange)
            self.mediaPlayer.play()
            self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
            self.play.setEnabled(True)
            self.stop.setEnabled(True)
            self.loop.setEnabled(True)
            self.l1.setText("00:00")
            self.mediaPlayer.durationChanged.connect(self.sliderDuration)

    def window_main(self):
        self.setWindowTitle(self.titles)
        qw = QWidget()
        self.setGeometry(self.left, self.top, qw.maximumWidth(),
                         qw.maximumHeight())
        self.setMinimumSize(540, 0)
        self.setWindowIcon(QIcon("mediaplayer.png"))
        self.video()
        self.show()

    def sliderChanged(self, position):
        pos = position * 1000
        self.mediaPlayer.setPosition(pos)
        self.slider.setValue(position)

    def adding_menus(self):
        menu = Allmenu(self)

    def volumeChange(self, vol):
        self.mediaPlayer.setVolume(vol)

    def sliderDuration(self, duratn):
        milisec = self.mediaPlayer.duration()
        sec = int(milisec / 1000)
        hour = int(sec / 3600)
        min = int((sec / 60) - (hour * 60))
        secs = int(sec - (min * 60) - (hour * 60 * 60))
        self.l2.setText(str(hour) + ":" + str(min) + ":" + str(secs))
        self.slider.setMaximum(sec)

    def sliderDuration2(self, duratn):
        second = int(duratn / 1000)
        self.slider.setValue(second)
        hour = int(second / 3600)
        min = int((second / 60) - (hour * 60))
        secs = int(second - (min * 60) - (hour * 60 * 60))
        if (min < 10):
            min = "0" + str(min)
        else:
            min = str(min)

        if (secs < 10):
            secs = "0" + str(secs)
        else:
            secs = str(secs)

        if (hour == 0):
            self.l1.setText(min + ":" + secs)
        else:
            self.l1.setText(str(hour) + ":" + min + ":" + secs)

    def mediaNameChange(self, index):
        mediaName = self.fnames[index].rsplit('/', 1)[-1]
        self.fulltitle = mediaName + " - " + self.titles
        self.setWindowTitle(self.fulltitle)
        if (self.playlist.playbackMode() == 4):
            self.forw.setEnabled(True)
            self.back.setEnabled(True)
        else:
            if ((index + 1) == self.playlist.mediaCount()):
                self.forw.setEnabled(False)
                self.back.setEnabled(True)
            else:
                self.back.setEnabled(True)

    def video(self):
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer.positionChanged.connect(self.sliderDuration2)
        self.mediaPlayer.setVolume(10)

        videoWidget = QVideoWidget()
        layout = QVBoxLayout()

        wid = QWidget(self)
        self.play = QPushButton()
        self.play.setEnabled(False)
        self.play.setFixedWidth(40)
        self.play.setFixedHeight(30)
        self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.play.setIconSize(QSize(20, 20))
        self.play.clicked.connect(self.playAction)
        self.play.setShortcut(QKeySequence("Space"))

        self.back = QPushButton()
        self.back.setEnabled(False)
        self.back.setFixedWidth(40)
        self.back.setFixedHeight(25)
        self.back.setStyleSheet("margin-left: 10px")
        self.back.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekBackward))
        self.back.setIconSize(QSize(14, 14))
        self.back.clicked.connect(self.prevAction)

        self.back.setShortcut(QKeySequence("Ctrl+b"))

        self.stop = QPushButton()
        self.stop.setEnabled(False)
        self.stop.setFixedWidth(40)
        self.stop.setFixedHeight(25)
        self.stop.setStyleSheet("margin-left: 0px")
        self.stop.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.stop.setIconSize(QSize(14, 14))
        self.stop.clicked.connect(self.stopAction)
        self.stop.setShortcut(QKeySequence("s"))

        self.forw = QPushButton()
        self.forw.setEnabled(False)
        self.forw.setFixedWidth(40)
        self.forw.setFixedHeight(25)
        self.forw.setStyleSheet("margin-left: 0px")
        self.forw.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekForward))
        self.forw.setIconSize(QSize(14, 14))
        self.forw.clicked.connect(self.forwAction)
        self.forw.setShortcut(QKeySequence("Ctrl+f"))

        self.loop = QPushButton()
        self.loop.setEnabled(False)
        self.loop.setFixedWidth(40)
        self.loop.setFixedHeight(25)
        self.loop.setStyleSheet("margin-left: 10px")
        self.loop.setIcon(QIcon(QPixmap("loop.svg")))
        self.loop.setIconSize(QSize(14, 14))
        self.loop.clicked.connect(self.loopAction)
        self.loop.setShortcut(QKeySequence("Ctrl+l"))

        self.shuffl = QPushButton()
        self.shuffl.setEnabled(False)
        self.shuffl.setFixedHeight(25)
        self.shuffl.setStyleSheet("margin-left: 0px")
        self.shuffl.setFixedWidth(40)
        self.shuffl.setFixedHeight(25)
        self.shuffl.setStyleSheet("margin-left: 0px")
        self.shuffl.setIcon(QIcon(QPixmap("shuffl.svg")))
        self.shuffl.setIconSize(QSize(14, 14))
        self.shuffl.clicked.connect(self.shufflAction)
        self.shuffl.setShortcut(QKeySequence("Ctrl+shift+s"))

        spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)

        self.volume = QDial()
        self.volume.setFixedWidth(40)
        self.volume.setFixedHeight(40)
        self.volume.setMaximum(100)
        self.volume.setMinimum(0)
        self.volume.setToolTip("Volume")
        self.volume.valueChanged.connect(self.volumeChange)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.play)
        hlayout.addWidget(self.back)
        hlayout.addWidget(self.stop)
        hlayout.addWidget(self.forw)
        hlayout.addWidget(self.loop)
        hlayout.addWidget(self.shuffl)
        hlayout.addItem(spacer)
        hlayout.addWidget(self.volume)

        hslayout = QHBoxLayout()
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(0)
        self.l1 = QLabel()
        self.l1.setText("--:--:--")
        self.l2 = QLabel()
        self.l2.setText("--:--:--")
        self.slider.sliderMoved.connect(self.sliderChanged)
        hslayout.addWidget(self.l1)
        hslayout.addWidget(self.slider)
        hslayout.addWidget(self.l2)

        layout.addWidget(videoWidget)

        layout.addLayout(hslayout)
        layout.addLayout(hlayout)
        wid.setLayout(layout)

        self.setCentralWidget(wid)
        self.mediaPlayer.setVideoOutput(videoWidget)

    def playAction(self):
        if (self.mediaPlayer.state() == 1):
            self.mediaPlayer.pause()
            self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        elif (self.mediaPlayer.state() == 2):
            self.mediaPlayer.play()
            self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))

        else:
            self.back.setEnabled(False)
            self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

    def stopAction(self):
        self.mediaPlayer.stop()
        self.play.setEnabled(False)
        self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.setWindowTitle(self.titles)
        self.l1.setText("--:--:--")
        self.l2.setText("--:--:--")

    def forwAction(self):
        if (self.playlist.playbackMode() == 4):
            self.forw.setEnabled(True)
            self.back.setEnabled(True)
            indexes = random.randint(0, (self.playlist.mediaCount() - 1))
            self.playlist.setCurrentIndex(indexes)
        elif (self.playlist.playbackMode() == 1):
            self.playlist.next()
        else:
            print(self.playlist.currentIndex())
            if ((self.playlist.currentIndex() +
                 2) == self.playlist.mediaCount()):
                self.forw.setEnabled(False)
                self.playlist.next()
                self.back.setEnabled(True)
            else:
                self.playlist.next()
                self.back.setEnabled(True)

    def prevAction(self):
        if (self.playlist.playbackMode() == 4):
            self.forw.setEnabled(True)
            self.back.setEnabled(True)
            indexes = random.randint(0, (self.playlist.mediaCount() - 1))
            self.playlist.setCurrentIndex(indexes)
        elif (self.playlist.playbackMode() == 1):
            self.playlist.previous()
        else:
            if (self.playlist.currentIndex() == 1):
                self.forw.setEnabled(True)
                self.playlist.previous()
                self.back.setEnabled(False)
            else:
                self.playlist.previous()
                self.forw.setEnabled(True)

    def loopAction(self):
        if (self.playlist.playbackMode() != 1):
            self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
            self.loop.setIcon(QIcon(QPixmap("greenloop.svg")))
            self.shuffl.setIcon(QIcon(QPixmap("shuffl.svg")))
        else:
            self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
            self.loop.setIcon(QIcon(QPixmap("loop.svg")))

    def shufflAction(self):
        if (self.playlist.playbackMode() != 4):
            self.playlist.setPlaybackMode(QMediaPlaylist.Random)
            self.shuffl.setIcon(QIcon(QPixmap("greenshuffl.svg")))
            self.loop.setIcon(QIcon(QPixmap("loop.svg")))
        else:
            self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
            self.shuffl.setIcon(QIcon(QPixmap("shuffl.svg")))

    def close(self):
        sys.exit(1)
Exemplo n.º 3
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1871, 1200)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.transformsGroupBox = QGroupBox(self.centralwidget)
        self.transformsGroupBox.setGeometry(QRect(1500, 170, 240, 500))
        self.transformsGroupBox.setMaximumSize(QSize(240, 600))
        font = QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.transformsGroupBox.setFont(font)
        self.transformsGroupBox.setToolTip("")
        self.transformsGroupBox.setWhatsThis("")
        self.transformsGroupBox.setObjectName("transformsGroupBox")
        self.edgesButton = QPushButton(self.transformsGroupBox)
        self.edgesButton.setGeometry(QRect(110, 180, 120, 30))
        self.edgesButton.setObjectName("edgesButton")
        self.brightnessButton = QPushButton(self.transformsGroupBox)
        self.brightnessButton.setGeometry(QRect(110, 20, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.brightnessButton.setFont(font)
        self.brightnessButton.setObjectName("brightnessButton")
        self.getSizeButton = QPushButton(self.transformsGroupBox)
        self.getSizeButton.setGeometry(QRect(0, 470, 75, 23))
        self.getSizeButton.setObjectName("getSizeButton")
        self.paramsGroupBox = QGroupBox(self.transformsGroupBox)
        self.paramsGroupBox.setGeometry(QRect(10, 29, 91, 321))
        font = QFont()
        font.setPointSize(8)
        self.paramsGroupBox.setFont(font)
        self.paramsGroupBox.setObjectName("paramsGroupBox")
        self.leftSlider = QSlider(self.paramsGroupBox)
        self.leftSlider.setGeometry(QRect(10, 50, 20, 240))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.leftSlider.sizePolicy().hasHeightForWidth())
        self.leftSlider.setSizePolicy(sizePolicy)
        self.leftSlider.setOrientation(Qt.Vertical)
        self.leftSlider.setTickPosition(QSlider.TicksAbove)
        self.leftSlider.setObjectName("leftSlider")
        self.rightSlider = QSlider(self.paramsGroupBox)
        self.rightSlider.setGeometry(QRect(50, 50, 20, 240))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.rightSlider.sizePolicy().hasHeightForWidth())
        self.rightSlider.setSizePolicy(sizePolicy)
        self.rightSlider.setOrientation(Qt.Vertical)
        self.rightSlider.setTickPosition(QSlider.TicksAbove)
        self.rightSlider.setObjectName("rightSlider")
        self.leftLabel = QLabel(self.paramsGroupBox)
        self.leftLabel.setGeometry(QRect(10, 20, 20, 15))
        self.leftLabel.setTextFormat(Qt.PlainText)
        self.leftLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.leftLabel.setObjectName("leftLabel")
        self.rightLabel = QLabel(self.paramsGroupBox)
        self.rightLabel.setGeometry(QRect(50, 20, 20, 15))
        self.rightLabel.setTextFormat(Qt.PlainText)
        self.rightLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.rightLabel.setObjectName("rightLabel")
        self.adaptiveThresholdButton = QPushButton(self.transformsGroupBox)
        self.adaptiveThresholdButton.setGeometry(QRect(110, 140, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.adaptiveThresholdButton.setFont(font)
        self.adaptiveThresholdButton.setObjectName("adaptiveThresholdButton")
        self.gray2colSelButton = QPushButton(self.transformsGroupBox)
        self.gray2colSelButton.setGeometry(QRect(110, 100, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.gray2colSelButton.setFont(font)
        self.gray2colSelButton.setObjectName("gray2colSelButton")
        self.gray2colAllButton = QPushButton(self.transformsGroupBox)
        self.gray2colAllButton.setGeometry(QRect(110, 60, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.gray2colAllButton.setFont(font)
        self.gray2colAllButton.setObjectName("gray2colAllButton")
        self.fftButton = QPushButton(self.transformsGroupBox)
        self.fftButton.setGeometry(QRect(110, 220, 120, 30))
        self.fftButton.setObjectName("fftButton")
        self.dftButton = QPushButton(self.transformsGroupBox)
        self.dftButton.setGeometry(QRect(110, 260, 120, 30))
        self.dftButton.setObjectName("dftButton")
        self.gaborButton = QPushButton(self.transformsGroupBox)
        self.gaborButton.setGeometry(QRect(110, 300, 120, 30))
        self.gaborButton.setObjectName("gaborButton")
        self.differenceButton = QPushButton(self.transformsGroupBox)
        self.differenceButton.setGeometry(QRect(110, 340, 120, 30))
        self.differenceButton.setObjectName("differenceButton")
        self.RGB2GrayButton = QPushButton(self.transformsGroupBox)
        self.RGB2GrayButton.setGeometry(QRect(110, 380, 120, 30))
        self.RGB2GrayButton.setObjectName("RGB2GrayButton")
        self.invertedCheckBox = QCheckBox(self.transformsGroupBox)
        self.invertedCheckBox.setGeometry(QRect(110, 430, 121, 17))
        self.invertedCheckBox.setObjectName("invertedCheckBox")
        self.angleDial = QDial(self.transformsGroupBox)
        self.angleDial.setGeometry(QRect(20, 360, 81, 64))
        self.angleDial.setMinimum(1)
        self.angleDial.setMaximum(4)
        self.angleDial.setPageStep(1)
        self.angleDial.setSliderPosition(1)
        self.angleDial.setWrapping(False)
        self.angleDial.setNotchesVisible(True)
        self.angleDial.setObjectName("angleDial")
        self.groupButtonsBox = QGroupBox(self.centralwidget)
        self.groupButtonsBox.setGeometry(QRect(1500, 730, 241, 141))
        self.groupButtonsBox.setMaximumSize(QSize(250, 600))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.groupButtonsBox.setFont(font)
        self.groupButtonsBox.setObjectName("groupButtonsBox")
        self.addImgButton = QPushButton(self.groupButtonsBox)
        self.addImgButton.setGeometry(QRect(50, 20, 150, 30))
        palette = QPalette()
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Button, brush)
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Button, brush)
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Button, brush)
        self.addImgButton.setPalette(palette)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.addImgButton.setFont(font)
        self.addImgButton.setObjectName("addImgButton")
        self.saveSceneImgButton = QPushButton(self.groupButtonsBox)
        self.saveSceneImgButton.setGeometry(QRect(50, 60, 150, 30))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.saveSceneImgButton.setFont(font)
        self.saveSceneImgButton.setObjectName("saveSceneImgButton")
        self.saveImgButton = QPushButton(self.groupButtonsBox)
        self.saveImgButton.setGeometry(QRect(50, 100, 150, 30))
        font = QFont()
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.saveImgButton.setFont(font)
        self.saveImgButton.setObjectName("saveImgButton")
        self.graphicsView = QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QRect(10, 15, 1471, 900))
        self.graphicsView.setMaximumSize(QSize(4000, 3000))
        self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.graphicsView.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.graphicsView.setObjectName("graphicsView")
        self.scene = TransformScene()
        self.graphicsView.setScene(self.scene)
        self.scaleEditLabel = QLabel(self.centralwidget)
        self.scaleEditLabel.setGeometry(QRect(1500, 100, 47, 13))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.scaleEditLabel.setFont(font)
        self.scaleEditLabel.setObjectName("scaleEditLabel")
        self.scaleBox = QDoubleSpinBox(self.centralwidget)
        self.scaleBox.setGeometry(QRect(1550, 100, 62, 22))
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        self.scaleBox.setFont(font)
        self.scaleBox.setMinimum(0.1)
        self.scaleBox.setMaximum(10.0)
        self.scaleBox.setSingleStep(0.1)
        self.scaleBox.setProperty("value", 0.5)
        self.scaleBox.setObjectName("scaleBox")
        self.infoLabel = QLabel(self.centralwidget)
        self.infoLabel.setGeometry(QRect(1499, 130, 230, 20))
        self.infoLabel.setFrameShape(QFrame.WinPanel)
        self.infoLabel.setText("")
        self.infoLabel.setAlignment(Qt.AlignCenter)
        self.infoLabel.setObjectName("infoLabel")
        self.infoLabel_2 = QLabel(self.centralwidget)
        self.infoLabel_2.setGeometry(QRect(1500, 20, 230, 20))
        font = QFont()
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.infoLabel_2.setFont(font)
        self.infoLabel_2.setFrameShape(QFrame.WinPanel)
        self.infoLabel_2.setText("")
        self.infoLabel_2.setAlignment(Qt.AlignCenter)
        self.infoLabel_2.setObjectName("infoLabel_2")
        self.infoLabel_3 = QLabel(self.centralwidget)
        self.infoLabel_3.setGeometry(QRect(1500, 60, 230, 20))
        font = QFont()
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.infoLabel_3.setFont(font)
        self.infoLabel_3.setFrameShape(QFrame.Box)
        self.infoLabel_3.setText("")
        self.infoLabel_3.setAlignment(Qt.AlignCenter)
        self.infoLabel_3.setObjectName("infoLabel_3")
        self.clearImgButton = QPushButton(self.centralwidget)
        self.clearImgButton.setGeometry(QRect(1550, 690, 150, 30))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.clearImgButton.setFont(font)
        self.clearImgButton.setObjectName("clearImgButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 1871, 21))
        self.menubar.setObjectName("menubar")
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionExit = QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setObjectName("actionHelp")
        self.actionAbout = QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.actionDefault_Values = QAction(MainWindow)
        self.actionDefault_Values.setObjectName("actionDefault_Values")
        self.menuHelp.addAction(self.actionHelp)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addSeparator()
        self.menuHelp.addAction(self.actionDefault_Values)
        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        self.scene.file_signal.connect(on_file_signal)
        self.scene.info_signal.connect(on_info_signal)
        self.scene.sliders_reset_signal.connect(on_sliders_reset_signal)
        

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Green Monkey"))
        self.transformsGroupBox.setTitle(_translate("MainWindow", "Transformations"))
        self.edgesButton.setText(_translate("MainWindow", "Edges, Sobel"))
        self.brightnessButton.setToolTip(_translate("MainWindow", "You can change brightness with left slider and blur with rigt one."))
        self.brightnessButton.setWhatsThis(_translate("MainWindow", "You can change brightness with left slider and blur with rigt one."))
        self.brightnessButton.setText(_translate("MainWindow", "Brightness and Blur"))
        self.getSizeButton.setText(_translate("MainWindow", "get Size"))
        self.paramsGroupBox.setTitle(_translate("MainWindow", "Parameters"))
        self.leftSlider.setToolTip(_translate("MainWindow", "Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on."))
        self.leftSlider.setWhatsThis(_translate("MainWindow", "Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on."))
        self.rightSlider.setToolTip(_translate("MainWindow", "Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well."))
        self.rightSlider.setWhatsThis(_translate("MainWindow", "Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well."))
        self.leftLabel.setText(_translate("MainWindow", "0"))
        self.rightLabel.setText(_translate("MainWindow", "0"))
        self.adaptiveThresholdButton.setText(_translate("MainWindow", "Adaptive Threshold"))
        self.gray2colSelButton.setToolTip(_translate("MainWindow", "Gray scale 0..255 to color with selected method only.\n"
"Image is converted to gray and finally to color."))
        self.gray2colSelButton.setWhatsThis(_translate("MainWindow", "Gray scale 0..255 to color with selected method only.\n"
"Image is converted to gray and  and finally to color."))
        self.gray2colSelButton.setText(_translate("MainWindow", "Gray2Color Sel."))
        self.gray2colAllButton.setToolTip(_translate("MainWindow", "Gray scale 0..255 to color for all available methods.\n"
"Image resized as per scale window and then  is converted to gray and finally to color."))
        self.gray2colAllButton.setWhatsThis(_translate("MainWindow", "Gray scale 0..255 to color for all available methods.\n"
"Image resized as per scale window and then  is converted to gray and finally to color."))
        self.gray2colAllButton.setText(_translate("MainWindow", "Gray2Color All"))
        self.fftButton.setText(_translate("MainWindow", "FFT"))
        self.dftButton.setText(_translate("MainWindow", "DFT"))
        self.gaborButton.setToolTip(_translate("MainWindow", "Applies Gabor Filter"))
        self.gaborButton.setWhatsThis(_translate("MainWindow", "Applies Gabor Filter"))
        self.gaborButton.setText(_translate("MainWindow", "Gabor Filter"))
        self.differenceButton.setText(_translate("MainWindow", "Difference"))
        self.RGB2GrayButton.setText(_translate("MainWindow", "RGB to Gray"))
        self.invertedCheckBox.setText(_translate("MainWindow", "Inverted Image"))
        self.angleDial.setToolTip(_translate("MainWindow", "GABOR Filter - angle 1..4 ~ 1*np.pi/angle"))
        self.angleDial.setWhatsThis(_translate("MainWindow", "GABOR Filter - angle 1..4 ~ 1*np.pi/angle"))
        self.groupButtonsBox.setTitle(_translate("MainWindow", "Images"))
        self.addImgButton.setText(_translate("MainWindow", "Add Image(s)"))
        self.addImgButton.setShortcut(_translate("MainWindow", "Ctrl+A"))
        self.saveSceneImgButton.setText(_translate("MainWindow", "Save Scene as Image"))
        self.saveImgButton.setText(_translate("MainWindow", "Save Selected as Image"))
        self.scaleEditLabel.setText(_translate("MainWindow", "Scale:"))
        self.clearImgButton.setText(_translate("MainWindow", "Clear Image(s)"))
        self.menuHelp.setTitle(_translate("MainWindow", "Help"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionHelp.setText(_translate("MainWindow", "Help"))
        self.actionAbout.setText(_translate("MainWindow", "About"))
        self.actionDefault_Values.setText(_translate("MainWindow", "Default Values"))

        self.actionHelp.setShortcut('F1')
        self.actionHelp.setStatusTip('Help')  
        self.actionHelp.triggered.connect(self.showHelp)
        self.actionAbout.setStatusTip('About')  
        self.actionAbout.triggered.connect(self.showAbout)
        self.actionDefault_Values.setStatusTip('Default folders and other values')
        self.actionDefault_Values.triggered.connect(self.updateINI)
   
        self.addImgButton.clicked.connect(partial(self.scene.addImg))
        self.clearImgButton.clicked.connect(self.scene.dialogClearScene)
        self.saveSceneImgButton.clicked.connect(partial(self.scene.saveScene))
        self.saveImgButton.clicked.connect(partial(self.scene.saveImg))
        self.scaleBox.valueChanged.connect(self.onScaleBoxValueChanged)
        self.getSizeButton.clicked.connect(self.showSceneSize)
        self.brightnessButton.clicked.connect(self.startBrightnessAndBlur)
        self.gray2colAllButton.clicked.connect(self.startGray2colAllButton)
        self.gray2colSelButton.clicked.connect(self.startGray2colSelButton)
        self.adaptiveThresholdButton.clicked.connect(self.startAdaptiveThreshold)
        self.edgesButton.clicked.connect(self.startSobelXY)
        self.fftButton.clicked.connect(self.startFFT)
        self.dftButton.clicked.connect(self.startDFT)
        self.gaborButton.clicked.connect(self.startGabor)
        self.differenceButton.clicked.connect(self.startDifference)
        self.RGB2GrayButton.clicked.connect(self.starRGB2Gray)

        
 
        self.leftSlider.valueChanged['int'].connect(self. leftSliderChanged)
        self.rightSlider.valueChanged['int'].connect(self.rightSliderChanged)
        self.angleDial.valueChanged['int'].connect(self.angleDialChanged)
        
    def setStart(self):
        self.graphicsView.setAlignment(Qt.AlignLeft|Qt.AlignTop)
        self.scene.setSceneRect(0, 0, 0, 0)
        self.scene.imgScale = self.scaleBox.value()
        self.clearSliders()
        self.infoLabel.setText("")
        self.scene.cv2Images = {}
        self.transformsGroupBox.setEnabled(False)
        self.transformsGroupBox.setEnabled(False)
        self.invertedCheckBox.setChecked(False)

        
        
    def clearSliders(self):
        self.infoLabel_2.setText('')
        self.infoLabel_3.setText('')
        self.scene.currentTransform = 0
        self.leftSlider.setEnabled(False)
        self.leftSlider.setToolTip("")
        self.leftSlider.setWhatsThis("")
        self.leftSlider.setMaximum(99)
        self.leftSlider.setMinimum(0)
        self.leftSlider.setTickInterval(10)        
        self.leftSlider.setSingleStep(1)
        self.leftSlider.setTickPosition(11)

        self.rightSlider.setEnabled(False)
        self.rightSlider.setToolTip("")
        self.rightSlider.setWhatsThis("")
        self.rightSlider.setMaximum(99)
        self.rightSlider.setMinimum(0)
        self.rightSlider.setTickInterval(10)        
        self.rightSlider.setSingleStep(1)
        self.rightSlider.setTickPosition(0) 
        self.paramsGroupBox.setFlat(False)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: black; font-weight: normal;}') 
        
        self.angleDial.setEnabled(False)
        self.angleDial.setToolTip(" ")
        self.angleDial.setWhatsThis("")



    def invertCheckBoxEvent(self, checked):
        self.scene.inverted = checked
               
    def showSceneSize(self):
        x = self.scene.sceneRect().width()
        y = self.scene.sceneRect().height()      
        self.infoLabel.setText(f'size: {x}x{y}, {self.scene.findSceneArea()}')

    def onScaleBoxValueChanged(self, val):
        self.scene.imgScale = val
          
    def startBrightnessAndBlur(self):
        self.scene.currentTransform = 1
        self.infoLabel_2.setText('Adaptive Threshold')      
        self.scene.currentBrightnessValue = 0
        self.scene.currentBlurValue = 0
        self.scene.transform1()

        self.infoLabel_2.setText('Brightness and Blur')
        self.scene.currentTransform = 1
        self.leftSlider.setEnabled(True)
        self.rightSlider.setEnabled(True)
        self.leftSlider.setToolTip("Change Brightness  -> 0 .. 99")
        self.leftSlider.setWhatsThis("Change Brightness  -> 0 .. 99")
        self.rightSlider.setToolTip("Change Blur  -> 0 .. 99")
        self.rightSlider.setWhatsThis("Change Blur  -> 0 .. 99")
        self.leftSlider.setMaximum(99)
        self.leftSlider.setMinimum(0)
        self.leftSlider.setTickInterval(10)        
        self.leftSlider.setSingleStep(1)
        self.leftSlider.setTickPosition(11)
        self.rightSlider.setMaximum(99)
        self.rightSlider.setMinimum(0)
        self.rightSlider.setTickInterval(10)        
        self.rightSlider.setSingleStep(1)
        self.rightSlider.setTickPosition(0) 
        self.paramsGroupBox.setFlat(True)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')
        
    def startGray2colAllButton(self):
        self.infoLabel_2.setText('Gray to Color All Methods')
        self.scene.currentTransform = 2
        self.scene.transform2(1, 1)
        
    def startGray2colSelButton(self):
        self.scene.currentTransform = 3
        self.infoLabel_2.setText(' Gray to Color')
        self.scene.transform2(0, 1)   
    
    def startSobelXY(self):
        self.scene.currentTransform = 4
        self.infoLabel_2.setText('Edge Detection')
        self.scene.transform4()
 
    def startFFT(self):
        self.scene.currentTransform = 7
        self.infoLabel_2.setText('FFT')
        self.scene.transform7()
    
    def startDFT(self):
        self.scene.currentTransform = 6
        self.infoLabel_2.setText('DFT')
        self.scene.transform6()
        
    def startDenoising(self):
        self.scene.currentTransform = 8
        self.infoLabel_2.setText('Denoising')
        self.scene.transform8()
        
    def startDifference(self):
        self.scene.currentTransform = 9
        self.infoLabel_2.setText('Difference')
        self.scene.transform9()
        
    def starRGB2Gray(self):
        self.scene.currentTransform = 10
        #txt = self.infoLabel_2.text()
        self.infoLabel_2.setText('RGB to Gray')
        self.scene.transform10()
        
    def startAdaptiveThreshold(self):
        self.scene.currentTransform = 5
        self.infoLabel_2.setText('Adaptive Threshold')      
        self.scene.currentBlockSizeValue = 11
        self.scene.currentCValue = 5
        self.scene.transform5()

        self.leftSlider.setEnabled(True)
        self.rightSlider.setEnabled(True)
        self.leftSlider.setToolTip("Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.")
        self.leftSlider.setWhatsThis("Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.")
        self.rightSlider.setToolTip("Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.")
        self.rightSlider.setWhatsThis("Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.")
        self.leftSlider.setMaximum(16)
        self.leftSlider.setMinimum(1)
        self.leftSlider.setTickInterval(1)        
        self.leftSlider.setSingleStep(1)
        self.leftSlider.setTickPosition(11)
        self.rightSlider.setMaximum(20)
        self.rightSlider.setMinimum(-5)
        self.rightSlider.setTickInterval(1)        
        self.rightSlider.setSingleStep(1)
        self.rightSlider.setTickPosition(5)     
        self.paramsGroupBox.setFlat(True)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')       

    def startGabor(self):
        self.scene.currentTransform = 8
        self.infoLabel_2.setText('Gabor Filter') 
        self.scene.currentKernelSizeValue = 10
        self.scene.currentSigmaValue = 10
        self.scene.thetaCurrentValue
        self.scene.transform8()
        self.angleDial.setEnabled(True)
        self.leftSlider.setEnabled(True)
        self.rightSlider.setEnabled(True)
        self.leftSlider.setToolTip("Gabor Filter\n"
                                  "kernelSize – Size of a kernel 1..50")
        self.leftSlider.setWhatsThis("Gabor Filter\n"
                                  "kernelSize – Size of a kernel")
        self.rightSlider.setToolTip("Gabor Filter\n"
                                  "Standard Deviation – 1..30")
        self.rightSlider.setWhatsThis("Gabor Filter\n"
                                  "Standard Deviation – 1..30")
        self.angleDial.setToolTip("GABOR Filter - angle 1..4 ~ 1*np.pi/angle")
        self.angleDial.setWhatsThis("GABOR Filter - angle 1..4 ~ 1*np.pi/angle")       
        self.leftSlider.setMaximum(50)
        self.leftSlider.setMinimum(1)
        self.leftSlider.setTickInterval(5)        
        self.leftSlider.setSingleStep(5)
        self.leftSlider.setTickPosition(10)
        self.rightSlider.setMaximum(30)
        self.rightSlider.setMinimum(1)
        self.rightSlider.setTickInterval(5)        
        self.rightSlider.setSingleStep(5)
        self.rightSlider.setTickPosition(10)     
        self.paramsGroupBox.setFlat(True)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')       


    def leftSliderChanged(self, value):
        self.leftLabel.setText(str(value))
        if self.scene.currentTransform == 1:
            self.scene.currentBrightnessValue = value
        elif self.scene.currentTransform == 5:
            if value % 2 == 1:return 
            self.scene.currentBlockSizeValue = value
        elif self.scene.currentTransform == 8:
            self.scene.currentKernelSizeValue = value
        else:
            pass
        self.update()
                    
    def rightSliderChanged(self, value):
        self.rightLabel.setText(str(value))
        if self.scene.currentTransform == 1:
            self.scene.currentBlurValue = value
        elif self.scene.currentTransform == 5:
             self.scene.currentCValue = value
        elif self.scene.currentTransform == 8:
            self.scene.currentSigmaValue = value
        else:
            pass
        self.update()  

    def angleDialChanged(self, value): 
        if self.scene.currentTransform == 8:
            self.scene.thetaCurrentValue = value
        self.update()
           
    def update(self):
        if self.scene.currentTransform == 1:
            if len(self.scene.selectedItems()) > 0:
                self.scene.transform1()
        elif self.scene.currentTransform == 5:
            self.infoLabel_2.setText(f'Adaptive Threshold {self.scene.currentBlockSizeValue} {self.scene.currentCValue}')
            if len(self.scene.selectedItems()) > 0:
                self.scene.transform5()
        elif self.scene.currentTransform == 8:
            if len(self.scene.selectedItems()) > 0:
                self.scene.transform8()
        else:
            ...

    def updateINI(self):
        Dialog = QDialog()
        ui = Ui_INI_Dialog()
        ui.setupUi(Dialog)
        Dialog.show()
        Dialog.exec_()
        self.readINI()
        
    def readINI(self):
        self.scene.source_dir = ''
        self.scene.result_dir = ''
        self.scene.color_map = '' 
        self.scene.scale = ''
        if os.path.exists("elilik.ini"):
            f = open("elilik.ini", "r")
            Lines = f.readlines()
            # Strips the newline character
            for line in Lines:
                l = line.strip()
                if "source_dir : " in l:
                    self.scene.source_dir = l.replace("source_dir : ","").strip()
                elif "result_dir : " in l:
                    self.scene.result_dir = l.replace("result_dir : ","").strip()  
                elif "color_map : " in l:
                     s = l.replace("color_map : ","").strip()
                     self.scene.color_map = s.split()
                elif "scale : " in l:
                    self.scene.scale = l.replace("scale : ","").strip()
                else:
                    ...

    def showHelp(self):
        help = showText(os.getcwd()+"/help.html") 
        help.exec_()
 
    def showAbout(self):
        about = showText(os.getcwd()+"/about.html")
        about.resize(280,250)
        about.exec_()
class MainWindow(QMainWindow):

    """Voice Changer main window."""

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
        self.setWindowTitle(__doc__)
        self.setMinimumSize(240, 240)
        self.setMaximumSize(480, 480)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
        self.tray = QSystemTrayIcon(self)
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
        self.menuBar().addMenu("Sound").addAction(
            "STOP !", lambda: call('killall rec', shell=True))
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Hide", lambda: self.hide())
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        # widgets
        group0 = QGroupBox("Voice Deformation")
        self.setCentralWidget(group0)
        self.process = QProcess(self)
        self.process.error.connect(
            lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
        self.control = QDial()
        self.control.setRange(-10, 20)
        self.control.setSingleStep(5)
        self.control.setValue(0)
        self.control.setCursor(QCursor(Qt.OpenHandCursor))
        self.control.sliderPressed.connect(
            lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.control.sliderReleased.connect(
            lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
        self.control.valueChanged.connect(
            lambda: self.control.setToolTip(f"<b>{self.control.value()}"))
        self.control.valueChanged.connect(
            lambda: self.statusBar().showMessage(
                f"Voice deformation: {self.control.value()}", 5000))
        self.control.valueChanged.connect(self.run)
        self.control.valueChanged.connect(lambda: self.process.kill())
        # Graphic effect
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.control.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)
        # Timer to start
        self.slider_timer = QTimer(self)
        self.slider_timer.setSingleShot(True)
        self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
        # an icon and set focus
        QLabel(self.control).setPixmap(
            QIcon.fromTheme("audio-input-microphone").pixmap(32))
        self.control.setFocus()
        QVBoxLayout(group0).addWidget(self.control)
        self.menu = QMenu(__doc__)
        self.menu.addAction(__doc__).setDisabled(True)
        self.menu.setIcon(self.windowIcon())
        self.menu.addSeparator()
        self.menu.addAction(
            "Show / Hide",
            lambda: self.hide() if self.isVisible() else self.showNormal())
        self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
        self.menu.addSeparator()
        self.menu.addAction("Quit", lambda: exit())
        self.tray.setContextMenu(self.menu)
        self.make_trayicon()

    def run(self):
        """Run/Stop the QTimer."""
        if self.slider_timer.isActive():
            self.slider_timer.stop()
        self.glow.setEnabled(True)
        call('killall rec ; killall play', shell=True)
        self.slider_timer.start(3000)

    def on_slider_timer_timeout(self):
        """Run subprocess to deform voice."""
        self.glow.setEnabled(False)
        value = int(self.control.value()) * 100
        command = f'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {value} "'
        print(f"Voice Deformation Value: {value}")
        print(f"Voice Deformation Command: {command}")
        self.process.start(command)
        if self.isVisible():
            self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
            print("Minimizing Main Window to System TrayIcon now...")
            sleep(3)
            self.hide()

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def make_trayicon(self):
        """Make a Tray Icon."""
        if self.windowIcon() and __doc__:
            self.tray.setIcon(self.windowIcon())
            self.tray.setToolTip(__doc__)
            self.tray.activated.connect(
                lambda: self.hide() if self.isVisible()
                else self.showNormal())
            return self.tray.show()
Exemplo n.º 5
0
class MainWindow(QMainWindow):
    """Voice Changer main window."""
    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
        self.setWindowTitle(__doc__)
        self.setMinimumSize(240, 240)
        self.setMaximumSize(480, 480)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
        self.tray = QSystemTrayIcon(self)
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
        self.menuBar().addMenu("Sound").addAction(
            "STOP !", lambda: call('killall rec', shell=True))
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Hide", lambda: self.hide())
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        # widgets
        group0 = QGroupBox("Voice Deformation")
        self.setCentralWidget(group0)
        self.process = QProcess(self)
        self.process.error.connect(
            lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
        self.control = QDial()
        self.control.setRange(-10, 20)
        self.control.setSingleStep(5)
        self.control.setValue(0)
        self.control.setCursor(QCursor(Qt.OpenHandCursor))
        self.control.sliderPressed.connect(
            lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.control.sliderReleased.connect(
            lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
        self.control.valueChanged.connect(
            lambda: self.control.setToolTip("<b>" + str(self.control.value())))
        self.control.valueChanged.connect(lambda: self.statusBar().showMessage(
            "Voice deformation: " + str(self.control.value()), 5000))
        self.control.valueChanged.connect(self.run)
        self.control.valueChanged.connect(lambda: self.process.kill())
        # Graphic effect
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.control.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)
        # Timer to start
        self.slider_timer = QTimer(self)
        self.slider_timer.setSingleShot(True)
        self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
        # an icon and set focus
        QLabel(self.control).setPixmap(
            QIcon.fromTheme("audio-input-microphone").pixmap(32))
        self.control.setFocus()
        QVBoxLayout(group0).addWidget(self.control)
        self.menu = QMenu(__doc__)
        self.menu.addAction(__doc__).setDisabled(True)
        self.menu.setIcon(self.windowIcon())
        self.menu.addSeparator()
        self.menu.addAction(
            "Show / Hide", lambda: self.hide()
            if self.isVisible() else self.showNormal())
        self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
        self.menu.addSeparator()
        self.menu.addAction("Quit", lambda: exit())
        self.tray.setContextMenu(self.menu)
        self.make_trayicon()

    def run(self):
        """Run/Stop the QTimer."""
        if self.slider_timer.isActive():
            self.slider_timer.stop()
        self.glow.setEnabled(True)
        call('killall rec', shell=True)
        self.slider_timer.start(3000)

    def on_slider_timer_timeout(self):
        """Run subprocess to deform voice."""
        self.glow.setEnabled(False)
        value = int(self.control.value()) * 100
        cmd = 'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {0} "'
        command = cmd.format(int(value))
        log.debug("Voice Deformation Value: {0}".format(value))
        log.debug("Voice Deformation Command: {0}".format(command))
        self.process.start(command)
        if self.isVisible():
            self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
            log.debug("Minimizing Main Window to System TrayIcon now...")
            sleep(3)
            self.hide()

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def make_trayicon(self):
        """Make a Tray Icon."""
        if self.windowIcon() and __doc__:
            self.tray.setIcon(self.windowIcon())
            self.tray.setToolTip(__doc__)
            self.tray.activated.connect(
                lambda: self.hide() if self.isVisible() else self.showNormal())
            return self.tray.show()
Exemplo n.º 6
0
class WidgetGallery(QDialog):
    def __init__(self, parent=None):
        super(WidgetGallery, self).__init__(parent)

        self.init_mediaplayer()

        self.originalPalette = QApplication.palette()

        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())

        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)

        disableWidgetsCheckBox = QCheckBox("&Inactive Buttons")

        self.createTopLeftGroupBox()
        self.createTopRightGroupBox()

        styleComboBox.activated[str].connect(self.changeStyle)
        disableWidgetsCheckBox.toggled.connect(
            self.topLeftGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(
            self.topRightGroupBox.setDisabled)

        topLayout = QHBoxLayout()
        topLayout.addWidget(styleLabel)
        topLayout.addWidget(styleComboBox)
        topLayout.addStretch(1)
        topLayout.addWidget(disableWidgetsCheckBox)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.topLeftGroupBox, 1, 0)
        mainLayout.addWidget(self.topRightGroupBox, 1, 1)
        mainLayout.setRowStretch(5, 5)
        mainLayout.setRowStretch(2, 1)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)
        self.setWindowTitle("Radios Angola")
        self.changeStyle('windows')

    def init_mediaplayer(self):

        self.instance = vlc.Instance(
            '--quiet --audio-visual visualizer --effect-list spectrum')
        self.media = None
        # Create an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()
        self.mediaplayer.video_set_aspect_ratio("16:5")
        self.mediaplayer.video_set_scale(0.25)
        self.alsa = alsaaudio.Mixer(alsaaudio.mixers()[0])
        self.is_paused = False

    def getStatus(self):

        status = {
            "stream length": self.mediaplayer.get_length(),
            "current time": self.mediaplayer.get_time(),
            "volume media player": self.mediaplayer.audio_get_volume(),
            "volume ": self.alsa.getvolume()[0],
            "state": self.mediaplayer.get_state()
        }
        return status

    def changeStyle(self, styleName):
        QApplication.setStyle(QStyleFactory.create(styleName))

    def select_radio(self, qmodelindex):

        self.stop_stream()
        self.station_name = self.radio_stations_list.currentItem()

        if self.station_name is None:
            self.video_frame.setText("reloading ... ")
        else:
            self.radio_obj = network.get_station_obj(self.radio_json)
            self.selected = [
                radio for radio in self.radio_obj
                if radio.r_name == self.station_name.text()
            ]
            self.load_station(self.selected[0])

    def set_volume(self, volume):
        self.alsa.setvolume(volume)

    def refresh_stream(self):
        self.video_frame.setText("reloading ... ")
        self.stop_stream()
        self.play_pause()

    def previous_station(self, qmodelindex):
        self.stop_stream()
        try:
            curr_position = self.radio_stations_list.indexFromItem(
                self.station_name).row()
            previous_pos = curr_position - 1

            if previous_pos < 0:
                previous_station = self.radio_stations_list.item(
                    len(self.radio_obj) - 1)
                self.radio_stations_list.setCurrentItem(previous_station)
                self.select_radio(qmodelindex)
            else:
                previous_station = self.radio_stations_list.item(previous_pos)
                self.radio_stations_list.setCurrentItem(previous_station)
                self.select_radio(qmodelindex)
        except AttributeError:
            self.video_frame.setText("select a radio station")
            pass

    def next_station(self, qmodelindex):
        self.stop_stream()
        try:
            curr_position = self.radio_stations_list.indexFromItem(
                self.station_name).row()
            next_pos = curr_position + 1

            if (next_pos > len(self.radio_obj) - 1):
                next_station = self.radio_stations_list.item(0)
                self.radio_stations_list.setCurrentItem(next_station)
                self.select_radio(qmodelindex)

            else:
                next_station = self.radio_stations_list.item(next_pos)
                self.radio_stations_list.setCurrentItem(next_station)
                self.select_radio(qmodelindex)
        except AttributeError:
            self.video_frame.setText("select a radio station")
            pass

    def stop_stream(self):

        self.reset_video_frame()
        self.mediaplayer.stop()
        self.b_play.setIcon(QIcon('application/img/play.png'))
        self.is_paused = False

    def load_station(self, radio_station):
        self.video_frame.setText("loading ... ")
        try:
            self.media = self.instance.media_new(radio_station.stream_link)
            self.mediaplayer.set_media(self.media)
            self.media.parse()
            # for Linux using the X Server
            if sys.platform.startswith('linux'):
                self.mediaplayer.set_xwindow(self.video_frame.winId())

            # for Windows
            elif sys.platform == "win32":
                self.mediaplayer.set_hwnd(self.video_frame.winId())

            # for MacOS(
            elif sys.platform == "darwin":
                self.mediaplayer.set_nsobject(int(self.video_frame.winId()))

            self.play_pause()

        except VLCException as err:
            raise err

    def play_pause(self):

        if self.mediaplayer.is_playing():
            self.stop_stream()
            self.b_play.setIcon(QIcon('application/img/play.png'))
            self.is_paused = True
        else:
            if self.mediaplayer.play() == -1:
                self.video_frame.setText("select a radio station")
                self.video_frame.setAlignment(Qt.AlignCenter)
                return

            self.mediaplayer.play()
            self.b_play.setIcon(QIcon('application/img/pause.png'))
            self.is_paused = False
            self.video_frame.setText("")

    def createTopLeftGroupBox(self):

        self.topLeftGroupBox = QGroupBox("")

        self.video_frame = QLabel()
        self.reset_video_frame()

        self.b_refresh = QPushButton()
        self.b_refresh.setIcon(QIcon("application/img/refresh.png"))
        self.b_refresh.setIconSize(QSize(30, 30))
        self.b_refresh.setGeometry(QRect(30, 10, 10, 30))
        self.b_refresh.setToolTip("Refresh stream")
        self.b_refresh.clicked.connect(self.refresh_stream)

        self.b_previous = QPushButton()
        self.b_previous.setIcon(QIcon("application/img/back.png"))
        self.b_previous.setIconSize(QSize(30, 30))
        self.b_previous.setGeometry(QRect(30, 10, 10, 30))
        self.b_previous.setToolTip("Previous Radio Station")
        self.b_previous.clicked.connect(self.previous_station)

        self.b_play = QPushButton()
        self.b_play.setIcon(QIcon("application/img/play.png"))
        self.b_play.setIconSize(QSize(30, 30))
        self.b_play.setGeometry(QRect(30, 30, 30, 30))
        self.b_play.clicked.connect(self.play_pause)

        self.b_next = QPushButton()
        self.b_next.setIcon(QIcon("application/img/next.png"))
        self.b_next.setIconSize(QSize(30, 30))
        self.b_next.setGeometry(QRect(30, 30, 30, 30))
        self.b_next.setToolTip("Next Radio Station")
        self.b_next.clicked.connect(self.next_station)

        self.b_stop = QPushButton()
        self.b_stop.setIcon(QIcon("application/img/stop.png"))
        self.b_stop.setIconSize(QSize(30, 30))
        self.b_stop.setGeometry(QRect(30, 30, 30, 3))
        self.b_stop.setToolTip("Stop Streaming")
        self.b_stop.clicked.connect(self.stop_stream)

        layoutbuttons = QHBoxLayout()
        layoutbuttons.addWidget(self.b_refresh)
        layoutbuttons.addWidget(self.b_previous)
        layoutbuttons.addWidget(self.b_play)
        layoutbuttons.addWidget(self.b_next)
        layoutbuttons.addWidget(self.b_stop)

        self.dial_volume = QDial()
        #self.dial_volume.setMaximum(100)
        #self.dial_volume.setValue(self.mediaplayer.audio_get_volume())
        self.dial_volume.setValue(self.alsa.getvolume()[0])
        self.dial_volume.setNotchesVisible(True)
        self.dial_volume.setToolTip("Volume")
        self.dial_volume.valueChanged.connect(self.set_volume)

        layoutbuttons.addWidget(self.dial_volume)

        layout = QVBoxLayout()
        layout.addWidget(self.video_frame)
        layout.addLayout(layoutbuttons)
        self.topLeftGroupBox.setLayout(layout)

    def createTopRightGroupBox(self):

        self.topRightGroupBox = QGroupBox("radio stations")
        self.radio_json = network.get_stations_from_api()
        if self.radio_json is not None:
            self.station_names = network.get_station_names(self.radio_json)
            self.radio_stations_list = QListWidget()
            self.radio_stations_list.insertItems(0, self.station_names)
            self.radio_stations_list.clicked.connect(self.select_radio)
        else:
            self.radio_stations_list = QListWidget()
            self.radio_stations_list.insertItems(
                0, ["Server Down .... no radio stations"])

        layout = QVBoxLayout()
        layout.addWidget(self.radio_stations_list)

        self.topRightGroupBox.setLayout(layout)

    def reset_video_frame(self):
        self.video_frame.setStyleSheet("background-color: black")
        self.video_frame.setAutoFillBackground(True)
Exemplo n.º 7
0
class InstrumentTab(QWidget):
    INSTRUMENT_INDEX = 0

    def __init__(self):
        super().__init__()
        self.instrument = MusicalInstrument()
        self.chord = chord()
        self.initUI()
        self.bindEvent()

    def initUI(self):
        self.layout = QVBoxLayout()
        # 往上对齐
        self.layout.setAlignment(Qt.AlignTop)

        # 查询条件
        self.hbox = QGridLayout()
        self.hbox.setSpacing(1)

        # 和弦/音阶选择条件区域
        rootLabel = QLabel('根音')
        self.rootCombo = QComboBox()
        self.rootCombo.addItems(self.instrument.roots)
        self.rootCombo.setMinimumWidth(100)
        proLabel = QLabel('三音')
        self.proCombo = QComboBox()
        self.proCombo.addItems(self.instrument.pros)
        self.proCombo.setMinimumWidth(100)
        intervelLabel = QLabel('五音')
        self.intervelCombo = QComboBox()
        self.intervelCombo.addItems(self.instrument.intervals)
        self.intervelCombo.setMinimumWidth(100)
        self.mode = 0  # 0:scale mode ; 1:chord mode
        self.scaCheck = QRadioButton('音阶')
        self.scaCheck.setChecked(True)
        self.chordCheck = QRadioButton('和弦')
        scaleLabel = QLabel('音阶')
        self.scaleCombo = QComboBox()
        self.scaleCombo.addItems(self.instrument.scales)
        self.scaleCombo.setMinimumWidth(100)

        commonBox = QGroupBox('音阶/和弦')
        commonBox.setStyleSheet(
            "QGroupBox{ border: 1px groove grey; border-radius:5px;border-style: outset;}"
        )
        commonLayout = QGridLayout()
        commonBox.setLayout(commonLayout)
        commonLayout.addWidget(self.scaCheck, 0, 0)
        commonLayout.addWidget(self.chordCheck, 0, 1)
        commonLayout.addWidget(scaleLabel, 0, 2)
        commonLayout.addWidget(self.scaleCombo, 0, 3, 1, 3)
        commonLayout.addWidget(rootLabel, 1, 0)
        commonLayout.addWidget(self.rootCombo, 1, 1)
        commonLayout.addWidget(proLabel, 1, 2)
        commonLayout.addWidget(self.proCombo, 1, 3)
        commonLayout.addWidget(intervelLabel, 1, 4)
        commonLayout.addWidget(self.intervelCombo, 1, 5)

        # 控制条件区域
        self.fretLabel = QLabel('品数')
        self.guitarSlider = QDial()
        self.guitarSlider.setNotchesVisible(True)
        self.guitarSlider.setMaximumHeight(60)
        self.guitarSlider.setToolTip('21')
        self.guitarSlider.setMinimum(12)
        self.guitarSlider.setMaximum(24)
        self.guitarSlider.setValue(21)
        # piano
        self.pianoSlider = QDial()
        self.pianoSlider.setNotchesVisible(True)
        self.pianoSlider.setMaximumHeight(60)
        self.pianoSlider.setToolTip('4')
        self.pianoSlider.setMinimum(3)
        self.pianoSlider.setMaximum(7)
        self.pianoSlider.setValue(4)
        self.pianoSlider.hide()

        self.speedLabel = QLabel('播放速度')
        self.speedSlider = QDial()
        self.speedSlider.setNotchesVisible(True)
        self.speedSlider.setMaximumHeight(60)
        self.speedLabel.setToolTip('4')
        self.speedSlider.setMinimum(1)
        self.speedSlider.setMaximum(6)
        self.speedSlider.setValue(4)
        self.speed = 0.25

        instLabel = QLabel('音色')
        self.guitarInstCheck = QComboBox()
        self.guitarInstCheck.addItems(
            list(self.instrument.programs[24:31]
                 ))  # Arachno SoundFont - Version 1.0     024~030

        self.pianoInstCheck = QComboBox()
        self.pianoInstCheck.addItems(
            list(self.instrument.programs[:7]
                 ))  # Arachno SoundFont - Version 1.0     0~6
        self.pianoInstCheck.hide()

        pos = ['-', 'C', 'A', 'G', 'E', 'D', '3-note-per-string']
        self.posLabel = QLabel('把位')
        self.posCombo = QComboBox()
        self.posCombo.addItems(pos)
        self.posCombo.setMinimumWidth(100)

        controlBox = QGroupBox('控制')
        controlBox.setStyleSheet(
            "QGroupBox{ border: 1px groove grey; border-radius:5px;border-style: outset;}"
        )
        self.controlLayout = QGridLayout()
        controlBox.setLayout(self.controlLayout)
        self.controlLayout.addWidget(self.guitarSlider, 0, 0)
        self.controlLayout.addWidget(self.fretLabel, 1, 0)
        self.controlLayout.addWidget(self.speedSlider, 0, 1)
        self.controlLayout.addWidget(self.speedLabel, 1, 1)
        self.controlLayout.addWidget(instLabel, 0, 2)
        self.controlLayout.addWidget(self.guitarInstCheck, 0, 3)
        self.controlLayout.addWidget(self.posLabel, 1, 2)
        self.controlLayout.addWidget(self.posCombo, 1, 3)

        self.generateBtn = QPushButton('生成')
        self.generateBtn.setMaximumWidth(100)
        self.generateBtn.setStyleSheet(
            "QPushButton{border:1px groove grey;border-radius:5px;border-style:outset; min-height:40px;}"
        )
        self.playBtn = QPushButton('播放')
        self.playBtn.setMaximumWidth(100)
        self.playBtn.setStyleSheet(
            "QPushButton{border:1px groove grey;border-radius:5px;border-style:outset;min-height:40px;}"
        )

        self.hbox.addWidget(commonBox, 0, 0, 2, 1)
        self.hbox.addWidget(controlBox, 0, 2, 2, 1)
        self.hbox.addWidget(self.generateBtn, 0, 3)
        self.hbox.addWidget(self.playBtn, 1, 3)
        self.hbox.addWidget(QWidget(), 0, 4, 2, 1)  # 占位

        # 垂直布局
        self.layout.addLayout(self.hbox)
        self.tabBox = QTabWidget()
        self.panels = InstrumentPanel(self.instrument).createInstrumentPanel(
            ['Guitar', 'Piano'])
        for pn in self.panels:
            self.tabBox.addTab(pn, pn.name)

        self.switchMode()
        self.layout.addWidget(self.tabBox)
        self.setLayout(self.layout)

    def bindEvent(self):
        self.guitarSlider.valueChanged[int].connect(self.reDrawInstrument)
        self.pianoSlider.valueChanged[int].connect(self.reDrawInstrument)
        self.speedSlider.valueChanged[int].connect(self.switchSpeed)
        self.generateBtn.clicked.connect(self.reDrawInstrument)
        self.scaCheck.toggled.connect(self.switchMode)
        self.chordCheck.toggled.connect(self.switchMode)
        self.guitarInstCheck.currentTextChanged.connect(self.changeProgram)
        self.pianoInstCheck.currentTextChanged.connect(self.changeProgram)
        self.playBtn.clicked.connect(self.playSound)
        self.tabBox.currentChanged.connect(self.activeInstrument)

    # change the current instrument panel,show or hide the corresponding widget
    def activeInstrument(self, value):
        self.INSTRUMENT_INDEX = value
        if self.INSTRUMENT_INDEX == 0:  # GUITAR
            self.pianoSlider.hide()
            self.guitarSlider.show()
            self.pianoInstCheck.hide()
            self.guitarInstCheck.show()
            self.controlLayout.replaceWidget(self.pianoSlider,
                                             self.guitarSlider)
            self.controlLayout.replaceWidget(self.pianoInstCheck,
                                             self.guitarInstCheck)
            self.posLabel.setEnabled(True)
            self.posCombo.setEnabled(True)
            self.fretLabel.setText('品数')
        elif self.INSTRUMENT_INDEX == 1:  # PIANO
            self.pianoSlider.show()
            self.guitarSlider.hide()
            self.pianoInstCheck.show()
            self.guitarInstCheck.hide()
            self.controlLayout.replaceWidget(self.guitarSlider,
                                             self.pianoSlider)
            self.controlLayout.replaceWidget(self.guitarInstCheck,
                                             self.pianoInstCheck)
            self.posLabel.setEnabled(False)
            self.posCombo.setEnabled(False)
            self.fretLabel.setText('八度')

    def reDrawInstrument(self):
        notes = self.getNotes()

        if self.panels[self.INSTRUMENT_INDEX].name == 'Guitar':
            freStr = 'Fret num [' + str(self.guitarSlider.value()) + ']'
            self.guitarSlider.setToolTip(str(self.guitarSlider.value()))
            fretPosition = '\r\n[Guitar board position] POSITION ' + self.posCombo.currentText(
            )
            sound = self.guitarInstCheck.currentText()
            if len(notes) > 1:
                notes1 = []
                for note in notes:
                    notes1.append(note.split('-')[0])
                mode = self.scaleCombo.currentText() if self.mode == 0 else '-'
                self.panels[self.INSTRUMENT_INDEX].initPanel(
                    int(self.guitarSlider.value()), notes1, mode,
                    self.posCombo.currentText())
        elif self.panels[self.INSTRUMENT_INDEX].name == 'Piano':
            freStr = 'Octave num [' + str(self.pianoSlider.value()) + ']'
            self.pianoSlider.setToolTip(str(self.pianoSlider.value()))
            fretPosition = ''
            sound = self.pianoInstCheck.currentText()
            if len(notes) > 1:
                self.panels[self.INSTRUMENT_INDEX].initPanel(
                    int(self.pianoSlider.value()), notes)
        else:
            pass

        infoStr = '[Instrument] ' + self.panels[self.INSTRUMENT_INDEX].name
        infoStr = infoStr + '\r\n[Program] ' + sound
        infoStr = infoStr + '\r\n[Scope] ' + freStr
        infoStr = infoStr + '\r\n[Note mode] ' + ('scale' if self.mode == 0
                                                  else 'chord')
        infoStr = infoStr + '\r\n[Key] ' + notes[0]
        infoStr = infoStr + '\r\n[Notes] ' + str(notes)
        infoStr = infoStr + fretPosition
        infoStr = infoStr + '\r\n[Speed] ' + str(self.speed) + ' seconds'
        self.panels[self.INSTRUMENT_INDEX].detail.setText(infoStr)

    def switchMode(self):
        self.mode = self.scaCheck.isChecked()
        self.mode = self.chordCheck.isChecked()
        if self.mode == 0:  # scale
            self.scaCheck.setChecked(True)
            self.chordCheck.setChecked(False)
            self.scaleCombo.setEnabled(True)
            self.proCombo.setEnabled(False)
            self.intervelCombo.setEnabled(False)
        else:  # chord
            self.scaCheck.setChecked(False)
            self.chordCheck.setChecked(True)
            self.scaleCombo.setEnabled(False)
            self.proCombo.setEnabled(True)
            self.intervelCombo.setEnabled(True)

    def switchSpeed(self, value):
        sp = {1: 1, 2: 0.75, 3: 0.5, 4: 0.25, 5: 0.1, 6: 0.05}
        self.speed = sp.get(value)
        self.speedSlider.setToolTip(str(self.speed))

    # change instrument's program
    def changeProgram(self, value):
        self.panels[self.INSTRUMENT_INDEX].changeProgram(value)

    # play a note or chord
    def playSound(self):
        notes = self.getNotes()
        if len(notes) > 1:
            self.panels[self.INSTRUMENT_INDEX].playArpeggio(notes, self.speed)

    # get all notes
    def getNotes(self):
        if self.mode == 0:  # scale
            notes = list(
                self.chord.getScales(self.rootCombo.currentText(),
                                     self.scaleCombo.currentText()).values())
        else:  # chord
            notes = list(
                self.chord.getChord(self.rootCombo.currentText(),
                                    self.proCombo.currentText(),
                                    self.intervelCombo.currentText()).values())
        return notes