Пример #1
0
class MyForm(QtGui.QMainWindow):
    def showMessage(self,string):
        self.ui.messageTextbox.setText(string)
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)     
        #here start
        downloader.fileLabel = self.ui.fileLabel
        downloader.nowSizeLabel = self.ui.nowSizeLabel
        downloader.totalSizeLabel = self.ui.totalSizeLabel
        downloader.messageTextbox = self.ui.messageTextbox
        #pass para
        self.connect(self.ui.aButton,QtCore.SIGNAL('clicked()'),self.aButton_clicked)
        self.connect(self.ui.bButton,QtCore.SIGNAL('clicked()'),self.bButton_clicked)
        self.connect(self.ui.aAfternoonButton,QtCore.SIGNAL('clicked()'),self.aAfternoonButton_clicked)
        self.connect(self.ui.bAfternoonButton,QtCore.SIGNAL('clicked()'),self.bAfternoonButton_clicked)
        self.connect(self.ui.downloadPercentButton,QtCore.SIGNAL('clicked()'),self.downloadPercentButton_clicked)
        self.connect(self.ui.nextButton,QtCore.SIGNAL('clicked()'),self.nextButton_clicked)
        #event
    def aButton_clicked(self):
        thread.start_new_thread(downloader.main,(1,True))
    def bButton_clicked(self):
        thread.start_new_thread(downloader.main,(0,True))
    def aAfternoonButton_clicked(self):
        thread.start_new_thread(downloader.main,(1,False))
    def bAfternoonButton_clicked(self):
        thread.start_new_thread(downloader.main,(0,False))
    def nextButton_clicked(self):
        downloader.goNext = True
    def downloadPercentButton_clicked(self):
        downloader.refreshPercent()
Пример #2
0
class Test(QMainWindow):
    def __init__(self, parent=None):
        super(Test, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.btn1 = self.ui.pushButton
        self.btn1.clicked.connect(self.make_clientid)
        self.btn3 = self.ui.pushButton_3
        self.btn3.clicked.connect(self.make_token)
        self.btn2 = self.ui.pushButton_2
        self.btn2.clicked.connect(self.tootstatus)

    def make_clientid(self):
        appname = self.ui.lineEdit.text()
        url = self.ui.lineEdit_2.text()
        cid_file = 'client_id.txt'
        Mastodon.create_app(appname, api_base_url=url, to_file=cid_file)
        with open(cid_file) as ci:
            self.ui.lineEdit_3.setText(ci.read())

    def make_token(self):
        clientid = "client_id.txt"
        url = self.ui.lineEdit_4.text()
        email = self.ui.lineEdit_5.text()
        password = self.ui.lineEdit_6.text()
        token = "access_token.txt"
        mastodon = Mastodon(
            client_id=clientid,
            api_base_url=url,
        )
        mastodon.log_in(username=email, password=password, to_file=token)
        with open(token) as at:
            self.ui.lineEdit_7.setText(at.read())

    def tootstatus(self):
        url = self.ui.lineEdit_4.text()
        cid_file = 'client_id.txt'
        token_file = 'access_token.txt'

        mastodon = Mastodon(client_id=cid_file,
                            access_token=token_file,
                            api_base_url=url)
        status = self.ui.textEdit.toPlainText()
        count = self.ui.spinBox.value()
        cw = self.ui.radioButton.isChecked()
        cwstatus = self.ui.lineEdit_8.text()
        visibility = self.ui.comboBox.currentText()
        print(status)
        print(count)
        print(cw)
        print(cwstatus)
        print(visibility)
        for i in range(count):
            if cw == True:
                mastodon.status_post(status=status,
                                     spoiler_text=cwstatus,
                                     visibility=visibility)
            else:
                mastodon.status_post(status=status, visibility=visibility)
Пример #3
0
class Gui(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.video = Video(cv2.VideoCapture(0))
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()
 
    def play(self):
        '''
        capture frame and display
        '''
        try:
            self.video.capture_next_frame()
            self.ui.videoFrame.setPixmap(
                self.video.convert_frame())
            self.ui.videoFrame.setScaledContents(True)
        except TypeError:
            print "No frame"


    def mousePressEvent(self, event):
        '''
        click mouse and put point on opencv window
        '''
        self.video.add_point(QtCore.QPoint(event.pos()), 
                            self.ui.videoFrame.geometry())
Пример #4
0
class CurrencyConv(QtWidgets.QMainWindow):
    def __init__(self):
        super(CurrencyConv, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_UI()

    def init_UI(self):
        self.setWindowTitle('Конвертер валют')
        self.setWindowIcon(QIcon('photo.png'))

        self.ui.input_currency.setPlaceholderText('Из валюты:')
        self.ui.input_amount.setPlaceholderText('У меня есть:')
        self.ui.output_currency.setPlaceholderText('В валюту:')
        self.ui.output_amount.setPlaceholderText('Я получу:')
        self.ui.pushButton.clicked.connect(self.converter)

    def converter(self):
        c = CurrencyConverter()
        input_currency = self.ui.input_currency.text()
        output_currency = self.ui.output_currency.text()
        input_amount = int(self.ui.input_amount.text())
        output_amount = round(
            c.convert(input_amount, '%s' % input_currency,
                      '%s' % output_currency), 2)
        self.ui.output_amount.setText(str(output_amount))
Пример #5
0
class CurrencyConv(QtWidgets.QMainWindow):
    def __init__(self):
        super(CurrencyConv, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_UI()

    def init_UI(self):
        self.setWindowTitle('Currency Converter')
        self.setWindowIcon(QIcon('exchange.png'))

        self.ui.input_currency.setPlaceholderText('from currency:')
        self.ui.input_amount.setPlaceholderText('i have:')
        self.ui.output_currency.setPlaceholderText('to currency')
        self.ui.output_amount.setPlaceholderText('i will get:')
        self.ui.pushButton.clicked.connect(self.converter)

    def converter(self):
        c = CurrencyConverter()
        input_currency = self.ui.input_currency.text()
        output_currency = self.ui.output_currency.text()
        input_amount = int(self.ui.input_amount.text())

        output_amount = round(
            c.convert(input_amount, '%s' % (input_currency),
                      '%s' % (output_currency)), 2)

        self.ui.output_amount.setText(str(output_amount))
Пример #6
0
class TranslateText(QtWidgets.QMainWindow):
    def __init__(self):
        super(TranslateText, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_UI()

    def init_UI(self):
        self.setWindowTitle('Google Translate')
        self.ui.btn_translate.clicked.connect(self.translate)
        self.ui.btn_check_lang.setDown(True)

        self.ui.btn_eng_lang.clicked.connect(self.translate_into_en)
        self.ui.btn_ru_lang.clicked.connect(self.translate_into_ru)
        self.ui.btn_ge_lang.clicked.connect(self.translate_into_de)

    def translate_into_en(self):
        global selected_language
        selected_language = 'en'

    def translate_into_ru(self):
        global selected_language
        selected_language = 'ru'

    def translate_into_de(self):
        global selected_language
        selected_language = 'de'

    def translate(self):
        global selected_language
        input_text = self.ui.input_text.toPlainText()
        translated_text = translator.translate(input_text,
                                               dest=f'{selected_language}')
        self.ui.output_text.setPlainText(translated_text.text)
Пример #7
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle("SyphmoTracker")
Пример #8
0
class StartQT4(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.clidict = Param_To_Cli()
        self.ui.interface_choice.addItems(netifaces.interfaces())
        QtCore.QObject.connect(
            self.ui.start, QtCore.SIGNAL("clicked()"), self.start_sniffer)
#        QtCore.QObject.connect(
#            self.ui.interface_choice, QtCore.SIGNAL("activated(const QString&)"), self.get_interface)
#
#        QtCore.QObject.connect(
#            self.ui.mode_choice, QtCore.SIGNAL("activated(const QString&)"), self.get_mode)
#        QtCore.QObject.connect(
# self.ui.lineEdit, QtCore.SIGNAL("editingFinished()"), self.get_filter)

    def start_sniffer(self):
        self.clidict.interface = str(self.ui.interface_choice.currentText())
        self.clidict.mode = str(self.ui.mode_choice.currentText())
        self.clidict.filter = str(self.ui.lineEdit.text())
        log.debug(self.clidict.interface + '' +
                  self.clidict.mode + '' + self.clidict.filter)
        sniffer_prepare(self.clidict)
        self.sniff_queue = Queue()
        sniffer = SnifferProcess(
            self.sniff_queue, iface=self.clidict.interface)
        sniffer.start()
        while True:
            item = self.sniff_queue.get()

            self.ui.packet_list.addItem(item.summary())
            QtGui.QApplication.processEvents()
Пример #9
0
class Gui(QtGui.QMainWindow):
    def __init__(self,capture, getFrame, parent = None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.video = Video(capture, getFrame)
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()

    def play(self):
        try:
            self.video.captureNextFrame()
            self.ui.videoFrame.setPixmap(self.video.convertFrame())
            self.ui.videoFrame.setScaledContents(True)
            gethistogram(self.ui.axes,tuple(self.video.histogram.values()),tuple(self.video.histogram.keys()))
            # l = [random.randint(0, 10) for i in range(4)]
            # self.ui.axes.plot(self.video.histogram.values(), 'r')
            self.ui.canvas.draw()

            if(len(self.video.labels)!=0):
                self.ui.label1.setText(self.video.name)
                # self.ui.label2.setText(self.video.labels[1])
                # self.ui.label3.setText(self.video.labels[2])
                # self.ui.label4.setText(self.video.labels[3])
                # self.ui.label5.setText(self.video.labels[4])
        except TypeError as e:
            print("No Frame", e)
Пример #10
0
class main(QtGui.QMainWindow):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.file_dialog=QtGui.QFileDialog()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.fn=None
        QtCore.QObject.connect(self.ui.action_Save,QtCore.SIGNAL("triggered()"),self.save_file)
        QtCore.QObject.connect(self.ui.actionNew,QtCore.SIGNAL("triggered()"),self.new_file)
        QtCore.QObject.connect(self.ui.actionOpen,QtCore.SIGNAL("triggered()"),self.open_file)
        QtCore.QObject.connect(self.ui.action_Saveas,QtCore.SIGNAL("triggered()"),self.saveas_file)
        QtCore.QObject.connect(self.ui.actionPrint,QtCore.SIGNAL("triggered()"),self.save_file)
        QtCore.QObject.connect(self.ui.actionPrint_Preview,QtCore.SIGNAL("triggered()"),self.save_file)
        QtCore.QObject.connect(self.ui.action_quit,QtCore.SIGNAL("triggered()"),self.quit)
    def save_file(self):
        if self.fn!=None:
            fileobj=open(self.fn,'w')
            fileobj.write(self.ui.textEdit.toPlainText())
            fileobj.close()
        else:
            filename=self.file_dialog.getSaveFileName(self,u"保存文件")
            try:
                fileobj=open(filename,'w')
                fileobj.write(self.ui.textEdit.toPlainText())
                self.fn=filename
                fileobj.close()
            except Exception ,e:
                pass
Пример #11
0
class Gui(QtGui.QMainWindow):
    def __init__(self, capture, getFrame, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.video = Video(capture, getFrame)
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()

    def play(self):
        try:
            self.video.captureNextFrame()
            self.ui.videoFrame.setPixmap(self.video.convertFrame())
            self.ui.videoFrame.setScaledContents(True)
            gethistogram(self.ui.axes, tuple(self.video.histogram.values()),
                         tuple(self.video.histogram.keys()))
            # l = [random.randint(0, 10) for i in range(4)]
            # self.ui.axes.plot(self.video.histogram.values(), 'r')
            self.ui.canvas.draw()

            if (len(self.video.labels) != 0):
                self.ui.label1.setText(self.video.name)
                # self.ui.label2.setText(self.video.labels[1])
                # self.ui.label3.setText(self.video.labels[2])
                # self.ui.label4.setText(self.video.labels[3])
                # self.ui.label5.setText(self.video.labels[4])
        except TypeError as e:
            print("No Frame", e)
Пример #12
0
class mainForm(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.pannel = []

        # 기본 패널

        self.pannel.append(tab_widget(addTab, self))
        self.func_insert_tab(u'새로운 탭')
        self.pannel.append(tab_widget(communicationPannel, self))
        self.func_insert_tab(u'DataPort')

        QtCore.QObject.connect(self.pannel[0].pannel.ui.clb, QtCore.SIGNAL("clicked()"), self.AddTab)

    def AddTab(self):
        current_index = len(self.ui.tabWidget)

        self.pannel.append(tab_widget(communicationPannel, self))
        self.func_insert_tab(u'DataPort')

  # 프로그램을 닫으려 할때
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.warning(self,
            u'프로그램 종료', u"진행중인 모든 데이터 송·수신을 중지합니다.\n프로그램을 종료하시겠습니까?",
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
            QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        elif reply == QtGui.QMessageBox.No:
            event.ignore()

    def func_insert_tab(self, tab_name):
        """
        * 탭이 추가되면 항상 '새탭추가탭' 앞 쪽에 위치
        * 추가된 탭이 활성화
        """
        current_index = len(self.ui.tabWidget)
        self.ui.tabWidget.insertTab(current_index - 1, self.pannel[current_index], unicode(tab_name))
        self.ui.tabWidget.setCurrentIndex(current_index - 1)



    def slot_close_tab(self, tab_index):
        print tab_index

        if 1 == self.ui.tabWidget.count():
            # '새탭 추가탭'을 닫으려 할 경우
            return
        reply = QtGui.QMessageBox.warning(
            self,u'탭 닫기', u"저장하지 않은 작업 내용은 잃게됩니다.\n탭을 닫으시겠습니까?",
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
            QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            self.pannel.pop(tab_index + 1)
            self.ui.tabWidget.removeTab(tab_index)
        elif reply == QtGui.QMessageBox.No: pass
Пример #13
0
class CMonoployApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initUi()

    def initUi(self):
        pass
Пример #14
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.setText('Hello World!')


    def update(self, subject):
        self.ui.label.setText(str(subject.num))
Пример #15
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.img = ''
        self.mask = ''
        self.model = ''

        self.ui = Ui_MainWindow()   
        self.ui.setupUi(self)
        self.ui.s_image_label.clicked.connect(self.select_image)
        self.ui.s_model.clicked.connect(self.select_model)
        self.ui.run.clicked.connect(self.execute)

    def select_image(self):
        image_path, filetype = QFileDialog.getOpenFileName(self,"選取原始圖片","./","All Files (*);;Text Files (*.txt)")
        label_path, filetype = QFileDialog.getOpenFileName(self,"原始圖片對應的mask","./","All Files (*);;Text Files (*.txt)")
        self.ui.image_path.setText(image_path)
        self.ui.label_path.setText(label_path)
        self.img = image_reader(image_path)
        self.mask = image_reader(label_path)

        #return image_path,label_path
    def select_model(self):
        model_path, filetype = QFileDialog.getOpenFileName(self,"選取模型","./","All Files (*);;Text Files (*.txt)")
        #print(model_path)
        self.ui.model_name.setText(model_path)
        self.model = model_loader(model_path)
        #return model_path

    def execute(self):
        dc_list = image_predict_v2(self.img,self.mask,self.model)
        self.ui.picture.setPixmap(QtGui.QPixmap("final_result.png"))

        self.ui.label.setText('DC 1: '+ str(dc_list[0]))
        self.ui.label_2.setText('DC 2: '+str(dc_list[1]))
        self.ui.label_3.setText('DC 3: '+str(dc_list[2]))
        self.ui.label_4.setText('DC 4: '+str(dc_list[3]))
        self.ui.label_5.setText('DC 5: '+str(dc_list[4]))
        self.ui.label_6.setText('DC 6: '+str(dc_list[5]))
        self.ui.label_7.setText('DC 7: '+str(dc_list[6]))
        self.ui.label_8.setText('DC 8: '+str(dc_list[7]))
        self.ui.label_9.setText('DC 9: '+str(dc_list[8]))
        self.ui.label_10.setText('DC 10: '+str(dc_list[9]))
        self.ui.label_11.setText('DC 11: '+str(dc_list[10]))
        self.ui.label_12.setText('DC 12: '+str(dc_list[11]))
        self.ui.label_13.setText('DC 13: '+str(dc_list[12]))
        self.ui.label_14.setText('DC 14: '+str(dc_list[13]))
        self.ui.label_15.setText('DC 15: '+str(dc_list[14]))
        self.ui.label_16.setText('DC 16: '+str(dc_list[15]))

        self.ui.label_17.setText('DC 17: '+str(dc_list[16]))
        self.ui.label_18.setText('DC 18: '+str(dc_list[17]))
        self.ui.label_19.setText('DC 19: '+str(dc_list[18]))
        self.ui.label_20.setText('DC AVG: '+ str(dc_list[19]))
Пример #16
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, logAnalyser, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self, len(logAnalyser.files))
        self.logAnalyser = logAnalyser
        self.threadLogAnalyser = ThreadedLogAnalyser(self, self.logAnalyser)
        self.connect(self.threadLogAnalyser, QtCore.SIGNAL("appendLogs"),
                     self.ui.appendLogs)

    def main(self):
        self.threadLogAnalyser.start()
Пример #17
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.setText('Hello World!')

        self.ui.pushButton.clicked.connect(self.buttonClicked)

    def buttonClicked(self):
        now = datetime.now()
        self.ui.label.setText(str(now))
Пример #18
0
class Gui(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.video = Video(cv2.VideoCapture(0))
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()
        self.ui.btnCapture.clicked.connect(self.cb)
        self.ui.btnAddText.clicked.connect(self.addText)
        self.ui.picComboBox.currentIndexChanged.connect(self.picResolution)

        self.ret, self.capturedFrame = self.video.capture.read()

    def picResolution(self):
        pass

    def cb(self):
        reso = self.ui.picComboBox.currentText().split('x')
        self.video.captureNextFrame()

        frame = self.video.convertFrame()

        self.ui.videoFrame_2.setPixmap(frame)
        self.ui.videoFrame_2.setScaledContents(True)

        self.capturedFrame = self.video.captureFrame()
        img = cv2.resize(self.capturedFrame, int(reso[0]), int(reso[1]))
        cv2.imwrite("test.jpg", img)

        print("captured")

    def addText(self):
        imText = self.video.getImage()
        imOrg = self.video.getImage()
        text = "%s" % self.ui.TextFieldAddText.text()
        cv2.putText(imText, text, (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 1,
                    (255, 255, 255), 2)
        cv2.imwrite("testText.jpg", imText)
        pixmap = QtGui.QPixmap('testText.jpg')
        self.ui.videoFrame_2.setPixmap(pixmap)
        print('Text added' + text)

    def play(self):
        try:
            self.video.captureNextFrame()
            self.ui.videoFrame.setPixmap(self.video.convertFrame())
            self.ui.videoFrame.setScaledContents(True)
        except TypeError:
            print("No frame")
Пример #19
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, logAnalyser, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self, len(logAnalyser.files))
        self.logAnalyser = logAnalyser
        self.threadLogAnalyser =  ThreadedLogAnalyser(self, self.logAnalyser)
        self.connect(self.threadLogAnalyser, QtCore.SIGNAL("appendLogs"), self.ui.appendLogs)

    
        
    def main(self):
        self.threadLogAnalyser.start()
Пример #20
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        #ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.startButton.clicked.connect(self.handleClicked)
        self.checkboxes = [
            self.ui.checkBox, self.ui.checkBox_2, self.ui.checkBox_3,
            self.ui.checkBox_4, self.ui.checkBox_5, self.ui.checkBox_6
        ]

    def handleClicked(self):
        if not self.ui.locationInput.text():
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Warning)
            msgBox.setText("지역을 설정해주세요.")

        else:
            filter = json.load(open("mod.json"))["filter"]
            filter_list = []
            for c in self.checkboxes:
                if c.isChecked():
                    filter_list.append(filter[c.text()])
            filter = ":".join(filter_list)
            #thread
            self.thread = QThread()
            self.worker = Worker(self.ui.locationInput.text(), filter)
            self.worker.moveToThread(self.thread)
            self.thread.started.connect(self.worker.run)
            self.worker.finished.connect(self.thread.quit)
            self.worker.finished.connect(self.worker.deleteLater)
            self.thread.finished.connect(self.thread.deleteLater)
            self.worker.progress.connect(self.ui.progressBar.setValue)
            self.thread.start()
            self.ui.startButton.setEnabled(False)
            self.thread.finished.connect(self.handleFinished)

    def handleFinished(self):
        self.ui.startButton.setEnabled(True)
        self.ui.progressBar.setValue(0)
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setText("수집이 완료되었습니다.")
        msgBox.setDefaultButton(QMessageBox.Ok)
        ret = msgBox.exec_()
        if ret == QMessageBox.Ok:
            path = os.getcwd() + "/result"
            webbrowser.open('file:///' + path)
Пример #21
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.setText('Hello World!')

    def update(self, subject):
        self.ui.label.setText(str(subject.now))

        alarmtime = str(subject.alarmtime)
        self.ui.label_2.setText(alarmtime)

        countdown = str(subject.countdown)
        self.ui.label_3.setText(countdown)
Пример #22
0
class Gui(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.video = Video(cv2.VideoCapture(0))
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()

    def play(self):
        try:
            self.video.captureNextFrame()
            self.ui.videoFrame.setPixmap(self.video.convertFrame())
            self.ui.videoFrame.setScaledContents(True)
        except TypeError:
            print "No frame"
Пример #23
0
class StartQT4(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.clidict = Param_To_Cli()
        self.ui.interface_choice.addItems(netifaces.interfaces())
        QtCore.QObject.connect(
            self.ui.start, QtCore.SIGNAL("clicked()"), self.start_sniffer)
        QtCore.QObject.connect(
            self.ui.action_stop, QtCore.SIGNAL("triggered()"), self.stop_sniffer)
        #self.ui.packet_list.setHorizontalHeaderLabels(['时间','源地址','目的地址','内容'])
#        QtCore.QObject.connect(
#            self.ui.interface_choice, QtCore.SIGNAL("activated(const QString&)"), self.get_interface)
#
#        QtCore.QObject.connect(
#            self.ui.mode_choice, QtCore.SIGNAL("activated(const QString&)"), self.get_mode)
#        QtCore.QObject.connect(
#            self.ui.lineEdit, QtCore.SIGNAL("editingFinished()"), self.get_filter)
        

    def start_sniffer(self):
        self.clidict.interface = str(self.ui.interface_choice.currentText())
        self.clidict.mode = str(self.ui.mode_choice.currentText())
        self.clidict.filter = str(self.ui.lineEdit.text())
        log.debug(self.clidict.interface + '' + self.clidict.mode + '' + self.clidict.filter)
        sniffer_prepare(self.clidict)
        self.sniff_queue = multiprocessing.JoinableQueue()
        self.sniffer = SnifferProcess(self.sniff_queue, iface=str(self.clidict.interface))
        self.sniffer.start()
        self.displaythreading = DisplayPacket(self.sniff_queue, self.ui.packet_list)
        self.displaythreading.start()
        self.ui.action_stop.setEnabled(True)

    def stop_sniffer(self):
        self.sniffer.terminate()

        self.sniff_queue.close()
        while True:
            if self.sniff_queue.empty():
                break
        self.displaythreading.terminate()
Пример #24
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        self.images =[]
        self.outputs =[]
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.new_ch.clicked.connect(self.add_img)
        self.ui.new_ch_2.clicked.connect(self.add_output)

    def add_img(self):
        """add image and it's cpmponent there is NO number limit"""
        logging.info(f'add new image channel')
        a = cr_image(self.ui.scrollAreaWidgetContents_2,self.ui.verticalLayout_2,self.ui.comp_combo_l,self.ui.img_combo_l,self.ui.delete_ch,self.ui.open_img)
        self.images.append(a)
    def add_output(self):
        """add output there is NO number limit"""
        logging.info(f'add new output channel')
        a = cr_output(self.ui.scrollAreaWidgetContents,self.ui.output_display,self.ui.comp_combo_l,self.ui.output_select,self.ui.ratio_l,self.ui.img_combo_l,self.ui.save_img,self.ui.delete_ch_2)
        self.outputs.append(a)
Пример #25
0
class Gui(QtGui.QMainWindow):
	def __init__(self,parent=None):
		QtGui.QWidget.__init__(self,parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ui.start_button.clicked.connect(self.start_master)
		self.ui.connect_button.clicked.connect(self.start_client)
		self.ui.close_button.clicked.connect(self.close)
		self.CONNECTION_PORT = 1111
		self.update()

	def start_master(self):
		hablar_master(self.CONNECTION_PORT, self.ui.label)
		
	def start_client(self):
		ip = self.ui.ip.getText()
		hablar_client(ip, self.CONNECTION_PORT, self.ui.label)
		
	def close(self):
		sys.exit()
Пример #26
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.choose.clicked.connect(self.open_file_dialog)

    def open_file_dialog(self):
        file = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]
        if file is None or len(file) == 0:
            return

        img = cv2.imread(file, 0)
        edges = cv2.Canny(img, 100, 200)
        print(file)
        print(img)
        print(edges)

        self.ui.initial.setPixmap(QPixmap.fromImage(to_QImage(img)))
        self.ui.result.setPixmap(QPixmap.fromImage(to_QImage(edges)))
Пример #27
0
class CalcUi(QtWidgets.QMainWindow):
    def __init__(self):
        super(CalcUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Czyszczenie pól
        self.ui.doClean.clicked.connect(lambda: self.doCleanInputs())
        # Wykonanie dzialania
        self.ui.doCalc.clicked.connect(lambda: self.makeCalc())

        self.show()

    def doCleanInputs(self):
        self.ui.input_a.setText('')
        self.ui.input_b.setText('')
        self.ui.output.setText('')

    def makeCalc(self):
        a = float(self.ui.input_a.text())
        b = float(self.ui.input_b.text())
        try:
            if self.ui.check_dodaj.isChecked():
                calc = a + b
                self.ui.output.setText(str(calc))
            elif self.ui.check_odejmij.isChecked():
                calc = a - b
                self.ui.output.setText(str(calc))
            elif self.ui.check_mnoz.isChecked():
                calc = a * b
                self.ui.output.setText(str(calc))
            elif self.ui.check_dziel.isChecked():
                if b == 0.0 or b == 0 or b == '0':
                    self.ui.output.setText('Nie dziel przez 0!')
                else:
                    calc = a / b
                    self.ui.output.setText(str(calc))
        except error as e:
            print(e)
Пример #28
0
class FreereaderUi(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.readButton, QtCore.SIGNAL("clicked()"), self.readButton)
        QtCore.QMetaObject.connectSlotsByName(self)
    
    def readButton(self):
        self.notify('please wait')
        
        try:
            obj = feedparser.parse(str(self.ui.urlText.text()))
            self.notify('feed readed')
            if obj.entries != []:
                for entry in obj.entries:
                    self.ui.listWidget.addItem(entry.title)
        except:
            self.notify('error in parsing url')
    
    def notify(self, string = ''):
        self.ui.notification.setText(string)
Пример #29
0
class MainWindow(QMainWindow):
    '''First application window the user sees'''
    def __init__(self, pod):
        super().__init__()
        self._pod = pod
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
        self._ui.actionNetwork.triggered.connect(self.networkDialog)

    def networkDialog(self):
        '''Open a window for changing network settings'''
        la = self._pod.get_local_addr()
        ra = self._pod.get_remote_addr()
        info = NetworkInfo(local=la, remote=ra)
        dialog = NetworkDialog(info)
        if dialog.exec_() == QDialog.Accepted:
            la, old = info.local, la
            if la != old:
                self._pod.set_local_addr(info.local)
            ra, old = info.remote, ra
            if ra != old:
                self._pod.set_remote_addr(info.remote)
Пример #30
0
class scrap(QtWidgets.QMainWindow):
    def __init__(self):
        super(scrap, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_UI()

    def init_UI(self):
        self.setWindowTitle('Web-scraper')

        self.ui.lineEdit.setPlaceholderText('url')
        self.ui.pushButton.clicked.connect(self.scrapping)

    def scrapping(self):
        url = self.ui.lineEdit.text()
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'lxml')
        quotes = soup.find_all('div')
        with open('test-scrap.doc', 'w', encoding='utf-8') as output_file:
            for quote in quotes:
                print(quote.text)
                output_file.write(quote.text)
Пример #31
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setStyleSheet(
            "background-image: url(binaries/backgroundmain.png);")
        self.setWindowIcon(QIcon('binaries/icon.png'))
        self.setWindowTitle('Steam Sales Finder by dewar')
        self.ui.listWidget.setStyleSheet(
            "background-image: url(binaries/background.png);color: rgb(255, 255, 255);"
        )
        self.ui.pushButton.setStyleSheet(
            "background-image: url(binaries/background.png);color: rgb(255, 255, 255);"
        )
        self.ui.pushButton_2.setStyleSheet(
            "background-image: url(binaries/background.png);color: rgb(255, 255, 255);"
        )
        self.ui.spinBox.setStyleSheet(
            "background-image: url(binaries/background.png); color: rgb(0, 39, 75);"
        )
        self.ui.pushButton.clicked.connect(self.btnClicked)
        self.ui.pushButton_2.clicked.connect(self.btnClicked_2)

    def btnClicked(self):
        count = self.ui.spinBox.value()
        main(count)
        text = str(self.ui.comboBox.currentText())
        if text == "По порядку":
            for h in range(len(finlist)):
                self.ui.listWidget.addItem(finlist[h])
        elif text == "По алфавиту":
            for h in range(len(finlist)):
                self.ui.listWidget.addItem(natsorted(finlist)[h])

    def btnClicked_2(self):
        self.close()
Пример #32
0
class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.startTask)
        self.ui.pushButton_2.clicked.connect(self.close)

    def startTask(self):
        self.ui.movie=QtGui.QMovie("C:\\Users\\KIIT\\Desktop\\JarvisUI\\sFaoXq3.gif")
        self.ui.label.setMovie(self.ui.movie)
        self.ui.movie.start()
        self.ui.movie=QtGui.QMovie("C:\\Users\\KIIT\\Desktop\\JarvisUI\\iron-man-jarvis-gif-5.gif")
        self.ui.label_2.setMovie(self.ui.movie)
        self.ui.movie.start() 

        self.ui.movie=QtGui.QMovie("C:\\Users\\KIIT\\Desktop\\JarvisUI\\BigheartedVagueFoal-size_restricted.gif")
        self.ui.label_3.setMovie(self.ui.movie)
        self.ui.movie.start()
        self.ui.movie=QtGui.QMovie("C:\\Users\\KIIT\\Desktop\\JarvisUI\\hey.gif")
        self.ui.label_4.setMovie(self.ui.movie)
        self.ui.movie.start()   

        self.ui.movie=QtGui.QMovie("C:\\Users\\KIIT\\Desktop\\JarvisUI\\jarvislogo.gif")
        self.ui.label_5.setMovie(self.ui.movie)
        self.ui.movie.start()
        self.ui.movie=QtGui.QMovie("C:\\Users\\KIIT\\Desktop\\JarvisUI\\iron-man-jarvis-gif-5.gif")
        self.ui.label_6.setMovie(self.ui.movie)
        self.ui.movie.start() 
        timer=QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)
        startExecution.start()

    def showTime(self):
        current_time=QTime.currentTime()
        lable_time=current_time.toString("hh:mm:ss")
        self.ui.textBrowser.setText(lable_time)
Пример #33
0
class MainWindow(QMainWindow):
    '''First application window the user sees'''

    def __init__(self, pod):
        super().__init__()
        self._pod = pod
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
        self._ui.actionNetwork.triggered.connect(self.networkDialog)

    def networkDialog(self):
        '''Open a window for changing network settings'''
        la = self._pod.get_local_addr()
        ra = self._pod.get_remote_addr()
        info = NetworkInfo(local=la, remote=ra)
        dialog = NetworkDialog(info)
        if dialog.exec_() == QDialog.Accepted:
            la, old = info.local, la
            if la != old:
                self._pod.set_local_addr(info.local)
            ra, old = info.remote, ra
            if ra != old:
                self._pod.set_remote_addr(info.remote)
Пример #34
0
class Main(QtWidgets.QMainWindow):
    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_UI()

    def init_UI(self):
        print(4)
        self.ui.pushButton.clicked.connect(self.button)
        #self.ui.verticalSlider.setRepeatAction(self.button,50,50)

    def button(self):
        print(5)
        ok = int(self.ui.verticalSlider.sliderPosition() * 2.55)
        ok1 = int(self.ui.verticalSlider_2.sliderPosition() * 2.55)
        ok2 = int(self.ui.verticalSlider_3.sliderPosition() * 2.55)
        l = ok * 16 * 16 * 16 * 16 + ok1 * 16 * 16 + ok2
        print(str(hex(l))[2::])
        l = str(hex(l))[2::]
        if ok < 16:
            l = "0" + l
        self.ui.centralwidget.setStyleSheet("QPushButton{background-color: #" +
                                            l + ";}")
Пример #35
0
class jaabaGUI(QMainWindow):
    """ controller for the blob labeling GUI"""
    def __init__(self,parent=None):
        QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #add new slider
        # self.positionSlider=QSlider(Qt.Horizontal)
        # self.positionSlider.setGeometry (800,800,100,30)
        # self.positionSlider.setRange(0, 0)
        # self.positionSlider.sliderMoved.connect(self.setPosition)

        #setup Video
        #video player
        self.mediaPlayer1 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer2 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        #self.mediaPlayer.metaDataChanged.connect(self.metaDataChanged)
        self.mediaPlayer1.durationChanged.connect(self.durationChanged)
        self.mediaPlayer1.positionChanged.connect(self.positionChanged)
        self.mediaPlayer2.positionChanged.connect(self.positionChanged)
        

        #visualizetion
        self.scene = QGraphicsScene()
        self.ui.graphicsView.setScene(self.scene)
        #self.scene.setBackgroundBrush(Qt.black)
        self.videoItem1 = QGraphicsVideoItem()
        self.videoItem2 = QGraphicsVideoItem()
        self.scene.addItem(self.videoItem1)
        self.scene.addItem(self.videoItem2)
        self.mediaPlayer1.setVideoOutput(self.videoItem1)
        self.mediaPlayer2.setVideoOutput(self.videoItem2)

        #slide bar
        print self.ui.horizontalSlider
        self.ui.horizontalSlider.setRange(0, 0)
        self.ui.horizontalSlider.sliderMoved.connect(self.setPosition)
        # self.ui.horizontalSlider.sliderPressed.connect(self.sliderPressed)



        #print self.ui.graphicsView.width()/2,self.ui.graphicsView.height()
        #self.videoItem1.setSize(QSizeF(self.ui.graphicsView.width()/2,self.ui.graphicsView.height()))
        #self.videoItem2.setSize(QSizeF(self.ui.graphicsView.width()*10,self.ui.graphicsView.height()*10))
       # self.videoItem2.setSize(graphicsView.size())
        #self.videoItem2.setOffset(QPointF(500,500))
        #self.videoItem2.setOffset(QPointF(self.ui.graphicsView.width()/2,0))   
        #self.videoItem2.setPos(QPointF(0,0))
        # print self.ui.graphicsView.width(), self.ui.graphicsView.height()
        # print self.ui.graphicsView.size()
        # print self.videoItem2.boundingRect().width(), self.videoItem2.boundingRect().height()
        # print self.ui.graphicsView.sceneRect()
        #self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)

        #callbacks
        self.ui.actionQuit.triggered.connect(self.quit)
        self.ui.actionLoad_Project.triggered.connect(self.loadVideo)
        #self.ui.buttonPlay.clicked[bool].connect(self.setToggleText)
        self.ui.buttonPlay.clicked.connect(self.play)
        #print self.ui.graphicsView.sizeHint()


        #initialization
        self.loaded = False
        self.videoFilename = None
        self.frame_count=None
        self.width=None
        self.height=None
        self.frame_trans=None



        
    # ###actions starts from here###
    def quit(self):
        QApplication.quit()

    def loadVideo(self):
        self.writeLog("Loading video...")

        self.videoFilename = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]
        if not self.videoFilename:
            self.writeLog("User cancelled - no video loaded")
            return
        else:
       		cap=cv2.VideoCapture(self.videoFilename)
	    	self.frame_count=cap.get(cv2.CAP_PROP_FRAME_COUNT)
	    	self.width=cap.get(3)
	    	self.height=cap.get(4)
	        self.mediaPlayer2.setMedia(QMediaContent(QUrl.fromLocalFile(self.videoFilename )))
	        self.mediaPlayer1.setMedia(QMediaContent(QUrl.fromLocalFile(self.videoFilename )))
	        self.ui.buttonPlay.setEnabled(True)
            # self.mediaPlayer2.setVideoOutput(self.videoItem2)
            # self.mediaPlayer1.setVideoOutput(self.videoItem1)
            # size= self.videoItem2.nativeSize()
            # print size
            #print self.mediaPlayer.duration()
          
            #print self.mediaPlayer.metaData()
        self.writeLog("Video loaded!")

    def play(self):
    	
        self.videoItem1.setAspectRatioMode(0)
        self.videoItem2.setAspectRatioMode(0)
        self.scene.setSceneRect(0,0,self.ui.graphicsView.width(),self.ui.graphicsView.height())
        self.videoItem1.setSize(QSizeF(self.ui.graphicsView.width()/2,self.ui.graphicsView.height()))
        self.videoItem2.setSize(QSizeF(self.ui.graphicsView.width()/2,self.ui.graphicsView.height()))
        self.videoItem1.setPos(QPointF(0,0))
        self.videoItem2.setPos(QPointF(self.ui.graphicsView.width()/2,0))
        #self.ui.graphicsView.setGeometry(0,0, 600,800)
        #print 'graphicsView size', self.ui.graphicsView.size()
        #print 'graphicsScene size', self.scene.sceneRect()
        #self.videoItem2.setSize(QSizeF(1000,300))
        #print 'graphicsVideoItem size',self.videoItem2.size()
        # print 'item x',self.videoItem2.scenePos().x()
        # print 'item y', self.videoItem2.scenePos().y()
        # print 'item x',self.videoItem1.scenePos().x()
        # print 'item y', self.videoItem1.scenePos().y()

        if self.mediaPlayer1.state() == QMediaPlayer.PlayingState:
        	self.ui.buttonPlay.setIcon(self.ui.style().standardIcon(PyQt5.QtWidgets.QStyle.SP_MediaPlay))
        	self.ui.buttonPlay.setText("Play")
        	self.mediaPlayer1.pause()
        	self.writeLog("Video paused")
        else: 
        	self.ui.buttonPlay.setIcon(self.ui.style().standardIcon(PyQt5.QtWidgets.QStyle.SP_MediaPause))
	        self.ui.buttonPlay.setText("Stop")
	        self.mediaPlayer1.play()
	        self.writeLog("Playing video")

        if self.mediaPlayer2.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer2.pause()
        else: 
            self.mediaPlayer2.play()


        
        #size= self.videoItem2.nativeSize()
        # print self.mediaPlayer.duration()
      
        #print self.mediaPlayer.metaData()
      

        # print self.ui.graphicsView.width(), self.ui.graphicsView.height()
        # print self.ui.graphicsView.size()
        # print self.videoItem2.boundingRect().width(), self.videoItem2.boundingRect().height()
        # print self.ui.graphicsView.sceneRect()
        # print self.scene.sceneRect()
        # print self.ui.graphicsView.sizeHint()

    

    def setPosition(self, position):
    	self.mediaPlayer1.setPosition(position) 
    	self.mediaPlayer2.setPosition(position)  

    # when position of media changed, set slider and text box accordingly.
    def positionChanged(self, position):
        self.ui.horizontalSlider.setValue(position)
        if isinstance(self.frame_trans,float):
	        # print type(position),position
	        # print type(self.frame_trans),self.frame_trans 
	        # print position/self.frame_trans
	     	self.ui.lineEdit.setText(str(int(round(position/self.frame_trans,0))))
	       
        self.writeLog(str(position))    
    
    def durationChanged(self, duration):
	    self.ui.horizontalSlider.setRange(0, duration) 
	    self.frame_trans=self.mediaPlayer1.duration()/self.frame_count
	    print self.frame_trans

    

    def writeLog(self,text):
        self.ui.log.setText(text)
Пример #36
0
class Gui(QtGui.QMainWindow):
    """ 
    Main GUI Class
    It contains the main function and interfaces between 
    the GUI and functions
    """
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        """ Main Variables Using Other Classes"""
        self.rex = Rexarm()
        self.video = Video(cv2.VideoCapture(0))
	self.world_coord = np.float32()

	""" Play and Repeat Variable """
	self.wayPoints = []
        self.wayPointsPos = []
	self.wayPointsSpeed = []
	self.wayPointsTime = []

        """ Other Variables """
        self.last_click = np.float32([-1,-1])
	self.define_template_flag = -1
        self.click_point1 = np.float32([-1,-1])
        self.click_point2 = np.float32([-1,-1])
	self.template = None
	self.targets = []
	self.waypointsfp = csv.writer(open("waypoint.csv","wb"))
        self.currtime = 0
        """ Set GUI to track mouse """
        QtGui.QWidget.setMouseTracking(self,True)

        """ 
        Video Function 
        Creates a timer and calls play() function 
        according to the given time delay (27mm) 
        """
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
       
        """ 
        LCM Arm Feedback
        Creates a timer to call LCM handler continuously
        No delay implemented. Reads all time 
        """  
        self._timer2 = QtCore.QTimer(self)
        self._timer2.timeout.connect(self.rex.get_feedback)
        self._timer2.start()

	"""
	ARM Plan and Command Thread
	Creates a timer to call REXARM.plan_command function continuously
	"""
	self._timer3 = QtCore.QTimer(self)
	self._timer3.timeout.connect(self.rex.plan_command)
	self._timer3.start()
        
	"""
        Connect Sliders to Function
        TO DO: CONNECT THE OTHER 5 SLIDERS IMPLEMENTED IN THE GUI 
        """ 
        self.ui.sldrBase.valueChanged.connect(self.slider_change)
        self.ui.sldrShoulder.valueChanged.connect(self.slider_change)
        self.ui.sldrElbow.valueChanged.connect(self.slider_change)
        self.ui.sldrWrist.valueChanged.connect(self.slider_change)
        self.ui.sldrMaxTorque.valueChanged.connect(self.slider_change)
	self.ui.sldrSpeed.valueChanged.connect(self.slider_change)

        """ Commands the arm as the arm initialize to 0,0,0,0 angles """
        self.slider_change() 
        
        """ Connect Buttons to Functions """
        self.ui.btnLoadCameraCal.clicked.connect(self.load_camera_cal)
        self.ui.btnPerfAffineCal.clicked.connect(self.affine_cal)
        self.ui.btnTeachRepeat.clicked.connect(self.tr_initialize)
        self.ui.btnAddWaypoint.clicked.connect(self.tr_add_waypoint)
        self.ui.btnSmoothPath.clicked.connect(self.tr_smooth_path)
        self.ui.btnPlayback.clicked.connect(self.tr_playback)
	self.ui.btnLoadPlan.clicked.connect(self.tr_load)
        self.ui.btnDefineTemplate.clicked.connect(self.def_template)
        self.ui.btnLocateTargets.clicked.connect(self.template_match)
        self.ui.btnExecutePath.clicked.connect(self.exec_path)


    def play(self):
        """ 
        Play Funtion
        Continuously called by GUI 
        """

        """ Renders the Video Frame """
        try:
            self.video.captureNextFrame()
	    for t in self.targets:
	    	self.video.addTarget(t)
            self.ui.videoFrame.setPixmap(self.video.convertFrame())
            self.ui.videoFrame.setScaledContents(True)
	    cv2.imwrite("curretFrame.png", self.video.currentFrame)
        except TypeError:
            print "No frame"
        
        """ 
        Update GUI Joint Coordinates Labels
        TO DO: include the other slider labels 
        """
        self.ui.rdoutBaseJC.setText(str(self.rex.joint_angles_fb[0]*R2D))
        self.ui.rdoutShoulderJC.setText(str(self.rex.joint_angles_fb[1]*R2D))
        self.ui.rdoutElbowJC.setText(str(self.rex.joint_angles_fb[2]*R2D))
        self.ui.rdoutWristJC.setText(str(self.rex.joint_angles_fb[3]*R2D))

	fk_result = self.rex.rexarm_FK(3)
	#print fk_result
        self.ui.rdoutX.setText(repr(fk_result[0]))
        self.ui.rdoutY.setText(repr(fk_result[1]))
        self.ui.rdoutZ.setText(repr(fk_result[2]))
	self.ui.rdoutT.setText(repr(fk_result[3]))
        """ 
        Mouse position presentation in GUI
        TO DO: after getting affine calibration make the apprriate label
        to present the value of mouse position in world coordinates 
        """    
        x = QtGui.QWidget.mapFromGlobal(self,QtGui.QCursor.pos()).x()
        y = QtGui.QWidget.mapFromGlobal(self,QtGui.QCursor.pos()).y()
        if ((x < MIN_X) or (x > MAX_X) or (y < MIN_Y) or (y > MAX_Y)):
            self.ui.rdoutMousePixels.setText("(-,-)")
            self.ui.rdoutMouseWorld.setText("(-,-)")
        else:
            x = x - MIN_X
            y = y - MIN_Y
            self.ui.rdoutMousePixels.setText("(%.0f,%.0f)" % (x,y))
            if (self.video.aff_flag == 2):
                """ TO DO Here is where affine calibration must be used """
                self.ui.rdoutMouseWorld.setText("(%0.f,%0.f)" % (self.world_coord[0][0], self.world_coord[1][0]))
            else:
                self.ui.rdoutMouseWorld.setText("(-,-)")

        """ 
        Updates status label when rexarm playback is been executed.
        This will be extended to includ eother appropriate messages
        """ 
        if(self.rex.plan_status == 1):
            self.ui.rdoutStatus.setText("Playing Back - Waypoint %d"
                                    %(self.rex.wpt_number + 1))


    def slider_change(self):
        """ 
        Function to change the slider labels when sliders are moved
        and to command the arm to the given position 
        TO DO: Implement for the other sliders
        """
        self.ui.rdoutBase.setText(str(self.ui.sldrBase.value()))
        self.ui.rdoutShoulder.setText(str(self.ui.sldrShoulder.value()))
        self.ui.rdoutElbow.setText(str(self.ui.sldrElbow.value()))
        self.ui.rdoutWrist.setText(str(self.ui.sldrWrist.value()))
        self.ui.rdoutTorq.setText(str(self.ui.sldrMaxTorque.value()) + "%")
        self.ui.rdoutSpeed.setText(str(self.ui.sldrSpeed.value()) + "%")
        self.rex.max_torque = self.ui.sldrMaxTorque.value()/100.0
	for i in xrange(4):
            self.rex.speed[i] = self.ui.sldrSpeed.value()/100.0
        self.rex.joint_angles[0] = self.ui.sldrBase.value()*D2R
        self.rex.joint_angles[1] = self.ui.sldrShoulder.value()*D2R
        self.rex.joint_angles[2] = self.ui.sldrElbow.value()*D2R
        self.rex.joint_angles[3] = self.ui.sldrWrist.value()*D2R
        self.rex.cmd_publish()

    def mousePressEvent(self, QMouseEvent):
        """ 
        Function used to record mouse click positions for 
        affine calibration 
        """
 
        """ Get mouse posiiton """
        x = QMouseEvent.x()
        y = QMouseEvent.y()

        """ If mouse position is not over the camera image ignore """
        if ((x < MIN_X) or (x > MAX_X) or (y < MIN_Y) or (y > MAX_Y)): return

        """ Change coordinates to image axis """
        self.last_click[0] = x - MIN_X
        self.last_click[1] = y - MIN_Y
       
        """ If affine calibration is been performed """
        if (self.video.aff_flag == 1):
            """ Save last mouse coordinate """
	    self.video.mouse_coord[self.video.mouse_click_id] = [(x-MIN_X),(y-MIN_Y)]

            """ Update the number of used poitns for calibration """
            self.video.mouse_click_id += 1

            """ Update status label text """
            self.ui.rdoutStatus.setText("Affine Calibration: Click point %d" 
                                      %(self.video.mouse_click_id + 1))

            """ 
            If the number of click is equal to the expected number of points
            computes the affine calibration.
            TO DO: Change this code to use you programmed affine calibration
            and NOT openCV pre-programmed function as it is done now.
            """
            if(self.video.mouse_click_id == self.video.aff_npoints):
                """ 
                Update status of calibration flag and number of mouse
                clicks
                """
                self.video.aff_flag = 2
                self.video.mouse_click_id = 0
                
		print self.video.mouse_coord
		print self.video.real_coord
                """ Perform affine calibration with OpenCV """
                #self.video.aff_matrix = cv2.getAffineTransform(
                #                        self.video.mouse_coord,
                #                        self.video.real_coord)
		self.video.compute_affine_matrix()            

                """ Updates Status Label to inform calibration is done """ 
                self.ui.rdoutStatus.setText("Waiting for input")

                """ 
                Uncomment to gether affine calibration matrix numbers 
                on terminal
                """ 
                print self.video.aff_matrix
	if self.video.aff_flag == 2:
            mouse_coord = np.array([[(x-MIN_X)], [(y-MIN_Y)],[1]])
	    self.world_coord = np.dot(self.video.aff_matrix, mouse_coord)
	
	if self.define_template_flag == 0:
	    self.click_point1 = copy.deepcopy(self.last_click)
	    self.define_template_flag = 1
	elif self.define_template_flag == 1:
	    self.click_point2 = copy.deepcopy(self.last_click)
	    self.template = copy.deepcopy(self.video.bwFrame[2*self.click_point1[1]:2*self.click_point2[1],2*self.click_point1[0]:2*self.click_point2[0]])
	    print self.click_point1
            print self.click_point2
	    self.define_template_flag = -1
	    cv2.imwrite('./template.png', self.template)

    def affine_cal(self):
        """ 
        Function called when affine calibration button is called.
        Note it only chnage the flag to record the next mouse clicks
        and updates the status text label 
        """
        self.video.aff_flag = 1 
        self.ui.rdoutStatus.setText("Affine Calibration: Click point %d" 
                                    %(self.video.mouse_click_id + 1))

    def load_camera_cal(self):
        print "Load Camera Cal"
	self.video.loadCalibration()

    def tr_initialize(self):
	self.wayPointsPos = []
	self.wayPointsSpeed = []
	self.wayPointsTime = []
        print "Teach and Repeat"

    def tr_add_waypoint(self):
	#waypoints1 = copy.deepcopy(self.rex.joint_angles_fb)
	#waypoints2 = copy.deepcopy(self.rex.joint_angles_fb)
	#self.wayPointsPos.append(waypoints1)
	#self.wayPointsTime.append([self.currtime, self.currtime, self.currtime, self.currtime])
        #self.wayPointsSpeed.append([0.1, 0.1, 0.1, 0.1])
        #self.currtime += 70000
	#waypoints2[1] -= 0.7
	#self.wayPointsPos.append(waypoints2)
	#self.wayPointsTime.append([self.currtime, self.currtime, self.currtime, self.currtime])
        #self.wayPointsSpeed.append([0.1, 0.1, 0.1, 0.1])
        #self.currtime += 70000
	#self.waypointsfp.writerow(waypoints1)
	#self.waypointsfp.writerow(waypoints2)
	#np.save("waypointsPos",self.wayPointsPos)
	#np.save("waypointsSpeed", self.wayPointsSpeed)
	#np.save("waypointsTime", self.wayPointsTime)
	self.wayPointsPos.append(copy.deepcopy(self.rex.joint_angles_fb))
	self.wayPointsSpeed.append(copy.deepcopy(self.rex.speed_fb))
	self.wayPointsTime.append(copy.deepcopy(self.rex.time_fb))
	np.save("waypointsPos",self.wayPointsPos)
	np.save("waypointsSpeed", self.wayPointsSpeed)
	np.save("waypointsTime", self.wayPointsTime)
	#print self.wayPoints
        print "Add Waypoint"
    
    def cubic_spline(self, q0, q0dot, t0, qf, qfdot, tf, stepnum):
	a0 = q0
	a1 = q0dot
	a2 = (3*(qf-q0) - (2*q0dot+qfdot)*float(tf-t0)) / float((tf-t0)*(tf-t0))
	a3 = (2*(q0-qf) + (q0dot+qfdot)*float(tf-t0)) / float((tf-t0)*(tf-t0)*(tf-t0))
	stepsize = float(tf-t0)/float(stepnum)
	currtime = t0 + stepsize
	pos_interpolated = []
	speed_interpolated = []
	for i in xrange(stepnum-1):
	   pos_interpolated.append(a0 + a1*currtime + a2*currtime*currtime + \
				   a3*currtime*currtime*currtime)
	   speed_interpolated.append(np.abs(a1 + 2*a2*currtime + 3*a3*currtime*currtime))
	   currtime += stepsize
	#print q0, qf
	#print pos_interpolated
	return (pos_interpolated, speed_interpolated) 

    def tr_smooth_path(self):
	if len(self.wayPointsPos) != len(self.wayPointsSpeed) and len(self.wayPointsPos) != len(self.wayPointsTime):
	    print "Error on waypoints number, cannot smooth path"
	    return
	for i in xrange(len(self.wayPointsTime)):
	    for j in xrange(4):
		self.wayPointsTime[i][j] *= US2S 
	for i in xrange(len(self.wayPointsSpeed)):
	    for j in xrange(4):
		self.wayPointsSpeed[i][j] *= percent2rads 
	interpolated_waypoints_pos = []
	interpolated_waypoints_speed = []
	for i in xrange(len(self.wayPointsPos)-1):
	    time_offset = self.wayPointsTime[i]
            startPos = self.wayPointsPos[i]
	    endPos = self.wayPointsPos[i+1]
	    startSpeed = self.wayPointsSpeed[i]
	    endSpeed = self.wayPointsSpeed[i+1]
	    startTime = self.wayPointsTime[i] 
	    endTime = self.wayPointsTime[i+1] 
	    stepnum = 3
	    four_joint_interpolated_pos = []
	    four_joint_interpolated_speed = []
	    for j in xrange(4):
		q0 = startPos[j]
		q0dot = startSpeed[j]
		t0 = startTime[j] - time_offset[j]
		qf = endPos[j]
		qfdot = endSpeed[j]
		tf = endTime[j] - time_offset[j]
		res = self.cubic_spline(q0, q0dot, t0, qf, qfdot, tf, stepnum)
		four_joint_interpolated_pos.append(res[0])
		four_joint_interpolated_speed.append(res[1])
	    
	    interpolated_waypoints_pos.append(startPos)
	    for i in xrange(len(four_joint_interpolated_pos[0])):
	        pos = []
		for j in xrange(len(four_joint_interpolated_pos)):
		    pos.append(four_joint_interpolated_pos[j][i])
		interpolated_waypoints_pos.append(pos)
	    interpolated_waypoints_pos.append(endPos)

	    interpolated_waypoints_speed.append(startSpeed)
	    for i in xrange(len(four_joint_interpolated_speed[0])):
	        speed = []
		for j in xrange(len(four_joint_interpolated_speed)):
		    speed.append(four_joint_interpolated_speed[j][i])
		interpolated_waypoints_speed.append(speed)
	    interpolated_waypoints_speed.append(endSpeed)

	self.wayPointsPos = interpolated_waypoints_pos
	self.wayPointsSpeed = interpolated_waypoints_speed
	for i in xrange(len(self.wayPointsSpeed)):
	    for j in xrange(len(self.wayPointsSpeed[0])):
	        self.wayPointsSpeed[i][j] /= percent2rads
	#pprint.pprint(self.wayPointsPos)
	#pprint.pprint(self.wayPointsSpeed)
	np.save("interpolated_waypoints_pos", self.wayPointsPos)
	np.save("interpolated_waypoints_speed", self.wayPointsSpeed)
        print "Smooth Path"

    def tr_playback(self):
	#print self.wayPoints
	self.rex.planPos = self.wayPointsPos
	self.rex.planSpeed = self.wayPointsSpeed 
	#print self.rex.plan
        self.rex.save_data = True
	self.rex.plan_status = 1
	self.rex.wpt_number = 0
	self.rex.wpt_total = len(self.rex.planPos)
        print "Playback"

    def tr_load(self):
        self.wayPointsPos = np.load("waypointsPos.npy")
	self.wayPointsSpeed = np.load("waypointsSpeed.npy")
	self.wayPointsTime = np.load("waypointsTime.npy")
	print "Load waypoints"

    def def_template(self):
        print "Define Template"
	self.define_template_flag = 0

    @do_cprofile
    def template_match(self):
        print "Template Match"
        self.targets = []
	result_pq = Queue.PriorityQueue()
	template = cv2.resize(self.template, None, fx=0.6, fy=0.6, interpolation=cv2.INTER_AREA)
	frame = cv2.resize(self.video.bwFrame, None, fx=0.6, fy=0.6, interpolation=cv2.INTER_AREA)
	height, width = template.shape	
	for i in xrange(0, frame.shape[0] - height):
	    for j in xrange(0, frame.shape[1] - width):
               	center_x = (i + height/2.0)/0.6
		center_y = (j + width/2.0)/0.6
		to_compare = frame[i:i+height,j:j+width]
		num = la.norm(to_compare - template) 
		result_pq.put((num, center_y, center_x))		
        result = []
	#for i in xrange(40):
	#    t = result_pq.get()
        #    print t[0]
        #    result.append([int(t[1]), int(t[2])])
        for i in xrange((frame.shape[0]-height)*(frame.shape[1]-width)):
            t = result_pq.get()
            if t[0] > 350:
                break
            else:
                result.append([int(t[1]), int(t[2])])
	distort = sys.maxint 
	cluster_size = 1
        #print result
	while distort > 20:
            clustered_result, distort = scv.kmeans(np.array(result), cluster_size)
            cluster_size += 1
        clustered_result, distort = scv.kmeans(np.array(result), 4)
        print "cluster_size: ", cluster_size-1
        print "distort", distort
        for r in clustered_result:
	    print r
	    self.targets.append((r[0], r[1]))
        #circles = cv2.HoughCircles(self.video.bwFrame, cv2.cv.CV_HOUGH_GRADIENT, 1, minDist=5, param1=50, param2=50, minRadius=1, maxRadius=30) 
        #for c in circlesi[0,:]:
        #    print c
        #    self.targets.append((c[0],c[1]))
 	#img = np.zeros((1000,1000,3), np.uint8)	
	#for t in self.targets:
	#    img = cv2.circle(img, t, 10, (255,255,255), -1)	
	#cv2.imwrite("./result.png", img)

    def exec_path(self):
        #waypoints = [(-80.0, 90.0, 350.0), (70.0, 80.0, 400.0), (-180.0, -250.0, 125.0),(240.0, -190.0, 95.0), (-80.0, 90.0, 350.0)]
        #waypoints = [(-100.0, 100.0, 5.0), (-100.0, 100.0, 200.0), (100.0, 100.0, 200.0),(100.0, 100.0, 5.0), (100.0, -100.0, 5.0), (100.0, -100.0, 200.0), (100.0, 100.0, 200.0)]
        waypoints = []
        for t in xrange(0,12,1):
            x = 150 * np.cos(t)
            y = 150 * np.sin(t)
            z = 5.0 + 30.0 * t
            waypoints.append((x, y, z))
        #waypoints = []
        #if not self.targets or len(self.targets) == 0:
        #    return
        #for t in self.targets:
        #    img_coord = np.array([[(t[0]/2.0)], [(t[1]/2.0)], [1]]) 
	#    world_coord = np.dot(self.video.aff_matrix, img_coord)
        #    print "img coord: ", img_coord
        #    print "world coord: ", world_coord
        #    waypoints.append((world_coord[0], world_coord[1], 5)) 
        print waypoints
	self.wayPointsPos = []
	self.wayPointsSpeed = []
	self.wayPointsTime = []
	for i in xrange(0, 3*len(waypoints), 3):
	    x, y, z = waypoints[i/3]
            self.wayPointsPos.append(self.rex.rexarm_IK_Search((x,y,z)))
            self.wayPointsSpeed.append(copy.deepcopy([0.15, 0.15, 0.15, 0.15]))
	    #jointsUp = self.rex.rexarm_IK_Search((x, y, 50.0))
	    #jointsDown = self.rex.rexarm_IK_Search((x, y, 0.0))
            #if jointsUp:
	    #    self.wayPointsPos.append(copy.deepcopy(jointsUp))
            #    self.wayPointsSpeed.append(copy.deepcopy([0.15, 0.15, 0.15, 0.15]))
            #    self.wayPointsTime.append([2000000*i,2000000*i,2000000*i,2000000*i])
            #
            #if jointsDown:
            #    self.wayPointsPos.append(copy.deepcopy(jointsDown))
	    #    self.wayPointsSpeed.append(copy.deepcopy([0.05, 0.05, 0.05, 0.05]))
	    #    self.wayPointsTime.append([2000000*(i+1),2000000*(i+1),2000000*(i+1),2000000*(i+1)])
            
            #if jointsUp:
	    #    self.wayPointsPos.append(copy.deepcopy(jointsUp))
	    #    self.wayPointsSpeed.append(copy.deepcopy([0.05, 0.05, 0.05, 0.05]))
	    #    self.wayPointsTime.append([2000000*(i+2),2000000*(i+2),2000000*(i+2),2000000*(i+2)])

	np.save("funPathPos",self.wayPointsPos)
	np.save("funPathSpeed", self.wayPointsSpeed)
	np.save("funPathTime", self.wayPointsTime)

	self.rex.planPos = self.wayPointsPos
	self.rex.planSpeed = self.wayPointsSpeed 
	print self.rex.planPos
        self.rex.save_data = True
	self.rex.plan_status = 1
	self.rex.wpt_number = 0
	self.rex.wpt_total = len(self.rex.planPos)
class Main(QtGui.QMainWindow):
    """
    Lanza la grilla principa
    """
    def __init__(self,parent=None):
        super(Main, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.load_data()
        self.connect_signals()
        self.show()

    def connect_signals(self):
        self.ui.agregar_marca.clicked.connect(self.agregar)
        self.ui.edtar_marca.clicked.connect(self.edit)
        self.ui.eliminar_marca.clicked.connect(self.delete)

    def load_data(self):
        """
        Función que carga la información de marcas en la grilla
        incluyendo la cantidad de modelos asociados a la marca
        """
        print "load data.."
        marcas = db_marcas.obtener_marcas()
        #Creamos el modelo asociado a la tabla
        self.data = QtGui.QStandardItemModel(len(marcas)+1, 3)
        self.data.setHorizontalHeaderItem(
            0, QtGui.QStandardItem("Nombre de Marca"))
        self.data.setHorizontalHeaderItem(
            1, QtGui.QStandardItem("Pais de Origen"))
        self.data.setHorizontalHeaderItem(
            2, QtGui.QStandardItem(u"Cantidad de Modelos"))

        for r, row in enumerate(marcas):
            index = self.data.index(r, 0, QtCore.QModelIndex())
            self.data.setData(index, row['Nombre de Marca'])
            index = self.data.index(r, 1, QtCore.QModelIndex())
            self.data.setData(index, row['Pais de Origen'])
            index = self.data.index(r, 2, QtCore.QModelIndex())
            self.data.setData(index, row['Cantidad de Modelos'])

        self.ui.tabla_marcas.setModel(self.data)

        # Para que las columnas 1 y 2 se estire o contraiga cuando
        # se cambia el tamaño de la pantalla
        self.ui.tabla_marcas.horizontalHeader().setResizeMode(
            0, self.ui.tabla_marcas.horizontalHeader().Stretch)
        self.ui.tabla_marcas.horizontalHeader().setResizeMode(
            1, self.ui.tabla_marcas.horizontalHeader().Stretch)

        self.ui.tabla_marcas.setColumnWidth(0, 100)
        self.ui.tabla_marcas.setColumnWidth(1, 210)
        self.ui.tabla_marcas.setColumnWidth(2, 210)

    def delete(self):
        """
        Función que borra un alumno de la base de datos e
        indica el resultado de la operación
        """
        data = self.ui.tabla_marcas.model()
        index = self.ui.tabla_marcas.currentIndex()
        if index.row() == -1:  # No se ha seleccionado una fila
            self.errorMessageDialog = QtGui.QErrorMessage(self)
            self.errorMessageDialog.showMessage(u"Debe seleccionar una fila")
            return False
        else:
            self.resp = QtGui.QMessageBox.question(
                self,"Borrar",
                "Deseas borrar esta marca?",
                QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No);
            
            if self.resp == QtGui.QMessageBox.Yes:
                marca = data.index(
                    index.row(), 0, QtCore.QModelIndex()).data()
                if (db_marcas.borrar(marca)):
                    self.load_data()
                    msgBox = QtGui.QMessageBox()
                    msgBox.setText(u"EL registro fue eliminado.")
                    msgBox.exec_()
                    return True
                else:
                    self.ui.errorMessageDialog = QtGui.QErrorMessage(self)
                    self.ui.errorMessageDialog.showMessage(
                        u"Error al eliminar el registro")
                    return False
                self.load_data()

    def agregar(self):
        """
        Agrega/edita una marca. Llama al formulario correspondiente
        """
        self.ui.form = FormMarca(self) ##
        self.ui.form.accepted.connect(self.load_data)
        #self.ui.form.rejected.connect(self.load_data)
        self.ui.form.show()

        
    def edit(self):
        """
        Función obtiene el alumno seleccionado en la grilla
        para poner sus datos en el formulario para su edición
        """
        data = self.ui.tabla_marcas.model()
        index = self.ui.tabla_marcas.currentIndex()
        if index.row() == -1:  # No se ha seleccionado una fila
            self.errorMessageDialog = QtGui.QErrorMessage(self)
            self.errorMessageDialog.showMessage(u"Debe seleccionar una fila")
            return False
        else:
            nom_marca = data.index(index.row(), 0, QtCore.QModelIndex()).data()
            self.ui.form = FormMarca(self, nom_marca)
            self.ui.form.accepted.connect(self.load_data)
            self.ui.form.show()
Пример #38
0
class MyForm(QtGui.QMainWindow):
	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.computeFunc)
		
	def computeFunc(self):
		# get IP
		try:
			s1 = int(self.ui.lineEdit_s1.text())
			s2 = int(self.ui.lineEdit_s2.text())
			s3 = int(self.ui.lineEdit_s3.text())
			s4 = int(self.ui.lineEdit_s4.text())
			
			if (self.validateFail(s1) or self.validateFail(s2) or self.validateFail(s3) or self.validateFail(s4)
				or int(s1) == 0 or int(s4) == 0):
				QtGui.QMessageBox.about(self, "Error", "Error in IP address!")
				
		except:
			QtGui.QMessageBox.about(self, "Error", "Empty IP address!")
		else:
			
		#get Mask
			#if short
			mode = None
			if str(self.ui.lineEdit_s5.text()) != '':
				mode = 's'
				sMask = str(self.ui.lineEdit_s5.text())
				if (int(sMask) > 32 or int(sMask) < 0):
					QtGui.QMessageBox.about(self, "Error", "Error in short mask!")
				mask = ''
				for i in range(int(sMask)):
					mask += '1'
				while len(mask) != 32:
					mask += '0'
					
				#print mask
				m1 = mask[:8]
				m2 = mask[8:16]
				m3 = mask[16:24]
				m4 = mask[24:32]			
			#if long
			elif (str(self.ui.lineEdit_m1.text()) != '' and str(self.ui.lineEdit_m2.text()) != ''
				and str(self.ui.lineEdit_m3.text()) != '' and str(self.ui.lineEdit_m4.text()) != ''):
				mode = 'l'
				lMask1 = int(self.ui.lineEdit_m1.text())
				lMask2 = int(self.ui.lineEdit_m2.text())
				lMask3 = int(self.ui.lineEdit_m3.text())
				lMask4 = int(self.ui.lineEdit_m4.text())
				#print "{0} {1} {2} {3}".format(lMask1, lMask2, lMask3, lMask4)
				UnitLen = self.validateLongMask(lMask1, lMask2, lMask3, lMask4)
				if UnitLen == -1:
					QtGui.QMessageBox.about(self, "Error", "Error in mask format!")
				else:
					if (lMask1 > 255 or lMask2 > 255 or lMask3 > 255 or lMask4 > 255 or
						lMask1 < 0 or lMask2 < 0 or lMask3 < 0 or lMask4 < 0):
						QtGui.QMessageBox.about(self, "Error", "Error in long mask!")
					else:
						m1 = str(self.make8bits(bin(lMask1)))
						m2 = str(self.make8bits(bin(lMask2)))
						m3 = str(self.make8bits(bin(lMask3)))
						m4 = str(self.make8bits(bin(lMask4)))
			#if empty
			else:
				QtGui.QMessageBox.about(self, "Error", "Empty mask!")
			
			if mode == 's' or mode == 'l':
				binIPDot = self.make8bits(bin(s1))+'.'+self.make8bits(str(bin(s2)))+'.'+\
					self.make8bits(str(bin(s3)))+'.'+self.make8bits(str(bin(s4)))
				self.ui.label_binIP.setText(binIPDot)
				self.ui.label_binIP2.setText(binIPDot)
			
				binMaskDot = m1+'.'+m2+'.'+m3+'.'+m4
				self.ui.label_binMask.setText(binMaskDot)
				self.ui.label_binMask2.setText(binMaskDot)
					
				if mode == 's':
					self.ui.lineEdit_m1.setText(str(int(m1, 2)))
					self.ui.lineEdit_m2.setText(str(int(m2, 2)))
					self.ui.lineEdit_m3.setText(str(int(m3, 2)))
					self.ui.lineEdit_m4.setText(str(int(m4, 2)))
				elif mode == 'l':
					if UnitLen >= 0:
						self.ui.lineEdit_s5.setText(str(UnitLen))
					
			#calculations
				#netAddr		
				netAddrStrBin = str(self.make8bits(bin(s1 & int(m1, 2))))+'.'+str(self.make8bits(bin(s2 & int(m2, 2))))+\
					'.'+str(self.make8bits(bin(s3 & int(m3, 2))))+'.'+str(self.make8bits(bin(s4 & int(m4, 2))))
				netAddrStr = str(s1 & int(m1, 2))+'.'+str(s2 & int(m2, 2))+'.'+str(s3 & int(m3, 2))+'.'+\
					str(s4 & int(m4, 2))
				self.ui.label_netAddr.setText(netAddrStrBin)
				self.ui.label_netAddrDec.setText(netAddrStr)
				
				#broadcastAddr
				broadAddrBin = self.make8bits(bin(s1|self.rev(m1)))+\
							'.'+self.make8bits(bin(s2|self.rev(m2)))+\
							'.'+self.make8bits(bin(s3|self.rev(m3)))+\
							'.'+self.make8bits(bin(s4|self.rev(m4)))
				broadAddrDec = str(s1|self.rev(m1))+\
							'.'+str(s2|self.rev(m2))+\
							'.'+str(s3|self.rev(m3))+\
							'.'+str(s4|self.rev(m4))
				self.ui.label_brodAddr.setText(broadAddrBin)
				self.ui.label_brodAddrDec.setText(broadAddrDec)
			
				#nr of addr
				a = 256 - int(m1, 2)
				b = 256 - int(m2, 2)
				c = 256 - int(m3, 2)
				d = 256 - int(m4, 2)
				allAddr = a*b*c*d
				self.ui.label_allAddr.setText(str(allAddr))
				
				#nr of effective addr
				reservedAddr = a*b*c*2
				effectiveAddr = allAddr - reservedAddr
				if effectiveAddr < 0:
					effectiveAddr = 0
				self.ui.label_effAddr.setText(str(effectiveAddr))

				#class
				if ((s1 >= 0 and s1 <= 127) and\
					(s2 >= 0 and s2 <= 255) and\
					(s3 >= 0 and s3 <= 255) and\
					(s4 >= 0 and s4 <=255)):
					self.ui.label_netClass.setText('A')
				elif ((s1 >= 128 and s1 <= 191) and\
					(s2 >= 0 and s2 <= 255) and\
					(s3 >= 0 and s3 <= 255) and\
					(s4 >= 0 and s4 <=255)):
					self.ui.label_netClass.setText('B')
				elif ((s1 >= 192 and s1 <= 223) and\
					(s2 >= 0 and s2 <= 255) and\
					(s3 >= 0 and s3 <= 255) and\
					(s4 >= 0 and s4 <=255)):
					self.ui.label_netClass.setText('C')
				elif ((s1 >= 244 and s1 <= 239) and\
					(s2 >= 0 and s2 <= 255) and\
					(s3 >= 0 and s3 <= 255) and\
					(s4 >= 0 and s4 <=255)):
					self.ui.label_netClass.setText('D')
				else:
					self.ui.label_netClass.setText('not in class')	
	
	def validateLongMask(self, m1, m2, m3, m4):	
		str = self.make8bits(bin(m1)) + self.make8bits(bin(m2)) + self.make8bits(bin(m3)) \
			+ self.make8bits(bin(m4))
		error = 0
		pos = -1
		c = 0
		for i in range(32):
			if str[i] == '0':
				if c == 0 :
					pos = i
				c = pos
				while c < 32:
					if str[c] == '1':
						error = 1
					c = c + 1
		if error == 1:
			return -1
		else:
			return pos			
		
	# input - raw result after unpack
	# output - str with '0' added in front if needed to make 8 bits long
	def make8bits(self, string_val):
		string_val = str(string_val)
		string_val = string_val[2:]
		while len(string_val) < 8:
			string_val = '0' + string_val
		if len(string_val) > 8:
			string_val = string_val[:8]
		return string_val		
	
	# recersing bin str
	def rev(self, string_val):
		rev_str = ''
		for i in string_val:
			if i == '0':
				rev_str += '1'
			else:
				rev_str += '0'
		return int(rev_str, 2)
	
	# ip validation
	def validateFail(self, ip):
		if not ip:
			return 1
		try:
			if (int(ip) > 255 or int(ip) < 0):
				return 1
			else:
				return 0
		except:
			return 1
Пример #39
0
class DecrypterWindow(QtGui.QMainWindow):
    def __init__(self):
        """
        Initializes the DecrypterWindow
        """
        super(DecrypterWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # connect event handlers
        self.ui.calibrateButton.clicked.connect(self.calibrateButtonHandler)
        self.ui.importButton.clicked.connect(self.importButtonHandler)
        self.ui.exportButton.clicked.connect(self.exportButtonHandler)
        for c in string.lowercase:
            self.ui.edit[c].textEdited.connect(self.editModifiedHandler)

        # disable unavailable functionality
        self.ui.importButton.setDisabled(True)
        self.ui.exportButton.setDisabled(True)
        for c in string.lowercase:
            self.ui.edit[c].setDisabled(True)

        self.decrypter = None

        self.show()

        self.setFixedSize(self.size())

    def calibrateButtonHandler(self):
        """
        Imports a calibration file and uses it to set letter frequencies
        """
        # get path to calibration file
        filename = QtGui.QFileDialog.getOpenFileName(self)

        if len(filename) > 0:
            # pass path to new cypher_decriptor object
            self.decrypter = cypher_decriptor(filename)

            # enable import button
            self.ui.importButton.setDisabled(False)

    def importButtonHandler(self):
        """
        Imports a ciphertext file and tries to decrypt it
        """
        # get path to ciphertext
        filename = QtGui.QFileDialog.getOpenFileName(self)

        if len(filename) > 0:
            # pass path to self.decrypter.guess_initial_mappings
            self.decrypter.guess_initial_mappings(filename)

            # display ciphertext in upper pane
            self.ui.ciphertext.setPlainText(QtCore.QString(self.decrypter.cypher_text))

            # display mappings
            mappings = self.decrypter.get_mapping()
            for k, v in self.ui.edit.iteritems():
                v.setText(QtCore.QString(mappings[k]))

            # decrypt ciphertext
            plaintext = self.decrypter.decrypt()

            # show results in lower pane
            self.ui.plaintext.setPlainText(QtCore.QString(plaintext))

            # enable export button and editing mappings
            self.ui.exportButton.setDisabled(False)
            for c in string.lowercase:
                self.ui.edit[c].setDisabled(False)

    def exportButtonHandler(self):
        """
        Exports the putative plaintext as a text file
        """
        filename = QtGui.QFileDialog.getSaveFileName(self)
        with open(filename, 'w') as f:
            f.write(self.decrypter.decrypt())

    def editModifiedHandler(self):
        """
        Updates the mappings and re-decrypts the ciphertext every time mappings are modified
        """
        mappings = { c: str(self.ui.edit[c].text()) for c in string.lowercase }
        self.decrypter.set_mapping(mappings)
        plaintext = self.decrypter.decrypt()
        self.ui.plaintext.setPlainText(plaintext)
Пример #40
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        logger.debug('Begin the program')
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui_set = Set(self.ui)
        self.images = [None, None]
        self.slider_vals = [[0, 0], [0, 0]]

        ############## Connections #################################
        logger.debug('Connections')
        self.ui.add_btn.clicked.connect(self.add_img)
        self.ui.combo_mix.currentIndexChanged.connect(
            lambda index: self.set_sliders(index))
        for i in range(len(self.ui_set.combo_imgs)):
            self.connect_combo_imgs(i)
        for i in self.ui_set.combo_comps.keys():
            self.connect_combo_comps(i)
        for i in range(len(self.ui_set.sliders)):
            self.ui_set.sliders[i].valueChanged.connect(self.mix)
        for i in range(len(self.ui_set.checkboxs)):
            self.ui_set.checkboxs[i].clicked.connect(self.mix)

    def connect_combo_imgs(self, i):
        self.ui_set.combo_imgs[i].currentIndexChanged.connect(
            lambda n: self.draw(i, n))

    def draw(self, img_index, attr_index):
        logger.debug('choosing {} of image{}'.format(
            self.ui_set.combo_imgs[img_index].currentText(), img_index + 1))
        if attr_index == 0:
            logger.debug('Drawing Magnitude of image{}'.format(img_index + 1))
            self.draw_on(img_index + 2,
                         20 * np.log10(self.images[img_index].attrs[0]))
        else:
            logger.debug('Drawing {} of image{}'.format(
                self.ui_set.combo_imgs[img_index].currentText(),
                img_index + 1))
            self.draw_on(img_index + 2,
                         self.images[img_index].attrs[attr_index])

    def connect_combo_comps(self, i):
        if i == 1:
            self.ui_set.combo_comps[1][1].currentIndexChanged.connect(
                lambda n: self.combine(n, 2))
            self.ui_set.combo_comps[1][0].currentIndexChanged.connect(self.mix)
        if i == 2:
            self.ui_set.combo_comps[2][1].currentIndexChanged.connect(
                lambda n: self.combine(n, 1))
            self.ui_set.combo_comps[2][0].currentIndexChanged.connect(self.mix)

    def combine(self, current_index, index_another_combo):
        logger.debug('Handling Component combobox')
        if current_index == 0:
            self.ui_set.combo_comps[index_another_combo][1].setCurrentIndex(1)
            self.ui_set.enable_checkboxs(True)
        if current_index == 1:
            self.ui_set.combo_comps[index_another_combo][1].setCurrentIndex(0)
            self.ui_set.enable_checkboxs(True)
        if current_index == 2:
            self.ui_set.combo_comps[index_another_combo][1].setCurrentIndex(3)
            self.ui_set.enable_checkboxs(False)
        if current_index == 3:
            self.ui_set.combo_comps[index_another_combo][1].setCurrentIndex(2)
            self.ui_set.enable_checkboxs(False)
        self.mix()

    def set_sliders(
        self, current_index
    ):  # for keep track of sliders of the user change form output1 to output2
        logger.debug('OutPut Changed')
        logger.debug('Drawing On Output{}'.format(current_index))
        logger.debug('getting the previous values of sliders')
        for i in range(len(self.ui_set.sliders)):
            self.ui_set.sliders[i].blockSignals(True)
            self.ui_set.sliders[i].setValue(self.slider_vals[current_index][i])
            self.ui_set.sliders[i].setValue(self.slider_vals[current_index][i])
            self.ui_set.sliders[i].blockSignals(False)
        self.mix()

    def draw_on(self, plot_index, data):
        logger.debug('Draw')
        self.ui_set.plotItems[plot_index].clear()
        img = pg.ImageItem()
        self.ui_set.plotItems[plot_index].addItem(img)
        self.ui_set.plotItems[plot_index].setXRange(min=0,
                                                    max=data.shape[0],
                                                    padding=0)
        self.ui_set.plotItems[plot_index].setYRange(min=0,
                                                    max=data.shape[1],
                                                    padding=0)
        img.setImage(data.T)
        self.ui_set.plotItems[plot_index].autoRange(padding=0)

    def is_there_image(self):
        logger.debug('Checking if there is image !')
        for i in range(len(self.images)):
            if self.images[i] is not None:
                return True
        return False

    def add_img(self):
        logger.debug('Add Image button clicked ')
        current_img = self.ui.combo_add.currentIndex()
        filename = QFileDialog(self).getOpenFileName()
        path = filename[0]
        if path != '':
            if not self.is_there_image():
                self.ui_set.set_combo_img(current_img)
            image = ImageModel(url=path)
            if self.check_size(image, current_img):
                logger.debug('Opening the image')
                self.images[current_img] = image
                self.draw_on(current_img, self.images[current_img].img_data)
                self.draw_on(current_img + 2,
                             20 * np.log10(self.images[current_img].attrs[0]))
                self.ui_set.enable_sliders()
                self.ui.combo_mix.setEnabled(True)
                self.mix()
            else:
                logger.debug('Error the Images must be the same size')
                msg = QMessageBox()
                msg.setWindowTitle('ERROR')
                msg.setText('Pls add images of the same size')
                msg.setIcon(QMessageBox.Critical)
                msg.exec_()

    def check_size(self, image, current_index):
        logger.debug('check the size of image ')
        if current_index == 0:
            try:
                if self.images[1].img_data.shape == image.img_data.shape:
                    return True
                else:
                    return False
            except:  # There is one image only
                return True
        else:
            try:
                if self.images[0].img_data.shape == image.img_data.shape:
                    return True
                else:
                    return False
            except:  # There is one image only
                return True

    def mix(self):
        logger.debug('Getting values to mix')
        current_output = self.ui.combo_mix.currentIndex()
        comp_imgs_index = [
            self.ui_set.combo_comps[i][0].currentIndex()
            for i in self.ui_set.combo_comps.keys()
        ]  # image index for each component
        comp_attrs_index = [
            self.ui_set.combo_comps[i][1].currentIndex()
            for i in self.ui_set.combo_comps.keys()
        ]  # attribute index for each component
        vals = np.array([
            self.ui_set.sliders[i].value() / 100
            for i in range(len(self.ui_set.sliders))
        ])  # value for each slider

        for i in self.ui_set.combo_comps.keys():
            logger.debug('choosing {} of {} of component{}'.format(
                self.ui_set.combo_comps[i][1].currentText(),
                self.ui_set.combo_comps[i][0].currentText(), i))

        logger.debug('slider_val1 = {}, slider_val2 = {}'.format(
            vals[0], vals[1]))

        for i in range(len(self.ui_set.slider_vals)):
            self.ui_set.slider_vals[i].setText('{}%'.format(int(vals[i] *
                                                                100)))

        self.slider_vals[current_output] = vals * 100

        # Checking the presence of images
        logger.debug('Checking the presence of images')
        for i in comp_imgs_index:
            if self.images[i] is None:
                logger.debug('There is no image{} to be mixed '.format(i + 1))
                msg = QMessageBox()
                msg.setWindowTitle('ERROR')
                msg.setText('Pls add image {}'.format(i + 1))
                msg.setIcon(QMessageBox.Critical)
                msg.exec_()
                if i == 0:
                    self.ui_set.set_combo_img(1)
                else:
                    self.ui_set.set_combo_img(0)
                return
        logger.debug('Mix')
        if comp_imgs_index[0] != comp_imgs_index[1]:  # Two Different images
            if comp_attrs_index[0] == 0:
                if self.ui_set.checkboxs[0].isChecked(
                ) and self.ui_set.checkboxs[1].isChecked():
                    logger.debug('Uniform Magnitude, Uniform Phase')
                    mix = self.images[comp_imgs_index[0]].mix(
                        self.images[comp_imgs_index[1]], vals[0], vals[1],
                        Modes.uniform_mag_phase)
                elif self.ui_set.checkboxs[0].isChecked():
                    logger.debug('Uniform Magnitude')
                    mix = self.images[comp_imgs_index[0]].mix(
                        self.images[comp_imgs_index[1]], vals[0], vals[1],
                        Modes.uniform_mag)
                elif self.ui_set.checkboxs[1].isChecked():
                    logger.debug('Uniform Phase')
                    mix = self.images[comp_imgs_index[0]].mix(
                        self.images[comp_imgs_index[1]], vals[0], vals[1],
                        Modes.uniform_phase)
                else:
                    mix = self.images[comp_imgs_index[0]].mix(
                        self.images[comp_imgs_index[1]], vals[0], vals[1],
                        Modes.magnitudeAndPhase)
            elif comp_attrs_index[0] == 1:
                if self.ui_set.checkboxs[0].isChecked(
                ) and self.ui_set.checkboxs[1].isChecked():
                    mix = self.images[comp_imgs_index[0]].mix(
                        self.images[comp_imgs_index[1]], vals[0], vals[1],
                        Modes.uniform_mag_phase)
                elif self.ui_set.checkboxs[0].isChecked():
                    mix = self.images[comp_imgs_index[1]].mix(
                        self.images[comp_imgs_index[0]], vals[1], vals[0],
                        Modes.uniform_phase)
                elif self.ui_set.checkboxs[1].isChecked():
                    mix = self.images[comp_imgs_index[1]].mix(
                        self.images[comp_imgs_index[0]], vals[1], vals[0],
                        Modes.uniform_mag)
                else:
                    mix = self.images[comp_imgs_index[1]].mix(
                        self.images[comp_imgs_index[0]], vals[1], vals[0],
                        Modes.magnitudeAndPhase)
            elif comp_attrs_index[0] == 2:
                mix = self.images[comp_imgs_index[0]].mix(
                    self.images[comp_imgs_index[1]], vals[0], vals[1],
                    Modes.realAndImaginary)
            else:
                mix = self.images[comp_imgs_index[1]].mix(
                    self.images[comp_imgs_index[0]], vals[1], vals[0],
                    Modes.realAndImaginary)
        else:  # There is only one image
            if comp_attrs_index[0] == 0:
                if self.ui_set.checkboxs[0].isChecked(
                ) and self.ui_set.checkboxs[1].isChecked():
                    mix = self.images[comp_imgs_index[0]].mix(
                        None, vals[0], vals[1], Modes.uniform_mag_phase)
                elif self.ui_set.checkboxs[0].isChecked():
                    mix = self.images[comp_imgs_index[0]].mix(
                        None, vals[0], vals[1], Modes.uniform_mag)
                elif self.ui_set.checkboxs[1].isChecked():
                    mix = self.images[comp_imgs_index[0]].mix(
                        None, vals[0], vals[1], Modes.uniform_phase)
                else:
                    mix = self.images[comp_imgs_index[0]].mix(
                        None, vals[0], vals[1], Modes.magnitudeAndPhase)
            elif comp_attrs_index[0] == 1:
                if self.ui_set.checkboxs[0].isChecked(
                ) and self.ui_set.checkboxs[1].isChecked():
                    mix = self.images[comp_imgs_index[0]].mix(
                        None, vals[0], vals[1], Modes.uniform_mag_phase)
                elif self.ui_set.checkboxs[0].isChecked():
                    mix = self.images[comp_imgs_index[1]].mix(
                        None, vals[1], vals[0], Modes.uniform_phase)
                elif self.ui_set.checkboxs[1].isChecked():
                    mix = self.images[comp_imgs_index[1]].mix(
                        None, vals[1], vals[0], Modes.uniform_mag)
                else:
                    mix = self.images[comp_imgs_index[1]].mix(
                        None, vals[1], vals[0], Modes.magnitudeAndPhase)
            elif comp_attrs_index[0] == 2:
                mix = self.images[comp_imgs_index[0]].mix(
                    None, vals[0], vals[1], Modes.realAndImaginary)
            else:
                mix = self.images[comp_imgs_index[1]].mix(
                    None, vals[1], vals[0], Modes.realAndImaginary)

        self.draw_on(current_output + 4, mix)
Пример #41
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, N):
        super(MainWindow, self).__init__()

        # This is always the same
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # no resizing
        self.setFixedSize(self.width(), self.height())

        
        from sph_demo import SPHDemo
        enable_advanced_rendering = not '--disable-advanced-rendering' in sys.argv
        self.sph_demo = SPHDemo(N, size=(self.ui.fluid.width(), self.ui.fluid.height()), enable_advanced_rendering=enable_advanced_rendering)

        # ui.fluid is the FluidWidget QGLWidget-widget.
        self.ui.fluid.init(self.sph_demo)
        self.ui.fluid.gl_initialized.connect(self.update_gui_from_params)

        self.setup_signals()
        statusBarInfo = QtGui.QLabel()
        statusBarInfo.setText("%s particles, initial density: %s, mass: %.02f, gas constant k: %s, timestep: %.05f" % (
                self.sph_demo.fluid_simulator.N,
                self.sph_demo.fluid_simulator.density0, 
                self.sph_demo.fluid_simulator.mass,
                self.sph_demo.fluid_simulator.k,
                self.sph_demo.fluid_simulator.dt
                ))

        self.statusBarFps = QtGui.QLabel()
        self.statusBar().addPermanentWidget(self.statusBarFps)
        self.statusBar().addWidget(statusBarInfo)

        if not self.sph_demo.enable_advanced_rendering:
            # disable ui elements dealing with advanced rendering
            self.ui.rm_points.setChecked(True)
            for el in (self.ui.rm_balls, 
                       self.ui.rm_advanced, 
                       self.ui.advanced,):
                el.setEnabled(False)

    def setup_signals(self):
        """
        Set up callbacks for the widgets.
        """

        ui = self.ui

        self.fps_timer = QtCore.QTimer()
        def callback():
            self.statusBarFps.setText("%.2f fps" % self.sph_demo.fps)
        self.fps_timer.timeout.connect(callback)
        self.fps_timer.start(1000)

        def callback(p):
            self.sph_demo.params.paused = p
        ui.paused.toggled.connect(callback)

        if self.sph_demo.enable_advanced_rendering:
            #from fluid_rendering.fluid_renderer import FluidRenderer

            def callback(p):
                self.sph_demo.params.blur_thickness_map = p
            ui.blur_thickness_map.toggled.connect(callback)
            def callback(p):
                self.sph_demo.params.render_mean_curvature = p
            ui.render_mean_curvature.toggled.connect(callback)        

            def callback():
                self.sph_demo.params.render_mode = 0
            ui.rm_points.pressed.connect(callback)
            def callback():
                self.sph_demo.params.render_mode = 1
            ui.rm_balls.pressed.connect(callback)
            def callback():
                self.sph_demo.params.render_mode = 2
            ui.rm_advanced.pressed.connect(callback)
            ui.rm_advanced.toggled.connect(ui.advanced.setEnabled)

            def callback(n):
                self.sph_demo.params.smoothing_iterations = n
            ui.smoothing_iterations.valueChanged.connect(callback)

            def callback(n):
                self.sph_demo.params.smoothing_z_contrib = n
            ui.smoothing_z_contrib.valueChanged.connect(callback)

    def update_gui_from_params(self):
        params = self.sph_demo.params
        if not params.dirty:
            return
        
        ui = self.ui
        ui.paused.setOn(params.paused)
        
        if self.sph_demo.enable_advanced_rendering:
            from fluid_rendering.fluid_renderer import FluidRenderer

            ui.blur_thickness_map.setOn(params.blur_thickness_map)
            ui.render_mean_curvature.setOn(params.render_mean_curvature)

            { FluidRenderer.RENDERMODE_POINTS: ui.rm_points,
              FluidRenderer.RENDERMODE_BALLS: ui.rm_balls,
              FluidRenderer.RENDERMODE_ADVANCED: ui.rm_advanced }[params.render_mode].setChecked(True)

            ui.smoothing_iterations.setValue(params.smoothing_iterations)
            ui.smoothing_z_contrib.setValue(params.smoothing_z_contrib)

            ui.advanced.setEnabled(ui.rm_advanced.isChecked())

        params.dirty = False
           
    def keyPressEvent(self, event):
        """
        Handle keyboard shortcuts
        """
        key = event.key()
        params = self.sph_demo.params
        if key == QtCore.Qt.Key_R:
            self.sph_demo.fluid_simulator.set_positions()
        elif key == QtCore.Qt.Key_P:
            params.paused = not params.paused
        elif key == QtCore.Qt.Key_B:
            params.blur_thickness_map = not params.blur_thickness_map
        elif key == QtCore.Qt.Key_N:
            params.render_mode = (params.render_mode+1) % self.sph_demo.fluid_renderer.number_of_render_modes
        elif key == QtCore.Qt.Key_C:
            params.render_mean_curvature = not params.render_mean_curvature
        else:
            super(MainWindow, self).keyPressEvent(event)

        self.update_gui_from_params()
class Main(QtGui.QMainWindow):
    """
    Esta es una grilla
    """
    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.load_data()
        self.connect_signals()
        self.show()

    def connect_signals(self):
        self.ui.agregar_marca.clicked.connect(self.add)
        #self.ui.eliminar_marca.connect(self.delete)

    def add(self):
        self.ui.form = FormAlumno(self)
        self.ui.form.accepted.connect(self.load_data)
        self.ui.form.show()

    def load_data(self):
        """
        Función que carga la información de marcas en la grilla
        incluyendo la cantidad de modelos asociados a la marca
        """
        marcas = db_marcas.obtener_marcas()
        #Creamos el modelo asociado a la tabla
        self.data = QtGui.QStandardItemModel(len(marcas)+1, 3)
        self.data.setHorizontalHeaderItem(
            0, QtGui.QStandardItem(u"Nombre de Marca"))
        self.data.setHorizontalHeaderItem(
            1, QtGui.QStandardItem(u"País de Origen"))
        self.data.setHorizontalHeaderItem(
            2, QtGui.QStandardItem(u"Cantidad de Modelos"))

        for r, row in enumerate(marcas):
            index = self.data.index(r, 0, QtCore.QModelIndex())
            self.data.setData(index, row['Nombre de Marca'])
            index = self.data.index(r, 1, QtCore.QModelIndex())
            self.data.setData(index, row['País de Origen'])
            index = self.data.index(r, 2, QtCore.QModelIndex())
            self.data.setData(index, row['Cantidad de Modelos'])

        self.ui.tabla_marcas.setModel(self.data)

        # Para que las columnas 1 y 2 se estire o contraiga cuando
        # se cambia el tamaño de la pantalla
        self.ui.tabla_marcas.horizontalHeader().setResizeMode(
            0, self.ui.tabla_marcas.horizontalHeader().Stretch)
        self.ui.tabla_marcas.horizontalHeader().setResizeMode(
            1, self.ui.tabla_marcas.horizontalHeader().Stretch)

        self.ui.tabla_marcas.setColumnWidth(0, 100)
        self.ui.tabla_marcas.setColumnWidth(1, 210)
        self.ui.tabla_marcas.setColumnWidth(2, 210)

    def delete(self):
        """
        Función que intenta borrar un alumno de la base de datos e
        indica el resultado de la operación
        """

        # ANTES DE REALIZAR LA ACCIÓN SE DEBERÍA PREGUNTAR
        # AL USUARIO CONFIRMAR LA OPERACIÓN !!!!!!!!!!!!!!
        data = self.ui.tabla_marcas.model()
        index = self.ui.tabla_marcas.currentIndex()
        if index.row() == -1:  # No se ha seleccionado una fila
            self.errorMessageDialog = QtGui.QErrorMessage(self)
            self.errorMessageDialog.showMessage(u"Debe seleccionar una fila")
            return False
        else:
            if tkMessageBox.askyesno(
                "Borrar Marca", "Deseas borrar esta marca?"):
                marca = data.index(
                    index.row(), 0, QtCore.QModelIndex()).data()
                if (db_marcas.borrar(marca)):
                    self.load_data()
                    msgBox = QtGui.QMessageBox()
                    msgBox.setText(u"EL registro fue eliminado.")
                    msgBox.exec_()
                    return True
                else:
                    self.ui.errorMessageDialog = QtGui.QErrorMessage(self)
                    self.ui.errorMessageDialog.showMessage(
                        u"Error al eliminar el registro")
                    return False

    ########### rehacer..
    def edit(self):
        """
        Función obtiene el alumno seleccionado en la grilla
        para poner sus datos en el formulario para su edición
        
        data = self.ui.tabla_marcas.model()
        index = self.ui.tabla_marcas.currentIndex()
        if index.row() == -1:  # No se ha seleccionado una fila
            self.errorMessageDialog = QtGui.QErrorMessage(self)
            self.errorMessageDialog.showMessage(u"Debe seleccionar una fila")
            return False
        else:
            rut = data.index(index.row(), 0, QtCore.QModelIndex()).data()
            self.ui.form = FormAlumno(self, rut)
            self.ui.form.accepted.connect(self.load_data)
            self.ui.form.show()
        """
        pass
Пример #43
0
class MainWindow(QMainWindow):
    '''First application window the user sees'''

    command = pyqtSignal(str, str) # (tag, payload)
    networkUpdate = pyqtSignal(str, int) # (host, port)

    def __init__(self, pod):
        super().__init__()
        MainWindow.console = ConsoleWidget(
            namespace = {
                'pod': pod,
                'win': self,
            },
            text='You can use this window to enter Python commands.')
        MainWindow.console.setWindowTitle('Python interaction')
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
        self._ui.startButton.clicked.connect(pod.begin)
        self._ui.submitButton.clicked.connect(self.submitCommand)
        pod.connected.connect(self.enable)
        self._ui.actionSettings.triggered.connect(self.networkDialog)
        self._ui.actionReconnect.triggered.connect(pod.begin)
        self._ui.actionConsoleOpen.triggered.connect(self.openConsole)
        pod.add_listener('*', self.appendNetworkLog)
        pod.add_listener('v', self.updateVelocityLCD)
        pod.add_listener('v', self._ui.velocityPlot.datum)
        pod.add_listener('h', self.updateHeightLCD)
        pod.add_listener('h', self._ui.heightPlot.datum)
        pod.add_listener('d', self.updateDistanceLCD)
        pod.add_listener('d', self._ui.distancePlot.datum)
        self.command.connect(pod)
        self.networkUpdate.connect(pod.try_connect)
        self.timer = QTimer()
        self.timer.timeout.connect(self._ui.velocityPlot.update)
        self.timer.timeout.connect(self._ui.heightPlot.update)
        self.timer.timeout.connect(self._ui.distancePlot.update)
        self.timer.start(_1s)

    @pyqtSlot()
    def enable(self):
        self._ui.startButton.setDisabled(True)
        self._ui.submitButton.setDisabled(False)

    @pyqtSlot(str)
    def updateVelocityLCD(self, new):
        self._ui.velocityLCD.display(new)

    @pyqtSlot(str)
    def updateHeightLCD(self, new):
        self._ui.heightLCD.display(new)

    @pyqtSlot(str)
    def updateDistanceLCD(self, new):
        self._ui.distanceLCD.display(new)

    def submitCommand(self):
        tag = self._ui.tagLineEdit.text()
        body = self._ui.bodyLineEdit.text()
        if tag == '' or body == '':
            return
        self.command.emit(tag, body)

    def sendStartMessage(self):
        return 'start'

    def openConsole(self):
        '''Open a console for Python interaction'''
        MainWindow.console.show()

    def networkDialog(self):
        '''Open a window for changing network settings'''
        dialog = NetworkDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.networkUpdate.emit(dialog.host, dialog.port)

    @pyqtSlot(str)
    def appendNetworkLog(self, text):
        self._ui.networkLog.appendPlainText(text)
Пример #44
0
class M2Todo(QApplication):
    def __init__(self, **args):
        super(QApplication, self).__init__([])

        self.setApplicationName(NAME)
        self.setApplicationVersion(VERSION)
        self.setOrganizationName(COMPANY)
        self.setOrganizationDomain(DOMAIN)

        self.settings = QSettings()

        self._mw = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self._mw)

        self.ui.actionOpen_MM.triggered.connect(self.openMM)
        self.ui.actionOpen_M2T.triggered.connect(self.openM2T)
        self.ui.actionMerge.triggered.connect(self.merge)
        self.ui.actionSave.triggered.connect(self.save)
        self.ui.actionSave_As.triggered.connect(self.saveAs)
        self.ui.actionAbout_M2Todo.triggered.connect(self.about)
        self.ui.actionHelp.triggered.connect(self.help)
        self.ui.actionFreeMind.triggered.connect(self.launchFreemind)

        self.ui.treeWidget.itemChanged.connect(self.itemStriker)

        self._openPath = None
        self._savePath = None

        self.ui.actionMerge.setDisabled(True)

        self._mw.show()

        lastFile = str(self.settings.value("session/lastOpenFile", None).toString())
        if lastFile:
            fType = self.settings.value("session/lastOpenFileType")
            self._openPath = {"type": fType, "path": lastFile}
            if fType == "m2t":
                self._parseM2T(lastFile)
            elif fType == "mm":
                self._parseMM(lastFile)
            self._mw.statusBar().showMessage(lastFile)
            self._mw.setWindowTitle(basename(str(lastFile)) + " - M2Todo")
            self.ui.actionMerge.setDisabled(False)
        # not debug!! here because it's always the last thing to do
        # even if/when we have a "last open file" option
        self.ui.actionSave.setDisabled(True)

    @pyqtSlot()
    def launchFreemind(self):
        try:
            subprocess.Popen(["freemind"])
        except OSError:
            QMessageBox.critical(
                self._mw,
                "Freemind not found",
                "FreeMind was not found. If you installed it, add the " + "installation directory to your PATH.",
            )

    def saveM2TState(self, *args):
        print args
        """ save details of last open file """
        if self._openPath is not None:

            self.settings.setValue("session/lastOpenFile", self._openPath["path"])
            self.settings.setValue("session/lastOpenFileType", self._openPath["type"])

    @pyqtSlot("QTreeWidgetItem*", int)
    def itemStriker(self, item, column, *args):
        """ modify widgets depending on check state """

        # re-enable the save button
        self.ui.actionSave.setDisabled(False)

        # strike / unstrike
        state = item.checkState(0)
        if state == Qt.Checked:
            strikeItem(item, True)
        elif state == Qt.Unchecked:
            strikeItem(item, False)

        # recurse down
        if item.childCount() > 0:
            for i in xrange(0, item.childCount()):
                item.child(i).setCheckState(0, state)

    @pyqtSlot(bool)
    def openMM(self, *args):
        """ open a FreeMind file """

        mmPath = QFileDialog.getOpenFileName(
            self.ui.menubar, "Select MM file", expanduser("~"), "FreeMind files (*.mm);;All Files(*.*)"
        )
        if not mmPath.isEmpty():
            self.ui.treeWidget.clear()
            self._openPath = {"type": "mm", "path": str(mmPath)}
            self._savePath = None
            self._parseMM(mmPath)
            self.ui.actionSave.setDisabled(False)
            self._mw.statusBar().showMessage(mmPath)
            self._mw.setWindowTitle(basename(str(mmPath)) + " - M2Todo")
            self.saveM2TState()

    @pyqtSlot(bool)
    def openM2T(self, *args):
        """ Open a M2Todo file """

        m2tPath = QFileDialog.getOpenFileName(
            self.ui.menubar, "Select M2T file", expanduser("~"), "M2T files (*.m2t);;All Files(*.*)"
        )
        if not m2tPath.isEmpty():
            self.ui.treeWidget.clear()
            self._openPath = {"type": "m2t", "path": str(m2tPath)}
            self._savePath = str(m2tPath)
            self._parseM2T(m2tPath)
            self.ui.actionSave.setDisabled(False)
            self._mw.statusBar().showMessage(m2tPath)
            self._mw.setWindowTitle(basename(str(m2tPath)) + " - M2Todo")
            self.saveM2TState()

    @pyqtSlot(bool)
    def save(self, *args):
        """ Save a M2Todo file """

        if self._openPath is None:
            return

        if self._savePath is None:
            opened = self._openPath["path"]
            if not opened.endswith(".m2t"):
                orig, ext = splitext(opened)
                opened = orig + ".m2t"

            savePath = QFileDialog.getSaveFileName(self.ui.menubar, "Save", opened, "M2T file (*.m2t)")
            if savePath.isEmpty():
                return  # user cancelled action
            self._savePath = savePath

        self._writeM2T(self._savePath)
        self.ui.actionSave.setDisabled(True)
        self._mw.statusBar().showMessage(self._savePath)
        self._mw.setWindowTitle(basename(str(self._savePath)) + " - M2Todo")
        self.saveM2TState()

    @pyqtSlot(bool)
    def saveAs(self, *args):
        """ Save a M2Todo file with new name"""

        savePath = QFileDialog.getSaveFileName(self.ui.menubar, "Save As", expanduser("~"), "M2T file (*.m2t)")

        if not savePath.isEmpty():
            self._savePath = savePath
            self._writeM2T(self._savePath)
            self.ui.actionSave.setDisabled(True)
            self._mw.statusBar().showMessage(self._savePath)
            self._mw.setWindowTitle(basename(str(self._savePath)) + " - M2Todo")
            self.saveM2TState()

    ### Parsing / writing utils ###

    def _writeM2T(self, path):
        # build our dom
        root = etree.Element("m2t")

        for i in xrange(0, self.ui.treeWidget.topLevelItemCount()):
            self._buildNodeFromItem(self.ui.treeWidget.topLevelItem(i), root)

        # first node has no checked state
        del root.find(".//node").attrib["m2t_checked"]
        etree.ElementTree(root).write(path, "utf-8")

    def _buildNodeFromItem(self, item, parentNode):
        el = etree.SubElement(
            parentNode,
            "node",
            {
                "ID": str(item.data(0, Qt.UserRole).toString()),
                "TEXT": item.text(0),
                "m2t_checked": str(int(item.checkState(0))),
            },
        )

        if item.childCount() > 0:
            for i in xrange(0, item.childCount()):
                self._buildNodeFromItem(item.child(i), el)

    def _parseMM(self, mmPath):
        doc = parse(str(mmPath))
        self._parseNode(doc.firstChild)
        doc.unlink()

    def _parseM2T(self, m2tPath):
        doc = parse(str(m2tPath))
        self._parseNode(doc.firstChild)
        doc.unlink()

    def _parseNode(self, node, parentItem=None):
        # ignore everything that is not a node
        item = None
        if node.nodeName == "node":
            if parentItem is not None:
                item = QTreeWidgetItem(parentItem)
            else:
                item = QTreeWidgetItem(self.ui.treeWidget)

            if node.hasAttribute("TEXT"):
                item.setText(0, node.attributes["TEXT"].value)
            else:
                # html nodes
                bodyNodes = node.getElementsByTagName("html")
                if len(bodyNodes) > 0:
                    text = stripTags(bodyNodes[0].toxml()).strip()
                    item.setText(0, text)

            if node.hasAttribute("m2t_checked"):
                checked = int(node.attributes["m2t_checked"].value)
                item.setCheckState(0, checked)
            elif parentItem is not None:
                item.setCheckState(0, 0)  # unchecked

            # expand unchecked nodes only
            if item.checkState(0) == Qt.Checked:
                item.setExpanded(False)
            else:
                item.setExpanded(True)

            # save the ID
            item.setData(0, Qt.UserRole, str(node.attributes["ID"].value))

        if node.hasChildNodes():
            for n in node.childNodes:
                self._parseNode(n, item)

    @pyqtSlot()
    def merge(self):
        """ merge current view with a previously-saved M2T """

        # first we get the old m2t path
        oldPath = QFileDialog.getOpenFileName(
            self.ui.menubar, "Select M2T file to merge", expanduser("~"), "M2T files (*.m2t);;All Files(*.*)"
        )
        if oldPath.isEmpty():
            return  # cancel action

        # then we save a copy of the current view, so that we have a m2t
        tempFile = QTemporaryFile()
        tempFile.setAutoRemove(False)
        tempFile.open()
        tempFile.close()
        self._writeM2T(tempFile.fileName())

        # then we merge
        old = etree.parse(str(oldPath))
        new = etree.parse(str(tempFile.fileName()))
        oldMap = {}

        # get statuses in the old file
        for node in old.findall(".//node"):
            if node.attrib.has_key("m2t_checked"):
                checked = node.attrib["m2t_checked"]
                oldMap[node.attrib["ID"]] = checked

        # set statuses in new file
        for node in new.findall(".//node"):
            nodeId = node.attrib["ID"]
            if oldMap.has_key(nodeId):
                node.attrib["m2t_checked"] = oldMap[nodeId]

        # write down the result
        new.write(tempFile.fileName(), "utf-8")

        # reload the view
        self.ui.treeWidget.clear()
        self._parseM2T(str(tempFile.fileName()))
        self.ui.actionSave.setDisabled(False)

        tempFile.remove()

    def printTree(self):
        pixmap = QPixmap.grabWidget(self.ui.treeWidget)

        printer = QPrinter()
        printDlg = QPrintDialog(self, printer, self._mw)
        if printDlg.exec_() == QDialog.Accepted:
            # print
            pass

    @pyqtSlot()
    def about(self):
        template = (
            "%(name)s v. %(version)s \n\n%(name)s is copyright @ "
            + "%(year)s %(author)s\n\n"
            + "This program is free software; you can redistribute it and/or "
            + "modify it under the terms of the GNU General Public License "
            + "as published by the Free Software Foundation; either version "
            + "3 of the License, or any later version.\n\n"
            + "This program is distributed in the hope that it will be "
            + "useful, but WITHOUT ANY WARRANTY; without even the implied "
            + "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR "
            + "PURPOSE. See the GNU General Public License for more details."
            + "\n\nYou should have received a copy of the GNU General Public "
            + "License along with this program; if not, write to the Free "
            + "Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, "
            + "MA  02111-1307, USA."
        )

        QMessageBox.about(
            self._mw,
            "About %(name)s" % NAME,
            template % {"name": NAME, "version": VERSION, "year": date.today().year, "author": AUTHOR},
        )

    @pyqtSlot()
    def help(self):
        QMessageBox.information(
            self._mw,
            "Help",
            """Once you open a FreeMind ".mm" file with File->Open MM, """
            + """it will be converted to the "M2T" format.
The original file will be preserved.

You can then mark actions as "done" by ticking their boxes, and the status """
            + """will be saved in the M2T file once you click on File->Save or File->Save As.
You can open any M2T file with File->Open M2T. By default, the program will"""
            + """ reopen the last open file, be it MM or M2T.

If you modify your original MM, you can merge the changes in this way:
1 - Open the new MM (File->Open MM)
2 - Click on Tools->Merge, then select the M2T file you want to merge (i.e."""
            + """where you saved your progress)
3 - the view will now reflect the merged state, and you can save it as a """
            + """new M2T or overwrite the old M2T.

Tools->FreeMind launches FreeMind in a separate window.""",
        )
class Gui(QtGui.QMainWindow):
    """
    Main GUI Class
    It contains the main function and interfaces between
    the GUI and functions
    """
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        """ Main Variables Using Other Classes"""
        self.rex = Rexarm()
        self.video = Video(cv2.VideoCapture(0))

        """ Other Variables """
        self.last_click = np.float32([0,0])

        """ Set GUI to track mouse """
        QtGui.QWidget.setMouseTracking(self,True)

        """
        Video Function
        Creates a timer and calls play() function
        according to the given time delay (27mm)
        """
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)

        """
        LCM Arm Feedback
        Creates a timer to call LCM handler continuously
        No delay implemented. Reads all time
        """
        self._timer2 = QtCore.QTimer(self)
        self._timer2.timeout.connect(self.rex.get_feedback)
        self._timer2.start()

        """
        Connect Sliders to Function
        TO DO: CONNECT THE OTHER 5 SLIDERS IMPLEMENTED IN THE GUI
        """
        self.ui.sldrBase.valueChanged.connect(self.slider_change)
        self.ui.sldrShoulder.valueChanged.connect(self.slider_change)
        self.ui.sldrElbow.valueChanged.connect(self.slider_change)
        self.ui.sldrWrist.valueChanged.connect(self.slider_change)
        self.ui.sldrMaxTorque.valueChanged.connect(self.slider_change)
        self.ui.sldrSpeed.valueChanged.connect(self.slider_change)

        """ Commands the arm as the arm initialize to 0,0,0,0 angles """
        self.slider_change()

        """ Connect Buttons to Functions """
        self.ui.btnLoadCameraCal.clicked.connect(self.load_camera_cal)
        self.ui.btnPerfAffineCal.clicked.connect(self.affine_cal)
        self.ui.btnTeachRepeat.clicked.connect(self.tr_initialize)
        self.ui.btnAddWaypoint.clicked.connect(self.tr_add_waypoint)
        self.ui.btnSmoothPath.clicked.connect(self.tr_smooth_path)
        self.ui.btnPlayback.clicked.connect(self.tr_playback)
        self.ui.btnDefineTemplate.clicked.connect(self.def_template)
        self.ui.btnLocateTargets.clicked.connect(self.template_match)
        self.ui.btnExecutePath.clicked.connect(self.exec_path)

        self.ui.path_start_time = None
        self.executed_path = []

        self.get_template = 0
        self.templat_point = None
        self.donuts = []


    def play(self):
        """
        Play Funtion
        Continuously called by GUI
        """

        """ Renders the Video Frame """
        try:
            self.video.captureNextFrame()
            self.ui.videoFrame.setPixmap(
                self.video.convertFrame())
            self.ui.videoFrame.setScaledContents(True)
        except TypeError:
            print "No frame"

        """
        Update GUI Joint Coordinates Labels
        TO DO: include the other slider labels
        """
        self.ui.rdoutBaseJC.setText(str(self.rex.joint_angles_fb[0]*R2D))
        self.ui.rdoutShoulderJC.setText(str(self.rex.joint_angles_fb[1]*R2D))
        self.ui.rdoutElbowJC.setText(str(self.rex.joint_angles_fb[2]*R2D))
        self.ui.rdoutWristJC.setText(str(self.rex.joint_angles_fb[3]*R2D))

        t = [self.rex.joint_angles_fb[0],
             self.rex.joint_angles_fb[1] - 90.0 * D2R,
             self.rex.joint_angles_fb[2],
             self.rex.joint_angles_fb[3]]

        a = [0.0, 100.0, 100.0, 108.0]

        d = [116.0, 0.0, 0.0, 0.0]
        al = [-90.0 * D2R, 0.0 * D2R, 0.0 * D2R, 0.0 * D2R]

        dh_table = [t,a,d,al]
        (x, y, z, phi) = self.rex.rexarm_FK(dh_table, 3)
        self.ui.rdoutX.setText(str(x))
        self.ui.rdoutY.setText(str(y))
        self.ui.rdoutZ.setText(str(z))
        self.ui.rdoutT.setText(str(phi*R2D))

        # res = self.rex.rexarm_IK((0.0,-275.0,80.0,0.0), 1)
        # if res != None:
        #     self.rex.joint_angles[0] = res[0]
        #     self.rex.joint_angles[1] = res[1]
        #     self.rex.joint_angles[2] = res[2]
        #     self.rex.joint_angles[3] = res[3]
        #     self.rex.cmd_publish()

        """
        Mouse position presentation in GUI
        TO DO: after getting affine calibration make the apprriate label
        to present the value of mouse position in world coordinates
        """
        x = QtGui.QWidget.mapFromGlobal(self,QtGui.QCursor.pos()).x()
        y = QtGui.QWidget.mapFromGlobal(self,QtGui.QCursor.pos()).y()
        if ((x < MIN_X) or (x > MAX_X) or (y < MIN_Y) or (y > MAX_Y)):
            self.ui.rdoutMousePixels.setText("(-,-)")
            self.ui.rdoutMouseWorld.setText("(-,-)")
        else:
            x = x - MIN_X
            y = y - MIN_Y
            self.ui.rdoutMousePixels.setText("(%.0f,%.0f)" % (x,y))
            if (self.video.aff_flag == 2):
                """ TO DO Here is where affine calibration must be used """
                aff = self.video.aff_matrix
                wx = x*aff[0][0] + y*aff[0][1] + aff[0][2]
                wy = x*aff[1][0] + y*aff[1][1] + aff[1][2]
                self.ui.rdoutMouseWorld.setText("(%.2f,%.2f)" %(wx,wy))
            else:
                self.ui.rdoutMouseWorld.setText("(-,-)")

                

        """
        Updates status label when rexarm playback is been executed.
        This will be extended to includ eother appropriate messages
        THIS SHOULD BE LAST BECAUSE IT RETURNS EARLY!!!!!!!!
        (Pedro don't be sad please)
        """
        if(self.rex.plan_status == 1):
            if self.rex.wpt_total == 0:
                self.ui.rdoutStatus.setText("No waypoints!")
                self.rex.plan_status = 0
            else:
                self.ui.rdoutStatus.setText("Playing Back - Waypoint %d"
                                            %(self.rex.wpt_number + 1))
                [start_time, prev_waypoint, prev_vel] = self.rex.plan[self.rex.wpt_number-1]
                [end_time, current_waypoint, current_vel] = self.rex.plan[self.rex.wpt_number]
                t = float(micro_time() - self.path_start_time)
               
                #Linear Interp
                for joint in range(4):
                    #Set the goal
                    self.rex.joint_angles[joint] = current_waypoint[joint]
                    
                    #Figure the speed out
                    dist = abs(current_waypoint[joint] - prev_waypoint[joint])
                    time_left = (end_time - t)/1000000.0
                    v = dist/time_left
                    # rad/sec * sec/min * rot/rad / max RPM
                    speed_val = v * (60.0/(2*math.pi)) / 59.0
                    speed_val = max(speed_val, 1.0/1023.0)

                    print speed_val, time_left
                    if time_left < 0:
                        #were behind haul ass
                        self.rex.speed[joint] = 1.0
                    else:
                        self.rex.speed[joint] = speed_val

                self.rex.cmd_publish()

                #Check if we have arrived
                def within_error(joint, wpt):
                    #print joint, wpt
                    error = math.fabs(joint * R2D - wpt * R2D)
                    #print error
                    return error < 5.0

                if within_error(self.rex.joint_angles_fb[0], current_waypoint[0]) and \
                   within_error(self.rex.joint_angles_fb[1], current_waypoint[1]) and \
                   within_error(self.rex.joint_angles_fb[2], current_waypoint[2]) and \
                   within_error(self.rex.joint_angles_fb[3], current_waypoint[3]):
                    print "Within Error Bounds: %d" %(self.rex.wpt_number)
                    self.rex.wpt_number += 1
                    self.executed_path.append([micro_time() - self.path_start_time , self.rex.joint_angles_fb[:]])
                    if self.rex.wpt_number >= len(self.rex.plan):
                        self.rex.plan_status = 0
                        self.ui.rdoutStatus.setText("Plan finished!")
                        self.rex.speed = [0.5, 0.5, 0.5, 0.5]
                        self.rex.plan = self.rex.plan[1:]
                        with open('executed_path.config', 'w') as f:
                            pickle.dump(self.executed_path, f)


    def slider_change(self):
        """
        Function to change the slider labels when sliders are moved
        and to command the arm to the given position
        TO DO: Implement for the other sliders
        """
        self.ui.rdoutBase.setText(str(self.ui.sldrBase.value()))
        self.ui.rdoutShoulder.setText(str(self.ui.sldrShoulder.value()))
        self.ui.rdoutElbow.setText(str(self.ui.sldrElbow.value()))
        self.ui.rdoutWrist.setText(str(self.ui.sldrWrist.value()))
        self.ui.rdoutTorq.setText(str(self.ui.sldrMaxTorque.value()) + "%")

        self.ui.rdoutSpeed.setText(str(self.ui.sldrSpeed.value()))

        if self.rex.plan_status == 0:
            self.rex.max_torque = self.ui.sldrMaxTorque.value()/100.0
            self.rex.joint_angles[0] = self.ui.sldrBase.value()*D2R
            self.rex.joint_angles[1] = self.ui.sldrShoulder.value()*D2R
            self.rex.joint_angles[2] = self.ui.sldrElbow.value()*D2R
            self.rex.joint_angles[3] = self.ui.sldrWrist.value()*D2R

        self.rex.cmd_publish()

    def solveAffineMatrix(self):
        A = []
        b = []
        for i in range(self.video.aff_npoints):
            px = self.video.mouse_coord[i][0]
            py = self.video.mouse_coord[i][1]
            wx = self.video.real_coord[i][0]
            wy = self.video.real_coord[i][1]

            A.append([px, py, 1.0, 0.0, 0.0, 0.0])
            A.append([0.0, 0.0, 0.0, px, py, 1.0])

            b.append(wx)
            b.append(wy)
        print A, '\n', b

        x, res, rank, s = np.linalg.lstsq(A, b)
        print x
        self.video.aff_matrix = [[x[0], x[1], x[2]],
                                 [x[3], x[4], x[5]],
                                 [0.0, 0.0, 1.0]]

    def mousePressEvent(self, QMouseEvent):
        """
        Function used to record mouse click positions for
        affine calibration
        """

        """ Get mouse posiiton """
        x = QMouseEvent.x()
        y = QMouseEvent.y()

        """ If mouse position is not over the camera image ignore """
        if ((x < MIN_X) or (x > MAX_X) or (y < MIN_Y) or (y > MAX_Y)): return

        """ Change coordinates to image axis """
        self.last_click[0] = x - MIN_X
        self.last_click[1] = y - MIN_Y

        """ If affine calibration is been performed """
        if (self.video.aff_flag == 1):
            """ Save last mouse coordinate """
            self.video.mouse_coord[self.video.mouse_click_id] = [(x-MIN_X),
                                                                 (y-MIN_Y)]

            """ Update the number of used poitns for calibration """
            self.video.mouse_click_id += 1

            """ Update status label text """
            self.ui.rdoutStatus.setText("Affine Calibration: Click point %d"
                                      %(self.video.mouse_click_id + 1))

            """
            If the number of click is equal to the expected number of points
            computes the affine calibration.
            TO DO: Change this code to use you programmed affine calibration
            and NOT openCV pre-programmed function as it is done now.
            """
            if(self.video.mouse_click_id == self.video.aff_npoints):
                """
                Update status of calibration flag and number of mouse
                clicks
                """
                self.video.aff_flag = 2
                self.video.mouse_click_id = 0

                """ Perform affine calibration with OpenCV """
                #self.video.aff_matrix = cv2.getAffineTransform(
                #                        self.video.mouse_coord,
                #                        self.video.real_coord)
                self.solveAffineMatrix()
                print self.video.aff_matrix
                """ Updates Status Label to inform calibration is done """
                self.ui.rdoutStatus.setText("Waiting for input")

                """
                Uncomment to gether affine calibration matrix numbers
                on terminal
                """
                #print self.video.aff_matrix
        
        if self.get_template == 1:
            self.template_point = [(x-MIN_X)*(960.0/480.0), (y-MIN_Y)*(1280.0/640.0)]
            self.get_template += 1
        elif self.get_template == 2:
            self.get_template = 0
            bottom_point = [(x-MIN_X)*(960.0/480.0), (y-MIN_Y)*(1280.0/640.0)]
            dx = bottom_point[0] - self.template_point[0]
            dy = bottom_point[1] - self.template_point[1]
            grey_frame = cv2.cvtColor(self.video.currentFrame, cv2.COLOR_BGR2GRAY)
            self.template = grey_frame[self.template_point[1]-dy:bottom_point[1], self.template_point[0]-dx:bottom_point[0]]
            #self.template = cv2.cvtColor(self.template, cv2.COLOR_BGR2GRAY)
            cv2.imwrite('./template.png', self.template)
            print "Got Template"

    def affine_cal(self):
        """
        Function called when affine calibration button is called.
        Note it only chnage the flag to record the next mouse clicks
        and updates the status text label
        """
        self.video.aff_flag = 1
        self.ui.rdoutStatus.setText("Affine Calibration: Click point %d"
                                    %(self.video.mouse_click_id + 1))

    def load_camera_cal(self):
        print "Load Camera Cal"
        self.video.loadCalibration()

    def tr_initialize(self):
        print "Teach and Repeat"
        self.path_start_time = micro_time()
        self.rex.plan = []
        self.rex.plan_status = 0
        self.rex.wpt_number = 0
        self.rex.max_torque = 0.0
        self.ui.sldrMaxTorque.setValue(0.0)

    def tr_add_waypoint(self):
        print "Add Waypoint"
        self.rex.plan.append([micro_time() - self.path_start_time, self.rex.joint_angles_fb[:], [0,0,0,0]])
        self.rex.wpt_total += 1

    def tr_smooth_path(self):
        print "Smooth Path"
        #Basic smoothing
        new_plan = []
        #for i, (t, p) in enumerate(self.rex.plan):
        #    np = p[:]
        #    nt = t + 1000000 * i + 500000
        #    if p[1] < 0:
        #        np[1] += 10*D2R
        #    else:
        #        np[1] -= 10*D2R
        #
        #    new_plan.append([nt-500000, np])
        #    new_plan.append([nt, p[:]])
        #    new_plan.append([nt+500000, np])

        self.rex.plan = [[0, [0, 0, 0, 0], [0,0,0,0]]] + self.rex.plan

        #Handle all other points
        for i in range(1,len(self.rex.plan)):
            [tprev, qprev, vprev] = self.rex.plan[i-1]
            [ti, qi, vi] = self.rex.plan[i]
            dt = (ti - tprev) * 0.3

            nprev = qprev[:]
            if nprev[1] < 0:
                nprev[1] += 10*D2R
            else:
                nprev[1] -= 10*D2R

            ni = qi[:]
            if ni[1] < 0:
                ni[1] += 10*D2R
            else:
                ni[1] -= 10*D2R

            new_plan.append([tprev + dt, nprev, vprev])
            new_plan.append([ti - dt, ni, vi])
            new_plan.append([ti, qi[:], vi])

        #Handle last point
        [ti, pi, vi] = self.rex.plan[-1]
        ni = qi[:]
        if ni[1] < 0:
            ni[1] += 10*D2R
        else:
            ni[1] -= 10*D2R

        new_plan.append([ti+500000, ni, vi])

        self.rex.plan = new_plan[1:]
        
        #Cubic spline smoothing
        
        # new_plan = [self.rex.plan[0][:]]
        # for i in range(1,len(self.rex.plan)):
        #     [start_time, prev_waypoint, prev_vel] = self.rex.plan[i-1]
        #     [end_time, current_waypoint, current_vel] = self.rex.plan[i]
        
        #     a0 = [0,0,0,0]
        #     a1 = [0,0,0,0]
        #     a2 = [0,0,0,0]
        #     a3 = [0,0,0,0]
        #     for joint in range(4):
        #         def calc_params(t0, q0, v0, tf, qf, vf):
        #             a0 = q0
        #             a1 = v0
        #             a2 = (3.0*(qf-q0)-(2.0*v0+vf)*(tf-t0))/math.pow(tf-t0, 2)
        #             a3 = (2.0*(q0-qf) + (v0+vf)*(tf-t0))/math.pow(tf-t0, 3)
        #             return a0, a1, a2, a3
    
        #         a0[joint], a1[joint], a2[joint], a3[joint] = calc_params(0.0,\
        #                                         float(prev_waypoint[joint]),\
        #                                         float(prev_vel[joint]),\
        #                                         1.0,\
        #                                         float(current_waypoint[joint]),\
        #                                         float(current_vel[joint]))
            
        #     duration = end_time - start_time
        #     for frac in range(1,100,10):
        #         frac = float(frac) / 100.0
        #         time = start_time + int(duration * frac)
        #         q = [0,0,0,0]
        #         for joint in range(4):
        #             q[joint] = a0[joint] + a1[joint] * frac + a2[joint] * frac * frac + a3[joint] * frac * frac * frac
                
        #         new_plan.append([time, q[:], [0.0, 0.0, 0.0, 0.0]])
            
        #     #Add the destination point
        #     new_plan.append(self.rex.plan[i][:])
           
        # with open('smooth_path.config', 'w') as f:
        #     print len(new_plan)
        #     pickle.dump(new_plan, f)

        # with open('path.config', 'w') as f:
        #     pickle.dump(self.rex.plan, f)

        # self.rex.plan = new_plan


    def tr_playback(self):
        print "Playback"
        self.path_start_time = micro_time()
        self.rex.wpt_number = 1
        self.rex.plan_status = 1
        self.rex.max_torque = 50.0
        self.ui.sldrMaxTorque.setValue(50.0)
        self.executed_path = []

        with open('path.config', 'w') as f:
            pickle.dump(self.rex.plan, f)
        self.rex.plan = [[micro_time() - self.path_start_time, self.rex.joint_angles_fb[:], [0,0,0,0]]] + self.rex.plan



    def def_template(self):
        print "Define Template"
        self.get_template = 1

    def template_match(self):
        print "Template Match"
        def make_bounding_box():
            min_x = 10000
            min_y = 10000
            max_x = 0
            max_y = 0
            for p in self.video.mouse_coord:
                x,y = mouse_to_raw(p[0], p[1])
                if x < min_x:
                    min_x = x
                if x > max_x:
                    max_x = x
                if y < min_y:
                    min_y = y
                if y > max_y:
                    max_y = y
            return [min_x, min_y], [max_x, max_y]

        #TODO get this working
        search_image = self.video.currentFrame
        #Make it greyscale
        search_image = cv2.cvtColor(search_image, cv2.COLOR_BGR2GRAY)
        [tx,ty],[bx,by] = make_bounding_box()
        print [tx,ty], [bx,by]
        search_image = search_image[tx:bx:,ty:by]
        search_size = search_image.shape
        print search_size

        #Get the size of the template
        template_size = self.template.shape
        #We just want a greyscale 2d image

        def SAD(x, y):
            sad = 0
            sub_region = search_image[x:x+template_size[0], y:y+template_size[1]]
            diff = sub_region - self.template
            sad = np.sum(diff**2)
            return sad / (template_size[0]*template_size[1])
            # for i in range(template_size[0]):
            #     for j in range(template_size[1]):
            #         sad += float(abs(int(search_image[x+i,y+j]) - int(self.template[i,j])))
            # return sad / (template_size[0]*template_size[1]*255.0)

        results = np.zeros((search_size[0]-template_size[0],
                    search_size[1]-template_size[1]))
        print "Doing SAD"
        for x in range(search_size[0] - template_size[0]):
            for y in range(search_size[1] - template_size[1]):
                results[x,y] = SAD(x,y)

        print results.max(), results.min()
        print "Done SAD"

        threshold = 70.0

        positions = []

        max_val = results.max()

        def arg_min(a):
            min_val = float('inf')
            min_x = 0
            min_y = 0
            for x in range(a.shape[0]):
                for y in range(a.shape[1]):
                    if a[x,y] < min_val:
                        min_val = a[x,y]
                        min_x = x
                        min_y = y
            return min_x, min_y

        count = 0
        while True:
            #If this is below the confidence level then quit
            min_index = arg_min(results)
            pixel_value = results[min_index]
            print pixel_value
            if pixel_value > threshold:
                break

            #Add it to potential positions
            positions.append(min_index)

            #Local max suppression
            def suppress_area(x,y):
                for i in range(-template_size[0]/2, template_size[0]/2):
                    for j in range(-template_size[1]/2, template_size[1]/2):
                        if x+i < 0 or y+j < 0:
                            continue
                        if x+i >= results.shape[0] or y+j >= results.shape[1]:
                            continue
                        results[x+i, y+j] = max_val

            suppress_area(min_index[0], min_index[1])
            out = results * (255.0/results.max())
            cv2.imwrite('./results_%d.png'%(count), out)
            count += 1

        #DONE-ish the points need to be shifted by half a template image size
        print positions

        #CONVERT POINTS TO WORLD COORDS
        cx = self.template.shape[0]/2
        cy = self.template.shape[1]/2
        positions = [raw_to_mouse(p[0]+tx+cx, p[1]+ty+cx) for p in positions]

        def aff_trans(x, y):
            aff = self.video.aff_matrix
            wx = x*aff[0][0] + y*aff[0][1] + aff[0][2]
            wy = x*aff[1][0] + y*aff[1][1] + aff[1][2]
            return wx,wy

        self.donuts = [aff_trans(p[0], p[1]) for p in positions]
        

    def exec_path(self):
        print "Execute Path"
        def get_phi(x,y):
            from math import sqrt, pow
            r = sqrt(pow(x,2)+pow(y,2))
            if r <= 95.0:
                return -135.0*D2R
            elif r > 95.0 and r < 190.0:
                return -90.0*D2R
            else:
                return -45.0*D2R

        self.donuts.sort(key=lambda x: math.atan2(x[1], x[0]))
        from itertools import chain, izip
        world_points = [(x,y, 50.0, get_phi(x,y)) for (x,y) in self.donuts]
        in_points = [(x,y, 10.0, get_phi(x,y)) for (x,y) in self.donuts]

        final_points = []
        for i,p in enumerate(world_points):
            final_points.append(p)
            final_points.append(in_points[i])
            final_points.append(p)

        config_space = [self.rex.rexarm_IK(p, 1) for p in final_points if self.rex.rexarm_IK(p, 1) != None]

        print "Playback"
        self.path_start_time = micro_time()
        self.rex.wpt_number = 1
        self.rex.plan_status = 1
        self.rex.max_torque = 50.0
        self.ui.sldrMaxTorque.setValue(50.0)
        self.executed_path = []

        self.rex.plan = [[0, self.rex.joint_angles_fb[:], [0,0,0,0]]] + \
                        [[3000000*(i+1), q, [0,0,0,0]] for i,q in enumerate(config_space)]

        print self.rex.plan
        self.rex.wpt_total = len(self.rex.plan)
Пример #46
0
class jaabaGUI(QMainWindow):
    """ controller for the blob labeling GUI"""

    def __init__(self,parent=None):
        self.debugMode = True
        self.debugVideoPath = '/Users/071cht/Desktop/Lab/jaabagui/testt.mjpeg.avi'

        QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.installEventFilter(self)
        self.setFocusPolicy(Qt.StrongFocus)
        #add new slider
        # self.positionSlider=QSlider(Qt.Horizontal)
        # self.positionSlider.setGeometry (800,800,100,30)
        # self.positionSlider.setRange(0, 0)
        # self.positionSlider.sliderMoved.connect(self.setPosition)

        #setup Video
        #video player
        self.mediaPlayer1 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer2 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer2.setNotifyInterval(10)
        #self.mediaPlayer.metaDataChanged.connect(self.metaDataChanged)
        self.mediaPlayer1.durationChanged.connect(self.durationChanged)
        self.mediaPlayer1.positionChanged.connect(self.positionChanged)
        self.mediaPlayer2.positionChanged.connect(self.positionChanged)
        #self.mediaPlayer2.positionChanged.connect(self.paintEvent)
        

        #visualizetion
        self.scene = QGraphicsScene()
        self.ui.graphicsView.setScene(self.scene)
        #self.scene.setBackgroundBrush(Qt.black)
        self.videoItem1 = QGraphicsVideoItem()
        self.videoItem2 = Video()
        self.scene.addItem(self.videoItem1)
        self.scene.addItem(self.videoItem2)
        self.mediaPlayer1.setVideoOutput(self.videoItem1)
        self.mediaPlayer2.setVideoOutput(self.videoItem2)

       

        #slider bar
        self.ui.horizontalSlider.setRange(0, 0)
        self.ui.horizontalSlider.sliderMoved.connect(self.setPosition)
        # self.ui.horizontalSlider.sliderPressed.connect(self.sliderPressed)

        #draw on video
        self.flyCanvas= TargetView()
        self.scene.addItem(self.flyCanvas)
        #give reference to target view
        self.flyCanvas.setWindowReference(self)

        #lineEdit signals:
        self.ui.lineEdit.returnPressed.connect(self.lineEditChanged)



        #callbacks
        self.ui.actionQuit.triggered.connect(self.quit)
        self.ui.actionLoad_Project.triggered.connect(self.loadVideo)
        self.ui.actionImport_Labels.triggered.connect(self.loadLabels)
        #self.ui.buttonPlay.clicked[bool].connect(self.setToggleText)
        self.ui.buttonPlay.clicked.connect(self.play)
        self.ui.actionSave.triggered.connect(self.saveLabels)
        ## print self.ui.graphicsView.sizeHint()

        #behavior Button
        self.ui.buttonBehavior.clicked.connect(self.behaviorButtonClick)
        self.ui.buttonNone.clicked.connect(self.noneButtonClick)

        #initialization
        self.loaded = False
        self.videoFilename = None
        self.frame_count=None
        self.width=None
        self.height=None
        self.frame_trans=None
        self.previous_frame=0
        self.current_frame=0
        self.behaviorButtonStart = False
        self.noneButtonStart = False
        self.currentFly=1

        #initialize flyInfo
        #self.setCurrentFly(self.currentFly)

        # register flyid changed callback
        self.flyCanvas.onCurrentFlyIdChanged(self.currentFlyIdChangedCallback)
        self.flyCanvas.setCurrentFlyId(self.currentFly)

        # when double click on video, change fly id in target view
        self.videoItem2.onDoubleClick(self.flyCanvas.setCurrentFlyIdByXY)

        ########################
        # DEBUG PART HERE!!!!! #
        ########################
        if (self.debugMode):
            self.debugLoadVideo()

    # add label UI related when load video   
    def showEvent(self, evt):
        super(jaabaGUI, self).showEvent(evt)
        ##### HERE THE WINDOW IS LOADED!!!!!!!!
        # self.loadLabelUI()

    def loadLabelUI(self):
         #labels
        self.labelScene = QGraphicsScene()

        self.ui.graphLabels.setScene(self.labelScene)
        # the size is only accurate after the window fully displayed
        labelUIWidth = self.ui.graphLabels.width()
        labelUIHeight = self.ui.graphLabels.height()-1

        self.labelScene.setSceneRect(0,0,labelUIWidth,labelUIHeight)

        
        self.labelUI = LabelUI()
        # visiableWidth = 850
        # height = 30
        # visiableFrameNum = 850

        self.labelUI.setWidthPerFrame(850.0/850.0)
        # print '850/500',850.0/850.0b
        # print 'length_perframe is ', self.labelUI.widthPerFrame 
        # 850 is the original length of graphLabel
        total_length= self.labelUI.widthPerFrame * self.frame_count
        self.labelUI.setVisiableSize(total_length,30)

        # set start position
        self.labelUI.setPos(labelUIWidth/2,0)


        print 'frame_count is ', self.frame_count
        print 'total length is', total_length
        
        self.labelScene.addItem(self.labelUI)

        # middle line ui
        self.labelUIMiddleLine = LabelUIMiddleLine()
        self.labelScene.addItem(self.labelUIMiddleLine)
        self.labelUIMiddleLine.setPos(labelUIWidth/2,0)
       


        # self.labelUI.setPos(QPointF(-100,0))
        self.writeLog('Label UI loaded')

    def eventFilter(self, obj, event):
  
    	if (event.type() == PyQt5.QtCore.QEvent.KeyPress):
    		# http://qt-project.org/doc/qt-4.8/qt.html#Key-enum
    		key = event.key()
    		
    		if (key == Qt.Key_Up) :
    			curr_frame= int(float(self.ui.lineEdit.text()))
    			curr_frame= curr_frame-30
    			media_position= int(round(curr_frame*self.frame_trans))

    			# print curr_frame, media_position
    			self.mediaPlayer1.setPosition(media_position) 
    			self.mediaPlayer2.setPosition(media_position)

    			# print 'down -30'
    		elif (key == Qt.Key_Right):
    			curr_frame= int(float(self.ui.lineEdit.text()))
    			# print 'right +1'
    			# print curr_frame
    			curr_frame= curr_frame+1
    			media_position= int(round(curr_frame*self.frame_trans))
    			# print 'curr_frame',curr_frame
    			# print 'frame_trans',self.frame_trans
    			# print ' curr_frame*self.frame_trans',curr_frame*self.frame_trans
    			# print 'media_position',media_position

    			# print curr_frame, media_position
    			self.mediaPlayer1.setPosition(media_position) 
    			self.mediaPlayer2.setPosition(media_position)
    			# self.mediaPlayerPositionChanged(media_position)
    		elif (key == Qt.Key_Left):
    			curr_frame= int(float(self.ui.lineEdit.text()))
    			curr_frame= curr_frame-1
    			media_position= int(round(curr_frame*self.frame_trans))
    			self.mediaPlayer1.setPosition(media_position) 
    			self.mediaPlayer2.setPosition(media_position)
    			# print 'left -1'
    		elif (key == Qt.Key_Down):
    			curr_frame= int(float(self.ui.lineEdit.text()))
    			curr_frame= curr_frame+30
    			media_position= int(round(curr_frame*self.frame_trans))
    			self.mediaPlayer1.setPosition(media_position) 
    			self.mediaPlayer2.setPosition(media_position)
    			# print 'up +30'
    		return True

    		

    	return False


    # ###actions starts from here###
    def quit(self):
        QApplication.quit()

    def loadVideo(self):
        
        # print QMediaPlayer.supportedMimeTypes()

        self.writeLog("Loading video...")

        self.videoFilename = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]
        if not self.videoFilename:
            self.writeLog("User cancelled - no video loaded")
            return
        else:
       		cap=cv2.VideoCapture(self.videoFilename)
	    	self.frame_count=cap.get(cv2.CAP_PROP_FRAME_COUNT)
	    	self.width=cap.get(3)
	    	self.height=cap.get(4)

	        self.mediaPlayer2.setMedia(QMediaContent(QUrl.fromLocalFile(self.videoFilename )))
	        self.mediaPlayer1.setMedia(QMediaContent(QUrl.fromLocalFile(self.videoFilename )))
	        self.ui.buttonPlay.setEnabled(True)
            # self.mediaPlayer2.setVideoOutput(self.videoItem2)
            # self.mediaPlayer1.setVideoOutput(self.videoItem1)
            # size= self.videoItem2.nativeSize()
            # # print size
            ## print self.mediaPlayer.duration()
          
            ## print self.mediaPlayer.metaData()
        self.writeLog("Video loaded!")

        # init label related ui
        self.loadLabelUI()


    def debugLoadVideo(self):

        self.videoFilename = self.debugVideoPath

        cap=cv2.VideoCapture(self.videoFilename)
        self.frame_count=cap.get(cv2.CAP_PROP_FRAME_COUNT)
        self.width=cap.get(3)
        self.height=cap.get(4)

        self.mediaPlayer2.setMedia(QMediaContent(QUrl.fromLocalFile(self.videoFilename )))
        self.mediaPlayer1.setMedia(QMediaContent(QUrl.fromLocalFile(self.videoFilename )))
        self.ui.buttonPlay.setEnabled(True)
        self.writeLog("Video loaded!")

        QTimer.singleShot(1000, self.loadLabelUI)

    def play(self):
    	
        self.videoItem1.setAspectRatioMode(0)
        self.videoItem2.setAspectRatioMode(0)
        self.scene.setSceneRect(0,0,self.ui.graphicsView.width(),self.ui.graphicsView.height())
        self.videoItem1.setSize(QSizeF(self.ui.graphicsView.width()/2,self.ui.graphicsView.height()))
        self.videoItem2.setSize(QSizeF(self.ui.graphicsView.width()/2,self.ui.graphicsView.height()))
        self.videoItem1.setPos(QPointF(0,0))
        self.videoItem2.setPos(QPointF(self.ui.graphicsView.width()/2,0))
        self.flyCanvas.setPos(QPointF(self.ui.graphicsView.width()/2,0))

        # custom function setXYScale
        self.videoItem2.setXYScale(self.width,self.height,self.ui.graphicsView.width()/2,self.ui.graphicsView.height())
        self.flyCanvas.setXYScale(self.width,self.height,self.ui.graphicsView.width()/2,self.ui.graphicsView.height())




        if self.mediaPlayer1.state() == QMediaPlayer.PlayingState:
        	self.ui.buttonPlay.setIcon(self.ui.style().standardIcon(PyQt5.QtWidgets.QStyle.SP_MediaPlay))
        	self.ui.buttonPlay.setText("Play")
        	self.mediaPlayer1.pause()
        	self.writeLog("Video paused")
        else: 
        	self.ui.buttonPlay.setIcon(self.ui.style().standardIcon(PyQt5.QtWidgets.QStyle.SP_MediaPause))
	        self.ui.buttonPlay.setText("Stop")
	        
	        self.mediaPlayer1.play()
	        self.writeLog("Playing video")

        if self.mediaPlayer2.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer2.pause()
        else: 
            self.mediaPlayer2.play()

    def loadLabels(self):

        self.writeLog("Loading labels from file...")
        self.labelFilename = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]
        self.labelUI.labelData = pickle.load(open(self.labelFilename,"rb"))
        self.writeLog("Label loaded from file:" + self.labelFilename)

    def saveLabels(self):
        # Now it can only save to current file. Will add an poput window to choose path later
        pickle.dump( self.labelUI.labelData, open( "newLabels.p", "wb" ) )
  

    def setPosition(self, position):
    	self.mediaPlayer1.setPosition(position) 
    	self.mediaPlayer2.setPosition(position) 

    # when position of media changed, set slider and text box accordingly.
    def positionChanged(self, position):
        #test change labelui position
        # self.labelUI.startLabel();
        # self.labelUI.update()
        previous_frame=  self.previous_frame
        curr_frame= int(round(position/self.frame_trans))
        self.current_frame=curr_frame
        frame_change= previous_frame-curr_frame
        move_width= frame_change * self.labelUI.widthPerFrame
        self.previous_frame= curr_frame

        self.labelUI.moveBy(move_width,0)

        self.labelUI.setCurrentFrame(curr_frame)
        # enforce labelUI paint once
        self.labelUI.update()
       
        # self.labelUI.setPos(self.labelUI.mapToParent(1,0));
        # self.labelUI.update()

    	# # print 'triggered position'
    	# # print position
    	# # print 'cur position'
    	# # print self.mediaPlayer2.position()
    	self.updateLineEdit(position)
    	self.updateSliderAndGraph(position)
    	
       #  self.ui.horizontalSlider.setValue(position)

       #  if isinstance(self.frame_trans,float):
	      #   # # print type(position),position
	      #   # # print type(self.frame_trans),self.frame_trans 
	      #   # # print position/self.frame_trans
	     	# self.ui.lineEdit.setText(str(int(round(position/self.frame_trans))))
	     	# self.flyCanvas.getFrame(int(round(position/self.frame_trans)))
	     	# self.flyCanvas.isManualCalled = True;
	     	# self.flyCanvas.update()

       #  self.writeLog(str(position))    
       # # self.updateMediaControlUI(position)
       # # self.flyCanvas.update()

    def updateSliderAndGraph(self, position):
    	self.ui.horizontalSlider.setValue(position)
    	if isinstance(self.frame_trans,float):
    		self.flyCanvas.getFrame(int(round(position/self.frame_trans)))
    		self.flyCanvas.isManualCalled = True
    		self.flyCanvas.update()

        #self.writeLog(str(position)) 
    def updateLineEdit(self, position): 
        # # print self.width
        # # print self.height
    	if isinstance(self.frame_trans,float):
	        # # print type(position),position
	        # # print type(self.frame_trans),self.frame_trans 
	        # # print position/self.frame_trans
	     	self.ui.lineEdit.setText(str(int(round(position/self.frame_trans))))

    def durationChanged(self, duration):
	    self.ui.horizontalSlider.setRange(0, duration) 
	    self.frame_trans=self.mediaPlayer1.duration()/self.frame_count
	    ## print self.frame_trans

	#def eventFilter(self,source,event):
		#if (event.type()==PyQt5.QtCore.QEvent.MousePress and source is self.videoItem2):
		# 	pos=event.pos()
		# 	# print('mouse position: (%d,%d)' % (pos.x(),pos.y()))
	 #    return PyQt5.QtGui.QWidget.eventFilter(self, source, event)

    def writeLog(self,text):
        self.ui.log.setText(text)

    # def eventFilter (self.ui.lineEdit,event):
    #     if event.type()==PyQt5.QtCore.QEvent

    def lineEditChanged(self):
    	#set position of media
    	curr_frame= int(float(self.ui.lineEdit.text()))
    	media_position= int(round(curr_frame*self.frame_trans))
    	self.mediaPlayer1.setPosition(media_position) 
    	self.mediaPlayer2.setPosition(media_position)
    	# print 'setPosition'
    	# print media_position
    	# print 'after set'
    	# print self.mediaPlayer2.position()
    	# self.updateSliderAndGraph(media_position)


    def behaviorButtonClick(self):
        # flip flag
        self.behaviorButtonStart = not self.behaviorButtonStart

        # check click to start or stop
        if (self.behaviorButtonStart):
            # start labeling
            self.labelUI.startLabel(self.ui.comboBox.currentIndex(),'',self.current_frame)
            self.writeLog('start labeling')


        else:
            # stop lableing
            self.labelUI.stopLabel()
            self.writeLog('stop labeling')

    def noneButtonClick(self):
           # flip flag
        self.noneButtonStart = not self.noneButtonStart

        # check click to start or stop
        if (self.noneButtonStart):
            # start labeling
            self.labelUI.startLabel(self.ui.comboBox.currentIndex(),'_none',self.current_frame)
            self.writeLog('start labeling')
        else:
            # stop lableing
            self.labelUI.stopLabel()
            self.writeLog('stop labeling')


    # set CurrentFly when fly changed! 
    def setCurrentFly(self,fly):
        self.currentFly = fly
        self.ui.flyInfo.setPlainText('FlyID:' + str(self.currentFly))
        self.flyCanvas.currentFly=fly

    def currentFlyIdChangedCallback(self,fly):
        print 'callback!!!!!';
        self.currentFly = fly
        self.ui.flyInfo.setPlainText('FlyID:' + str(self.currentFly))
Пример #47
0
Файл: gui.py Проект: oiyio/492
class Editor(QtGui.QMainWindow):
	def __init__(self):
		super(Editor, self).__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.show()
Пример #48
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.file_name = ''
        self.file_flag = False
        self.sic = None
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.input_file_name.clicked.connect(self.set_file_name)
        self.ui.op_table.clicked.connect(self.op_table)
        self.ui.symbol_table.clicked.connect(self.symbol_table)
        self.ui.object_code.clicked.connect(self.object_code)
        self.ui.object_program_format.clicked.connect(
            self.object_program_format)
        self.ui.language.activated[str].connect(self.change_language)

    def create_sic(self):
        clear_global_variable()
        self.sic = sic.SIC(self.file_name)

    def set_message(self, index):
        if self.ui.language.currentText() == self.ui.languages[0]:
            self.ui.textBrowser.insertPlainText(self.ui.english[index - 1] +
                                                '\n')
        elif self.ui.language.currentText() == self.ui.languages[1]:
            self.ui.textBrowser.insertPlainText(
                self.ui.traditional_chinese[index - 1] + '\n')
        else:
            self.ui.textBrowser.insertPlainText(self.ui.japanese[index - 1] +
                                                '\n')

    def change_language(self):
        self.ui.change_language()
        if not self.file_name == '' and self.ui.push_button == 1:
            self.ui.textBrowser.clear()
            if self.file_flag is True:
                self.set_message(3)
                self.set_message(4)
            else:
                self.set_message(2)
        elif self.file_name == '':
            self.ui.textBrowser.clear()
            if self.ui.push_button == 1:
                self.set_message(1)
            elif self.ui.push_button > 1:
                self.set_message(5)

    def set_file_name(self):
        self.ui.push_button = 1
        file_name = self.ui.textEdit.toPlainText()
        if file_name.find('.txt') == -1:
            file_name += '.txt'

        d_list = os.listdir()
        self.ui.textBrowser.clear()

        if file_name not in d_list:
            self.set_message(1)
            self.file_name = ''
        elif file_name == self.file_name:
            self.file_flag = False
            self.set_message(2)
        else:
            self.ui.textBrowser.clear()
            self.file_name = file_name
            self.file_flag = True
            self.set_message(3)
            self.create_sic()
            self.set_message(4)
            self.sic.start()

    def op_table(self):
        self.ui.push_button = 2
        self.ui.textBrowser.clear()
        if self.file_name == '':
            self.set_message(5)
            pass
        else:
            op_table = sic.OPTABLE.items()
            count = 0
            for each in op_table:
                count += 1
                self.ui.textBrowser.insertPlainText(
                    '{:<20}'.format(str(each)) + '\t')
                if count % 5 == 0:
                    self.ui.textBrowser.insertPlainText('\n')

    def symbol_table(self):
        self.ui.push_button = 3
        self.ui.textBrowser.clear()
        if self.file_name == '':
            self.set_message(5)
            pass
        else:
            count = 0
            for each in sic.Symbol:
                count += 1
                self.ui.textBrowser.insertPlainText(each + '\t')
                if count % 3 == 0:
                    self.ui.textBrowser.insertPlainText('\n')

    def object_code(self):
        self.ui.push_button = 4
        self.ui.textBrowser.clear()
        if self.file_name == '':
            self.set_message(5)
            pass
        else:
            line_count = 1
            self.ui.textBrowser.insertPlainText(
                'Line\t Loc\t\t\tSource statement\t\t\tObject code\n')
            for i in range(len(self.sic.instruction)):
                temp = self.sic.instruction[i]
                if temp.machineCode == 'error':
                    self.ui.textBrowser.insertPlainText(
                        '\t\tInstruction is error, so can not get the result\n'
                    )
                else:
                    line = '{:>4}'.format(str(line_count)) + '\t'
                    if temp.order == 'END':
                        line += '\t'
                    else:
                        line += temp.leftAddress + '\t'
                    line += '{:<18}'.format(temp.symbol) + '\t'
                    line += temp.order + '\t\t'
                    line += '{:<18}'.format(temp.label) + '\t    '
                    line += temp.machineCode + '\n'
                    self.ui.textBrowser.insertPlainText(line)
                    line_count += 1

    def object_program_format(self):
        self.ui.push_button = 5
        self.ui.textBrowser.clear()
        if self.file_name == '':
            self.set_message(5)
            pass
        else:
            left = '00'
            temp = self.sic
            instruction_len = len(temp.instruction)
            header = 'H^' + temp.instruction[
                0].symbol + '^' + left + temp.instruction[0].leftAddress + '^'
            txt_begin = function.hex_to_dec(temp.instruction[0].leftAddress)
            txt_end = function.hex_to_dec(temp.instruction[instruction_len -
                                                           1].leftAddress)
            header += left + function.dec_to_hex(txt_end - txt_begin)
            self.ui.textBrowser.insertPlainText(header + '\n')
            size = 0
            begin_index = 1
            lines = []
            b = []
            sizes = []
            line = ''
            b.append(begin_index)
            while True:
                if begin_index == instruction_len - 1:
                    lines.append(line)
                    sizes.append(size)
                    b.append(begin_index)
                    break
                elif size + (len(sic.MC[begin_index]) / 2) > 30:
                    lines.append(line)
                    sizes.append(size)
                    b.append(begin_index)
                    line = ''
                    size = 0
                elif sic.MC[begin_index] == '':
                    lines.append(line)
                    sizes.append(size)
                    b.append(begin_index + 1)
                    line = ''
                    size = 0
                if sic.MC[begin_index] == 'error':
                    pass
                elif sic.MC[begin_index] == '':
                    pass
                else:
                    line += '^' + function.fill_zeros(sic.MC[begin_index])
                    size += (len(sic.MC[begin_index]) / 2)
                begin_index += 1

            for i in range(len(lines)):
                line = ''
                if lines[i] == '':
                    pass
                else:
                    line += 'T^' + left + temp.instruction[
                        b[i]].leftAddress + '^'
                    if sizes[i] < 16:
                        line += '0'
                    line += function.dec_to_hex(int(
                        sizes[i])) + lines[i] + '\n'
                    self.ui.textBrowser.insertPlainText(line)
            self.ui.textBrowser.insertPlainText(
                'E^00' + temp.instruction[0].leftAddress)
Пример #49
0
class MainWindow(QtGui.QMainWindow):
    
    def __init__(self, settings, application=None):
        '''
        UI Object that draws the main window.
        
        Listens to the following settings:
        - delay: 
        '''
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self._renderwidgets = [
                               RenderWidget(self),
                               RenderWidget(self),
                               RenderWidget(self),
                               RenderWidget(self),
                               ]
        
        self.update()
        self.application = application
        
        self.settings = settings
        self.settings.settingChanged.connect(self.settingChanged)
        self.ui.delay.setText(str(settings.getSetting("delay")))
        self._loadScreens(self.settings.getSetting("layouts")[self.settings.getSetting("selectedlayout")]["screen"])
        self._bindings = {}
        self._windowstate = None
        self._loadBindings(settings.getSetting('keybinding'))
        
    # end __init__()
    
    # signals
    incDelay = Signal()         #+>=. (while running)
    decDelay = Signal()         #-<,  (while running)
    incFrame = Signal()         #+>=. (while paused)
    decFrame = Signal()         #-<,  (while paused)
    help = Signal()             #F1
    edit = Signal()             #F2
    togglePlay = Signal()       #F7 <space>
    recordBuffer = Signal()     #F12
    
    # signals (new)
    processFrame = Signal(str, object)
    processGroup = Signal(str, object)
    resized = Signal()
    
    def resizeEvent(self, *args, **kwargs):
        returncode = QtGui.QMainWindow.resizeEvent(self, *args, **kwargs)
        self.resized.emit()
        return returncode
    
    @Slot(str,object)
    def settingChanged(self, name, value):
        if name == "delay":
            self.ui.delay.setText(str(value))
        elif name == "keybinding":
            self._loadBindings(value)
        elif name == "selectedlayout":
            self._loadScreens(self.settings.getSetting("layouts")[value]["screen"])
    
    ## reimplemented ##
    def showEvent(self, *args, **kwargs):
        if self._windowstate is None:
            self._windowstate = self.settings.getSetting("delayanalysisui")
            self.setGeometry(*self._windowstate['geometry'])
            if self._windowstate['mode'] == 'fullscreen':
                self.showFullScreen()
            elif self._windowstate['mode'] == 'maximised':
                self.showMaximized()
        return QtGui.QMainWindow.showEvent(self, *args, **kwargs)
    
    def closeEvent(self, *args, **kwargs):
        if self._windowstate is not None:
            self._windowstate = self.settings.getSetting("delayanalysisui")
            if self._windowstate['savemode'] == True:
                if self.windowState() == QtCore.Qt.WindowFullScreen:
                    self._windowstate['mode'] = "fullscreen"
                elif self.windowState() == QtCore.Qt.WindowMaximized:
                    self._windowstate['mode'] = "maximised"
                else:
                    self._windowstate['mode'] = "normal"
            if self._windowstate['savegeometry'] == True:
                self._windowstate['geometry'] = self.geometry().getRect()
            self.settings.setSetting('delayanalysisui', self._windowstate)
        
        return QtGui.QMainWindow.closeEvent(self, *args, **kwargs)
    
    ## support ##
    def _loadScreens(self, screens):
        self._screens = screens
        self._layouts = min(4, len(self._screens))
#         print "Layouts: %s" % self._layouts
#         print "Screens: %s" % self._screens
        for i in range(self._layouts):
            self._renderwidgets[i].setLayout(screens[i])
        
    
    def _loadBindings(self, bindings):
        '''
        Extracts the actual key ids from the string representations of them provided.
        
        @param bindings: dict containing keybindings {'<keyname>': [('<group>', '<function>', <optionargs>,...), ...]} 
        '''
        try:
            
            groups = {'core': None,
                    'processframe': lambda m,c: self.processFrame.emit(m,c),
                    'processgroup': lambda m,c: self.processGroup.emit(m,c),
                    }
            corefuncs = {
                         'quit': lambda a,b: self.close(),
                         'play': lambda a,b: self.togglePlay.emit(),
                         'incdelay': lambda a,b: self.incDelay.emit(),
                         'decdelay': lambda a,b: self.decDelay.emit(),
                         'incframe': lambda a,b: self.incFrame.emit(),
                         'decframe': lambda a,b: self.decFrame.emit(),
                         'fullscreen': lambda a,b: self.toggleFullScreen(),
                         'edit': lambda a,b: self.edit.emit(),
                         'help': lambda a,b: self.help.emit(),
                         }
            
            errors = []
            self._bindings = {}
            for keystr, events in bindings.items():
                for event in events:
                    try:
                        # convert to integer
                        keyint = getattr(QtCore.Qt,"Key_%s"% str(keystr))
                        
                        # get functions to perform tasks
                        func = groups[event[0]]
                        if func is None:
                            func = corefuncs[event[1]]
                        
                        if keyint in self._bindings:
                            self._bindings[keyint].append((func, event[1], event[2:]))
                        else:
                            self._bindings[keyint] = [(func, event[1], event[2:])]
                    except AttributeError:
                        errors.append("Key: %s" %keystr)
                    except KeyError:
                        errors.append("Group: %s" %keystr)

            if len(errors) > 0:
                print "Ignoring the following invalid key bindings (%s)" % (", ".join(errors)) 
        except:
            pass
    
    def toggleFullScreen(self):
        '''Toggles between fullscreen and normal mode'''
        if not self.isFullScreen():
            self.showFullScreen()
        else:
            self.showNormal()
    
    def keyPressEvent(self, e):
        '''Perform tasks for various key events'''
        
        if e.key() in self._bindings:
            for binding in self._bindings[e.key()]:
                func, action, config = binding
                func(action, config)
        else:
            print "key: %s" % (e.key(),)
    
    def renderFrameset(self, frameset):
        '''
        Renders the relevent frames from the frameset to screen
        '''
        for i in range(self._layouts):
            self._renderwidgets[i].process(frameset)
    
#     def updateView(self, vid, pixmap):
#         '''Updates a view to display given pixmap'''
#         self.ui.videoFrame.setPixmap(pixmap)
#         self.ui.videoFrame.setScaledContents(True)
    
    def setFrameId(self, frameid):
        self.ui.frameNum.setText(frameid)
        
    def setFrameRate(self, framerate):
        self.ui.frameRate.setText(framerate)
Пример #50
0
class Gui(QMainWindow):
    """ 
    Main GUI Class
    contains the main function and interfaces between 
    the GUI and functions
    """
    def __init__(self,parent=None):
        QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        """ Set GUI to track mouse """
        QWidget.setMouseTracking(self,True)

        """dynamixel bus -- add other motors here"""
        self.dxlbus = DXL_BUS(DEVICENAME, BAUDRATE)
        port_num = self.dxlbus.port()
        base = DXL_MX(port_num, 0)
        shld = DXL_MX(port_num, 1)
        elbw = DXL_MX(port_num, 2)
        wrst = DXL_AX(port_num, 3)
        wrst2 = DXL_XL(port_num, 4) # NIC 10/4
        grip = DXL_XL(port_num, 5) # NIC 10/4

        """Objects Using Other Classes"""
        self.kinect = Kinect()
        self.rexarm = Rexarm((base,shld,elbw,wrst,wrst2),grip) # NIC 10/4
        self.tp = TrajectoryPlanner(self.rexarm)
        self.sm = StateMachine(self.rexarm, self.tp, self.kinect)
    
        """ 
        Attach Functions to Buttons & Sliders
        TODO: NAME AND CONNECT BUTTONS AS NEEDED
        """
        self.ui.btn_estop.clicked.connect(self.estop)
	self.ui.btn_exec.clicked.connect(partial(self.sm.set_next_state,"execute_plan"))
        self.ui.btn_task1.clicked.connect(partial(self.sm.set_next_state,"task_1"))
	self.ui.btn_task2.clicked.connect(partial(self.sm.set_next_state,"task_2"))
	self.ui.btn_task4.clicked.connect(partial(self.sm.set_next_state,"task_5"))
	#self.ui.btn_exec.clicked.connect(partial(self.sm.set_next_state,"execute"))
        self.ui.btnUser1.setText("Calibrate")
        self.ui.btnUser1.clicked.connect(partial(self.sm.set_next_state, "calibrate"))
	self.ui.btnUser2.setText("Record Waypoints")
	self.ui.btnUser2.clicked.connect(partial(self.sm.set_next_state, "record"))
	self.ui.btnUser3.setText("Play")
	self.ui.btnUser3.clicked.connect(partial(self.sm.set_next_state, "play"))
	self.ui.btnUser4.setText("Open Gripper") # NIC 10/4
	self.ui.btnUser4.clicked.connect(self.rexarm.open_gripper) # NIC 10/4
	self.ui.btnUser5.setText("Close Gripper") # NIC 10/4
	self.ui.btnUser5.clicked.connect(self.rexarm.close_gripper) # NIC 10/4
        self.ui.sldrBase.valueChanged.connect(self.sliderChange)
        self.ui.sldrShoulder.valueChanged.connect(self.sliderChange)
        self.ui.sldrElbow.valueChanged.connect(self.sliderChange)
        self.ui.sldrWrist.valueChanged.connect(self.sliderChange)
        self.ui.sldrGrip1.valueChanged.connect(self.sliderChange)
        self.ui.sldrGrip2.valueChanged.connect(self.sliderChange)
        self.ui.sldrMaxTorque.valueChanged.connect(self.sliderChange)
        self.ui.sldrSpeed.valueChanged.connect(self.sliderChange)
        self.ui.chk_directcontrol.stateChanged.connect(self.directControlChk)
        self.ui.rdoutStatus.setText("Waiting for input")

        """initalize manual control off"""
        self.ui.SliderFrame.setEnabled(False)

        """initalize rexarm"""
        self.rexarm.initialize()

        """Setup Threads"""
        self.videoThread = VideoThread(self.kinect)
        self.videoThread.updateFrame.connect(self.setImage)        
        self.videoThread.start()

        
        self.logicThread = LogicThread(self.sm)
        self.logicThread.start()
        

        self.displayThread = DisplayThread(self.rexarm, self.sm)
        self.displayThread.updateJointReadout.connect(self.updateJointReadout)
        self.displayThread.updateEndEffectorReadout.connect(self.updateEndEffectorReadout)
        self.displayThread.updateStatusMessage.connect(self.updateStatusMessage)
        self.displayThread.start()

        """ 
        Setup Timer 
        this runs the trackMouse function every 50ms
        """
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.trackMouse)
        self._timer.start(50)

    """ Slots attach callback functions to signals emitted from threads"""

    @pyqtSlot(QImage, QImage)
    def setImage(self, rgb_image, depth_image):
        if(self.ui.radioVideo.isChecked()):
            self.ui.videoDisplay.setPixmap(QPixmap.fromImage(rgb_image))
        if(self.ui.radioDepth.isChecked()):
            self.ui.videoDisplay.setPixmap(QPixmap.fromImage(depth_image))

    @pyqtSlot(list)
    def updateJointReadout(self, joints):
        self.ui.rdoutBaseJC.setText(str("%+.2f" % (joints[0]*R2D)))
        self.ui.rdoutShoulderJC.setText(str("%+.2f" % ((joints[1]*R2D)+90.0)))
        self.ui.rdoutElbowJC.setText(str("%+.2f" % (joints[2]*R2D)))
        self.ui.rdoutWristJC.setText(str("%+.2f" % (joints[3]*R2D)))

    @pyqtSlot(list)
    def updateEndEffectorReadout(self, pos):
        self.ui.rdoutX.setText(str("%+.2f" % (pos[0])))
        self.ui.rdoutY.setText(str("%+.2f" % (pos[1])))
        self.ui.rdoutZ.setText(str("%+.2f" % (pos[2])))
        self.ui.rdoutT.setText(str("%+.2f" % (pos[3])))

    @pyqtSlot(str)
    def updateStatusMessage(self, msg):
        self.ui.rdoutStatus.setText(msg)


    """ Other callback functions attached to GUI elements"""

    def estop(self):
        self.rexarm.estop = True
        self.sm.set_next_state("estop")

    def sliderChange(self):
        """ 
        Function to change the slider labels when sliders are moved
        and to command the arm to the given position
        """
        self.ui.rdoutBase.setText(str(self.ui.sldrBase.value()))
        self.ui.rdoutShoulder.setText(str(self.ui.sldrShoulder.value()))
        self.ui.rdoutElbow.setText(str(self.ui.sldrElbow.value()))
        self.ui.rdoutWrist.setText(str(self.ui.sldrWrist.value()))
        #enter the vale for the slider  :slider rdoutGrip2 and rdoutGrip2   
        self.ui.rdoutTorq.setText(str(self.ui.sldrMaxTorque.value()) + "%")
        self.ui.rdoutSpeed.setText(str(self.ui.sldrSpeed.value()) + "%")
        self.rexarm.set_torque_limits([self.ui.sldrMaxTorque.value()/100.0]*self.rexarm.num_joints, update_now = False)
        self.rexarm.set_speeds_normalized_global(self.ui.sldrSpeed.value()/100.0, update_now = False)
        joint_positions = np.array([self.ui.sldrBase.value()*D2R, 
                           self.ui.sldrShoulder.value()*D2R,
                           self.ui.sldrElbow.value()*D2R,
                           self.ui.sldrWrist.value()*D2R,
                           self.ui.sldrGrip1.value()*D2R,
                           self.ui.sldrGrip2.value()*D2R])
        self.rexarm.set_positions(joint_positions, update_now = False)

    def directControlChk(self, state):
        if state == Qt.Checked:
            self.sm.set_next_state("manual")
            self.ui.SliderFrame.setEnabled(True)
        else:
            self.sm.set_next_state("idle")
            self.ui.SliderFrame.setEnabled(False)

    def trackMouse(self):
        """ 
        Mouse position presentation in GUI
        TODO: after implementing workspace calibration 
        display the world coordinates the mouse points to 
        in the RGB video image.
        """

        x = QWidget.mapFromGlobal(self,QCursor.pos()).x()
        y = QWidget.mapFromGlobal(self,QCursor.pos()).y()
        if ((x < MIN_X) or (x >= MAX_X) or (y < MIN_Y) or (y >= MAX_Y)):
            self.ui.rdoutMousePixels.setText("(-,-,-)")
            self.ui.rdoutMouseWorld.setText("(-,-,-)")
        else:
            x = x - MIN_X
            y = y - MIN_Y
            if(self.kinect.currentDepthFrame.any() != 0):
                z = self.kinect.currentDepthFrame[y][x]
                self.ui.rdoutMousePixels.setText("(%.0f,%.0f,%.0f)" % (x,y,z))
		if (self.kinect.kinectCalibrated):
		   zw = self.kinect.depthcalibration(z)
		   xwyw = self.kinect.pixeltoworldcoordinates(np.array([x,y,1]), z)
                   self.ui.rdoutMouseWorld.setText("(%.0f,%.0f,%.0f)" % (xwyw[0],xwyw[1],zw))

    def mousePressEvent(self, QMouseEvent):
        """ 
        Function used to record mouse click positions for calibration 
        """
 
        """ Get mouse posiiton """
        x = QMouseEvent.x()
        y = QMouseEvent.y()

        """ If mouse position is not over the camera image ignore """
        if ((x < MIN_X) or (x > MAX_X) or (y < MIN_Y) or (y > MAX_Y)): return

        """ Change coordinates to image axis """
        self.kinect.last_click[0] = x - MIN_X 
        self.kinect.last_click[1] = y - MIN_Y
        self.kinect.new_click = True
Пример #51
0
class Calc(QtWidgets.QMainWindow):
    def __init__(self):
        super(Calc, self).__init__()
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
        self.setWindowIcon(QtGui.QIcon('calculator.jpg'))
        self.setWindowTitle('Calculator')
        self.setFixedSize(QSize(426, 440))
        # self.setBackgroundRole()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(palette.Window, QColor(120, 20, 230))
        self.setPalette(palette)

        self.ui.lineEdit_2.setReadOnly(True)
        # Заполнение comboBox
        for i in range(2, 17):
            self.ui.Of.addItem(str(i))
            self.ui.In.addItem(str(i))

        self.initUi()

    def initUi(self):
        # Кнопочки
        self.ui.zero.clicked.connect(lambda: self.entry_field(0))
        self.ui.one.clicked.connect(lambda: self.entry_field(1))
        self.ui.two.clicked.connect(lambda: self.entry_field(2))
        self.ui.three.clicked.connect(lambda: self.entry_field(3))
        self.ui.four.clicked.connect(lambda: self.entry_field(4))
        self.ui.five.clicked.connect(lambda: self.entry_field(5))
        self.ui.six.clicked.connect(lambda: self.entry_field(6))
        self.ui.seven.clicked.connect(lambda: self.entry_field(7))
        self.ui.eight.clicked.connect(lambda: self.entry_field(8))
        self.ui.nine.clicked.connect(lambda: self.entry_field(9))
        self.ui.A.clicked.connect(lambda: self.entry_field('A'))
        self.ui.B.clicked.connect(lambda: self.entry_field('B'))
        self.ui.C.clicked.connect(lambda: self.entry_field('C'))
        self.ui.D.clicked.connect(lambda: self.entry_field('D'))
        self.ui.F.clicked.connect(lambda: self.entry_field('F'))
        # self.ui.Point.clicked.connect(lambda: self.entry_field('.'))
        self.ui.Backsp.clicked.connect(lambda: self.ui.lineEdit.backspace())
        self.ui.CE.clicked.connect(lambda: self.ui.lineEdit.clear())
        self.ui.execute.clicked.connect(lambda: self.convert())

    # Заполнение поля ввода
    def entry_field(self, sumb):
        if self.ui.lineEdit.text() == "Введите число" or self.ui.lineEdit.text(
        ) == "0":
            self.ui.lineEdit.clear()
        # print(self.ui.lineEdit.text())
        self.ui.lineEdit.setText(self.ui.lineEdit.text() + str(sumb))

    # Заполненеи поля результата
    def output_field(self, res):
        self.ui.lineEdit_2.clear()
        self.ui.lineEdit_2.setText(str(res))

    # Ф-я расчета
    def convert(self):
        try:
            self.output_field(
                convert_base(self.ui.lineEdit.text(),
                             self.ui.In.currentIndex() + 2,
                             self.ui.Of.currentIndex() + 2))
        except:
            self.output_field("Выбра неверная с/c")
Пример #52
0
    hwd.actionEnglish.triggered.connect(
        lambda: set_menu_langugage_english(hwd))
    hwd.actionJapanese.triggered.connect(
        lambda: set_menu_langugage_japanese(hwd))
    hwd.actionAbout.triggered.connect(about)


class MyDialog(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyDialog, self).__init__()
        self.ffmpeg = None

    def closeEvent(self, evnt):
        super(MyDialog, self).closeEvent(evnt)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = MyDialog()
    #MainWindow.setUnifiedTitleAndToolBarOnMac(True)
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    ui.app = app
    ui.win = MainWindow
    set_up_actions(ui)

    MainWindow.show()
    sys.exit(app.exec_())
Пример #53
0
class StartQt(QtGui.QMainWindow):
    conf = "conf.ini"
    assets = "assets/"
    activeDb = ""
    activeTable = ""
    type_id = 35
    to_check = ["delete","drop","truncate"]
    to_add_server = ["Name","Host","Username","Password"]
    
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initSlots()
        self.initMenu()
    def setStatus(self, text):
        self.statusBar().showMessage(text)
    def initSlots(self):
        self.statusBar()
        self.ui.clear_button.clicked.connect(self.clearAction)
        self.ui.new_button.clicked.connect(self.newAction)
        self.ui.query_button.clicked.connect(self.queryAction)
        self.ui.list.clicked.connect(self.listAction())
        self.ui.new_server.triggered.connect(self.addServer())
    def initMenu(self):
        self.config = ConfigParser.ConfigParser()
        # os.path.expanduser('~') + '/' + self.ssqb_dir + '/' + 
        self.ui.servers_menu.clear()
        self.config.read(self.conf)
        for name in self.config._sections:
            item = QtGui.QAction(QtGui.QIcon(self.assets+"database_connect.png"), name, self)
            item.triggered.connect(self.dbConnect(self.config._sections[name]["host"], self.config._sections[name]["user"], self.config._sections[name]["pass"]))
            self.ui.servers_menu.addAction(item);
    def progressBar(self):
        pass
    def queryAction(self):
        activeTab = self.ui.tab.currentWidget()
        queryField = activeTab.findChild(QtGui.QPlainTextEdit)
        sql = queryField.toPlainText()
        proceed = True
        danger = False
        for word in self.to_check:
            if word in sql.toLower():
                danger = True
                self.danger_word = word
                msg = "Are you sure you want to %s?" % word
                reply = QtGui.QMessageBox.question(self, 'Message', msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
                if reply == QtGui.QMessageBox.No:
                    proceed = False
                    break
        if not proceed:    
            pass
        else:
            self.progress = QtGui.QProgressDialog("Please Wait", "Cancel", 0, 100, self.ui.result_table)
            self.progress.setWindowModality(QtCore.Qt.WindowModal)
            self.progress.setAutoReset(True)
            self.progress.setAutoClose(True)
            self.progress.setMinimum(0)
            self.progress.setMaximum(100)
            self.progress.resize(800,220)
            self.progress.setWindowTitle("Running Query")
            self.progress.show()
            self.progress.setValue(0)
            self.progress.setValue(10)

            self.db.query(str(sql))
            self.progress.setValue(25)
            if danger:
                QtGui.QMessageBox.information(self,"Message","Item was %s" % self.danger_word)
            self.showResults()
    def showResults(self):
        
        fields = self.db.getFields()
        rows = self.db.getRows()
        self.progress.setValue(30)
        self.ui.result_table.clear()
        self.ui.result_table.setColumnCount(len(fields))
        self.ui.result_table.setRowCount(len(rows))
        header = self.ui.result_table.horizontalHeader()
        self.ui.result_table.setHorizontalHeaderLabels(fields)
        i = 1
        for row in rows:
            j = 0
            for v in row:
                item = QtGui.QTableWidgetItem(str(v))
                if i % 2:
                    item.setBackgroundColor(QtGui.QColor(221,221,221))
                self.ui.result_table.setItem(i,j,item)
                j += 1
            i += 1
        self.progress.setValue(100)    
        self.progress.hide()        
        header.setStretchLastSection(True)
        #header.setResizeMode(QtGui.QHeaderView.Stretch)
        self.ui.result_table.setVisible(False)
        self.ui.result_table.resizeColumnsToContents()
        self.ui.result_table.resizeRowsToContents()
        self.ui.result_table.setVisible(True)
    def clearAction(self):
        self.ui.query_field.clear()
    def newAction(self):
        next_id = self.ui.tab.count() + 1
        new_tab = QtGui.QWidget()
        new_tab.setObjectName(_fromUtf8("tab_%i" % next_id))
        new_query_field = QtGui.QPlainTextEdit(new_tab)
        new_query_field.setGeometry(QtCore.QRect(0, 0, 711, 161))
        new_query_field.setObjectName(_fromUtf8("query_field"))        
        vl = QtGui.QVBoxLayout(new_tab)
        vl.addWidget(new_query_field)
        self.ui.tab.addTab(new_tab, _fromUtf8("")) 
        self.ui.tab.setTabText(self.ui.tab.indexOf(new_tab), QtGui.QApplication.translate("MainWindow", "Tab %i" % next_id, None, QtGui.QApplication.UnicodeUTF8)) 
        self.ui.tab.setCurrentIndex(self.ui.tab.indexOf(new_tab))  
    def addServer(self):
        def callback():
            self.dialog = QtGui.QWidget()
            save = QtGui.QPushButton("Save")
            test = QtGui.QPushButton("Test")
            cancel = QtGui.QPushButton("Cancel")
            cancel.clicked.connect(self.clearForm())
            test.clicked.connect(self.testConnect())
            save.clicked.connect(self.saveServer())
            hbox = QtGui.QHBoxLayout()
            vbox = QtGui.QVBoxLayout()

            for field in self.to_add_server:
                item = QtGui.QLineEdit()
                if field == "Password":
                    item.setEchoMode(QtGui.QLineEdit.Password)
                item.setObjectName(field.lower())
                label = QtGui.QLabel(item)
                label.setText(field + ":")
                vbox.addWidget(label)
                vbox.addWidget(item)
            hbox.addStretch(1)
            hbox.addWidget(test)
            hbox.addWidget(save)
            hbox.addWidget(cancel)

            vbox.addStretch(1)
            vbox.addLayout(hbox)
            
            self.dialog.setLayout(vbox)
            self.dialog.move(QtGui.QApplication.desktop().screen().rect().center() - self.rect().center())            
            self.dialog.show()
        return callback
    def clearForm(self):
        def callback():
            sender = self.sender()
            widget = sender.parent()
            for a in widget.findChildren(QtGui.QLineEdit):
                a.clear()
            widget.close()
        return callback 
    def testConnect(self):
        def callback():
            sender = self.sender()
            widget = sender.parent()
            tmp = {}
            for a in widget.findChildren(QtGui.QLineEdit):
                tmp[str(a.objectName())] = str(a.text())
            try:
                con = MySQLdb.connect(tmp['host'], tmp['username'], tmp['password'])
                msg = "Connection successful, WOOT!"
            except:
                msg = "Awwww. Sorry, that info didn't work."
                pass
            QtGui.QMessageBox.information(widget, "Connection Test to %s" % tmp['host'], msg)
        return callback
    def saveServer(self):
        def callback():
            sender = self.sender()
            widget = sender.parent()
            tmp = {}
            for a in widget.findChildren(QtGui.QLineEdit):
                tmp[str(a.objectName())] = str(a.text())
            self.config.add_section(tmp["name"])
            self.config.set(tmp["name"], "host", tmp["host"])
            self.config.set(tmp["name"], "user", tmp["username"])
            self.config.set(tmp["name"], "pass", tmp["password"])
            with open(self.conf, 'wb') as configfile:
                self.config.write(configfile)            
            for a in widget.findChildren(QtGui.QLineEdit):
                a.clear()
            widget.close()
            self.initMenu()
            QtGui.QMessageBox.information(self, "Message", "Connection Saved!")
        return callback
    def dbConnect(self, host, user, passwrd):
        def callback():
            self.db = SsqbDb(host,user,passwrd)
            databases = self.db.getDbs()
            self.ui.list.clear()
            for db in databases:
                item = QtGui.QListWidgetItem(db['Database'])
                item.setData(self.type_id, "db")
                self.ui.list.addItem(item)
        return callback
    def listAction(self):
        def callback():
            sender = self.sender()
            item = sender.currentItem()
            item_type = item.data(self.type_id)
            if item_type == "db":
                rtn = self.dbUseDb()
            elif item_type == "table":
                rtn = self.dbUseTable()
        return callback
    def dbUseDb(self):
        sender = self.sender()
        self.activeDb = item = sender.currentItem().text()
        query = "USE %s" % item
        self.db.queryNoVals(query)
        self.setStatus("%s is now the active database" % item)
        tables = self.db.getTables(item)
        self.ui.list.clear()
        for table in tables:
            item = QtGui.QListWidgetItem(table[0])
            item.setData(self.type_id, "table")
            self.ui.list.addItem(item)
    def dbUseTable(self):
        sender = self.sender()
        self.activeTable = item = sender.currentItem().text()
        query = "SELECT * FROM %s LIMIT 1000" % item
        self.setStatus("%s is now the active table" % item)
        self.activeTab = self.ui.tab.currentWidget()
        self.activeQueryField = self.activeTab.findChild(QtGui.QPlainTextEdit)
        self.activeQueryField.setPlainText(query)
Пример #54
0
class Gui(QMainWindow):
    """ 
    Main GUI Class
    contains the main function and interfaces between 
    the GUI and functions
    """
    def __init__(self,parent=None):
        QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        """ Set GUI to track mouse """
        QWidget.setMouseTracking(self,True)

        """
        Dynamixel bus
        TODO: add other motors here as needed with their correct address"""
        self.dxlbus = DXL_BUS(DEVICENAME, BAUDRATE)
        port_num = self.dxlbus.port()
        base = DXL_MX(port_num, 1)
        shld = DXL_MX(port_num, 2)
        elbw = DXL_MX(port_num, 3)
        wrst = DXL_AX(port_num, 4)
        wrst2 = DXL_AX(port_num, 5)
        wrst3 = DXL_XL(port_num, 6)
        gripper = DXL_XL(port_num, 7)

        """Objects Using Other Classes"""
        self.kinect = Kinect()
        self.rexarm = Rexarm((base,shld,elbw,wrst,wrst2,wrst3),gripper)
        self.tp = TrajectoryPlanner(self.rexarm)
        self.sm = StateMachine(self.rexarm, self.tp, self.kinect)
    
        """ 
        Attach Functions to Buttons & Sliders
        TODO: NAME AND CONNECT BUTTONS AS NEEDED
        """
        self.ui.btn_exec.clicked.connect(self.execute)


        self.ui.btn_estop.clicked.connect(self.estop)
        
        self.ui.btnUser1.setText("Calibrate")
        self.ui.btnUser1.clicked.connect(partial(self.sm.set_next_state, "calibrate"))
        
        self.ui.sldrBase.valueChanged.connect(self.sliderChange)
        self.ui.sldrShoulder.valueChanged.connect(self.sliderChange)
        self.ui.sldrElbow.valueChanged.connect(self.sliderChange)
        self.ui.sldrWrist.valueChanged.connect(self.sliderChange)
        self.ui.sldrWrist2.valueChanged.connect(self.sliderChange)
        self.ui.sldrWrist3.valueChanged.connect(self.sliderChange)
        #self.ui.sldrGrip1.valueChanged.connect(self.sliderChange)

        self.ui.sldrMaxTorque.valueChanged.connect(self.sliderChange)
        self.ui.sldrSpeed.valueChanged.connect(self.sliderChange)
        self.ui.chk_directcontrol.stateChanged.connect(self.directControlChk)
        self.ui.rdoutStatus.setText("Waiting for input")

        """Team10 section for buttons"""
        self.ui.btnUser2.setText("teach")
        self.ui.btnUser2.clicked.connect(partial(self.sm.set_next_state, "teach"))

        self.ui.btnUser3.setText("repeat")
        self.ui.btnUser3.clicked.connect(partial(self.sm.set_next_state, "repeat"))
        
        self.ui.btnUser4.setText("Set ROI")
        self.ui.btnUser4.clicked.connect(partial(self.sm.set_next_state, "set_roi"))

        self.ui.btnUser5.setText("Set Exclusion")
        self.ui.btnUser5.clicked.connect(partial(self.sm.set_next_state, "set_exclusion"))

        self.ui.btnUser6.setText("Save frames")
        self.ui.btnUser6.clicked.connect(partial(self.sm.set_next_state, "save_frames"))


        self.ui.btn_task3.clicked.connect(partial(self.sm.set_next_state, "task3"))

        self.ui.btnUser7.setText("Click & Grab")
        self.ui.btnUser7.clicked.connect(partial(self.sm.set_next_state, "ClickandGrab"))
 

        """initalize manual control off"""
        self.ui.SliderFrame.setEnabled(False)

        """initalize rexarm"""
        self.rexarm.initialize()

        """Setup Threads"""
        self.videoThread = VideoThread(self.kinect)
        self.videoThread.updateFrame.connect(self.setImage)        
        self.videoThread.start()

        
        self.logicThread = LogicThread(self.sm)
        self.logicThread.start()
        

        self.displayThread = DisplayThread(self.rexarm, self.sm)
        self.displayThread.updateJointReadout.connect(self.updateJointReadout)
        self.displayThread.updateEndEffectorReadout.connect(self.updateEndEffectorReadout)
        self.displayThread.updateStatusMessage.connect(self.updateStatusMessage)
        self.displayThread.start()

        """ 
        Setup Timer 
        this runs the trackMouse function every 50ms
        """
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.trackMouse)
        self._timer.start(50)

    """ Slots attach callback functions to signals emitted from threads"""

    @pyqtSlot(QImage, QImage, QImage, QImage)
    def setImage(self, rgb_image, depth_image, level_image, superpose_frame):
        if(self.ui.radioVideo.isChecked()):
            self.ui.videoDisplay.setPixmap(QPixmap.fromImage(rgb_image))
        if(self.ui.radioDepth.isChecked()):
            self.ui.videoDisplay.setPixmap(QPixmap.fromImage(depth_image))
        if(self.ui.radioUsr2.isChecked()):
            self.ui.videoDisplay.setPixmap(QPixmap.fromImage(level_image))
        if(self.ui.radioUsr1.isChecked()):
            self.ui.videoDisplay.setPixmap(QPixmap.fromImage(superpose_frame))

    @pyqtSlot(list)
    def updateJointReadout(self, joints):
        self.ui.rdoutBaseJC.setText(str("%+.2f" % (joints[0]*R2D)))
        self.ui.rdoutShoulderJC.setText(str("%+.2f" % ((joints[1]*R2D)+90.0)))
        self.ui.rdoutElbowJC.setText(str("%+.2f" % (joints[2]*R2D)))
        self.ui.rdoutWristJC.setText(str("%+.2f" % (joints[3]*R2D)))
        self.ui.rdoutWrist2JC.setText(str("%+.2f" % (joints[4]*R2D)))
        self.ui.rdoutWrist3JC.setText(str("%+.2f" % (joints[4]*R2D)))

        if(len(joints)>5):
            self.ui.rdoutWrist3JC.setText(str("%+.2f" % (joints[5]*R2D)))

        else:
            self.ui.rdoutWrist3JC.setText(str("N.A."))

    @pyqtSlot(list)
    def updateEndEffectorReadout(self, pos):
        self.ui.rdoutX.setText(str("%+.2f" % (pos[0])))
        self.ui.rdoutY.setText(str("%+.2f" % (pos[1])))
        self.ui.rdoutZ.setText(str("%+.2f" % (pos[2])))
        self.ui.rdoutT.setText(str("%+.2f" % (pos[3])))
        self.ui.rdoutG.setText(str("%+.2f" % (pos[4])))
        self.ui.rdoutP.setText(str("%+.2f" % (pos[5])))

    @pyqtSlot(str)
    def updateStatusMessage(self, msg):
        self.ui.rdoutStatus.setText(msg)


    """ Other callback functions attached to GUI elements"""
    def execute(self):
        #self.rexarm.set_positions()
        self.sm.set_next_state("execute")

    def estop(self):
        self.rexarm.estop = True
        self.sm.set_next_state("estop")

    def sliderChange(self):
        """ 
        Function to change the slider labels when sliders are moved
        and to command the arm to the given position
        """
        self.ui.rdoutBase.setText(str(self.ui.sldrBase.value()))
        self.ui.rdoutShoulder.setText(str(self.ui.sldrShoulder.value()))
        self.ui.rdoutElbow.setText(str(self.ui.sldrElbow.value()))
        self.ui.rdoutWrist.setText(str(self.ui.sldrWrist.value()))
        self.ui.rdoutWrist2.setText(str(self.ui.sldrWrist2.value()))
        self.ui.rdoutWrist3.setText(str(self.ui.sldrWrist3.value()))
        #self.ui.rdoutGrip1.setText(str(self.ui.sldrGrip1.value()))

        self.ui.rdoutTorq.setText(str(self.ui.sldrMaxTorque.value()) + "%")
        self.ui.rdoutSpeed.setText(str(self.ui.sldrSpeed.value()) + "%")
        self.rexarm.set_torque_limits([self.ui.sldrMaxTorque.value()/100.0]*self.rexarm.num_joints, update_now = False)
        self.rexarm.set_speeds_normalized_global(self.ui.sldrSpeed.value()/100.0, update_now = False)
        joint_positions = np.array([self.ui.sldrBase.value()*D2R, 
                           self.ui.sldrShoulder.value()*D2R,
                           self.ui.sldrElbow.value()*D2R,
                           self.ui.sldrWrist.value()*D2R,
                           self.ui.sldrWrist2.value()*D2R,
                           self.ui.sldrWrist3.value()*D2R])
        self.rexarm.set_positions(joint_positions, update_now = False)
        #self.rexarm.gripper.set_position(self.ui.sldrGrip1.value()*D2R)

    def directControlChk(self, state):
        if state == Qt.Checked:
            self.sm.set_next_state("manual")
            self.ui.SliderFrame.setEnabled(True)
        else:
            self.sm.set_next_state("idle")
            self.ui.SliderFrame.setEnabled(False)

    def trackMouse(self):
        """ 
        Mouse position presentation in GUI
        TODO: after implementing workspace calibration 
        display the world coordinates the mouse points to 
        in the RGB video image.
        """

        x = QWidget.mapFromGlobal(self,QCursor.pos()).x()
        y = QWidget.mapFromGlobal(self,QCursor.pos()).y()
        if ((x < MIN_X) or (x >= MAX_X) or (y < MIN_Y) or (y >= MAX_Y)):
            self.ui.rdoutMousePixels.setText("(-,-,-)")
            self.ui.rdoutMouseWorld.setText("(-,-,-)")
        else:
            x = x - MIN_X
            y = y - MIN_Y
            if(self.kinect.currentDepthFrame.any() != 0):
                z = self.kinect.currentDepthFrame[y][x]
                self.ui.rdoutMousePixels.setText("(%.0f,%.0f,%.0f)" % (x,y,z))
                PointCameraFrm = self.kinect.ConvertImagePointToCameraFrame(np.array([x,y]))
                PointWorldFrm = self.kinect.ConvertCameraFrametoWorlFrame(PointCameraFrm)
                #self.ui.rdoutMouseWorld.setText("(-,-,-)")
                self.ui.rdoutMouseWorld.setText("(%.3f,%.3f,%.3f)" % (PointWorldFrm[0],PointWorldFrm[1],PointWorldFrm[2]))

    def mousePressEvent(self, QMouseEvent):
        """ 
        Function used to record mouse click positions for calibration 
        """
 
        """ Get mouse posiiton """
        x = QMouseEvent.x()
        y = QMouseEvent.y()

        """ If mouse position is not over the camera image ignore """
        if ((x < MIN_X) or (x > MAX_X) or (y < MIN_Y) or (y > MAX_Y)): return

        """ Change coordinates to image axis """
        self.kinect.last_click[0] = x - MIN_X 
        self.kinect.last_click[1] = y - MIN_Y
        if (self.kinect.kinectCalibrated == True):
            self.kinect.PointCamera_last_click = self.kinect.ConvertImagePointToCameraFrame(np.array([x - MIN_X, y - MIN_Y]))
            self.kinect.PointWorld_last_click  = self.kinect.ConvertCameraFrametoWorlFrame(self.kinect.PointCamera_last_click)
            for i in range(10):
                self.kinect.BlockCenter, self.kinect.BlockOrientation_last_click  = self.kinect.SelectBlock(np.array([ self.kinect.last_click[0], self.kinect.last_click[1]]))
                if not np.array_equal(self.kinect.BlockCenter,np.array([0.0, 0.0, 0.0])):
                    self.kinect.PointWorld_last_click  = self.kinect.BlockCenter
                    #print("Coodinates: "+str(self.kinect.PointWorld_last_click))
                    #print("Orientation: "+str(self.kinect.BlockOrientation_last_click))
                    break
                time.sleep(0.010)
        print("Wold point selected: "+str(self.kinect.PointWorld_last_click))
        print("Orientation: " +str(self.kinect.BlockOrientation_last_click))
        self.kinect.new_click = True
Пример #55
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        
        # UI Setup
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # Set the default icons for UI actions
        self.ui.actionNew.setIcon(QtGui.QIcon.fromTheme("document-new"))
        self.ui.actionOpen.setIcon(QtGui.QIcon.fromTheme("document-open"))
        self.ui.actionSave.setIcon(QtGui.QIcon.fromTheme("document-save"))
        self.ui.actionSave_As.setIcon(QtGui.QIcon.fromTheme("document-save-as"))
        self.ui.actionPrint.setIcon(QtGui.QIcon.fromTheme("document-print"))
        self.ui.actionQuit.setIcon(QtGui.QIcon.fromTheme("system-log-out"))
        self.ui.actionUndo.setIcon(QtGui.QIcon.fromTheme("edit-undo"))
        self.ui.actionRedo.setIcon(QtGui.QIcon.fromTheme("edit-redo"))
        self.ui.actionCut.setIcon(QtGui.QIcon.fromTheme("edit-cut"))
        self.ui.actionCopy.setIcon(QtGui.QIcon.fromTheme("edit-copy"))
        self.ui.actionPaste.setIcon(QtGui.QIcon.fromTheme("edit-paste"))
        self.ui.actionDelete.setIcon(QtGui.QIcon.fromTheme("edit-delete"))
        self.ui.actionPreferences.setIcon(QtGui.QIcon.fromTheme("preferences"))
        self.ui.actionAbout.setIcon(QtGui.QIcon.fromTheme("help-browser"))
        self.ui.actionRun.setIcon(QtGui.QIcon.fromTheme("go-next"))
        # UI ToolBox
        self.buttonGroup = QtGui.QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonGroup.buttonClicked[int].connect(self.toolBoxButtonClicked)
        self.toolBox = self.ui.componentBrowser
        # Populate the toolbox
        self.createToolBox()  
        # Create a scene for the GraphicsView
        self.scene=DiagramScene()
        self.ui.graphicsView.setScene(self.scene)
        self.scene.setSceneRect(0,0,600,400)
        # Make it bigger
        self.setWindowState(QtCore.Qt.WindowMaximized)
        # Create an UNDO stack and view
        self.undoStack = QtGui.QUndoStack(self)
        self.undoView = QtGui.QUndoView(self.undoStack)
        self.undoView.setWindowTitle("Undo View")
        self.undoView.show()
        self.undoView.setAttribute(QtCore.Qt.WA_QuitOnClose, False)
        self.createActions()
        self.createMenus()
        # Set the window title      
        self.setWindowTitle("Schematix")
    def createActions(self):
        self.ui.actionDelete = QtGui.QAction("&Delete Item", self)
        self.ui.actionDelete.setShortcut("Del");
        QtCore.QObject.connect(self.ui.actionDelete,
                               QtCore.SIGNAL("triggered()"),
                               self.deleteItem)
                               
#        QtCore.QObject.connect(self.scene,
#                               QtCore.SIGNAL("itemMoved()"),
#                               self.itemMoved)
                               
        self.scene.itemMoved.connect(self.itemMoved)
        self.ui.actionUndo = self.undoStack.createUndoAction(self, "&Undo")
        self.ui.actionUndo.setShortcuts(QtGui.QKeySequence.Undo)
        self.ui.actionRedo = self.undoStack.createRedoAction(self, "&Redo")
        self.ui.actionRedo.setShortcuts(QtGui.QKeySequence.Redo)
    def createMenus(self):
        self.newEditMenu = self.ui.menubar.addMenu("&EditNew")
        self.newEditMenu.addAction(self.ui.actionUndo)
        self.newEditMenu.addAction(self.ui.actionRedo)
        self.newEditMenu.addSeparator()
        self.newEditMenu.addAction(self.ui.actionDelete)
        
        
        
        
        QtCore.QObject.connect(self.ui.menuEdit,
                               QtCore.SIGNAL("aboutToShow()"),
                               self.itemMenuAboutToShow)
        QtCore.QObject.connect(self.ui.menuEdit,
                               QtCore.SIGNAL("aboutToHide()"),
                               self.itemMenuAboutToHide)
                    
    def itemMenuAboutToHide(self):
        self.ui.actionDelete.setEnabled(True)
    def itemMenuAboutToShow(self):
        self.ui.actionDelete.setEnabled(len(self.scene.selectedItems())!=0)
    def deleteItem(self):
        print "Delete called..."
        if (len(self.scene.selectedItems()) == 0):
            return
        deleteCommand = DeleteCommand(self.scene)
        self.undoStack.push(deleteCommand);
    def addComponent(self, component):
        # TODO: Make it so that the component has to be dragged onto the
        # canvas from the toolbox, or clicked once in the toolbox and then
        # clicked again on the canvas to place or right click/esc to cancel.
        action = AddCommand(component, self.scene)
        self.undoStack.push(action)
    def itemMoved(self, movedItem, oldPosition):
        print "MAINWINDOW: An item in the graphics view got moved..."
        self.undoStack.push(MoveCommand(movedItem, oldPosition))
    def createToolBox(self):
        """ Populates the toolbox widget of the main UI with components
        from the component library """ 
        id = 0
        # Parse the component library and add components to the toolbox 
        for library_name, library in components:
            # At this level of the loop we have a library of components
            # Create a new section on the toolbox for this library and add
            # its components as buttons
            layout = QtGui.QGridLayout()
            x = 0
            y = 0
            for component in library:
                # For each component, add a button
                title = component["name"]
                layout.addWidget(self.createCellWidget(title,id), y, x)
                id += 1
                if x >= 1:
                    x = 0
                    y += 1
                else:
                    x += 1
            layout.setRowStretch(3, 10)
            layout.setColumnStretch(2, 10)
            itemWidget = QtGui.QWidget()
            itemWidget.setLayout(layout)
            self.toolBox.addItem(itemWidget, library_name)
    def createCellWidget(self, text, id):
        """ Create a button for the toolbox """
        button = QtGui.QToolButton()
        button.setIcon(QtGui.QIcon.fromTheme("emblem-symbolic-link"))
        button.setIconSize(QtCore.QSize(32, 32))
        button.setText(text)
        self.buttonGroup.addButton(button, id)
        layout = QtGui.QGridLayout()
        layout.addWidget(button, 0, 0, QtCore.Qt.AlignHCenter)
        layout.addWidget(QtGui.QLabel(text), 1, 0, QtCore.Qt.AlignCenter)
        widget = QtGui.QWidget()
        widget.setLayout(layout)
        return widget                   
    def toolBoxButtonClicked(self, id):
        """ Event handler for tool box button clicks. For now just add to the
        diagram the component that was clicked by the user """
        # TODO: Add graphics for different block types
        # TODO: Allow components to be 'dragged' from the toolbox onto the
        # canvas
        # TODO: Show contextual help if the mouse is hovered over an item in
        # the toolbox showing information about the relevant component
        buttons = self.buttonGroup.buttons()
        for button in buttons:
            if self.buttonGroup.button(id) != button:
                button.setChecked(False)
        sender = self.buttonGroup.button(id).text()
        self.ui.ObjectInspectorText.setText(sender)
        self.addComponent(id)