Ejemplo n.º 1
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # set up ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle('Chess Analyser')

        # connect signals
        self.ui.findButton.clicked.connect(self._onFindClicked)
        self.ui.AnalyseButton.clicked.connect(self._onAnalyseClicked)

    def _onFindClicked(self):
        '''do stuff '''

    def _onAnalyseClicked(self):
        filePath = self.ui.filePath.text()
        analyser = Analyser(filePath)
        list = analyser.analyse()
        print(list)
        display = ConsolDisplay(list, self)
        display.show()
        display.update()
        display.output()
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.cap = cv2.VideoCapture(0)
        self.timer = QTimer()
        self.timer.start(20)
        self.box = cv2.imread('box.bmp')
        host = 'localhost'
        user = '******'
        password = '******'
        db = 'face_pay'
        charset = 'utf8'
        try:
            self.connection = pymysql.connect(host=host,
                                              user=user,
                                              password=password,
                                              db=db,
                                              charset=charset)
        except pymysql.err.OperationalError as e:
            QMessageBox.warning(self, '警告', '无法连接数据库')
            self.close()
            return
        self.face_handle = Face_handle('known_people_folder/', self.connection)

        self.UI = Ui_MainWindow()
        self.UI.setupUi(self)
        self.signal_connect()
Ejemplo n.º 3
0
    def __init__(self):
        super(UI, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.buttonShowStats.setEnabled(False)

        self.changed_individual.connect(self.changeIndividual)
        self.changed_individual_hc.connect(self.changeIndividualHC)
        self.threadevo_finished.connect(self.threadEvoFinished)
        self.threadhc_finished.connect(self.threadHCFinished)
        self.threadstat_finished.connect(self.statisticsFinished)

        self.ui.buttonStart.clicked.connect(self.onClickButtonStart)
        self.ui.buttonStop.clicked.connect(self.onClickButtonStop)
        self.ui.startHCdef.clicked.connect(self.onClickButtonStartHCdef)
        self.ui.startHCevo.clicked.connect(self.onClickButtonStartHCevo)
        self.ui.buttonStopHC.clicked.connect(self.onClickButtonStopHC)
        self.ui.buttonStatistics.clicked.connect(self.onClickButtonStatistics)
        self.ui.buttonShowStats.clicked.connect(self.showStatistics)
Ejemplo n.º 4
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # set up ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle('Chess Analyser')

        # connect signals
        self.ui.findButton.clicked.connect(self._onFindClicked)
        self.ui.AnalyseButton.clicked.connect(self._onAnalyseClicked)
Ejemplo n.º 5
0
import sys
from ModelParser import ModelParser
from UI_MainWindow import Ui_MainWindow
from PyQt5 import QtCore, QtWidgets, QtOpenGL

if __name__ == '__main__':
    model_parser = ModelParser('model1.obj')

    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QMainWindow()
    ui = Ui_MainWindow(Form, model_parser=model_parser)
    ui.show()

    sys.exit(app.exec_())
Ejemplo n.º 6
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.cap = cv2.VideoCapture(0)
        self.timer = QTimer()
        self.timer.start(20)
        self.box = cv2.imread('box.bmp')
        host = 'localhost'
        user = '******'
        password = '******'
        db = 'face_pay'
        charset = 'utf8'
        try:
            self.connection = pymysql.connect(host=host,
                                              user=user,
                                              password=password,
                                              db=db,
                                              charset=charset)
        except pymysql.err.OperationalError as e:
            QMessageBox.warning(self, '警告', '无法连接数据库')
            self.close()
            return
        self.face_handle = Face_handle('known_people_folder/', self.connection)

        self.UI = Ui_MainWindow()
        self.UI.setupUi(self)
        self.signal_connect()

    def signal_connect(self):
        self.timer.timeout.connect(self.play_video)
        self.UI.pay_btn.clicked.connect(self.pay)
        self.UI.add_new_user_btn.clicked.connect(self.add_new_client)
        self.UI.show_balance_btn.clicked.connect(self.show_balance)

    @pyqtSlot(name="play_video")
    def play_video(self):
        ret, frame = self.cap.read()
        frame = cv2.rectangle(frame, (100, 50), (500, 300), (0, 0, 255), 3)
        if ret:
            MainWindow.play_frame(self.UI.video_label, frame)

    @staticmethod
    def play_frame(label: QtWidgets.QLabel, frame: ndarray):
        rbgframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        convert_to_qt = QImage(rbgframe, rbgframe.shape[1], rbgframe.shape[0],
                               QImage.Format_RGB888)
        label.setPixmap(QPixmap.fromImage(convert_to_qt))

    @pyqtSlot(name='recognise_face')
    def pay(self):
        """
            this function recognise face from the current frame
          cut out the face part and show it in a other label, the
          name display in the label blow
        :return: None
        """
        self.timer.timeout.disconnect(self.play_video)
        ret, frame = self.cap.read()
        frame = frame[50:300, 100:500]
        name, box = self.face_handle.recognise(frame)
        if name is not None:
            top, right, bottom, left = box
            face_part = frame[top:bottom, left:right]
            new_size = self.UI.face.size().height(), self.UI.face.size().width(
            )
            face_part = cv2.resize(face_part, new_size)
            self.play_frame(self.UI.face, face_part)
            self.UI.name_label.setText(name)
            pay_num = self.UI.pay_num_edit.text()
            if len(pay_num) == 0:
                QMessageBox.warning(self, '错误', '请输入金额')
                self.timer.timeout.connect(self.play_video)
                return
            if QMessageBox.question(self, '提示', '确认支付?') == QMessageBox.Yes:
                with self.connection.cursor() as cursor:
                    sql = 'UPDATE `client_record` SET `balance` = `balance` - %s WHERE `user_name` = %s'
                    cursor.execute(sql, (self.UI.pay_num_edit.text(), name))
                self.connection.commit()
        else:
            self.UI.name_label.setText(box)
        self.timer.timeout.connect(self.play_video)

    @pyqtSlot(name='add_new_client')
    def add_new_client(self):
        self.timer.timeout.disconnect(self.play_video)
        ret, frame = self.cap.read()
        add_client = AddClientWindow(self, self.connection, self.face_handle,
                                     frame)
        if add_client.exec() == QDialog.Rejected:
            QMessageBox.information(self, '提示', '取消新增客户')

        self.timer.timeout.connect(self.play_video)

    @pyqtSlot(name='show_balance')
    def show_balance(self):
        self.timer.timeout.disconnect(self.play_video)
        ret, frame = self.cap.read()
        name, box = self.face_handle.recognise(frame)
        sql = 'SELECT `balance` FROM `client_record` WHERE `user_name` = %s'
        with self.connection.cursor() as cursor:
            cursor.execute(sql, name)
            result = cursor.fetchone()
            balance = result[0]
            QMessageBox.information(self, '余额', '%f' % balance)
        self.timer.timeout.connect(self.play_video)
Ejemplo n.º 7
0
class UI(QtWidgets.QMainWindow):
    # Signals
    changed_individual = pyqtSignal(list)
    changed_individual_hc = pyqtSignal(list)
    threadevo_finished = pyqtSignal(str)
    threadhc_finished = pyqtSignal(str)
    threadstat_finished = pyqtSignal(list)

    # Threads
    ThreadEVO = None
    ThreadHC = None
    ThreadStatistics = None

    # Thread Flags
    threadevo_interrupt = False
    threadhc_interrupt = False

    # Result of preious Evolutionary alg
    evo_res = None

    # Statistics
    fitness_array = None

    def __init__(self):
        super(UI, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.buttonShowStats.setEnabled(False)

        self.changed_individual.connect(self.changeIndividual)
        self.changed_individual_hc.connect(self.changeIndividualHC)
        self.threadevo_finished.connect(self.threadEvoFinished)
        self.threadhc_finished.connect(self.threadHCFinished)
        self.threadstat_finished.connect(self.statisticsFinished)

        self.ui.buttonStart.clicked.connect(self.onClickButtonStart)
        self.ui.buttonStop.clicked.connect(self.onClickButtonStop)
        self.ui.startHCdef.clicked.connect(self.onClickButtonStartHCdef)
        self.ui.startHCevo.clicked.connect(self.onClickButtonStartHCevo)
        self.ui.buttonStopHC.clicked.connect(self.onClickButtonStopHC)
        self.ui.buttonStatistics.clicked.connect(self.onClickButtonStatistics)
        self.ui.buttonShowStats.clicked.connect(self.showStatistics)

    def onClickButtonStart(self):
        individualsize = int(self.ui.individualSize.text())
        noIterations = int(self.ui.noIterations.text())
        probability = float(self.ui.mutationProb.text())
        popsize = int(self.ui.populationSize.text())
        reprate = float(self.ui.reproductionRate.text())
        #evolutionary(noIterations, individualsize, popsize, probability, reprate, self.ui)

        self.ThreadEVO = threading.Thread(target=self.evolutionaryThread, \
        args=[noIterations, individualsize, popsize, probability, reprate])

        self.ui.statusEvo.setText("Running")
        self.threadevo_interrupt = False
        self.ui.buttonStart.setEnabled(False)
        self.ThreadEVO.start()

    def onClickButtonStop(self):
        self.threadevo_interrupt = True

    def onClickButtonStartHCdef(self):
        individualsize = int(self.ui.individualSizeHC.text())

        self.ThreadHC = threading.Thread(target=self.hillClimbingThread, \
        args=[individualsize])

        self.ui.statusHC.setText("Running")
        self.threadhc_interrupt = False
        self.ui.startHCdef.setEnabled(False)
        self.ui.startHCevo.setEnabled(False)

        self.ThreadHC.start()

    def onClickButtonStartHCevo(self):
        if self.evo_res is None:
            self.ui.statusHC.setText(
                "ERROR: No evolution result, run evolution")
            return

        self.ThreadHC = threading.Thread(target=self.hillClimbingThread,
                                         args=[None])

        self.ui.statusHC.setText("Running")
        self.threadhc_interrupt = False
        self.ui.startHCdef.setEnabled(False)
        self.ui.startHCevo.setEnabled(False)

        self.ThreadHC.start()

    def onClickButtonStopHC(self):
        self.threadhc_interrupt = True

    def changeIndividual(self, l):
        self.ui.displayCurrent.setText(format_individual(l[1]))
        self.ui.lineFitness.setText(str(l[0]))
        self.evo_res = l

    def changeIndividualHC(self, l):
        self.ui.displayCurrentHC.setText(format_individual(l[1]))
        self.ui.lineFitnessHC.setText(str(l[0]))

    def threadEvoFinished(self, status):
        self.ui.statusEvo.setText(status)
        self.ui.buttonStart.setEnabled(True)

    def threadHCFinished(self, status):
        self.ui.statusHC.setText(status)
        self.ui.startHCdef.setEnabled(True)
        self.ui.startHCevo.setEnabled(True)

    def evolutionaryThread(self, noIterations, individualsize, popsize,
                           probability, reprate):
        p = population(popsize, individualsize)

        cur = p[0]
        for _ in range(noIterations):
            if self.threadevo_interrupt is True:
                self.threadevo_finished.emit("Stopped")
                return

            p = iteration(p, probability, reprate)

            if p[0][0] == 0:
                break

            if cur != p[0]:
                cur = p[0]
                self.changed_individual.emit(cur)

        graded = sorted(p, key=lambda x: x[0])

        best = graded[0]

        self.changed_individual.emit(best)
        self.threadevo_finished.emit("Finished")

    def hillClimbingThread(self, size):

        if size is None:
            start = copy.deepcopy(self.evo_res[1])
        else:
            start = individual(size)

        (curFit, curNode) = generateNextBestNeighbor(start)

        while True:
            if self.threadhc_interrupt is True:
                self.threadhc_finished.emit("Stopped")
                return

            if curFit == 0:
                self.changed_individual_hc.emit([fitness(curNode), curNode])
                self.threadhc_finished.emit("Finished")
                return curNode

            (newFit, newNode) = generateNextBestNeighbor(curNode)

            self.changed_individual_hc.emit([newFit, newNode])
            if newFit == curFit:
                self.threadhc_finished.emit("Finished")
                return newNode

            curFit = newFit
            curNode = newNode

    def statisticsFinished(self, array):
        self.fitness_array = array
        self.ui.buttonStatistics.setEnabled(True)
        self.ui.buttonShowStats.setEnabled(True)
        self.ui.buttonStatistics.setText("Recalculate Statistics")

    def calculateStatistics(self):
        fitness = list()

        for _ in range(30):
            fitness.append(self.statistics())

        self.threadstat_finished.emit(fitness)

    def onClickButtonStatistics(self):
        self.ui.buttonStatistics.setEnabled(False)
        self.ui.buttonShowStats.setEnabled(False)
        self.ui.buttonStatistics.setText("Calculating...")
        self.ThreadStatistics = threading.Thread(
            target=self.calculateStatistics)
        self.ThreadStatistics.start()

    def showStatistics(self):
        mean = np.mean(self.fitness_array)
        std = sqrt(np.var(self.fitness_array))

        plt.plot(self.fitness_array)
        plt.xlabel("mean: " + str(mean) + "; std deviation: " + str(std))
        plt.show()

    def statistics(self):
        """
        Statistics of the fitness function with: populationsize = 40, individualsize = 4,
        noiterations = 1000, mutationProb = reproductionRate = 0.5
        """

        p = population(40, 5)

        for _ in range(1000):
            p = iteration(p, 0.5, 0.5)

            if p[0][0] == 0:
                break

        return p[0][0]
Ejemplo n.º 8
0
 def __init__(self, parent=None):
     super(MainWindow, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     
     # Link to the Db
     self.dblink = Db()
     # Servers pool for basic monitoring
     self.servers = ServersPool()
     
     # List of opened tabs
     self.tabs = {}
     self.servers_items = {}
     self.welcome_tab = True
     
     self.threads = []
     
     # Add connectors to the "Add server" button and menu
     self.connect(self.ui.pbAddServer, QtCore.SIGNAL('clicked()'),
                  self.on_event_pbAddServer_clicked)
     
     self.connect(self.ui.actionAdd_server, QtCore.SIGNAL('triggered()'),
                  self.on_event_pbAddServer_clicked)
     
     # Add connectors to the "Edit server" button
     self.connect(self.ui.pbEditServer, QtCore.SIGNAL('clicked()'),
                  self.on_event_pbEditServer_clicked)
     
     # Add connector to "Delete server" button
     self.connect(self.ui.pbDelServer, QtCore.SIGNAL('clicked()'),
                  self.on_event_pbDelServer_clicked)
     
     # Add connector to "Reconnect to server" button
     self.connect(self.ui.pbRefreshServer, QtCore.SIGNAL('clicked()'),
                  self.on_event_pbRefreshServer_clicked)
     
     # Add connectors to the "Manage logins and passwords" button and menu
     self.connect(self.ui.actionManage_logins_and_passwords, QtCore.SIGNAL('triggered()'),
                  self.on_actionManage_logins_and_passwords_clicked)
     
     # Add connectors to the "Send a command to servers" menu
     self.connect(self.ui.actionSend_a_command_to_servers, QtCore.SIGNAL('triggered()'),
                  self.on_actionSend_a_command_to_servers_clicked)
     
     # Add connectors to the "Manage bookmarks" menu
     self.connect(self.ui.actionManage_bookmarks, QtCore.SIGNAL('triggered()'),
                  self.on_actionManage_bookmarks_clicked)
     
     # Add connectors to the "Read Help" menu
     self.connect(self.ui.actionRead_Help, QtCore.SIGNAL('triggered()'),
                  self.on_actionRead_Help_clicked)
     
     # "About" trigger
     self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'),
                  self.on_actionAbout_clicked)
     
     # Add connector to the servers list
     self.connect(self.ui.lwServers, QtCore.SIGNAL('itemDoubleClicked(QListWidgetItem *)'),
                  self.on_event_lwServers_itemDoubleClicked)
     
     # Add context menu to the servers list
     self.connect(self.ui.lwServers, QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'),
                  self.on_lwservers_contextmenu_requested)
     
     ### BEGIN CONTEXT MENU
     # Add context menu to the servers list
     self.contextMenu = QtGui.QMenu(self.tr('Context menu'), self)
     openAction = self.contextMenu.addAction(self.tr('Open advanced monitoring'))
     sendCommandAction = self.contextMenu.addAction(self.tr('Send a command'))
     openInteractAction = self.contextMenu.addAction(self.tr('Open an interactive shell'))
     editAction = self.contextMenu.addAction(self.tr('Edit'))
     deleteAction = self.contextMenu.addAction(self.tr('Delete'))
     reconnectAction = self.contextMenu.addAction(self.tr('Reconnect'))
     
     # Add connectors
     self.connect(openAction, QtCore.SIGNAL('triggered()'),
                  self.on_contextmenu_openAction_clicked)
     
     # Add connectors
     self.connect(sendCommandAction, QtCore.SIGNAL('triggered()'),
                  self.on_contextmenu_sendCommandAction_clicked)
     
     # Add connectors
     self.connect(openInteractAction, QtCore.SIGNAL('triggered()'),
                  self.on_contextmenu_openInteractAction_clicked)
     
     # Add connectors
     self.connect(editAction, QtCore.SIGNAL('triggered()'),
                  self.on_contextmenu_editAction_clicked)
     
     # Add connectors
     self.connect(deleteAction, QtCore.SIGNAL('triggered()'),
                  self.on_contextmenu_deleteAction_clicked)
     
     # Add connectors
     self.connect(reconnectAction, QtCore.SIGNAL('triggered()'),
                  self.on_contextmenu_reconnectAction_clicked)
     ### END CONTEXT MENU
     
     # Close tab from advanced monitors
     self.connect(self.ui.twMonitor, QtCore.SIGNAL('tabCloseRequested(int)'),
                  self.removeTab)
     
     # "Reduce to tray" trigger
     self.connect(self.ui.actionReduce, QtCore.SIGNAL('triggered()'),
                  self.hide)
     
     # Setup icons
     self.online_icon = QtGui.QIcon()
     self.online_icon.addPixmap(QtGui.QPixmap(':/img/Tick-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
     
     self.offline_icon = QtGui.QIcon()
     self.offline_icon.addPixmap(QtGui.QPixmap(':/img/Notconnected-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
     self.offline_icon.addPixmap(QtGui.QPixmap(":/img/Notconnected-32.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
     
     self.waiting_icon = QtGui.QIcon()
     self.waiting_icon.addPixmap(QtGui.QPixmap(':/img/Clock-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
     self.waiting_icon.addPixmap(QtGui.QPixmap(":/img/Clock-32.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
     
     self.warning_icon = QtGui.QIcon()
     self.warning_icon.addPixmap(QtGui.QPixmap(':/img/Warning-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
     
     self.tab_icon = QtGui.QIcon()
     self.tab_icon.addPixmap(QtGui.QPixmap(':/img/Statistics_32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
     
     # Setup the tray icon
     self.trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon(':/img/Activity-monitor-32.png'), self)
     menu = QtGui.QMenu(self)
     openAction = menu.addAction(self.tr('Open'))
     closeAction = menu.addAction(self.tr('Reduce to tray'))
     exitAction = menu.addAction(self.tr('Exit'))
     self.trayIcon.setContextMenu(menu)
     self.trayIcon.show()
     
     self.connect(openAction, QtCore.SIGNAL('triggered()'),
                  self.show)
     
     self.connect(closeAction, QtCore.SIGNAL('triggered()'),
                  self.hide)
     
     self.connect(exitAction, QtCore.SIGNAL('triggered()'),
                  self.close)
     
     self.connect(self.trayIcon, QtCore.SIGNAL('activated(QSystemTrayIcon::ActivationReason)'),
                  self.on_iconActivated)
     
     self.connect(self.trayIcon, QtCore.SIGNAL('messageClicked()'),
                  self.on_iconMessageClicked)
     
     # Fill the servers list
     self.fillServersList()
Ejemplo n.º 9
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        # Link to the Db
        self.dblink = Db()
        # Servers pool for basic monitoring
        self.servers = ServersPool()
        
        # List of opened tabs
        self.tabs = {}
        self.servers_items = {}
        self.welcome_tab = True
        
        self.threads = []
        
        # Add connectors to the "Add server" button and menu
        self.connect(self.ui.pbAddServer, QtCore.SIGNAL('clicked()'),
                     self.on_event_pbAddServer_clicked)
        
        self.connect(self.ui.actionAdd_server, QtCore.SIGNAL('triggered()'),
                     self.on_event_pbAddServer_clicked)
        
        # Add connectors to the "Edit server" button
        self.connect(self.ui.pbEditServer, QtCore.SIGNAL('clicked()'),
                     self.on_event_pbEditServer_clicked)
        
        # Add connector to "Delete server" button
        self.connect(self.ui.pbDelServer, QtCore.SIGNAL('clicked()'),
                     self.on_event_pbDelServer_clicked)
        
        # Add connector to "Reconnect to server" button
        self.connect(self.ui.pbRefreshServer, QtCore.SIGNAL('clicked()'),
                     self.on_event_pbRefreshServer_clicked)
        
        # Add connectors to the "Manage logins and passwords" button and menu
        self.connect(self.ui.actionManage_logins_and_passwords, QtCore.SIGNAL('triggered()'),
                     self.on_actionManage_logins_and_passwords_clicked)
        
        # Add connectors to the "Send a command to servers" menu
        self.connect(self.ui.actionSend_a_command_to_servers, QtCore.SIGNAL('triggered()'),
                     self.on_actionSend_a_command_to_servers_clicked)
        
        # Add connectors to the "Manage bookmarks" menu
        self.connect(self.ui.actionManage_bookmarks, QtCore.SIGNAL('triggered()'),
                     self.on_actionManage_bookmarks_clicked)
        
        # Add connectors to the "Read Help" menu
        self.connect(self.ui.actionRead_Help, QtCore.SIGNAL('triggered()'),
                     self.on_actionRead_Help_clicked)
        
        # "About" trigger
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'),
                     self.on_actionAbout_clicked)
        
        # Add connector to the servers list
        self.connect(self.ui.lwServers, QtCore.SIGNAL('itemDoubleClicked(QListWidgetItem *)'),
                     self.on_event_lwServers_itemDoubleClicked)
        
        # Add context menu to the servers list
        self.connect(self.ui.lwServers, QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'),
                     self.on_lwservers_contextmenu_requested)
        
        ### BEGIN CONTEXT MENU
        # Add context menu to the servers list
        self.contextMenu = QtGui.QMenu(self.tr('Context menu'), self)
        openAction = self.contextMenu.addAction(self.tr('Open advanced monitoring'))
        sendCommandAction = self.contextMenu.addAction(self.tr('Send a command'))
        openInteractAction = self.contextMenu.addAction(self.tr('Open an interactive shell'))
        editAction = self.contextMenu.addAction(self.tr('Edit'))
        deleteAction = self.contextMenu.addAction(self.tr('Delete'))
        reconnectAction = self.contextMenu.addAction(self.tr('Reconnect'))
        
        # Add connectors
        self.connect(openAction, QtCore.SIGNAL('triggered()'),
                     self.on_contextmenu_openAction_clicked)
        
        # Add connectors
        self.connect(sendCommandAction, QtCore.SIGNAL('triggered()'),
                     self.on_contextmenu_sendCommandAction_clicked)
        
        # Add connectors
        self.connect(openInteractAction, QtCore.SIGNAL('triggered()'),
                     self.on_contextmenu_openInteractAction_clicked)
        
        # Add connectors
        self.connect(editAction, QtCore.SIGNAL('triggered()'),
                     self.on_contextmenu_editAction_clicked)
        
        # Add connectors
        self.connect(deleteAction, QtCore.SIGNAL('triggered()'),
                     self.on_contextmenu_deleteAction_clicked)
        
        # Add connectors
        self.connect(reconnectAction, QtCore.SIGNAL('triggered()'),
                     self.on_contextmenu_reconnectAction_clicked)
        ### END CONTEXT MENU
        
        # Close tab from advanced monitors
        self.connect(self.ui.twMonitor, QtCore.SIGNAL('tabCloseRequested(int)'),
                     self.removeTab)
        
        # "Reduce to tray" trigger
        self.connect(self.ui.actionReduce, QtCore.SIGNAL('triggered()'),
                     self.hide)
        
        # Setup icons
        self.online_icon = QtGui.QIcon()
        self.online_icon.addPixmap(QtGui.QPixmap(':/img/Tick-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        
        self.offline_icon = QtGui.QIcon()
        self.offline_icon.addPixmap(QtGui.QPixmap(':/img/Notconnected-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.offline_icon.addPixmap(QtGui.QPixmap(":/img/Notconnected-32.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
        
        self.waiting_icon = QtGui.QIcon()
        self.waiting_icon.addPixmap(QtGui.QPixmap(':/img/Clock-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.waiting_icon.addPixmap(QtGui.QPixmap(":/img/Clock-32.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
        
        self.warning_icon = QtGui.QIcon()
        self.warning_icon.addPixmap(QtGui.QPixmap(':/img/Warning-32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        
        self.tab_icon = QtGui.QIcon()
        self.tab_icon.addPixmap(QtGui.QPixmap(':/img/Statistics_32.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        
        # Setup the tray icon
        self.trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon(':/img/Activity-monitor-32.png'), self)
        menu = QtGui.QMenu(self)
        openAction = menu.addAction(self.tr('Open'))
        closeAction = menu.addAction(self.tr('Reduce to tray'))
        exitAction = menu.addAction(self.tr('Exit'))
        self.trayIcon.setContextMenu(menu)
        self.trayIcon.show()
        
        self.connect(openAction, QtCore.SIGNAL('triggered()'),
                     self.show)
        
        self.connect(closeAction, QtCore.SIGNAL('triggered()'),
                     self.hide)
        
        self.connect(exitAction, QtCore.SIGNAL('triggered()'),
                     self.close)
        
        self.connect(self.trayIcon, QtCore.SIGNAL('activated(QSystemTrayIcon::ActivationReason)'),
                     self.on_iconActivated)
        
        self.connect(self.trayIcon, QtCore.SIGNAL('messageClicked()'),
                     self.on_iconMessageClicked)
        
        # Fill the servers list
        self.fillServersList()
    
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, self.tr('Are you sure ?'), self.tr('Are you sure you really want to quit ?'),
                                   QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        
        if reply == QtGui.QMessageBox.Yes:
            self.hide()
            self.__del__()
            
            # Cleanly close each ssh connection
            try:
                del self.servers
            except:
                pass
            #for server in self.servers:
            #    server.close()
            
            event.accept()
        else:
            event.ignore()
    
    def __del__(self):
        self.trayIcon.hide()
        
    """
    Fills the servers list (GUI) from the Db
    """
    def fillServersList(self):
        dblink = Db()
        self.ui.lwServers.clear()
        servers = dblink.getServers()
        
        i = 0
        for ligne in servers:
            self.addServerToMonitor(ligne)
            i += 1
            
    def addServerToMonitor(self, server):
        if self.servers_items.has_key(server['id']):
            self.servers_items[server['id']].setIcon(self.waiting_icon)
            self.servers_items[server['id']].setToolTip(self.tr('Waiting for connection...'))
            self.servers_items[server['id']].setText(server['type'])
            
            self.servers_items[server['id']].setStatusTip(self.tr('Host') + ' : ' + server['host'] + ':' + str(server['port']) + '    ' + self.tr('Login') + ' : ' + server['login'])
            
            if server['login'] == '' and server['password'] == '':
                print 'rsa'
                self.servers.edit(server['id'], server['host'], server['port'], server['type'], 'rsa', 'rsa')
            else:
                self.servers.edit(server['id'], server['host'], server['port'], server['type'], server['login'], server['password'])
            
            # Connects
            self.connect(self.servers[server['id']], QtCore.SIGNAL('connected'),
                         self.on_server_connected)
            self.connect(self.servers[server['id']], QtCore.SIGNAL('notConnected'),
                         self.on_server_notConnected)
            
            self.servers_items[server['id']].setIcon(self.waiting_icon)
            
            # Reconnects to the server
            self.servers[server['id']].connect()
        else:
            item = QtGui.QListWidgetItem(self.ui.lwServers)
            item.setData(32, QtCore.QVariant(server['id']))
            item.setIcon(self.waiting_icon)
            item.setToolTip(self.tr('Waiting for connection...'))
            item.setText(server['type'])
            
            item.setStatusTip(self.tr('Host') + ' : ' + server['host'] + ':' + str(server['port']) + '    ' + self.tr('Login') + ' : ' + server['login'])
            
            self.servers.add(server['id'], server['host'], server['port'], server['type'], server['login'], server['password'])
            
            self.servers_items[server['id']] = item
            
            # Connects
            self.connect(self.servers[server['id']], QtCore.SIGNAL('connected'),
                         self.on_server_connected)
            self.connect(self.servers[server['id']], QtCore.SIGNAL('notConnected'),
                         self.on_server_notConnected)
            
            self.servers_items[server['id']].setIcon(self.waiting_icon)
            self.servers[server['id']].connect()
    
    def list_servers_get_selected_id(self):
        server_id, trash = self.ui.lwServers.currentItem().data(32).toInt()
        
        return server_id
        
    """
    SLOTS
    """
    # Opens the "Add Server" window
    def on_event_pbAddServer_clicked(self):
        addServerWindow = AddServerWindow(self.dblink, self)
        addServerWindow.show()
    
    # Opens the "Edit Server" window
    def on_event_pbEditServer_clicked(self):
        server_id = self.list_servers_get_selected_id()
        
        editServerWindow = EditServerWindow(self.dblink, self.servers[server_id], server_id, self)
        editServerWindow.show()
    
    # Delete a server from the db
    def on_event_pbDelServer_clicked(self):
        reply = QtGui.QMessageBox.question(self, self.tr('Are you sure ?'), self.tr('Are you sure you really want to delete this server ?'),
                                   QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        
        if reply == QtGui.QMessageBox.Yes:
            # Get the ID of the server (id is the same as the one in DB)
            server_id = self.list_servers_get_selected_id()
            self.ui.lwServers.takeItem(self.ui.lwServers.currentRow())
            
            if self.servers.has_key(server_id):
                del self.servers[server_id]
                
            if self.servers_items.has_key(server_id):
                del self.servers_items[server_id]
                
            if self.tabs.has_key(server_id):
                del self.tabs[server_id]
                
            self.dblink.removeServer(server_id)
        
    def on_event_pbRefreshServer_clicked(self):
        # Get the ID of the server (id is the same as the one in DB)
        server_id = self.list_servers_get_selected_id()
        
        self.servers[server_id].connect()
        
        self.servers_items[server_id].setIcon(self.waiting_icon)
    
    # Opens the "Edit Server" window
    def on_actionManage_logins_and_passwords_clicked(self):
        editLoginPassWindow = EditLoginPassWindow(self.dblink, self)
        editLoginPassWindow.show()
    
    # Opens the "Edit Server" window
    def on_actionSend_a_command_to_servers_clicked(self):
        sendCommandPool = SendCommandPool(self.dblink, self.servers, self)
        sendCommandPool.show()
       
    def on_actionManage_bookmarks_clicked(self):
        editBookmarksWindow = EditBookmarksWindow(self.dblink, self)
        editBookmarksWindow.show()
    
    def on_actionRead_Help_clicked(self):
        if platform.system() == 'Linux':
            subprocess.Popen('/usr/bin/xdg-open ../doc/userguide.pdf', shell=True)
        elif platform.system() == 'Darwin':
            subprocess.Popen('/usr/bin/open ../doc/userguide.pdf', shell=True)
        elif platform.system() == 'Windows':
            subprocess.Popen('start ..\doc\userguide.pdf', shell=True)
    
    def on_actionAbout_clicked(self):
        splash = QtGui.QSplashScreen(self, QtGui.QPixmap(':/img/splash.png'))
        splash.show()
        splash.showMessage('v 1.0', QtCore.Qt.AlignRight, QtCore.Qt.white)

    # Opens a new tab with advanced monitoring for the double-clicked server in the list
    def on_event_lwServers_itemDoubleClicked(self, item):
        # Get server id from defined data
        id = self.list_servers_get_selected_id()
        
        # Check if the ssh server is online
        if self.servers[id].isConnected:
            # Check if a tab doesn't already exist
            # If it exists, switch to the tab
            if self.tabs.has_key(id):
                self.ui.twMonitor.setCurrentWidget(self.tabs[id])
            # Doesn't exist, create a new tab
            else:
                # Close the welcome tab
                if self.welcome_tab:
                    self.ui.twMonitor.clear()
                    self.welcome_tab = False
                
                # Create a tab and store the object
                tab = MainWindowTab(self.dblink, self.servers[id])
                tab.setId(id)
                self.tabs[id] = tab
                self.ui.twMonitor.addTab(tab, self.tab_icon, item.text())
                
                # Switch to the current tab
                self.ui.twMonitor.setCurrentWidget(tab)
        else:
            self.on_event_pbRefreshServer_clicked()
            
    def removeTab(self, tab_id):
        if not self.welcome_tab or tab_id != 0:
            id = self.ui.twMonitor.widget(tab_id).getId()
        
            # Delete the tab from the GUI
            self.ui.twMonitor.removeTab(tab_id)
            
            # Delete the tab object
            self.tabs[id].stop()
            del self.tabs[id]
        else:
            self.welcome_tab = False
            
            # Delete the tab from the GUI
            self.ui.twMonitor.removeTab(tab_id)
        
        # Reopen the welcome tab if no tab remain
        if not self.welcome_tab and self.ui.twMonitor.count() == 0:
            self.ui.twMonitor.clear()
            self.welcome_tab = True
            self.ui.twMonitor.addTab(self.ui.welcome_tab, self.tab_icon, self.tr('Welcome'))
    
    # Monitoring events
    # CPU
    def on_cpuOk(self, server_id):
        # Sets online icon
        if not self.servers[server_id].monitoring.mem_alert:
            self.servers_items[server_id].setIcon(self.online_icon)
        
    def on_cpuWarning(self, server_id):
        self.trayIcon.showMessage(self.tr('Warning !'), self.tr('Server ') + self.servers[server_id].server.type + self.tr(' has more than 60% CPU load !'))
        # Sets warning icon
        self.servers_items[server_id].setIcon(self.warning_icon)
        
    def on_cpuAlert(self, server_id):
        self.trayIcon.showMessage(self.tr('Alert !'), self.tr('Server ') + self.servers[server_id].server.type + self.tr(' has more than 80% CPU load !'), QtGui.QSystemTrayIcon.Warning)
        # Sets warning icon
        self.servers_items[server_id].setIcon(self.warning_icon)
        
    def on_cpuCritical(self, server_id):
        self.trayIcon.showMessage(self.tr('Critical !'), self.tr('Server ') + self.servers[server_id].server.type + self.tr(' has more than 90% CPU load !'), QtGui.QSystemTrayIcon.Critical)
        # Sets warning icon
        self.servers_items[server_id].setIcon(self.warning_icon)
        
    # Memory
    def on_memOk(self, server_id):
        # Sets online icon
        if not self.servers[server_id].monitoring.cpu_alert:
            self.servers_items[server_id].setIcon(self.online_icon)
        
    def on_memWarning(self, server_id):
        self.trayIcon.showMessage(self.tr('Warning !'), self.tr('Server ') + self.servers[server_id].server.type + self.tr(' has more than 60% memory used !'))
        # Sets warning icon
        self.servers_items[server_id].setIcon(self.warning_icon)
        
    def on_memAlert(self, server_id):
        self.trayIcon.showMessage(self.tr('Alert !'), self.tr('Server ') + self.servers[server_id].server.type + self.tr(' has more than 80% memory used !'), QtGui.QSystemTrayIcon.Warning)
        # Sets warning icon
        self.servers_items[server_id].setIcon(self.warning_icon)
        
    def on_memCritical(self, server_id):
        self.trayIcon.showMessage(self.tr('Critical !'), self.tr('Server ') + self.servers[server_id].server.type + self.tr(' has more than 90% memory used !'), QtGui.QSystemTrayIcon.Critical)
        # Sets warning icon
        self.servers_items[server_id].setIcon(self.warning_icon)
        
    def on_iconActivated(self, reason):
        if reason == QtGui.QSystemTrayIcon.Trigger:
            self.raise_()
            if self.isVisible():
                self.hide()
            else:
                self.show()
        
    def on_iconMessageClicked(self):
        self.show()
    
    def on_server_connected(self, server):
        self.servers_items[server.server.id].setToolTip(self.tr('Online'))
        self.servers_items[server.server.id].setIcon(self.online_icon)
        self.servers[server.server.id].monitor()
        
        self.servers_items[server.server.id].setStatusTip(self.tr('Host') + ' : ' + str(server.server.hostname) + ' (' + server.server.host + ':' + str(server.server.port) + ')    ' + self.tr('Login') + ' : ' + server.auth.login)
        
        # Connect to the monitoring signals (warnings, alerts, criticals)
        # CPU
        self.connect(server.monitoring, QtCore.SIGNAL('cpuOk'),
                     self.on_cpuOk)
        #self.connect(server.monitoring, QtCore.SIGNAL('cpuWarning'),
        #             self.on_cpuWarning)
        self.connect(server.monitoring, QtCore.SIGNAL('cpuAlert'),
                     self.on_cpuAlert)
        self.connect(server.monitoring, QtCore.SIGNAL('cpuCritical'),
                     self.on_cpuCritical)
        # Memory
        self.connect(server.monitoring, QtCore.SIGNAL('memOk'),
                     self.on_memOk)
        #self.connect(server.monitoring, QtCore.SIGNAL('memWarning'),
        #             self.on_memWarning)
        self.connect(server.monitoring, QtCore.SIGNAL('memAlert'),
                     self.on_memAlert)
        self.connect(server.monitoring, QtCore.SIGNAL('memCritical'),
                     self.on_memCritical)
    
    def on_server_notConnected(self, server):
        self.servers_items[server.server.id].setToolTip(self.tr('Offline'))
        self.servers_items[server.server.id].setIcon(self.offline_icon)
    
    def on_lwservers_contextmenu_requested(self, pos):
        pos.setX(pos.x() + 10)
        pos.setY(pos.y() + 40)
        self.contextMenu.exec_(self.mapToGlobal(pos))
    
    def on_contextmenu_openAction_clicked(self):
        self.on_event_lwServers_itemDoubleClicked(self.ui.lwServers.currentItem())
    
    def on_contextmenu_sendCommandAction_clicked(self):
        server_id = self.list_servers_get_selected_id()
        
        self.sendCommand = SendCommand(self.dblink, self.servers[server_id], self)
        self.sendCommand.show()
    
    def on_contextmenu_openInteractAction_clicked(self):
        server_id = self.list_servers_get_selected_id()
        
        self.servers[server_id].open_interactive_shell()
    
    def on_contextmenu_editAction_clicked(self):
        self.on_event_pbEditServer_clicked()
    
    def on_contextmenu_deleteAction_clicked(self):
        self.on_event_pbDelServer_clicked()
    
    def on_contextmenu_reconnectAction_clicked(self):
        self.on_event_pbRefreshServer_clicked()
Ejemplo n.º 10
0
        self.graphicsView.scale(0.9,0.9)
        self.drawGrid()

        
    def drawGrid(self): 
        global boxes,cur_field,NUMBER_OF_CELLS


        box_width = self.graphicsScene.width()/NUMBER_OF_CELLS
        box_height = self.graphicsScene.height()/NUMBER_OF_CELLS

        #QBrushes for checked or unchecked cells
        checked = QtGui.QBrush(QtGui.QColor(0,0,0))
        unchecked = QtGui.QBrush(QtGui.QColor(0,0,255))

        for i in range(NUMBER_OF_CELLS):
            for j  in range(NUMBER_OF_CELLS):
                if cur_field[i][j] == 1:
                    boxes[i][j].setBrush(checked)
                else:
                    boxes[i][j].setBrush(unchecked)




if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ui = Ui_MainWindow()
    ui.show()

    app.exec_()