Esempio n. 1
0
class CurrencyConv(QtWidgets.QMainWindow):
    def __init__(self):
        super(CurrencyConv, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_UI()

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

        self.ui.input_currency.setPlaceholderText('From currency: ')
        self.ui.input_amount.setPlaceholderText('I got: ')
        self.ui.output_currency.setPlaceholderText('To currency: ')
        self.ui.output_amount.setPlaceholderText('I\'ll get: ')
        self.ui.pushButton.clicked.connect(self.converter)

    def converter(self):
        c = CurrencyConverter()
        input_currency = self.ui.input_currency.text()
        output_currency = self.ui.output_currency.text()
        input_amount = int(self.ui.input_amount.text())
        
        output_amount = round(c.convert(input_amount, '%s' % (input_currency), '%s' % (output_currency)), 2)

        self.ui.output_amount.setText(str(output_amount))
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.Q1 = Image_Processing()
        self.Q2 = Image_Smoothing()
        self.Q3 = Edge_Detection()

        self.ui.setupUi(self)
        self.show()
Esempio n. 3
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle('Code-to-Html')
        self.setWindowIcon(QIcon('pic/icon.png'))

        # StyleSheet
        self.setStyleSheet('''
        QMainWindow{background-color:
        qlineargradient(spread:
        pad, x1:0, y1:0.5, x2:1, y2:0.5,
        stop:0 rgb(255, 255, 255),
        stop:1 rgb(150, 150, 150));}
        ''')

        # Highlight class
        self.highlight = Highlight()

        # ComboBox
        all_langs = self.highlight.return_all_languages()
        all_styles = self.highlight.return_all_styles()
        self.ui.comboBox.addItems(all_langs)
        self.ui.comboBox_2.addItems(all_styles)

        # Button
        self.ui.pushButton.clicked.connect(self.convertEvent)

    # Convert the input code to html text
    def convertEvent(self):
        code = self.ui.plainTextEdit.toPlainText()
        code = self.highlightEvent(code)
        self.ui.textBrowser.setHtml(
            re.findall("(.*)<textarea readonly id=", code, re.DOTALL)[0])
        self.ui.plainTextEdit_2.setPlainText(code)
        self.ui.plainTextEdit_2.selectAll()
        self.ui.plainTextEdit_2.copy()

        # Fresh
        self.ui.plainTextEdit_2.repaint()
        self.ui.textBrowser.repaint()

    # Using highlight class to highlight the code
    def highlightEvent(self, code):
        lexer = self.ui.comboBox.currentText()
        style = self.ui.comboBox_2.currentText()
        results = self.highlight.highlightEvent(code, style, lexer,
                                                self.ui.checkBox.isChecked())

        return results
Esempio n. 4
0
class MainWindowUI(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        global fs, data , gainArray
        self.flag = 2
        self.UI=Ui_MainWindow()
        self.UI.setupUi(self)
        self.UI.Popupwindow.triggered.connect(self.newwindowfunc)
        self.UI.Hanning.triggered.connect(self.Hanningfunc)
        self.UI.Rect.triggered.connect(self.Rectfunc)
        self.UI.Hamming.triggered.connect(self.Hammingfunc)
        self.UI.OpenAction.triggered.connect(self.OpenFile)
        self.UI.playAction.triggered.connect(self.Play)
        self.UI.stopAction.triggered.connect(self.stop)
        self.UI.save.triggered.connect(self.savefunc)
        self.loopslider()

    # *******************************************************functions of menuebar***************************
    def OpenFile(self):
        self.filepath = QtWidgets.QFileDialog.getOpenFileName()
        self.path = self.filepath[0]
    # =======================================================================================================
    def savefunc(self):
        array=self.changeslidervalue()
        audio = self.audioRun(self.flag,*array)
        m = np.max(np.abs(audio))
        sig = (audio / m).astype(np.float32)
        name="audiofile{}.wav"
        name=name.format(self.flag)
        save = wavfile.write(name, int(fs), sig)
        subplot(211)
        plot(audio)
        
    # =======================================================================================
    def newwindowfunc(self):
        array=self.changeslidervalue()
        self.SW = SecondWindow(data, fs,self.flag,*array)
        self.SW.show()
 
    # =============================================================
    def stop(self):
        sd.stop()
   
    #==============================================================
    def Play(self):
        global fs, data
        data, fs = librosa.load(self.path, sr=None, duration=20.0)
        print(data)
        print(fs)
        self.datafft = fft(data)
        self.fftabs = abs(self.datafft)
        self.freqs = fftfreq(len(self.fftabs), 1 / fs)
        self.N = len(self.fftabs)
        self.T = int(self.N / fs)
        print(self.T)
        self.t = 1 / fs * np.arange(self.N)
        self.UI.pcArray[1].plot(self.freqs[:int(self.freqs.size / 2)], self.fftabs[:int(self.freqs.size / 2)], pen='b')
        self.UI.pcArray[0].plot(data[:self.T * fs], pen='b')
        self.changeslidervalue()
     #================================================================
    def Hanningfunc(self):
        global i  
        i=0
        while i<4 :
            self.UI.pcArray[i].clear()
            i+=1
        self.flag = 2
        self.Play()
    
    #===================================================================================
    def Hammingfunc(self):
        global i
        i=0
        while i<4 :
            self.UI.pcArray[i].clear()
            i+=1
        self.flag = 0
        self.Play()
     
    # ==============================================================
    def Rectfunc(self):
        global i
        i=0
        while i<4 :
            self.UI.pcArray[i].clear()
            i+=1
        self.flag = 1
        self.Play()
    

    # ===========================================================================
    def loopslider(self):
        global i
        i = 0
        while i < 10:
            self.UI.sliderArray[i].valueChanged.connect(self.changeslidervalue)
            i += 1

    # ============================================================================
    def bandpass_filter(self, datanyquistfreq, lowcut, highcut, fs, order=5):
        nyquistfreq = 0.5 * fs
        low = lowcut / nyquistfreq
        high = highcut / nyquistfreq
        b, a = butter(order, [low, high], btype='band', analog=False)
        filtered = lfilter(b, a, data)
        return filtered

    def hammingprocessing(self, data, begin, end,fs,order):
        band = self.bandpass_filter(data, begin, end, fs, order=order)
        bandsize = len(band)
        rand = data[:int(bandsize / 2)]
        window = signal.windows.hamming(int(2 * bandsize))
        banda = np.concatenate((rand, band, rand), axis=0) * window
        bandafterwindowing = banda[int(bandsize / 2):int(3 * bandsize/2 )]
        return bandafterwindowing

    def processHammingAudio(self, data, fs, gain1, gain2, gain3, gain4, gain5, gain6, gain7, gain8, gain9, gain10):
        freq = np.arange(fs * 0.5)
        size = len(freq) / 10
        band1 = self.hammingprocessing(data, freq[21], freq[int(size)], fs,4) * 10 ** (gain1 / 20)
        band2 = self.hammingprocessing(data, freq[int(size)], freq[2 * int(size)], fs,4) * 10 ** (gain2 / 20)
        band3 = self.hammingprocessing(data, freq[2 * int(size)], freq[3 * int(size)], fs, 4) * 10 ** (gain3 / 20)
        band4 = self.hammingprocessing(data, freq[3 * int(size)], freq[4 * int(size)], fs, 4) * 10 ** (gain4 / 20)
        band5 = self.hammingprocessing(data, freq[4 * int(size)], freq[5 * int(size)], fs,4) * 10 ** (gain5 / 20)
        band6 = self.hammingprocessing(data, freq[5 * int(size)], freq[6 * int(size)], fs, 4) * 10 ** (gain6 / 20)
        band7 = self.hammingprocessing(data, freq[6 * int(size)], freq[7 * int(size)], fs, 4) * 10 ** (gain7 / 20)
        band8 = self.hammingprocessing(data, freq[7 * int(size)], freq[8 * int(size)], fs, 4) * 10 ** (gain8 / 20)
        band9 = self.hammingprocessing(data, freq[8 * int(size)], freq[9 * int(size)], fs, 4) * 10 ** (gain9 / 20)
        band10 = self.hammingprocessing(data, freq[9 * int(size)], freq[-1], fs, order=3) * 10 ** (gain10 / 20)
        Hsignal = band1 + band2 + band3 + band4 + band5 + band6 + band7 + band8 + band9 + band10
        return Hsignal
    
    def hanningprocessing(self, data, begin, end,fs,order):
        band = self.bandpass_filter(data, begin, end, fs, order=order)
        bandsize = len(band)
        rand = data[:int(bandsize / 2)]
        window = signal.windows.hann(int(2 * bandsize))
        banda = np.concatenate((rand, band, rand), axis=0) * window
        bandafterwindowing = banda[int(bandsize / 2):int(3 * bandsize/2 )]
        return bandafterwindowing

    def processHanningAudio(self, data, fs, gain1, gain2, gain3, gain4, gain5, gain6, gain7, gain8, gain9, gain10):
        freq = np.arange(fs * 0.5)
        size = len(freq) / 10
        band1 = self.hanningprocessing(data, freq[21], freq[int(size)], fs,4) * 10 ** (gain1 / 20)
        band2 = self.hanningprocessing(data, freq[int(size)], freq[2 * int(size)], fs,4) * 10 ** (gain2 / 20)
        band3 = self.hanningprocessing(data, freq[2 * int(size)], freq[3 * int(size)], fs, 4) * 10 ** (gain3 / 20)
        band4 = self.hanningprocessing(data, freq[3 * int(size)], freq[4 * int(size)], fs, 4) * 10 ** (gain4 / 20)
        band5 = self.hanningprocessing(data, freq[4 * int(size)], freq[5 * int(size)], fs,4) * 10 ** (gain5 / 20)
        band6 = self.hanningprocessing(data, freq[5 * int(size)], freq[6 * int(size)], fs, 4) * 10 ** (gain6 / 20)
        band7 = self.hanningprocessing(data, freq[6 * int(size)], freq[7 * int(size)], fs, 4) * 10 ** (gain7 / 20)
        band8 = self.hanningprocessing(data, freq[7 * int(size)], freq[8 * int(size)], fs, 4) * 10 ** (gain8 / 20)
        band9 = self.hanningprocessing(data, freq[8 * int(size)], freq[9 * int(size)], fs, 4) * 10 ** (gain9 / 20)
        band10 = self.hanningprocessing(data, freq[9 * int(size)], freq[-1], fs, order=3) * 10 ** (gain10 / 20)
        Hsignal = band1 + band2 + band3 + band4 + band5 + band6 + band7 + band8 + band9 + band10
        return Hsignal




    def processAudio(self, data, fs, gain1, gain2, gain3, gain4, gain5, gain6, gain7, gain8, gain9, gain10):
        freq = np.arange(fs * 0.5)
        size = len(freq) / 10
        band1 = self.bandpass_filter(data, freq[21], freq[int(size)], fs, order=4) * 10 ** (gain1 / 20)
        band2 = self.bandpass_filter(data, freq[int(size)], freq[2 * int(size)], fs, order=4) * 10 ** (gain2 / 20)
        band3 = self.bandpass_filter(data, freq[2 * int(size)], freq[3 * int(size)], fs, order=4) * 10 ** (gain3 / 20)
        band4 = self.bandpass_filter(data, freq[3 * int(size)], freq[4 * int(size)], fs, order=4) * 10 ** (gain4 / 20)
        band5 = self.bandpass_filter(data, freq[4 * int(size)], freq[5 * int(size)], fs, order=4) * 10 ** (gain5 / 20)
        band6 = self.bandpass_filter(data, freq[5 * int(size)], freq[6 * int(size)], fs, order=4) * 10 ** (gain6 / 20)
        band7 = self.bandpass_filter(data, freq[6 * int(size)], freq[7 * int(size)], fs, order=4) * 10 ** (gain7 / 20)
        band8 = self.bandpass_filter(data, freq[7 * int(size)], freq[8 * int(size)], fs, order=4) * 10 ** (gain8 / 20)
        band9 = self.bandpass_filter(data, freq[8 * int(size)], freq[9 * int(size)], fs, order=4) * 10 ** (gain9 / 20)
        band10 = self.bandpass_filter(data, freq[9 * int(size)], freq[-1], fs, order=3) * 10 ** (gain10 / 20)
        osignal = band1 + band2 + band3 + band4 + band5 + band6 + band7 + band8 + band9 + band10
        return osignal
#====================================================================================================
    def audioRun(self, flag, *gainArray):
        if (flag==0):
            Hs = self.processHammingAudio(data, fs,*gainArray)
            self.plot(Hs, fs)
            return Hs 
        elif (flag == 1 ):
            Rs = self.processAudio(data, fs, *gainArray)
            self.plot(Rs,fs)
            return Rs
        else:
            hs=self.processHanningAudio(data, fs,*gainArray)
            self.plot(hs, fs)
            return hs 
#=====================================================================================
    def plot(self,signal, sample_rate):
        global i
        i=2
        while i<4 :
            self.UI.pcArray[i].clear()
            i+=1          
        datafftafter = fft(signal)
        fftabsafter = abs(datafftafter)
        freqsa = fftfreq(len(datafftafter), 1 / sample_rate)
        self.UI.pcArray[3].plot(freqsa[:int(freqsa.size / 2)], fftabsafter[:int(freqsa.size / 2)], pen='r')
        N1 = len(signal)
        T1 = int(N1 / sample_rate)
        self.UI.pcArray[2].plot(signal[:T1 * sample_rate], pen='r')
        sd.play(signal, sample_rate)
     
# ====================================================================================================
    def changeslidervalue(self):
        global i
        i = 0
        gainArray = []
        while i < 10:
            gainArray.append(self.UI.sliderArray[i].value())
            i += 1
        print(gainArray)
        self.audioRun(self.flag,*gainArray)
        return gainArray
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from UI import Ui_MainWindow

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(mainWindow)
    mainWindow.show()
    sys.exit(app.exec_())
Esempio n. 6
0
class MainWindow (QtGui.QMainWindow):

	def __init__ (self, rpc, rpcworker, params, parent = None):
		QtGui.QMainWindow.__init__ (self, parent)

		self.rpc = rpc
		self.rpcworker = rpcworker
		self.rpcworker.lostconnection.connect (self.lostconnection)
		self.params = params

		self.ui = Ui_MainWindow()
		self.ui.setupUi (self)
		self.setWindowFlags (QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowMinimizeButtonHint)

		self.setWindowTitle (self.tr ("Cartoon Encoding and Uploading Platform"))
		self.setWindowIcon (QtGui.QIcon (':/images/icon.png'))

		self.createActions()
		self.createplayer()
		self.createmerger()
		self.createUIdetails()
		self.creategobject()

		self.transcoding = list()
		self.translisting = TransTaskProcessing
		self.mergelist = list()
		self.checkers = list()
		self.splitchoose = SplitNotChosen
		self.playerfile = None

		self.leftclicked = False

	def createActions (self):
		self.restact = QtGui.QAction (self.tr ("&Restore"), self, triggered = self.showNormal)
		self.minact = QtGui.QAction (self.tr ("Mi&nimize"), self, triggered = self.showMinimized)
		self.maxact = QtGui.QAction (self.tr ("Ma&ximize"), self, triggered = self.showMaximized)
		self.quitact = QtGui.QAction (self.tr ("&Quit"), self, triggered = QtGui.qApp.quit)

		self.trayicon = QtGui.QSystemTrayIcon (QtGui.QIcon (':/images/icon.png'))

		self.trayiconmenu = QtGui.QMenu (self)
		self.trayiconmenu.addAction (self.minact)
		self.trayiconmenu.addAction (self.maxact)
		self.trayiconmenu.addAction (self.restact)
		self.trayiconmenu.addSeparator()
		self.trayiconmenu.addAction (self.quitact)

		self.trayiconmenu.setStyleSheet ("QMenu {background-color: rgba(255, 255, 255, 255); border: 1px solid black;} QMenu::item {background-color: transparent;} QMenu::item:selected {background-color: rgba(0, 100, 255, 128);}")

		self.trayicon.setToolTip (self.tr ("Minimize to system tray. Right click this icon and choose Quit to close."))
		self.trayicon.setContextMenu (self.trayiconmenu)

		self.trayicon.show()

		self.trayicon.activated.connect (self.trayiconactivated)

	def createUIdetails (self):

		self.ui.transview.setModel (self.transfermodel (self))
		self.ui.transview.setRootIsDecorated (False)
		self.ui.transview.setAlternatingRowColors (True)
		self.ui.transview.setItemDelegate (TransferDelegate (self))
		self.ui.transview.setContextMenuPolicy (QtCore.Qt.CustomContextMenu)

		self.ui.mergeview.setModel (self.mergemodel (self))
		self.ui.mergeview.setRootIsDecorated (False)
		self.ui.mergeview.setAlternatingRowColors (True)
		self.ui.mergeview.setItemDelegate (MergeDelegate (self))

		self.ui.stackedWidget.setCurrentIndex (0)

		self.ui.lineeditstarttime.installEventFilter (self)
		self.ui.lineeditendtime.installEventFilter (self)
		self.ui.lineeditleadertitle.installEventFilter (self)

		self.params.setdefault ('LastPlayerPath', '')
		self.params.setdefault ('LastSplitTime', '')
		self.params.setdefault ('LastSplitFile', '')
		self.params.setdefault ('LastSplitPath', '')
		self.params.setdefault ('LastMergePath', '')
		self.params.setdefault ('LastMergeSrcPath', '')
		self.params.setdefault ('LastTransferPath', '')
		self.params.setdefault ('LastTransferSrcPath', '')
		self.params.setdefault ('NumEdited', 0)
		self.params.setdefault ('NumTransferred', 0)

		self.ui.labelvideoedit.setText (self.tr ("Video Edit: %d") % (self.params['NumEdited']))
		self.ui.labelvideoconvert.setText (self.tr ("Video Transfer: %d") % (self.params['NumTransferred']))

		self.ui.labellastrecordtime.setText (self.params['LastSplitTime'])
		self.ui.labellastsavefile.setText (self.params['LastSplitFile'])
		self.ui.lineeditsaveblank.setText (self.params['LastMergePath'])

		self.ui.buttoncancelbrowse.hide()

		self.ui.labelfilmtitle.setAlignment (QtCore.Qt.AlignHCenter)

	def creategobject (self):
		gobject.threads_init()
		self.mainloop = gobject.MainLoop()
		self.context = self.mainloop.get_context()

		self.p = self.context.pending
		self.t = self.context.iteration
		self.e = QtGui.qApp.processEvents

		self.contexttimer = QtCore.QTimer (QtGui.QApplication.instance())
		self.contexttimer.timeout.connect (self.contexthandler)
		self.contexttimer.start (10)

	@QtCore.Slot()
	def contexthandler (self): # optimized or not?
		p = self.p
		t = self.t
		e = self.e
		for i in xrange (100):
			if p():
				t()
			else:
				break

		e()

	@QtCore.Slot()
	def lostconnection (self):
		msg = CommonError (self.tr ("Lost connection to server. Exiting..."))
		msg.exec_()
		QtGui.qApp.quit()

	@QtCore.Slot (QtCore.QPoint)
	def on_transview_customContextMenuRequested (self, point):
		row = self.ui.transview.currentIndex().row()
		if row >= len (self.transcoding) or row < 0:
			return

		menu = QtGui.QMenu (self)
		menu.addAction (QtGui.QAction (self.tr ("Start"), self, triggered = self.singletransbegin))
		menu.addAction (QtGui.QAction (self.tr ("Pause"), self, triggered = self.singletranspause))
		menu.addAction (QtGui.QAction (self.tr ("Delete"), self, triggered = self.on_buttontransdelete_clicked))
		menu.exec_ (QtGui.QCursor.pos())

	@QtCore.Slot (unicode)
	def newmerged (self, path):
		self.params['NumEdited'] += 1
		self.ui.labelvideoedit.setText (self.tr ("Video Edit: %d") % (self.params['NumEdited']))
		self.params['LastMergePath'] = path
		self.ui.lineeditsaveblank.setText (path)

		self.rpcworker.newmergedsignal.emit (self.params)

	@QtCore.Slot (unicode, unicode, unicode)
	def newsplitted (self, time, filename, path):
		self.params['NumEdited'] += 1
		self.ui.labelvideoedit.setText (self.tr ("Video Edit: %d") % (self.params['NumEdited']))
		self.params['LastSplitTime'] = time
		self.ui.labellastrecordtime.setText (time)
		self.params['LastSplitFile'] = filename
		self.ui.labellastsavefile.setText (filename)
		self.params['LastSplitPath'] = path

		self.rpcworker.newsplittedsignal.emit (self.params)

	@QtCore.Slot (unicode)
	def newtransferred (self, path, srcpath):
		self.params['NumTransferred'] += 1
		self.ui.labelvideoconvert.setText (self.tr ("Video Transfer: %d") % (self.params['NumTransferred']))
		self.params['LastTransferPath'] = path
		self.params['LastTransferSrcPath'] = srcpath

		self.rpcworker.newtransferredsignal.emit (self.params)

	@QtCore.Slot (int)
	def trayiconactivated (self, event):
		if event == QtGui.QSystemTrayIcon.Trigger:
			if self.isHidden():
				self.ui.buttonmaximize.setIcon (QtGui.QIcon (':/images/maximize.png'))
				self.showNormal()
			else:
				self.ui.buttonmaximize.setIcon (QtGui.QIcon (':/images/maximize.png'))
				self.hide()

	@QtCore.Slot()
	def on_buttonminimize_clicked (self):
		self.showMinimized()

	@QtCore.Slot()
	def on_buttonmaximize_clicked (self):
		if self.isMaximized():
			self.ui.buttonmaximize.setIcon (QtGui.QIcon (':/images/maximize.png'))
			self.showNormal()
		else:
			self.ui.buttonmaximize.setIcon (QtGui.QIcon (':/images/restore.png'))
			self.showMaximized()

	@QtCore.Slot()
	def on_buttonclose_clicked (self):
		self.ui.buttonmaximize.setIcon (QtGui.QIcon (':/images/maximize.png'))
		self.hide()
		self.trayicon.showMessage (self.tr ("Cartoon Encoding and Uploading Platform"),
				self.tr ("Minimize to system tray. Right click this icon and choose Quit to close."),
				QtGui.QSystemTrayIcon.Information, 10000)

	def transfermodel (self, parent):
		model = QtGui.QStandardItemModel (0, 4, parent)
		model.setHorizontalHeaderLabels ([self.tr ("Cartoon Name"), self.tr ("Transfer Progress"), self.tr ("Status"), self.tr ("Output Path")])
		return model

	def mergemodel (self, parent):
		model = QtGui.QStandardItemModel (0, 4, parent)
		model.setHorizontalHeaderLabels ([self.tr ("File Name"), self.tr ("Duration"), self.tr ("Resolution"), self.tr ("Status")])
		return model

	def createplayer (self):

		winid = self.ui.frame_2.winId()
		pythonapi.PyCObject_AsVoidPtr.restype = c_void_p
		pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object]
		self.windowId = pythonapi.PyCObject_AsVoidPtr (winid)

		self.ui.frame_2.mouseMoveEvent = self.mouseMoveEvent
		self.ui.frame_2.mousePressEvent = self.mousePressEvent
		self.ui.frame_2.mouseReleaseEvent = self.frameMouseRelease

		self.player = Player (self.windowId, self.ui.sliderseek.minimum(), self.ui.sliderseek.maximum(), self.ui.slidervolume.minimum(), self.ui.slidervolume.maximum())

		self.ui.buttonplayerplay.clicked.connect (self.player.playclickedsignal)
		self.ui.buttonplayerstop.clicked.connect (self.player.stopclickedsignal)
		self.ui.buttonplayerbackward.clicked.connect (self.player.backwardclickedsignal)
		self.ui.buttonplayerforward.clicked.connect (self.player.forwardclickedsignal)
		self.ui.buttonvolume.clicked.connect (self.player.muteornotsignal)
		self.ui.sliderseek.valueChanged.connect (self.player.sliderseekvaluesignal)
		self.ui.slidervolume.valueChanged.connect (self.player.slidervolumevaluesignal)

		self.player.updatelabelduration.connect (self.updatelabelduration)
		self.player.updatesliderseek.connect (self.updatesliderseek)
		self.player.updateslidervolume.connect (self.updateslidervolume)
		self.player.updatelineedit.connect (self.updatelineedit)
		self.player.setbuttonplay.connect (self.playersetbuttonplay)
		self.player.setbuttonpause.connect (self.playersetbuttonpause)

		self.player.startworker()

	@QtCore.Slot()
	def on_buttonloadfile_clicked (self):

		if os.path.isdir (self.params['LastPlayerPath']):
			lastpath = self.params['LastPlayerPath']
		else:
			lastpath = QtGui.QDesktopServices.storageLocation (QtGui.QDesktopServices.MoviesLocation)

		self.playerfile = QtGui.QFileDialog.getOpenFileName (self, self.tr ("Open"), lastpath)[0]
		if self.playerfile:
			checker = MediaFileChecker (self.playerfile, len (self.checkers))
			checker.discoveredsignal.connect (self.mediafilediscovered)
			checker.finished.connect (checker.deleteLater)
			self.checkers.append ({"worker": checker, "operation": "Player", "params": self.playerfile})
			checker.startworker()

			self.params['LastPlayerPath'] = QtCore.QDir.toNativeSeparators (QtCore.QFileInfo (self.playerfile).absolutePath())
			self.rpcworker.renewparamssignal.emit (self.params)

	@QtCore.Slot (unicode)
	def updatelabelduration (self, text):
		self.ui.labelduration.setText (text)

	@QtCore.Slot (int)
	def updatesliderseek (self, value):
		self.ui.sliderseek.blockSignals (True)
		self.ui.sliderseek.setValue (value)
		self.ui.sliderseek.blockSignals (False)

	@QtCore.Slot (unicode)
	def updatelineedit (self, text):
		if self.splitchoose == SplitNotChosen:
			return
		elif self.splitchoose == SplitAdjustStart:
			self.ui.lineeditstarttime.setText (text)
		elif self.splitchoose == SplitAdjustStop:
			self.ui.lineeditendtime.setText (text)

	@QtCore.Slot (int)
	def updateslidervolume (self, value):
		self.ui.slidervolume.blockSignals (True)
		self.ui.slidervolume.setValue (value)
		self.ui.slidervolume.blockSignals (False)

		self.on_slidervolume_valueChanged (value)

	@QtCore.Slot (int)
	def on_slidervolume_valueChanged (self, value):

		volmax = self.ui.slidervolume.maximum()
		volmin = self.ui.slidervolume.minimum()

		if value == 0:
			self.ui.buttonvolume.setIcon (QtGui.QIcon (':/images/mute.png'))
		elif value < (volmin + (volmax - volmin) / 3):
			self.ui.buttonvolume.setIcon (QtGui.QIcon (':/images/volume.png'))
		elif value < (volmin + (volmax - volmin) * 2 / 3):
			self.ui.buttonvolume.setIcon (QtGui.QIcon (':/images/weakvolume.png'))
		else:
			self.ui.buttonvolume.setIcon (QtGui.QIcon (':/images/strongvolume.png'))

	@QtCore.Slot()
	def playersetbuttonplay (self):
		self.ui.buttonplayerplay.setIcon (QtGui.QIcon (':/images/play.png'))

	@QtCore.Slot()
	def playersetbuttonpause (self):
		self.ui.buttonplayerplay.setIcon (QtGui.QIcon (':/images/pause2.png'))

	@QtCore.Slot()
	def on_buttoncancelbrowse_clicked (self):
		self.player.setloopsignal.emit (0, 0)

		self.ui.buttoncancelbrowse.hide()
		self.ui.buttonpreview.show()

		self.ui.lineeditstarttime.setEnabled (True)
		self.ui.lineeditendtime.setEnabled (True)
		
	@QtCore.Slot()
	def on_buttonpreview_clicked (self):

		self.splitchoose = SplitNotChosen
		self.ui.lineeditstarttime.setEnabled (False)
		self.ui.lineeditendtime.setEnabled (False)

		starttime = str2time (self.ui.lineeditstarttime.text())
		stoptime = str2time (self.ui.lineeditendtime.text())
		if starttime < 0 or stoptime <= starttime:
			msg = CommonError (self.tr ("Start time or stop time invalid."))
			msg.exec_()
			self.ui.buttoncancelbrowse.clicked.emit()
			return

		self.player.setloopsignal.emit (self.ui.lineeditstarttime.text(), self.ui.lineeditendtime.text())

		self.ui.buttonpreview.hide()
		self.ui.buttoncancelbrowse.show()

	def createmerger (self):

		self.merger = VideoMerger (self)

		self.merger.removerowsignal.connect (self.removemergerow)
		self.merger.updatemodel.connect (self.updatemergemodel)
		self.merger.finished.connect (self.unblockmergeelements)
		self.merger.finished.connect (self.flushmergelist)
		self.merger.filenamedecided.connect (self.updatefilename)

		self.merger.startnewmerge.connect (self.newmerged)

	@QtCore.Slot()
	def on_buttonplus_clicked (self):

		if os.path.isdir (self.params['LastMergeSrcPath']):
			lastpath = self.params['LastMergeSrcPath']
		else:
			lastpath = QtGui.QDesktopServices.storageLocation (QtGui.QDesktopServices.MoviesLocation)

		files = QtGui.QFileDialog.getOpenFileNames (self, self.tr ("Open"), lastpath)[0]
		if len (files) == 0:
			return

		self.params['LastMergeSrcPath'] = QtCore.QDir.toNativeSeparators (QtCore.QFileInfo (files[0]).absolutePath())
		self.rpcworker.renewparamssignal.emit (self.params)

		model = self.ui.mergeview.model()

		while len (files) > 0:
			newfile = QtCore.QFileInfo (files.pop (0))

			row = model.rowCount()
			model.insertRow (row)

			model.setData (model.index (row, 0), newfile.fileName())
			model.setData (model.index (row, 3), (0, self.tr ("Not Started")))

			rownum = 1
			for i in xrange (row):
				if self.mergelist[i] == MergeTaskReadyToProcess or self.mergelist[i] == MergeTaskVerifying:
					rownum += 1
			self.ui.labelmerge.setText (self.tr ("There are %d video clips to be merged.") % rownum)

			checker = MediaFileChecker (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()), len (self.checkers))
			checker.discoveredsignal.connect (self.mediafilediscovered)
			checker.finished.connect (checker.deleteLater)
			self.merger.appendtasksignal.emit (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()))
			self.checkers.append ({"worker": checker, "operation": "Merge", "params": row})
			self.mergelist.append (MergeTaskVerifying)
			checker.startworker()

	@QtCore.Slot()
	def on_buttonup_clicked (self):
		prevrow = row = self.ui.mergeview.currentIndex().row()
		model = self.ui.mergeview.model()

		if not self.mergelist[row] == MergeTaskReadyToProcess:
			return

		while prevrow > 0:
			prevrow -= 1
			if self.mergelist[prevrow] == MergeTaskReadyToProcess:
				break

		if prevrow < 0 or prevrow == row:
			return
		
		model.insertRow (prevrow, model.takeRow (row))
		self.mergelist[row], self.mergelist[prevrow] = self.mergelist[prevrow], self.mergelist[row]
		self.merger.switchrowsignal.emit (row, prevrow)
		self.ui.mergeview.setCurrentIndex (model.index (prevrow, 0))

	@QtCore.Slot()
	def on_buttondown_clicked (self):
		nextrow = row = self.ui.mergeview.currentIndex().row()
		model = self.ui.mergeview.model()

		if not self.mergelist[row] == MergeTaskReadyToProcess:
			return

		while nextrow < model.rowCount() - 1:
			nextrow += 1
			if self.mergelist[nextrow] == MergeTaskReadyToProcess:
				break

		if nextrow >= model.rowCount() or nextrow == row:
			return

		model.insertRow (nextrow, model.takeRow (row))
		self.mergelist[row], self.mergelist[nextrow] = self.mergelist[nextrow], self.mergelist[row]
		self.merger.switchrowsignal.emit (row, nextrow)
		self.ui.mergeview.setCurrentIndex (model.index (nextrow, 0))

	@QtCore.Slot()
	def on_buttondelete_clicked (self):
		row = self.ui.mergeview.currentIndex().row()
		self.merger.removerowsignal.emit (row)

	@QtCore.Slot()
	def on_buttonstart_clicked (self):
		filename = self.ui.lineeditfilenameblank.text()
		path = self.ui.lineeditsaveblank.text()

		if filename == "":
			msg = CommonError (self.tr ("Please input output filename"))
			msg.exec_()
			return
		elif len (filename) > 255:
			msg = CommonError (self.tr ("Filename too long."))
			msg.exec_()
			return
		
		if path == "":
			msg = CommonError (self.tr ("Please input output path"))
			msg.exec_()
			return

		self.merger.startsignal.emit (filename, path)
		self.blockmergeelements()

	@QtCore.Slot()
	def on_buttoncancel_clicked (self):
		self.merger.cancelsignal.emit()
		self.unblockmergeelements()

	@QtCore.Slot()
	def on_buttonexamine_clicked (self):
		exam = MergeExam (self.ui.lineeditfilenameblank.text(), self.ui.lineeditsaveblank.text())
		exam.move (self.pos() + self.rect().center() - exam.rect().center())
		exam.exec_()

	def blockmergeelements (self):
		self.ui.mergeview.setEnabled (False)
		self.ui.buttonstart.setEnabled (False)
		self.ui.buttonplus.setEnabled (False)
		self.ui.buttonup.setEnabled (False)
		self.ui.buttondown.setEnabled (False)
		self.ui.buttondelete.setEnabled (False)
		self.ui.lineeditfilenameblank.setEnabled (False)
		self.ui.lineeditsaveblank.setEnabled (False)
		self.ui.buttonbrowse.setEnabled (False)
		self.ui.buttonexamine.setEnabled (False)

	@QtCore.Slot()
	def unblockmergeelements (self):
		self.ui.mergeview.setEnabled (True)
		self.ui.buttonstart.setEnabled (True)
		self.ui.buttonplus.setEnabled (True)
		self.ui.buttonup.setEnabled (True)
		self.ui.buttondown.setEnabled (True)
		self.ui.buttondelete.setEnabled (True)
		self.ui.lineeditfilenameblank.setEnabled (True)
		self.ui.lineeditsaveblank.setEnabled (True)
		self.ui.buttonbrowse.setEnabled (True)
		self.ui.buttonexamine.setEnabled (True)

	@QtCore.Slot()
	def flushmergelist (self):
		for row in xrange (self.ui.mergeview.model().rowCount()):
			self.merger.removerowsignal.emit (row)

	@QtCore.Slot (unicode)
	def updatefilename (self, filename):
		self.ui.lineeditfilenameblank.setText (filename)

	@QtCore.Slot (int)
	def removemergerow (self, row):
		self.mergelist[row] = MergeTaskDeleted
		self.ui.mergeview.setRowHidden (row, QtCore.QModelIndex(), True)

		rownum = 0
		for i in xrange (self.ui.mergeview.model().rowCount()):
			if self.mergelist[i] == MergeTaskReadyToProcess or self.mergelist[i] == MergeTaskVerifying:
				rownum += 1
		self.ui.labelmerge.setText (self.tr ("There are %d video clips to be merged.") % rownum)

	@QtCore.Slot (int, int)
	def updatemergemodel (self, row, value):
		model = self.ui.mergeview.model()
		rownum = model.rowCount()

		if row >= rownum:
			for i in xrange (rownum):
				model.setData (model.index (i, 3), (100, self.tr ("Finished")))
			return

		if value is not None:
			if model.data (model.index (row, 3))[0] < value:
				if value < 100:
					model.setData (model.index (row, 3), (value, self.tr ("Processing...")))
				else:
					model.setData (model.index (row, 3), (100, self.tr ("Finished")))

			for i in xrange (row):
				model.setData (model.index (i, 3), (100, self.tr ("Finished")))

	@QtCore.Slot (unicode)
	def on_lineeditleadertitle_textChanged (self, text):
		self.ui.checkboxleadertitle.setChecked (True)

	@QtCore.Slot()
	def on_buttonsave_clicked (self):
		if not self.playerfile:
			return

		self.splitchoose = SplitNotChosen

		starttime = str2time (self.ui.lineeditstarttime.text())
		stoptime = str2time (self.ui.lineeditendtime.text())
		duration = stoptime - starttime
		if starttime < 0 or duration <= 0:
			msg = CommonError (self.tr ("Start time or stop time invalid."))
			msg.exec_()
			return

		if self.ui.checkboxleadertitle.isChecked():
			title = self.ui.lineeditleadertitle.text()
			if len (title) > 63:
				msg = CommonError (self.tr ("Movie title too long."))
				msg.exec_()
				return
		else:
			title = None

		timestring = "%s -- %s" % (time2str (starttime), time2str (stoptime))

		ss = SaveSplit (self.params['LastSplitPath'])
		ss.move (self.pos() + self.rect().center() - ss.rect().center())
		if not ss.exec_() == QtGui.QDialog.Accepted:
			return

		outputfile = os.path.join (ss.splitpath, ss.splitfile)

		self.splitter = VideoSplitter (self.playerfile, outputfile, starttime, duration, title, ss.totranscode, self.player.params, self)
		self.splitter.addtranscode.connect (self.addtranscode)
		self.splitter.startnewsplit.connect (self.newsplitted)
		self.splitter.startworker (timestring)

		self.splitprog = SplitProg()
		self.splitprog.move (self.pos() + self.rect().center() - self.splitprog.rect().center())
		self.splitter.updatemodel.connect (self.splitprog.setprogressbar)
		self.splitter.finished.connect (self.splitprog.accept)

		if not self.splitprog.exec_() == QtGui.QDialog.Accepted:
			self.splitter.finished.emit()

	@QtCore.Slot (int, tuple)
	def updatetransmodel (self, row, value):
		model = self.ui.transview.model()
		rownum = model.rowCount()

		if row >= rownum:
			return

		if value[0] is not None:
			if model.data (model.index (row, 1)) < value[0]:
				model.setData (model.index (row, 1), value[0])

			if value[0] >= 100:
				self.transcoding [row] ["status"] = TransTaskFinished
				model.setData (model.index (row, 2), self.tr ("Finished"))

				if self.translisting == TransTaskProcessing:
					self.ui.transview.setRowHidden (row, QtCore.QModelIndex(), True)
				else:
					self.ui.transview.setRowHidden (row, QtCore.QModelIndex(), False)

		if value[1] is not None:
			model.setData (model.index (row, 2), value[1])

	def closeEvent (self, event):
		if self.trayicon.isVisible():
			self.hide()
			event.ignore()

	@QtCore.Slot()
	def on_buttontransnew_clicked (self):

		model = self.ui.transview.model()

		nc = NewConvert (self.params['LastTransferPath'], self.params['LastTransferSrcPath'])
		if nc.exec_() == QtGui.QDialog.Accepted:

			files = nc.files
			newpath = nc.transferpath

			self.params['LastTransferPath'] = newpath
			self.rpcworker.renewparamssignal.emit (self.params)

			while len (files) > 0:
				newfile = QtCore.QFileInfo (files.pop (0))
				row = model.rowCount()
				model.insertRow (row)

				model.setData (model.index (row, 0), newfile.fileName())
				model.setData (model.index (row, 1), 0)
				model.setData (model.index (row, 2), self.tr ("Verifying File Parameters..."))
				model.setData (model.index (row, 3), newpath)

				checker = MediaFileChecker (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()), len (self.checkers))
				checker.discoveredsignal.connect (self.mediafilediscovered)
				checker.finished.connect (checker.deleteLater)
				self.checkers.append ({"worker": checker, "operation": "Transcode",
					"params": (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()), newpath, row, self)})
				self.transcoding.append ({"worker": None, "status": TransTaskVerifying})
				checker.startworker()

	@QtCore.Slot (unicode)
	def addtranscode (self, filename):
		model = self.ui.transview.model()
		newfile = QtCore.QFileInfo (filename)
		row = model.rowCount()
		model.insertRow (row)
		path = QtCore.QDir.toNativeSeparators (newfile.absolutePath())

		model.setData (model.index (row, 0), newfile.fileName())
		model.setData (model.index (row, 1), 0)
		model.setData (model.index (row, 2), self.tr ("Transcoding..."))
		model.setData (model.index (row, 3), path)

		transcode = Transcoder (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()), path, row, self)

		transcode.playsignal.connect (transcode.play)
		transcode.pausesignal.connect (transcode.pause)
		transcode.removesignal.connect (transcode.remove)
		transcode.updatemodel.connect (self.updatetransmodel)
		transcode.finished.connect (transcode.deleteLater)
		transcode.startnewtransfer.connect (self.newtransferred)

		transcode.startworker()
		self.transcoding.append ({"worker": transcode, "status": TransTaskProcessing})

	@QtCore.Slot()
	def on_buttontransbegin_clicked (self):
		for i in xrange (self.ui.transview.model().rowCount()):
			if self.transcoding [i] ["status"] == TransTaskProcessing:
				self.transcoding [i] ["worker"].playsignal.emit()

	@QtCore.Slot()
	def singletransbegin (self):
		row = self.ui.transview.currentIndex().row()
		if row >= len (self.transcoding):
			return
		if self.transcoding [row] ["status"] == TransTaskProcessing:
			self.transcoding [row] ["worker"].playsignal.emit()

	@QtCore.Slot()
	def on_buttontranspause_clicked (self):
		for i in xrange (self.ui.transview.model().rowCount()):
			if self.transcoding [i] ["status"] == TransTaskProcessing:
				self.transcoding [i] ["worker"].pausesignal.emit()

	@QtCore.Slot()
	def singletranspause (self):
		row = self.ui.transview.currentIndex().row()
		if row >= len (self.transcoding):
			return
		if self.transcoding [row] ["status"] == TransTaskProcessing:
			self.transcoding [row] ["worker"].pausesignal.emit()

	@QtCore.Slot()
	def on_buttontransdelete_clicked (self):
		row = self.ui.transview.currentIndex().row()
		if self.transcoding [row] ["status"] == TransTaskProcessing:
			self.transcoding [row] ["worker"].removesignal.emit()
		self.transcoding [row] ["status"] = TransTaskDeleted
		self.ui.transview.setRowHidden (row, QtCore.QModelIndex(), True)

	@QtCore.Slot()
	def on_listWidget_itemClicked (self):
		self.translisting = self.ui.listWidget.currentRow() == 0 and TransTaskProcessing or TransTaskFinished

		for row in xrange (self.ui.transview.model().rowCount()):
			if self.transcoding [row] ["status"] == self.translisting:
				self.ui.transview.setRowHidden (row, QtCore.QModelIndex(), False)
			else:
				self.ui.transview.setRowHidden (row, QtCore.QModelIndex(), True)

	@QtCore.Slot()
	def on_buttonbrowse_clicked (self):
		self.ui.lineeditsaveblank.setText (QtGui.QFileDialog.getExistingDirectory (self, self.tr ("Select output directory")))

	@QtCore.Slot()
	def on_MovieEdit_clicked (self):
		self.ui.stackedWidget.setCurrentIndex (0)

	@QtCore.Slot()
	def on_FormatConvert_clicked (self):
		self.ui.stackedWidget.setCurrentIndex (1)

	@QtCore.Slot()
	def on_buttonvideomerge_clicked (self):
		self.ui.stackedWidget_2.setCurrentIndex (1)

	@QtCore.Slot()
	def on_buttonvideointerceptpage_clicked (self):
		self.ui.stackedWidget_2.setCurrentIndex (0)

	@QtCore.Slot (int, bool, dict)
	def mediafilediscovered (self, row, verified, params):

		if row >= len (self.checkers):
			return

		checker = self.checkers[row]

		if not verified:
			le = LoadError()
			le.move (self.pos() + self.rect().center() - le.rect().center())
			le.exec_()
#			le.show()

		if checker["operation"] == "Merge":

			mergerow = checker["params"]
			model = self.ui.mergeview.model()

			if not verified:
				model.setData (model.index (mergerow, 1), "%s" % (self.tr ("Video Source Criteria Not Met")))
				model.setData (model.index (mergerow, 2), "")
				self.removemergerow (mergerow)

				rownum = 0
				for i in xrange (model.rowCount()):
					if self.mergelist[i] == MergeTaskReadyToProcess or self.mergelist[i] == MergeTaskVerifying:
						rownum += 1
				self.ui.labelmerge.setText (self.tr ("There are %d video clips to be merged.") % rownum)

			else:
				model.setData (model.index (mergerow, 1), "%s" % (time2str (params.get ("length"))))
				model.setData (model.index (mergerow, 2), "%d X %d" % (params.get ("videowidth"), params.get ("videoheight")))
				self.mergelist[mergerow] = MergeTaskReadyToProcess

			self.merger.verifiedtasksignal.emit (mergerow, params, verified)

		elif checker["operation"] == "Player":

			if verified:
				self.player.params = params
				self.player.playurisignal.emit (checker["params"])
				self.ui.labelfilmtitle.setText (QtCore.QFileInfo (checker["params"]).fileName())

		elif checker["operation"] == "Transcode":

			transrow = checker["params"][2]

			if not verified:
				self.transcoding [transrow]["status"] = TransTaskDeleted
				self.ui.transview.setRowHidden (transrow, QtCore.QModelIndex(), True)
				return

			transcode = Transcoder (*checker["params"])

			transcode.playsignal.connect (transcode.play)
			transcode.pausesignal.connect (transcode.pause)
			transcode.removesignal.connect (transcode.remove)
			transcode.updatemodel.connect (self.updatetransmodel)
			transcode.finished.connect (transcode.deleteLater)
			transcode.startnewtransfer.connect (self.newtransferred)

			transcode.startworker()
			self.transcoding [transrow]["worker"] = transcode
			self.transcoding [transrow]["status"] = TransTaskProcessing

		del checker

	def eventFilter (self, obj, event):
		if event.type() == QtCore.QEvent.FocusIn:
			if obj == self.ui.lineeditstarttime:
				self.splitchoose = SplitAdjustStart
			elif obj == self.ui.lineeditendtime:
				self.splitchoose = SplitAdjustStop
			elif obj == self.ui.lineeditleadertitle:
				self.splitchoose = SplitNotChosen

		elif event.type() == QtCore.QEvent.KeyPress:
			if event.key() == QtCore.Qt.Key_Enter or event.key() == QtCore.Qt.Key_Return:
				if obj == self.ui.lineeditstarttime:
					self.player.seekstarttimesignal.emit (self.ui.lineeditstarttime.text())
				elif obj == self.ui.lineeditleadertitle:
					self.ui.buttonsave.clicked.emit()

		return QtGui.QWidget.eventFilter (self, obj, event)

	def mouseMoveEvent (self, event):
		super (MainWindow, self).mouseMoveEvent (event)

		if self.leftclicked == True:

			if self.isMaximized():
				self.ui.buttonmaximize.setIcon (QtGui.QIcon (':/images/maximize.png'))

				origsize = self.rect().size()
				self.showNormal()
				newsize = self.rect().size()

				xfactor = float (newsize.width()) / origsize.width()
				yfactor = float (newsize.height()) / origsize.height()

				self.startdragging.setX (self.startdragging.x() * xfactor)
				self.startdragging.setY (self.startdragging.y() * yfactor)

			self.move (event.globalPos() - self.startdragging)

	def mousePressEvent (self, event):
		super (MainWindow, self).mousePressEvent (event)
		if event.button() == QtCore.Qt.LeftButton:
			self.leftclicked = True
			self.startdragging = event.globalPos() - self.pos()
			self.clickedpos = event.globalPos()

	def mouseReleaseEvent (self, event):
		super (MainWindow, self).mouseReleaseEvent (event)
		self.leftclicked = False

	def mouseDoubleClickEvent (self, event):
		super (MainWindow, self).mouseDoubleClickEvent (event)
		self.ui.buttonmaximize.clicked.emit()

	def frameMouseRelease (self, event):
		super (MainWindow, self).mouseReleaseEvent (event)
		if event.button() == QtCore.Qt.LeftButton and event.globalPos() == self.clickedpos:
			self.leftclicked = False
			self.ui.buttonplayerplay.clicked.emit()

	def resizeEvent (self, event):
		pixmap = QtGui.QPixmap (self.size())

		if not self.isMaximized():
			painter = QtGui.QPainter()
			painter.begin (pixmap)
			painter.fillRect (pixmap.rect(), QtCore.Qt.white)
			painter.setBrush (QtCore.Qt.black)
			painter.drawRoundRect (pixmap.rect(), 3, 3)
			painter.end()

		self.setMask (pixmap.createMaskFromColor (QtCore.Qt.white))
Esempio n. 7
0
class main(QtGui.QMainWindow):
     
     def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        
        self.connect(self.ui.pushButton1_0, SIGNAL("clicked()"),self.button_display_orginal_model)
        self.connect(self.ui.pushButton1_1, SIGNAL("clicked()"),self.button_edit_orginal_model)
        self.connect(self.ui.pushButton1_2, SIGNAL("clicked()"),self.button_view_orginal_model)
        self.connect(self.ui.pushButton2_0, SIGNAL("clicked()"),self.button_generate_species)
        self.connect(self.ui.pushButton2_1, SIGNAL("clicked()"),self.button_edit_species)
        self.connect(self.ui.pushButton2_2, SIGNAL("clicked()"),self.button_view_species)
        self.connect(self.ui.pushButton3_0, SIGNAL("clicked()"),self.button_generate_atomic_refinment)
        self.connect(self.ui.pushButton3_1, SIGNAL("clicked()"),self.button_edit_atomic_refinment)
        self.connect(self.ui.pushButton3_2, SIGNAL("clicked()"),self.button_view_atomic_refinment)
        self.connect(self.ui.pushButton4_0, SIGNAL("clicked()"),self.button_generate_complex_refinment)
        self.connect(self.ui.pushButton4_1, SIGNAL("clicked()"),self.button_edit_complex_refinment)
        self.connect(self.ui.pushButton4_2, SIGNAL("clicked()"),self.button_view_complex_refinment)
        self.connect(self.ui.pushButton5_0, SIGNAL("clicked()"),self.button_generate_refined_model)
        self.connect(self.ui.pushButton5_1, SIGNAL("clicked()"),self.button_display_refined_model)
        self.connect(self.ui.pushButton5_2, SIGNAL("clicked()"),self.button_view_refined_model)
        
     def button_display_orginal_model(self):
          
          orginal_filename = self.ui.lineEdit_1.text()
          
          try:
               f = open(orginal_filename, "r")
               
               self.ui.textEdit_original_model.clear()
               
               b = print_chemical_reaction(orginal_filename)
               for i in range (0,len(b)):
                    self.ui.textEdit_original_model.append(b[i])
               
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          
          
          
          
     def button_edit_orginal_model(self):
          orginal_filename = self.ui.lineEdit_1.text()
          try:
               f = open(orginal_filename, "r")
                     
               if os.name == "darwin":#Mac
                    sp.Popen(["open", orginal_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["gedit", orginal_filename])
               elif  os.name=="nt":     #win
                    sp.Popen( ["write", orginal_filename])
          
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
                        
                   
     def button_view_orginal_model(self):
          orginal_filename = self.ui.lineEdit_1.text()
          try:
               f = open(orginal_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", orginal_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["firefox", orginal_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["explorer", orginal_filename])
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
               
         
          
  #****************************************************************************************************             
                    
     def button_generate_species(self):
          orginal_filename = self.ui.lineEdit_1.text()
          try:
               f = open(orginal_filename, "r")
               dict_species=extract_species(orginal_filename)
               species_filename= self.ui.lineEdit_2.text()
               f = open(species_filename, "w")
               write_species(dict_species,species_filename)
               
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
         
          
     def button_edit_species(self):
          species_filename= self.ui.lineEdit_2.text()
          try:
               f = open(species_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", species_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["gedit", species_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["write", species_filename])
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          
     def button_view_species(self):
          species_filename= self.ui.lineEdit_2.text()
          
          try:
               f = open(species_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", species_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["firefox", species_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["explorer", species_filename])
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
               
          
               
 #************************************************************************************************         
               
     def button_generate_atomic_refinment(self):
          species_filename= self.ui.lineEdit_2.text()
          try:
               f = open(species_filename, "r")
               atomic_refinment_filename= self.ui.lineEdit_3.text()
               f = open(atomic_refinment_filename, "w")
               write_atomic_refinement(species_filename,atomic_refinment_filename)
               
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          

     def button_edit_atomic_refinment(self):
          atomic_refinment_filename= self.ui.lineEdit_3.text()
          try:
               f = open(atomic_refinment_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", atomic_refinment_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["gedit", atomic_refinment_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["write",  atomic_refinment_filename])
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          
               
          
         
          
     def button_view_atomic_refinment(self):
          atomic_refinment_filename= self.ui.lineEdit_3.text()
          try:
               f = open(atomic_refinment_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", atomic_refinment_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["firefox", atomic_refinment_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["explorer",  atomic_refinment_filename])
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          
          
 #**********************************************************************************************
               

     def button_generate_complex_refinment(self):
          species_filename= self.ui.lineEdit_2.text()
          try:
               atomic_refinment_filename= self.ui.lineEdit_3.text()
               dict_complex_refinement_generated = generate_complex_refinement(species_filename,atomic_refinment_filename)
               complex_refinment_filename= self.ui.lineEdit_4.text()
               write_complex_refinement(dict_complex_refinement_generated,complex_refinment_filename)
               
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          

     def button_edit_complex_refinment(self):
          complex_refinment_filename= self.ui.lineEdit_4.text()
          try:
               f = open(complex_refinment_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", complex_refinment_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["gedit", complex_refinment_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["write",  complex_refinment_filename])
                 
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          
          
          
     def button_view_complex_refinment(self):
          complex_refinment_filename= self.ui.lineEdit_4.text()
          try:
               f = open(complex_refinment_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open", complex_refinment_filename]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["firefox", complex_refinment_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["explorer",  complex_refinment_filename])
                
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
          
#*******************************************************************************************************************************         

     def button_generate_refined_model(self):
          try:
               orginal_model_filename = self.ui.lineEdit_1.text()
               species_filename= self.ui.lineEdit_2.text()
               dict_species_with_atomic=read_species(species_filename)
               atomic_refinment_filename= self.ui.lineEdit_3.text()
               dict_atomic_refinement = read_atomic_refinement(atomic_refinment_filename)
               complex_refinment_filename= self.ui.lineEdit_4.text()
               dict_complex_refinement_read = read_complex_refinement(complex_refinment_filename)
               reactions = read_reactions(orginal_model_filename)
               reaction_dic = generate_reactions(reactions, dict_complex_refinement_read)
               refined_model_filename = self.ui.lineEdit_5.text()
               write_reaction(dict_species_with_atomic,dict_atomic_refinement,dict_complex_refinement_read,reaction_dic,refined_model_filename)

          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
         
          
     def button_display_refined_model(self):
          refined_model_filename = self.ui.lineEdit_5.text()
          
          try:
               f = open(refined_model_filename, "r")
               self.ui.textEdit_refined_model.clear()
               b = print_chemical_reaction(refined_model_filename)
               for i in range (0,len(b)):
                    self.ui.textEdit_refined_model.append(b[i])
               
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
              
          
     def button_view_refined_model(self):
          refined_model_filename= self.ui.lineEdit_5.text()
          try:
               f = open(refined_model_filename, "r")
               if os.name == "darwin":#Mac
                    sp.Popen(["open",refined_model_filename ]) 
               elif  os.name=='posix': #linux
                    sp.Popen(["firefox", refined_model_filename])
               elif  os.name=="nt":     #win
                    sp.Popen(["explorer",  refined_model_filename])
                   
          except IOError as e:
               root = tk.Tk()
               root.withdraw()
               messagebox.showerror(title="Error",message=e.strerror + ": '" + e.filename + "'")
Esempio n. 8
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Esempio n. 9
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.Reg_Button.clicked.connect(self.registration)
        self.ui.Book_issuance_pushButton.clicked.connect(self.book_issuance)
        self.ui.Add_books_Button.clicked.connect(self.add_book)
        self.ui.Recovery_book_pushButton.clicked.connect(self.book_return)
        self.funcs = funcs.add()
        self.dialog = DIALOG(self.ui.UDC_label)
        self.ui.UDC_pushButton.clicked.connect(self.UDC_B)
        self.update_table()

    def UDC_B(self):
        self.dialog.show()

    def update_table(self):
        a = self.funcs.update_tadle()
        rows = len(a)
        self.ui.Info_tableWidget.setColumnCount(7)
        self.ui.Info_tableWidget.setRowCount(rows)
        self.ui.Info_tableWidget.setHorizontalHeaderLabels(
            ['articul', 'UDC', 'Name', 'Title', 'Date', 'Count', 'Count on hands'])
        header = self.ui.Info_tableWidget.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(6, QHeaderView.ResizeToContents)
        for i in range(len(a)):
            for j in range(len(a[i])):
                self.ui.Info_tableWidget.setItem(i, j, \
                QTableWidgetItem(str(a[i][j])))

        lst_count = self.funcs.getCount()
        counts = 0
        for elem in lst_count:
            counts += elem
        self.ui.all_books.setText(str(counts))

        lst_countHands = self.funcs.getCountHands()
        counts = 0
        for elem in lst_countHands:
            counts += elem
        self.ui.news_room.setText(str(counts))


    def registration(self):
        try:
            articul = int(self.ui.articul_lineEdit.text())
            UDC = self.ui.UDC_label.text()
            name = self.ui.Name_lineEdit.text()
            title = self.ui.Title_lineEdit.text()
            date = int(self.ui.Date_lineEdit.text())
            count = int(self.ui.Count_lineEdit.text())

            a = self.funcs.getAllBD()
            boolean = False
            for i in range(len(a)):
                if a[i][2] == title or a[i][0] == articul:
                    boolean = True
                    break
            if articul and UDC and name and title and date and count:
                if not boolean:
                    self.funcs.insert_new(articul, UDC, name, title, date, count, count)

                    self.ui.articul_lineEdit.clear()
                    self.ui.UDC_label.clear()
                    self.ui.Name_lineEdit.clear()
                    self.ui.Title_lineEdit.clear()
                    self.ui.Date_lineEdit.clear()
                    self.ui.Count_lineEdit.clear()
                else:
                    QMessageBox.about(
                        self, 'Ошибка', 'В базе данных была найдена книга с таким же названием или артикулем.')

            else:
                QMessageBox.about(
                    self, 'Ошибка', 'Не все данные были введены.')

            count_all = self.funcs.getCount()


            self.update_table()

        except Exception as e:
            QMessageBox.about(
                self, 'Ошибка', 'Введите верные значения!')



    def add_book(self):
        UDC, ok = QInputDialog.getText(self, 'Выбор Артикуля', 'Введите артикуль книги')
        if ok and UDC:
            count, ok = QInputDialog.getText(self, 'Кол-во книг', \
            'Введите кол-во книг для добавления книг в базу')
            if ok and count:
                try:
                    req = self.funcs.getCount_all_All(int(UDC))
                    count_db = int(req[0]) + int(count)
                    count_all_db = int(req[1]) + int(count)
                    self.funcs.UPDATE_counts(count_db, count_all_db, int(UDC))
                except IndexError:
                    QMessageBox.about(
                    self, 'Ошибка', 'Введите правильное значение артикуля!')
                except ValueError:
                    QMessageBox.about(
                    self, 'Ошибка', 'Введите целое значение кл-во книг для добавления!')
        self.update_table()


    def book_issuance(self):
        UDC, ok = QInputDialog.getText(self, 'Выбор Артикуль', 'Введите артикуль книги')
        if ok and UDC:
            try:
                req = self.funcs.book_issuance_SELECT(int(UDC))
                count = req[0]
                if count > 0:
                    count_on_hands = req[1] + 1
                    count -= 1
                    self.funcs.book_issuance_UPDATE(count, count_on_hands, int(UDC))

                    UDC = 'Книга "' + str(req[2]) + '" автора "' + str(req[3]) + \
                    '" успешно выдана читателю!' + '\n' + str(count) \
                    + ' книг осталось.\n' + str(count_on_hands) + \
                    ' книг(и) у читателя(ей) на руках.'

                    self.update_table()
                    QMessageBox.about(self, 'Артикуль', UDC)
                else:
                    QMessageBox.about(self, 'ERROR', "Нет книг для выдачи, \
                    ожидайте возврата книг другими читателями!")
            except IndexError:
                QMessageBox.about(
                    self, 'Ошибка', 'Введите правильное значение Артикуля.')



    def book_return(self):
        UDC, ok = QInputDialog.getText(self, 'Выбор Артикуль', 'Введите Артикуль книги')
        if ok and UDC:
            try:
                req = self.funcs.get_book_return(int(UDC))
                count_on_hands = req[0]
                if count_on_hands > 0:
                    count = req[1] + 1
                    count_on_hands -= 1
                    self.funcs.UPDATE_book_return(count, count_on_hands, int(UDC))
                    UDC = 'Книга "' + str(req[2]) + '" автора "' + str(req[3]) + \
                    '" успешно принята!' + '\n' + str(count) \
                    + ' книг осталось.\n' + str(count_on_hands) + \
                    ' книг(и) у читателя(ей) на руках.'
                    self.update_table()
                    QMessageBox.about(self, 'Артикуль', UDC)
                else:
                    QMessageBox.about(self, 'Артикуль',
                     "Никто из читателей не взял данную книгу!")
            except IndexError:
                QMessageBox.about(self, 'Ошибка',\
                 'Введите правильное значение Артикуль.')
Esempio n. 10
0
class first(QtGui.QMainWindow):

    #update map [database -> memory]
    def update_memory(self):
        self.CU.execute("select * from material")
        self.MATERIAL = self.CU.fetchall()
        self.MATERIAL_id_code = {}
        self.MATERIAL_code_id = {}
        self.PRODUCT = []
        for i in self.MATERIAL:
            self.MATERIAL_id_code[i[0]] = str(i[1])
            self.MATERIAL_code_id[str(i[1])] = i[0]
            if i[3]==True:
                self.PRODUCT.append(i[1])
        self.CU.execute("select * from relation")
        self.RELATION = self.CU.fetchall()

    #update treeWdigets
    def update_tree(self):
        self.ui.treeWidget.clear()
        self.ui.treeWidget_2.clear()
        self.tree1Item = []
        self.tree2Item = {}
        for i in self.MATERIAL:
            self.tree1Item.append(QTreeWidgetItem(self.tree1))
            self.tree1Item[-1].setText(0, str(i[1]))
            self.tree1Item[-1].setText(1, str(i[2]))
            if i[3]==1:
                self.tree1Item[-1].setText(2, 'True')
        for i in self.RELATION:
            fatherID = i[1]
            fatherCode = self.MATERIAL_id_code[fatherID]
            sonID = i[2]
            sonCode = self.MATERIAL_id_code[sonID]
            ratio = i[3]

            if fatherID not in self.tree2Item:
                self.tree2Item[fatherID] = QTreeWidgetItem(self.tree2)
                self.tree2Item[fatherID].setText(0, fatherCode)
                if some_functions.return_Table_Column_Value('material', 'id', str(some_functions.code_to_id(fatherCode)))[0][3]==True:
                    self.tree2Item[fatherID].setText(2, fatherCode)
            key = (fatherID, sonID)
            if key not in self.tree2Item:
                self.tree2Item[key] = QTreeWidgetItem(self.tree2Item[fatherID])
                self.tree2Item[key].setText(0, sonCode)
                self.tree2Item[key].setText(1, str(ratio))

    def MoveToScreenCenter(self):
        screen = QDesktopWidget().screenGeometry()
        mysize = self.geometry()
        hpos = ( screen.width() - mysize.width() ) / 2
        vpos = ( screen.height() - mysize.height() ) / 2
        self.move(hpos, vpos)

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.MoveToScreenCenter()

        #-stable---------------------------------------------------------------------------
        self.currentDIR = os.path.dirname(os.path.realpath(__file__))

        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName(os.path.join(self.currentDIR, "data.db"))
        if self.db.open():
            print "Open data.db successfully"
        else:
            print "Could not open data.db"
        self.CX = sqlite3.connect("data.db")
        self.CU = self.CX.cursor()

        self.tree1 = self.ui.treeWidget
        self.tree1.setColumnCount(3)
        self.tree1.setHeaderLabels(['Code','Name','IsProduct'])
        self.tree2 = self.ui.treeWidget_2
        self.tree2.setColumnCount(2)
        self.tree2.setHeaderLabels(['Code', 'Ratio', 'Product'])
        #----------------------------------------------------------------------------

        self.update_memory()
        self.update_tree()


        QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL("clicked()"), self.deleteMaterial)
        QtCore.QObject.connect(self.ui.pushButton_4, QtCore.SIGNAL("clicked()"), self.deleteRelation)
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.addMaterial)
        QtCore.QObject.connect(self.ui.pushButton_3, QtCore.SIGNAL("clicked()"), self.addRelation)

        QtCore.QObject.connect(self.ui.pushButton_5, QtCore.SIGNAL("clicked()"), self.singleQuery)
        QtCore.QObject.connect(self.ui.pushButton_6, QtCore.SIGNAL("clicked()"), self.multiQuery)
        QtCore.QObject.connect(self.ui.pushButton_7, QtCore.SIGNAL("clicked()"), self.singleReverseQuery)
        QtCore.QObject.connect(self.ui.pushButton_8, QtCore.SIGNAL("clicked()"), self.multiReverseQuery)
        QtCore.QObject.connect(self.ui.pushButton_9, QtCore.SIGNAL("clicked()"), self.endReverseQuery)


    def singleQuery(self):
        code = str(self.ui.lineEdit.text())
        self.CU.execute("select * from material where code = '"+code+"'")
        ans = self.CU.fetchmany(1)
        if len(ans) > 0:
            single_query.SingleQuery().go(code, self.MATERIAL, self.RELATION, self.PRODUCT, \
                                          self.MATERIAL_id_code, self.MATERIAL_code_id)
            QMessageBox.warning(self, "single query", 'EXCEL generated successfully')
        else:
            QMessageBox.warning(self, "single query", 'Please select an existed material code!')


    def multiQuery(self):
        code = str(self.ui.lineEdit.text())
        self.CU.execute("select * from material where code = '"+code+"'")
        ans = self.CU.fetchmany(1)
        if len(ans) > 0:
            multi_query.MultiQuery().go(code, self.MATERIAL, self.RELATION, self.PRODUCT, \
                                        self.MATERIAL_id_code, self.MATERIAL_code_id)
            QMessageBox.warning(self, "multi query", 'EXCEL generated successfully')
        else:
            QMessageBox.warning(self, "multi query", 'Please select an existed material code!')


    def singleReverseQuery(self):
        code = str(self.ui.lineEdit.text())
        self.CU.execute("select * from material where code = '"+code+"'")
        ans = self.CU.fetchmany(1)
        if len(ans) > 0:
            single_reverse_query.SingleReverseQuery().go(code, self.MATERIAL, self.RELATION, self.PRODUCT, \
                                                         self.MATERIAL_id_code, self.MATERIAL_code_id)
            QMessageBox.warning(self, "single reverse query", 'EXCEL generated successfully')
        else:
            QMessageBox.warning(self, "single reverse query", 'Please select an existed material code!')


    def multiReverseQuery(self):
        code = str(self.ui.lineEdit.text())
        self.CU.execute("select * from material where code = '"+code+"'")
        ans = self.CU.fetchmany(1)
        if len(ans) > 0:
            multi_reverse_query.MultiReverseQuery().go(code, self.MATERIAL, self.RELATION, self.PRODUCT, \
                                                       self.MATERIAL_id_code, self.MATERIAL_code_id)
            QMessageBox.warning(self, "multi reverse query", 'EXCEL generated successfully')
        else:
            QMessageBox.warning(self, "multi reverse query", 'Please select an existed material code!')


    def endReverseQuery(self):
        code = str(self.ui.lineEdit.text())
        self.CU.execute("select * from material where code = '"+code+"'")
        ans = self.CU.fetchmany(1)
        if len(ans) > 0:
            end_reverse_query.EndReverseQuery().go(code, self.MATERIAL, self.RELATION, self.PRODUCT, \
                                                   self.MATERIAL_id_code, self.MATERIAL_code_id)
            QMessageBox.warning(self, "end reverse query", 'EXCEL generated successfully')
        else:
            QMessageBox.warning(self, "end reverse query", 'Please select an existed material code!')


    def addMaterial(self):
        add1 = second()
        add1.exec_()

    def addRelation(self):
        add2 = third()
        add2.exec_()

    def deleteMaterial(self):
        selections = self.tree1.selectedItems()
        if len(selections) > 0:
            Code = str(selections[0].text(0))
            reply = QMessageBox.question(self, "TABLE material", "Are you sure to delete?", QMessageBox.Yes|QMessageBox.No)
            if reply==QMessageBox.Yes:
                self.CU.execute("select * from relation where father = "+str(self.MATERIAL_code_id[Code])+\
                                " or son = "+str(self.MATERIAL_code_id[Code]))
                ans = self.CU.fetchmany(1)
                if len(ans) > 0:
                    QMessageBox.warning(self, "ERROR", 'Please first clean TABLE relation!')
                else:
                    self.CU.execute("delete from material where code = '"+Code+"'")
                    self.CX.commit()
                    self.update_memory()
                    self.update_tree()


    def deleteRelation(self):
        selections = self.tree2.selectedItems()
        if len(selections) > 0:
            ratio = str(selections[0].text(1))
            if ratio != '':
                reply = QMessageBox.question(self, "TABLE relation", "Are you sure to delete?", QMessageBox.Yes|QMessageBox.No)
                if reply==QMessageBox.Yes:
                    parent = selections[0].parent()
                    fatherID = self.MATERIAL_code_id[str(parent.text(0))]
                    sonID = self.MATERIAL_code_id[str(selections[0].text(0))]
                    self.CU.execute("delete from relation where father = '"+str(fatherID)+"' and son = '"+str(sonID)+"'")
                    self.CX.commit()
                    self.update_memory()
                    self.update_tree()
            else:
                QMessageBox.warning(self, "ERROR", 'Please delete its children!')
Esempio n. 11
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Icon
        byte_data = b64decode(icon)
        image_data = BytesIO(byte_data)
        image = Image.open(image_data)
        image = image.convert('RGBA')
        qImage = ImageQt.ImageQt(image)
        image = QPixmap.fromImage(qImage)
        self.setWindowIcon(QIcon(image))

        # Hide Window Title
        self.setFixedSize(self.width(), self.height())
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setWindowOpacity(0.9)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setCursor(Qt.CrossCursor)
        self.screenWidth = QDesktopWidget().screenGeometry().width()
        self.screenHeight = QDesktopWidget().screenGeometry().height()

        # LCD
        self.ui.lcdNumber.setDigitCount(8)
        self.ui.lcdNumber.display('00:00:00')

        # Button
        self.start = True
        self.sec = 0
        self.timer = QTimer()
        self.timer.timeout.connect(self.LCDEvent)
        self.ui.pushButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.ui.pushButton.clicked.connect(self.timeGo)
        self.ui.pushButton_2.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.ui.pushButton_2.clicked.connect(self.initTime)
        self.ui.pushButton_3.setIcon(self.style().standardIcon(QStyle.SP_DialogCancelButton))
        self.ui.pushButton_3.clicked.connect(self.exitEvent)

        # Shortcut
        self.startShortcut = QShortcut(QKeySequence("Ctrl+s"), self)
        self.startShortcut.activated.connect(self.timeGo)

        self.leftMove = QShortcut(QKeySequence("Ctrl+left"), self)
        self.rightMove = QShortcut(QKeySequence("Ctrl+right"), self)
        self.upMove = QShortcut(QKeySequence("Ctrl+up"), self)
        self.downMove = QShortcut(QKeySequence("Ctrl+down"), self)

        self.leftMove.activated.connect(lambda: self.shortcutMoveEvent('left'))
        self.rightMove.activated.connect(lambda: self.shortcutMoveEvent('right'))
        self.upMove.activated.connect(lambda: self.shortcutMoveEvent('up'))
        self.downMove.activated.connect(lambda: self.shortcutMoveEvent('down'))

        self.exit = QShortcut(QKeySequence("Ctrl+D"), self)
        self.exit.activated.connect(self.exitEvent)

    def initTime(self):
        self.ui.lcdNumber.display('00:00:00')
        self.sec = 0
        self.start = True
        self.ui.pushButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.timer.stop()

    def timeGo(self):
        if self.start:
            self.ui.pushButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
            self.timer.start(1000)
            self.start = False
        else:
            self.ui.pushButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
            self.timer.stop()
            self.start = True

    def LCDEvent(self):
        self.sec += 1

        hour = self.sec//3600
        min = self.sec%3600//60
        sec = self.sec%60
        print(hour, min, sec)

        self.ui.lcdNumber.display('%02d:%02d:%02d' % (hour, min, sec))

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.moveFlag = True
            self.movePosition = event.globalPos() - self.pos()
            self.setCursor(QCursor(Qt.OpenHandCursor))
            event.accept()

    def mouseMoveEvent(self, event):
        if Qt.LeftButton and self.moveFlag:
            self.move(event.globalPos() - self.movePosition)
            event.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.moveFlag = False
        self.setCursor(Qt.CrossCursor)

    def shortcutMoveEvent(self, direction):
        if direction == 'left':
            self.move(QPoint(0, self.pos().y()))
        elif direction == 'right':
            self.move(QPoint(self.screenWidth-self.width(), self.pos().y()))
        elif direction == 'up':
            self.move(QPoint(self.pos().x(), 0))
        elif direction == 'down':
            self.move(QPoint(self.pos().x(), self.screenHeight-self.height()))

    def exitEvent(self):
        sys.exit()
Esempio n. 12
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.default_style_sheet = self.styleSheet()
        self.setWindowTitle("StockAle v.5.0.0")
        self.setWindowIcon(QtGui.QIcon('./pint_icon.png'))
        self.max_display = 90
        self.grain_list = []
        self.sel_grain = 0
        self.used_grain_list = []
        self.grainRecipe_list = []
        self.hop_list = []
        self.used_hop_list = []
        self.hopRecipe_list = []
        self.grain_select = 0
        self.hop_select = 0
        self.total_ebu = 0
        self.pkt_use = 0
        self.process_notes = ""
        self.brew_dirty = False
        self.stock_dirty = False
        self.recipe_filename = None
        self.path = ""
        self.dateList = []
        self.months = {
            'Jan': 1,
            'Feb': 2,
            'Mar': 3,
            'Apr': 4,
            'May': 5,
            'Jun': 6,
            'Jul': 7,
            'Aug': 8,
            'Sep': 9,
            'Oct': 10,
            'Nov': 11,
            'Dec': 12
        }
        self.palette = QtGui.QPalette()

        # Connect signals to slots
        self.ui.button_back.clicked.connect(self.year_back)
        self.ui.button_forward.clicked.connect(self.year_forward)
        self.ui.rcg.button_write_notes.clicked.connect(self.write_notes)
        self.ui.hcg.button_use_recipe.clicked.connect(self.use_recipe)
        self.ui.rcg.button_save_brew.clicked.connect(self.open_save_dlg)
        self.ui.rcg.button_commit.clicked.connect(self.commit)
        self.ui.button_clear.clicked.connect(self.clear_search)

        self.ui.rcg.grain_use.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.rcg.grain_use.setSelectionMode(
            QtWidgets.QAbstractItemView.NoSelection)
        self.ui.rcg.grain_use.customContextMenuRequested.connect\
            (self.grain_use_rclick)

        self.ui.grain_stock.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.grain_stock.customContextMenuRequested.connect\
            (self.grain_stock_rclick)

        self.ui.hop_stock.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.hop_stock.customContextMenuRequested.connect\
            (self.hop_stock_rclick)

        self.ui.rcg.hop_use.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.rcg.hop_use.customContextMenuRequested.connect\
            (self.hop_use_rclick)

        self.ui.button_search.clicked.connect(self.search)

        # Sub-classed qt widgets, etc
        self.textEdit = QtWidgets.QTextEdit()
        self.textEdit.setStyleSheet("""QTextEdit{Background-color:#1d1e1f;
         color: #eff0f1}""")
        self.saveDialogue = SaveDialogue(self)
        self.showMaximized()

        self.model_dict = {}
        self.year = 0
        self.dirty = False

    ########################################################################
    # Initialise some stuff
    def startup(self):
        self.ui.rcg.button_commit.setEnabled(False)
        self.read_prefs()
        self.ui.tasting_notes.installEventFilter(self)
        self.ui.process_notes.installEventFilter(self)
        self.ui.box_style.currentIndexChanged.connect(self.save_notes)
        self.ui.rating.valueChanged.connect(self.save_notes)
        today = datetime.date.today()
        self.year = today.year
        self.dirty = False
        self.setup_year()

    def setup_year(self):
        """Populates current year from brew files"""
        io = IO(self)
        io.open_brews()
        try:
            self.model = self.model_dict[self.year]
        except:
            self.model = Model(self)
            self.model.setup()
        self.model.set_year(self.year)
        self.ui.yearView.setModel(self.model)
        self.ui.yearView.set_selection_model(self.model)
        self.ui.label_year.setText(str(self.year))

    def year_back(self):
        """YearView back button"""
        self.year -= 1
        self.setup_year()

    def year_forward(self):
        """YearView forward button"""
        self.year += 1
        self.setup_year()

    def read_prefs(self):
        """Reads preferences saved in 'prefx.xml' file"""
        self.ui.colourSettings.defaults()
        style_list = []
        try:
            path = './prefs.xml'
            with open(path, "r") as fo:
                tree = ET.ElementTree(file=fo)
                root = tree.getroot()
                for elem in root.iter():
                    if elem.tag == 'Days':
                        max_display = (int(elem.text))
                    if elem.tag == 'Length':
                        length = (str(elem.text))
                    if elem.tag == 'Temp':
                        mash_temp = (str(elem.text))
                    if elem.tag == 'Eff':
                        mash_eff = (str(elem.text))
                    if elem.tag == 'Styles':
                        for style in elem:
                            style = style.tag.replace('_', ' ')
                            style_list.append(style)
                    if elem.tag == 'Theme':
                        if elem.text == 'dark':
                            dark_theme = True
                        else:
                            dark_theme = False
            self.set_prefs(max_display, length, mash_temp, mash_eff,
                           style_list, dark_theme)
        except:
            with open('prefs.xml', 'wb') as fo:
                root = ET.Element('Root')
                tree = ET.ElementTree(root)
                tree.write(fo)
                self.error_message("No Preferences Set")
                #self.prefs()

    def set_prefs(self, days, length, temp, eff, styles, dark_theme):
        """Applies preferences"""
        self.max_display = days
        self.ui.rcg.vol_disp.setText(length)
        self.ui.rcg.mash_temp_disp.setText(temp)
        self.ui.rcg.mash_eff_disp.setText(eff)
        self.ui.box_style.clear()
        styles.sort()
        for item in styles:
            self.ui.box_style.addItem(item)
        # Available QStyle keys: 'Breeze', 'Windows', 'Motif', 'CDE',
        # 'Plastique', 'GTK+', 'Cleanlooks'
        if dark_theme:
            self.setStyleSheet(DarkStyle.load_stylesheet())
            QtWidgets.QApplication.setStyle(Qt.QStyleFactory.create('Breeze'))
        else:
            self.setStyleSheet(self.default_style_sheet)
            QtWidgets.QApplication.setStyle(
                Qt.QStyleFactory.create('cleanlooks'))

    ###########################################################################
    # Event handlers

    def eventFilter(self, source, event):
        """Detect notes losing focus and save contents"""
        if (event.type() == QtCore.QEvent.FocusOut
                and source is self.ui.tasting_notes):
            self.save_notes()
        if (event.type() == QtCore.QEvent.FocusOut
                and source is self.ui.process_notes):
            self.save_notes()
        return super().eventFilter(source, event)

    def keyPressEvent(self, qKeyEvent):
        """
        Triggers calculation of stock and used items, and sorts tables to
        eliminate blank lines. Arithmetic operators in stock tables are
        calculated.
        """
        add = "+"
        sub = "-"
        mult = "*"
        div = "/"
        tables = [self.ui.grain_stock, self.ui.hop_stock]
        if qKeyEvent.key() == QtCore.Qt.Key_Return:
            for table in tables:
                for row in range(table.rowCount()):
                    if table.item(row, 0) is not None:
                        for col in range(table.columnCount()):
                            if table.item(row, col) is not None:
                                inpt = str(table.item(row, col).text())
                                total = inpt
                                if inpt.find(add) != -1:
                                    op = inpt.split(add)
                                    total = float(op[0]) + float(op[1])
                                if inpt.find(sub) != -1:
                                    op = inpt.split(sub)
                                    total = float(op[0]) - float(op[1])
                                if inpt.find(mult) != -1:
                                    op = inpt.split(mult)
                                    total = float(op[0]) * float(op[1])
                                if inpt.find(div) != -1:
                                    op = inpt.split(div)
                                    total = float(op[0]) / float(op[1])
                                total = str(total)
                                total = QtWidgets.QTableWidgetItem(total)
                                table.setItem(row, col, total)
            self.update_all()

    ###########################################################################
    # Grain
    def grain_grp_update(self):
        """ Add an instance of class Grain to grain_list list of
        instances, sorts the list by EBC value and calls grain_table_update.
        """
        self.grain_list = []
        for row in range(self.ui.grain_stock.rowCount()):
            if self.ui.grain_stock.item(row, 0) is not None:
                if self.ui.grain_stock.item(row, 0).text() != "":
                    name = self.ui.grain_stock.item(row, 0).text()
                    ebc = self.ui.grain_stock.item(row, 1).text()
                    extr = self.ui.grain_stock.item(row, 2).text()
                    wgt = self.ui.grain_stock.item(row, 3).text()
                    a_grain = Grain(name, ebc, extr, wgt)
                    if name != "":
                        self.grain_list.append(a_grain)
        num = -1 + len(self.grain_list)
        if len(self.grain_list) > 5:
            self.ui.grain_stock.setRowCount(num + 1)
        # sort using int or 3, 10, 1 sorts to 1, 10, 3
        self.grain_list.sort(key=lambda Grain: int(Grain.ebc))
        self.grain_table_update()

    def use_grain(self):
        """ Populate used_grain_list and calculate percentage use."""
        total = 0
        self.used_grain_list = []
        stock_list = []
        for row in range(self.ui.rcg.grain_use.rowCount()):
            if self.ui.rcg.grain_use.item(row, 0) is not None:
                if self.ui.rcg.grain_use.item(row, 1) is None:
                    wgt = QtWidgets.QTableWidgetItem()
                    self.ui.rcg.grain_use.setItem(row, 1, wgt)
                    wgt.setText(str(0))

                name = self.ui.rcg.grain_use.item(row, 0).text()
                wgt = float(self.ui.rcg.grain_use.item(row, 1).text())
                for item in self.grain_list:
                    if name == item.get_name():
                        stock_name = item.get_name()
                        stock_list.append(stock_name)
                        extr = item.get_extr()
                        ebc = item.get_ebc()
                if name not in stock_list:
                    self.error_message("Warning: " + name + " not in stock")
                    self.ui.rcg.grain_use.removeRow(row)
                else:
                    total += wgt
                    a_used_grain = Grain(name, ebc, extr, wgt)
                    self.used_grain_list.append(a_used_grain)
        if total > 0:  # Calculate percentages in table
            for item in self.used_grain_list:
                pos = self.used_grain_list.index(item)
                wgt = float(Grain.get_wgt(item))
                perCent = int((wgt / total) * 100)
                perCent = str(perCent)
                perCent = QtWidgets.QTableWidgetItem(perCent)
                self.ui.rcg.grain_use.setItem(pos, 2, perCent)
        row_count = len(self.used_grain_list)  # Ensure extra rows available
        if row_count > 5:
            self.ui.rcg.grain_use.setRowCount(row_count + 1)
        self.ui.rcg.grain_use.clearSelection()
        self.grain_info_calc()

    def grain_info_calc(self):
        """ Calculate wort OG and EBC."""
        if len(self.used_grain_list) > 0:
            mash_deg = 0
            total_col = 0
            mash_eff = int(self.ui.rcg.mash_eff_disp.text())
            vol = float(self.ui.rcg.vol_disp.text())
            for item in self.used_grain_list:
                wgt = float(Grain.get_wgt(item))
                extr = float(Grain.get_extr(item))
                col = int(Grain.get_ebc(item))
                deg = (extr * wgt * (float(mash_eff) / 100)) / vol
                mash_deg += deg
                col *= wgt
                total_col += col
            OG = int(mash_deg)
            OG = str(OG)
            total_col = int(total_col * 10 * (float(mash_eff) / 100)) / vol
            colour = int(total_col)
            self.ui.rcg.ebc_disp.setText(str(colour))
            self.ui.rcg.og_disp.setText(OG)

    def grain_table_update(self):
        """ Fill cells in the grain stock table with instances
        from grain_list. If grain not in stock the text is greyed.
        """
        self.ui.grain_stock.clearContents()
        row_count = len(self.grain_list)  # Ensure extra rows available
        if row_count > 6:
            self.ui.grain_stock.setRowCount(row_count + 1)
        for item in self.grain_list:
            pos = self.grain_list.index(item)
            name = Grain.get_name(item)
            ebc = Grain.get_ebc(item)
            extr = Grain.get_extr(item)
            wgt = Grain.get_wgt(item)
            name = QtWidgets.QTableWidgetItem(name)
            if float(wgt) <= 0:
                in_stock = False
            else:
                in_stock = True
            self.ui.grain_stock.setItem(pos, 0, name)
            col = QtWidgets.QTableWidgetItem(ebc)
            self.ui.grain_stock.setItem(pos, 1, col)
            extr = QtWidgets.QTableWidgetItem(extr)
            self.ui.grain_stock.setItem(pos, 2, extr)
            qty = QtWidgets.QTableWidgetItem(wgt)
            self.ui.grain_stock.setItem(pos, 3, qty)
            if not in_stock:
                for col in range(4):
                    self.ui.grain_stock.item(pos, col).setForeground\
                        (QtGui.QColor('#697076'))

    def grain_stock_rclick(self):
        """ select entry to delete from grain stock table."""
        menu = QtWidgets.QMenu(self)
        delete = QtWidgets.QAction('Delete', self)
        menu.addAction(delete)
        menu.popup(QtGui.QCursor.pos())
        delete.triggered.connect(self.delete_grain)

    def delete_grain(self):
        """ Delete stock grain."""
        # Get the value in the right-clicked cell
        row = self.ui.grain_stock.currentRow()
        row = int(row)
        try:
            self.grain_list.pop(row)
        except IndexError:
            pass
        self.grain_table_update()
        self.stock_dirty = True

    def grain_use_rclick(self):
        """ select entry to delete from used grain table."""
        menu = QtWidgets.QMenu(self)
        delete = QtWidgets.QAction('Delete', self)
        menu.addAction(delete)
        menu.popup(QtGui.QCursor.pos())
        delete.triggered.connect(self.delete_used_grain)

    def delete_used_grain(self):
        """ Delete used grain."""
        row = self.ui.rcg.grain_use.currentRow()
        row = int(row)
        try:
            self.used_grain_list.pop(row)
        except IndexError:
            pass
        self.used_grain_update()

    def used_grain_update(self):
        """ Re-populate used grain table."""
        self.ui.rcg.grain_use.clearContents()
        for item in self.used_grain_list:
            pos = self.used_grain_list.index(item)
            name = Grain.get_name(item)
            wgt = str(Grain.get_wgt(item))
            name = QtWidgets.QTableWidgetItem(name)
            #name.setFlags(name.flags() & ~QtCore.Qt.ItemIsEditable)
            #name.setFlags(name.flags() & ~QtCore.Qt.ItemIsDropEnabled)
            self.ui.rcg.grain_use.setItem(pos, 0, name)
            wgt = QtWidgets.QTableWidgetItem(wgt)
            self.ui.rcg.grain_use.setItem(pos, 1, wgt)
        self.use_grain()

    def grain_recipe_update(self):
        """ Re-populate used grain table and adjusts row count to allow
        new entries."""
        self.ui.hcg.grain_use.clearContents()
        total = 0
        for item in self.grainRecipe_list:
            pos = self.grainRecipe_list.index(item)
            name = Grain.get_name(item)
            wgt = str(Grain.get_wgt(item))
            calc_wgt = float(Grain.get_wgt(item))
            total += calc_wgt
            percent = int((calc_wgt / total) * 100)
            percent = str(percent)
            name = QtWidgets.QTableWidgetItem(name)
            self.ui.hcg.grain_use.setItem(pos, 0, name)
            wgt = QtWidgets.QTableWidgetItem(wgt)
            self.ui.hcg.grain_use.setItem(pos, 1, wgt)
            percent = QtWidgets.QTableWidgetItem(percent)
            self.ui.hcg.grain_use.setItem(pos, 2, percent)
        row_count = len(self.grainRecipe_list)  # Ensure extra rows available
        if len(self.grainRecipe_list) > 4:
            self.ui.hcg.grain_use.setRowCount(row_count + 1)

    ###########################################################################
    # Hops
    def hop_grp_update(self):
        """ Add an instance of class Hop to hop_list list of
        instances, sorts the list alphabetically and calls hop_table_update.
        """
        self.hop_list = []
        for row in range(self.ui.hop_stock.rowCount()):
            if self.ui.hop_stock.item(row, 0) is not None:
                if self.ui.hop_stock.item(row, 0).text() != "":
                    name = self.ui.hop_stock.item(row, 0).text()
                    alpha = self.ui.hop_stock.item(row, 1).text()
                    wgt = self.ui.hop_stock.item(row, 2).text()
                    a_hop = Hop(name, alpha, wgt, 0)
                    if name != "":
                        self.hop_list.append(a_hop)
        num = -1 + len(self.hop_list)
        if len(self.hop_list) > 5:
            self.ui.hop_stock.setRowCount(num + 1)
        self.hop_list.sort(key=lambda Hop: Hop.name)
        self.hop_table_update()

    def hop_table_update(self):
        """Re-populate hop_stock table after changes to self.hop_list"""
        self.ui.hop_stock.clearContents()
        row_count = len(self.hop_list)  # Ensure extra rows available
        if row_count > 6:
            self.ui.hop_stock.setRowCount(row_count + 1)
        for item in self.hop_list:
            pos = self.hop_list.index(item)
            name = Hop.get_name(item)
            alpha = Hop.get_alpha(item)
            wgt = Hop.get_wgt(item)
            name = QtWidgets.QTableWidgetItem(name)
            if float(wgt) <= 0:
                in_stock = False
            else:
                in_stock = True
            self.ui.hop_stock.setItem(pos, 0, name)
            alpha = QtWidgets.QTableWidgetItem(alpha)
            self.ui.hop_stock.setItem(pos, 1, alpha)
            wgt = QtWidgets.QTableWidgetItem(wgt)
            self.ui.hop_stock.setItem(pos, 2, wgt)
            if not in_stock:
                for col in range(3):
                    self.ui.hop_stock.item(pos, col).setForeground\
                        (QtGui.QColor('#697076'))

    def use_hop(self):
        """Reads entries in the hop_use table. If the weight or time
        columns are empty, it automatically enters default values: 0g
        and 0 minutes. If an adjustment has been made to the entry's
        alpha, this value is used for the calculation.
        """
        temp_used_hops = self.used_hop_list
        self.used_hop_list = []
        total = 0
        stock_list = []
        adj_alpha = None
        for row in range(self.ui.rcg.hop_use.rowCount()):
            if self.ui.rcg.hop_use.item(row, 0) is not None:
                if self.ui.rcg.hop_use.item(row, 1) is None:
                    wgt = QtWidgets.QTableWidgetItem()
                    self.ui.rcg.hop_use.setItem(row, 1, wgt)
                    wgt.setText(str(0))
                if self.ui.rcg.hop_use.item(row, 2) is None:
                    time = QtWidgets.QTableWidgetItem()
                    self.ui.rcg.hop_use.setItem(row, 2, time)
                    time.setText(str(0))
                name = self.ui.rcg.hop_use.item(row, 0).text()
                wgt = float(self.ui.rcg.hop_use.item(row, 1).text())
                time = float(self.ui.rcg.hop_use.item(row, 2).text())
                for hop in temp_used_hops:
                    if hop.get_name() == name:
                        adj_alpha = hop.get_alpha()
                for item in self.hop_list:
                    if name == item.get_name():
                        stock_name = item.get_name()
                        stock_list.append(stock_name)
                        alpha = item.get_alpha()
                if name not in stock_list:
                    self.error_message("Warning: " + name + " not in stock")
                    self.ui.rcg.hop_use.removeRow(row)
                else:
                    total += wgt
                    if adj_alpha:
                        alpha = adj_alpha
                    a_used_hop = Hop(name, alpha, wgt, time)
                    self.used_hop_list.append(a_used_hop)
                    adj_alpha = None
        row_count = len(self.used_hop_list)  # Ensure extra rows available
        if row_count > 5:
            self.ui.rcg.hop_use.setRowCount(row_count + 1)
        self.ui.rcg.hop_use.clearSelection()
        self.hop_info_calc()

    def hop_info_calc(self):
        """Calculates wort EBU"""
        if len(self.used_hop_list) > 0:
            base_utn = float(37)
            curve = float(15)
            curve *= -0.001
            total_ebu = 0
            vol = float(self.ui.rcg.vol_disp.text())
            for item in self.used_hop_list:
                wgt = float(Hop.get_wgt(item))
                alpha = float(Hop.get_alpha(item))
                time = float(Hop.get_time(item))
                # Negative time represents hop stand at 80 C
                if time < 0:
                    time = -time
                    time = time * 0.25
                boil_comp = 1 - math.e**(curve * time)
                ut = base_utn * boil_comp
                ebu = (wgt * alpha * ut) / (vol * 10)
                total_ebu += int(ebu)
            self.ui.rcg.ebu_disp.setText(str(total_ebu))

    def hop_stock_rclick(self):
        """ Select entry to delete from hop stock table."""
        menu = QtWidgets.QMenu(self)
        action = QtWidgets.QAction('Delete', self)
        menu.addAction(action)
        menu.popup(QtGui.QCursor.pos())
        action.triggered.connect(self.delete_hop)

    def delete_hop(self):
        """ Delete hop from stock table."""
        row = self.ui.hop_stock.currentRow()
        row = int(row)
        try:
            self.hop_list.pop(row)
        except IndexError:
            pass
        self.hop_table_update()
        self.stock_dirty = True

    def hop_use_rclick(self):
        """ Select entry to delete from hop use table or adjust alpha
        for selected hop instance.
        """
        menu = QtWidgets.QMenu(self)
        del_action = QtWidgets.QAction('Delete', self)
        alpha_action = QtWidgets.QAction('Adjust Alpha', self)
        menu.addAction(del_action)
        menu.addAction(alpha_action)
        menu.popup(QtGui.QCursor.pos())
        del_action.triggered.connect(self.delete_used_hop)
        alpha_action.triggered.connect(self.adj_used_hop)

    def adj_used_hop(self):
        """For making local adjustment to alpha value"""
        row = self.ui.rcg.hop_use.currentRow()
        row = int(row)
        for hop in self.used_hop_list:
            if hop.get_name() == self.ui.rcg.hop_use.item(row, 0).text():
                curr_alpha = hop.get_alpha()
                alpha, ok = QtWidgets.QInputDialog.getText(
                    self, "Adjust Alpha", "Enter Alpha",
                    QtWidgets.QLineEdit.Normal, curr_alpha)
                if ok:
                    hop.set_alpha(alpha)
        self.hop_info_calc()

    def delete_used_hop(self):
        """ Remove hop instance from used hop table."""
        row = self.ui.rcg.hop_use.currentRow()
        row = int(row)
        try:
            self.used_hop_list.pop(row)
        except IndexError:
            pass
        self.used_hop_update()

    def used_hop_update(self):
        """ Re-populate used hop table"""
        self.ui.rcg.hop_use.clearContents()
        for item in self.used_hop_list:
            pos = self.used_hop_list.index(item)
            name = Hop.get_name(item)
            wgt = str(Hop.get_wgt(item))
            time = str(Hop.get_time(item))
            name = QtWidgets.QTableWidgetItem(name)
            #name.setFlags(QtCore.Qt.ItemIsEditable)
            #name.setFlags(QtCore.Qt.ItemIsDropEnabled)
            self.ui.rcg.hop_use.setItem(pos, 0, name)
            wgt = QtWidgets.QTableWidgetItem(wgt)
            self.ui.rcg.hop_use.setItem(pos, 1, wgt)
            time = QtWidgets.QTableWidgetItem(time)
            self.ui.rcg.hop_use.setItem(pos, 2, time)
        self.use_hop()

    def hop_recipe_update(self):
        """ Re-populate used hop table and adjusts row count to allow
        new entries.
        """
        self.ui.hcg.hop_use.clearContents()
        for item in self.hopRecipe_list:
            pos = self.hopRecipe_list.index(item)
            name = Hop.get_name(item)
            wgt = str(Hop.get_wgt(item))
            time = str(Hop.get_time(item))
            name = QtWidgets.QTableWidgetItem(name)
            self.ui.hcg.hop_use.setItem(pos, 0, name)
            wgt = QtWidgets.QTableWidgetItem(wgt)
            self.ui.hcg.hop_use.setItem(pos, 1, wgt)
            time = QtWidgets.QTableWidgetItem(time)
            self.ui.hcg.hop_use.setItem(pos, 2, time)
        row_count = len(self.hopRecipe_list)  # Ensure extra rows available
        if len(self.hopRecipe_list) > 4:
            self.ui.hcg.hop_use.setRowCount(row_count + 1)

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

    def update_all(self):
        self.use_grain()
        self.used_grain_update()
        self.grain_grp_update()
        self.use_hop()
        self.used_hop_update()
        self.hop_grp_update()
        self.brew_dirty = True
        self.stock_dirty = True

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

    def commit_enable(self):
        self.ui.rcg.button_commit.setEnabled(True)

    def commit(self):
        """ Subtract used grain and hops from stock and command data
        save.
        """
        reply = QtWidgets.QMessageBox.question(
            self, "Commit Changes", "Commit changes to Database?",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
            | QtWidgets.QMessageBox.Cancel)
        if reply == QtWidgets.QMessageBox.Cancel:
            return False
        elif reply == QtWidgets.QMessageBox.No:
            return True
        elif reply == QtWidgets.QMessageBox.Yes:
            for used_grain in self.used_grain_list:
                used_name = Grain.get_name(used_grain)
                used_wgt = float(Grain.get_wgt(used_grain))
                for grain in self.grain_list:
                    grain_name = Grain.get_name(grain)
                    if grain_name == used_name:
                        grain.wgt = float(grain.wgt)
                        grain.wgt -= used_wgt
                        grain.wgt = Decimal(grain.wgt)
                        grain.wgt = round(grain.wgt, 2)
                        if grain.wgt < 0:
                            grain.wgt = 0
                        grain.wgt = str(grain.wgt)
                        self.grain_table_update()
            for used_hop in self.used_hop_list:
                used_name = Hop.get_name(used_hop)
                used_wgt = float(Hop.get_wgt(used_hop))
                for hop in self.hop_list:
                    hop_name = Hop.get_name(hop)
                    if hop_name == used_name:
                        hop.wgt = float(hop.wgt)
                        hop.wgt -= used_wgt
                        hop.wgt = Decimal(hop.wgt)
                        hop.wgt = round(hop.wgt, 1)
                        if hop.wgt < 0:
                            hop.wgt = 0
                            hop.wgt = str(hop.wgt)
                        self.hop_table_update()
            self.ui.rcg.button_commit.setEnabled(False)
            self.save_data()
            self.stock_dirty = False
            return True

    ###########################################################################
    # Save/Load stock data
    def save_data(self):
        io = IO(self)
        io.save_data()

    def load_data(self):
        io = IO(self)
        io.load_data()

    ###########################################################################
    # Save/Load brew
    def write_notes(self):
        """Opens process notes floating window"""
        posn = (QtGui.QCursor.pos())
        self.textEdit.setGeometry((posn.x()) - 460, posn.y(), 400, 200)
        self.textEdit.setWindowTitle("Process Notes")
        self.textEdit.show()
        self.brew_dirty = True

    def save_notes(self):
        io = IO(self)
        io.save_notes()

    def open_save_dlg(self):
        self.update_all()
        self.saveDialogue.setGeometry(780, 290, 300, 220)
        self.saveDialogue.exec_()

    def save_brew(self, fname, date):
        io = IO(self)
        io.save_brew(fname, date)
        self.setup_year()

    def load_brew(self, name):
        """Displays selected brew in history area"""
        self.ui.process_notes.clear()
        self.ui.tasting_notes.clear()
        io = IO(self)
        io.load_brew(name)

    def delete_brew(self):
        """Deletion using YearView RClick menu"""
        io = IO(self)
        io.delete_brew()

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

    def use_recipe(self):
        """ Load recipe from history panel into recipe panel."""
        if self.grain_list == []:
            msg = "Error: no stock data"
            self.errorMessage(msg)
        elif self.hop_list == []:
            msg = "Error: no stock data"
            self.errorMessage(msg)
        else:
            self.ui.rcg.grain_use.clearContents()
            self.ui.rcg.hop_use.clearContents()
            for item in self.grainRecipe_list:
                pos = self.grainRecipe_list.index(item)
                name = Grain.get_name(item)
                wgt = str(Grain.get_wgt(item))
                name = QtWidgets.QTableWidgetItem(name)
                self.ui.rcg.grain_use.setItem(pos, 0, name)
                wgt = QtWidgets.QTableWidgetItem(wgt)
                self.ui.rcg.grain_use.setItem(pos, 1, wgt)
            self.use_grain()
            for item in self.hopRecipe_list:
                pos = self.hopRecipe_list.index(item)
                name = Hop.get_name(item)
                wgt = str(Hop.get_wgt(item))
                time = str(Hop.get_time(item))
                name = QtWidgets.QTableWidgetItem(name)
                self.ui.rcg.hop_use.setItem(pos, 0, name)
                wgt = QtWidgets.QTableWidgetItem(wgt)
                self.ui.rcg.hop_use.setItem(pos, 1, wgt)
                time = QtWidgets.QTableWidgetItem(time)
                self.ui.rcg.hop_use.setItem(pos, 2, time)
            self.use_hop()
            temp = self.ui.hcg.mash_temp_disp.text()
            self.ui.rcg.mash_temp_disp.setText(temp)
            self.ui.recipe_box.setTitle("Unsaved Brew")
            self.ui.tabbed_area.setCurrentIndex(0)

    def time_ago(self):
        """ Calculate and display time since brewed."""
        date_string = self.recipe_filename
        day = int(date_string[0:2])
        month = str(date_string[2:5])
        year = int('20' + date_string[5:7])
        num_month = int(self.months[month])
        brew_date = QtCore.QDate(year, num_month, day)
        curr_date = QtCore.QDate.currentDate()
        days = brew_date.daysTo(curr_date)
        if days < int(self.max_display):
            if days < 0:
                days = 0
            weeks = int(days / 7)
            rem_days = days % 7
            self.ui.since_brew.setText('{0} Weeks {1} Days'.format(
                str(weeks), str(rem_days)))
        else:
            self.ui.since_brew.setText('Out of Range')

    def error_message(self, msg):
        """Show a message box"""
        mb = QtWidgets.QMessageBox()
        mb.setText(msg)
        mb.exec_()

    ###########################################################################
    # Search
    def get_brew_path(self):
        path = IO.get_path(self)
        if path:
            brew_path = path + '/Brews/'
            os.makedirs(brew_path, exist_ok=True)
            return brew_path

    def search(self):
        """ Search by keyword and/or rating in brew files, and display
        search results.
        """
        brew_path = self.get_brew_path()
        word_list = []
        search_word = str(self.ui.search_box.text())
        if not search_word:
            pass
        else:
            for item in search_word.split():
                word_list.append(item)
            result = []
            rating_list = []
            rating = int(self.ui.rating_input.value())
            rating_range = self.ui.rating_plus_minus.value()
            if rating != 0:
                for brew_file in os.listdir(brew_path):
                    if not brew_file.startswith(
                            '.'):  # filter unix hidden files
                        with open(brew_path + brew_file) as brew:
                            tree = ET.parse(brew)
                            root = tree.getroot()
                            for elem in root.iter():
                                if elem.tag == 'Rating':
                                    if elem.text is None:
                                        elem.text = 0
                                    brew_rating = int(elem.text)
                                    if rating - rating_range <= brew_rating \
                                            <= rating + rating_range:
                                        rating_list.append(brew_file)
                # now search only the files in rating_list
                for brew_file in rating_list:
                    with open(brew_path + brew_file) as brew:
                        for line in brew:
                            if search_word.lower() in line.lower():
                                if brew_file not in result:
                                    result.append(brew_file)
                                    # condition if rating not entered
            else:
                for brew_file in os.listdir(brew_path):
                    if not brew_file.startswith('.'):
                        with open(brew_path + brew_file) as brew:
                            for line in brew:
                                for item in word_list:
                                    if item.lower() in line.lower():
                                        if brew_file not in result:
                                            result.append(brew_file)
            if result != []:
                results_all = ''
                for item in result:
                    results_all = results_all + item + ', '
                # Remove last comma
                results_all = results_all[0:len(results_all) - 2]
                self.ui.results_box.setText(results_all)
                self.convert_search(result)
            else:
                self.error_message("No Result Found")

    def convert_search(self, result):
        """Converts brew file names to QDates and sends date to the
        appropriate model"""
        for date in result:
            day = int(date[0:2])
            month = date[2:5]
            month = self.months[month]  # Convert month name to number
            year = date[5:7]
            year = int(str(20) + year)
            date = QtCore.QDate(year, month, day)
            if year not in self.model_dict:
                model = Model(self)
                model.set_year(year)
                self.model_dict[self.year] = model
            model = self.model_dict[year]
            model.display_search(date)

    def clear_search(self):
        """Clears search from all models"""
        for key in self.model_dict:
            model = self.model_dict[key]
            model.clear_search()
            model.setup()
            model.set_year(key)
            self.ui.search_box.clear()
            self.ui.results_box.clear()
        self.setup_year()

    ###########################################################################
    # YearView
    #def cell_clicked(self, date):
    #    self.select_brew(date)

    def select_brew(self, date):
        if date:
            day = date.day()
            month = date.month()
            month = date.shortMonthName(month)
            year = date.year()
            year = str(year - 2000)
            month = str(month)
            if day < 10:
                day = "0" + str(day)
            day = str(day)
            brew = day + month + year
            self.load_brew(brew)

    ###########################################################################
    def closeEvent(self, event):
        """ On closing application window, save notes from open recipe, check
        if data save required."""
        if self.recipe_filename:
            self.save_notes()
        if self.used_grain_list != [] and self.brew_dirty:
            reply = QtWidgets.QMessageBox.question(
                self, "UnSaved Brew", "Save Brew?", QtWidgets.QMessageBox.Yes
                | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel)
            if reply == QtWidgets.QMessageBox.Cancel:
                event.ignore()
            elif reply == QtWidgets.QMessageBox.Yes:
                event.ignore()
                self.open_save_dlg()
            elif reply == QtWidgets.QMessageBox.No:
                self.save_data()
        if self.ui.rcg.button_commit.isEnabled():
            commit = self.commit()
            if commit is True:
                event.accept()
            elif commit is False:
                event.ignore()
                return
        if self.stock_dirty:
            self.save_data()
            event.accept()
        else:
            event.accept()
Esempio n. 13
0
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):

        # Controller Thread Variable (z.B. um den Thread zu beenden)
        self.con_Thread_var = True

        # Client
        self.client = None

        # Connected Thread Variable
        self.connected = False

        # initialise controller
        self.controller1 = Controller()

        # Data to be packed and processed
        self.direction = 0
        self.leghight = 0
        self.velocity = 0

        # Create window
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Connect button
        self.ui.connectButton.clicked.connect(self.connect)

        # Threads
        self.con_thread = Thread(target=self.conReact, args=())
        self.con_thread.start()
        self.data_thread = Thread(target=self.dataReact, args=())
        self.data_thread.start()
        self.send_thread = Thread(target=self.sendReact, args=())

    # Set direction to 0
    def setDirection0(self):
        self.direction = 0

    # Elevate hexapod
    def setAnheben(self):
        self.leghight = 1

    # Delevate hexapod
    def setAbsenken(self):
        self.leghight = 0

    # Set velocity
    def setSpeed(self):

        if (self.controller1.getVelocity() < 0.01):
            self.velocity = 0
        else:
            self.velocity = self.controller1.getVelocity() * 100

    # Connect to server
    def connect(self):
        # ip = textinput in QtDesigner implementieren
        #self.client = Com(ip="192.168.137.61", server=False)
        #self.send_thread.start()
        self.ui.connectionLabel.setText("<font color='green'>Connected</font>")

        self.client = Com(ip=self.ui.ipText.text(), server=False)
        self.send_thread.start()

    # Set direction
    def setDirection(self):
        self.direction = math.degrees(-self.controller1.getAngleDirection())

    # Controller Thread
    def conReact(self):

        while True:
            if (self.controller1.getVelocity() != 0 and self.con_Thread_var):
                self.setSpeed()
            if (self.controller1.getAngleDirection() != 0
                    and self.con_Thread_var):
                self.setDirection()
            if (self.controller1.getButtonLeghight() == 1
                    and self.con_Thread_var):
                self.setAnheben()
            if (self.controller1.getButtonLeghight() == 0
                    and self.con_Thread_var):
                self.setAbsenken()

    # Data Thread
    def dataReact(self):

        while True:
            # Pack data
            self.data = {
                'Winkelrichtung': self.direction,
                'Geschwindigkeit': self.velocity,
                'Angehoben': self.leghight
            }
            # print(self.data) //local testen

    # Send data Thread
    def sendReact(self):

        while True:
            self.client.send(self.data)
Esempio n. 14
0
class Window(QMainWindow):
    requestPage = pyqtSignal(str, str, str, str)

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

        self.threading()
        self.btn_functionality()
        self.nav_functionality()
        self.MainWindow.show()

    def update_textedit(self, html):
        self.ui.textEdit.textCursor().insertHtml(html)

    def update_progressbar(self, percentage):
        self.ui.progressBar.setValue(percentage * 100)

    def threading(self):
        self._thread = QThread()
        self._threaded = Threaded(self.update_textedit,
                                  self.update_progressbar,
                                  result=self.display_page)

        self.requestPage.connect(self._threaded.get_info)

        self._thread.started.connect(self._threaded.start)
        self._threaded.moveToThread(self._thread)
        qApp.aboutToQuit.connect(self._thread.quit)
        self._thread.start()

    def nav_functionality(self):
        # TODO - Where to save this file?
        self.ui.actionNew.triggered.connect(self.new_project)
        self.ui.actionOpen.triggered.connect(self.file_path)
        self.ui.actionSave.triggered.connect(self.file_save)
        self.ui.actionQuit.triggered.connect(lambda: QApplication.quit())

        self.ui.actionFAQ.triggered.connect(self.project_FAQ)
        self.ui.actionAbout.triggered.connect(self.project_about)

    def new_project(self):
        self.ui.textEdit.setText('')
        self.ui.progressBar.setValue(0)
        self.ui.label_excel_name.setText('Excel file')
        self.ui.label_tab_name.setText('Tab name')
        self.file_path()

    def project_FAQ(self):
        faq_file = open('txt_files/FAQ.txt', 'r')
        faq = faq_file.read()
        self.ui.textEdit.setText(faq)

    def project_about(self):
        about_file = open('txt_files/About.txt', 'r')
        about = about_file.read()
        self.ui.textEdit.setText(about)

    def btn_functionality(self):
        self.MainWindow = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

        self.ui.pushButton_Run.clicked.connect(self.get_comboBox_info)
        self.ui.pushButton_Clear.clicked.connect(self.clear_texteditbox)
        self.ui.pushButton_Save.clicked.connect(self.file_save)

    def file_path(self):
        path = QFileDialog.getOpenFileName(
            self, 'Open File', os.getenv('HOME'),
            'Excel(*.xlsx);;csv(*.csv);;All Files(*.*)')
        # TODO - need ability to return a CSV as well, need to accept it in the script as well!

        csv = False
        excel = False

        if path[0][-5:] == '.xlsx':
            excel = True
        elif path[0][-4:] == '.csv':
            csv = True

        if path[0] == "":  # Needs a space... -.-
            return "Missing"
        if csv:
            df_new = pd.read_csv(path[0])
            writer = pd.ExcelWriter('temp.xlsx')
            df_new.to_excel(writer, 'Sheet1', index=False)
            writer.save()
            self.ui.label_excel_name.setText(path[0])
            return 'temp.xlsx'
        elif excel:
            self.ui.label_excel_name.setText(path[0])
            return path[0]

    def file_save(self):
        name = QFileDialog.getSaveFileName(self, 'Save File',
                                           os.getenv('HOME'),
                                           'Text file(*.txt)')
        file = open(name[0], 'w')
        text = self.ui.textEdit.toPlainText()
        file.write(text)
        file.close()

    @pyqtSlot()
    def get_comboBox_info(self):
        if self.ui.label_excel_name.text() == "Excel file":
            file_path = self.file_path()
            if file_path == 'Missing':
                self.ui.textEdit.setText(
                    'WARNING: Must use a CSV or Excel file.')
                return
        else:
            # Makes sure to use the temp excel file if the user selected a CSV
            if self.ui.label_excel_name.text()[-4:] == '.csv':
                file_path = 'temp.xlsx'
            else:
                # Used if a file location has already been selected!
                file_path = self.ui.label_excel_name.text()

        # Get combobox values
        self.script_select = self.ui.comboBox_program.currentText()
        self.country_select = self.ui.comboBox_country.currentText()
        self.modheader_select = self.ui.comboBox_modheader.currentText()

        # Emit all values to slot
        self.requestPage.emit(file_path, self.script_select,
                              self.country_select, self.modheader_select)

        # Disable button functions
        self.ui.pushButton_Run.setEnabled(False)
        self.ui.pushButton_Clear.setEnabled(False)
        self.ui.pushButton_Save.setEnabled(False)

        # Disable nav bar during Run
        self.ui.actionAbout.setEnabled(False)
        self.ui.actionFAQ.setEnabled(False)
        self.ui.actionNew.setEnabled(False)
        self.ui.actionOpen.setEnabled(False)
        self.ui.actionQuit.setEnabled(False)
        self.ui.actionSave.setEnabled(False)

        self.ui.progressBar.setValue(0)

    @pyqtSlot(object)
    def display_page(self, df):
        global final_df
        self.ui.pushButton_Run.setEnabled(True)
        self.ui.pushButton_Clear.setEnabled(True)
        self.ui.pushButton_Save.setEnabled(True)

        self.ui.actionAbout.setEnabled(True)
        self.ui.actionFAQ.setEnabled(True)
        self.ui.actionNew.setEnabled(True)
        self.ui.actionOpen.setEnabled(True)
        self.ui.actionQuit.setEnabled(True)
        self.ui.actionSave.setEnabled(True)

        final_df = df

    def clear_texteditbox(self):
        self.ui.textEdit.setText('')
        self.ui.progressBar.setValue(0)
Esempio n. 15
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        # os.chdir(mainpath);
        super(MainWindow, self).__init__(parent)
        # self.status = self.statusBar()
        # self.status.showMessage("This is StatusBar",5000)
        # self.setWindowTitle("PyQt MianWindow")
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #print "self=",self
        #print "self.dir=",dir(self)
        #cls=getattr(WebConfig,"%s_Cfg"%product)

        #根据WebConfig模块里面的类名*_Cfg 更新下拉表单的数据
        pi = 0
        for item in dir(WebConfig):
            rm = re.search("_Cfg", item)
            if rm is not None and item != "WEB_Cfg":
                self.ui.dut_type.setItemText(
                    pi, _translate("MainWindow",
                                   item.split("_")[0], None))
                self.ui.cmp_type.setItemText(
                    pi, _translate("MainWindow",
                                   item.split("_")[0], None))
                pi = pi + 1

        #将sys.stdout的write函数重写为Redirect的write函数,Redirect重定向到testlog框
        #需重点理解

        self.stdout = Redirect(self.ui.testlog)
        sys.stdout = self.stdout

        #初始化树
        self.init_tree()

        #加载配置文件
        self.configfile = os.path.join(mainpath, "config.ini")
        self.selectfile = os.path.join(mainpath, "selected.ini")
        self.load_config()

        #设置UI界面连接
        self.ui.btn_save.clicked.connect(self.save_config)
        self.ui.btn_auto.clicked.connect(self.get_auto)
        self.ui.btn_tcl.clicked.connect(self.get_tcl)
        self.ui.btn_python.clicked.connect(self.get_python)
        self.ui.btn_run.clicked.connect(self.run_test)
        self.ui.btn_log.clicked.connect(self.set_log)
        self.ui.btn_stop.clicked.connect(self.run_stop)
        self.ui.rep_btn.clicked.connect(self.make_test_report)

        self.init_login()
        #print "product_cmp=%s"%self.product_cmp
        #print "login="******""

        #初始化交换机接口
        #print Port_Init(**port_init)

        #self.atten_init()
        #self.atten_opt("A,20")
        #串口操作
        # self.workthread=None
        # if run_flag==1 and workq.empty() and  self.make_report:
        #启动factory
        #self.factorydir=os.path.join(mainpath,"factory\\factory_2.py")
        #appname="python %s" % self.factorydir
        #self.factoryprocess=subprocess.Popen(appname,creationflags=subprocess.CREATE_NEW_CONSOLE)
        #self.connection=None
        #self.factoryprocess=factoryprocess
        #time.sleep(1)
        #self.Connect2Factory()
    def atten_init(self):
        self.atten_serialObj = serial.Serial(
            #port=unicode(self.ui.atten_COM.currentText()),              # number of device, numbering starts at
            port="COM8",
            # zero. if everything fails, the user
            # can specify a device string, note
            # that this isn't portable anymore
            # if no port is specified an unconfigured
            # an closed serial port object is created
            baudrate=9600,  # baud rate  
            bytesize=serial.EIGHTBITS,  # number of databits  
            parity=serial.PARITY_NONE,  # enable parity checking  
            stopbits=serial.STOPBITS_ONE,  # number of stopbits  
            timeout=None,  # set a timeout value, None for waiting forever  
            xonxoff=0,  # enable software flow control  
            rtscts=0,  # enable RTS/CTS flow control  
            interCharTimeout=None  # Inter-character timeout, None to disable 
        )

    def atten_opt(self, cmd):
        if cmd is not None and cmd != "":
            #self.atten_serialObj.open()
            self.atten_serialObj.write(cmd)
            print "write suc"
            i = 0
            while 1:
                print self.atten_serialObj.readline()
                time.sleep(0.1)
                i += 1
                if i >= 30:
                    break
            #
    def closeEvent(self, event):
        #关闭窗口时,停止服务
        # running_process=[runname for runname in self.lunchstate.keys() if self.lunchstate[runname]]
        # if running_process:
        # button=QtGui.QMessageBox.question(self,u"请回答",
        # u"还有测试没有停止,是否自动停止?",
        # QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel,
        # QtGui.QMessageBox.Ok)
        # if button==QtGui.QMessageBox.Ok:
        # for process in running_process:
        # self.connection.transport.getHandle().sendall("command lunch %s %s\r\n" % (process,'stop'))
        # self.lunchstate[process]=False
        # print u"服务:%s 停止" % process
        # time.sleep(0.5)
        if self.connection:
            self.connection.transport.getHandle().sendall("quit\r\n")
            time.sleep(0.1)
            # self.connection.transport.getHandle().sendall("")
            self.connection.disconnect()
        if self.factoryprocess:
            self.factoryprocess.terminate()
            self.factoryprocess = None
        event.accept()

    def Connect2Factory(self):
        if not check_net(('127.0.0.1', 10087)):
            QtGui.QMessageBox.critical(self, u"错误提示", u"factory服务器连接不上,请检查连接!")
            return
        if not self.connection:
            self.connection = reactor.connectTCP('127.0.0.1', 10087,
                                                 EchoClientFactory(self))

    def Connected(self):
        QtGui.QMessageBox.information(self, u"成功提示", u"连接成功")

    def make_test_report(self):
        os.chdir(mainpath)
        global reportpath, testscript, tcl_obj
        self.init_devargs()

        select_case_ids = {}
        cls = getattr(Report, "Rep_Action1")
        reportobj = cls()
        cls2 = getattr(Report, "Do_Excel_V2")
        reportExcel = cls2(reportpath=reportpath)
        # if reportpath=="":
        # reportpath=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
        # reportpath=os.path.join("tendareport",reportpath)
        # self.reportdirname=reportpath
        #print self.reportdirname
        if 1:
            #得到所有勾选的内容
            #print "self.root.childCount()=",self.root.childCount()
            for i in range(self.root.childCount()):
                item = self.root.child(i)
                #print "item.text=",item.text(0)
                if item.checkState(0) != Qt.Unchecked:
                    item_name = str(item.text(0))
                    select_case_ids[item_name] = []
                #print "item.childCount()=",item.childCount()
                for j in range(item.childCount()):
                    case_item = item.child(j)
                    if case_item.checkState(0) == Qt.Checked:
                        select_case_ids[item_name].append(case_item.id)
                    # print "case_checked=",case_item.id
            # if not select_case_ids:
            # QMessageBox.information(self,"Information",u"请选择用例")
            # return
            # print "select_case_ids[item_name]=",select_case_ids[item_name]
            for each_item, case_ids in select_case_ids.iteritems():
                #print "each_item=%s"%each_item
                tclfile = tcl_obj.eval("source cases/%s.tcl" % each_item)
                #print "tclfile=%s"%tclfile
                for case_id in case_ids:
                    #time.sleep(1)
                    #print "case_id=%s"%case_id
                    # print "~~"%eval(tcl_obj.eval("getargs %s" % case_id))
                    #print "caselmt=%s"%eval(tcl_obj.eval("getargs %s" % case_id))
                    (case_name,
                     repos) = eval(tcl_obj.eval("getpos %s" % case_id))
                    #print len(case_name)
                    rspath = os.path.join(self.product, case_name)
                    # if reportobj.make_report(casename=rspath,runscript=testscript,dstpath=reportpath,dstpos=repos,rssi_check=(1,-35,-25)):
                    # print "make report error!"
                    # else:
                    # print "%s report maked suc!!report:%s"%(rspath,reportpath)
                    # if cmp_flag==1:
                    # rspath=os.path.join(self.product_cmp,case_name)
                    # if reportobj.make_report(casename=rspath,runscript=testscript,dstpath=reportpath,dstpos=repos,make_cmp=cmp_flag,rssi_check=(1,-35,-25)):
                    # print "make report error!"
                    # else:
                    # print "%s report maked suc!!report:%s"%(rspath,reportpath)
                    #print reportobj.get_csv_throughput(casename=rspath,dstpos=repos)
                    #rspath=os.path.join(self.product_cmp,case_name)
                    #print reportobj.get_csv_throughput(casename=rspath,dstpos=repos)
                    if reportExcel.writeExcel(
                            dstpos=repos,
                            data=reportobj.get_csv_throughput(
                                casename=rspath, dstpos=repos)) is not True:
                        print "make report error!"
                    else:
                        print "%s report maked suc!!report:%s" % (rspath,
                                                                  reportpath)
                    if cmp_flag == 1:
                        rspath = os.path.join(self.product_cmp, case_name)
                        if reportExcel.writeExcel(
                                dstpos=repos,
                                data=reportobj.get_csv_throughput(
                                    casename=rspath, dstpos=repos),
                                make_cmp=cmp_flag) is not True:
                            print "make report error!"
                        else:
                            print "%s report maked suc!!report:%s" % (
                                rspath, reportpath)
        reportExcel.save_excel()

    def make_test_report_1(self):
        os.chdir(mainpath)
        global reportpath, testscript, tcl_obj
        self.init_devargs()

        select_case_ids = {}
        cls = getattr(Report, "Rep_Action1")
        reportobj = cls()
        # if reportpath=="":
        # reportpath=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
        # reportpath=os.path.join("tendareport",reportpath)
        # self.reportdirname=reportpath
        if 1:
            #得到所有勾选的内容
            for i in range(self.root.childCount()):
                item = self.root.child(i)
                if item.checkState(0) != Qt.Unchecked:
                    item_name = str(item.text(0))
                    select_case_ids[item_name] = []
                for j in range(item.childCount()):
                    case_item = item.child(j)
                    if case_item.checkState(0) == Qt.Checked:
                        select_case_ids[item_name].append(case_item.id)
            # if not select_case_ids:
            # QMessageBox.information(self,"Information",u"请选择用例")
            # return
            for each_item, case_ids in select_case_ids.iteritems():
                tclfile = tcl_obj.eval("source cases/%s.tcl" % each_item)
                for case_id in case_ids:
                    time.sleep(1)
                    (case_name,
                     repos) = eval(tcl_obj.eval("getpos %s" % case_id))
                    rspath = os.path.join(self.product, case_name)
                    if reportobj.make_report(casename=rspath,
                                             runscript=testscript,
                                             dstpath=reportpath,
                                             dstpos=repos,
                                             rssi_check=(1, -35, -25)):
                        print "make report error!"
                    else:
                        print "%s report maked suc!!report:%s" % (rspath,
                                                                  reportpath)
                    if cmp_flag == 1:
                        rspath = os.path.join(self.product_cmp, case_name)
                        if reportobj.make_report(casename=rspath,
                                                 runscript=testscript,
                                                 dstpath=reportpath,
                                                 dstpos=repos,
                                                 make_cmp=cmp_flag,
                                                 rssi_check=(1, -35, -25)):
                            print "make report error!"
                        else:
                            print "%s report maked suc!!report:%s" % (
                                rspath, reportpath)

    def run_stop(self):
        if not workq.empty():
            workq.queue.clear()
        if self.workthread:
            self.workthread.p.terminate()

    def init_tcl(self):
        # tcl_obj=Tkinter.Tcl()
        global tcl_obj
        tcl_obj.evalfile("main.tcl")

    def init_login(self):
        self.product = unicode(self.ui.dut_type.currentText())
        self.user = unicode(self.ui.dut_user.text())
        self.pwd = unicode(self.ui.dut_pwd.text())
        self.url = unicode(self.ui.dut_ip.text())

    def init_devargs(self):
        global cmp_flag
        self.make_cmp = 0
        cmp_flag = 0
        #self.product_cmp=""
        self.product = unicode(self.ui.dut_type.currentText())
        self.user = unicode(self.ui.dut_user.text())
        self.pwd = unicode(self.ui.dut_pwd.text())
        self.url = unicode(self.ui.dut_ip.text())
        if self.ui.make_cmp.isChecked():
            self.make_cmp = 1
            cmp_flag = 1
            self.product_cmp = unicode(self.ui.cmp_type.currentText())
            self.user_cmp = unicode(self.ui.cmp_user.text())
            self.pwd_cmp = unicode(self.ui.cmp_pwd.text())
            self.url_cmp = unicode(self.ui.cmp_ip.text())

    def ssh_link(self, ip, username, passwd):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(ip, 22, username, passwd, timeout=5)
            if ip == self.Serip:
                conn_ssh['serv'] = ssh
                print "conn_serv=", conn_ssh['serv']
            return True
        except paramiko.ssh_exception.NoValidConnectionsError:
            print u'网络连接不成功'
            return False
        except paramiko.ssh_exception.AuthenticationException:
            print u'用户名或密码不正确'
            return False

    def run_test(self):
        global run_flag, testscript, config_path, dir_auto
        #执行前首先清空队列
        if not workq.empty():
            workq.queue.clear()
        self.init_devargs()
        self.time_start = datetime.datetime.now()
        os.chdir(mainpath)
        select_case_ids = {}
        item_name = ""
        path = os.environ['Path']
        dir_auto = unicode(self.ui.path_auto.text())
        dir_tcl = os.path.dirname(unicode(self.ui.path_tcl.text())).replace(
            "/", "\\")
        bin_tcl = unicode(self.ui.path_tcl.text()).replace("/", "\\")
        dir_python = os.path.dirname(unicode(
            self.ui.path_python.text())).replace("/", "\\")
        config_path = os.path.join(dir_auto,
                                   "automation/conf/insert_config.tcl")
        tcl_exec_bin = os.path.join(dir_auto, "automation/bin/vw_auto.tcl")
        #dut_ssid=str(self.ui.ssid_name.text())
        parent_log_dir = unicode(self.ui.path_log.text()).replace("/", "\\")
        parent_log_dir_dut = os.path.join(parent_log_dir, self.product)
        if self.make_cmp:
            parent_log_dir_cmp = os.path.join(parent_log_dir, self.product_cmp)

        exec_str = "%s %s" % (bin_tcl, tcl_exec_bin)
        exec_args = ""
        bclean_log = self.ui.btnclean.isChecked()
        if bclean_log:
            if os.path.exists(parent_log_dir) and os.listdir(parent_log_dir):
                reply = QMessageBox.information(
                    self, u"请确认", u"是否删除当前目录下其他日志?",
                    QMessageBox.Yes | QMessageBox.No)
                if reply:
                    os.system('rd /s /q "%s"' % parent_log_dir.encode("gbk"))
                    os.makedirs(parent_log_dir.encode("gbk"))
                    os.makedirs(parent_log_dir_dut.encode("gbk"))
                    if self.make_cmp:
                        os.makedirs(parent_log_dir_cmp.encode("gbk"))
        # if not (path.find(dir_tcl)!=-1 or path.find(dir_tcl.replace("/","\\"))!=-1):
        # QMessageBox.information(self,"Information",u"添加TCL路径到环境变量")
        # return
        # if not (dir_python in path or dir_python.lower() in path):
        # QMessageBox.information(self,"Information",u"添加Python路径到环境变量")
        # return
        vw_auto_path = os.path.join(dir_auto, "automation/bin/vw_auto.tcl")
        if not os.path.exists(vw_auto_path):
            QMessageBox.information(self, "Information",
                                    u"自动化目录/automation/bin/vw_auto.tcl必须存在")
            return
        #得到所有勾选的内容
        #print "self.root.childCount()=",self.root.childCount()
        for i in range(self.root.childCount()):
            item = self.root.child(i)
            if item.checkState(0) != Qt.Unchecked:
                item_name = str(item.text(0))
                select_case_ids[item_name] = []
            for j in range(item.childCount()):
                case_item = item.child(j)
                if case_item.checkState(0) == Qt.Checked:
                    select_case_ids[item_name].append(case_item.id)
        if not select_case_ids:
            QMessageBox.information(self, "Information", u"请选择用例")
            return
        for each_item, case_ids in select_case_ids.iteritems():
            tclfile = tcl_obj.eval("source cases/%s.tcl" % each_item)
            for case_id in case_ids:
                exec_str = "%s %s" % (bin_tcl, tcl_exec_bin)
                #print "case_id=%s"%case_id
                (case_name, configweb,
                 steps) = eval(tcl_obj.eval("getargs %s" % case_id))
                #steps=steps.split(",")
                #steps=[step.strip() for step in steps if step.strip()]
                #steps.extend(['keylset global_config TestList {%s}' %testscript])
                #steps="\n".join(steps)

                steps = each_item

                full_log_path = os.path.join(
                    parent_log_dir_dut,
                    "%s\%s" % (each_item, case_name.decode("utf-8")))
                #tcl_obj.eval( "set VW_TEST_ROOT1 %s" % each_item )

                # if not os.path.exists(full_log_path):
                # os.makedirs(full_log_path)
                wmlpath = os.path.join(mainpath,
                                       "cases\%s\%s.tcl" % (steps, case_name))
                #print "wmlpath=",wmlpath
                #exec_args=' --var logdir "%s,%s" ' %(full_log_path.encode('utf-8'),wmlpath.encode('utf-8').replace("\\","/"))
                #exec_args=' --var logdir "%s" ' %full_log_path.encode('utf-8').replace("\\","/")

                case_log_dir = os.path.join(parent_log_dir_dut,
                                            "%s" % case_name.decode("utf-8"))
                exec_args = ' --var logdir "%s" ' % case_log_dir.encode(
                    'utf-8').replace("\\", "/")
                #exec_args+=' --var1 _casefile "%s" ' %full_log_path.encode('utf-8')
                exec_args += ' --var _casefile "%s" ' % wmlpath.encode('utf-8')
                #steps=full_log_path.encode('utf-8')
                # with open(config_path,"w+") as fd:
                # fd.write(steps)
                # fd.close()

                #NAT模块网关必须为DUT的管理IP(网关) 数据才可转发出去
                conf_gw = "puts 0"
                conf_ip = "puts 1"
                #print each_item
                if each_item == "(5)无线NAT转发率_24G2T2R":
                    conf_gw = "keylset Group_002 Gateway %s" % self.url
                    conf_ip = "keylset Group_002 BaseIp %s" % IP(
                        self.url
                    ).make_net(
                        '255.255.255.0'
                    )[111]  #IP(self.url).make_net('255.255.255.0')利用IP和子网掩码生成IP网段 返回值为IP网段列表
                ipinfo_str = ' --var _natipinfo "%s;%s;" ' % (conf_gw, conf_ip)

                exec_str_dut = exec_str + exec_args
                exec_str_dut += ipinfo_str
                #print exec_str,repr(exec_str)
                #print "exec_str_dut=%s"%exec_str_dut
                # libdir=os.path.join(os.path.dirname(dir_tcl),"lib/vcl")
                # os.chdir(libdir)

                #configweb="wifiSSID='aaaaa',wifiChannel=8"
                #将脚本名称和运行脚本的命令 传入 队列workq中
                workq.put((configweb, case_name, exec_str_dut.encode('gbk'),
                           steps, self.product))
                if self.make_cmp:
                    full_log_path_cmp = os.path.join(parent_log_dir_cmp,
                                                     case_name.decode("utf-8"))
                    full_script_path = os.path.join(
                        parent_log_dir_cmp,
                        "%s\%s" % (each_item, case_name.decode("utf-8")))
                    if not os.path.exists(full_log_path_cmp):
                        os.makedirs(full_log_path_cmp)
                    exec_args_cmp = ' --var logdir "%s" ' % full_log_path_cmp.encode(
                        'utf-8')
                    exec_args_cmp += ' --var _casefile "%s" ' % wmlpath.encode(
                        'utf-8')

                    #NAT模块 网关必须为DUT的管理IP 数据才可转发出去
                    #steps.extend(['keylset global_config TestList {%s}' %testscript])
                    #steps="\n".join(steps)
                    conf_gw = "puts 0"
                    conf_ip = "puts 1"
                    if each_item == "(5)无线NAT转发率_24G2T2R":
                        conf_gw = "keylset Group_002 Gateway %s" % self.url_cmp
                        conf_ip = "keylset Group_002 BaseIp %s" % IP(
                            self.url_cmp).make_net('255.255.255.0')[111]
                    ipinfo_str = ' --var _natipinfo "%s;%s;" ' % (conf_gw,
                                                                  conf_ip)

                    exec_str_cmp = exec_str + exec_args_cmp
                    exec_str_cmp += ipinfo_str
                    #print "cmp_exestr=%s"%exec_str_cmp
                    workq.put(
                        (configweb, case_name, exec_str_cmp.encode('gbk'),
                         steps, self.product_cmp))
        libdir = os.path.join(os.path.dirname(dir_tcl), "lib/vcl")
        os.chdir(libdir)
        #print "%s,%s,%s,%s"%(self.product,self.user,self.pwd,self.url)

        if self.make_cmp:
            #print "%s,%s,%s,%s"%(self.product_cmp,self.user_cmp,self.pwd_cmp,self.url_cmp)
            self.workthread = RunThread(self.product, self.user, self.pwd,
                                        self.url, self.product_cmp,
                                        self.user_cmp, self.pwd_cmp,
                                        self.url_cmp)
        else:
            self.workthread = RunThread(self.product, self.user, self.pwd,
                                        self.url)
        self.workthread.sinOut.connect(self.outText)
        self.workthread.start()

    def ticklock(self):
        #>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        #    '2016-07-08 16:19:44'
        #(beforetime-datetime.datetime.now()).total_seconds()
        pass

    def Debug_Log(self, data):
        global Debug_logfile
        self.time_end = datetime.datetime.now()
        datas = data
        data = "%s  %s" % (
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), data)
        #print u"aaa=%s"%reportpath
        fd = open(Debug_logfile, 'a')
        fd.write("%s\n" % data)
        if datas == u"运行结束":
            data_endstr1 = "test start:%s, test end:%s\n" % (self.time_start,
                                                             self.time_end)
            data_endstr2 = "total time(H):%s\n" % str(
                float('%0.3f' % (
                    (self.time_end - self.time_start).total_seconds() / 3600)))
            fd.write(data_endstr1)
            fd.write(data_endstr2)
        fd.close()

    def outText(self, text):
        self.ui.testlog.append(text)
        #print unicode(QString(text).toUtf8(), 'utf-8', 'ignore')
        #若运行结束根据GUI控件标识自动整理报告
        self.Debug_Log(unicode(QString(text).toUtf8(), 'utf-8', 'ignore'))
        self.make_report = self.ui.make_report.isChecked()
        # if  unicode(QString(text).toUtf8(), 'utf-8', 'ignore') == u"运行结束":
        #print "aaaaaaaaaa"
        # self.time_end=datetime.datetime.now()
        # print self.time_end
        if unicode(QString(text).toUtf8(), 'utf-8',
                   'ignore') == u"运行结束" and self.make_report:
            self.make_test_report()

    def set_log(self):
        autodir = QFileDialog.getExistingDirectory()
        if autodir:
            self.ui.path_log.setText(unicode(autodir))

    def get_auto(self):
        autodir = QFileDialog.getExistingDirectory()
        if autodir:
            self.ui.path_auto.setText(unicode(autodir))

    def get_tcl(self):
        s = QFileDialog.getOpenFileName(self, u"查找tclsh.exe", "C:/Tcl/bin",
                                        "tclsh.exe(*.exe)")
        self.ui.path_tcl.setText(unicode(s))

    def get_python(self):
        s = QFileDialog.getOpenFileName(self, u"查找python.exe", "C:/python24",
                                        "python.exe(*.exe)")
        self.ui.path_python.setText(unicode(s))

    def save_config(self):
        if not self.config:
            self.config = ConfigObj(self.configfile, encoding='UTF8')
        dir_auto = unicode(self.ui.path_auto.text())
        dir_tcl = unicode(self.ui.path_tcl.text())
        dir_python = unicode(self.ui.path_python.text())
        dir_log = unicode(self.ui.path_log.text())
        #ssid=unicode(self.ui.ssid_name.text())
        #ssid5=unicode(self.ui.ssid_name5g.text())
        product = unicode(self.ui.dut_type.currentText())
        user = unicode(self.ui.dut_user.text())
        pwd = unicode(self.ui.dut_pwd.text())
        url = unicode(self.ui.dut_ip.text())
        user_cmp = unicode(self.ui.cmp_user.text())
        pwd_cmp = unicode(self.ui.cmp_pwd.text())
        url_cmp = unicode(self.ui.cmp_ip.text())
        if not (dir_auto and dir_tcl and dir_python):
            QMessageBox.information(self, "Information", u"所需信息不能为空")
            return
        # if not (os.path.exists(dir_auto) and os.path.exists(dir_tcl) and os.path.exists(dir_python)):
        # QMessageBox.information(self,"Information",u"部分路径不存在")
        # return;
        self.config['app'] = {}
        self.config['app']["dir_auto"] = dir_auto
        self.config['app']["dir_tcl"] = dir_tcl
        self.config['app']["dir_python"] = dir_python
        self.config['app']["dir_log"] = dir_log
        #self.config['app']["ssid"]=ssid
        self.config['app']["product"] = product
        self.config['app']["user"] = user
        self.config['app']["pwd"] = pwd
        self.config['app']["url"] = url
        self.config['app']["user_cmp"] = user_cmp
        self.config['app']["pwd_cmp"] = pwd_cmp
        self.config['app']["url_cmp"] = url_cmp
        #self.config['app']["ssid5"]=ssid5
        self.config.write()
        QMessageBox.information(self, "Information", u"保存成功")
        self.load_config()

    # def load_config(self):
    # if os.path.exists(self.configfile):
    # self.config = ConfigObj(self.configfile,encoding='UTF8')
    # else:
    # self.config=None
    # return
    # self.ui.path_auto.setText(unicode(self.config['app']["dir_auto"]))
    # self.ui.path_tcl.setText(unicode(self.config['app']["dir_tcl"]))
    # self.ui.path_python.setText(unicode(self.config['app']["dir_python"]))
    # if not 'dir_log'  in self.config['app']:
    # self.ui.path_log.setText(os.path.join(mainpath,"results").decode("gbk"))
    # else:
    # self.ui.path_log.setText(unicode(self.config['app']["dir_log"]))
    # if "ssid" in self.config['app']:
    # self.ui.ssid_name.setText(unicode(self.config['app']["ssid"]))

    def load_config(self):
        global dir_auto, dir_python
        if os.path.exists(self.configfile):
            self.config = ConfigObj(self.configfile, encoding='UTF8')
        else:
            self.config = None
            return
        #print "self.config=",self.config
        self.ui.path_auto.setText(unicode(self.config['app']["dir_auto"]))
        self.ui.path_tcl.setText(unicode(self.config['app']["dir_tcl"]))
        self.ui.path_python.setText(unicode(self.config['app']["dir_python"]))
        #self.ui.dut_type.setItemText(0,unicode(self.config['app']["product"]))
        self.ui.dut_user.setText(unicode(self.config['app']["user"]))
        self.ui.dut_pwd.setText(unicode(self.config['app']["pwd"]))
        self.ui.dut_ip.setText(unicode(self.config['app']["url"]))
        self.ui.cmp_user.setText(unicode(self.config['app']["user_cmp"]))
        self.ui.cmp_pwd.setText(unicode(self.config['app']["pwd_cmp"]))
        self.ui.cmp_ip.setText(unicode(self.config['app']["url_cmp"]))

        if not 'dir_log' in self.config['app']:
            self.ui.path_log.setText(
                os.path.join(mainpath, "results").decode("gbk"))
        else:
            self.ui.path_log.setText(unicode(self.config['app']["dir_log"]))
        # if "ssid" in self.config['app']:
        # self.ui.ssid_name.setText(unicode(self.config['app']["ssid"]))
        # if "ssid5" in self.config['app']:
        # self.ui.ssid_name5g.setText(unicode(self.config['app']["ssid5"]))
        dir_auto = unicode(self.ui.path_auto.text())
        #print dir_auto
        GlobalVar.set_dir_auto(self.ui.path_auto.text())
        dir_python = unicode(self.ui.path_python.text())
        GlobalVar.set_dir_python(self.ui.path_python.text())
        #GlobalVar.set_dir_log(self.ui.path_log.text())

    def init_tree(self):
        xml_path = os.path.join(mainpath, "cases")
        #print "xml_path=",xml_path
        self.ui.casetree = CaseTreeWidget(self)
        self.ui.casetree.setGeometry(QtCore.QRect(0, 0, 341, 571))
        self.ui.casetree.setObjectName(_fromUtf8("casetree"))
        self.ui.casetree.headerItem().setText(0, _fromUtf8("1"))
        self.ui.casetree.setHeaderLabel(u"用例树")
        self.ui.casetree.setColumnCount(1)
        self.ui.casetree.setMaximumWidth(360)
        self.root = CaseWidgetItem(self.ui.casetree)
        self.root.setText(0, u"树根")
        self.ui.casetree.setItemExpanded(self.root, True)
        xmlfiles = [
            i for i in os.listdir(xml_path) if os.path.splitext(i)[1] == '.xml'
        ]
        for xmlfile in xmlfiles:
            tree = ET.ElementTree(file=os.path.join(xml_path, xmlfile))
            xmlroot = tree.getroot()
            item_name = xmlroot.get("name")
            ModelTtem = CaseWidgetItem(self.root)
            ModelTtem.itype = "model"
            ModelTtem.iname = item_name
            ModelTtem.setText(0, item_name)
            ModelTtem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled
                               | Qt.ItemIsSelectable)
            ModelTtem.setCheckState(0, Qt.Unchecked)
            for child in xmlroot:
                CaseItem = TreeWidgetItem(child.get("id"), ModelTtem)
                CaseItem.itype = "case"
                CaseItem.iname = child.get("name")
                CaseItem.setText(0, child.get("name"))
                CaseItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled
                                  | Qt.ItemIsSelectable)
                CaseItem.setCheckState(0, Qt.Unchecked)
        self.connect(self.ui.casetree,
                     SIGNAL("itemChanged(QTreeWidgetItem*, int)"),
                     self.select_action)

    #*****************树形选择动作**********
    def select_action(self, item, index):
        if Qt.PartiallyChecked != item.checkState(0):
            self.setChildCheckState(item, item.checkState(0))
        if Qt.PartiallyChecked == item.checkState(0):
            if not self.isTopItem(item):
                item.parent().setCheckState(0, Qt.PartiallyChecked)

    def setChildCheckState(self, item, cs):
        if not item: return
        for i in range(item.childCount()):
            child = item.child(i)
            if child.checkState(0) != cs:
                child.setCheckState(0, cs)
        self.setParentCheckState(item.parent())

    def setParentCheckState(self, item):
        if not item: return
        selectedCount = 0
        childCount = item.childCount()
        for i in range(item.childCount()):
            child = item.child(i)
            if child.checkState(0) == Qt.Checked:
                selectedCount += 1
        if selectedCount == 0:
            item.setCheckState(0, Qt.Unchecked)
        elif selectedCount == childCount:
            item.setCheckState(0, Qt.Checked)
        else:
            item.setCheckState(0, Qt.PartiallyChecked)

    def isTopItem(self, item):
        if not item: return False
        if not item.parent(): return True
        return False
Esempio n. 16
0
class Pmeter(QMainWindow):
    __author__ = "Gregory Moille"
    __copyright__ = "Copyright 2018, NIST"
    __credits__ = ["Gregory Moille", "Xiyuan Lu", "Kartik Srinivasan"]
    __license__ = "GPL"
    __version__ = "2.0.0"
    __maintainer__ = "Gregory Moille"
    __email__ = "*****@*****.**"
    __status__ = "Development"

    def __init__(self, **kwargs):
        super(Pmeter, self).__init__()
        # -- setup the UI --
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.P_IN = myQLabel('In. Pwr')
        self.ui.P_IN.setObjectName("P_IN")
        self.ui.P_IN.setAlignment(Qt.AlignCenter)
        self.ui.pin_frame.addWidget(self.ui.P_IN)

        self.ui.P_OUT = myQLabel('Outp. Pwr')
        self.ui.P_OUT.setObjectName("P_OUT")
        self.ui.P_OUT.setAlignment(Qt.AlignCenter)
        self.ui.pout_frame.addWidget(self.ui.P_OUT)

        self.SetupDict()
        self.GetConnectedRessources()

        self.but_connect['in'].clicked.connect(lambda: self.Connect('in'))
        self.but_connect['out'].clicked.connect(lambda: self.Connect('out'))

    def SetupDict(self):
        # -- Define UI elements --
        self.address = ['']
        self.but_connect = {
            'in': self.ui.connect_IN,
            'out': self.ui.connect_OUT
        }
        self.list_address = {
            'in': self.ui.address_IN,
            'out': self.ui.address_OUT
        }
        self.connected_instr = {}
        self.Pfactor = {
            'in': lambda: float(self.ui.fact_IN.text()),
            'out': lambda: float(self.ui.fact_OUT.text())
        }
        self.Pdisp = {'in': self.ui.P_IN, 'out': self.ui.P_OUT}
        self.Pmeter = {'in': None, 'out': None}
        self.λ = {
            'in': lambda: float(self.ui.wavelength_IN.currentText()),
            'out': lambda: float(self.ui.wavelength_OUT.currentText())
        }
        self._isconnected = {'in': False, 'out': False}
        self.threadread = {'in': None, 'out': None}
        self._readlopp = {'in': True, 'out': True}
        self.P = {'in': 0, 'out': 0}

    def GetConnectedRessources(self):
        try:
            rm = visa.ResourceManager()
            try:
                dev = rm.list_resources()
                # get the names of the instruments:
                names = []
                for dd in dev:
                    try:
                        instr = rm.open_resource(dd, timeout=0.5)
                        print('-' * 60)
                        n = instr.query('*IDN?').strip().replace(
                            'Thorlabs,', '').replace('1.3.0',
                                                     '').replace(',', ', ')
                        names += [n]
                        self.connected_instr[n] = dd
                    except Exception as err:
                        print(err)

                [self.list_address[kk].addItems(names) for kk in ['in', 'out']]
            except Exception as err:
                print('Listing ressources Error')
                print(err)
                pass
        except:
            try:
                dev = rm.list_resources()
                for dd in dev:
                    try:
                        instr = rm.open_resource(dd, timeout=0.5)
                        print('-' * 60)
                        instr.write('*RST')
                        instr.write('*CLS')
                        n = instr.query('*IDN?').strip()
                        names += [n]
                        self.list_address['in'].addItems(n)
                        self.list_address['in'].addItems(n)
                        self.connected_instr[n] = dd
                    except Exception as err:
                        print(err)
            except Exception as err:
                print('Listing ressources @py Error')
                print(err)
                pass

    def Connect(self, port):
        print(port)
        if self._isconnected[port]:
            self.ReadLoop(port, False)
            time.sleep(0.25)
            self.Pmeter[port].connected = False
            self._isconnected[port] = False
            self.but_connect[port].setText('Connect')
        else:
            try:
                instr = self.list_address[port].currentText()
                add = self.connected_instr[instr]
                self.Pmeter[port] = ThorlabsP1xx(address=add)
                self.Pmeter[port].connected = True
                self._isconnected[port] = True

                self.SetupPmeter(port)

                time.sleep(0.25)
                self.but_connect[port].setText('Disconnect')
                self._readlopp[port] = True
                self.ReadLoop(port, True)
            except Exception as err:
                print('Connection to device error')
                print(err)
                pass

    def SetupPmeter(self, port):
        self.Pmeter[port].lbd = self.λ[port]()
        print(self.Pmeter[port].lbd)

    def ReadLoop(self, port, state):
        class PowerMonitor(QThread):
            pwr = pyqtSignal(tuple)

            def __init__(self, **kwargs):
                self.pmeter = kwargs.get('pmeter', None)
                self.port = kwargs.get('port', None)
                self._isRuning = True
                QThread.__init__(self)

            def run(self):
                while self._isRuning:
                    try:
                        p = self.pmeter.power
                        to_emit = (p, self.port)
                        self.pwr.emit(to_emit)
                    except Exception as err:
                        self.pmeter._instr.write('*RST')
                        self.pmeter._instr.write('*CLS')
                        self.pmeter.connected = False
                        time.sleep(1)
                        self.pmeter.connected = True
                        # self.pmeter._instr.write('*RST')
                        # self.pmeter._instr.write('*CLS')

            def stop(self):
                self._isRuning = False

        @pyqtSlot(tuple)
        def UpdatePower(tpl):
            # ipdb.set_trace()
            pwr = tpl[0]
            port = tpl[1]
            coef = np.array([-9, -6, -3, 1], dtype=float)
            units = ['nW', 'µW', 'mW', 'W']

            try:
                fact = self.Pfactor[port]()
            except Exception as err:
                print(err)
                fact = 1

            data = pwr * fact
            self.P[port] = data
            print(self.P[port])
            if self.P[port] <= 0:
                Pstr = '-Inf'
            else:
                ind = np.where(np.log10(self.P[port]) < coef)[0][0] - 1
                print(ind)
                print(self.P[port] * 10**(-1 * coef[ind]))
                Pstr = '{:.3f} {}'.format(self.P[port] * 10**(-1 * coef[ind]),
                                          units[ind])
                # Pstr = '{:.3f}'.format(data* 1e6)
            self.Pdisp[port].setText(Pstr)

            if self._isconnected['in'] and self._isconnected['out']:
                losses = 10 * np.log10(self.P['out'] / self.P["in"])
                self.ui.losses.setText('{:.2f} dB'.format(losses))

        if state:
            self.threadread[port] = PowerMonitor(pmeter=self.Pmeter[port],
                                                 port=port)
            self.threadread[port].pwr[tuple].connect(UpdatePower)
            self.threadread[port].start()
        else:
            self.threadread[port].stop()
Esempio n. 17
0
import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
from PyQt5 import QtWidgets
from UI import Ui_MainWindow

if __name__ == '__main__':
    ui = Ui_MainWindow()
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()
    ui.setupUi(window)
    window.show()
    sys.exit(app.exec_())
Esempio n. 18
0
class MyMain(QMainWindow):
    def __init__(self, parent=None):
        global logDir, logDirPath
        super(MyMain, self).__init__(parent)
        self.setObjectName('MainWindow')
        self.Success = False
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initPath()
        self.ui.logPathEdit.setText(logDir)
        self.ui.chooseLocation.clicked.connect(self.choose)
        self.ui.startButton.clicked.connect(self.start_download)
        self.ui.pause_button.clicked.connect(self.pause_download)
        self.ui.stopButton.clicked.connect(self.stop_download)
        self.ui.pushButton.clicked.connect(self.setting)
        self.ui.chooseBT.clicked.connect(self.logPath)
        self.ui.log_button.clicked.connect(self.showLog)
        self.multidownload = MultiThreadDownload(self.show_download_info)
        self.multidownload.download_info_signal.connect(
            self.show_download_info)

    def initPath(self):
        global logDir, logDirPath
        # 默认下载文件位置
        if os.path.exists(saveDir):
            with open(saveDir) as f:
                self.ui.lineEdit.setText(f.read())
        else:
            with open(saveDir, 'x') as f:
                pass
        if os.path.exists(logDirPath):
            with open(logDirPath) as f:
                logDir = f.read() + '/log.txt'
        else:
            pass

    # 重写主窗口关闭事件,实现对本次软件使用的日志导入
    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        global logDir, logDirPath
        if self.ui.log_checkBox.isChecked(
        ) and not self.ui.log_checkBox2.isChecked():
            with open(logDir, 'a') as f:
                f.write('此次运行日志为:\n')
                f.write(self.ui.Download_info.toPlainText())
                f.write('\n\n\n')

    def choose(self):
        if self.ui.checkBox.isChecked():
            if not os.path.exists(saveDir):
                QMessageBox.warning(self, '警告',
                                    '您未曾选择过默认路径\n请前往设置界面设置路径\n或者取消选择默认路径下载')
            else:
                with open(saveDir, 'r') as f:
                    dir_path = f.read()
                self.ui.filepathEdit.setText(dir_path + '/')
        else:
            dir_path = QFileDialog.getExistingDirectory(self, "请选择文件夹路径", "/:")
            if dir_path:
                self.ui.filepathEdit.setText(dir_path + '/')

    def logPath(self):
        # 默认日志位置为./log.txt
        if self.ui.log_checkBox.isChecked():
            logDir = QFileDialog.getExistingDirectory(self, "请选择文件夹路径", "/:")
            with open(logDirPath, 'w') as f:
                f.write(logDir)
            self.ui.logPathEdit.setText(logDir)
        else:
            QMessageBox.critical(self, '错误', '您还没有启用日志功能')

    def showLog(self):
        global logDir
        if self.ui.log_checkBox.isChecked():
            if os.path.exists(logDir):
                with open(logDir, 'r') as f:
                    self.ui.log_plainEdit.setPlainText(f.read())
            else:
                QMessageBox.critical(self, '错误', '第一次使用暂无日志文件')
        else:
            QMessageBox.critical(self, '错误', '您还没有启用日志功能')

    def show_download_info(self, info):
        if 'info' in info.keys():
            self.ui.Download_info.appendPlainText(info['info'])
            if 'value' in info.keys():
                if info['value'] < 0.0:
                    QMessageBox.critical(self, "出错啦", "暂不支持多分p视频下载")
                elif info['value'] > 0.0:
                    QMessageBox.critical(self, "Bilibili error", "BV号解析失败")
        else:
            self.ui.Download_info.undo()
            percent = int(info['downloaded'] / g.globals_variable.file_size *
                          100)
            self.ui.MainprogressBar.setValue(percent)
            if percent == 100 and self.Success:
                self.Success = True
                QMessageBox.information(self, "成功", "您的下载已经成功完成")
            download_info = ""
            for thread_id, process in info['sub_downloaded'].items():
                if process > 100:
                    process = 100
                download_info += 'INFO: {' + thread_id + '}' + str(
                    round(process, 3)) + '%' + '\n'
            self.ui.Download_info.appendPlainText(download_info)
            self.ui.Download_info.moveCursor(QTextCursor.End)

    def setting(self):
        dir_path = QFileDialog.getExistingDirectory(self, "请选择文件夹路径", "/:")
        if dir_path:
            self.ui.lineEdit.setText(dir_path)
            with open(saveDir, 'w') as f:
                f.write(dir_path)
            QMessageBox.information(self, '提示', '默认保存位置已写入route文件')

    def start_download(self):
        StartFlag = True
        g.globals_variable.__init__()
        self.ui.Download_info.setPlainText("")
        self.ui.MainprogressBar.setValue(0)
        g.globals_variable.filepath = self.ui.filepathEdit.text()
        if self.ui.DownloadType.currentText() == 'URL':
            if not re.match(
                    r'(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
                    self.ui.URLlineEdit.text()):
                QMessageBox.warning(self, '警告', '您输入的链接格式错误')
                StartFlag = False
            else:
                g.globals_variable.url = self.ui.URLlineEdit.text()
                self.ui.Download_info.appendPlainText(
                    f'您所下载的链接为{g.globals_variable.url}')
                g.globals_variable.filename = g.globals_variable.url.split(
                    '?')[0].split('/')[-1]
                g.globals_variable.Type = 'URL'
        elif self.ui.DownloadType.currentText() == 'BVid':
            if not re.match(r'BV[A-Za-z0-9]{10}', self.ui.URLlineEdit.text()):
                QMessageBox.warning(self, '警告', '您输入的BV号格式错误')
                StartFlag = False
            else:
                g.globals_variable.BVid = self.ui.URLlineEdit.text()
                self.ui.Download_info.appendPlainText(
                    f'您所下载的视频BV号为{g.globals_variable.BVid}')
                g.globals_variable.Type = 'Bilibili'
        if StartFlag:
            g.globals_variable.threads_num = self.ui.horizontalSlider.value()
            self.multidownload.start()

    def pause_download(self):
        self.multidownload.pause()
        if self.ui.pause_button.text() == '暂停下载':
            self.ui.pause_button.setText('继续下载')
        else:
            self.ui.pause_button.setText('暂停下载')

    def stop_download(self):
        if not self.multidownload.isRunning():
            QMessageBox.critical(self, "错误", "你还没有开始下载!")
        else:
            self.multidownload.stop()
            self.multidownload.terminate()
            self.ui.Download_info.appendPlainText('成功结束下载!')
Esempio n. 19
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initialArrowIcon()
        self.setFixedSize(self.size())

        # Add pLabel & delete old QLabel
        self.label_image_original = dLabel(self.ui.centralwidget, self)
        self.label_image_original.setGeometry(
            QRect(self.ui.label_image_original.pos(),
                  self.ui.label_image_original.size()))

        del self.ui.label_image_original

        # Button
        self.ui.pushButton_upload.clicked.connect(self.openFileEvent)
        self.ui.pushButton_exit.clicked.connect(self.exitEvent)
        self.ui.pushButton_save.clicked.connect(self.saveEvent)

        # Slider
        self.ui.horizontalSlider_R.setDisabled(True)
        self.ui.horizontalSlider_G.setDisabled(True)
        self.ui.horizontalSlider_B.setDisabled(True)

        self.ui.horizontalSlider_R.setMaximum(255)
        self.ui.horizontalSlider_G.setMaximum(255)
        self.ui.horizontalSlider_B.setMaximum(255)
        self.ui.horizontalSlider_R.valueChanged.connect(
            lambda: self.color_value('R'))
        self.ui.horizontalSlider_G.valueChanged.connect(
            lambda: self.color_value('G'))
        self.ui.horizontalSlider_B.valueChanged.connect(
            lambda: self.color_value('B'))

        # LineEdit
        self.ui.lineEdit_R.textChanged.connect(self.color_change)
        self.ui.lineEdit_G.textChanged.connect(self.color_change)
        self.ui.lineEdit_B.textChanged.connect(self.color_change)

    def changeOutputColor(self):
        image = ImageQt.fromqpixmap(self.ui.label_image_output.pixmap())
        image = image.resize((self.ui.label_image_output.size().width(),
                              self.ui.label_image_output.size().height()))
        image_data = list(image.getdata())

        newRGBA = (self.newR, self.newG, self.newB, self.rgba[3])
        for index in self.changePos:
            image_data[index] = newRGBA

        image.putdata(image_data)

        if image.mode == "RGB":
            r, g, b = image.split()
            image = Image.merge("RGB", (b, g, r))
        elif image.mode == "RGBA":
            r, g, b, a = image.split()
            image = Image.merge("RGBA", (b, g, r, a))
        elif image.mode == "L":
            image = image.convert("RGBA")

        image2 = image.convert("RGBA")
        data = image2.tobytes("raw", "RGBA")
        qim = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32)
        pixmap = QPixmap.fromImage(qim)

        self.ui.label_image_output.setPixmap(QPixmap(pixmap))

    def get(self, pos):
        index = pos.y() * self.label_image_original.size().width() + pos.x()
        image = ImageQt.fromqpixmap(self.label_image_original.pixmap())
        image = image.resize((self.label_image_original.size().width(),
                              self.label_image_original.size().height()))
        image_data = image.getdata()

        self.rgba = image_data[index]
        if len(self.rgba) == 3:
            r, g, b = self.rgba
        elif len(image_data[index]) == 4:
            r, g, b, a = self.rgba

        self.changePos = []

        index = 0
        for item in image_data:
            if item == self.rgba:
                self.changePos.append(index)

            index += 1

        print(len(self.changePos))
        print(self.changePos)
        self.ui.label_color_original.setStyleSheet(
            'background-color: rgb({},{},{});'.format(r, g, b))
        self.ui.horizontalSlider_R.setDisabled(False)
        self.ui.horizontalSlider_G.setDisabled(False)
        self.ui.horizontalSlider_B.setDisabled(False)

    def color_change(self):
        self.newR = int(self.ui.lineEdit_R.text())
        self.newG = int(self.ui.lineEdit_G.text())
        self.newB = int(self.ui.lineEdit_B.text())
        self.ui.label_color_output.setStyleSheet(
            'background-color: rgb({}, {}, {});'.format(
                self.newR, self.newG, self.newB))
        self.changeOutputColor()

    def color_value(self, color):
        if color == 'R':
            self.ui.lineEdit_R.setText(str(self.ui.horizontalSlider_R.value()))
        elif color == 'G':
            self.ui.lineEdit_G.setText(str(self.ui.horizontalSlider_G.value()))
        elif color == 'B':
            self.ui.lineEdit_B.setText(str(self.ui.horizontalSlider_B.value()))

    def openFileEvent(self):
        file_name, _ = QFileDialog.getOpenFileName(self, "Open Image",
                                                   QDir.homePath())

        if file_name.split('.')[-1] in ['png', 'jpg', 'jpeg']:
            image = Image.open(file_name)
            image = image.resize((self.ui.label_image_output.size().width(),
                                  self.ui.label_image_output.size().height()))

            if image.mode == "RGB":
                r, g, b = image.split()
                image = Image.merge("RGB", (b, g, r))
            elif image.mode == "RGBA":
                r, g, b, a = image.split()
                image = Image.merge("RGBA", (b, g, r, a))
            elif image.mode == "L":
                image = image.convert("RGBA")

            image2 = image.convert("RGBA")
            data = image2.tobytes("raw", "RGBA")
            qim = QImage(data, image.size[0], image.size[1],
                         QImage.Format_ARGB32)
            pixmap = QPixmap.fromImage(qim)

            self.label_image_original.setPixmap(QPixmap(pixmap))
            self.ui.label_image_output.setPixmap(QPixmap(pixmap))
            self.label_image_original.switch = 1

    def initialArrowIcon(self):
        # Load byte data
        byte_data = base64.b64decode(arrow)
        image_data = BytesIO(byte_data)
        image = Image.open(image_data)
        image = image.convert('RGBA')

        # PIL to QPixmap
        qImage = ImageQt.ImageQt(image)
        image = QPixmap.fromImage(qImage)

        self.ui.label_arrow.setPixmap(QPixmap(image))
        self.ui.label_arrow.setScaledContents(True)

    def saveEvent(self):
        image = ImageQt.fromqpixmap(self.ui.label_image_output.pixmap())
        image.save('test.png')

    def exitEvent(self):
        exit()
Esempio n. 20
0
class Speed_Gun:
	"""
	Main controller class for the Speed Gun application
	"""
	def __init__(self, samp_T_us, cpi_samps, savefile, emulate=False):
		"""
		PURPOSE: creates a new Speed_Gun
		ARGS: 
			samp_T_us (float): sampling period in microseconds
			cpi_samps (int): number of samples in one cpi
			emulate (bool): if True loads pre-recorded data, if False runs for 
				real
			savefile (str): the file to save to
		RETURNS: new instance of a Speed_Gun
		NOTES:
		"""
		#Save arguments
		self.samp_T_us = samp_T_us
		self.fs = 1e6 / samp_T_us
		self.cpi_samps = cpi_samps
		self.emulate = emulate
		self.savefile = savefile

		#Setup app
		self.app = QtWidgets.QApplication(sys.argv)
		self.main_win = QtWidgets.QMainWindow()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self.main_win)

		#Initialize UI values
		self.init_ui_values()

		#Connect buttons
		self.ui.run_button.clicked.connect(self.run_button_clicked)
		self.ui.stop_button.clicked.connect(self.stop_button_clicked)
		self.ui.vel_radbutton.toggled.connect(self.rad_button_toggled)
		self.ui.raw_sig_radbutton.toggled.connect(self.rad_button_toggled)

		#Setup queues
		self.record_q = queue.Queue()
		self.res_q = queue.Queue()
		self.save_q = queue.Queue()

		#Setup other modules
		#Setup recorder.replayer
		if emulate:
			self.recorder = Replayer("C:\\Users\\rga0230\\Documents\\School\\EE-137\\EE-137-Doppler-Radar\\data\\car.mat", [self.record_q, self.save_q], ts_us=samp_T_us, chunk_size=cpi_samps)
		else:
			self.recorder = Chunked_Arduino_ADC(samp_T_us, cpi_samps, [self.record_q, self.save_q])
		#Setup processor
		self.proc = Processor(samp_T_us, cpi_samps, self.record_q, self.res_q)
		#Setup saver
		self.saver = Chunk_Saver(savefile, samp_T_us, cpi_samps, self.save_q)

		#Setup variables for our update thread
		self.update_thread = threading.Thread(target = self.update_thread_run)
		self.update_keep_going = threading.Event()
		self.update_keep_going.set()

	############################################################################
	def run_app(self):
		"""
		PURPOSE: runs the GUI application
		ARGS: none
		RETURNS: none
		NOTES:
		"""
		#Start update thread
		self.update_thread.start()

		#Run GUI
		self.main_win.show()
		rc = self.app.exec_()

		#Join update thread
		self.update_keep_going.clear()
		self.update_thread.join()
		self.update_thread = None

		#Return GUI exit code
		return rc

	############################################################################
	def init_ui_values(self):
		"""
		PURPOSE: initializes all of the ui input and output fields
		ARGS: none
		RETURNS: none
		NOTES:
		"""
		self.ui.samp_freq_lbl.setText("%.2f" % (self.fs / 1e3))
		self.ui.cpi_lbl.setText(str(int(self.cpi_samps / self.fs * 1e3)))
		self.ui.ard_con_lbl.setText("No")
		self.ui.recv_data_lbl.setText("No")
		self.ui.run_lbl.setText("No")
		self.ui.cpi_num_lbl.setText("")
		self.ui.eng_lbl.setText("")
		self.ui.detc_lbl.setText("")
		self.ui.vel_lbl.setText("")
		self.ui.stop_button.setEnabled(False)
		self.ui.vel_radbutton.setChecked(True)

	############################################################################
	def rad_button_toggled(self):
		if self.ui.vel_radbutton.isChecked():
			self.proc.to_plot = "freq"
			self.proc.setup_res_dict()
		else:
			self.proc.to_plot = "raw"
			self.proc.setup_res_dict()

	############################################################################
	def run_button_clicked(self):
		"""
		PURPOSE: runs when the load/run button is clicked
		ARGS: none
		RETURNS: none
		NOTES:
		"""
		self.ui.run_button.setEnabled(False)
		self.ui.stop_button.setEnabled(True)

		self.recorder.start()
		self.proc.start()

	############################################################################
	def stop_button_clicked(self):
		"""
		PURPOSE: runs when the stop button is clicked
		ARGS: none
		RETURNS: none
		NOTES:
		"""
		#Stop threads
		self.recorder.stop()
		self.proc.stop()

		self.ui.run_button.setEnabled(True)
		self.ui.stop_button.setEnabled(False)

	############################################################################
	def update_thread_run(self):
		"""
		PURPOSE: constantly updates the output values on the GUI
		ARGS: none
		RETURNS: none
		NOTES:
		"""
		#Indicate thread is running
		self.update_keep_going.set()
		self.saver.start()

		try:
			#Run until we are told to stop
			prev_thread_poll_time = 0
			prev_res_time = 0
			while self.update_keep_going.is_set():
				cur_time = time.time()
				if (cur_time - prev_thread_poll_time) >= 1:
					rec_status = self.recorder.get_status()
					proc_status = self.proc.get_status()
					rec_running = rec_status.get("running", False)
					proc_running = proc_status.get("running", False)
					if rec_running and proc_running:
						ard_con = rec_status.get("connected", False)
						recv_data = rec_status.get("receiving_data", False)
						if recv_data and ard_con:
							self.ui.recv_data_lbl.setText("Yes")
						else:
							self.ui.recv_data_lbl.setText("No")
						if ard_con:
							self.ui.ard_con_lbl.setText("Yes")
						else:
							self.ui.ard_con_lbl.setText("No")
						self.ui.run_lbl.setText("Yes")
					else:
						self.ui.ard_con_lbl.setText("No")
						self.ui.recv_data_lbl.setText("No")
						self.ui.run_lbl.setText("No")
						if proc_running != rec_running:
							self.stop_button_clicked()
					prev_thread_poll_time = cur_time
				if (cur_time - prev_res_time) >= 0.1:
					try:
						sig = self.res_q.get(timeout=0.1)
						ax = self.ui.disp_plot.canvas.ax
						ax.clear()
						ax.plot(sig["x"], sig["y"])
						ax.set_xlabel(sig["xlabel"])
						ax.set_ylabel(sig["ylabel"])
						ax.set_title(sig["title"])
						ax.set_xlim(sig["xlim"][0], sig["xlim"][1])
						ax.set_ylim(sig["ylim"][0], sig["ylim"][1])
						self.ui.disp_plot.canvas.draw()
						self.ui.cpi_num_lbl.setText(str(sig["cpi_num"]))
						self.ui.eng_lbl.setText("%.4f" % (sig["eng"]))
						self.ui.detc_lbl.setText(str(sig["detc"]))
						self.ui.vel_lbl.setText("%.2f" % sig["vel"])
					except queue.Empty as e:
						pass
					prev_res_time = cur_time
				time.sleep(0.1)
		except Exception as e:
			print("ERROR: 'update_thread' got exception %s" % type(e))
			print(e)
			self.update_keep_going.clear()

		#Cleanup
		self.recorder.stop()
		self.proc.stop()
		self.saver.stop()
Esempio n. 21
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Button
        self.ui.pushButton00.clicked.connect(lambda: self.buttonEvent(0, 0))
        self.ui.pushButton00.clicked.connect(lambda: self.buttonEvent(0, 0))
        self.ui.pushButton01.clicked.connect(lambda: self.buttonEvent(0, 1))
        self.ui.pushButton02.clicked.connect(lambda: self.buttonEvent(0, 2))
        self.ui.pushButton03.clicked.connect(lambda: self.buttonEvent(0, 3))
        self.ui.pushButton04.clicked.connect(lambda: self.buttonEvent(0, 4))
        self.ui.pushButton05.clicked.connect(lambda: self.buttonEvent(0, 5))
        self.ui.pushButton06.clicked.connect(lambda: self.buttonEvent(0, 6))
        self.ui.pushButton07.clicked.connect(lambda: self.buttonEvent(0, 7))
        self.ui.pushButton08.clicked.connect(lambda: self.buttonEvent(0, 8))
        self.ui.pushButton10.clicked.connect(lambda: self.buttonEvent(1, 0))
        self.ui.pushButton11.clicked.connect(lambda: self.buttonEvent(1, 1))
        self.ui.pushButton12.clicked.connect(lambda: self.buttonEvent(1, 2))
        self.ui.pushButton13.clicked.connect(lambda: self.buttonEvent(1, 3))
        self.ui.pushButton14.clicked.connect(lambda: self.buttonEvent(1, 4))
        self.ui.pushButton15.clicked.connect(lambda: self.buttonEvent(1, 5))
        self.ui.pushButton16.clicked.connect(lambda: self.buttonEvent(1, 6))
        self.ui.pushButton17.clicked.connect(lambda: self.buttonEvent(1, 7))
        self.ui.pushButton18.clicked.connect(lambda: self.buttonEvent(1, 8))
        self.ui.pushButton20.clicked.connect(lambda: self.buttonEvent(2, 0))
        self.ui.pushButton21.clicked.connect(lambda: self.buttonEvent(2, 1))
        self.ui.pushButton22.clicked.connect(lambda: self.buttonEvent(2, 2))
        self.ui.pushButton23.clicked.connect(lambda: self.buttonEvent(2, 3))
        self.ui.pushButton24.clicked.connect(lambda: self.buttonEvent(2, 4))
        self.ui.pushButton25.clicked.connect(lambda: self.buttonEvent(2, 5))
        self.ui.pushButton26.clicked.connect(lambda: self.buttonEvent(2, 6))
        self.ui.pushButton27.clicked.connect(lambda: self.buttonEvent(2, 7))
        self.ui.pushButton28.clicked.connect(lambda: self.buttonEvent(2, 8))
        self.ui.pushButton30.clicked.connect(lambda: self.buttonEvent(3, 0))
        self.ui.pushButton31.clicked.connect(lambda: self.buttonEvent(3, 1))
        self.ui.pushButton32.clicked.connect(lambda: self.buttonEvent(3, 2))
        self.ui.pushButton33.clicked.connect(lambda: self.buttonEvent(3, 3))
        self.ui.pushButton34.clicked.connect(lambda: self.buttonEvent(3, 4))
        self.ui.pushButton35.clicked.connect(lambda: self.buttonEvent(3, 5))
        self.ui.pushButton36.clicked.connect(lambda: self.buttonEvent(3, 6))
        self.ui.pushButton37.clicked.connect(lambda: self.buttonEvent(3, 7))
        self.ui.pushButton38.clicked.connect(lambda: self.buttonEvent(3, 8))
        self.ui.pushButton40.clicked.connect(lambda: self.buttonEvent(4, 0))
        self.ui.pushButton41.clicked.connect(lambda: self.buttonEvent(4, 1))
        self.ui.pushButton42.clicked.connect(lambda: self.buttonEvent(4, 2))
        self.ui.pushButton43.clicked.connect(lambda: self.buttonEvent(4, 3))
        self.ui.pushButton44.clicked.connect(lambda: self.buttonEvent(4, 4))
        self.ui.pushButton45.clicked.connect(lambda: self.buttonEvent(4, 5))
        self.ui.pushButton46.clicked.connect(lambda: self.buttonEvent(4, 6))
        self.ui.pushButton47.clicked.connect(lambda: self.buttonEvent(4, 7))
        self.ui.pushButton48.clicked.connect(lambda: self.buttonEvent(4, 8))
        self.ui.pushButton50.clicked.connect(lambda: self.buttonEvent(5, 0))
        self.ui.pushButton51.clicked.connect(lambda: self.buttonEvent(5, 1))
        self.ui.pushButton52.clicked.connect(lambda: self.buttonEvent(5, 2))
        self.ui.pushButton53.clicked.connect(lambda: self.buttonEvent(5, 3))
        self.ui.pushButton54.clicked.connect(lambda: self.buttonEvent(5, 4))
        self.ui.pushButton55.clicked.connect(lambda: self.buttonEvent(5, 5))
        self.ui.pushButton56.clicked.connect(lambda: self.buttonEvent(5, 6))
        self.ui.pushButton57.clicked.connect(lambda: self.buttonEvent(5, 7))
        self.ui.pushButton58.clicked.connect(lambda: self.buttonEvent(5, 8))
        self.ui.pushButton60.clicked.connect(lambda: self.buttonEvent(6, 0))
        self.ui.pushButton61.clicked.connect(lambda: self.buttonEvent(6, 1))
        self.ui.pushButton62.clicked.connect(lambda: self.buttonEvent(6, 2))
        self.ui.pushButton63.clicked.connect(lambda: self.buttonEvent(6, 3))
        self.ui.pushButton64.clicked.connect(lambda: self.buttonEvent(6, 4))
        self.ui.pushButton65.clicked.connect(lambda: self.buttonEvent(6, 5))
        self.ui.pushButton66.clicked.connect(lambda: self.buttonEvent(6, 6))
        self.ui.pushButton67.clicked.connect(lambda: self.buttonEvent(6, 7))
        self.ui.pushButton68.clicked.connect(lambda: self.buttonEvent(6, 8))
        self.ui.pushButton70.clicked.connect(lambda: self.buttonEvent(7, 0))
        self.ui.pushButton71.clicked.connect(lambda: self.buttonEvent(7, 1))
        self.ui.pushButton72.clicked.connect(lambda: self.buttonEvent(7, 2))
        self.ui.pushButton73.clicked.connect(lambda: self.buttonEvent(7, 3))
        self.ui.pushButton74.clicked.connect(lambda: self.buttonEvent(7, 4))
        self.ui.pushButton75.clicked.connect(lambda: self.buttonEvent(7, 5))
        self.ui.pushButton76.clicked.connect(lambda: self.buttonEvent(7, 6))
        self.ui.pushButton77.clicked.connect(lambda: self.buttonEvent(7, 7))
        self.ui.pushButton78.clicked.connect(lambda: self.buttonEvent(7, 8))
        self.ui.pushButton80.clicked.connect(lambda: self.buttonEvent(8, 0))
        self.ui.pushButton81.clicked.connect(lambda: self.buttonEvent(8, 1))
        self.ui.pushButton82.clicked.connect(lambda: self.buttonEvent(8, 2))
        self.ui.pushButton83.clicked.connect(lambda: self.buttonEvent(8, 3))
        self.ui.pushButton84.clicked.connect(lambda: self.buttonEvent(8, 4))
        self.ui.pushButton85.clicked.connect(lambda: self.buttonEvent(8, 5))
        self.ui.pushButton86.clicked.connect(lambda: self.buttonEvent(8, 6))
        self.ui.pushButton87.clicked.connect(lambda: self.buttonEvent(8, 7))
        self.ui.pushButton88.clicked.connect(lambda: self.buttonEvent(8, 8))

        # Button color
        self.colorPosition = (-1, -1)

        # Go button
        self.ui.GoButton.clicked.connect(self.GoButtonEvent)

    def buttonEvent(self, i, j):
        if self.colorPosition != (-1, -1):
            self.removeButtonColor(self.colorPosition[0],
                                   self.colorPosition[1])

        if (i, j) == (0, 0):
            self.ui.pushButton00.setStyleSheet(
                'background-color: rgb(220, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 1):
            self.ui.pushButton01.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 2):
            self.ui.pushButton02.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 3):
            self.ui.pushButton03.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 4):
            self.ui.pushButton04.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 5):
            self.ui.pushButton05.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 6):
            self.ui.pushButton06.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 7):
            self.ui.pushButton07.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (0, 8):
            self.ui.pushButton08.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 0):
            self.ui.pushButton10.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 1):
            self.ui.pushButton11.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 2):
            self.ui.pushButton12.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 3):
            self.ui.pushButton13.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 4):
            self.ui.pushButton14.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 5):
            self.ui.pushButton15.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 6):
            self.ui.pushButton16.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 7):
            self.ui.pushButton17.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (1, 8):
            self.ui.pushButton18.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 0):
            self.ui.pushButton20.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 1):
            self.ui.pushButton21.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 2):
            self.ui.pushButton22.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 3):
            self.ui.pushButton23.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 4):
            self.ui.pushButton24.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 5):
            self.ui.pushButton25.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 6):
            self.ui.pushButton26.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 7):
            self.ui.pushButton27.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (2, 8):
            self.ui.pushButton28.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 0):
            self.ui.pushButton30.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 1):
            self.ui.pushButton31.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 2):
            self.ui.pushButton32.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 3):
            self.ui.pushButton33.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 4):
            self.ui.pushButton34.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 5):
            self.ui.pushButton35.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 6):
            self.ui.pushButton36.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 7):
            self.ui.pushButton37.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (3, 8):
            self.ui.pushButton38.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 0):
            self.ui.pushButton40.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 1):
            self.ui.pushButton41.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 2):
            self.ui.pushButton42.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 3):
            self.ui.pushButton43.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 4):
            self.ui.pushButton44.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 5):
            self.ui.pushButton45.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 6):
            self.ui.pushButton46.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 7):
            self.ui.pushButton47.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (4, 8):
            self.ui.pushButton48.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 0):
            self.ui.pushButton50.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 1):
            self.ui.pushButton51.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 2):
            self.ui.pushButton52.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 3):
            self.ui.pushButton53.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 4):
            self.ui.pushButton54.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 5):
            self.ui.pushButton55.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 6):
            self.ui.pushButton56.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 7):
            self.ui.pushButton57.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (5, 8):
            self.ui.pushButton58.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 0):
            self.ui.pushButton60.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 1):
            self.ui.pushButton61.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 2):
            self.ui.pushButton62.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 3):
            self.ui.pushButton63.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 4):
            self.ui.pushButton64.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 5):
            self.ui.pushButton65.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 6):
            self.ui.pushButton66.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 7):
            self.ui.pushButton67.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (6, 8):
            self.ui.pushButton68.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 0):
            self.ui.pushButton70.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 1):
            self.ui.pushButton71.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 2):
            self.ui.pushButton72.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 3):
            self.ui.pushButton73.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 4):
            self.ui.pushButton74.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 5):
            self.ui.pushButton75.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 6):
            self.ui.pushButton76.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 7):
            self.ui.pushButton77.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (7, 8):
            self.ui.pushButton78.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 0):
            self.ui.pushButton80.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 1):
            self.ui.pushButton81.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 2):
            self.ui.pushButton82.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 3):
            self.ui.pushButton83.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 4):
            self.ui.pushButton84.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 5):
            self.ui.pushButton85.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 6):
            self.ui.pushButton86.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 7):
            self.ui.pushButton87.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)
        elif (i, j) == (8, 8):
            self.ui.pushButton88.setStyleSheet(
                'background-color: rgb(200, 0, 0);')
            self.colorPosition = (i, j)

    def removeButtonColor(self, i, j):
        if i == 0 and j == 0:
            self.ui.pushButton00.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 1:
            self.ui.pushButton01.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 2:
            self.ui.pushButton02.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 3:
            self.ui.pushButton03.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 4:
            self.ui.pushButton04.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 5:
            self.ui.pushButton05.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 6:
            self.ui.pushButton06.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 7:
            self.ui.pushButton07.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 0 and j == 8:
            self.ui.pushButton08.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 0:
            self.ui.pushButton10.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 1:
            self.ui.pushButton11.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 2:
            self.ui.pushButton12.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 3:
            self.ui.pushButton13.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 4:
            self.ui.pushButton14.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 5:
            self.ui.pushButton15.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 6:
            self.ui.pushButton16.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 7:
            self.ui.pushButton17.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 1 and j == 8:
            self.ui.pushButton18.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 0:
            self.ui.pushButton20.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 1:
            self.ui.pushButton21.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 2:
            self.ui.pushButton22.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 3:
            self.ui.pushButton23.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 4:
            self.ui.pushButton24.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 5:
            self.ui.pushButton25.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 6:
            self.ui.pushButton26.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 7:
            self.ui.pushButton27.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 2 and j == 8:
            self.ui.pushButton28.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 0:
            self.ui.pushButton30.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 1:
            self.ui.pushButton31.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 2:
            self.ui.pushButton32.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 3:
            self.ui.pushButton33.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 4:
            self.ui.pushButton34.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 5:
            self.ui.pushButton35.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 6:
            self.ui.pushButton36.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 7:
            self.ui.pushButton37.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 3 and j == 8:
            self.ui.pushButton38.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 0:
            self.ui.pushButton40.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 1:
            self.ui.pushButton41.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 2:
            self.ui.pushButton42.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 3:
            self.ui.pushButton43.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 4:
            self.ui.pushButton44.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 5:
            self.ui.pushButton45.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 6:
            self.ui.pushButton46.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 7:
            self.ui.pushButton47.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 4 and j == 8:
            self.ui.pushButton48.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 0:
            self.ui.pushButton50.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 1:
            self.ui.pushButton51.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 2:
            self.ui.pushButton52.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 3:
            self.ui.pushButton53.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 4:
            self.ui.pushButton54.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 5:
            self.ui.pushButton55.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 6:
            self.ui.pushButton56.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 7:
            self.ui.pushButton57.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 5 and j == 8:
            self.ui.pushButton58.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 0:
            self.ui.pushButton60.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 1:
            self.ui.pushButton61.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 2:
            self.ui.pushButton62.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 3:
            self.ui.pushButton63.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 4:
            self.ui.pushButton64.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 5:
            self.ui.pushButton65.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 6:
            self.ui.pushButton66.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 7:
            self.ui.pushButton67.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 6 and j == 8:
            self.ui.pushButton68.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 0:
            self.ui.pushButton70.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 1:
            self.ui.pushButton71.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 2:
            self.ui.pushButton72.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 3:
            self.ui.pushButton73.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 4:
            self.ui.pushButton74.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 5:
            self.ui.pushButton75.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 6:
            self.ui.pushButton76.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 7:
            self.ui.pushButton77.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 7 and j == 8:
            self.ui.pushButton78.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 0:
            self.ui.pushButton80.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 1:
            self.ui.pushButton81.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 2:
            self.ui.pushButton82.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 3:
            self.ui.pushButton83.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 4:
            self.ui.pushButton84.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 5:
            self.ui.pushButton85.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 6:
            self.ui.pushButton86.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 7:
            self.ui.pushButton87.setStyleSheet(
                'background-color: rgb(200, 200, 200);')
        elif i == 8 and j == 8:
            self.ui.pushButton88.setStyleSheet(
                'background-color: rgb(200, 200, 200);')

    def keyPressEvent(self, event):
        if self.colorPosition != (None, None):
            if event.key() == Qt.Key_1:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 1)
            elif event.key() == Qt.Key_2:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 2)
            elif event.key() == Qt.Key_3:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 3)
            elif event.key() == Qt.Key_4:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 4)
            elif event.key() == Qt.Key_5:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 5)
            elif event.key() == Qt.Key_6:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 6)
            elif event.key() == Qt.Key_7:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 7)
            elif event.key() == Qt.Key_8:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 8)
            elif event.key() == Qt.Key_9:
                self.filledNumberInButton(self.colorPosition[0],
                                          self.colorPosition[1], 9)

    def filledNumberInButton(self, x, y, num):
        num = str(num)
        if x == 0 and y == 0:
            self.ui.pushButton00.setText(num)
        if x == 0 and y == 1:
            self.ui.pushButton01.setText(num)
        if x == 0 and y == 2:
            self.ui.pushButton02.setText(num)
        if x == 0 and y == 3:
            self.ui.pushButton03.setText(num)
        if x == 0 and y == 4:
            self.ui.pushButton04.setText(num)
        if x == 0 and y == 5:
            self.ui.pushButton05.setText(num)
        if x == 0 and y == 6:
            self.ui.pushButton06.setText(num)
        if x == 0 and y == 7:
            self.ui.pushButton07.setText(num)
        if x == 0 and y == 8:
            self.ui.pushButton08.setText(num)
        if x == 1 and y == 0:
            self.ui.pushButton10.setText(num)
        if x == 1 and y == 1:
            self.ui.pushButton11.setText(num)
        if x == 1 and y == 2:
            self.ui.pushButton12.setText(num)
        if x == 1 and y == 3:
            self.ui.pushButton13.setText(num)
        if x == 1 and y == 4:
            self.ui.pushButton14.setText(num)
        if x == 1 and y == 5:
            self.ui.pushButton15.setText(num)
        if x == 1 and y == 6:
            self.ui.pushButton16.setText(num)
        if x == 1 and y == 7:
            self.ui.pushButton17.setText(num)
        if x == 1 and y == 8:
            self.ui.pushButton18.setText(num)
        if x == 2 and y == 0:
            self.ui.pushButton20.setText(num)
        if x == 2 and y == 1:
            self.ui.pushButton21.setText(num)
        if x == 2 and y == 2:
            self.ui.pushButton22.setText(num)
        if x == 2 and y == 3:
            self.ui.pushButton23.setText(num)
        if x == 2 and y == 4:
            self.ui.pushButton24.setText(num)
        if x == 2 and y == 5:
            self.ui.pushButton25.setText(num)
        if x == 2 and y == 6:
            self.ui.pushButton26.setText(num)
        if x == 2 and y == 7:
            self.ui.pushButton27.setText(num)
        if x == 2 and y == 8:
            self.ui.pushButton28.setText(num)
        if x == 3 and y == 0:
            self.ui.pushButton30.setText(num)
        if x == 3 and y == 1:
            self.ui.pushButton31.setText(num)
        if x == 3 and y == 2:
            self.ui.pushButton32.setText(num)
        if x == 3 and y == 3:
            self.ui.pushButton33.setText(num)
        if x == 3 and y == 4:
            self.ui.pushButton34.setText(num)
        if x == 3 and y == 5:
            self.ui.pushButton35.setText(num)
        if x == 3 and y == 6:
            self.ui.pushButton36.setText(num)
        if x == 3 and y == 7:
            self.ui.pushButton37.setText(num)
        if x == 3 and y == 8:
            self.ui.pushButton38.setText(num)
        if x == 4 and y == 0:
            self.ui.pushButton40.setText(num)
        if x == 4 and y == 1:
            self.ui.pushButton41.setText(num)
        if x == 4 and y == 2:
            self.ui.pushButton42.setText(num)
        if x == 4 and y == 3:
            self.ui.pushButton43.setText(num)
        if x == 4 and y == 4:
            self.ui.pushButton44.setText(num)
        if x == 4 and y == 5:
            self.ui.pushButton45.setText(num)
        if x == 4 and y == 6:
            self.ui.pushButton46.setText(num)
        if x == 4 and y == 7:
            self.ui.pushButton47.setText(num)
        if x == 4 and y == 8:
            self.ui.pushButton48.setText(num)
        if x == 5 and y == 0:
            self.ui.pushButton50.setText(num)
        if x == 5 and y == 1:
            self.ui.pushButton51.setText(num)
        if x == 5 and y == 2:
            self.ui.pushButton52.setText(num)
        if x == 5 and y == 3:
            self.ui.pushButton53.setText(num)
        if x == 5 and y == 4:
            self.ui.pushButton54.setText(num)
        if x == 5 and y == 5:
            self.ui.pushButton55.setText(num)
        if x == 5 and y == 6:
            self.ui.pushButton56.setText(num)
        if x == 5 and y == 7:
            self.ui.pushButton57.setText(num)
        if x == 5 and y == 8:
            self.ui.pushButton58.setText(num)
        if x == 6 and y == 0:
            self.ui.pushButton60.setText(num)
        if x == 6 and y == 1:
            self.ui.pushButton61.setText(num)
        if x == 6 and y == 2:
            self.ui.pushButton62.setText(num)
        if x == 6 and y == 3:
            self.ui.pushButton63.setText(num)
        if x == 6 and y == 4:
            self.ui.pushButton64.setText(num)
        if x == 6 and y == 5:
            self.ui.pushButton65.setText(num)
        if x == 6 and y == 6:
            self.ui.pushButton66.setText(num)
        if x == 6 and y == 7:
            self.ui.pushButton67.setText(num)
        if x == 6 and y == 8:
            self.ui.pushButton68.setText(num)
        if x == 7 and y == 0:
            self.ui.pushButton70.setText(num)
        if x == 7 and y == 1:
            self.ui.pushButton71.setText(num)
        if x == 7 and y == 2:
            self.ui.pushButton72.setText(num)
        if x == 7 and y == 3:
            self.ui.pushButton73.setText(num)
        if x == 7 and y == 4:
            self.ui.pushButton74.setText(num)
        if x == 7 and y == 5:
            self.ui.pushButton75.setText(num)
        if x == 7 and y == 6:
            self.ui.pushButton76.setText(num)
        if x == 7 and y == 7:
            self.ui.pushButton77.setText(num)
        if x == 7 and y == 8:
            self.ui.pushButton78.setText(num)
        if x == 8 and y == 0:
            self.ui.pushButton80.setText(num)
        if x == 8 and y == 1:
            self.ui.pushButton81.setText(num)
        if x == 8 and y == 2:
            self.ui.pushButton82.setText(num)
        if x == 8 and y == 3:
            self.ui.pushButton83.setText(num)
        if x == 8 and y == 4:
            self.ui.pushButton84.setText(num)
        if x == 8 and y == 5:
            self.ui.pushButton85.setText(num)
        if x == 8 and y == 6:
            self.ui.pushButton86.setText(num)
        if x == 8 and y == 7:
            self.ui.pushButton87.setText(num)
        if x == 8 and y == 8:
            self.ui.pushButton88.setText(num)

        self.removeButtonColor(x, y)

    def GoButtonEvent(self):
        question = [[0 for a in range(9)] for b in range(9)]
        if self.ui.pushButton00:
            question[0][0] = int(self.ui.pushButton00.text())
        if self.ui.pushButton01:
            question[0][1] = int(self.ui.pushButton01.text())
        if self.ui.pushButton02:
            question[0][2] = int(self.ui.pushButton02.text())
        if self.ui.pushButton03:
            question[0][3] = int(self.ui.pushButton03.text())
        if self.ui.pushButton04:
            question[0][4] = int(self.ui.pushButton04.text())
        if self.ui.pushButton05:
            question[0][5] = int(self.ui.pushButton05.text())
        if self.ui.pushButton06:
            question[0][6] = int(self.ui.pushButton06.text())
        if self.ui.pushButton07:
            question[0][7] = int(self.ui.pushButton07.text())
        if self.ui.pushButton08:
            question[0][8] = int(self.ui.pushButton08.text())
        if self.ui.pushButton10:
            question[1][0] = int(self.ui.pushButton10.text())
        if self.ui.pushButton11:
            question[1][1] = int(self.ui.pushButton11.text())
        if self.ui.pushButton12:
            question[1][2] = int(self.ui.pushButton12.text())
        if self.ui.pushButton13:
            question[1][3] = int(self.ui.pushButton13.text())
        if self.ui.pushButton14:
            question[1][4] = int(self.ui.pushButton14.text())
        if self.ui.pushButton15:
            question[1][5] = int(self.ui.pushButton15.text())
        if self.ui.pushButton16:
            question[1][6] = int(self.ui.pushButton16.text())
        if self.ui.pushButton17:
            question[1][7] = int(self.ui.pushButton17.text())
        if self.ui.pushButton18:
            question[1][8] = int(self.ui.pushButton18.text())
        if self.ui.pushButton20:
            question[2][0] = int(self.ui.pushButton20.text())
        if self.ui.pushButton21:
            question[2][1] = int(self.ui.pushButton21.text())
        if self.ui.pushButton22:
            question[2][2] = int(self.ui.pushButton22.text())
        if self.ui.pushButton23:
            question[2][3] = int(self.ui.pushButton23.text())
        if self.ui.pushButton24:
            question[2][4] = int(self.ui.pushButton24.text())
        if self.ui.pushButton25:
            question[2][5] = int(self.ui.pushButton25.text())
        if self.ui.pushButton26:
            question[2][6] = int(self.ui.pushButton26.text())
        if self.ui.pushButton27:
            question[2][7] = int(self.ui.pushButton27.text())
        if self.ui.pushButton28:
            question[2][8] = int(self.ui.pushButton28.text())
        if self.ui.pushButton30:
            question[3][0] = int(self.ui.pushButton30.text())
        if self.ui.pushButton31:
            question[3][1] = int(self.ui.pushButton31.text())
        if self.ui.pushButton32:
            question[3][2] = int(self.ui.pushButton32.text())
        if self.ui.pushButton33:
            question[3][3] = int(self.ui.pushButton33.text())
        if self.ui.pushButton34:
            question[3][4] = int(self.ui.pushButton34.text())
        if self.ui.pushButton35:
            question[3][5] = int(self.ui.pushButton35.text())
        if self.ui.pushButton36:
            question[3][6] = int(self.ui.pushButton36.text())
        if self.ui.pushButton37:
            question[3][7] = int(self.ui.pushButton37.text())
        if self.ui.pushButton38:
            question[3][8] = int(self.ui.pushButton38.text())
        if self.ui.pushButton40:
            question[4][0] = int(self.ui.pushButton40.text())
        if self.ui.pushButton41:
            question[4][1] = int(self.ui.pushButton41.text())
        if self.ui.pushButton42:
            question[4][2] = int(self.ui.pushButton42.text())
        if self.ui.pushButton43:
            question[4][3] = int(self.ui.pushButton43.text())
        if self.ui.pushButton44:
            question[4][4] = int(self.ui.pushButton44.text())
        if self.ui.pushButton45:
            question[4][5] = int(self.ui.pushButton45.text())
        if self.ui.pushButton46:
            question[4][6] = int(self.ui.pushButton46.text())
        if self.ui.pushButton47:
            question[4][7] = int(self.ui.pushButton47.text())
        if self.ui.pushButton48:
            question[4][8] = int(self.ui.pushButton48.text())
        if self.ui.pushButton50:
            question[5][0] = int(self.ui.pushButton50.text())
        if self.ui.pushButton51:
            question[5][1] = int(self.ui.pushButton51.text())
        if self.ui.pushButton52:
            question[5][2] = int(self.ui.pushButton52.text())
        if self.ui.pushButton53:
            question[5][3] = int(self.ui.pushButton53.text())
        if self.ui.pushButton54:
            question[5][4] = int(self.ui.pushButton54.text())
        if self.ui.pushButton55:
            question[5][5] = int(self.ui.pushButton55.text())
        if self.ui.pushButton56:
            question[5][6] = int(self.ui.pushButton56.text())
        if self.ui.pushButton57:
            question[5][7] = int(self.ui.pushButton57.text())
        if self.ui.pushButton58:
            question[5][8] = int(self.ui.pushButton58.text())
        if self.ui.pushButton60:
            question[6][0] = int(self.ui.pushButton60.text())
        if self.ui.pushButton61:
            question[6][1] = int(self.ui.pushButton61.text())
        if self.ui.pushButton62:
            question[6][2] = int(self.ui.pushButton62.text())
        if self.ui.pushButton63:
            question[6][3] = int(self.ui.pushButton63.text())
        if self.ui.pushButton64:
            question[6][4] = int(self.ui.pushButton64.text())
        if self.ui.pushButton65:
            question[6][5] = int(self.ui.pushButton65.text())
        if self.ui.pushButton66:
            question[6][6] = int(self.ui.pushButton66.text())
        if self.ui.pushButton67:
            question[6][7] = int(self.ui.pushButton67.text())
        if self.ui.pushButton68:
            question[6][8] = int(self.ui.pushButton68.text())
        if self.ui.pushButton70:
            question[7][0] = int(self.ui.pushButton70.text())
        if self.ui.pushButton71:
            question[7][1] = int(self.ui.pushButton71.text())
        if self.ui.pushButton72:
            question[7][2] = int(self.ui.pushButton72.text())
        if self.ui.pushButton73:
            question[7][3] = int(self.ui.pushButton73.text())
        if self.ui.pushButton74:
            question[7][4] = int(self.ui.pushButton74.text())
        if self.ui.pushButton75:
            question[7][5] = int(self.ui.pushButton75.text())
        if self.ui.pushButton76:
            question[7][6] = int(self.ui.pushButton76.text())
        if self.ui.pushButton77:
            question[7][7] = int(self.ui.pushButton77.text())
        if self.ui.pushButton78:
            question[7][8] = int(self.ui.pushButton78.text())
        if self.ui.pushButton80:
            question[8][0] = int(self.ui.pushButton80.text())
        if self.ui.pushButton81:
            question[8][1] = int(self.ui.pushButton81.text())
        if self.ui.pushButton82:
            question[8][2] = int(self.ui.pushButton82.text())
        if self.ui.pushButton83:
            question[8][3] = int(self.ui.pushButton83.text())
        if self.ui.pushButton84:
            question[8][4] = int(self.ui.pushButton84.text())
        if self.ui.pushButton85:
            question[8][5] = int(self.ui.pushButton85.text())
        if self.ui.pushButton86:
            question[8][6] = int(self.ui.pushButton86.text())
        if self.ui.pushButton87:
            question[8][7] = int(self.ui.pushButton87.text())
        if self.ui.pushButton88:
            question[8][8] = int(self.ui.pushButton88.text())

        sudoku = Sudoku(question)
        sudoku.run()
Esempio n. 22
0
class Window(QMainWindow):
    requestDoc = pyqtSignal(str, str)

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

        self.threading()
        self.btn_functionality()
        self.nav_functionality()

        self.MainWindow.show()

    def update_progressbar(self, percentage):
        self.ui.progressBar.setValue(percentage * 100)

    def threading(self):
        self._thread = QThread()
        self._threaded = Threaded(self.update_progressbar,
                                  result=self.display_page)

        self.requestDoc.connect(self._threaded.create_reports)

        self._thread.started.connect(self._threaded.start)
        self._threaded.moveToThread(self._thread)
        qApp.aboutToQuit.connect(self._thread.quit)
        self._thread.start()

    def btn_functionality(self):
        self.MainWindow = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

        self.ui.pushButton_Run.clicked.connect(self.get_comboBox_info)
        self.ui.pushButton_GoToFolder.clicked.connect(self.go_to_folder)

    def nav_functionality(self):
        self.ui.actionNew.triggered.connect(self.new_project)
        self.ui.actionOpen.triggered.connect(self.file_path)
        self.ui.actionRun.triggered.connect(self.get_comboBox_info)
        self.ui.actionQuit.triggered.connect(lambda: QApplication.quit())

        self.ui.actionFAQ.triggered.connect(self.project_FAQ)
        self.ui.actionAbout.triggered.connect(self.project_about)
        self.ui.actionHow_To_Run.triggered.connect(self.how_to_run)

    def new_project(self):
        self.ui.textEdit.setText('')
        self.ui.progressBar.setValue(0)
        self.ui.label_excel_name.setText('Excel file')
        self.file_path()

    def project_FAQ(self):
        faq_file = open('txt_files/FAQ.txt', 'r')
        faq = faq_file.read()
        self.ui.textEdit.setText(faq)

    def project_about(self):
        about_file = open('txt_files/About.txt', 'r')
        about = about_file.read()
        self.ui.textEdit.setText(about)

    def how_to_run(self):
        howtorun_file = open('txt_files/HowToRun.txt', 'r')
        howto = howtorun_file.read()
        self.ui.textEdit.setText(howto)

    def go_to_folder(self):
        folder = 'Reports/' + str(datetime.date.today()) + '/'
        if not os.path.exists(folder):
            os.makedirs(folder)

        dir_path = os.path.dirname(os.path.realpath(__file__))
        folder = folder.replace('/', '\\')
        subprocess.Popen(r"explorer /select," + dir_path + '\\' + folder)

    def file_path(self):
        path = QFileDialog.getOpenFileName(
            self, 'Open File', os.getenv('HOME'),
            'Excel(*.xlsx);;csv(*.csv);;All Files(*.*)')
        csv = False
        excel = False

        if path[0][-5:] == '.xlsx':
            excel = True
        elif path[0][-4:] == '.csv':
            csv = True

        if path[0] == " ":  # Needs a space... -.-
            return "Missing"
        if csv:
            df_new = pd.read_csv(path[0])
            writer = pd.ExcelWriter('temp.xlsx')
            df_new.to_excel(writer, 'Sheet1', index=False)
            writer.save()
            self.ui.label_excel_name.setText(path[0])
            return 'temp.xlsx'
        elif excel:
            self.ui.label_excel_name.setText(path[0])
            return path[0]

    @pyqtSlot()
    def get_comboBox_info(self):
        if self.ui.label_excel_name.text() == "Excel file":
            file_path = self.file_path()
            if file_path == 'Missing':
                # TODO - need a way to warn things
                #self.ui.textEdit.setText('WARNING: Must use a CSV or Excel file.')
                return
        else:
            # Makes sure to use the temp excel file if the user selected a CSV
            if self.ui.label_excel_name.text()[-4:] == '.csv':
                file_path = 'temp.xlsx'
            else:
                # Used if a file location has already been selected!
                file_path = self.ui.label_excel_name.text()

        self.template_select = self.ui.comboBox_report.currentText()

        self.requestDoc.emit(file_path, self.template_select)

        # Todo - disable buttons! *Turn them back on in "Display page function"
        self.ui.pushButton_Run.setEnabled(False)
        self.ui.pushButton_GoToFolder.setEnabled(False)

        self.ui.actionNew.setEnabled(False)
        self.ui.actionOpen.setEnabled(False)
        self.ui.actionRun.setEnabled(False)
        self.ui.actionGo_To_Folder.setEnabled(False)
        self.ui.actionQuit.setEnabled(False)

    @pyqtSlot(object)
    def display_page(self):
        # TODO - make sure all of these labels are correct
        self.ui.pushButton_Run.setEnabled(True)
        self.ui.pushButton_GoToFolder.setEnabled(True)

        self.ui.actionNew.setEnabled(True)
        self.ui.actionOpen.setEnabled(True)
        self.ui.actionRun.setEnabled(True)
        self.ui.actionGo_To_Folder.setEnabled(True)
        self.ui.actionQuit.setEnabled(True)
Esempio n. 23
0
    success(ui)

# 开始计算


def allin(ui):
    try:
        success(ui)
    except:
        error(ui)


# ———————————————————————————————————调用区——————————————————————————————

if __name__ == "__main__":
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    # 公称截面面积数据表
    data = pd.read_excel("./data/test.xlsx", index_col=0)
    # 进行实例化
    calculator = Calculator(data)

    ui.pushButtoncalculate.clicked.connect(partial(allin, ui))
    ui.pushButtonreturn.clicked.connect(partial(return0, ui))

    sys.exit(app.exec_())
Esempio n. 24
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        ######## create html file #######
        file = open("graph.html", "w")
        file.close()
        ############Preprocessing #################
        self.dataset1 = pd.read_csv('covid_19_clean_complete.csv')
        self.dataset2 = pd.read_csv('COVID19_line_list_data.csv')
        self.dataset1 = self.dataset1.iloc[:1000, :]
        # replacing Mainland china with just China
        self.dataset1['Country/Region'] = self.dataset1[
            'Country/Region'].replace('Mainland China', 'China')
        # Replace missing values with a number
        self.dataset1["Province/State"].fillna("Not Found", inplace=True)
        self.dataset2["gender"].fillna("Not Found", inplace=True)
        ########Connections ############
        list_buttons = [
            self.ui.comboBox, self.ui.comboBox, self.ui.comboBox,
            self.ui.comboBoxMap, self.ui.comboBox_lengthBar,
            self.ui.comboBox_SortBars, self.ui.comboBox_lengthBar
        ]
        list_fns = [
            self.visual_options, self.sorted_comboBox, self.map_control,
            self.map_control, self.comboBoxBar_control, self.sorted_comboBox,
            self.sorted_comboBox
        ]
        for i in range(len(list_buttons)):
            list_buttons[i].currentIndexChanged.connect(list_fns[i])

    def visual_options(self):
        self.curr_index = self.ui.comboBox.currentIndex()
        if (self.curr_index == 1):
            self.load_Bubble1()
            self.message("Please Wait................................")
        elif (self.curr_index == 2):
            self.map_control()
            self.message("Please Select from Map Color ComboBox only ")
        elif (self.curr_index == 3):
            self.comboBoxBar_control()
            self.message(
                "Please select from Bars Length and Bars sorting ComboBoxes only"
            )
        elif (self.curr_index == 4):
            self.Load_bubble2()
            self.message("Please Wait...................................")

    def load_Bubble1(self):
        fig = px.scatter(self.dataset1,
                         x="Deaths",
                         y="Recovered",
                         animation_frame="Date",
                         animation_group="Province/State",
                         size="Confirmed",
                         color="Country/Region",
                         hover_name="Province/State",
                         log_x=True,
                         log_y=True,
                         size_max=500,
                         range_x=[0.1, 1000000000],
                         range_y=[0.1, 1000000000000000000000000000000000],
                         title='Recovered vs Death (Log10 Scale )')

        self.html(fig)

    def Load_bubble2(self):
        fig = px.scatter(self.dataset2,
                         x="age",
                         y="case_in_country",
                         animation_frame="reporting date",
                         animation_group="gender",
                         size="case_in_country",
                         color="country",
                         hover_name="gender",
                         size_max=300,
                         log_x=True,
                         log_y=True,
                         range_x=[0.1, 150],
                         range_y=[0.1, 10000000],
                         title=' Cases vs Ages(Log10 Scale )')

        self.html(fig)

    def map_control(self):
        self.curr_main = self.ui.comboBox.currentIndex()
        self.curr_index = self.ui.comboBoxMap.currentIndex()
        self.Load_map(self.curr_main, self.curr_index)

    def Load_map(self, curr_main, curr_index):
        #self.curr_index = self.ui.comboBoxMap.currentIndex()
        if (curr_main == 2):
            if (curr_index == 1):

                fig = px.choropleth(
                    self.dataset1,
                    locations="Country/Region",
                    locationmode="country names",
                    color="Confirmed",
                    hover_name="Country/Region",
                    animation_frame="Date",
                    animation_group="Confirmed",
                    color_continuous_scale="Viridis",
                    range_color=(0, 8000),
                    title=' Cases Of COVID19 all over the World')
                self.html(fig)

            elif (curr_index == 2):
                fig = px.choropleth(
                    self.dataset1,
                    locations="Country/Region",
                    locationmode="country names",
                    color="Deaths",
                    hover_name="Country/Region",
                    animation_frame="Date",
                    animation_group="Deaths",
                    range_color=(0, 8000),
                    title=' Deaths Of COVID19 all over the World')
                self.html(fig)

    def comboBoxBar_control(self):
        self.curr_index1 = self.ui.comboBox_lengthBar.currentIndex()

        if (self.curr_index1 == 1):
            self.item("Number of Cases in each Country.")

        elif (self.curr_index1 == 2):
            self.item("Number of Deaths in each Country.")

        elif (self.curr_index1 == 3):
            self.item("Both # of Cases and # of Deaths in each Country.")

    def item(self, text):
        self.ui.comboBox_SortBars.clear()
        items = ["Bars sorted by :", text]
        for i in items:
            self.ui.comboBox_SortBars.addItem(i)

    def sorted_comboBox(self):
        curr_index = self.ui.comboBox.currentIndex()
        curr_index1 = self.ui.comboBox_lengthBar.currentIndex()
        curr_index2 = self.ui.comboBox_SortBars.currentIndex()
        self.Load_bar(curr_index, curr_index1, curr_index2)

    def Load_bar(self, curr_index, curr_index1, curr_index2):
        if (curr_index == 3):
            if (curr_index1 == 1 and curr_index2 == 1):
                self.plot(
                    self.dataset1, "Confirmed",
                    "Sorting of Countries By Number of Cases of COVID19")

            elif (curr_index1 == 2 and curr_index2 == 1):
                self.plot(self.dataset1, "Deaths",
                          "Sorting of Countries By Number of Deaths")

            elif (curr_index1 == 3 and curr_index2 == 1):
                Total = self.dataset1["Confirmed"] + self.dataset1["Deaths"]
                self.dataset1["DeathsPLUSConfirmed"] = Total
                self.plot(
                    self.dataset1, "DeathsPLUSConfirmed",
                    "Sorting of Countries By Number of Cases and Number of Deaths of COVID19"
                )

    def plot(self, dataset, y, title):
        fig = px.bar(dataset,
                     x="Country/Region",
                     y=y,
                     animation_frame="Date",
                     color="Country/Region",
                     width=1400,
                     height=720,
                     template='gridon',
                     range_y=[0, 50000],
                     title=title)

        fig.update_layout(xaxis={'categoryorder': 'total descending'})
        self.html(fig)

    def html(self, fig):
        py.io.write_html(fig, "graph.html")
        path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "graph.html"))
        self.ui.widget.load(QUrl.fromLocalFile(path))

    def message(self, value):
        msg = QMessageBox()
        msg.setWindowTitle("Information")
        msg.setText(value)
        msg.setIcon(QMessageBox.Information)
        x = msg.exec_()
class myWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(myWindow, self).__init__()
        self.myCommand = " "
        self.setWindowIcon(QtGui.QIcon('two.ico'))
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.firstFit_bar.triggered.connect(self.firstFitbar_recognize)  # firstFit模式触发
        self.ui.bestFit_bar.triggered.connect(self.bestFitbar_recognize)  # bestFit模式触发
        self.ui.text_btn.clicked.connect(self.text_changed)  # 文本框输入确认按钮连接文本处理函数
        self.ui.textbox.returnPressed.connect(self.text_changed)  # 文本框输入响应enter键
        self.ui.clear_btn.clicked.connect(self.clear)  # Reset按钮连接重置内存空间函数

        for i in range(0, 64):
            self.ui.btnGroup[i].clicked.connect(
                partial(self.addNode, 10*(i+1)))
        self.isbestFit = False  # 标志是否选择bestFit识别
        self.workNumber = 0  # 作业个数
        self.nodeList = []  # 结点链表
        # 初始化,将640k视为一个空结点
        self.nodeList.insert(0, {'number': -1,  # 非作业结点
                                 'start': 0,  # 开始为0
                                 'length': 640,  # 长度为640
                                 'isnull': True})  # 空闲
        # 加入一个非作业btn
        self.nodeList[0]['btn'] = self.addButton(self.nodeList[0])

    # firstFit从未选状态转变为已选状态时会触发firstFitbar_recognize函数
    def firstFitbar_recognize(self):
        self.clear()  # 重置内存空间
        self.ui.firstFit_bar.setChecked(True)
        self.ui.bestFit_bar.setChecked(False)
        self.ui.firstFit_action.setText(" √  First fit  ")
        font = QtGui.QFont()
        font.setFamily("Calibri")
        font.setPointSize(10)
        self.ui.firstFit_action.setFont(font)
        self.ui.firstFit_action.setStyleSheet(
            "QLabel { color: rgb(255,255,255);  /*字体颜色*/ \
                background-color:rgb(51,105,30);\
                }"
            "QLabel:hover{  background-color:rgb(51,105,30);/*选中的样式*/ \
                }"
        )
        self.ui.bestFit_action.setText("     Best fit  ")
        font = QtGui.QFont()
        font.setFamily("Calibri")
        font.setPointSize(10)
        self.ui.bestFit_action.setFont(font)
        self.ui.bestFit_action.setStyleSheet(
            "QLabel { color: rgb(225,225,225);  /*字体颜色*/ \
                background-color:rgb(124,179,66);\
                }"
            "QLabel:hover{ background-color:rgb(51,105,30);/*选中的样式*/ \
                            }"
        )
        self.isbestFit = False

    # bestFit从未选状态转变为已选状态时会触发bestFitbar_recognize函数
    def bestFitbar_recognize(self):
        self.clear()  # 重置内存空间
        self.ui.bestFit_bar.setChecked(True)
        self.ui.firstFit_bar.setChecked(False)
        self.ui.firstFit_action.setText("     First fit  ")
        font = QtGui.QFont()
        font.setFamily("Calibri")
        font.setPointSize(10)
        self.ui.firstFit_action.setFont(font)
        self.ui.firstFit_action.setStyleSheet(
            "QLabel { color: rgb(225,225,225);  /*字体颜色*/ \
                background-color:rgb(124,179,66);\
                }"
            "QLabel:hover{ background-color:rgb(51,105,30);/*选中的样式*/ \
                            }"
        )
        self.ui.bestFit_action.setText(" √  Best fit  ")
        font = QtGui.QFont()
        font.setFamily("Calibri")
        font.setPointSize(10)
        self.ui.bestFit_action.setFont(font)
        self.ui.bestFit_action.setStyleSheet(
            "QLabel { color: rgb(255,255,255);  /*字体颜色*/ \
                background-color:rgb(51,105,30);\
                }"
            "QLabel:hover{  background-color:rgb(51,105,30);/*选中的样式*/ \
                }"
        )
        self.isbestFit = True

    # 重置内存空间函数
    def clear(self):
        self.workNumber = 0  # 作业个数置0
        self.nodeList.insert(0, {'number': -1,  # 非作业结点
                                 'start': 0,  # 开始0
                                 'length': 640,  # 长度640
                                 'isnull': True})  # 空闲
        # 加入一个非作业btn
        self.nodeList[0]['btn'] = self.addButton(self.nodeList[0])
        size = len(self.nodeList)
        for i in range(1, size):
            self.nodeList.pop()

    # 寻找首次适应算法添加结点的位置
    def findFirstNode(self, length):
        self.targetNumber = -1
        for i in range(0, len(self.nodeList)):
            # 如果结点i为空闲
            if self.nodeList[i]['isnull'] and self.nodeList[i]['length'] >= length:
                self.targetNumber = i
                return self.targetNumber
        return -1

    # 寻找最佳适应算法添加结点的位置
    def findBestNode(self, length):
        self.min = 650
        self.targetNumber = -1
        for i in range(0, len(self.nodeList)):
            # 如果结点i为空闲
            if self.nodeList[i]['isnull'] and (self.min > self.nodeList[i]['length'] >= length):
                self.min = self.nodeList[i]['length']
                self.targetNumber = i
        return self.targetNumber

    # 添加结点
    def addNode(self, length):
        if self.isbestFit:
            i = self.findBestNode(length)
        else:
            i = self.findFirstNode(length)
        if i >= 0:
            self.workNumber += 1  # 作业数量+1
            if self.nodeList[i]['length'] > length:
                # 在该结点后插入新的作业结点
                self.nodeList.insert(i+1, {'number': self.workNumber,  # 作业workNumber
                                           'start': self.nodeList[i]['start'],  # 开始为结点i的开始
                                           'length': length,  # 长度
                                           'isnull': False})  # 不空闲
                # 加入一个作业btn
                self.nodeList[i+1]['btn'] = self.addButton(self.nodeList[i+1])
                self.nodeList[i+1]['btn'].clicked.connect(
                    partial(self.deleteNode, self.nodeList[i+1]['number']))
                # 将剩下的部分置为空白结点
                self.nodeList.insert(i+2, {'number': -1,  # 非作业结点
                                           'start': self.nodeList[i+1]['start']+length,  # 开始为i+1的开始+length
                                           'length': self.nodeList[i]['length']-length,  # 长度为结点i的长度-length
                                           'isnull': True})  # 空闲
                # 加入一个非作业btn
                self.nodeList[i+2]['btn'] = self.addButton(self.nodeList[i+2])
                # 删除结点i
                del self.nodeList[i]
            # 空闲结点i的长度等于所需长度
            elif self.nodeList[i]['length'] == length:
                # 在该结点后插入新的作业结点
                self.nodeList.insert(i + 1, {'number': self.workNumber,  # 作业workNumber
                                             'start': self.nodeList[i]['start'],  # 开始为结点i的开始
                                             'length': length,  # 长度
                                             'isnull': False})  # 不空闲
                # 插入一个作业btn
                self.nodeList[i + 1]['btn'] = self.addButton(self.nodeList[i+1])
                self.nodeList[i + 1]['btn'].clicked.connect(
                    partial(self.deleteNode, self.nodeList[i + 1]['number']))
                # 删除结点i
                del self.nodeList[i]

    # 删除作业结点
    def deleteNode(self, workNumber):
        self.current = -1
        # 寻找目标删除结点
        for i in range(0, len(self.nodeList)):
            if self.nodeList[i]['number'] == workNumber:
                self.current = i
                break
        # 找到目标删除结点
        if self.current != -1:
            # 前后都无空闲结点
            if (self.current == 0 or bool(1-self.nodeList[self.current - 1]['isnull'])) \
                    and (self.current == len(self.nodeList) - 1 or bool(1-self.nodeList[self.current + 1]['isnull'])):
                self.nodeList.insert(self.current + 1, {'number': -1,  # 非作业结点
                                                        # 开始为self.current结点的开始
                                                        'start': self.nodeList[self.current]['start'],
                                                        # 长度为结点self.current长度
                                                        'length': self.nodeList[self.current]['length'],
                                                        'isnull': True})  # 空闲
                # 加入一个非作业btn
                self.nodeList[self.current + 1]['btn'] = self.addButton(self.nodeList[self.current+1])
                del self.nodeList[self.current]
            else:
                # 结点非头结点且其前一个结点是空闲结点
                if self.current-1 >= 0 and self.nodeList[self.current-1]['isnull']:
                    # 将两部分合为一个空白结点
                    self.nodeList.insert(self.current + 1, {'number': -1,  # 非作业结点
                                                             # 开始为self.current-1结点的开始
                                                             'start': self.nodeList[self.current - 1]['start'],
                                                             # 长度为结点self.current-1的长度+结点self.current的长度
                                                             'length': self.nodeList[self.current-1]['length']
                                                                       + self.nodeList[self.current]['length'],
                                                             'isnull': True})  # 空闲
                    # 加入一个非作业btn
                    self.nodeList[self.current + 1]['btn'] = self.addButton(self.nodeList[self.current+1])
                    # 删除原来两结点
                    del self.nodeList[self.current-1]
                    # 删除current
                    del self.nodeList[self.current-1]
                    self.current -= 1
                # 结点非尾结点且其后一个结点为空白结点
                if self.current < len(self.nodeList)-1 and self.nodeList[self.current+1]['isnull']:
                    # 将两部分合为一个空白结点
                    self.nodeList.insert(self.current + 2, {'number': -1,  # 非作业结点
                                                            # 开始为self.current结点的开始
                                                           'start': self.nodeList[self.current]['start'],
                                                           # 长度为结点self.current的长度+结点self.current+1的长度
                                                           'length': self.nodeList[self.current]['length']
                                                                     + self.nodeList[self.current + 1]['length'],
                                                           'isnull': True})  # 空闲
                    # 加入一个非作业btn
                    self.nodeList[self.current + 2]['btn'] = self.addButton(self.nodeList[self.current+2])
                    # 删除原来两结点
                    del self.nodeList[self.current]
                    # 删除current+1
                    del self.nodeList[self.current]

    # 加入作业
    def addButton(self, node=[]):
        if node['isnull']:  # 空闲结点按钮
            btn = QtWidgets.QPushButton(str(node['length'])+'k', self)
            btn.setFont(QtGui.QFont('Microsoft YaHei', node['length']/42 + 5))
            btn.setGeometry(380, 30+node['start'], 100, node['length'])
            btn.setStyleSheet(
                "QPushButton{color:rgb(150,150,150)}"
                "QPushButton{background-color:rgb(240,240,240)}"
                "QPushButton{border: 1.5px solid rgb(66,66,66);}"
            )
            btn.setVisible(True)
        else:       # 作业结点按钮
            btn = QtWidgets.QPushButton('P'+str(node['number'])+':\n'+str(node['length'])+'k', self)
            btn.setFont(QtGui.QFont('Microsoft YaHei', node['length'] / 42 + 5))
            btn.setGeometry(380, 30 + node['start'], 100, node['length'])
            btn.setStyleSheet(
                "QPushButton{color:rgb(1,0,0)}"
                "QPushButton{background-color:rgb(124,179,66)}"
                "QPushButton:hover{background-color:rgb(210,210,210)}"
                "QPushButton:pressed{background-color:rgb(200,200,200)}"
                "QPushButton{border: 1.5px solid rgb(66,66,66);}"
            )
            btn.setVisible(True)
        return btn

    #文本处理函数
    def text_changed(self):
        if self.ui.textbox.text() == '':
            self.content = 0
        else:
            self.content = 0
            if ('.' not in self.ui.textbox.text()):
                self.content = int(self.ui.textbox.text())
                #self.content = int("".join(list(filter(str.isdigit, self.ui.textbox.text()))))
            else:
                self.content = float(self.ui.textbox.text())
        print(self.content)
        self.ui.textbox.setText('')
        if self.content <= 640:
            self.addNode(self.content)
Esempio n. 26
0
class FileSharerGUI(QMainWindow, Ui_MainWindow):
    
    def __init__(self, initialPeer, ttl=2, maxKnownPeers=5, initialPeerPort=1234, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        initialPeerHostName, initialPeerPort = initialPeer.split(':')
        self.peerHandler = P2PMessageHandler(maxKnownPeers, initialPeerPort, initialPeerHostName)
        t = threading.Thread(target=self.peerHandler.listenForConnections, args=[])
        t.start()
        self.peerHandler.buildPeerList(initialPeerHostName, int(initialPeerPort), ttl)
        self.updatePeers()
        QtCore.QObject.connect(self.ui.btn_download, QtCore.SIGNAL('clicked()'), self.onDownloadClicked)
        QtCore.QObject.connect(self.ui.btn_addFile, QtCore.SIGNAL('clicked()'), self.onAddFileClicked)
        QtCore.QObject.connect(self.ui.btn_Search, QtCore.SIGNAL('clicked()'), self.onSearchClicked)
        QtCore.QObject.connect(self.ui.btn_refresh, QtCore.SIGNAL('clicked()'), self.onRefreshClicked)
    
    def updatePeers(self):
        for peerId in self.peerHandler.getPeerIds():
            self.ui.listView_files.addItem(peerId)
    
    def updateFilesList(self):
        for file in self.peerHandler.files:
            fileHost = self.peerHandler.files[file]
            if not fileHost:
                fileHost = ('localhost')
            self.listView_files.addItem("%s:%s:1234" % (file, fileHost))
            self.ui.listView_files.repaint()
    
    def onDownloadClicked(self):
        selections = self.ui.listView_files.selectedItems()
        if selections:
            for s in selections:
                if(len(s.text().split(':')) > 2):
                    fileName, hostName, port = s.text().split(':')
                    response = self.peerHandler.connectAndSend(hostName, port, GETFILE, fileName)
                    if len(response) and response[0][0] == REPLY:
                        fileDescriptor = open(fileName, 'w')
                        fileDescriptor.write(response[0][1])
                        fileDescriptor.close()
                        self.peerHandler.files[fileName] = None
        else:
            self.popupErrorMessage('Please select a file before proceeding.')            
            
    def onAddFileClicked(self):
        fileName = self.ui.tb_Search.text()
        if fileName:
            fileName = fileName.lstrip().rstrip()
            self.peerHandler.files[fileName] = None
            print('File added for sharing')
        else:
            self.popupErrorMessage('Please enter a filename before adding.')
        self.ui.tb_addFile.setText(None)
            
    def onSearchClicked(self):
        searchText = self.ui.tb_Search.text()
        if searchText:
            for peerId in self.peerHandler.getPeerIds():
                self.peerHandler.sendMessageToPeer(peerId, SEARCH, '%s %s 4' % (self.peerHandler.hostId, searchText))
        else:
            self.popupErrorMessage('Please enter some search text.')
    
    def popupErrorMessage(self, errorString):
        messageBox = QMessageBox()
        messageBox.setWindowTitle('Error!!!')
        messageBox.setText(errorString)
        messageBox.exec_()
    
    def onRefreshClicked(self):
        self.updatePeers();
        self.updateFilesList()