Exemple #1
0
class ScopeShotTimer(QDialog):
    def __init__(self):
        super(ScopeShotTimer, self).__init__()

        self.initUI()

    def initUI(self):

        self.count = 0

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.Time)
        self.timer.start(1000)

        self.lcd = QLCDNumber(self)
        # get the palette
        palette = self.lcd.palette()

        # foreground color
        palette.setColor(palette.WindowText, QtGui.QColor(85, 85, 255))
        # background color
        palette.setColor(palette.Background, QtGui.QColor(0, 170, 255))
        # "light" border
        palette.setColor(palette.Light, QtGui.QColor(255, 0, 0))
        # "dark" border
        palette.setColor(palette.Dark, QtGui.QColor(0, 255, 0))

        # set the palette
        self.lcd.setPalette(palette)
        self.lcd.setMinimumHeight(100)
        self.lcd.setMinimumWidth(148)

        self.lcd.display(self.count)

        diologGrid = QGridLayout()
        diologGrid.addWidget(self.lcd, 0, 0)

        self.okButton = QPushButton('Capture Scope Shot', self)
        self.okButton.clicked[bool].connect(self.close)
        diologGrid.addWidget(self.okButton, 0, 1)

        self.setLayout(diologGrid)

        self.setGeometry(200, 200, 150, 100)
        self.setWindowTitle('Scope Capture')
        self.setWindowIcon(QIcon('xbox_icon.ico'))

    def Time(self):
        #        self.lcd.display(strftime("%H"+":"+"%M"+":"+"%S"))
        self.count += 1
        self.lcd.display(self.count)
        if self.count == 120:
            print '\a'
class TimeSettingWidget(QWidget):
    def __init__(self, parent=None):
        super(TimeSettingWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.lcd = QLCDNumber(self)
        self.lcd.setNumDigits(2)
        self.lcd.setMinimumHeight(80)
        self.lcd.setStyleSheet("QLCDNumber{ color: black;}")
        self.sld = QSlider(Qt.Horizontal, self)
        self.sld.setMinimum(1)
        self.sld.setMaximum(90)

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.lcd)
        self.vbox.addWidget(self.sld)

        self.setLayout(self.vbox)
        self.sld.valueChanged.connect(self.lcd.display)

    def setTime(self, t):
        self.sld.setValue(t)

    def setDisplayTime(self, t):
        self.lcd.display(t)

    def setActiveStyle(self):
        self.lcd.setStyleSheet("QLCDNumber{ color: green;}")

    def setInactiveStyle(self):
        self.lcd.setStyleSheet("QLCDNumber{ color: black;}")

    def setSliderEnable(self, bool):
        self.sld.setEnabled(bool)

    def freshDisplayTime(self):
        self.lcd.display(self.sld.value())

    def getTime(self):
        return self.sld.value()
class Objetives(QWidget):
    NumButtons = 3

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

        self.createDisplay()
        self.createDisplayAverage()
        self.createButtons()

        self.numVictory = 0
        self.numLosses = 0

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.displayLCD)
        mainLayout.addWidget(self.horizontalGroupBox)
        mainLayout.addWidget(self.displayWinPercent)

        self.setLayout(mainLayout)

        self.setWindowTitle("Objetives")

    def createButtons(self):
        self.horizontalGroupBox = QGroupBox("")
        layout = QGridLayout()

        self.victoryButton = self.createButton("Victory", "+",self.addVictoryOrLosses)
        self.lossesButton = self.createButton("Losses", "+",self.addVictoryOrLosses)
        self.victoryDecreaseButton = self.createButton("DV","-",self.addVictoryOrLosses)
        self.losseDecreaseButton = self.createButton("DL","-",self.addVictoryOrLosses)

        self.lossesButton.setMinimumWidth(150)
        self.victoryButton.setMinimumWidth(150)

        self.losseDecreaseButton.setMaximumHeight(20)
        self.victoryDecreaseButton.setMaximumHeight(20)

        layout.addWidget(self.victoryButton, 0, 0, 1, 1)
        layout.addWidget(self.lossesButton, 0, 2, 1, 1)
        layout.addWidget(self.victoryDecreaseButton, 1, 0, 1, 1)
        layout.addWidget(self.losseDecreaseButton, 1, 2, 1, 1)

        self.horizontalGroupBox.setLayout(layout)

    def createDisplayAverage(self):
        self.displayWinPercent = QGroupBox("Wins")
        layout = QHBoxLayout()

        self.progressBar = QProgressBar()
        self.progressBar.setRange(0, 100)
        # self.progressBar.setValue(5000)

        layout.addWidget(self.progressBar)

        self.displayWinPercent.setLayout(layout)

    def createDisplay(self):
        self.displayLCD = QGroupBox("")
        layout = QHBoxLayout()

        paletteLosses = QPalette()
        paletteVictory = QPalette()

        paletteLosses.setColor(paletteLosses.WindowText, QColor(255, 000, 000))
        paletteVictory.setColor(paletteVictory.WindowText, QColor(000, 255, 000))

        self.lossesLcd = QLCDNumber(3)
        self.lossesLcd.setSegmentStyle(QLCDNumber.Filled)
        self.lossesLcd.setPalette(paletteLosses)

        self.victoryLcd = QLCDNumber(3)
        self.victoryLcd.setSegmentStyle(QLCDNumber.Filled)
        self.victoryLcd.setPalette(paletteVictory)

        self.lossesLcd.setMinimumHeight(100)
        self.victoryLcd.setMinimumHeight(100)

        self.lossesLcd.setMinimumWidth(150)
        self.victoryLcd.setMinimumWidth(150)

        layout.addWidget(self.victoryLcd)
        layout.addWidget(self.lossesLcd)

        self.displayLCD.setLayout(layout)

    def addVictoryOrLosses(self):
        clickedButton = self.sender()
        clickedOperator = clickedButton.text()
        operand = float(1)

        if clickedOperator == "Victory":
            self.numVictory = self.numVictory + 1
            self.victoryLcd.display(str(self.numVictory))

        if clickedOperator == "DV":
            self.numVictory = self.numVictory - 1
            self.victoryLcd.display(str(self.numVictory))

        if clickedOperator == "Losses":
            self.numLosses = self.numLosses + 1
            self.lossesLcd.display(str(self.numLosses))

        if clickedOperator == "DL":
            self.numLosses = self.numLosses - 1
            self.lossesLcd.display(str(self.numLosses))

        self.calculateAverage()

    def calculateAverage(self):
        total = self.numVictory + self.numLosses

        # self.progressBar.setValue((int(self.numVictory / total * 100)))
        self.progressBar.setValue(100)
        # self.victoryLcdAv.display(str(int(self.numVictory / total * 100)))
        # self.lossesLcdAv.display(str(int(self.numLosses / total * 100)))

    def createButton(self, text, op, member):
        button = Button(text,op)
        button.clicked.connect(member)
        return button
class Form(QWidget):
    def get_win_resolution_XY(self):
        res_x = pyautogui.size()[0]
        res_y = pyautogui.size()[1]

        return res_x, res_y

    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.dirty_flag = False

        self.res_x, self.res_y = self.get_win_resolution_XY()

        self.setWindowTitle("Save URLs")
        #self.setFixedWidth(480)
        #self.setFixedHeight(680)
        #self.setFixedWidth(640)
        #self.setFixedHeight(480)
        self.setMaximumWidth(self.res_x)
        self.setMaximumHeight(self.res_y)

        # start location
        self.move(self.res_x - 500, 200)

        # 환경 변수 파일 이름
        self.config_filename = "./config.txt"

        self.cfg = Config(self.config_filename)

        layout_base = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(layout_base)

        ##########################################################
        # 영번째 그룹 (타이머 표시)
        ##########################################################
        self.remain_time = 0

        ## 0.1 Timer
        self.flag = 1  # 0 : 시작위치, 1 : 저장위치

        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.timeout)

        ## 0.2 LCD
        self.lcd = QLCDNumber(self)
        self.lcd.setMinimumHeight(80)

        ## 0번째 그룹 설정
        grp_0 = QGroupBox("Lcd..")
        layout_base.addWidget(grp_0)
        layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        layout.addWidget(self.lcd)
        grp_0.setLayout(layout)

        ##########################################################
        # 첫번째 그룹 (사용자 입력값 받기, QGridLayout)
        ##########################################################
        ## 1.1 최하단 위치
        self.lbl_max_y = QLabel(str(self.cfg.win_last_pos_y))

        ## 1.2 전체 URL 수
        self.sb_url_t = QSpinBox()
        self.sb_url_t.setMinimum(1)
        self.sb_url_t.setMaximum(200)
        self.sb_url_t.setValue(self.cfg.total_url_count)
        self.sb_url_t.setSingleStep(1)

        self.lbl_url_t = QLabel(str(self.cfg.total_url_count))

        ## 1.3 화면 URL 수
        self.sb_url_w = QSpinBox()
        self.sb_url_w.setMinimum(1)
        self.sb_url_w.setMaximum(100)
        self.sb_url_w.setValue(self.cfg.win_url_count)
        self.sb_url_w.setSingleStep(1)

        self.lbl_url_w = QLabel(str(self.cfg.win_url_count))

        ## 1.4 첫번째 URL의 시작위치 (X, Y)
        self.btn_s_url_XY = QPushButton('Get', self)
        self.btn_s_url_XY.setMaximumWidth(200)
        self.lbl_s_url_XY = QLabel("({},{})".format(self.cfg.win_s_pos_x,
                                                    self.cfg.win_s_pos_y))

        ## 1.5 Save RAW 위치(X, Y)
        self.btn_save_raw_pos_XY = QPushButton('Get', self)
        self.btn_save_raw_pos_XY.setMaximumWidth(200)
        self.lbl_save_raw_pos_XY = QLabel("({},{})".format(
            self.cfg.win_save_raw_pos_x, self.cfg.win_save_raw_pos_y))

        ## 1.6 Request 위치 (X, Y)
        self.btn_req_pos_XY = QPushButton('Get', self)
        self.btn_req_pos_XY.setMaximumWidth(200)
        self.lbl_req_pos_XY = QLabel("({},{})".format(self.cfg.win_req_pos_x,
                                                      self.cfg.win_req_pos_y))

        ## 1.7 Header 위치 (X, Y)
        self.btn_req_header_XY = QPushButton('Get', self)
        self.btn_req_header_XY.setMaximumWidth(200)
        self.lbl_req_header_XY = QLabel("({},{})".format(
            self.cfg.win_req_header_x, self.cfg.win_req_header_y))

        ## 1.8 파일 입력 창 위치 (X, Y)
        self.btn_save_XY = QPushButton('Get', self)
        self.btn_save_XY.setMaximumWidth(200)
        self.lbl_save_XY = QLabel("({},{})".format(
            self.cfg.win_out_file_pos_x, self.cfg.win_out_file_pos_y))

        ## 1.9 prefix
        self.lbl_prefix = QLabel(self.cfg.prefix)
        self.le_prefix = QLineEdit(self)
        self.le_prefix.setMaximumWidth(100)

        ## 1.10 save directory
        self.lbl_save_dir = QLabel(self.reduce_string(self.cfg.save_dir))
        #self.lbl_save_dir = QLabel(self.cfg.save_dir)
        self.pb_save_dir = QPushButton("Choose")
        self.pb_save_dir.setMaximumWidth(200)

        ## 1번째 그룹 설정
        grp_1 = QGroupBox("Check Inputs")

        layout_base.addWidget(grp_1)
        layout = QGridLayout()

        # Grid ( , 0)
        layout.addWidget(QLabel('최하단 위치(Y)'), 0, 0)
        layout.addWidget(QLabel('전체 URL 수'), 1, 0)
        layout.addWidget(QLabel('화면 URL 수'), 2, 0)
        layout.addWidget(QLabel('시작위치'), 3, 0)
        layout.addWidget(QLabel('Save RAW 위치'), 4, 0)
        layout.addWidget(QLabel('Request 위치'), 5, 0)
        layout.addWidget(QLabel('Header 위치'), 6, 0)
        layout.addWidget(QLabel('파일입력창 위치'), 7, 0)
        layout.addWidget(QLabel('파일시작명'), 8, 0)
        layout.addWidget(QLabel('파일저장 위치'), 9, 0)

        # Grid ( , 1)
        layout.addWidget(self.sb_url_t, 1, 1)
        layout.addWidget(self.sb_url_w, 2, 1)
        layout.addWidget(self.btn_s_url_XY, 3, 1)
        layout.addWidget(self.btn_save_raw_pos_XY, 4, 1)
        layout.addWidget(self.btn_req_pos_XY, 5, 1)
        layout.addWidget(self.btn_req_header_XY, 6, 1)
        layout.addWidget(self.btn_save_XY, 7, 1)
        layout.addWidget(self.le_prefix, 8, 1)
        layout.addWidget(self.pb_save_dir, 9, 1)

        # Grid ( , 2)
        layout.addWidget(self.lbl_max_y, 0, 2)
        layout.addWidget(self.lbl_url_t, 1, 2)
        layout.addWidget(self.lbl_url_w, 2, 2)
        layout.addWidget(self.lbl_s_url_XY, 3, 2)
        layout.addWidget(self.lbl_save_raw_pos_XY, 4, 2)
        layout.addWidget(self.lbl_req_pos_XY, 5, 2)
        layout.addWidget(self.lbl_req_header_XY, 6, 2)
        layout.addWidget(self.lbl_save_XY, 7, 2)
        layout.addWidget(self.lbl_prefix, 8, 2)
        layout.addWidget(self.lbl_save_dir, 9, 2)

        grp_1.setLayout(layout)

        # 1번째 그룹 이벤트 정리
        self.sb_url_t.valueChanged.connect(self.value_changed_t)
        self.sb_url_w.valueChanged.connect(self.value_changed_w)
        self.btn_s_url_XY.clicked.connect(self.get_s_url_XY)
        self.btn_save_raw_pos_XY.clicked.connect(self.get_save_raw_pos_XY)
        self.btn_req_pos_XY.clicked.connect(self.get_req_pos_XY)
        self.btn_req_header_XY.clicked.connect(self.get_req_header_XY)
        self.btn_save_XY.clicked.connect(self.get_save_XY)
        self.le_prefix.textChanged[str].connect(self.onChanged)
        self.pb_save_dir.clicked.connect(self.get_save_dir)

        ##########################################################
        # 두번째 그룹 (실행부, QBoxLayout)
        ##########################################################
        # 2번째 그룹 변수들
        self.btn_test = QPushButton("Test")
        self.btn_clear = QPushButton("Clear")
        self.btn_run = QPushButton("Run")
        self.btn_quit = QPushButton("Quit")

        # 2번째 그룹 설정
        grp_2 = QGroupBox("Run...")
        layout_base.addWidget(grp_2)
        layout = QHBoxLayout()
        layout.addWidget(self.btn_test)
        layout.addWidget(self.btn_clear)
        layout.addWidget(self.btn_run)
        layout.addWidget(self.btn_quit)
        grp_2.setLayout(layout)

        # 2번째 그룹 이벤트 정리
        """
        self.btn_test.clicked.connect(self.printMessage("Test"))
        self.btn_run.clicked.connect(self.printMessage("Run"))
        self.btn_quit.clicked.connect(self.printMessage("Quit"))
        """
        self.btn_test.clicked.connect(self.printMessage_test)
        self.btn_clear.clicked.connect(self.printMessage_clear)
        self.btn_run.clicked.connect(self.printMessage_run)
        #self.btn_quit.clicked.connect(self.printMessage_quit)
        #self.btn_quit.clicked.connect(self.close)
        self.btn_quit.clicked.connect(self.printMessage_quit)

        ##########################################################
        # 세번째 그룹 (메시지 출력부)
        ##########################################################
        # 3번쨰 그룹 변수들
        self.lbl_msg = QLabel()

        # 3번째 그룹 설정
        grp_3 = QGroupBox("Message..")
        layout_base.addWidget(grp_3)
        layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        layout.addWidget(self.lbl_msg)
        grp_3.setLayout(layout)

    def onChanged(self, text):
        self.cfg.prefix = text
        self.lbl_prefix.setText(self.cfg.prefix)
        self.lbl_prefix.adjustSize()

    '''
    def printMessage_save(self):
        self.lbl_msg.setText("'Save' button pressed...")
        time.sleep(2)
        msg = """self.cfg.win_last_pos_y = {}
self.cfg.total_url_count = {}
self.cfg.win_url_count = {}
self.cfg.win_s_pos_(x,y) = ({},{})
self.cfg.win_out_file_pos_(x,y) = ({},{})
self.cfg.prefix = {}
self.cfg.stop_count = {}""".format(self.cfg.win_last_pos_y, self.cfg.total_url_count, self.cfg.win_url_count, self.cfg.win_s_pos_x, self.cfg.win_s_pos_y, self.cfg.win_save_raw_pos_x, self.cfg.win_save_raw_pos_y, self.cfg.win_req_pos_x, self.cfg.win_req_pos_y, sef.cfg.win_req_header_x, self.cfg.win_req_header_y, self.cfg.win_out_file_pos_x, self.cfg.win_out_file_pos_y, self.cfg.prefix, self.cfg.stop_count)
        self.lbl_msg.setText(msg)

        self.update_config_file()
    '''

    def printMessage_test(self):
        self.update_config_file()
        #su = saveURL(self.config_filename, False, False, False)
        su = saveURL(self.config_filename, True, False, False)
        for i in range(self.cfg.stop_count):
            msg = "{}th url processing...".format(i + 1)
            self.lbl_msg.setText(msg)
            self.lbl_msg.repaint()
            su.save_current_url(i)

        msg = "test completed...."
        self.lbl_msg.setText(msg)
        self.lbl_msg.repaint()

    def printMessage_clear(self):

        self.dirty_flag = False

        if not os.path.exists(self.cfg.save_dir):
            msg = "{} not found..".format(self.cfg.save_dir)
            self.lbl_msg.setText(msg)
            self.lbl_msg.repaint()
            return

        msg = "clearing output directory...\n [{}]".format(self.cfg.save_dir)
        self.lbl_msg.setText(msg)
        self.lbl_msg.repaint()

        time.sleep(0.5)

        shutil.rmtree(self.cfg.save_dir, ignore_errors=True)
        os.makedirs(self.cfg.save_dir)

        msg = "clearing output directory completed...\n [{}]".format(
            self.cfg.save_dir)
        self.lbl_msg.setText(msg)
        self.lbl_msg.repaint()

    def printMessage_run(self):
        self.update_config_file()

        err_no = self.check_save_dir()

        if err_no < 0:
            msg = "error no : {}".format(err_no)
            self.lbl_msg.setText(msg)
            self.lbl_msg.repaint()

            return

        su = saveURL(self.config_filename, False, True, True)
        for i in range(self.cfg.total_url_count):
            msg = "{}th url processing...".format(i + 1)
            self.lbl_msg.setText(msg)
            self.lbl_msg.repaint()
            su.save_current_url(i)

        msg_1 = "python ~/webhack_storage/PROJECT_K/ZAP_RESULT/XSS/22.MAKE_XSS_URL_FROM_DIR.py --input_dir {}\n".format(
            self.cfg.save_dir)
        msg_2 = "python ~/webhack_storage/PROJECT_K/ZAP_RESULT/SQLInjection/22.MAKE_SQL_MAP_URL.py --input_dir {}\n".format(
            self.cfg.save_dir)
        msg = "{}{}".format(msg_1, msg_2)
        self.lbl_msg.setText(msg)
        self.lbl_msg.repaint()

        self.dirty_flag = True

    def printMessage_quit(self):
        self.lbl_msg.setText("'Quit' button pressed...")
        if self.dirty_flag:
            msg_1 = "python ~/webhack_storage/PROJECT_K/ZAP_RESULT/XSS/22.MAKE_XSS_URL_FROM_DIR.py \n\t--input_dir {}\n".format(
                self.cfg.save_dir)
            msg_2 = "python ~/webhack_storage/PROJECT_K/ZAP_RESULT/SQLInjection/22.MAKE_SQL_MAP_URL.py \n\t--input_dir {}\n".format(
                self.cfg.save_dir)
            print("\n{}{}".format(msg_1, msg_2))
        self.close()

    def printMessage_lcd(self, sec):
        self.lbl_msg.setText("{} seconds remained...".format(sec))

    def value_changed_t(self):
        self.cfg.total_url_count = self.sb_url_t.value()
        self.lbl_url_t.setText(str(self.cfg.total_url_count))

    def value_changed_w(self):
        self.cfg.win_url_count = self.sb_url_w.value()
        self.lbl_url_w.setText(str(str(self.cfg.win_url_count)))

    def timeout(self):
        if self.remain_time <= 0:
            self.timer.stop()
            x = pyautogui.position()[0]
            y = pyautogui.position()[1]

            xy = "({},{})".format(x, y)

            if self.flag == 0:
                self.cfg.win_s_pos_x = x
                self.cfg.win_s_pos_y = y
                self.lbl_s_url_XY.setText(xy)

                return

            if self.flag == 1:
                self.cfg.win_save_raw_pos_x = x
                self.cfg.win_save_raw_pos_y = y
                self.lbl_save_raw_pos_XY.setText(xy)

                return

            if self.flag == 2:
                self.cfg.win_req_pos_x = x
                self.cfg.win_req_pos_y = y
                self.lbl_req_pos_XY.setText(xy)

                return

            if self.flag == 3:
                self.cfg.win_req_header_x = x
                self.cfg.win_req_header_y = y
                self.lbl_req_header_XY.setText(xy)

                return

            if self.flag == 4:
                self.cfg.win_out_file_pos_x = x
                self.cfg.win_out_file_pos_y = y
                self.lbl_save_XY.setText(xy)

                return

        sender = self.sender()
        self.remain_time = self.remain_time - 1
        if id(sender) == id(self.timer):
            self.lcd.display(str(self.remain_time))
        self.lbl_msg.setText("{} seconds remained..".format(self.remain_time))

    def get_s_url_XY(self):
        #self.lbl_msg.setText("5 seconds remained...")
        self.remain_time = 6
        self.flag = 0
        self.timer.start()

    def get_save_raw_pos_XY(self):
        #self.lbl_msg.setText("5 seconds remained...")
        self.remain_time = 6
        self.flag = 1
        self.timer.start()

    def get_req_pos_XY(self):
        #self.lbl_msg.setText("5 seconds remained...")
        self.remain_time = 6
        self.flag = 2
        self.timer.start()

    def get_req_header_XY(self):
        #self.lbl_msg.setText("5 seconds remained...")
        self.remain_time = 6
        self.flag = 3
        self.timer.start()

    def get_save_XY(self):
        #self.lbl_msg.setText("5 seconds remained...")
        self.remain_time = 6
        self.flag = 4
        self.timer.start()

    def get_save_dir(self):
        """
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.DirectoryOnly)
        save_dir = QFileDialog.getOpenFileName()
        self.lbl_save_dir.setText(save_dir[0])
        """
        new_save_dir = QFileDialog.getExistingDirectory(
            self, "Choose Directory", self.cfg.save_dir)
        if new_save_dir == '':
            self.lbl_msg.setText("Choose Directory Canceled...")
            self.lbl_msg.repaint()
            return

        self.lbl_msg.setText(new_save_dir)
        self.lbl_msg.repaint()
        self.cfg.save_dir = new_save_dir
        self.lbl_save_dir.setText(self.reduce_string(self.cfg.save_dir))
        #self.lbl_save_dir.setText(self.cfg.save_dir)
        self.lbl_save_dir.repaint()

    def make_30_chars(self, str):
        if len(str) <= 30:
            return str
        new_str = "..{}".format(str[-28:])

        return new_str

    def reduce_string(self, str, max_chars=40):
        if len(str) <= max_chars:
            return str

        sp = (max_chars * -1) + 2
        new_str = "..{}".format(str[sp:])

        return new_str

    def update_config_file(self):
        self.cfg.make_config_dict_from_self()
        self.cfg.save_config_file()

    def get_file_list(self):
        fileList = []
        rootdir = self.cfg.save_dir

        for root, subFolders, files in os.walk(rootdir):
            for file in files:
                fileList.append(os.path.join(root, file))

        return fileList

    def check_save_dir(self):
        if not os.path.exists(self.cfg.save_dir):
            reply = QMessageBox.question(self, "Message",
                                         "Do you want to make save_dir?",
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)

            if reply == QMessageBox.Yes:
                os.makedirs(self.cfg.save_dir)
                return 0
            else:
                return -1001

        file_list = self.get_file_list()
        if len(file_list) > 0:
            reply = QMessageBox.question(self, "Message",
                                         "Do you want to remove all files?",
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.Yes)

            if reply == QMessageBox.Yes:
                shutil.rmtree(self.cfg.save_dir, ignore_errors=True)
                os.makedirs(self.cfg.save_dir)
                return 0
            else:
                return -2000

        return 0
Exemple #5
0
class Preferences(QMainWindow):
    """
    Preferences window
    """
    def __init__(self, parent, status_queue):
        """
        Initialize preferences window.

        It allows to:

        * enable or disable process discovery analysis
        * select the number of runs after which event log is generated
        * select analysis type (either decision points or most frequent routine)

        :param status_queue: queue to send messages to main GUI
        """
        super(Preferences, self).__init__(
            parent,
            flags=Qt.Window | Qt.WindowTitleHint | Qt.CustomizeWindowHint
            | Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint)

        self.status_queue = status_queue
        self.setWindowTitle(" ")
        if WINDOWS:
            self.resize(360, 320)

        if WINDOWS:
            monospaceFont = 'Lucida Console'
            fontSize = 10
        elif MAC:
            monospaceFont = 'Monaco'
            fontSize = 13
        else:
            monospaceFont = 'monospace'
            fontSize = 13
        font = QFont(monospaceFont, fontSize, QFont.Normal)

        self.decisionGroupBox = QGroupBox("Analysis type")

        self.process_discovery_cb = QCheckBox(
            "Enable Process Discovery \nanalysis on event log")
        self.process_discovery_cb.setToolTip(
            "If enabled, process discovery analysis is performed automatically\n"
            "after selecting event log file, otherwise only event log is generated"
        )
        self.process_discovery_cb.tag = "process_discovery_cb"
        self.process_discovery_cb.stateChanged.connect(self.handle_cb)
        perform_process_discovery = utils.config.MyConfig.get_instance(
        ).perform_process_discovery
        self.process_discovery_cb.setChecked(perform_process_discovery)
        self.decisionGroupBox.setEnabled(perform_process_discovery)

        self.mfr = QRadioButton("Most frequent routine")
        self.mfr.clicked.connect(self.handle_radio)
        self.mfr.setChecked(utils.config.MyConfig.get_instance().
                            enable_most_frequent_routine_analysis)
        self.mfr.setToolTip(
            "Create SW Robot based on most frequent routine in the event log")

        self.decision = QRadioButton("Decision points")
        self.decision.clicked.connect(self.handle_radio)
        self.decision.setChecked(utils.config.MyConfig.get_instance().
                                 enable_decision_point_analysis)
        self.decision.setToolTip("Create SW Robot based on user decisions")

        self.decisionRPA = QRadioButton("Decision points in UiPath")
        self.decisionRPA.clicked.connect(self.handle_radio)
        self.decisionRPA.setChecked(utils.config.MyConfig.get_instance().
                                    enable_decision_point_RPA_analysis)
        self.decisionRPA.setToolTip(
            "Create SW Robot that asks for user decisions in UiPath script")

        slider_minimum = 1 if utils.config.MyConfig.get_instance(
        ).enable_most_frequent_routine_analysis else 2
        slider_maximum = 30

        self.lcd = QLCDNumber(self)
        self.lcd.setMinimumHeight(45)

        self.sld = QSlider(Qt.Horizontal, self)
        self.sld.setMinimum(slider_minimum)
        self.sld.setMaximum(slider_maximum)
        self.sld.setValue(
            utils.config.MyConfig.get_instance().totalNumberOfRunGuiXes)
        self.sld.valueChanged.connect(self.handle_slider)

        label_minimum = QLabel(str(1), alignment=Qt.AlignLeft, font=font)
        label_maximum = QLabel(str(slider_maximum),
                               alignment=Qt.AlignRight,
                               font=font)

        self.slider_label = QLabel(
            "Number of runs after which \nevent is generated:")
        self.slider_label.setToolTip(
            "When the selected number of runs is reached, all CSV logs collected are merged into one \nand a XES file "
            "is automatically generated, to be used for process mining techniques"
        )
        self.handle_slider()

        confirmButton = QPushButton("OK")
        confirmButton.setCheckable(True)
        confirmButton.setChecked(False)
        confirmButton.clicked.connect(self.handleButton)
        if darkdetect.isDark():
            confirmButton.setStyleSheet(
                'QPushButton {background-color: #656565;}')

        processDiscoveryGroupBox = QGroupBox("Process Discovery")
        vbox = QVBoxLayout()
        vbox.addWidget(self.process_discovery_cb)
        processDiscoveryGroupBox.setLayout(vbox)

        vbox = QVBoxLayout()
        vbox.addWidget(self.mfr)
        vbox.addWidget(self.decision)
        # vbox.addWidget(self.decisionRPA)
        self.decisionGroupBox.setLayout(vbox)

        xesGroupBox = QGroupBox()
        vbox = QVBoxLayout()
        vbox.addWidget(self.slider_label)
        vbox.addWidget(self.lcd)
        vbox.addSpacing(10)
        vbox.addWidget(self.sld)
        hbox = QHBoxLayout()
        hbox.addWidget(label_minimum, Qt.AlignLeft)
        hbox.addWidget(label_maximum, Qt.AlignRight)
        vbox.addLayout(hbox)
        xesGroupBox.setLayout(vbox)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(processDiscoveryGroupBox)
        mainLayout.addWidget(self.decisionGroupBox)
        mainLayout.addWidget(xesGroupBox)
        mainLayout.addWidget(confirmButton)

        wid = QWidget(self)
        self.setCentralWidget(wid)
        wid.setLayout(mainLayout)
        wid.setGeometry(300, 300, 250, 150)
        wid.show()

    def handle_slider(self):
        value = self.sld.value()
        self.lcd.display(value)
        utils.config.MyConfig.get_instance().totalNumberOfRunGuiXes = value

    def handle_cb(self):
        perform = self.process_discovery_cb.isChecked()
        self.decisionGroupBox.setEnabled(perform)
        utils.config.MyConfig.get_instance(
        ).perform_process_discovery = perform
        if perform:
            self.status_queue.put("[GUI] Process discovery enabled")
        else:
            self.status_queue.put("[GUI] Process discovery disabled")

    def handle_radio(self):
        mfr_checked = self.mfr.isChecked()
        decision_checked = self.decision.isChecked()
        decisionRPA_checked = self.decisionRPA.isChecked()

        utils.config.MyConfig.get_instance(
        ).enable_most_frequent_routine_analysis = mfr_checked
        utils.config.MyConfig.get_instance(
        ).enable_decision_point_analysis = decision_checked
        utils.config.MyConfig.get_instance(
        ).enable_decision_point_RPA_analysis = decisionRPA_checked

        # update lcd value, if decision there should be at least 2 traces
        if mfr_checked:
            self.sld.setMinimum(1)
            self.sld.setValue(1)
        else:
            self.sld.setMinimum(2)

        msg = "[GUI] "
        if mfr_checked:
            msg += "Most frequent routine analysis enabled"
        elif decision_checked:
            msg += "Decision point analysis enabled"
        elif decisionRPA_checked:
            msg += "Decision point analysis in RPA script enabled"
        self.status_queue.put(msg)

    def handleButton(self):
        self.close()
Exemple #6
0
class OmniRigQTControls:
    def __init__(self, operatingAsClient, sendCommandFunction=None):
        self.operatingAsClient = operatingAsClient
        self.omnirigObject = None
        self.omniRigInfo = {}
        self.sendCommandFunction = sendCommandFunction
        self.blackColorPalette = QPalette()
        self.blackColorPalette.setColor(QPalette.WindowText, QColor("black"))
        self.redColorPalette = QPalette()
        self.redColorPalette.setColor(QPalette.WindowText, QColor("red"))
        self.boldFont = QFont()
        self.boldFont.setBold(True)
        self.regularFont = QFont()
        self.regularFont.setBold(False)

        self.labelRigName = QLabel("Rig is not responding")
        self.rigSelectGroupBox = QGroupBox("Rig select:")

        self.radioBtnTRX1 = QRadioButton("Rig 1")
        self.radioBtnTRX1.setChecked(True)
        self.radioBtnTRX1.toggled.connect(self.refreshRigInformation)
        self.radioBtnTRX2 = QRadioButton("Rig 2")
        self.radioBtnTRX2.toggled.connect(self.refreshRigInformation)

        hboxRigSelect = QHBoxLayout()
        hboxRigSelect.addWidget(self.radioBtnTRX1)
        hboxRigSelect.addWidget(self.radioBtnTRX2)
        hboxRigSelect.addWidget(self.labelRigName)
        hboxRigSelect.addStretch()
        self.rigSelectGroupBox.setLayout(hboxRigSelect)
        self.rigSelectGroupBox.setMaximumWidth(360)

        self.lcdTrxFrequency = QLCDNumber(10)
        self.lcdTrxFrequency.display('00.000.00')
        self.lcdTrxFrequency.setPalette(self.blackColorPalette)
        self.lcdTrxFrequency.setMinimumHeight(50)
        self.lcdTrxFrequency.setMaximumHeight(50)
        self.lcdTrxFrequency.setMaximumWidth(275)
        self.lcdTrxFrequency.setMinimumWidth(275)

        self.labelRigModeLSB = QLabel('LSB')
        self.labelRigModeLSB.setFont(self.boldFont)
        self.labelRigModeLSB.setEnabled(False)

        self.labelRigModeUSB = QLabel('USB')
        self.labelRigModeUSB.setFont(self.boldFont)
        self.labelRigModeUSB.setEnabled(False)

        vboxMiddlePanel = QVBoxLayout()
        vboxMiddlePanel.addWidget(self.labelRigModeLSB)
        vboxMiddlePanel.addWidget(self.labelRigModeUSB)

        hboxMiddlePanel = QHBoxLayout()
        hboxMiddlePanel.addLayout(vboxMiddlePanel)
        hboxMiddlePanel.addStretch()

        self.btnBack500Hz = QPushButton("<--")
        self.btnBack500Hz.setFixedWidth(50)

        self.btnForward500Hz = QPushButton("-->")
        self.btnForward500Hz.setFixedWidth(50)
        self.btnForward500Hz.clicked.connect(self.btnOmniRigPlus500HzClick)

        self.btnOmniRigUSB = QPushButton("USB")
        self.btnOmniRigUSB.clicked.connect(self.btnOmniUSBClick)
        self.btnOmniRigUSB.setFixedWidth(50)

        self.btnOmniRigLSB = QPushButton("LSB")
        self.btnOmniRigLSB.clicked.connect(self.btnOmniLSBClick)
        self.btnOmniRigLSB.setFixedWidth(50)

        hboxRigCATControl = QHBoxLayout()
        hboxRigCATControl.addWidget(self.btnBack500Hz)
        hboxRigCATControl.addWidget(self.btnForward500Hz)
        hboxRigCATControl.addStretch()
        hboxRigCATControl.addWidget(self.btnOmniRigLSB)
        hboxRigCATControl.addWidget(self.btnOmniRigUSB)
        hboxRigCATControl.addStretch(1)

        hboxMainLayout = QHBoxLayout()
        hboxMainLayout.addWidget(self.lcdTrxFrequency)
        hboxMainLayout.addLayout(hboxMiddlePanel)

        self.vboxMainLayout = QVBoxLayout()
        self.vboxMainLayout.addWidget(self.rigSelectGroupBox)
        self.vboxMainLayout.addLayout(hboxMainLayout)
        if self.operatingAsClient is True:
            self.vboxMainLayout.addLayout(hboxRigCATControl)

    def setOmnirigObject(self, omnirigObject):
        self.omnirigObject = omnirigObject

    def btnOmniRigPlus500HzClick(self):
        try:
            self.omnirigObject = win32.Dispatch("OmniRig.OmniRigX")
        except:
            pass
        if self.omnirigObject is not None and self.operatingAsClient is False:
            if self.radioBtnTRX1.isChecked():
                self.omnirigObject.Rig1.SetSimplexMode(str(self.omnirigObject.Rig1.Freq+500))
            else:
                self.omnirigObject.Rig2.SetSimplexMode(str(self.omnirigObject.Rig1.Freq+500))
        if self.operatingAsClient is True and self.sendCommandFunction is not None:
            self.sendCommandFunction('+500=1')

    def btnOmniLSBClick(self):
        try:
            self.omnirigObject = win32.Dispatch("OmniRig.OmniRigX")
        except:
            pass
        if self.omnirigObject is not None and self.operatingAsClient is False:
            if self.radioBtnTRX1.isChecked():
                self.omnirigObject.Rig1.Mode = '67108864'
            else:
                self.omnirigObject.Rig2.Mode = '67108864'
        if self.operatingAsClient is True and self.sendCommandFunction is not None:
            self.sendCommandFunction('setLSB=1')

    def btnOmniUSBClick(self):
        try:
            self.omnirigObject = win32.Dispatch("OmniRig.OmniRigX")
        except:
            pass
        if self.omnirigObject is not None and self.operatingAsClient is False:
            if self.radioBtnTRX1.isChecked():
                self.omnirigObject.Rig1.Mode = '33554432'
            else:
                self.omnirigObject.Rig2.Mode = '33554432'

        if self.operatingAsClient is True and self.sendCommandFunction is not None:
            self.sendCommandFunction('setUSB=1')

    def setDisplayFreq(self, txtFreq):
        self.lcdTrxFrequency.display(txtFreq)

    def setOmniRigErrorText(self, msgText):
        self.labelRigName.setText(msgText)
        self.labelRigName.setPalette(self.redColorPalette)

    def setRigStatus(self, rigType):
        self.labelRigName.setText(rigType)
        self.labelRigName.setPalette(self.blackColorPalette)

    def getRigsInformation(self):
        return self.omniRigInfo

    def disableControls(self):
        self.radioBtnTRX1.setEnabled(False)
        self.radioBtnTRX2.setEnabled(False)

    def refreshRigInformation(self):
        rignum = '2'
        if self.radioBtnTRX1.isChecked():
            rignum = '1'
        if len(self.omniRigInfo) > 1:
            self.radioBtnTRX1.setText(self.omniRigInfo['1'].getRigType())
            self.radioBtnTRX2.setText(self.omniRigInfo['2'].getRigType())
            freqTxt = self.omniRigInfo[rignum].getRigFreq()
            self.setDisplayFreq(self.addDotsToFreq(freqTxt))
            self.setRigStatus(self.omniRigInfo[rignum].getRigStatus())

            if freqTxt == 0:
                self.labelRigModeUSB.setEnabled(False)
                self.labelRigModeLSB.setEnabled(False)
            else:
                if self.omniRigInfo[rignum].getRigMode() == 'LSB':
                    self.labelRigModeUSB.setEnabled(False)
                    self.labelRigModeLSB.setEnabled(True)
                else:
                    self.labelRigModeUSB.setEnabled(True)
                    self.labelRigModeLSB.setEnabled(False)

    def setRigInformation(self, omniRigInfo):
        self.omniRigInfo = omniRigInfo
        self.refreshRigInformation()

    def addDotsToFreq(self, freqvalue):
        freqTxt = str(freqvalue)
        if len(freqTxt) < 6:
            freqTxt = '00000000'

        firstPart = freqTxt[:-6]
        if len(freqTxt) == 8:
            mainPart = freqTxt[:7]
            middlePart = mainPart[2:5]
            lastPart = mainPart[5:]
        else:
            mainPart = freqTxt[:6]
            middlePart = mainPart[1:4]
            lastPart = mainPart[4:]

        return firstPart+"."+middlePart+"."+lastPart

    def getGUI(self):
        return self.vboxMainLayout
class CRUD(QWidget):
    def __init__(self):
        super().__init__()
        self.iniUI()

    def iniUI(self):

        createDBConnection()

        time = QTime.currentTime()
        text = time.toString('hh:mm:ss')
        self.lCD_time = QLCDNumber(self)
        self.lCD_time.setDigitCount(
            25)  # change the number of digits displayed from 5 to 8
        self.lCD_time.setSegmentStyle(QLCDNumber.Flat)
        self.lCD_time.setStyleSheet("QLCDNumber {color: Teal;}")
        self.lCD_time.setMinimumHeight(40)  # change the font size to bigger
        self.lCD_time.display(text)

        # refresh timer to reset time in lCD_time
        self.refreshTimer = QTimer(self)
        self.refreshTimer.start(
            1000
        )  # Starts or restarts the timer with a timeout of duration msec milliseconds.
        self.refreshTimer.timeout.connect(
            self.show_Time)  # This signal is emitted when the timer times out.

        bt_add = QPushButton("Add")
        bt_del = QPushButton("Delete")
        bt_clr = QPushButton("Clear Screen")
        bt_sho = QPushButton("Show_Current")
        bt_sho_all = QPushButton("Show_All")
        lb_ID = QLabel("Associate ID #")
        self.ln_ID = QLineEdit()
        self.ln_ID.setMaxLength(6)
        lb_Name = QLabel("Full Name")
        self.ln_Name = QLineEdit()
        self.ln_Name.setMaxLength(30)
        lb_Desig = QLabel("Designation")
        self.ln_Desig = QLineEdit()
        self.ln_Desig.setMaxLength(15)
        lb_Dob = QLabel("Date of Birth")
        self.lbl = QLineEdit(self)
        self.cal_Dob = QCalendarWidget(self)
        self.cal_Dob.setGridVisible(True)
        self.cal_Dob.clicked[QDate].connect(self.showDate)
        #         self.lb_msg = QMessageBox(self)
        #         self.lb_msg.setReadOnly(True)

        layout = QFormLayout()
        layout.addWidget(self.lCD_time)
        layout.addWidget(lb_ID)
        layout.addWidget(self.ln_ID)
        layout.addWidget(lb_Name)
        layout.addWidget(self.ln_Name)
        layout.addWidget(lb_Desig)
        layout.addWidget(self.ln_Desig)
        layout.addWidget(lb_Dob)
        layout.addWidget(self.lbl)
        layout.addWidget(self.cal_Dob)
        layout.addWidget(bt_add)
        layout.addWidget(bt_del)
        layout.addWidget(bt_clr)
        layout.addWidget(bt_sho)
        layout.addWidget(bt_sho_all)
        self.ln_ID.setFocus()
        #         layout.addWidget(self.lb_msg)

        bt_add.clicked.connect(self.add_records)
        bt_del.clicked.connect(self.del_records)
        bt_clr.clicked.connect(self.clr_records)
        bt_sho.clicked.connect(self.show_records)
        bt_sho_all.clicked.connect(self.show_all_records)

        self.tableView = QTableView(self)
        self.tableView.setObjectName("tableView")

        layout.addWidget(self.tableView)

        self.setLayout(layout)
        self.setWindowTitle("Employee Details form")
        self.setGeometry(100, 300, 250, 450)  # x,y, width, height
        self.show()

    def showDate(self, date):
        self.lbl.setText(date.toString("dd-MMM-yyyy"))

    def add_records(self):

        emp_id = self.ln_ID.text()
        name = self.ln_Name.text()
        designation = self.ln_Desig.text()
        dob = self.lbl.text()

        #             createDBConnection()
        query = QSqlQuery()
        query.prepare("INSERT INTO employee1 (emp_id, name, designation, dob) "
                      "VALUES (:emp_id, :name, :designation, :dob)")

        query.bindValue(":emp_id", emp_id)
        query.bindValue(":name", name)
        query.bindValue(":designation", designation)
        query.bindValue(":dob", dob)

        try:
            if query.exec_():
                #                 add_msg = "Row Added"
                #                 self.lb_msg.setText(add_msg)
                print("add_records Successful")
                QMessageBox.information(self, 'Info', 'Row Added',
                                        QMessageBox.Ok)
                #                 self.show_records()
                self.clr_records()

            else:
                err_text = query.lastError().text()
                print("add_records Error: ", err_text)
                QMessageBox.critical(self, 'Error', err_text,
                                     QMessageBox.Retry)
#                 fail_msg = "Insert Failed !! "
#                 self.lb_msg.SetText(fail_msg)
        except:
            pass

    def show_records(self):
        #         createDBConnection()
        query = QSqlQuery()
        try:
            emp_id_txt = self.ln_ID.text()
        except:
            pass

        if emp_id_txt:
            emp_id = int(emp_id_txt)
            query.prepare(
                "SELECT emp_id, name, Designation, dob from employee1 where emp_id = (:emp_id) "
            )
            query.bindValue(":emp_id", emp_id)

            if query.exec_():
                print("show_records Successful")

    #             self.lb_msg.SetText("showing current record !! ")
            else:
                print("show_records Error: ", query.lastError().text())
                model = QSqlTableModel()
                self.show_records_View("Title", model)
            while query.next():
                print("query show_records ", query.value(0), query.value(1),
                      query.value(2), query.value(3))
        else:
            QMessageBox.critical(self, 'Error', 'Please Enter Associate ID',
                                 QMessageBox.Retry)
            self.ln_ID.setFocus()

    def show_all_records(self):
        #         createDBConnection()
        query = QSqlQuery()
        query.exec_("SELECT emp_id, name, Designation, dob from employee1")

        if query.exec_():
            print("show_records Successful")
#             all_msg = "Showing ALL records !!"
#             self.lb_msg.SetText(all_msg)
        else:
            print("show_records Error: ", query.lastError().text())

        while query.next():
            print("query show_records ", query.value(0), query.value(1),
                  query.value(2), query.value(3))
        model = QSqlTableModel()
        self.show_records_View("Title", model)

    def clr_records(self):
        #         createDBConnection()

        print("inside Clear records")
        self.ln_ID.setText("")
        self.ln_Name.setText("")
        self.ln_Desig.setText("")
        print(toString(QDate.currentDate(), "dd-MMM-yyyy"))


#         self.cal_Dob.setText(QDate.currentDate())
#         self.lbl.setText(toString(QDate.currentDate(),"dd-MMM-yyyy")

    def del_records(self):
        #         createDBConnection()

        query = QSqlQuery()
        emp_id_txt = self.ln_ID.text()
        emp_id = int(emp_id_txt)
        query.prepare("DELETE from employee1 where emp_id = (:emp_id)  ")
        query.bindValue(":emp_id", emp_id)

        if query.exec_():
            print("del_records Successful")
            QMessageBox.information(self, 'Info', 'Row Deleted',
                                    QMessageBox.Ok)
            self.show_records()
        else:
            print("del_records Error: ", query.lastError().text())

    def del_records1(self):
        #         createDBConnection()
        query = QSqlQuery()
        query.exec_("DELETE from employee1")
        if query.exec_():
            print("del_records Successful")
            self.show_records()
        else:
            print("del_records Error: ", query.lastError().text())

    def show_records_View(self, title, model):

        model.setTable('employee1')
        model.setEditStrategy(QSqlTableModel.OnFieldChange)
        model.select()
        model.setHeaderData(0, Qt.Horizontal, "emp_id")
        model.setHeaderData(1, Qt.Horizontal, "name")
        model.setHeaderData(2, Qt.Horizontal, "designation")
        model.setHeaderData(3, Qt.Horizontal, "dob")

        self.tableView.setModel(model)
        self.tableView.setWindowTitle(title)
        return self.tableView

    def show_Time(self):
        time = QTime.currentTime()
        #         print(time)
        text = time.toString('hh:mm:ss')
        self.lCD_time.display(text)
Exemple #8
0
class RecordUI(QWidget):
    def __init__(self):
        super().__init__()
        self._running = False
        self.drivers = get_drivers()
        # ui
        self.input_lb = QLabel("Input", self)
        self.output_lb = QLabel("Output", self)
        self.input_driver_lb = QLabel('Driver', self)
        self.output_driver_lb = QLabel('Driver', self)
        self.input_device_lb = QLabel('Device', self)
        self.output_device_lb = QLabel('Device', self)
        self.signal_lb = QLabel('Signal', self)

        self.customized_signal_file = MyLineEdit(self)

        self.save_dir = MyLineEdit(self)
        self.dir1 = QLineEdit(self)
        self.dir2 = QLineEdit(self)
        self.filename = QLineEdit(self)

        self.input_driver = QComboBox()
        self.output_driver = QComboBox()
        self.input_device = QComboBox()
        self.output_device = QComboBox()
        self.signal = QComboBox()

        self.start = QPushButton('Start', self)
        self.stop = QPushButton('Stop', self)

        self.time = QLCDNumber()
        self.time.setMinimumHeight(100)
        self.time.setDigitCount(5)
        self.time.setMode(QLCDNumber.Dec)
        self.time.setSegmentStyle(QLCDNumber.Flat)
        self.time.display("00.00")

        self.record_thread = recordtool.Record(self.time)

        self.initUI()

    def initUI(self):
        # 全局vbox
        vbox = QVBoxLayout()
        # 输入输出设备选择初始化
        input_box, output_box = self.init_audio_io()
        vbox.addWidget(self.input_lb)
        vbox.addLayout(input_box)
        vbox.addWidget(self.output_lb)
        vbox.addLayout(output_box)
        # 信号选择初始化
        singal_box = self.init_signal()
        vbox.addLayout(singal_box)
        # 存储路径初始化
        sf_box = self.init_save_file()
        vbox.addLayout(sf_box)
        # 开始结束按键初始化
        ss_box = self.init_button()
        vbox.addLayout(ss_box)

        vbox.addWidget(self.time)

        self.setLayout(vbox)
        self.resize(800, 320)
        self.center()
        self.setWindowTitle('Gesture Recorder')
        self.show()

    def center(self):
        # 获得窗口
        qr = self.frameGeometry()
        # 获得屏幕中心点
        cp = QDesktopWidget().availableGeometry().center()
        # 显示到屏幕中心
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def init_audio_io(self):
        input_box = QHBoxLayout()
        input_box.addWidget(self.input_driver_lb)
        input_box.addWidget(self.input_driver)
        input_box.addWidget(self.input_device_lb)
        input_box.addWidget(self.input_device)
        input_box.setStretch(0, 1)
        input_box.setStretch(1, 1)
        input_box.setStretch(2, 1)
        input_box.setStretch(3, 6)
        self.input_driver.addItems([driver['name'] for driver in self.drivers])
        self.input_driver.activated[str].connect(self.on_input_drive_selected)

        output_box = QHBoxLayout()
        output_box.addWidget(self.output_driver_lb)
        output_box.addWidget(self.output_driver)
        output_box.addWidget(self.output_device_lb)
        output_box.addWidget(self.output_device)
        output_box.setStretch(0, 1)
        output_box.setStretch(1, 1)
        output_box.setStretch(2, 1)
        output_box.setStretch(3, 6)
        self.output_driver.addItems(
            [driver['name'] for driver in self.drivers])
        self.output_driver.activated[str].connect(
            self.on_output_drive_selected)
        return input_box, output_box

    def on_input_drive_selected(self, driver):
        input_devices = get_devices(self.drivers, kind='Input', driver=driver)
        self.input_device.clear()
        self.input_device.addItems(
            [f"{device['id']}:{device['name']}" for device in input_devices])

    def on_output_drive_selected(self, driver):
        output_devices = get_devices(self.drivers,
                                     kind='Output',
                                     driver=driver)
        self.output_device.clear()
        self.output_device.addItems(
            [f"{device['id']}:{device['name']}" for device in output_devices])

    def init_signal(self):
        signal_box = QHBoxLayout()
        signal_box.addWidget(self.signal_lb)
        signal_box.setStretchFactor(self.signal_lb, 1)

        signal_box.addWidget(self.signal)
        self.signal.activated[str].connect(self.on_customized_selected)
        signal_box.setStretchFactor(self.signal, 1)

        signal_box.addWidget(self.customized_signal_file)
        self.customized_signal_file.setPlaceholderText("选择wav音频文件...")
        self.customized_signal_file.setFocusPolicy(Qt.NoFocus)
        self.customized_signal_file.setDisabled(True)
        self.customized_signal_file.clicked.connect(
            self.show_wav_file_dialogue)
        signal_box.setStretchFactor(self.customized_signal_file, 4)

        self.signal.addItems(get_all_types())
        return signal_box

    def on_customized_selected(self, text):
        if text == 'customized':
            self.customized_signal_file.setDisabled(False)
        else:
            self.customized_signal_file.setDisabled(True)

    def show_wav_file_dialogue(self):
        file_name, file_type = QFileDialog.getOpenFileName(
            self, directory=os.getcwd(), filter='WAV Files (*.wav)')
        self.customized_signal_file.setText(file_name)

    def init_save_file(self):
        file_box = QHBoxLayout()
        file_box.addWidget(self.save_dir)
        self.save_dir.setFocusPolicy(Qt.NoFocus)
        self.save_dir.setText(os.getcwd())
        self.save_dir.clicked.connect(self.show_dir_dialogue)
        file_box.setStretchFactor(self.save_dir, 4)

        file_box.addWidget(QLabel('/'))
        file_box.addWidget(self.dir1)
        self.dir1.setText('0')
        file_box.setStretchFactor(self.dir1, 1)

        file_box.addWidget(QLabel('/'))
        file_box.addWidget(self.dir2)
        self.dir2.setText('0')
        file_box.setStretchFactor(self.dir2, 1)

        file_box.addWidget(QLabel('/'))
        file_box.addWidget(self.filename)
        self.filename.setText('0')
        file_box.setStretchFactor(self.filename, 1)
        file_box.addWidget(QLabel('.wav'))

        return file_box

    def show_dir_dialogue(self):
        dir_name = QFileDialog.getExistingDirectory(self,
                                                    directory=os.getcwd())
        self.save_dir.setText(dir_name)

    def init_button(self):
        ss_box = QHBoxLayout()
        self.start.setStyleSheet("background-color:lightgreen")
        self.start.clicked.connect(self.start_playrec)
        ss_box.addWidget(self.start)
        self.stop.setStyleSheet("background-color:#CD2626")
        self.stop.clicked.connect(self.stop_playrec)
        ss_box.addWidget(self.stop)
        return ss_box

    def start_playrec(self):
        if not self._running:
            input_id = get_device_id(self.input_device.currentText())
            output_id = get_device_id(self.output_device.currentText())
            if input_id == -1 or output_id == -1:
                self.setWindowTitle("请选择输入/输出设备")
                return
            # signal_pattern可能是一个wav文件名称或者是一串信号
            signal_pattern = get_signal_by_type(
                self.signal.currentText(),
                customized_signal_file=self.customized_signal_file.text())
            if type(signal_pattern) == str and signal_pattern == '':
                self.setWindowTitle("请选择wav音频文件")
                return
            rec_path = self.create_save_path()

            in_d = p.get_device_info_by_index(input_id)
            self.record_thread.set_param(input_id, output_id,
                                         in_d['maxInputChannels'], rec_path)
            try:
                self.record_thread.play_and_record(signal_pattern)
            except:
                self.setWindowTitle("Unexpected error:" + sys.exc_info()[0])
            self._running = True
            self.setWindowTitle("正在录制中...")
        else:
            self.setWindowTitle("已经开始录制")

    def stop_playrec(self):
        if self._running:
            try:
                self.record_thread.stop()
                self.setWindowTitle("停止录制")
            except:
                self.setWindowTitle("Unexpected error:" + sys.exc_info()[0])
            finally:
                self._running = False
            try:
                num = int(self.filename.text())
                num = num + 1
                self.filename.setText(str(num))
            except:
                pass
        else:
            self.setWindowTitle("还没开始录制")

    def create_save_path(self):
        path1 = os.path.join(self.save_dir.text(), self.dir1.text())
        if not os.path.exists(path1):
            os.mkdir(path1)
        path2 = os.path.join(path1, self.dir2.text())
        if not os.path.exists(path2):
            os.mkdir(path2)

        return os.path.join(path2, f'{self.filename.text()}.wav')

    # 按键录制 esc
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            if self._running:
                self.stop_playrec()
            else:
                self.start_playrec()
Exemple #9
0
class DigitalClock(QMainWindow):

    # duration time in mins
    targetTime = 10
    answerTime = 5
    counter = 0
    willblack = True
    p = 'report'

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent, Qt.WindowStaysOnTopHint)
        self.central = QWidget(self)
        # self.setWindowTitle("SHAO PPT记时")

        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint
                            | Qt.WindowStaysOnTopHint)
        # initial timer
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showTime)
        self.inicio = self.targetTime * 60

        # LCDwidget
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(QLCDNumber.Filled)
        self.lcd.setMinimumHeight(40)

        # Black screen checkbox
        # self.cb = QCheckBox('Black Screen')
        # self.cb.toggle()
        # self.cb.stateChanged.connect(self.blackornot)

        # Duration setup
        self.line = QLineEdit()
        self.line.setMaximumWidth(30)
        self.line.setContentsMargins(0, 0, 0, 0)
        self.setbutton = QPushButton('K', self)
        self.setbutton.setMaximumWidth(20)
        self.setbutton.clicked.connect(self.setTimer)

        # Label widget
        # self.nameLabel = QLabel()
        # self.nameLabel.setText('Duration: ' + str(self.targetTime) + ' mins')
        # self.nameLabel.resize(60, 20)

        # start and reset button
        self.start_button = QPushButton("S")
        self.start_button.resize(30, 20)
        self.start_button.setMaximumWidth(20)
        self.stop_button = QPushButton("R")
        self.stop_button.setMaximumWidth(20)
        self.start_button.clicked.connect(self.restartTimer)
        self.stop_button.clicked.connect(self.stopTimer)

        # layout setup
        self.vbox = QVBoxLayout(self.central)
        # self.vbox = QVBoxLayout(self.center)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        self.vbox.addStretch(0)
        self.hbox1 = QGridLayout()
        self.hbox1.setContentsMargins(0, 0, 0, 0)
        self.vbox.addWidget(self.lcd)
        self.vbox.addLayout(self.hbox1)
        self.hbox1.addWidget(self.start_button, 0, 0)
        self.hbox1.addWidget(self.stop_button, 0, 1)
        self.hbox1.addWidget(self.line, 0, 2)
        self.hbox1.addWidget(self.setbutton, 0, 3)
        # self.vbox.addWidget(self.nameLabel)
        self.setCentralWidget(self.central)

        self.setMaximumWidth(120)
        self.setContentsMargins(0, 0, 0, 0)
        # self.setGeometry(0,0,100,80)
        self.setMinimumWidth(120)
        # initial clock display
        self.updateLCD()

    def updateLCD(self):
        diffStr = "%d:%02d" % (self.inicio // 60, self.inicio % 60)
        self.lcd.setDigitCount(len(diffStr))
        self.lcd.display(diffStr)

    def setTimer(self):
        if self.line.text():
            try:
                self.targetTime = float(self.line.text().split(",")[0])
                self.answerTime = float(self.line.text().split(",")[1])
                # self.nameLabel.setText('Duration: ' + str(self.targetTime) + ' mins')
            except ValueError:
                self.line.clear()
                # self.nameLabel.setText('Duration: (mins)  1 ~ 100 mins!')
        else:
            self.targetTime = 10.0

        self.inicio = self.targetTime * 60
        self.p = 'report'
        self.updateLCD()
        self.start_button.setText('S')
        self.counter = 0
        self.timer.stop()

    def blackornot(self, state):
        if state == Qt.Checked:
            self.willblack = True
        else:
            self.willblack = False

    def restartTimer(self):
        # Reset the timer and the lcd
        self.p = 'report'
        if self.counter == 0:
            self.timer.start(1000)
            self.start_button.setText('P')
            self.counter += 1
        else:
            self.timer.stop()
            self.start_button.setText('C')
            self.counter -= 1

    def stopTimer(self):
        self.timer.stop()
        self.inicio = self.targetTime * 60
        self.updateLCD()
        self.start_button.setText('S')
        self.counter = 0

    def showTime(self):
        self.inicio -= 1
        self.updateLCD()

        if self.inicio == 0:
            self.stopTimer()
            self.timer.stop()
            self.start_button.setText('S')
            self.counter = 0
            if self.willblack:
                self.blackscreen()

    def blackscreen(self):

        self.dialog = QDialog()
        self.dialog.resize(1024, 768)

        self.dcentral = QWidget(self)
        self.dlayout = QVBoxLayout()
        self.dlabel = QLabel()
        self.dlabel.setAlignment(Qt.AlignCenter)
        if self.p == 'report':
            self.db = QPushButton("按此进入答辩环节 (5秒后自动进入)", self.dialog)
            self.db.setStyleSheet('QPushButton {color: black;}')
            self.dlabel.setText("汇报时间到")
            self.puttontime = 5
            self.btimer = QTimer(self)
            self.btimer.timeout.connect(self.countdown)
            self.btimer.start(1000)
        else:
            self.dlabel.setText("答辩时间到")
            self.db = QPushButton("5秒后自动结束", self.dialog)
            self.db.setStyleSheet('QPushButton {color: black;}')
            self.puttontime = 5
            self.btimer = QTimer(self)
            self.btimer.timeout.connect(self.countdown)
            self.btimer.start(1000)
        newfont = QtGui.QFont("SimSun", 120)
        bfont = QtGui.QFont("Hei", 45)
        self.db.setFont(bfont)
        self.dlabel.setFont(newfont)
        self.dlayout.addWidget(self.dlabel)
        self.dlayout.addWidget(self.db)
        self.dialog.setLayout(self.dlayout)
        self.db.setMaximumHeight(120)
        # self.setCentralWidget(self.dcentral)
        self.dlabel.resize(400, 300)

        self.db.clicked.connect(self.closeit)
        self.dialog.setWindowFlags(Qt.WindowStaysOnTopHint)

        self.dialog.exec_()

    def countdown(self):
        self.puttontime -= 1
        if self.p == 'report':
            self.db.setText("按此确认进入答辩环节 (" + str(self.puttontime) + "秒后自动进入)")
        else:
            self.db.setText(str(self.puttontime) + "秒后自动结束")

        self.updateLCD()

        if self.puttontime == 0:
            self.btimer.stop()
            self.closeit()

    def closeit(self):
        self.dialog.close()
        if self.p == 'report':
            self.inicio = self.answerTime * 60
            self.timer.start(1000)
            self.p = 'answer'
        else:
            self.inicio = self.targetTime * 60
            self.timer.stop()
            self.p = 'report'
        self.updateLCD()
        self.start_button.setText('S')
        self.counter = 0