Esempio n. 1
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MOVE WINDOW
        def moveWindow(event):
            # RESTORE BEFORE MOVE
            if UIFunctions.returnStatus() == 1:
                UIFunctions.maximize_restore(self)

            # IF LEFT CLICK MOVE WINDOW
            if event.buttons() == Qt.LeftButton:
                self.move(self.pos() + event.globalPos() - self.dragPos)
                self.dragPos = event.globalPos()
                event.accept()

        # SET TITLE BAR
        self.ui.title_bar.mouseMoveEvent = moveWindow

        ## ==> SET UI DEFINITIONS
        UIFunctions.uiDefinitions(self)

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()

    ## APP EVENTS
    ########################################################################
    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()
Esempio n. 2
0
class BrowserWindow(QtGui.QWidget):
    """Das Hauptfenster des Browsers."""
    def __init__(self, *args):
        QtGui.QMainWindow.__init__(self, *args)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.createConnects()

    def createConnects(self):
        self.ui.editAddress.returnPressed.connect(self.loadPage)
        self.ui.webView.urlChanged.connect(self.updateUrl)
        self.ui.buttonBack.clicked.connect(self.ui.webView.back)
        self.ui.buttonForward.clicked.connect(self.ui.webView.forward)
        self.ui.buttonReload.clicked.connect(self.ui.webView.reload)

    @QtCore.pyqtSlot(QtCore.QUrl)
    def updateUrl(self, url):
        self.ui.editAddress.setText(url.toString())

    @QtCore.pyqtSlot()
    def loadPage(self):
        stringUrl = unicode(self.ui.editAddress.text())
        if not re.search(r"^http", stringUrl):
            stringUrl = "http://" + stringUrl
        url = QtCore.QUrl(stringUrl)
        self.ui.webView.load(url)
        self.ui.editAddress.clearFocus()
Esempio n. 3
0
class BrowserWindow(QtGui.QWidget):
    """Das Hauptfenster des Browsers."""

    def __init__(self, *args):
        QtGui.QMainWindow.__init__(self, *args)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.createConnects()

    def createConnects(self):
        self.ui.editAddress.returnPressed.connect(self.loadPage)
        self.ui.webView.urlChanged.connect(self.updateUrl)
        self.ui.buttonBack.clicked.connect(self.ui.webView.back)
        self.ui.buttonForward.clicked.connect(self.ui.webView.forward)
        self.ui.buttonReload.clicked.connect(self.ui.webView.reload)

    @QtCore.pyqtSlot(QtCore.QUrl)
    def updateUrl(self, url):
        self.ui.editAddress.setText(url.toString())

    @QtCore.pyqtSlot()
    def loadPage(self):
        stringUrl = unicode(self.ui.editAddress.text())
        if not re.search(r"^http", stringUrl):
            stringUrl = "http://" +stringUrl
        url = QtCore.QUrl(stringUrl)
        self.ui.webView.load(url)
        self.ui.editAddress.clearFocus()
Esempio n. 4
0
class AppWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        def moveWindow(event):
            if UIFunctions.returnStatus(self) == 1:
                UIFunctions.maximize_restore(self)
            if event.buttons() == Qt.LeftButton:
                self.move(self.pos() + event.globalPos() - self.dragPos)
                self.dragPos = event.globalPos()
                event.accept()

        self.ui.frame_titleBar_title.mouseMoveEvent = moveWindow
        UIFunctions.uiDefinitions(self)
    
    # EVENT
    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()

    def resizeEvent(self, event):
        return super(AppWindow, self).resizeEvent(event)
Esempio n. 5
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ## TOGGLE SUB MENUS
        ########################################################################
        #self.ui.Btn_Toggle.clicked.connect(lambda: UIFunctions.toggleMenu(self, 200, True))
        self.ui.Btn_hpc.clicked.connect(lambda: UIFunctions.openSubMenu(
            self, 240, self.ui.frame_hpc, True))
        self.ui.Btn_spc.clicked.connect(lambda: UIFunctions.openSubMenu(
            self, 240, self.ui.frame_spc, True))
        self.ui.Btn_dpc.clicked.connect(lambda: UIFunctions.openSubMenu(
            self, 240, self.ui.frame_dpc, True))
        self.ui.Btn_ssc.clicked.connect(lambda: UIFunctions.openSubMenu(
            self, 240, self.ui.frame_ssc, True))
        self.ui.Btn_alc.clicked.connect(lambda: UIFunctions.openSubMenu(
            self, 240, self.ui.frame_alc, True))
        self.ui.Btn_cmt.clicked.connect(lambda: UIFunctions.openSubMenu(
            self, 240, self.ui.frame_cmt, True))

        ## NAVIGATING PAGES
        self.ui.Btn_spc_main.clicked.connect(
            lambda: UIFunctions.handleButton(self, 1))
        self.ui.Btn_hpc_main.clicked.connect(
            lambda: UIFunctions.handleButton(self, 0))
        self.ui.Btn_hpc_mat.clicked.connect(
            lambda: UIFunctions.handleButton(self, 2))

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
Esempio n. 6
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle('Knowledge On The Go')

        self.ui.Btn_Toggle.clicked.connect(lambda: UIFunctions.toggle_menu(self, 250, True))

        # PAGE 1 - Dictionary
        self.ui.btn_page_1.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_1))

        # PAGE 2 - Wikipedia
        self.ui.btn_page_2.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_2))

        # PAGE 3 - Message-Server
        self.ui.btn_page_3.clicked.connect(lambda: self.server())

        # PAGE 4 - Message-Client
        self.ui.btn_page_4.clicked.connect(lambda: self.client())

    def server(self):
        print()
        print()
        import server

    def client(self):
        print()
        print()
        import client
Esempio n. 7
0
class MainWindow:
    def __init__(self, parent=None):
        self.main_win = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_win)

        self.ui.MakeMoneyButton.clicked.connect(self.on_MAKEMONEY_click)
        self.ui.lookupButton.clicked.connect(self.on_LOOKUP_click)

    def show(self):
        self.main_win.show()

    def on_LOOKUP_click(self):
        userSymbol = self.ui.stockSymbol.text().upper()
        lookup_info = "Current price of " + userSymbol + ": " + str(
            get_current_stock_price(userSymbol))
        self.ui.OutputText.setText(lookup_info)

    def on_MAKEMONEY_click(self):
        if self.ui.stockSymbol.hasAcceptableInput() == False:
            self.ui.OutputText.setText("Please enter a valid stock symbol")
        if self.ui.desiredMargins.text().isdigit() == False:
            self.ui.OutputText.setText("Please enter a number greater than 0")
        userSymbol = self.ui.stockSymbol.text().upper()
        userMargins = float(self.ui.desiredMargins.text()) / 100
        self.ui.OutputText.setText(marginBot(userSymbol, userMargins))
Esempio n. 8
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ## TOGGLE/BURGUER MENU
        ########################################################################
        self.ui.Btn_Toggle.clicked.connect(
            lambda: UIFunctions.toggleMenu(self, 250, True))

        ## PAGES
        ########################################################################

        # PAGE 1
        self.ui.btn_page_1.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_1))

        # PAGE 2
        self.ui.btn_page_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_2))

        # PAGE 3
        self.ui.btn_page_3.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_3))

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
Esempio n. 9
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ## PAGES
        ########################################################################

        # PAGE 1
        self.ui.btn_page_1.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_1))

        # PAGE 2
        self.ui.btn_page_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_2))

        # PAGE 3
        self.ui.btn_page_3.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_3))

        ########################################################################
        app.aboutToQuit.connect(lambda: UIFunctions.closeEvent(self))

        self.ui.pushButton.clicked.connect(
            lambda: UIFunctions.clickedButton(self))

        #self.ui.pushButton.clicked.connect(lambda: UIFunctions.clickedButton(self))
        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
class Main(QtGui.QMainWindow):
    """
    Módulo principal del sistema
    """
    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_Main()
        self.ui.setupUi(self)
        # Cargamos las acciones al presionar el menú
        self.menu_actions()
        self.show()
        self.activar()

    def menu_actions(self):
        self.ui.actionModulo_Clientes.triggered.connect(self.load_mod1)
        self.ui.actionMarcas.triggered.connect(self.load_mod2)
        self.ui.actionModelosAutos.triggered.connect(self.load_mod3)
        self.ui.actionLogin.triggered.connect(self.load_mod4)
        
    def load_mod1(self):
        """carga modulo clientes"""
        widget = Mod1(self)
        self.setCentralWidget(widget)

    def load_mod2(self):
        """
        carga modulo marcas
        """
        widget = Mod2(self)
        self.setCentralWidget(widget)

    def load_mod3(self):
        """
        carga modulo modelos
        """
        widget = Mod3(self)
        self.setCentralWidget(widget)

    def load_mod4(self):
        """
        carga modulo del login
        """
        widget = Mod4(self)
        self.setCentralWidget(widget)

    def activar(self):
        """
        Este metodo lo llamara el login para activar las
        opciones princupales [originalmente estan desasctivadas]
        """
        self.ui.actionModulo_Clientes.setEnabled(True)
        self.ui.actionMarcas.setEnabled(True)
        self.ui.actionModelosAutos.setEnabled(True)
Esempio n. 11
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MAIN WINDOW LABEL
        QtCore.QTimer.singleShot(
            1500, lambda: self.ui.label.setText(
                "<strong>THANKS</strong> FOR WATCHING"))
        QtCore.QTimer.singleShot(
            1500,
            lambda: self.setStyleSheet("background-color: #222; color: #FFF"))
Esempio n. 12
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        self.setFixedSize(self.width(), self.height())
        self.statusBar().setSizeGripEnabled(False)
        self.ui.lineEdit_email.setReadOnly(True)
        self.ui.lineEdit_name.setReadOnly(True)
        self.ui.lineEdit_password.setReadOnly(True)
        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
Esempio n. 13
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ## TOGGLE/BURGUER MENU
        ########################################################################
        self.ui.Btn_Toggle.clicked.connect(lambda: UIFunctions.toggleMenu(self, 250, True))


        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
Esempio n. 14
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ## DROP SHADOW EFFECT

        self.setAttribute(Qt.WA_TranslucentBackground)
        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(20)
        self.shadow.setXOffset(0)
        self.shadow.setYOffset(0)
        self.shadow.setColor(QColor(0, 0, 0, 60))
        self.ui.frame.setGraphicsEffect(self.shadow)
Esempio n. 15
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MAIN WINDOW LABEL
        QtCore.QTimer.singleShot(
            3000, lambda: self.ui.label.setText(
                "<strong>Thank You</strong> for using Mudra"))
        QtCore.QTimer.singleShot(
            1500,
            lambda: self.setStyleSheet("background-color: #222; color: #FFF"))

        window = tk.Tk()
        window.title("Mudra Camera Interface")
        window.iconphoto(False, tk.PhotoImage(file='mn.png'))
        window.geometry('500x500')
        window.configure(bg='#383A59')

        frame1 = tk.Frame(window)
        btn5 = tk.Button(frame1,
                         text='Upload File',
                         height=90,
                         width=230,
                         fg='black',
                         compound='left')

        btn4_image = Image.open('./main.png')
        btn4_image = btn4_image.resize((50, 50), Image.ANTIALIAS)
        btn4_image = ImageTk.PhotoImage(btn4_image)

        # --------------- Button -------------------#
        btn_font = font.Font(size=25)

        btn4 = tk.Button(frame1,
                         text='Launch',
                         height=90,
                         width=230,
                         fg='black',
                         command=record,
                         image=btn4_image,
                         compound='left')
        btn4['font'] = btn_font
        btn4.grid(row=5, pady=(20, 20), column=5)

        frame1.pack()
        window.mainloop()
Esempio n. 16
0
class MainWindow(QMainWindow):
    def __init__(self, client):
        super(MainWindow, self).__init__()
        self.client = client

        # Set up the user interface from Designer.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.info_group_box.setTitle("User: "******"%0.2f" % (balance / 100.0))
        pattern = "Pay %0.2f to %s" if balance < 0 else "Receive %0.2f from %s"

        self.ui.transactions_list.clear()
        for user, value in transactions.items():
            self.ui.transactions_list.addItem(pattern % (value / 100.0, user))

    def pending(self):
        if not self._pending_dialog:
            self._pending_dialog = PendingWidget(self.client)
        self._pending_dialog.refresh()
        self._pending_dialog.show()
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # SET VALUE TO 0
        self.ui.progressBar.setValue(0)

        # EXPAND BTN
        self.ui.btnExpand.clicked.connect(self.expand)

        # RETRACT BTN
        self.ui.btnRetract.clicked.connect(self.retract)

        # RESIZE MAIN WINDOW
        self.ui.btnResizeWindow.clicked.connect(
            lambda: self.resizeMainWindow(1200, 500))

        # SHOW WINDOW
        self.show()

    # FUNCTION TO EXPAND PROGRESS BAR OR ANOTHER WIDGET
    def expand(self):
        # CREATE ANIMATION
        self.animation = QPropertyAnimation(self.ui.progressBar, b"value")
        self.animation.setDuration(2000)
        self.animation.setStartValue(0)
        self.animation.setEndValue(100)
        self.animation.setEasingCurve(QtCore.QEasingCurve.Linear)
        self.animation.start()

    def retract(self):
        # CREATE ANIMATION
        self.animation = QPropertyAnimation(self.ui.progressBar, b"value")
        self.animation.setDuration(2000)
        self.animation.setStartValue(100)
        self.animation.setEndValue(0)
        self.animation.setEasingCurve(QtCore.QEasingCurve.Linear)
        self.animation.start()

    def resizeMainWindow(self, width, height):
        # CREATE ANIMATION
        self.animation = QPropertyAnimation(self, b"size")
        self.animation.setDuration(1000)
        self.animation.setEndValue(QtCore.QSize(width, height))
        self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuad)
        self.animation.start()
Esempio n. 18
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MOVE WINDOW
        def moveWindow(event):
            # RESTORE BEFORE MOVE
            if UIFunctions.returnStatus() == 1:
                UIFunctions.maximize_restore(self)

            # IF LEFT CLICK MOVE WINDOW
            if event.buttons() == Qt.LeftButton:
                self.move(self.pos() + event.globalPos() - self.dragPos)
                self.dragPos = event.globalPos()
                event.accept()

        # SET TITLE BAR
        self.ui.title_bar.mouseMoveEvent = moveWindow

        ## ==> SET UI DEFINITIONS
        UIFunctions.uiDefinitions(self)

        ## QTIMER ==> START
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.systemInformation)

        # TIMER IN MILLISECONDS
        self.timer.start(1000)

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()

    ## APP EVENTS
    ########################################################################
    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()
    
    ## SYSTEM INFORMATION
    def systemInformation(self):
        text = str(psutil.sensors_temperatures()['coretemp'][0])
        m = re.findall(r"\W current\D*(\d+.\d)", text)
        self.ui.label_22.setText(str(psutil.virtual_memory().percent) + "%")
        self.ui.label_18.setText(str(psutil.cpu_percent()) + "%")
        self.ui.label_20.setText("Temp: " + str(m[0]) + "C°")
Esempio n. 19
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.Btn_Toggle.clicked.connect(lambda: UIFunctions.toggleMenu(self, 250, True))


        self.ui.pushButton_15.clicked.connect(self.ui.client)
        self.ui.pushButton_2.clicked.connect(self.ui.client)
        self.ui.lineEdit.returnPressed.connect(self.ui.client)




        self.show()
Esempio n. 20
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.logger = logging.getLogger('MainWindow')
        self.ui = Ui_MainWindow()
        self.rootDir = Path(__file__).parent

        # UI Stuff
        self.ui.setupUi(self)
        self.ui_functions = ui_Functions(self, self.ui)
        self.ui_functions.setWindowTitle('Code Highlighter')
        self.setWindowIcon(QtGui.QIcon(os.path.join(self.rootDir, 'App.ico')))

        # Connectors
        self.ui.btn_close.clicked.connect(self.window_close)
        self.ui.btn_max.clicked.connect(self.ui_functions.maximize_restore)
        self.ui.btn_min.clicked.connect(self.showMinimized)

        # dialogexec("Heading", "Message", "icon", "Button1name", "button2name")
        # errorexec("Message", "icon", "buttonname")

        # focus Textfield
        self.ui.textEdit.selectAll()
        self.ui.textEdit.setFocus()

        # Clipboard https://pythonprogramminglanguage.com/pyqt-clipboard/n

    def dialogexec(self, heading, message, icon, btn1, btn2):
        self.dialog.dialogConstrict(self.dialog, heading, message, icon, btn1,
                                    btn2)
        self.dialog.exec_()

    def errorexec(self, heading, icon, btnOk):
        self.error.errorConstrict(self.error, heading, icon, btnOk)
        self.error.exec_()

    def closeEvent(self, event):
        """ catch the closing Event """
        print("X is clicked: I'm now closing ...")

    def window_close(self):
        """ exit the app """
        app.quit()
Esempio n. 21
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.file_explorer_widget = FileSystemView

        ## TOGGLE/BURGUER MENU
        ########################################################################

        ## PAGES
        ########################################################################



        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
Esempio n. 22
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.DF = pd.DataFrame([])

        ## TOP
        ########################################################################

        self.ui.BtnLoadDf.clicked.connect(lambda: DataFunc.get_data(self))

        ## PAGES
        ########################################################################

        # PAGE 1
        self.ui_page1 = Ui_Page1(self)

        # PAGE 2
        self.ui.Btn_Menu_2.clicked.connect(
            lambda: self.ui.Pages_Widget.setCurrentWidget(self.ui.page_2))

        # PAGE 3
        self.ui.Btn_Menu_3.clicked.connect(
            lambda: self.ui.Pages_Widget.setCurrentWidget(self.ui.page_3))

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()

    def eventFilter(self, source, event):
        if event.type() == QEvent.ContextMenu and source is self.ui.TablePlan:
            self.ui_page1.TableEvent(source, event)

        return super().eventFilter(source, event)
Esempio n. 23
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.logger = logging.getLogger('MainWindow')
        self.ui = Ui_MainWindow()
        self.rootDir = Path(__file__).parent
        self.dbDir = os.path.join(self.rootDir, "db")
        self.configFile = os.path.join(self.rootDir, 'src', 'config',
                                       'config.yaml')
        self.config = self.load_yml()

        # UI Stuff
        self.ui.setupUi(self)
        self.ui_functions = ui_Functions(self, self.ui)
        self.ui_functions.setWindowTitle(self.config['app']['title'])
        self.setWindowIcon(QtGui.QIcon(os.path.join(self.rootDir, 'App.ico')))

        # Connectors
        self.ui.btn_close.clicked.connect(self.window_close)
        self.ui.btn_max.clicked.connect(self.ui_functions.maximize_restore)
        self.ui.btn_min.clicked.connect(self.showMinimized)

        # Database Setup --------------------------
        self.db = Database(self.dbDir)

        # Setup Tables ----------------------------
        table_user = Users(self, "users")
        table_user.setup()

        QtCore.QTimer.singleShot(500, lambda: self.test())

    def test(self):
        """ only a Test Situation """
        dialog = Dialog()
        self.ui_functions.showDialog(dialog, "Information",
                                     "Heute ist ein \n schöner Tag", "warning",
                                     "Cancel", "OK")
        # which Button was pressed
        if dialog.leftButton is True:
            print("Left")
        if dialog.rightButton is True:
            print("Right")

    def closeEvent(self, event):
        """ catch the closing Event """
        print("X is clicked: I'm now closing ...")

    def createEmptyConfigFile(self):
        """ will create an Empty Config File """
        data = dict(app=dict(title='MyApp', ),
                    azure=dict(
                        client_id='xxxx',
                        client_secret='xxx',
                        tenant_id='xxx',
                    ))
        with open(self.configFile, 'w') as f:
            yaml.dump(data, f, sort_keys=False, default_flow_style=False)

    def load_yml(self):
        """ Load the yaml file config.yaml """
        if os.path.exists(self.configFile) is False:
            self.createEmptyConfigFile()
            self.logger.error("New config.yml File created ...")
            self.logger.error(
                "Please edit src/config/config.yml as needed ...")
            self.logger.error("- Exit -")
            sys.exit(-1)
        with open(self.configFile, 'rt') as f:
            yml = yaml.safe_load(f.read())
        return yml

    def window_close(self):
        """ exit the app """
        app.quit()
Esempio n. 24
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ########################################################################
        ## START - WINDOW ATTRIBUTES
        ########################################################################

        ## SET ==> WINDOW TITLE
        self.setWindowTitle('RENDER TIME CALCULATOR')
        UIFunctions.labelTitle(self, 'RENDER TIME CALCULATOR')
        UIFunctions.labelDescription(self,
                                     'Calculate a rendering time estimate')
        ## ==> END ##

        ## REMOVE ==> STANDARD TITLE BAR
        UIFunctions.removeTitleBar(True)
        ## ==> END ##

        ## REMOVE ==> STANDARD TITLE BAR
        self.resize(500, 800)
        self.setMinimumSize(QSize(500, 800))
        UIFunctions.enableMaximumSize(self, 500, 800)

        ## ==> END ##

        ## ==> MOVE WINDOW / MAXIMIZE / RESTORE
        ########################################################################
        def moveWindow(event):
            # IF MAXIMIZED CHANGE TO NORMAL
            if UIFunctions.returStatus() == 1:
                UIFunctions.maximize_restore(self)

            # MOVE WINDOW
            if event.buttons() == Qt.LeftButton:
                self.move(self.pos() + event.globalPos() - self.dragPos)
                self.dragPos = event.globalPos()
                event.accept()

        def dobleClickMaximizeRestore(event):
            # IF DOUBLE CLICK CHANGE STATUS
            if event.type() == QtCore.QEvent.MouseButtonDblClick:
                QtCore.QTimer.singleShot(
                    250, lambda: UIFunctions.maximize_restore(self))

        # WIDGET TO MOVE
        self.ui.frame_label_top_btns.mouseMoveEvent = moveWindow
        #self.ui.frame_label_top_btns.mouseDoubleClickEvent = dobleClickMaximizeRestore
        ## ==> END ##

        ## ==> LOAD DEFINITIONS
        ########################################################################
        UIFunctions.uiDefinitions(self)
        ## ==> END ##

        ########################################################################
        ## END - WINDOW ATTRIBUTES
        ############################## ---/--/--- ##############################

        ########################################################################
        #                                                                      #
        ## START -------------- WIDGETS FUNCTIONS/PARAMETERS ---------------- ##
        #                                                                      #
        ## ==> USER CODES BELLOW                                              ##
        ########################################################################

        ## ==> CREATE MENUS
        ########################################################################

        ## ==> TOGGLE MENU SIZE
        self.ui.btn_toggle_menu.clicked.connect(
            lambda: UIFunctions.toggleMenu(self, 240, True))
        ## ==> END ##

        ## ==> ADD CUSTOM MENUS
        self.ui.stackedWidget.setMinimumWidth(400)
        UIFunctions.addNewMenu(self, "Render Time Calculator", "btn_home",
                               "url(:/16x16/icons/16x16/cil-av-timer.png)",
                               True)
        UIFunctions.addNewMenu(self, "About", "btn_settings",
                               "url(:/16x16/icons/16x16/cil-options.png)",
                               False)

        # START MENU => SELECTION
        UIFunctions.selectStandardMenu(self, "btn_home")

        #UIFunctions.selectMenu(getButton.objectName().styleSheet())
        ## ==> END ##

        ## ==> START PAGE
        ########################################################################
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_home)
        self.ui.label_user_icon.hide()
        ## ==> END ##

        ## ==> QTableWidget RARAMETERS
        ########################################################################
        self.ui.tableWidget_renders.hide()
        self.ui.label_current_render.hide()
        self.ui.frame_div_table_widget.setMaximumSize(400, 50)
        self.ui.tableWidget_renders.horizontalHeader().setSectionResizeMode(
            0, QtWidgets.QHeaderView.Stretch)
        self.ui.tableWidget_renders.horizontalHeader().setSectionResizeMode(
            1, QtWidgets.QHeaderView.Fixed)
        self.ui.tableWidget_renders.horizontalHeader().setSectionResizeMode(
            2, QtWidgets.QHeaderView.Fixed)
        self.ui.tableWidget_renders.setColumnWidth(
            0, QtWidgets.QHeaderView.Stretch)
        self.ui.tableWidget_renders.setColumnWidth(1, 120)
        self.ui.tableWidget_renders.setColumnWidth(2, 50)
        delegate = AlignDelegate(self.ui.tableWidget_renders)
        self.ui.tableWidget_renders.setItemDelegateForColumn(1, delegate)
        self.ui.tableWidget_renders.setItemDelegateForColumn(2, delegate)
        ## ==> END ##

        ## ==> ADD NEW ROW
        self.ui.pushButton_add_render.clicked.connect(
            lambda: Functions.addTableRow(self))

        ## ==> JUST NUMBERS
        self.onlyInt = QIntValidator()
        # FIELDS
        self.ui.lineEdit_hours.setValidator(self.onlyInt)
        self.ui.lineEdit_minutes.setValidator(self.onlyInt)
        self.ui.lineEdit_seconds.setValidator(self.onlyInt)
        self.ui.lineEdit_frames.setValidator(self.onlyInt)
        self.ui.lineEdit_machines.setValidator(self.onlyInt)

        ## ==> AUTO UPDATE
        Functions.calculateTime(self)
        self.timer = QtCore.QTimer(self)
        self.timer.start(500)
        self.timer.timeout.connect(lambda: Functions.calculateTime(self))

        ## ==> OPEN LINKS
        self.ui.btn_artstation.clicked.connect(
            lambda: webbrowser.open('https://www.artstation.com/vfxonfire'))
        self.ui.btn_gumroad.clicked.connect(
            lambda: webbrowser.open('https://gumroad.com/blender_addons'))

        ########################################################################
        #                                                                      #
        ## END --------------- WIDGETS FUNCTIONS/PARAMETERS ----------------- ##
        #                                                                      #
        ############################## ---/--/--- ##############################

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
        ## ==> END ##

    ########################################################################
    ## TABLE WIDGET ==> FUNCTIONS
    ########################################################################
    def deleteClicked(self):
        button = self.sender()
        table = self.ui.tableWidget_renders
        count = table.rowCount()

        if button:
            row = self.ui.tableWidget_renders.indexAt(button.pos()).row()
            self.ui.tableWidget_renders.removeRow(row)

        if count == 1:
            Functions.toggleTable(self)
            QtCore.QTimer.singleShot(
                600, lambda: self.ui.tableWidget_renders.hide())
            QtCore.QTimer.singleShot(
                600, lambda: self.ui.label_current_render.hide())

    ########################################################################
    ## MENUS ==> DYNAMIC MENUS FUNCTIONS
    ########################################################################
    def Button(self):

        # GET BT CLICKED
        btnWidget = self.sender()

        if btnWidget.objectName() == "btn_home":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_home)
            UIFunctions.resetStyle(self, "btn_home")
            UIFunctions.labelPage(self, "Home")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        if btnWidget.objectName() == "btn_settings":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_info)
            UIFunctions.resetStyle(self, "btn_settings")
            UIFunctions.labelPage(self, "About")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

    ## ==> END ##

    ########################################################################
    ## START ==> APP EVENTS
    ########################################################################

    ## EVENT ==> MOUSE DOUBLE CLICK
    ########################################################################
    def eventFilter(self, obj, event):
        pass
        # if isinstance(obj, QLineEdit) and event.type() == QEvent.keyPressEvent:
        #     i = obj.property("index")
        #     self.keyPressEvent.emit(i)
        # return QWidget.eventFilter(self, obj, event)

    ## ==> END ##

    ## ==> keyReleaseEvent
    ########################################################################
    def keyReleaseEvent(self, event):
        pass
        #Functions.calculateTime(self)

    ## EVENT ==> MOUSE CLICK
    ########################################################################
    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()
        # if event.buttons() == Qt.LeftButton:
        #     print('Mouse click: LEFT CLICK')
        # if event.buttons() == Qt.RightButton:
        #     print('Mouse click: RIGHT CLICK')
        # if event.buttons() == Qt.MidButton:
        #     print('Mouse click: MIDDLE BUTTON')

    ## ==> END ##

    ## EVENT ==> KEY PRESSED
    ########################################################################
    def keyPressEvent(self, event):
        pass
        # print('Text Key: ' + str(event.key()) + ' | Text Press: ' + str(event.text()))

    ## ==> END ##

    ## EVENT ==> RESIZE EVENT
    ########################################################################
    def resizeEvent(self, event):
        self.resizeFunction()
        return super(MainWindow, self).resizeEvent(event)

    def resizeFunction(self):
        pass
Esempio n. 25
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        # Class Ui_MainWindow is autogenerated by PyQt5, method setupUi too
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Hides normal TopBar
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        # Adds minimizing, maximizing and closing functionality
        self.ui.exitBtn.clicked.connect(lambda: self.close())
        self.ui.minimizeBtn.clicked.connect(lambda: self.showMinimized())
        self.maximizeToggle = False
        self.ui.maximizeBtn.clicked.connect(lambda: self.maximize())

        # DRAGGING FUNCTIONS--------------------------------------------------------
        def moveWindow(event):
            print(event.button())
            print(Qt.LeftButton)
            if event.buttons() == Qt.LeftButton:
                delta = QPoint(event.globalPos() - self.oldPos)
                #print(delta)
                self.move(self.x() + delta.x(), self.y() + delta.y())
                self.oldPos = event.globalPos()

        # RESIZE FUNCTIONS----------------------------------------------------------
        # Top resize
        self.MIN_HEIGHT = 80

        def resizeWindowTop(event):
            if event.buttons() == Qt.LeftButton:
                self.globalY = self.pos().y()
                newYPos = event.globalPos().y() - self.globalY
                oldHeight = self.height()
                newHeight = self.MIN_HEIGHT if self.height(
                ) - newYPos < self.MIN_HEIGHT else self.height() - newYPos
                self.resize(self.width(), newHeight)
                if oldHeight - self.height() != 0:
                    self.move(self.x(), self.y() + newYPos)

        # Left resize
        def resizeWindowLeft(event):
            if event.buttons() == Qt.LeftButton:
                self.globalX = self.pos().x()
                newXPos = event.globalPos().x() - self.globalX
                oldWidth = self.width()
                self.resize(self.width() - newXPos, self.height())
                if oldWidth - self.width() != 0:
                    self.move(self.x() + newXPos, self.y())

        # Bottom resize
        def resizeWindowBottom(event):
            if event.buttons() == Qt.LeftButton:
                self.globalY = self.pos().y()
                newHeight = self.MIN_HEIGHT if event.globalPos().y(
                ) - self.globalY < self.MIN_HEIGHT else event.globalPos().y(
                ) - self.globalY
                self.resize(self.width(), newHeight)

        # Right resize
        def resizeWindowRight(event):
            if event.buttons() == Qt.LeftButton:
                self.globalX = self.pos().x()
                newWidth = event.globalPos().x() - self.globalX
                self.resize(newWidth, self.height())

        # TopLeft resize
        def resizeWindowTopLeft(event):
            resizeWindowTop(event)
            resizeWindowLeft(event)

        # TopRight resize
        def resizeWindowTopRight(event):
            resizeWindowTop(event)
            resizeWindowRight(event)

        # BottomLeft resize
        def resizeWindowBottomLeft(event):
            resizeWindowBottom(event)
            resizeWindowLeft(event)

        # BottomRight resize
        def resizeWindowBottomRight(event):
            resizeWindowBottom(event)
            resizeWindowRight(event)

        def doubleClickMaximize(event):
            self.maximize()

        # Making application draggable
        self.oldPos = self.pos()
        self.ui.topBarMiddle.mouseMoveEvent = moveWindow
        self.ui.topBarMiddle.mouseDoubleClickEvent = doubleClickMaximize

        # Making application resizeable
        self.ui.rightGripBorder.mouseMoveEvent = resizeWindowRight
        self.ui.bottomGripBorder.mouseMoveEvent = resizeWindowBottom
        self.ui.leftGripBorder.mouseMoveEvent = resizeWindowLeft
        self.ui.topGripBorder.mouseMoveEvent = resizeWindowTop

        self.ui.topLeftCorner.mouseMoveEvent = resizeWindowTopLeft
        self.ui.topRightCorner.mouseMoveEvent = resizeWindowTopRight
        self.ui.bottomLeftCorner.mouseMoveEvent = resizeWindowBottomLeft
        self.ui.bottomRightCorner.mouseMoveEvent = resizeWindowBottomRight

    # Getting the current position if any mousePressEvent happened
    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def maximize(self):
        self.maximizeToggle ^= True
        if self.maximizeToggle:
            self.showMaximized()
        else:
            self.showNormal()
Esempio n. 26
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # Set up the user interface from QtDesigner
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.act_periph = []
        self.ui.menu_periph = []
        self.ui.lab_status = QLabel()
        self.ui.lab_status.setText("No connection")
        self.ui.statusBar.addPermanentWidget(self.ui.lab_status)

        self.about_dialog = QDialog(self)
        self.about_dialog.ui = Ui_AboutDialog()
        self.about_dialog.ui.setupUi(self.about_dialog)

        self.svd_dialog = QDialog(self)
        self.svd_dialog.ui = Ui_SVDDialog()
        self.svd_dialog.ui.setupUi(self.svd_dialog)
        self.svd_dialog.ui.tree_svd.itemDoubleClicked.connect(self.handle_svd_dialog_item_double_clicked)
        self.svd_dialog.ui.tree_svd.headerItem().setText(0, "List of packed SVD")

        # Add some vars
        self.svd_reader = SVDReader()
        self.openocd_tn = OpenOCDTelnet()
        self.openocd_rt = None
        self.opt_autoread = False

    # -- Events --
    def closeEvent(self, event):
        if self.openocd_tn.is_opened:
            self.disconnect_openocd()
        event.accept()

    # -- Slots --
    def handle_act_connect_triggered(self):
        if self.openocd_tn.is_opened:
            self.disconnect_openocd()
        else:
            self.connect_openocd()

    def handle_act_open_svd_triggered(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getOpenFileName(self,
                                                  "Open SVD file", "", "SVD Files (*.svd *.SVD *.xml)",
                                                  options=options)
        if fileName:
            self.open_svd_path(fileName)

    def handle_act_open_packed_svd_triggered(self):
        self.svd_dialog.ui.tree_svd.clear()
        for vendor in self.svd_reader.get_packed_list():
            vendor_name = vendor["vendor"]
            item0 = QTreeWidgetItem(self.svd_dialog.ui.tree_svd)
            item0.setText(0, vendor_name)
            item0.is_vendor = True
            self.svd_dialog.ui.tree_svd.addTopLevelItem(item0)
            for filename in vendor["filenames"]:
                item1 = QTreeWidgetItem(item0)
                item1.is_vendor = False
                item1.setText(0, filename)
                item0.addChild(item1)
        if self.svd_dialog.exec_() and (not self.svd_dialog.ui.tree_svd.currentItem().is_vendor):
            vendor = self.svd_dialog.ui.tree_svd.currentItem().parent().text(0)
            filename = self.svd_dialog.ui.tree_svd.currentItem().text(0)
            self.open_svd_packed(vendor, filename)

    def handle_svd_dialog_item_double_clicked(self, item, col):
        if not item.is_vendor:
            vendor = item.parent().text(0)
            filename = item.text(0)
            self.open_svd_packed(vendor, filename)
            self.svd_dialog.accept()

    def handle_act_about_triggered(self):
        text = self.about_dialog.ui.lab_version.text().replace("x.x", VERSION)
        self.about_dialog.ui.lab_version.setText(text)
        self.about_dialog.exec_()

    def handle_act_periph_triggered(self):
        sender_name = self.sender().objectName()
        for periph in self.svd_reader.device:
            if sender_name == periph["name"]:
                periph_num = self.svd_reader.device.index(periph)
                periph_name = self.svd_reader.device[periph_num]["name"]
                break

        if (self.ui.tabs_device.findChild(QWidget, periph_name)):
            self.ui.tabs_device.setCurrentWidget(self.ui.tabs_device.findChild(QWidget, periph_name))
        else:
            periph_tab = PeriphTab(self.svd_reader.device[periph_num])
            for i in range(0, periph_tab.tree_regs.topLevelItemCount()):
                reg = periph_tab.tree_regs.itemWidget(periph_tab.tree_regs.topLevelItem(i), 1)
                reg.btn_read.clicked.connect(functools.partial(self.handle_btn_read_clicked, index=i))
                reg.btn_write.clicked.connect(functools.partial(self.handle_btn_write_clicked, index=i))
            self.ui.tabs_device.addTab(periph_tab, periph_name)
            self.ui.tabs_device.setCurrentIndex(self.ui.tabs_device.count() - 1)

    def handle_btn_read_clicked(self, index):
        if self.openocd_tn.is_opened:
            periph = self.ui.tabs_device.currentWidget()
            reg = periph.tree_regs.itemWidget(periph.tree_regs.topLevelItem(index), 1)
            addr = periph.svd["base_address"] + reg.svd["address_offset"]
            try:
                reg.setVal(self.openocd_tn.read_mem(addr))
                self.ui.statusBar.showMessage("Read %s.%s @ 0x%08X - OK" % (periph.svd["name"],
                                                                            reg.svd["name"],
                                                                            addr))
            except RuntimeError:
                self.ui.statusBar.showMessage("Read %s.%s @ 0x%08X - Error" % (periph.svd["name"],
                                                                               reg.svd["name"],
                                                                               addr))

    def handle_btn_write_clicked(self, index):
        if self.openocd_tn.is_opened:
            periph = self.ui.tabs_device.currentWidget()
            reg = periph.tree_regs.itemWidget(periph.tree_regs.topLevelItem(index), 1)
            addr = periph.svd["base_address"] + reg.svd["address_offset"]
            try:
                self.openocd_tn.write_mem(addr, reg.val())
                self.ui.statusBar.showMessage("Write %s.%s @ 0x%08X - OK" % (periph.svd["name"],
                                                                             reg.svd["name"],
                                                                             addr))

            except RuntimeError:
                self.ui.statusBar.showMessage("Write %s.%s @ 0x%08X - Error" % (periph.svd["name"],
                                                                                reg.svd["name"],
                                                                                addr))

    def handle_tab_periph_close(self, num):
        widget = self.ui.tabs_device.widget(num)
        if widget is not None:
            widget.deleteLater()
        self.ui.tabs_device.removeTab(num)

    def handle_act_autowrite_toggled(self, state):
        for tab_n in range(0, self.ui.tabs_device.count()):
            tab = self.ui.tabs_device.widget(tab_n)
            for reg_n in range(0, tab.tree_regs.topLevelItemCount()):
                reg = tab.tree_regs.itemWidget(tab.tree_regs.topLevelItem(reg_n), 1)
                reg.setAutoWrite(state)

    def handle_act_autoread_toggled(self, state):
        self.opt_autoread = state

    # -- Application specific code --
    def close_svd(self):
        title = self.windowTitle()
        title = title.split(" - ")[-1]
        self.setWindowTitle(title)
        while self.ui.tabs_device.currentIndex() != -1:
            self.handle_tab_periph_close(self.ui.tabs_device.currentIndex())
        self.ui.menuView.clear()
        self.ui.menu_periph.clear()

    def open_svd_path(self, path):
        try:
            self.close_svd()
            self.svd_reader.parse_path(path)
            self.setWindowTitle(os.path.basename(path) + " - " + self.windowTitle())
            self.__update_menu_view()
        except:
            self.ui.statusBar.showMessage("Can't open %s - file is corrupted!" % os.path.basename(path))

    def open_svd_packed(self, vendor, filename):
        try:
            self.close_svd()
            self.svd_reader.parse_packed(vendor, filename)
            self.setWindowTitle(filename + " - " + self.windowTitle())
            self.__update_menu_view()
        except:
            self.ui.statusBar.showMessage("Can't open %s - file is corrupted!" % filename)

    def __update_menu_view(self):
        for periph in self.svd_reader.device:
                if periph["name"] == periph["group_name"]:
                    self.ui.act_periph += [QAction(self)]
                    self.ui.act_periph[-1].setObjectName(periph["name"])
                    self.ui.act_periph[-1].setText(periph["name"])
                    self.ui.act_periph[-1].triggered.connect(self.handle_act_periph_triggered)
                    self.ui.menuView.addAction(self.ui.act_periph[-1])
                else:
                    if periph["group_name"] in [menu.objectName() for menu in self.ui.menu_periph]:
                        menu_num = [menu.objectName() for menu in self.ui.menu_periph].index(periph["group_name"])
                    else:
                        self.ui.menu_periph += [QMenu(self.ui.menubar)]
                        menu_num = -1
                        self.ui.menu_periph[menu_num].setObjectName(periph["group_name"])
                        self.ui.menu_periph[menu_num].setTitle(periph["group_name"])
                        self.ui.menuView.addAction(self.ui.menu_periph[menu_num].menuAction())
                        self.ui.menu_periph[menu_num].act_periph = []
                    self.ui.menu_periph[menu_num].act_periph += [QAction(self)]
                    self.ui.menu_periph[menu_num].act_periph[-1].setObjectName(periph["name"])
                    self.ui.menu_periph[menu_num].act_periph[-1].setText(periph["name"])
                    self.ui.menu_periph[menu_num].act_periph[-1].triggered.connect(self.handle_act_periph_triggered)
                    self.ui.menu_periph[menu_num].addAction(self.ui.menu_periph[menu_num].act_periph[-1])

    def connect_openocd(self):
        try:
            self.openocd_tn.open()
            self.ui.act_connect.setText("Disconnect OpenOCD")
            self.openocd_target = self.openocd_tn.get_target_name()
            self.openocd_target_pc = self.openocd_tn.get_target_pc()
            self.__poll_openocd()
            self.openocd_rt = RepeatedTimer(1, self.__poll_openocd)
        except:
            self.ui.statusBar.showMessage("Can't connect to OpenOCD!")

    def __poll_openocd(self):
        if self.openocd_tn.check_alive():
            self.openocd_target_state = self.openocd_tn.get_target_state()
            if self.openocd_target_state != "halted":
                new_target_pc = self.openocd_target_pc
            else:
                new_target_pc = self.openocd_tn.get_target_pc()
            self.ui.lab_status.setText("Connected: %s | %s | 0x%08X" % (self.openocd_target,
                                                                        self.openocd_target_state, new_target_pc))
            if self.opt_autoread and self.ui.tabs_device.count():
                if ((self.openocd_target_state == "halted") and (new_target_pc != self.openocd_target_pc)):
                    self.ui.tabs_device.currentWidget().btn_readall.clicked.emit()
            self.openocd_target_pc = new_target_pc

        else:
            self.openocd_rt.is_executing = False
            self.disconnect_openocd()

    def disconnect_openocd(self):
        self.openocd_rt.stop()
        while self.openocd_rt.is_executing:
            pass
        self.openocd_tn.close()
        self.ui.act_connect.setText("Connect OpenOCD")
        self.ui.lab_status.setText("No connection")
Esempio n. 27
0
class MainWindow(QMainWindow, Ui_MainWindow):
    #Create settings for the software
    settings = QSettings('Mte90', 'QAsana')
    settings.setFallbacksEnabled(False)
    version = '2.0'
    appname = 'QAsana - ' + version + ' by Mte90'
    workspaces_id = {}
    workspace_id = ''
    projects_id = {}
    project_id = ''
    proj_tasks_id = {}
    asana_api = None

    def __init__(self, parent=None):
        #http://pythonadventures.wordpress.com/2013/01/10/launch-just-one-instance-of-a-qt-application/
        wid = self.get_pid()
        if_focus = os.popen('xdotool getactivewindow').readlines()
        #hide if the window have focues when executed again
        if if_focus[0] == wid:
            os.system('xdotool windowunmap "' + wid + '"')
            sys.exit()
        #Software already opened
        if wid:
            #Show
            os.system('xdotool windowmap ' + wid)
            #get focus
            os.system('xdotool windowactivate ' + wid)
            move_under_cursor()
            sys.exit()
        else:
            #Load the ui
            QMainWindow.__init__(self, parent)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            #Set the MainWindow Title
            self.setWindowTitle(self.appname)
            #Connect the function with the signal
            self.ui.pushSettings.clicked.connect(self.openKeyDialog)
            self.ui.pushRefresh.clicked.connect(self.loadAsana)
            self.ui.pushAddTask.clicked.connect(self.addTask)
            self.ui.pushUpdate.clicked.connect(self.comboProjectChanged)
            self.ui.lineTask.returnPressed.connect(self.addTask)
            self.ui.comboWorkspace.currentIndexChanged.connect(self.comboWorkspaceChanged)
            self.ui.comboProject.currentIndexChanged.connect(self.comboProjectChanged)
            #When the software are closed on console the software are closed
            signal.signal(signal.SIGINT, signal.SIG_DFL)
            #Add hide parameter
            parser = argparse.ArgumentParser()
            parser.add_argument("--hide", help="hide the window at startup", action="store_true")
            args = parser.parse_args()
            #Show the form
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.show()
            if not args.hide:
                move_under_cursor()
            else:
                wid = self.get_pid()
                os.popen('xdotool windowunmap "' + wid + '"')
            self.loadAsana()

    def openKeyDialog(self):
        key, ok = QInputDialog.getText(self, 'Authorization Key', 'Insert the key:', QLineEdit.Normal, self.settings.value('Key'))
        if not self.settings.value('Key'):
            self.settings.setValue('Key', key)

    def loadAsana(self):
        if self.settings.value('Key') != -1:
            if self.settings.value('Key'):
                self.ui.comboWorkspace.currentIndexChanged.disconnect(self.comboWorkspaceChanged)
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                self.asana_api = asana.Client.access_token(self.settings.value('Key'))
                #get workspace
                workspace = self.asana_api.users.me()
                workspace = workspace['workspaces']
                self.ui.comboWorkspace.clear()
                for workspace in self.asana_api.workspaces.find_all():
                    self.workspaces_id[workspace['name']] = workspace['id']
                    #populate the combobox
                    self.ui.comboWorkspace.addItem(workspace['name'])
                self.ui.comboWorkspace.currentIndexChanged.connect(self.comboWorkspaceChanged)
                self.comboWorkspaceChanged()
            else:
                QMessageBox.critical(self.window(), "Key not configured", "Set the key for access to Asana!")
        else:
            QMessageBox.critical(self.window(), "Key not configured", "Set the key for access to Asana!")

    def comboWorkspaceChanged(self):
        self.ui.comboProject.currentIndexChanged.disconnect(self.comboProjectChanged)
        self.workspace_id = self.workspaces_id[self.ui.comboWorkspace.currentText()]
        #get projects
        self.ui.comboProject.clear()
        for projects in self.asana_api.projects.find_all({'workspace': self.workspace_id, 'archived': 'false'}):
            self.projects_id[projects['name']] = projects['id']
            #populate the combobox
            self.ui.comboProject.addItem(projects['name'])
        self.ui.comboProject.currentIndexChanged.connect(self.comboProjectChanged)
        self.comboProjectChanged()

    def comboProjectChanged(self):
        if len(self.ui.comboProject.currentText()) > 0:
            self.project_id = self.projects_id[self.ui.comboProject.currentText()]
            #get project tasks
            qsubtasks = QStandardItemModel()
            for proj_tasks in self.asana_api.tasks.find_by_project(self.project_id, { 'completed_since': 'now'}):
                item = QStandardItem(proj_tasks['name'])
                item.setEditable(True)
                item.setToolTip('Double click to edit')
                if not proj_tasks['name'].endswith(':'):
                    check = Qt.Unchecked
                    item.setCheckState(check)
                    item.setCheckable(True)
                    self.projects_id[proj_tasks['name']] = proj_tasks['id']
                    item.setStatusTip(str(proj_tasks['id']))
                else:
                    font = QFont()
                    font.setWeight(QFont.Bold)
                    item.setFont(font)
                #populate the listview
                qsubtasks.appendRow(item)
            self.ui.listTasks.setModel(qsubtasks)
            QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))
            qsubtasks.itemChanged.connect(self.checkTasks)

    def checkTasks(self, item):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if item.checkState():
            self.asana_api.tasks.delete(self.projects_id[item.text()])
            self.ui.listTasks.model().removeRow(item.row())
        else:
            self.asana_api.tasks.update(item.statusTip(), {'id': item.statusTip(), 'name': item.text()})
        QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))

    def addTask(self):
        task = self.ui.lineTask.text()
        self.ui.lineTask.setText('')
        self.asana_api.tasks.create_in_workspace(self.workspace_id, {'name': task, 'projects': [self.project_id]})
        self.comboProjectChanged()

    def get_pid(self):
        wid = os.popen('xdotool search --name "' + self.appname + '"').readlines()
        #Check if multiple rows output
        if len(wid) > 0:
            wid = wid[0]
        return wid
class MainWindow(QMainWindow):
    def __init__(self):

        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)


        #----> SET WINDOW TITLE AND ICON
        applicationName = "App Name"
        self.setWindowTitle(applicationName) #SETS THE APPLICATION NAME IN THE WINDOW TOPBAR                        ---------(C4)
        #EVENTHOW IT IS AVSENT THIS IS NECESSERY AS THE OPERATING SYSTEM RECOGNISES THE SOFTWARE SUING THIS NAME
        #SO YOU WILL SEE THE NAME ENTERED HERE IN THE TASKBAR, TITLEBAR, E.T.C
        UIFunction.labelTitle(self, applicationName) #PASSING THE CODE TO SET THE TITLE TO THE CUSTOME TOPBAR IN OUR UI
        #THIS UOFunction CLASS IS IN THE FILE: ui_function.py.
        ###############################


        #-----> INITIAL STACKED WIDGET PAGE WIDGET AND TAB
        #THIS MAKE THE INITIAL WINDOW OF OUR APPLICATION, I.E. THE FIRST PAGE OR THE WELCOME PAGE/SCREEN            ---------(C5)
        #IN OUR APPLICATION THIS IS THE MENU BAR, TOODLE SWITCH, MIN, MAX, CLOSE BUTTONS, AND THE HOME PAGE.
        #ALL THIS GET INITIALISED HERE.
        #SINCE ALL THE FUNCTION RELATED STUFF IS DONE IN THE ui_function.py FILE, IT GOES THERE
        #REMEMBER THIS FUNCTION CAN ALSO BE DONE HERE, BUT DUE TO CONVINENCE IT IS SHIFTD TO A NEW FILE.
        UIFunction.initStackTab(self)
        ############################################################

        
        #----> CERTAIN TOOLS LIKE DRAG, MAXIMISE, MINIMISE, CLOSE AND HIDING OF THE WINDOWS TOPBAR
        # THIS WINDOW INITIALISES THE BUTTONS NECESSERY FOR THE MAINWINDOW LIKE: CLOSE, MIN, MAX E.T.C.                ---------(C6)
        UIFunction.constantFunction(self)
        #############################################################


        #----> TOODLE THE MENU HERE
        #THIS CODE DETETS THE BUTTON IN THE RIGHT TOP IS PRESSED OR NOT AND IF PRESSED IT CONNECT  TO A FUNCTION IN THE ui_function.py                 ---------(C7)
        #FILE, WHICH EXPANDS THE MENU BAR TO DOUBLE ITS WIDTH MAKING ROOM FOR THE ABOUT PAGES.
        #THIS EFFECT CALLED AS TOODLE, CAN BE MADE USE IN MANY WAYS. CHECK THE FUNCTION: toodleMenu: IN THE ui_function.py
        #FILE FOR THE CLEAR WORKING
        self.ui.toodle.clicked.connect(lambda: UIFunction.toodleMenu(self, 160, True))
        #############################################################


        #----> MENU BUTTON PRESSED EVENTS
        #NOW SINCE OUR DEMO APPLICATION HAS ONLY 4 MENU BUTTONS: Home, Bug, Android, Cloud, WHEN USER PRESSES IT THE FOLLOWING CODE             ---------(C8)
        #REDIRECTS IT TO THE ui_function.py FILE buttonPressed() FUNCTION TO MAKE THE NECESSERY RESPONSES TO THE BUTTON PRESSED.
        #IT TAKES SELF AND THE BUTTON NAME AS THE RGUMENT, THIS IS ONLY TO RECOGNISE WHICH BUTTON IS PRESSED BY THE buttonPressed() FUNCTION.
        self.ui.bn_home.clicked.connect(lambda: UIFunction.buttonPressed(self, 'bn_home'))
        self.ui.bn_bug.clicked.connect(lambda: UIFunction.buttonPressed(self, 'bn_bug'))
        self.ui.bn_android.clicked.connect(lambda: UIFunction.buttonPressed(self, 'bn_android'))
        self.ui.bn_cloud.clicked.connect(lambda: UIFunction.buttonPressed(self, 'bn_cloud'))
        #############################################################


        #-----> STACK PAGE FUNCTION
        #OUR APPLICATION CHANGES THE PAGES BY USING THE STACKED WIDGET, THIS CODE POINTS TO A FUNCTION IN ui_function.py FILE             ---------(C9)
        #WHICH GOES AND SETS THE DEFAULT IN THESE PAGES AND SEARCHES FOR THE RESPONSES MADE BY THE USER IN THE CORRSPONDING PAGES.
        UIFunction.stackPage(self)
        #############################################################


        #----> EXECUTING THE ERROR AND DIALOG BOX MENU : THIS HELP TO CALL THEM WITH THE FUNCTIONS.
        #THIS CODE INITIALISED THE DIALOGBOX AND THE ERRORBOX, MAKES AN OBJECT OF THE CORRESPONDING CLASS, SO THAT WE CAN CALL THEM         ---------(C10)
        #WHENEVER NECESSERY.
        self.diag = dialogUi()
        self.error = errorUi()
        #############################################################


        #############################################################

        #UNCOMMENT THE RESPECTIVE LINES OF CODE AS REQUIRED:
        #WARNING: MAKE SURE THAT YOU COMMENT OUT CODES THAT IS ENTERED IN THIS FILE AND FILE ui_function.py FOR THE SMAE
        #WIDGET PERFORMING THE SAME FUNCTION.

#--ADDING A NEW MENU BUTTON------------------:
#REFER THE DOCUMENTATION: Documentation.pdf FILE

#--CALLING A DIALOG BOX----------------------:
        #dialogexec("Heading", "Message", "icon", "Button1name", "button2name")

#--CALLING A ERROR BOX-----------------------:
        #errorexec("Message", "icon", "buttonname")

#--PAGE HOME---------------------------------:
    #--HEADING----------------------:
        #self.ui.lab_home_main_hed.setText("heading")
        #self.ui.lab_home_stat_hed.setText("Sata heading")

    #--LABEL------------------------:
        #self.ui.lab_home_main_disc.setText("-----------")
        #self.ui.lab_home_stat_disc.setText("--------------")

#--PAGE BUG----------------------------------:
    #--CHANGING THE HEADING---------:
        #self.ui.lab_bug.setText("your heading")

    #--USING PROGRESS BAR VALUE-----:
        #self.ui.progressBar_bug.setValue(% in int)

    #--USING COMBO BOX--------------:
        #self.ui.comboBox_bug.addItem("item") #TO ADD ITEMS IN THE COMBOBOX LIST
        #self.ui.comboBox_bug.setItemText() #INDEX YOUR ADDED ITEM
        #self.ui.comboBox_bug.currentIndex() #GIVES THE CURRENT INDEX OF THE LIST

    #--USING START BUTTON-----------:
        #self.ui.bn_bug_start.clicked.connect(some function to execute) #THE FUNCTION GET ACTIVATED WHEN YOU CLICK THE BUTTON

#--PAGE CLOUD--------------------------------:
    #--CHANGE HEADING---------------:
        #self.ui.lab_cloud_main.setText("heading")

    #--CHANGING LABELS--------------:
        #self.ui.label_2.setText("change: Clint ID")
        #self.ui.label_3.setText("change: Server Adress")
        #self.ui.label_4.setText("change: Proxy")

    #--USING LINE FILED-------------:
        #self.ui.line_cloud_id.setText("set the initial text")
        #text_get = self.ui.line_cloud_id.text() #GIVES THE TEXT ENTERED BY THE USER.
        #DO THE SAME CODE OFR THE RES OF THE LINE EDIT : line_cloud_adress and line_cloud_proxy

    #--USING THE PUSH BUTTONS-------:
        #self.ui.bn_cloud_clear.clicked.connect(function to execute)
        #self.ui.bn_cloud_connect.clikced.connect(function to execute)

#--PAGE ANDROID:CONTACT----------------------:
    #--CHANGING THE HEADING---------:
        #self.ui.lab_android_contact.setText("Heading")

    #--CHANGING LABELS--------------:
        #self.ui.label.setText("-----")
        #perform the same for the label with obeject tname: 'label_5', 'label_6', 'label_7', 'label_8'

    #--USING TEXT FIELD-------------:
        #sefl.ui.line_android_name.setText("---")
        #self.ui.lineandroid_name.text() #TO GET WHAT THE USER HAS ENTERED.
        #PERFORM THE SAME CODE FOR THE: OBJECT NAME: 'line_android_adress', 'line_android_eamil', 'line_android_ph', 'line_android_org'

    #--USING PUSH BUTTONS-----------:
        #self.ui.bn_adroid_contact_edit.clicked.connect("function goes here")
        #self.ui.bn_adroid_contact_share.clicked.connect("function goes here")
        #self.ui.bn_adroid_contact_delete.clicked.connect("function goes here")
        #self.ui.bn_adroid_contact_save.clicked.connect("function goes here")

        #self.ui.bn_android_contact_save.setEnable(True) #TO ENABLE THE BUTTON
        #DO THE SAME FOR THE REST OF THE BUTTON WHEREEVER NECESSERY.

#--PAGE ANDROID:GAME-------------------------:
    #--CHANGING THE HEADING---------:
        #self.ui.lab_gamepad.setText("-----")

    #--USING TEXT BROWSER-----------:
        #self.ui.textEdit_gamepad.setText("----")

#FOR REST OF THE WIDGET GOTO THE Documentation.pdf AND CHECK THE LAYOUT FOR MORE DETAILS.


        #---> MOVING THE WINDOW WHEN LEFT MOUSE PRESSED AND DRAGGED OVER APPNAME LABEL
        #SAME TO SAY AS IN COMMENT (C2)
        self.dragPos = self.pos()
        def moveWindow(event):
            # IF MAXIMIZED CHANGE TO NORMAL
            if UIFunction.returStatus() == 1: 
                UIFunction.maximize_restore(self)

            # MOVE WINDOW
            if event.buttons() == Qt.LeftButton:
                self.move(self.pos() + event.globalPos() - self.dragPos)
                self.dragPos = event.globalPos()
                event.accept()

        # WIDGET TO MOVE: WE CHOOSE THE TOPMOST FRAME WHERE THE APPLICATION NAME IS PRESENT AS THE AREA TO MOVE THE WINDOW.
        self.ui.frame_appname.mouseMoveEvent = moveWindow  #CALLING THE FUNCTION TO CJANGE THE POSITION OF THE WINDOW DURING MOUSE DRAG
        
    #----> FUNCTION TO CAPTURE THE INITIAL POSITION OF THE MOUSE: NECESSERY FOR THE moveWindow FUNCTION
    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()
    #############################################################


    #-----> FUNCTION WHICH OPENS THE DIALOG AND DISPLAYS IT: SO TO CALL DIALOG BOX JUST CALL THE FUNCTION dialogexec() WITH ALL THE PARAMETER
    #NOW WHENEVER YOU WANT A DIALOG BOX TO APPEAR IN THE APP LIKE IN PRESS OF CLODE BUTTON, THIS CAN BE DONE BY CALLING THIS FUNCTION.        ----------(C11)
    #IT TAKES DIALOG OBJECT(INITIALISED EARLIER), HEADER NAME OF DIALOG BOX, MESSAGE TO BE DISPLAYED, ICON, BUTTON NAMES.
    #THIS CODE EXECUTES THE DIALOGBOX AND SO WE CAN SEE THE DIALOG BOX IN THE SCREEN.
    #DURING THE APPEARENCE OF THIS WINDOW, YOU CANNOT USE THE MAINWINDOW, YOU SHPULD EITHER PRESS ANY ONE OFT HE PROVIDED BUTTONS
    #OR JUST CLODE THE DIALOG BOX.
    def dialogexec(self, heading, message, icon, btn1, btn2):
        dialogUi.dialogConstrict(self.diag, heading, message, icon, btn1, btn2)
        self.diag.exec_()
    #############################################################


    #-----> FUNCTION WHICH OPENS THE ERROR BOX AND DISPLAYS IT: SO TO CALL DIALOG BOX JUST CALL THE FUNCTION errorexec() WITH ALL THE PARAMETER
    #SAME AS COMMEND (C11), EXCEPT THIS IS FOR THE ERROR BOX.
    def errorexec(self, heading, icon, btnOk):
        errorUi.errorConstrict(self.error, heading, icon, btnOk)
        self.error.exec_()
Esempio n. 29
0
        print 'up'
    if QKeyEvent.key() == Qt.Key_Down:
        print 'down'
    b(QKeyEvent)


def send():
    text = u"<span style='color:red'>{}</span>".format(ui.lineEdit.text())
    ui.plainTextEdit.appendHtml(text)
    data = ui.lineEdit.text()
    t = u"{}\n".format(data).encode('cp1251')
    tn.write(t)
    ui.lineEdit.clear()


ui.setupUi(window)
ui.lineEdit.returnPressed.connect(send)
b = ui.lineEdit.keyPressEvent
ui.lineEdit.keyPressEvent = a

ui.plainTextEdit.document().setMaximumBlockCount(10000)
ui.plainTextEdit.setReadOnly(True)
ui.plainTextEdit.setCenterOnScroll(False)

font = QFont("Droid Sans Mono", 11)
ui.plainTextEdit.setFont(font)

window.show()

tn = telnetlib.Telnet('arda.pp.ru', 4000)
tn.set_debuglevel(100)
Esempio n. 30
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Esempio n. 31
0
class EmotionAnnotationUi:
    def __init__(self):
        self.videolist = []  # save the list of unwatched videos
        self.watched = []  # Save the list of watched videos
        self.emotion = 0  # store the numerical value of emotion
        self.saved = 0  # Flag to check video anotation is saved or not before pressing next
        self.image = None
        self.cap = None
        self.timer = None

        self.main_win = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_win)
        self.ui.currentfolder = None
        self.ui.currentvideo = None
        self.ui.folderpath.setText("No Folder Selected")
        self.ui.emotion.setText("None")
        self.ui.Videoname.setText("None")
        self.ui.folder.clicked.connect(self.selectfolder)
        self.ui.save.clicked.connect(self.saveclicked)

        self.ui.replay.clicked.connect(self.replayclicked)
        self.ui.next.clicked.connect(self.nextclicked)

        self.ui.angry.clicked.connect(self.angryclicked)
        self.ui.happy.clicked.connect(self.happyclicked)
        self.ui.sad.clicked.connect(self.sadclicked)
        self.ui.surprise.clicked.connect(self.surpriseclicked)
        self.ui.disgust.clicked.connect(self.disgustclicked)
        self.ui.fear.clicked.connect(self.fearclicked)
        self.ui.noemotion.clicked.connect(self.noemotionclicked)
        self.ui.uncertain.clicked.connect(self.uncertainclicked)

    def selectfolder(self):

        file_path = None
        file_path = QFileDialog.getExistingDirectory(None,
                                                     'Select Video Folder',
                                                     os.getcwd())
        #file_path = filedialog.askopenfilename()
        if (file_path != None):
            self.currentfolder = file_path
            self.videolist = [
                f for f in os.listdir(self.currentfolder)
                if re.match(r'.*\.mkv', f)
            ]
            self.ui.folderpath.setText(self.currentfolder)
            if (self.videolist != []):
                self.currentvideo = self.videolist.pop()
                self.ui.Videoname.setText(self.currentvideo)
            else:
                pass

        else:
            pass

        #select the folder #set the path on display folderpath.setText

#made a folder inside same folderpath with annotation and mark the
#current emotion
#1  Happy
#2  Sad
#3  Surprise
#4  Disgust
#5  Fear
#6  Angry
#7  Uncertain
#8  Noemotion
# Load the player with next emotion

    def saveclicked(self):
        if (self.emotion != 0):
            if not os.path.exists(self.currentfolder + "/annotation/"):
                os.makedirs(self.currentfolder + "/annotation/")
            file = open(
                self.currentfolder + "/annotation/" + self.currentvideo +
                ".txt", 'w+')
            file.write(str(self.emotion))
            file.close()
            self.saved = 1
        else:
            self.saved = 0
            self.ui.emotion.setText("Select Anotation")
        self.ui.emotion.setText("Select Anotation")
        self.emotion = 0

    def replayclicked(self):
        self.saved = 0
        self.cap = cv2.VideoCapture(self.currentfolder + "/" +
                                    self.currentvideo)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 381)
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 571)

        # cv2.imshow('window-name',frame)
        # cv2.imwrite("frame%d.jpg" % count, frame)
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(40)

        self.update_frame

        #play the first video
    def update_frame(self):
        ret, frame = self.cap.read()
        if frame is not None:
            self.image = frame
            self.display_image(self.image, 1)
        else:
            pass

    def display_image(self, img, window=1):
        qformat = QImage.Format_RGB888
        outimage = QImage(img, img.shape[1], img.shape[0], img.strides[0],
                          qformat)
        outimage = outimage.rgbSwapped()
        self.ui.videoplayer.setPixmap(QPixmap.fromImage(outimage))
        self.ui.videoplayer.setScaledContents(True)

#Go to the next video

    def nextclicked(self):
        if (self.saved == 0):
            self.ui.emotion.setText("UnSaved Data")
        else:

            self.watched.append(self.currentvideo)
            if (len(self.videolist) != 0):
                self.currentvideo = self.videolist.pop()
                self.ui.Videoname.setText(self.currentvideo)
                self.timer.stop()
                self.replayclicked()
            else:
                self.ui.Videoname.setText("All Done!!! ")

    def angryclicked(self):
        self.emotion = 6
        self.ui.emotion.setText("Angry")

    def happyclicked(self):
        self.emotion = 1
        self.ui.emotion.setText("happy")

    def sadclicked(self):
        self.emotion = 2
        self.ui.emotion.setText("sad")

    def surpriseclicked(self):
        self.emotion = 3
        self.ui.emotion.setText("surprise")

    def disgustclicked(self):
        self.emotion = 4
        self.ui.emotion.setText("disgust")

    def fearclicked(self):
        self.emotion = 5
        self.ui.emotion.setText("fear")

    def noemotionclicked(self):
        self.emotion = 8
        self.ui.emotion.setText("NoEmotion")

    def uncertainclicked(self):
        self.emotion = 7
        self.ui.emotion.setText("Uncertain")

    def show(self):
        self.main_win.show()

    def setTitle(self, s):
        self.main_win.setWindowTitle(s)
Esempio n. 32
0
class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.np_img = None
        self.image_actions = []
        self._init_ui()

        self.view = self.ui.imageLabel
        self.image_opener = ImageOpener(self)
        self.image_saver = ImageSaver(self)
        self.image_editor = ImageEditor()
        self.image_history = History()
        self.user_settings_dump_n_loader = UserSettingsDumpNLoader()
        self.diff_images_dir = self.user_settings_dump_n_loader.get_diff_images_dir()
        self.golden_images_dir = self.user_settings_dump_n_loader.get_golden_images_dir()

        self._init_file_actions()
        self._init_M2_actions()
        self._init_M3_actions()
        self._init_M4_actions()
        self._init_M5_actions()
        self._init_M6_actions()
        self._enable_menu_items(False)

    def _init_ui(self):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.imageLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.setCentralWidget(self.ui.imageLabel)

    def _init_file_actions(self):
        self.ui.actionExit.triggered.connect(QtGui.qApp.quit)
        self.ui.actionOpen.triggered.connect(self._open_file)
        self.ui.actionSave.triggered.connect(self._save_file)
        self.ui.actionSave_As.triggered.connect(self.image_saver.save_as_file)
        self.ui.actionUndo.triggered.connect(self._undo)
        self.ui.actionRedo.triggered.connect(self._redo)

        self.image_actions.append(self.ui.actionSave)
        self.ui.actionSave_As.setEnabled(False)
        self._enable_undo_redo()

    def _init_M2_actions(self):
        self.ui.actionErosion.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.erosion))
        self.ui.actionDilatation.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.dilatation))
        self.ui.actionInversion.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.inversion))
        self.image_actions.extend([self.ui.actionErosion, self.ui.actionDilatation, self.ui.actionInversion])

    def _init_M3_actions(self):
        self.ui.actionIntegrating_filter.triggered.connect(
            lambda: self._image_editor_wrapper(self.image_editor.linear_filter, ImageEditor.integration_filter_matrix,
                                               ImageEditor.integration_filter_divisor)
        )
        self.ui.actionBlur.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.linear_filter,
                                             ImageEditor.blur_matrix, ImageEditor.blur_divisor))
        self.ui.actionSharpen.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.linear_filter,
                                                ImageEditor.sharpen_matrix, ImageEditor.sharpen_divisor))
        self.ui.actionMake_new_custom_filter.triggered.connect(self._make_new_custom_filter)
        for filter_name, (matrix, divisor) in self.user_settings_dump_n_loader.get_filters().iteritems():
            action = QtGui.QAction(self)
            action.setText(filter_name)
            action.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.linear_filter,
                                     matrix, divisor))
            self.ui.menuCustom_filters.addAction(action)
        self.image_actions.extend([self.ui.actionIntegrating_filter, self.ui.actionBlur,
                                   self.ui.actionSharpen, self.ui.actionMake_new_custom_filter])

    def _init_M4_actions(self):
        self.ui.actionWhite_noise.triggered.connect(lambda: self._get_two_params_and_edit("Probability (%)", "Range",
                                                                                          self.image_editor.white_noise))
        self.ui.actionDust.triggered.connect(lambda: self._get_two_params_and_edit("Probability (%)", "Min value",
                                                                                   self.image_editor.dust))
        self.ui.actionGrid.triggered.connect(lambda: self._get_two_params_and_edit("Width", "Height",
                                                                                   self.image_editor.grid))
        self.image_actions.extend([self.ui.actionWhite_noise, self.ui.actionDust, self.ui.actionGrid])

    def _init_M5_actions(self):
        self.ui.actionDifference.triggered.connect(lambda: self._diff_images())
        self.ui.actionSet_diff_images_path.triggered.connect(lambda: self._set_diff_images_dir(self._choose_directory()))
        self.ui.actionSet_golden_images_path.triggered.connect(lambda: self._set_golden_images_dir(self._choose_directory()))
        self.image_actions.extend([self.ui.actionDifference,
                                   self.ui.actionSet_diff_images_path, self.ui.actionSet_golden_images_path])

    def _init_M6_actions(self):
        self.ui.actionMedian_filter_r_1.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.median_filter, 1))
        self.ui.actionMedian_filter_r_2.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.median_filter, 2))
        self.ui.actionMedian_filter_r_3.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.median_filter, 3))
        self.image_actions.extend([self.ui.actionMedian_filter_r_1, self.ui.actionMedian_filter_r_2,
                                   self.ui.actionMedian_filter_r_3])

    def _enable_menu_items(self, mode):
        for action in self.image_actions:
            action.setEnabled(mode)

    def _image_editor_wrapper(self, editor_func, *args):
        self.image_history.add_new_state(self.np_img)
        self.image_editor.update_image(self.np_img)
        self.np_img = editor_func(*args)
        self._show_np_image()
        self._enable_undo_redo()
        self._enable_menu_items(True)

    def _make_new_custom_filter(self):
        dialog = MakeNewCustomLinearFilterDialog(self.user_settings_dump_n_loader.get_filters().keys())
        if dialog.exec_():
            matrix, divisor, name = dialog.get_values()
            self._image_editor_wrapper(self.image_editor.linear_filter, matrix, divisor)
            self.user_settings_dump_n_loader.save_filter(matrix, divisor, name)
            action = QtGui.QAction(self)
            action.setText(name)
            self.ui.menuCustom_filters.addAction(action)
            action.triggered.connect(lambda: self._image_editor_wrapper(self.image_editor.linear_filter,
                                     matrix, divisor))

    def _get_two_params_and_edit(self, param1, param2, editor_func):
        dialog = BaseTwoParamsDialog(param1, param2)
        if dialog.exec_():
            param1_value, param2_value = dialog.get_values()
            self._image_editor_wrapper(editor_func, param1_value, param2_value)

    @staticmethod
    def _choose_directory():
        return str(QtGui.QFileDialog.getExistingDirectory(None, 'Choose directory', '.', QtGui.QFileDialog.ShowDirsOnly))

    def _set_golden_images_dir(self, dirname):
        if dirname:
            self.golden_images_dir = dirname
            self.user_settings_dump_n_loader.set_golden_images_dir(dirname)

    def _set_diff_images_dir(self, dirname):
        if dirname:
            self.golden_images_dir = dirname
            self.user_settings_dump_n_loader.set_diff_images_dir(dirname)

    def _diff_images(self):
        self.image_editor.update_image(self.np_img)
        basename = os.path.basename(str(self.image_saver.filename))
        try:
            golden_np_img = scipy.misc.imread(os.path.join(str(self.golden_images_dir), basename))
            is_ok, diff_img, percentage = self.image_editor.diff_images(golden_np_img)
            if not is_ok:
                QtGui.QMessageBox.about(self, 'Error', 'Images have different size.s')
            else:
                QtGui.QMessageBox.about(self, 'Diff percentage', 'diff: %.1f %%' % percentage)
                diff_filename = os.path.join(str(self.diff_images_dir), basename)
                if percentage:
                    self.image_saver.save_any(diff_img, diff_filename)
        except IOError:
            QtGui.QMessageBox.about(self, 'Error', 'There is no golden image with corresponding name.')

    def _open_file(self):
        self.np_img = self.image_opener.open_file()
        self.image_history.reset()
        self.image_history.add_new_state(self.np_img)
        self.image_saver.filename = self.image_opener.filename

        # in case of png files swap channels
        if self.np_img.shape[2] == 4:
            self.np_img = utils.bgra2rgba(self.np_img)
        self._show_np_image()

        self._enable_menu_items(True)
        self._enable_undo_redo()
        self.ui.actionSave_As.setEnabled(True)

    def _save_file(self):
        self.image_saver.np_img = self.np_img
        self.image_saver.save_file()
        self.ui.actionSave.setEnabled(False)

    def _undo(self):
        if self.image_history.can_undo():
            self.np_img = self.image_history.undo()
            self._show_np_image()
            self._enable_undo_redo()

    def _redo(self):
        if self.image_history.can_redo():
            self.np_img = self.image_history.redo()
            self._show_np_image()
            self._enable_undo_redo()

    def _enable_undo_redo(self):
        undo_state, redo_state = True, True
        if not self.image_history.can_redo():
            redo_state = False
        if not self.image_history.can_undo():
            undo_state = False
        self.ui.actionRedo.setEnabled(redo_state)
        self.ui.actionUndo.setEnabled(undo_state)

    def _show_np_image(self):
        img = utils.np_to_qimage(self.np_img)
        self._show_image(img)

    def _show_image(self, img):
        pixmap = QtGui.QPixmap.fromImage(img)
        pixmap = self.scale_pixmap(pixmap)
        self.view.setPixmap(pixmap)

    def scale_pixmap(self, pixmap):
        dest_height, dest_width = self.view.size().height(), self.view.size().width()
        if dest_height < pixmap.size().height():
            pixmap = pixmap.scaledToHeight(self.view.size().height())
        elif dest_width < pixmap.size().width():
            pixmap = pixmap.scaledToWidth(self.view.size().width())
        return pixmap

    def show_window(self):
        self.show()            
Esempio n. 33
0
class Main(QMainWindow):
    def __init__(self, *args):
        super(Main, self).__init__(*args)
        self.ui = Ui_Main()
        self.ui.setupUi(self)
        icon = QtGui.QIcon("favicon.ico")
        self.setWindowIcon(icon)
        self.download_windows = File_Manager()

        self.date = datetime.fromisoformat('2011-11-04T00:00:00')
        self.state = True
        self.ui.time.setText(self.date.strftime('%H:%M:%S'))

        self.ui.dialog.clicked.connect(self.show_dialog)
        self.ui.video.clicked.connect(self.on_video)
        self.ui.file.clicked.connect(self.file_browser)
        self.ui.set_ip.clicked.connect(self.set_ip)
        self.ui.file_2.clicked.connect(self.show_files)

        self.record_state = QTimer()
        self.record_state.setInterval(1000)
        self.record_state.timeout.connect(self.onTimerOut)
        self.runing_state = QTimer()
        self.runing_state.setInterval(1000)
        self.stopEvent = threading.Event()
        self.stopEvent.clear()

    def show_files(self):
        self.download_windows.show()

    def on_video(self):
        if self.state:
            self.date = datetime.fromisoformat('2011-11-04T00:00:00')
            self.ui.video.setText("Stop")
            self.record_state.start()
            th = threading.Thread(target=self.on_event)
            th.start()
            self.state = False
        else:
            self.ui.video.setText("Screen recorder")

            self.stopEvent.set()
            self.record_state.stop()
            self.state = True

    def onTimerOut(self):

        self.date = self.date + timedelta(seconds=1)
        self.ui.time.setText(self.date.strftime('%H:%M:%S'))

    def on_event(self):

        screen = ImageGrab.grab()
        now = datetime.now()
        filename = now.strftime("%Y%m%d%H%M%S") + '.avi'
        length, width = screen.size
        video_decode_style = cv2.VideoWriter_fourcc(*'XVID')
        video = cv2.VideoWriter(os.path.join(capture_path, filename),
                                video_decode_style, 8, (length, width))
        while True:
            im = ImageGrab.grab()
            imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
            video.write(imm)

            if self.stopEvent.is_set():
                self.record_state.stop()
                self.stopEvent.clear()
                break
        video.release()
        cv2.destroyAllWindows()

    def file_browser(self):

        QDesktopServices.openUrl(QUrl('file:///' + capture_path))

    def set_ip(self):

        text, ok = QInputDialog.getText(self, 'Input ip', 'input ip:')
        if ok:
            if check_ip(str(text)):
                self.ip = str(text)
                global used_ip
                used_ip = self.ip
                self.ui.ip.setText(str(text))
            else:
                show_box("Setting Error", "IP not valid")

    def show_dialog(self):
        show_box("失败", "First")
Esempio n. 34
0
class MainWindow(QMainWindow):
    # Constructor which set's up the Main Window's GUI context.
    def __init__(self):
        QMainWindow.__init__(self)
        self.toggleHistory = False
        self.context = Ui_MainWindow()
        self.context.setupUi(self)

        # Define's a media player that play's music and connects the seeker bar to it's seek position.
        self.player = QMediaPlayer()
        self.player.positionChanged.connect(self.updateSeeker)

        # Connects callback functions to the buttons in the GUI.
        self.context.btnPlay.clicked.connect(self.playMusic)
        self.context.btnPause.clicked.connect(self.pauseMusic)
        self.context.btnStop.clicked.connect(self.stopMusic)
        self.context.btnShuffle.clicked.connect(self.shuffleMusic)
        self.context.btnHistory.clicked.connect(self.switchHistory)
        self.context.btnClearHistory.clicked.connect(self.clearHistory)
        self.context.btnFund.clicked.connect(self.fundAccount)
        self.context.btnRefreshStore.clicked.connect(self.refreshStore)
        self.context.btnBuy.clicked.connect(self.buyMusic)
        self.context.btnCheckout.clicked.connect(self.checkout)
        self.context.btnPurchaseHistory.clicked.connect(self.showPurchases)
        self.context.seekSlider.sliderMoved.connect(self.setPosition)
        self.context.btnProfile.clicked.connect(self.showProfile)
        self.context.btnManager.clicked.connect(self.showManagerPanel)
        self.context.btnLogout.clicked.connect(self.logout)

        # Connects the history list to the media player.
        self.historyCount = 0
        self.context.btnClearHistory.setVisible(False)
        self.context.historyList.setVisible(False)
        self.context.historyList.setColumnWidth(0, 250)
        self.context.historyList.setColumnWidth(1, 60)
        self.context.historyList.setColumnWidth(2 , 150)
        self.context.historyList.verticalHeader().setVisible(False)
        self.context.historyList.cellDoubleClicked.connect(self.selectHistory)

        # Update's the GUI according to the current user's account info.
        self.updateAccountInfo()

    # Log's the user out of the system and saves the store's database.
    # Also pauses the music in order to prevent any interference when logging
    # into a different account from the previous login.
    def logout(self):
        global currentAccount
        currentAccount = Account()
        saveDatabase()

        loginForm.show()
        self.stopMusic()
        self.hide()

    # Updates and shows the manager panel if it is not already visible.
    def showManagerPanel(self):
        if (not managerPanel.isVisible()):
            managerPanel.updateSetList()
            managerPanel.exec_()

    # Updates and shows the profile dialog if it is not already visible.
    def showProfile(self):
        if (not profileDialog.isVisible()):
            profileDialog.updateDialog()
            profileDialog.exec_()

    # Updates and shows the purchase dialog if it is not already visible.
    def showPurchases(self):
        if (not purchaseHistory.isVisible()):
            purchaseHistory.updateHistory()
            purchaseHistory.exec_()

    # Updates and shows the checkout dialog if it is not already visible.
    def checkout(self):
        if (not checkoutForm.isVisible()):
            checkoutForm.updateCheckout()
            checkoutForm.exec_()

    # Returns the present song selected within the store's list. Return's null if no selection is made.
    def getCurrentSong(self):
        selectSong = None
        for index, song in songs.enum():
            if (song.title == self.context.storeList.item(self.context.storeList.currentRow(), 0).text()):
                selectSong = song
        return selectSong

    # Add's a track to the user's cart according to their selection.
    def buyMusic(self):
        currentSong = self.getCurrentSong()

        # Determines if the user already has the track in their cart or purchases.
        if (not currentAccount.hasTrack(currentSong)):
            # Determines if there are more than 10 tracks in their cart.
            if (len(currentAccount.orders) == 9):
                QMessageBox.information(self, "Buy Track", "You can only purchase 10 tracks at a time.")
            else:
                # Display a confirmation message stating whether or not the user wants to buy the song.
                reply = QMessageBox.question(self, "Buy Track",
                     "Are you sure you would like to add\n%s\nto your cart for $%s?" % (currentSong.title, str(currentSong.cost)), QMessageBox.Yes, QMessageBox.No)
                if (reply == QMessageBox.Yes):
                    currentAccount.orders.append(currentSong)
                    checkoutForm.updateCheckout()
        else:
            QMessageBox.information(self, "Buy Track", "This track is already in your cart, or you have already bought the track.")

    # Re-populates the store's inventory list.
    def refreshStore(self):
        loadMusic(False)

    # Funds the user's balance with an inputted amount of money.
    def fundAccount(self):
        try:
            currentAccount.fund(float(QInputDialog.getText(self, "Fund Account", "Amount:", QLineEdit.Normal, "0")[0]))
            QMessageBox.information(self, "Fund Account", "Your account has been successfully funded.")
        except ValueError:
            QMessageBox.information(self, "Fund Account", "The amount you wished to fund is invalid.")

    # Clear's the history list.
    def clearHistory(self):
        self.context.historyList.clearContents()
        self.context.historyList.setRowCount(0)
        self.historyCount = 0

    # Toggles between the history list and store inventory list.
    def switchHistory(self):
        self.toggleHistory = not self.toggleHistory
        self.context.historyList.setVisible(self.toggleHistory)
        self.context.btnClearHistory.setVisible(self.toggleHistory)
        self.context.storeList.setVisible(not self.toggleHistory)
        self.context.btnRefreshStore.setVisible(not self.toggleHistory)
        if (self.toggleHistory):
            self.context.btnHistory.setText("Browse Store")
        else:
            self.context.btnHistory.setText("Play History")

    # Updates the GUI according to the current user's info.
    def updateAccountInfo(self):
        global currentAccount
        self.context.cashLabel.setText("$%.2f" % (currentAccount.balance))

        # Set's the Manager Panel button visible if the user is a manager.
        self.context.btnManager.setVisible(currentAccount.status == MANAGER_ACCOUNT)

    # Re-populates the store inventory list.
    def fillMusicList(self):
        # Nullifies the present content in the store's inventory list.
        self.context.storeList.clearContents()

        # Re-populates the store list.
        self.context.storeList.setRowCount(songs.size())
        self.context.storeList.setSortingEnabled(False)
        for index, song in songs.enum():
            titleObj = QTableWidgetItem(song.title)
            durationObj = QTableWidgetItem(msToHms(int(song.duration)))
            artistObj = QTableWidgetItem(song.artist)
            priceObj = QTableWidgetItem(str(song.cost))

            # Set's each widget on the store list as read-only.
            titleObj.setFlags(Qt.ItemIsEnabled)
            durationObj.setFlags(Qt.ItemIsEnabled)
            artistObj.setFlags(Qt.ItemIsEnabled)
            priceObj.setFlags(Qt.ItemIsEnabled)

            self.context.storeList.setItem(index, 0, titleObj)
            self.context.storeList.setItem(index, 1, durationObj)
            self.context.storeList.setItem(index, 2, artistObj)
            self.context.storeList.setItem(index, 3, priceObj)

        # Defines the store column widths.
        self.context.storeList.setColumnWidth(0, 250)
        self.context.storeList.setColumnWidth(1, 60)
        self.context.storeList.setColumnWidth(2 , 150)
        self.context.storeList.setSortingEnabled(True)
        self.context.storeList.verticalHeader().setVisible(False)
        self.context.storeList.cellDoubleClicked.connect(self.selectSong)

        # Shows the user how many track's are in stock.
        self.context.trackCount.setText("There are currently %s tracks in stock." % (str(songs.size())))

    # A callback function that handles whenever a song is double clicked within the store inventory list.
    def selectSong(self, row, column):
        selectSong = self.getCurrentSong()
        if (selectSong != None): # Determine if a selection is present.
            self.context.seekSlider.setMaximum(int(selectSong.duration))
            self.context.songName.setText(selectSong.title)

            # Play's the song.
            self.setMusic(selectSong.streamUrl, True)

            # Shows the user the song's thumbnail if the song has a thumbnail. Otherwise shows a blank canvas.
            if (selectSong.imageUrl != None):
                try:
                    image = QPixmap()
                    image.loadFromData(urllib.request.urlopen(selectSong.imageUrl).read())
                    image = image.scaled(QSize(225, 225), Qt.KeepAspectRatio, Qt.SmoothTransformation);
                    scene = QGraphicsScene(self.context.songImage)
                    scene.addPixmap(image)
                    self.context.songImage.setScene(scene)
                except ValueError:
                    image = QPixmap()
                    scene = QGraphicsScene(self.context.songImage)
                    scene.addPixmap(image)

                    self.context.songImage.setScene(scene)

                # Add's the song to the history.
                self.addHistory(selectSong)

    # Add's an entry to the history list.
    def addHistory(self, song):
        tObj = QTableWidgetItem(song.title)
        dObj = QTableWidgetItem(msToHms(int(song.duration)))
        aObj = QTableWidgetItem(song.artist)
        pObj = QTableWidgetItem(str(song.cost))

        # Set the widget for the history column to be read-only.
        tObj.setFlags(Qt.ItemIsEnabled)
        dObj.setFlags(Qt.ItemIsEnabled)
        aObj.setFlags(Qt.ItemIsEnabled)
        pObj.setFlags(Qt.ItemIsEnabled)

        self.context.historyList.setRowCount(self.historyCount + 1)
        self.context.historyList.setItem(self.historyCount, 0, tObj)
        self.context.historyList.setItem(self.historyCount, 1, dObj)
        self.context.historyList.setItem(self.historyCount, 2, aObj)
        self.context.historyList.setItem(self.historyCount, 3, pObj)
        self.historyCount += 1

    # A callback function that handles whenever a song is double clicked within the history list.
    def selectHistory(self, row, column):
        selectSong = self.getCurrentSong()
        if (selectSong != None): # Determines if a selection is present.
            self.context.seekSlider.setMaximum(int(selectSong.duration))
            self.context.songName.setText(selectSong.title)

            # Play's the song.
            self.setMusic(selectSong.streamUrl, True)

            # Shows the user the song's thumbnail if the song has a thumbnail. Otherwise shows a blank canvas.
            if (selectSong.imageUrl != None):
                try:
                    image = QPixmap()
                    image.loadFromData(urllib.request.urlopen(selectSong.imageUrl).read())
                    image = image.scaled(QSize(225, 225), Qt.KeepAspectRatio, Qt.SmoothTransformation);
                    scene = QGraphicsScene(self.context.songImage)
                    scene.addPixmap(image)
                    self.context.songImage.setScene(scene)
                except ValueError:
                    image = QPixmap()
                    scene = QGraphicsScene(self.context.songImage)
                    scene.addPixmap(image)
                    self.context.songImage.setScene(scene)

    # Play's or sets a song on the media player according to a given stream URL.
    def setMusic(self, streamUrl, play=False):
        global soundcloud_api_key
        self.player.setMedia(QMediaContent(QUrl(streamUrl + "?client_id=" + soundcloud_api_key)))
        if (play):
            self.playMusic()

    # A callback function that binds the media player's seek position to the seek slider's position.
    def setPosition(self):
        self.player.setPosition(self.context.seekSlider.sliderPosition())

    # Update's the seek slider's position as the media player streams a song.
    # Also update's the audio position label to the media player.
    def updateSeeker(self, position):
        self.context.seekSlider.setSliderPosition(position)
        self.context.audioPosition.setText(msToHms(position))

    # Randomly play's a song in the store's inventory list.
    def shuffleMusic(self):
        randomRow = random.randint(0, self.context.storeList.rowCount())
        self.context.storeList.setCurrentCell(randomRow, 0)
        self.selectSong(randomRow, 0)

    # Tell's the media player to play.
    def playMusic(self):
        self.player.play()

    # Tell's the media player to pause itself.
    def pauseMusic(self):
        self.player.pause()

    # Tell's the media player to pause itself and seek the current media towards it's
    # initial point.
    def stopMusic(self):
        self.player.stop()
Esempio n. 35
0
class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

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

        self.setupSignalsSlots()
        self.switchToMain()

        self.current_id = None

        self.led_model = LedModel()

        db = QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName('led-tool.db')
        db.open()

        self.manufacturers_model = QSqlTableModel()
        self.manufacturers_model.setTable("manufacturers")
        self.manufacturers_model.select()

        self.ui.brightness_group_table_view.setModel(self.led_model)

        self.ui.manufacturer_combo.setModel(self.manufacturers_model)
        self.ui.manufacturer_combo.setModelColumn(1)

        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(self.led_model)
        self.mapper.addMapping(self.ui.name_edit, 1)
        self.mapper.addMapping(self.ui.typical_voltage_spin, 6)
        self.mapper.addMapping(self.ui.typical_current_spin, 7)
        self.mapper.addMapping(self.ui.thermal_resistance_spin, 4)
        self.mapper.addMapping(self.ui.reference_temperature_spin, 5)
        self.mapper.addMapping(self.ui.manufacturer_combo, 3)
        self.mapper.toFirst()

        self.ui.led_filter.installEventFilter(self)

        self.ui.main_stacked_widget.setCurrentIndex(1)
        self.ui.editor_stacked_widget.setCurrentIndex(0)

    def setupSignalsSlots(self):
        self.ui.edit_led_button.clicked.connect(self.switchToEditor)
        self.ui.buttonBox.clicked.connect(self.switchToMain)

    def switchToEditor(self):
        self.ui.main_stacked_widget.setCurrentIndex(1)

    def switchToMain(self):
        self.ui.main_stacked_widget.setCurrentIndex(0)

    def eventFilter(self, source, event):
        if source is self.ui.led_filter:
            if event.type() == QEvent.KeyPress:
                if event.key() == Qt.Key_Escape:
                    self.ui.led_filter.clear()
        return QWidget.eventFilter(self, source, event)

    def keyPressEvent(self, event):

        default = True

        if event.key() == Qt.Key_Escape:
            self.switchToMain()
            default = False
#        if (event.modifiers() & Qt.ControlModifier):
#            if event.key() == Qt.Key_C: #copy
#                self.copyTableToClipboard()
#                default = False
#
#            if event.key() == Qt.Key_V: #paste
#                self.pasteClipboardToTable()
#                default = False

        if default:
            super(Window, self).keyPressEvent(event)
Esempio n. 36
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ########################################################################
        ## START - WINDOW ATTRIBUTES
        ########################################################################

        ## REMOVE ==> STANDARD TITLE BAR
        UIFunctions.removeTitleBar(True)
        ## ==> END ##

        ## SET ==> WINDOW TITLE
        self.setWindowTitle('Process Mining')
        UIFunctions.labelTitle(self, 'Process Mining')
        ## ==> END ##

        ## WINDOW SIZE ==> DEFAULT SIZE
        startSize = QSize(1000, 720)
        self.resize(startSize)
        self.setMinimumSize(startSize)
        ## ==> END ##

        ## ==> CREATE MENUS
        ########################################################################

        ## ==> TOGGLE MENU SIZE
        self.ui.btn_toggle_menu.clicked.connect(
            lambda: UIFunctions.toggleMenu(self, 220, True))
        ## ==> END ##

        ## ==> ADD CUSTOM MENUS
        self.ui.stackedWidget.setMinimumWidth(20)
        UIFunctions.addNewMenu(self, "Home", "btn_home",
                               "url(:/16x16/icons/16x16/cil-home.png)", True)
        UIFunctions.addNewMenu(self, "Calcular Log", "btn_log",
                               "url(:/16x16/icons/16x16/cil-chart.png)", True)
        UIFunctions.addNewMenu(self, "Previsão de Estado", "btn_preve",
                               "url(:/16x16/icons/16x16/cil-chart-line.png)",
                               True)
        UIFunctions.addNewMenu(self, "Exportar Dados", "btn_ex",
                               "url(:/16x16/icons/16x16/cil-share-boxed.png)",
                               True)
        UIFunctions.addNewMenu(
            self, "Mostrar Arquivo", "btn_show1",
            "url(:/16x16/icons/16x16/cil-justify-center.png)", True)
        UIFunctions.addNewMenu(self, "Mostrar Log", "btn_show2",
                               "url(:/16x16/icons/16x16/cil-notes.png)", True)

        ## ==> END ##

        # START MENU => SELECTION
        UIFunctions.selectStandardMenu(self, "btn_log")
        ## ==> END ##

        ## ==> START PAGE
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_home)

        ## ==> END ##

        ## ==> MOVE WINDOW / MAXIMIZE / RESTORE
        ########################################################################
        def moveWindow(event):
            # IF MAXIMIZED CHANGE TO NORMAL
            if UIFunctions.returStatus(self) == 1:
                UIFunctions.maximize_restore(self)

            # MOVE WINDOW
            if event.buttons() == Qt.LeftButton:
                self.move(self.pos() + event.globalPos() - self.dragPos)
                self.dragPos = event.globalPos()
                event.accept()

        # WIDGET TO MOVE
        self.ui.frame_label_top_btns.mouseMoveEvent = moveWindow
        ## ==> END ##

        ## ==> LOAD DEFINITIONS
        ########################################################################
        UIFunctions.uiDefinitions(self)

        ## SHOW ==> MAIN WINDOW
        ########################################################################
        self.show()
        ## ==> END ##

        ########################################################################
        ## MENUS ==> DYNAMIC MENUS FUNCTIONS
        ########################################################################

    def Button(self):
        # GET BT CLICKED
        btnWidget = self.sender()

        # PAGE 0
        if btnWidget.objectName() == "btn_home":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_home)
            UIFunctions.resetStyle(self, "btn_home")
            UIFunctions.labelPage(self, "Home")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        # PAGE 1
        if btnWidget.objectName() == "btn_log":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_calculate)
            UIFunctions.resetStyle(self, "btn_log")
            UIFunctions.labelPage(self, "Calculate Log")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        # PAGE 2
        if btnWidget.objectName() == "btn_preve":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_preve)
            UIFunctions.resetStyle(self, "btn_preve")
            UIFunctions.labelPage(self, "State Forecast")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        # PAGE 3
        if btnWidget.objectName() == "btn_ex":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_expor)
            UIFunctions.resetStyle(self, "btn_ex")
            UIFunctions.labelPage(self, "Export Excel")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        # PAGE 4
        if btnWidget.objectName() == "btn_show1":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_showFile)
            UIFunctions.resetStyle(self, "btn_show1")
            UIFunctions.labelPage(self, "Show File")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        # PAGE 5
        if btnWidget.objectName() == "btn_show2":
            self.ui.stackedWidget.setCurrentWidget(self.ui.page_showLog)
            UIFunctions.resetStyle(self, "btn_show2")
            UIFunctions.labelPage(self, "Show Log")
            btnWidget.setStyleSheet(
                UIFunctions.selectMenu(btnWidget.styleSheet()))

        ## EVENT ==> MOUSE DOUBLE CLICK
        ########################################################################

    def eventFilter(self, watched, event):
        if watched == self.le and event.type(
        ) == QtCore.QEvent.MouseButtonDblClick:
            print("pos: ", event.pos())
        ## ==> END ##

        ## EVENT ==> MOUSE CLICK
        ########################################################################

    def mousePressEvent(self, event):
        self.dragPos = event.globalPos()

        ## ==> END ##

        ## ==> SET VALUES TO DEF progressBarValue
        def setValue(self, slider, labelPercentage, progressBarName, color):

            # GET SLIDER VALUE
            value = slider.value()

            # CONVERT VALUE TO INT
            sliderValue = int(value)

            # HTML TEXT PERCENTAGE
            htmlText = """<p align="center"><span style=" font-size:50pt;">{VALUE}</span><span style=" font-size:40pt; vertical-align:super;">%</span></p>"""
            labelPercentage.setText(
                htmlText.replace("{VALUE}", str(sliderValue)))

            # CALL DEF progressBarValue
            self.progressBarValue(sliderValue, progressBarName, color)

    ## DEF PROGRESS BAR VALUE
    ########################################################################
    def progressBarValue(self, value, widget, color):

        # PROGRESSBAR STYLESHEET BASE
        styleSheet = """
        QFrame{
        	border-radius: 110px;
        	background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:{STOP_1} rgba(255, 0, 127, 0), stop:{STOP_2} {COLOR});
        }
        """

        # GET PROGRESS BAR VALUE, CONVERT TO FLOAT AND INVERT VALUES
        # stop works of 1.000 to 0.000
        progress = (100 - value) / 100.0

        # GET NEW VALUES
        stop_1 = str(progress - 0.001)
        stop_2 = str(progress)

        # FIX MAX VALUE
        if value == 100:
            stop_1 = "1.000"
            stop_2 = "1.000"

        # SET VALUES TO NEW STYLESHEET
        newStylesheet = styleSheet.replace("{STOP_1}", stop_1).replace(
            "{STOP_2}", stop_2).replace("{COLOR}", color)

        # APPLY STYLESHEET WITH NEW VALUES
        widget.setStyleSheet(newStylesheet)
Esempio n. 37
0
class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):

        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.server_pointers = []
        self.config_file = "config"

        self.server_list_layout = QtGui.QVBoxLayout()
        self.ui.server_list_container.setLayout(self.server_list_layout)

        self.ui.tab.content_set = "server_list"

        self.connect(self.ui.add_server_button, 
            QtCore.SIGNAL('pressed()'),self.add_server_to_list)

        self.connect(self.ui.tabWidget,
            QtCore.SIGNAL("currentChanged(int)"),self.tab_changed)

        ### menu triggers
        ### wonder if i can connect this ways buttons, etc...
        ### lazy to read manual for it :P
        self.ui.actionExit.triggered.connect(QtGui.qApp.quit)
        ### :'-(((can not connect to a function)))-':
        #self.ui.actionOpen.triggered.connect(self.open_config_file())
        self.connect(self.ui.actionOpen,
            QtCore.SIGNAL("triggered()"),self.open_config_file)

        self.get_servers_from_config()

        

    def open_config_file(self):
        open_dialog = QtGui.QFileDialog()
        # open_dialog.exec_()

        # print open_dialog

        self.config_file = open_dialog.getOpenFileName()
        self.rebuild_config_gui(self.config_file)

    def rebuild_config_gui(self, config_file):
        print self.server_pointers
        for server in self.server_pointers:
            server.remove_server()
            print self.server_pointers

        self.get_servers_from_config(config_file)


    def add_server_to_list(self,name="",ip="",user="",passwd="",port="22"):
        
        server = ServerGUI_Node(self,name,ip,user,passwd,port)
        if self.server_pointers != None:
            self.server_pointers.append(server)
        else:
            self.server_pointers = []
            self.server_pointers.append(server)

        self.server_list_layout.addWidget(server.group_box)
        

        # self.ui.server_list_layout.addWidget(group_box)

    def get_servers_from_config(self, config_file=None):
        server_list = server_connect.get_config(config_file)
        print server_list.server_list
        for server in server_list.server_list:

            self.add_server_to_list(server.name,server.ip,
                server.user,server.passwd,server.port)

    def set_edit_conf_menu_active(self):
        self.ui.menuConfiguration.setDisabled(False)

    def tab_changed(self, i):
        if self.ui.tabWidget.currentWidget().content_set == "conf":
            self.set_edit_conf_menu_active()
        elif self.ui.tabWidget.currentWidget().content_set == "server_list":
            self.ui.menuConfiguration.setDisabled(True)