예제 #1
0
 def __init__(self):
     QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.btnBack.hide()
     self.ui.areaModule.hide()
     self.addModuleButtons()
예제 #2
0
파일: main.py 프로젝트: brmlab/edubrm
class Main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btnBack.hide()
        self.ui.areaModule.hide()
        self.addModuleButtons()

    @pyqtSlot()
    def on_btnExit_clicked(self):
        self.close()

    @pyqtSlot()
    def on_btnBack_clicked(self):
        self.mod.stop()
        self.ui.lblTitle.setText('EduBRM')
        self.ui.areaChoose.show()
        self.ui.areaModule.hide()
        self.ui.btnExit.show()
        self.ui.btnBack.hide()

    @pyqtSlot()
    def on_btnAbout_clicked(self):
        box = QMessageBox(QMessageBox.NoIcon, "About EduBRM", "EduBRM by Hackerspace brmlab\n\nhttp://brmlab.cz/\n\nSee README for more information.", QMessageBox.Ok, self)
        box.setIconPixmap(QPixmap( ":/icons/icon.png"))
        box.exec_()

    def addModuleButtons(self):
        import modules
        for mod in modules.list():
            c = self.ui.gridLayout.count()
            btn = ModuleButton(mod, self)
            self.ui.gridLayout.addWidget(btn, c / 2, c % 2)
예제 #3
0
    def __init__(self, cfg):
        QtGui.QMainWindow.__init__(self)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.cfg = cfg
        self.show()

        # Initialize sound output
        pygame.mixer.init()

        # Message Window
        self.messageWindow = MessageWindow(self)
        
        # Windows
        self.codeWindow = CodeWindow(self.messageWindow, self.redeemCode, self)
        self.tosWindow = TosWindow(self)
        self.screensaverWindow = ScreensaverWindow(self)
        self.adminWindow = AdminWindow(self)

        # RFID reading
        if not cfg.client.use_rfid_dummy:
            self.rfid = RFIDWorker(cfg.rfid.key)
        else:
            self.rfid = RFIDDummyWorker(cfg.rfid.key)
        self.connect(self.rfid, SIGNAL("cardRead(PyQt_PyObject)"), self.rfidUpdate)
        self.rfid.start()
 
        # Business logic stuff
        self.client = CoffeeClient()
        self.card = self.rfid.readCard()
        self.wallet = None
        self.user = None
        self.lastcard = None
        self.adminButton = None
        self.buttons = {}
        self.items = {}

        # Timer for screensaver timeouts
        self.screensaverTimer = QtCore.QTimer()
        QtCore.QObject.connect(self.screensaverTimer, QtCore.SIGNAL("timeout()"), self.screensaverTimeout)
        self.screensaverTimer.setInterval(cfg.client.screensaver_timeout * 1000)
        self.screensaverTimer.start()

         # Timer for interaction timeouts
        self.interactionTimer = QtCore.QTimer()
        QtCore.QObject.connect(self.interactionTimer, QtCore.SIGNAL("timeout()"), self.interactionTimeout)
        self.interactionTimer.setInterval(cfg.client.interaction_timeout * 1000)
        self.interactionTimer.start()
 
        # Timer for item updates
        self.itemsTimer = QtCore.QTimer()
        QtCore.QObject.connect(self.itemsTimer, QtCore.SIGNAL("timeout()"), self.rebuildItemTimeout)
        self.rebuildItems()
        self.itemsTimer.setInterval(cfg.client.item_refresh)
        self.itemsTimer.start()
        
        # Click event for message label
        self.ui.message.mousePressEvent = self.onMessageLabelClicked
예제 #4
0
 def __init__(self, pages, workingdir):
     QtGui.QMainWindow.__init__(self)
     self.inputpages = pages
     self.workingdir = workingdir
     self.pages = []
     self.data = []
     self.currentpage = 0
     self.getPages()
     self.finalwidth = 1448
     self.finalxoffset = 164
     self.rulers = []
     
     self.ui=Ui_MainWindow()
     self.ui.setupUi(self)
     self.frame = self.ui.webView.page().mainFrame()
     self.ui.webView.connect(self.ui.webView, QtCore.SIGNAL('loadFinished(bool)'), self.loadFinished)
     self.ui.webView.connect(self.ui.webView.page().mainFrame(), QtCore.SIGNAL('javaScriptWindowObjectCleared()'), self.addmodeltojs)
     self.connect(self.ui.next, QtCore.SIGNAL('clicked()'), self.nextPage)
     self.connect(self.ui.previous, QtCore.SIGNAL('clicked()'), self.previousPage)
     self.connect(self.ui.chopPage, QtCore.SIGNAL('clicked()'), self.page2jpg)
     self.connect(self.ui.addRuler, QtCore.SIGNAL('clicked()'), self.addruler)
     self.ui.webView.setUrl(QtCore.QUrl("/home/nic/git/tablemaker/magic.html"))
     self.currentpage = 0
     self.ui.webView.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
     self.webInspector = QWebInspector(self)
     self.webInspector.setPage(self.ui.webView.page())
     self.webInspector.setVisible(True)
     self.ui.verticalLayout_2.addWidget(self.webInspector)
    def __init__(self, *args, **kwargs): #, source, destination, fps, size, gui, serial

        if 'logger' in kwargs:
            self.logger = kwargs['logger']
        if 'app' in kwargs:
            self.app = kwargs['app']

        QtGui.QMainWindow.__init__(self)    
#        mw = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.resize(800,800)
        self.show()
        
        self.vb = pg.ViewBox()
        self.ui.graphicsView.setCentralItem(self.vb)
        self.vb.setAspectLocked()
        self.img = pg.ImageItem()
        self.vb.addItem(self.img)
        self.vb.setRange(QtCore.QRectF(0, 0, 512, 512))
#        self.img.setPxMode(True)
        
        self.logger.info('%s starting spotter', self)
        self.spotter = Spotter(*args, **kwargs)    
        self.spotter.gui_grabber.displayTarget = self.img
        self.logger.info('%s spotter instantiated', self)

        self.lastTime = ptime.time()
        self.fps = None

        # main window refresh timer
#        self.timer = QtCore.QTimer()
#        self.timer.timeout.connect(self.update)
#        self.timer.start(0)
        self.update()
예제 #6
0
파일: main.py 프로젝트: brmlab/edubrm
 def __init__(self):
     QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.btnBack.hide()
     self.ui.areaModule.hide()
     self.addModuleButtons()
예제 #7
0
 def __init__(self):
     """
         Method to initialize all instance variables and connect signals-slots.
     """
     super().__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.show_reminder = ShowReminder()
     self.list_of_reminders = [
     ]  #A list to store all components of the reminders in the form of a tuple.
     self.ui.list_widget.addItem('Reminder Titles:')
     self.ui.list_widget.setSelectionMode(
         qtw.QAbstractItemView.SingleSelection)
     self.ui.add_reminder_button.clicked.connect(self.add_reminder)
     self.ui.remind_me_button.clicked.connect(self.remind_me)
     self.ui.clearAll_button.clicked.connect(self.clear_all)
     self.ui.delete_button.clicked.connect(self.delete_reminders)
예제 #8
0
    def __init__(self):

        #Qt main window init
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.resetToggle.clicked.connect(self.resetSession)
        self.ui.settingsButton.clicked.connect(self.get_dossier_location)
        self.dossier_folder = None

        self.path = self.module_path()

        self.tankdata = self.get_json_data(os.path.join(self.path, 'data', 'tanks.json'))
        self.mapdata = self.get_json_data(os.path.join(self.path, 'data', 'maps.json'))
        stuctures = [10, 17, 18, 20, 22, 24, 26, 27, 28, 29, 65, 69]
        self.structdata = dict()
        self.tanks = []

        for sid in stuctures:
            structfile = os.path.join(self.path, 'data', 'structures_'+str(sid)+'.json')
            self.structdata[sid] = self.get_json_data(structfile)


        if os.path.exists('settings.cfg'):
            self.settings = self.get_json_data(os.path.join(self.path, 'settings.cfg'))
            if os.path.exists(self.settings['dossier_path']):
                self.dossier_folder = self.settings['dossier_path']
        else:
            dpath = os.path.join(os.environ['APPDATA'], "Wargaming.net", "WorldOfTanks", "dossier_cache")
            if not os.path.exists(dpath):
                dpath = None
            self.settings = {
                'update_interval': 10,
                'dossier_path': dpath
            }
        self.running=True
        
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.mainloop)
        self.timer.start(self.settings['update_interval']*1000)

        self.last = 0
        self.results = []
        self.sessionStart = []
 def __init__(self):
     """
         Method to initialize all instance variables and connect signals-slots.
     """
     super().__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.dest_path = ''
     self.link = ''
     self.yt = None
     self.videos = []
     self.ui.list_widget.addItem('Titles: ')
     self.ui.list_widget.setSelectionMode(
         qtw.QAbstractItemView.SingleSelection)
     self.ui.destination_button.clicked.connect(
         self.select_destination_folder)
     self.ui.add_list_button.clicked.connect(self.add_link_to_list)
     self.ui.download_button.clicked.connect(self.download_videos)
     self.ui.clear_list_button.clicked.connect(self.clear_list)
     self.ui.delete_button.clicked.connect(self.delete_item)
예제 #10
0
파일: reEpub.py 프로젝트: eknowles/reEpub
 def __init__(self):
     QtGui.QMainWindow.__init__(self)
     self.ui=Ui_MainWindow()
     self.ui.setupUi(self)
     self.setAcceptDrops(True)
     self.targetproceses = 0
     self.currentprocess = 0
     
     #filenames to ignore
     self.ignorelist = ["Thumbs.db",
                        ".dsstore",
                        "mimetype"]
예제 #11
0
class Main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btnBack.hide()
        self.ui.areaModule.hide()
        self.addModuleButtons()

    @pyqtSlot()
    def on_btnExit_clicked(self):
        self.close()

    @pyqtSlot()
    def on_btnBack_clicked(self):
        self.mod.stop()
        self.ui.lblTitle.setText('EduBRM')
        self.ui.areaChoose.show()
        self.ui.areaModule.hide()
        self.ui.btnExit.show()
        self.ui.btnBack.hide()

    @pyqtSlot()
    def on_btnAbout_clicked(self):
        box = QMessageBox(
            QMessageBox.NoIcon, "About EduBRM",
            "EduBRM by Hackerspace brmlab\n\nhttp://brmlab.cz/\n\nSee README for more information.",
            QMessageBox.Ok, self)
        box.setIconPixmap(QPixmap(":/icons/icon.png"))
        box.exec_()

    def addModuleButtons(self):
        import modules
        for mod in modules.list():
            c = self.ui.gridLayout.count()
            btn = ModuleButton(mod, self)
            self.ui.gridLayout.addWidget(btn, c / 2, c % 2)
예제 #12
0
파일: reEpub.py 프로젝트: eknowles/reEpub
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.setAcceptDrops(True)
        self.targetproceses = 0
        self.currentprocess = 0
        
        #filenames to ignore
        self.ignorelist = ["Thumbs.db",
                           ".dsstore",
                           "mimetype"]
    
    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()
    
    def test_for_ignore(self, filename):
        for ignorefile in self.ignorelist:
            #print filename
            if ignorefile.lower() == filename.lower():
                return False
        return True
    
    def get_file_count(self, directory):
        counter = 0
        for subdir, dirs, files in os.walk(directory, False):
            for name in files:
                counter = counter +1
        return counter
    
    def get_process_count(self, directory):
        files = self.get_file_count(directory)
        processes = files
        if os.path.exists(directory+".epub"):
            processes = processes + 1
        if os.path.exists(os.path.join(directory, "mimetype")):
            processes = processes + 1
        return processes+1
    
    def update_progress (self, parseText):
        if self.currentprocess < self.targetproceses:
            self.currentprocess = self.currentprocess + 1
        perc = (float(self.currentprocess)/float(self.targetproceses))*100
        self.ui.progressBarRunning.setProperty("value", perc)
        self.ui.labelProgress.setText(parseText)
        #print parseText
    
    def reassemble (self, directory, rootdir):
        self.ui.labelProgress.setText(os.path.basename(directory)+": checking...")
        self.targetproceses = self.get_process_count (os.path.join(rootdir,directory))
        self.currentprocess = 0
        if os.path.exists(os.path.join(rootdir,(directory+".epub"))):
            if self.ui.radioButtonArchive.isChecked():
                self.update_progress(os.path.basename(directory)+": archiving original...")
                os.rename(os.path.join(rootdir,(directory+".epub")), os.path.join(rootdir,(directory+"-"+str(int(time.time()))[5:]+".epub")))
                self.update_progress(os.path.basename(directory)+": creating new EPUB file")
            else:
                self.targetproceses = self.targetproceses - 1
                self.update_progress(os.path.basename(directory)+": overwriting EPUB file")
        else:
            self.targetproceses = self.targetproceses - 1
            self.update_progress(os.path.basename(directory)+": overwriting EPUB file")
        new_epub = zipfile.ZipFile(os.path.join(rootdir,(directory+".epub")),"w")
        
        self.update_progress(os.path.basename(directory)+": adding mimetype")
        new_epub.writestr("mimetype", "application/epub+zip", zipfile.ZIP_STORED)
        for subdir, dirs, files in os.walk(os.path.join(rootdir,directory), False):
            for name in files:
                target = os.path.join(subdir, name)
                new_target = target[len(os.path.join(directory,"")):]
                if self.test_for_ignore(name):
                    #print "writing "+new_target+" to "+directory+".epub"
                    self.update_progress(os.path.basename(directory)+": adding "+new_target +" to EPUB")
                    new_epub.write(target,new_target, zipfile.ZIP_DEFLATED)
        
        self.update_progress(os.path.basename(directory)+": Done")
        new_epub.close()
        
    def dropEvent(self, e):
        for indrag in e.mimeData().urls():
            target = str(indrag.toLocalFile())
            if target[len(target)-1] == "/":
                target = target[:len(target)-1]
            rootdir = os.path.dirname(os.path.realpath(target))
            #print indrag
            #print target
            #print rootdir
            if os.path.exists(target):
                #print "bungholio"
                self.reassemble(target, rootdir)
예제 #13
0
class Main (QtGui.QMainWindow):

    def __init__(self):

        #Qt main window init
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.resetToggle.clicked.connect(self.resetSession)
        self.ui.settingsButton.clicked.connect(self.get_dossier_location)
        self.dossier_folder = None

        self.path = self.module_path()

        self.tankdata = self.get_json_data(os.path.join(self.path, 'data', 'tanks.json'))
        self.mapdata = self.get_json_data(os.path.join(self.path, 'data', 'maps.json'))
        stuctures = [10, 17, 18, 20, 22, 24, 26, 27, 28, 29, 65, 69]
        self.structdata = dict()
        self.tanks = []

        for sid in stuctures:
            structfile = os.path.join(self.path, 'data', 'structures_'+str(sid)+'.json')
            self.structdata[sid] = self.get_json_data(structfile)


        if os.path.exists('settings.cfg'):
            self.settings = self.get_json_data(os.path.join(self.path, 'settings.cfg'))
            if os.path.exists(self.settings['dossier_path']):
                self.dossier_folder = self.settings['dossier_path']
        else:
            dpath = os.path.join(os.environ['APPDATA'], "Wargaming.net", "WorldOfTanks", "dossier_cache")
            if not os.path.exists(dpath):
                dpath = None
            self.settings = {
                'update_interval': 10,
                'dossier_path': dpath
            }
        self.running=True
        
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.mainloop)
        self.timer.start(self.settings['update_interval']*1000)

        self.last = 0
        self.results = []
        self.sessionStart = []

    def we_are_frozen(self):
        """Returns whether we are frozen via py2exe.
        This will affect how we find out where we are located."""

        return hasattr(sys, "frozen")


    def module_path(self):
        """ This will get us the program's directory,
        even if we are frozen using py2exe"""

        if self.we_are_frozen():
            return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))

        return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))

    def savesettings(self):
        settings = json.dumps(self.settings)
        fh = open(os.path.join(self.path, 'settings.cfg'), 'w')
        fh.write(settings)
        fh.close()

    def get_dossier_location(self):
        self.dossier_folder = str(QtGui.QFileDialog.getExistingDirectory(self, 'Dossier Location', self.settings['dossier_path']))
        self.settings['dossier_path'] = self.dossier_folder
        self.savesettings()
        self.mainloop()

    def get_latest (self):
        latest = ['',0]
        for subdir, dirs, files in os.walk(self.dossier_folder, False):
            for name in files:
                target = os.path.join(subdir, name)
                mod = os.path.getmtime(target)
                if mod > latest[1]:
                    latest[0] = target
                    latest[1] = mod

        return latest

    def resetSession(self):
        self.last = 0
        self.sessionStart = self.results
        self.drawstats()


    def drawstats (self):
        battleSession = winSession = wrSession = wrChange = ratingTotal = ratingSession = fragsAvg = fragsChange = dmgAvg = dmgChange = spotAvg = spotChange = defAvg = defChange = tierSession = tierChange = wn7change = 0.0

        diff = []
        norm = []
        for i, s in enumerate(zip(self.results, self.sessionStart)):

            diff.append(float(s[0]-s[1]))
            if s[0]-s[1] > 0:
                norm.append((float(s[0])/float(self.results[0]))-(float(s[1])/float(self.sessionStart[0])))
            else:
                norm.append(0.0)

        print diff

        ratingTotal = self.results[8]
        ratingSession = self.calc_wn7(diff[0], diff[1], diff[2], diff[3], diff[4], diff[5], diff[6], diff[7])
        if diff[0] > 0:
            battleSession = diff[0]
            winSession = diff[1]
            wrSession = (diff[1]/diff[0])*100
            wrChange = norm[1]*100
            fragsAvg = diff[2]/diff[0]
            fragsChange = norm[2]
            dmgAvg = diff[4]/diff[0]
            dmgChange = norm[4]
            spotAvg = diff[3]/diff[0]
            spotChange = norm[3]
            defAvg = diff[6]/diff[0]
            defChange = norm[6]
            tierSession = diff[7]/diff[0]
            tierChange = norm[7]
            wn7change = diff[8]


        #[0:battles, 1:wins, 2:frags, 3:spot, 4:damage, 5:cap, 6:defn, 7:tierpoints, 8:wn7]
        self.ui.battleSession.setText('%.2f' % battleSession)
        self.ui.winSession.setText('%.2f' % winSession)
        self.ui.wrSession.setText('%.2f%%' % wrSession)
        self.ui.wrChange.setText('%.3f%%' % wrChange)
        self.ui.ratingTotal.setText('%.2f' % ratingTotal)
        self.ui.ratingSession.setText('%.2f' % ratingSession)
        self.ui.fragsAvg.setText('%.2f' % fragsAvg)
        self.ui.fragsChange.setText('%.3f' % fragsChange)
        self.ui.dmgAvg.setText('%.2f' % dmgAvg)
        self.ui.dmgChange.setText('%.4f' % dmgChange)
        self.ui.spotAvg.setText('%.2f' % spotAvg)
        self.ui.spotChange.setText('%.3f' % spotChange)
        self.ui.defAvg.setText('%.2f' % defAvg)
        self.ui.defChange.setText('%.3f' % defChange)
        self.ui.tierSession.setText('%.1f' % tierSession)
        self.ui.tierChange.setText('%.4f' % tierChange)
        self.ui.change.setText('%.4f' % wn7change)

        self.setColor(self.ui.dmgChange, dmgChange)
        self.setColor(self.ui.spotChange, spotChange)
        self.setColor(self.ui.defChange, defChange)
        self.setColor(self.ui.wrChange, wrChange)
        self.setColor(self.ui.tierChange, 0-tierChange)
        self.setColor(self.ui.fragsChange, fragsChange)
        self.setColor(self.ui.change, wn7change)



        wn7scale = [424.0, 794.0, 1174.0, 1569.0, 1884.0, 999999999.0]
        wn7colors = ["#FE0E00", "#FE0E00", "#FE7903", "#F8F400", "#60FF00", "#02C9B3", "#D042F3"]

        self.setColor(self.ui.ratingTotal, ratingTotal, levels=wn7scale, colors=wn7colors)
        self.setColor(self.ui.ratingSession, ratingSession, levels=wn7scale, colors=wn7colors)
        self.setColor(self.ui.wrSession, wrSession, levels=[46.0, 48.0, 51.0, 56.0, 63.0, 1000.0], colors=wn7colors)
        self.setColor(self.ui.tierSession, tierSession, levels=[2.0,5.0,7.0, 9.0, 100.0], colors=["#D042F3", "#D042F3", "#02C9B3", "#60FF00", "#F8F400", "#FE0E00"])




    def setColor(self, target, value, levels=[0.0, 999999999999.9], colors=['#FF0000', '#FF0000', '#00FF00'], stationary=0, stationary_color='#FFFFFF'):
        levels_sorted = sorted(levels)
        color = colors[0]

        if stationary == value:
            color = stationary_color
        else:
            for num, level in enumerate(levels_sorted):
                if value <= level:
                    color = colors[num+1]
                    break
        target.setStyleSheet('QLabel {color: '+color+'}')



    def mainloop(self):
        if self.dossier_folder:
            dossierfile = self.get_latest()
            if dossierfile[1] > self.last:
                self.tanks = []
                self.last = dossierfile[1]
                newresults = self.process_file(dossierfile[0])
                if not newresults == self.results:
                    if self.sessionStart == []:
                        self.sessionStart = newresults
                    self.results = newresults
                    self.drawstats()
                




    def process_file(self, filename):
        global tankdata, mapdata, structdata, tanks
        cachefile = open(filename, 'rb')
        dossierversion, dossierCache = cPickle.load(cachefile)


        
        tankitems = [(k, v) for k, v in dossierCache.items()]
        base32name = base64.b32decode(os.path.splitext(os.path.basename(filename))[0].replace('.\\', ''))
        
        dossier = dict()
            
        dossierheader = dict()
        dossierheader['dossierversion'] = str(dossierversion)
        dossierheader['parser'] = 'statpadder'
        dossierheader['tankcount'] = len(tankitems)

        
        dossierheader['server'] = base32name.split(';', 1)[0];
        dossierheader['username'] = base32name.split(';', 1)[1];

        for tankitem in tankitems:
            tank = dict()
            tank['tankid'] = tankitem[0][1] >> 8 & 65535
            tank['countryid'] = tankitem[0][1] >> 4 & 15
            data = tankitem[1][1]
            tankstruct = str(len(data)) + 'B'
            sourcedata = struct.unpack(tankstruct, data)
            tank['version'] = sourcedata[0]
            tank['name'] = self.get_tank_data(tank['countryid'], tank['tankid'], 'title')
            tank['tier'] = self.get_tank_data(tank['countryid'], tank['tankid'], 'tier')


            if tank['version'] < 65:

                for k in self.structdata[tank['version']]:
                    if k['category'] == "tankdata":
                        tank[k['name']] = self.get_data(sourcedata, k['offset'], k['length'])

            if tank['version'] >= 65:
                if tank['version'] == 65:
                    blocks = ('a15x15', 'a15x15_2', 'clan', 'clan2', 'company', 'company2', 'a7x7', 'achievements', 'frags', 'total', 'max15x15', 'max7x7')
                if tank['version'] == 69:
                    blocks = ('a15x15', 'a15x15_2', 'clan', 'clan2', 'company', 'company2', 'a7x7', 'achievements', 'frags', 'total', 'max15x15', 'max7x7', 'playerInscriptions', 'playerEmblems', 'camouflages', 'compensation', 'achievements7x7')
                blockcount = len(list(blocks))+1
                newbaseoffset = (blockcount * 2)
                header = struct.unpack_from('<' + 'H' * blockcount, data)
                blocksizes = list(header[1:])
                blocknumber = 0
                fragslist = []
                numoffrags_list = 0
                numoffrags_a15x15 = 0
                
                for blockname in blocks:
                    if blocksizes[blocknumber] > 0:
                        if blockname == 'frags':
                                fmt = '<' + 'IH' * (blocksizes[blocknumber]/6)
                                fragsdata = struct.unpack_from(fmt, data, newbaseoffset)
                                
                                for x in range(0, blocksizes[blocknumber]):
                                    dossier[newbaseoffset+x] = str(sourcedata[newbaseoffset+x]) + " / Frags; "

                                index = 0
                                for i in xrange((blocksizes[blocknumber]/6)):
                                    compDescr, amount = (fragsdata[index], fragsdata[index + 1])
                                    numoffrags_list += amount   
                                    frag_countryid, frag_tankid, frag_tanktitle = self.get_tank_details(compDescr, self.tankdata)
                                    tankfrag = [frag_countryid, frag_tankid, amount, frag_tanktitle]
                                    fragslist.append(tankfrag)
                                    index += 2
                            
                                newbaseoffset += blocksizes[blocknumber]
                            
                        else:
                            oldbaseoffset = newbaseoffset
                            structureddata = self.get_structured_data(sourcedata, data, dossier, blockname, tank['version'], newbaseoffset)
                            newbaseoffset = oldbaseoffset+blocksizes[blocknumber]
                            tank[blockname] = structureddata

                    blocknumber +=1

            self.get_interesting_data(tank)

            self.tanks.append(tank)

        battles = wins = frags = spot = damage = cap = defn = tierpoints = 0

        for tank in self.tanks:
            if 'battlesCount' in tank:
                battles = battles + int(tank['battlesCount'])
                wins = wins + int(tank['wins'])
                frags = frags + int(tank['frags'])
                spot = spot + int(tank['spotted'])
                damage = damage + int(tank['damageDealt'])
                cap = cap + int(tank['capturePoints'])
                defn = defn + int(tank['droppedCapturePoints'])
                tierpoints = tierpoints + (int(tank['tier'])*int(tank['battlesCount']))

        wn7 = self.calc_wn7(battles, wins, frags, spot, damage, cap, defn, tierpoints)
        return [battles, wins, frags, spot, damage, cap, defn, tierpoints, wn7]

    def get_interesting_data(self, tank):
        keys = ('a15x15', 'a15x15_2') # 'clan', 'clan2', 'company', 'company2'
        useful_data = {'battlesCount', 'wins', 'frags', 'spotted','damageDealt', 'capturePoints', 'droppedCapturePoints'}

        for item in keys:
            if item in tank:
                for useful_key in useful_data:
                    if useful_key in tank[item]:
                        if not useful_key in tank:
                            tank[useful_key] = tank[item][useful_key]
                        else:
                            tank[useful_key] += tank[item][useful_key]
        return tank

    def get_json_data(self, filename):
        if not os.path.exists(filename) or not os.path.isfile(filename) or not os.access(filename, os.R_OK):
            raise NameError('CANNOT FIND FILE: '+str(filename))
            sys.exit(1)
        file_json = open(filename, 'r')
        try:
            file_data = json.load(file_json)
        except Exception, e:
            sys.exit(1)
        file_json.close()
        return file_data
예제 #14
0
class MainWindowFunctionality(qtw.QMainWindow):
    def __init__(self):
        """
            Method to initialize all instance variables and connect signals-slots.
        """
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.dest_path = ''
        self.link = ''
        self.yt = None
        self.videos = []
        self.ui.list_widget.addItem('Titles: ')
        self.ui.list_widget.setSelectionMode(
            qtw.QAbstractItemView.SingleSelection)
        self.ui.destination_button.clicked.connect(
            self.select_destination_folder)
        self.ui.add_list_button.clicked.connect(self.add_link_to_list)
        self.ui.download_button.clicked.connect(self.download_videos)
        self.ui.clear_list_button.clicked.connect(self.clear_list)
        self.ui.delete_button.clicked.connect(self.delete_item)

    def select_destination_folder(self):
        """
           Method to store the path of the destination folder where all the downloaded audios will be saved.
        """
        try:
            self.dest_path = QFileDialog.getExistingDirectory(
                self, 'Choose Folder')
            if self.dest_path == '':  #A case where no destination folder is selected and an appropriate message to display.
                msg_not_selected = qtw.QMessageBox()
                msg_not_selected.setWindowTitle('Error')
                msg_not_selected.setIcon(qtw.QMessageBox.Critical)
                msg_not_selected.setText('Destination folder not selected.')
                msg_not_selected.setStandardButtons(qtw.QMessageBox.Ok)
                msg_not_selected.exec_()
            else:  #Appropriate message for successful selection of the destination folder.
                msg_selected = qtw.QMessageBox()
                msg_selected.setWindowTitle('Information')
                msg_selected.setIcon(qtw.QMessageBox.Information)
                msg_selected.setText(
                    'Destination folder successfully selected.')
                msg_selected.setStandardButtons(qtw.QMessageBox.Ok)
                msg_selected.exec_()
        except Exception:  #Displaying an appropriate message in case of an exception.
            error_msg = qtw.QMessageBox()
            error_msg.setWindowTitle('Error')
            error_msg.setIcon(qtw.QMessageBox.Critical)
            error_msg.setText('An error occurred. Please try again.')
            error_msg.exec_()

    def add_link_to_list(self):
        """
            Method to add the video titles of the links in the list widget.
        """
        try:
            self.link = self.ui.input_text.text(
            )  #Getting the link from the text box.
            self.yt = YouTube(self.link)  #Fetching the link's attributes.
            video_title = self.yt.title
            while 'YouTube.' in video_title:  #Sometimes the title has only 'YouTube' in it. Therefore we keep looping till the actual title is fetched.
                self.yt = YouTube(self.link)
                video_title = self.yt.title

            self.videos.append(self.yt)
            self.ui.list_widget.addItem(
                video_title)  #Adding the link's title in the list widget.
            self.ui.input_text.clear()
        except Exception:  #Displaying an appropriate message in case of an exception.
            error_msg = qtw.QMessageBox()
            error_msg.setWindowTitle('Error')
            error_msg.setIcon(qtw.QMessageBox.Critical)
            error_msg.setText('Invalid link! Try again.')
            error_msg.exec_()
            self.ui.input_text.clear()

    def download_videos(self):
        """
            Method for downloading the video in the best available quality (based on audio bitrate).
        """
        if len(self.videos) == 0 or len(self.dest_path) == 0:
            msg_empty_list = qtw.QMessageBox()
            msg_empty_list.setWindowTitle('Information')
            msg_empty_list.setIcon(qtw.QMessageBox.Information)
            msg_empty_list.setText(
                'List is empty or destination folder is not selected!')
            msg_empty_list.setStandardButtons(qtw.QMessageBox.Ok)
            msg_empty_list.exec_()
        else:
            #Here we are sorting the audio formats based on their [abr] attribute. Normally it ranges from 128kbps-160kbps.
            #Also, the downloaded audio can be a .mp4 or a .webm file because we are specifically sorting according to kbps values.
            #Hence, we are sorting to get the best kbps quality and then downloading it.
            try:
                for item in self.videos:
                    vid_formats = item.streams.filter(only_audio=True)
                    kbps_val = []
                    for option in vid_formats:
                        #In the next 3 lines , we are extracting the kbps value.
                        start_index = str(option).index('abr="') + 5
                        end_index = str(option).index('kbps"')
                        audio_quality = str(option)[start_index:end_index]
                        kbps_val.append(int(audio_quality))

                    max_quality = str(
                        max(kbps_val))  #Getting the maximum kbps value.
                    value_to_check = 'abr="' + max_quality + 'kbps"'
                    for i, item in enumerate(vid_formats):
                        if value_to_check in str(item):
                            audio_to_download = vid_formats[i]
                            audio_to_download.download(
                                self.dest_path
                            )  #Downloading the audio and saving it in the destination folder.

                msg_dwnld_success = qtw.QMessageBox()
                msg_dwnld_success.setWindowTitle('Information')
                msg_dwnld_success.setIcon(qtw.QMessageBox.Information)
                msg_dwnld_success.setText('Successfully downloaded!')
                msg_dwnld_success.setStandardButtons(qtw.QMessageBox.Ok)
                msg_dwnld_success.exec_()

                self.clear_list()
            except Exception:  #Displaying an appropriate message in case of an exception.
                error_msg = qtw.QMessageBox()
                error_msg.setWindowTitle('Error')
                error_msg.setIcon(qtw.QMessageBox.Critical)
                error_msg.setText(
                    'An error occurred while downloading! Try again.')
                error_msg.exec_()

    def clear_list(self):
        """
            Method to clear the list widget.
        """
        self.videos.clear()
        self.ui.list_widget.clear()
        self.ui.list_widget.addItem('Titles: ')

    def delete_item(self):
        """
            Method to delete a selected item from the list.
        """
        sel_rows = self.ui.list_widget.selectedIndexes()
        sel_items_text = [
            x.text() for x in self.ui.list_widget.selectedItems()
        ]
        dict_of_row_item = {
            k: v.row()
            for (k, v) in zip(sel_items_text, sel_rows)
        }  #Using dictionary comprehension.

        for item in self.videos:
            if item.title in dict_of_row_item.keys():
                row = dict_of_row_item[item.title]
                self.ui.list_widget.takeItem(row)
                self.videos.remove(item)
예제 #15
0
class MainWindowFunctionality(qtw.QMainWindow):
    def __init__(self):
        """
            Method to initialize all instance variables and connect signals-slots.
        """
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show_reminder = ShowReminder()
        self.list_of_reminders = [
        ]  #A list to store all components of the reminders in the form of a tuple.
        self.ui.list_widget.addItem('Reminder Titles:')
        self.ui.list_widget.setSelectionMode(
            qtw.QAbstractItemView.SingleSelection)
        self.ui.add_reminder_button.clicked.connect(self.add_reminder)
        self.ui.remind_me_button.clicked.connect(self.remind_me)
        self.ui.clearAll_button.clicked.connect(self.clear_all)
        self.ui.delete_button.clicked.connect(self.delete_reminders)

    def add_reminder(self):
        """
            Method to add the reminder to the list.
        """
        if self.ui.line_edit.text() == '':
            error_msg = qtw.QMessageBox()
            error_msg.setWindowTitle('Error')
            error_msg.setIcon(qtw.QMessageBox.Critical)
            error_msg.setText('Title field is empty!')
            error_msg.setStandardButtons(qtw.QMessageBox.Ok)
            error_msg.exec_()
        elif self.ui.text_edit.toPlainText() == '':
            error_msg = qtw.QMessageBox()
            error_msg.setWindowTitle('Error')
            error_msg.setIcon(qtw.QMessageBox.Critical)
            error_msg.setText('Content field is empty!')
            error_msg.setStandardButtons(qtw.QMessageBox.Ok)
            error_msg.exec_()
        else:
            r_date, r_month, r_year = self.ui.date_edit.date().day(
            ), self.ui.date_edit.date().month(), self.ui.date_edit.date().year(
            )  #Getting the date of reminder.
            date_format = f'{str(r_date)}-{str(r_month)}-{str(r_year)}'

            r_hour, r_minutes = self.ui.time_edit.time().hour(
            ), self.ui.time_edit.time().minute(
            )  #Getting the time of reminder.
            if r_hour in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
                r_hour = '0' + str(r_hour)
            if r_minutes in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
                r_minutes = '0' + str(r_minutes)
            time_format = f'{str(r_hour)}:{str(r_minutes)}'

            msg_title = self.ui.line_edit.text(
            )  #Getting the title of the remainder.
            msg_content = self.ui.text_edit.toPlainText(
            )  #Getting the content of the reminder.

            if self.check_duplicate_title(msg_title):
                error_msg_dup = qtw.QMessageBox()
                error_msg_dup.setWindowTitle('Error')
                error_msg_dup.setIcon(qtw.QMessageBox.Critical)
                error_msg_dup.setText(
                    'Duplicate title exists. Please try a different one.')
                error_msg_dup.setStandardButtons(qtw.QMessageBox.Ok)
                error_msg_dup.exec_()
            else:
                reminder = Reminders(date_format, time_format, msg_title,
                                     msg_content)
                self.list_of_reminders.append(
                    reminder.get_tuple()
                )  #Adding a tuple so that heap sorts the reminders based on date and time.
                heapq.heapify(
                    self.list_of_reminders
                )  #Using heapq for maintaining the order of the reminders based on date and time.
                self.ui.list_widget.clear()

                #Displaying on the list in sorted order.
                self.ui.list_widget.addItem('Reminder Titles:')
                for item in self.list_of_reminders:
                    self.ui.list_widget.addItem(item[2] + ' on ' + item[0] +
                                                ' @' + item[1])

                self.ui.line_edit.clear()
                self.ui.text_edit.clear()
                self.ui.time_edit.setMinimumTime(QtCore.QTime.currentTime())
                self.ui.date_edit.setMinimumDate(QtCore.QDate.currentDate())

    def check_duplicate_title(self, msg_title):
        """
            Method to check if any duplicate reminder title exists.
        """
        for item in self.list_of_reminders:
            if item[2] == msg_title:
                return True
        return False

    def delete_reminders(self):
        """
            Method to delete the reminders from the list.
        """
        sel_row = self.ui.list_widget.selectedIndexes()
        x = self.ui.list_widget.selectedItems()
        sel_item_text = x[0].text()

        for item in self.list_of_reminders:
            if item[2] in sel_item_text:
                self.ui.list_widget.takeItem(sel_row[0].row())
                self.list_of_reminders.remove(item)

    def clear_all(self):
        """
            Method to clear all reminders from the list.
        """
        self.ui.list_widget.clear()
        self.list_of_reminders.clear()
        self.ui.list_widget.addItem('Reminder Titles:')
        self.show_reminder.quit(
        )  #Terminating the thread that notifies the user of the reminder.

    def remind_me(self):
        """
           Method to call the thread responsible for showing the reminder.
        """
        if len(self.list_of_reminders) == 0:
            reminders_completed_msg = qtw.QMessageBox()
            reminders_completed_msg.setWindowTitle('Information')
            reminders_completed_msg.setIcon(qtw.QMessageBox.Information)
            reminders_completed_msg.setText('All reminders are notified.')
            reminders_completed_msg.setStandardButtons(qtw.QMessageBox.Ok)
            reminders_completed_msg.exec_()
        else:
            confirmation_msg = qtw.QMessageBox()
            confirmation_msg.setWindowTitle('Information')
            confirmation_msg.setIcon(qtw.QMessageBox.Information)
            confirmation_msg.setText(
                'All reminders are set and ready to be notified.')
            confirmation_msg.setStandardButtons(qtw.QMessageBox.Ok)
            confirmation_msg.exec_()
            self.show_reminder.content_of_reminder(self.list_of_reminders,
                                                   self.ui.list_widget)
            self.show_reminder.start()
예제 #16
0
class Main(QtGui.QMainWindow):
    def __init__(self, pages, workingdir):
        QtGui.QMainWindow.__init__(self)
        self.inputpages = pages
        self.workingdir = workingdir
        self.pages = []
        self.data = []
        self.currentpage = 0
        self.getPages()
        self.finalwidth = 1448
        self.finalxoffset = 164
        self.rulers = []
        
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.frame = self.ui.webView.page().mainFrame()
        self.ui.webView.connect(self.ui.webView, QtCore.SIGNAL('loadFinished(bool)'), self.loadFinished)
        self.ui.webView.connect(self.ui.webView.page().mainFrame(), QtCore.SIGNAL('javaScriptWindowObjectCleared()'), self.addmodeltojs)
        self.connect(self.ui.next, QtCore.SIGNAL('clicked()'), self.nextPage)
        self.connect(self.ui.previous, QtCore.SIGNAL('clicked()'), self.previousPage)
        self.connect(self.ui.chopPage, QtCore.SIGNAL('clicked()'), self.page2jpg)
        self.connect(self.ui.addRuler, QtCore.SIGNAL('clicked()'), self.addruler)
        self.ui.webView.setUrl(QtCore.QUrl("/home/nic/git/tablemaker/magic.html"))
        self.currentpage = 0
        self.ui.webView.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.webInspector = QWebInspector(self)
        self.webInspector.setPage(self.ui.webView.page())
        self.webInspector.setVisible(True)
        self.ui.verticalLayout_2.addWidget(self.webInspector)

    def addruler (self):
        added = False
        
        for fish in self.rulers:
            if fish[2].isHidden():
                fish[2].show()
                fish[3].show()
                fish[4].show()
                added = True
                break
            
        if not added:
            rulerno = len(self.rulers)+1
            
            newRulerbox = QtGui.QHBoxLayout()
            
            rulerLabel = QtGui.QLabel(self.ui.rulerBox)
            rulerLabel.setText("Ruler #"+str(rulerno))
            
            rulerSpin = QtGui.QSpinBox( self.ui.rulerBox)
            rulerSpin.setMaximum(10000)
            rulerSpin.setObjectName(_fromUtf8("split"+str(rulerno)+"y"))
            
            rulerInc = QtGui.QCheckBox( self.ui.rulerBox)
            rulerInc.setText("Include")
            rulerInc.setChecked(True)
            rulerInc.setObjectName(_fromUtf8("include"+str(rulerno)))
            
            newRulerbox.addWidget(rulerLabel)
            newRulerbox.addWidget(rulerSpin)
            newRulerbox.addWidget(rulerInc)
            
            self.rulers.append([rulerno, newRulerbox, rulerSpin, rulerInc, rulerLabel])
            self.connect(newRulerbox, QtCore.SIGNAL('valueChanged(int)'), self.setHandles)
            self.ui.verticalLayout_3.addLayout(newRulerbox)
            
            
        
    def clearRulers (self):
        for rulerbox in self.rulers:
            rulerbox[2].hide()
            rulerbox[3].hide()
            rulerbox[4].hide()

    def toggleInspector(self):
        self.webInspector.setVisible(not self.webInspector.isVisible())
        self.ui.next.connect(self.ui.next, QtCore.SIGNAL('clicked(bool)'), self.nextPage)
        
    def addmodeltojs (self):
        self.frame.addToJavaScriptWindowObject("pyObj", self)
    
    
    @QtCore.pyqtSlot()
    def handleMoved(self, ret=False):
        t**s = self.frame.evaluateJavaScript("getRulers();")
        t**s= t**s.toList()
        rulers = []
        for moo in t**s:
            rulers.append(int(moo.toInt()[0]))
        if ret:
            return rulers
        else:
            self.getHandles(rulers)
        
    def getHandles (self, rulers):
        moo = 0
        for t**s in rulers:
            if len(self.rulers) > moo:
                if not self.rulers[moo][2].isHidden():
                    self.rulers[moo][2].show()
                    self.rulers[moo][3].show()
                    self.rulers[moo][4].show()
                self.rulers[moo][2].setValue(t**s)
            else:
                pewpew = self.addruler()
                self.rulers[len(self.rulers)-1][2].setValue(t**s)
            moo = moo+1
    def getpagerulers (self):
        rulersarr = []
        for ruler in self.rulers:
            if not ruler[2].isHidden():
                rulersarr.append(int(ruler[2].value()))
        return rulersarr
    
    def setHandles (self):
        rulersarr = self.getpagerulers()  
        self.frame.evaluateJavaScript("setRulers("+str(rulersarr)+");")
    
    def getPages (self):
        for chunk in self.inputpages:
            for page in range(chunk[0],(chunk[1]+1)):
                self.pages.append(os.path.join(self.workingdir, "workingpages", "page"+str(page)+".jpg"))
                self.data.append([page, [100, 200, 300]])
    
    def goToPage(self, page):
        t**s =self.frame.evaluateJavaScript("setPage('"+self.pages[page]+"');")
        t**s= t**s.toString()
    
    def saveHandles (self):
        self.data[self.currentpage] = [self.data[self.currentpage][0],[]]
        for rulers in self.rulers:
            if not rulers[2].isHidden():
                self.data[self.currentpage][1].append(int(rulers[2].value()))
        
    def nextPage (self):
        self.saveHandles()
        self.clearRulers()
        self.currentpage = self.currentpage+1
        if self.currentpage > len(self.pages):
            self.currentpage = len(self.pages)
        self.goToPage(self.currentpage)
        self.getHandles(self.data[self.currentpage][1])
        self.setHandles()
    
    def previousPage (self):
        dosomething = 1
        self.saveHandles()
        self.currentpage = self.currentpage-1
        if self.currentpage < 0:
            self.currentpage = 0
        self.goToPage(self.currentpage)
        self.getHandles(self.data[self.currentpage][1])
        self.setHandles()
        
        
    
    def loadFinished(self, ok):
        self.goToPage(self.currentpage)
        self.handleMoved()
    
    def pdf2pages(self):
        for chunk in pages:
            for page in range(chunk[0],(chunk[1]+1)):
                os.system("convert -density 400 '"+os.path.join(targetfolder,pdf)+"'["+str(page)+"] -resize 2000x\\> -crop 1763x2696+119+118 '"+os.path.join(workingpages,"page"+str(page)+".jpg")+"'")
                #break
            #break
    
    def pages2splits(self,targetpage=None):    
        for chunk in pages:
            for page in range(chunk[0],(chunk[1]+1)):
                if targetpage == None or page == targetpage:
                    adjust = 0
                    previous = 0
                    os.system("convert '"+os.path.join(workingpages,"page"+str(page)+".jpg")+"' -crop "+str(self.finalwidth)+"x"+str(786+adjust)+"+"+str(self.finalxoffset)+"+"+str(120+previous)+" '"+os.path.join(tables,"page"+str(page)+"_1.jpg")+"'")
                    os.system("convert '"+os.path.join(workingpages,"page"+str(page)+".jpg")+"' -crop "+str(self.finalwidth)+"x"+str(735+adjust)+"+159+"+str(906+previous)+" '"+os.path.join(tables,"page"+str(page)+"_2.jpg")+"'")
                    os.system("convert '"+os.path.join(workingpages,"page"+str(page)+".jpg")+"' -crop "+str(self.finalwidth)+"x"+str(852+adjust)+"+159+"+str(1641+previous)+" '"+os.path.join(tables,"page"+str(page)+"_3.jpg")+"'")
                #break
            #break
    
    def page2jpg(self,targetpage=None):    
        if targetpage == None:
            targetpage = self.data[self.currentpage][0]
        rulers = self.handleMoved(ret=True)
        os.system("convert '"+self.pages[self.currentpage]+"' -crop "+str(self.finalwidth)+"x"+str(rulers[1]-rulers[0])+"+"+str(self.finalxoffset)+"+"+str(rulers[0])+" '"+os.path.join(tables,"page"+str(self.data[self.currentpage][0])+"_1.jpg")+"'")
        os.system("convert '"+self.pages[self.currentpage]+"' -crop "+str(self.finalwidth)+"x"+str(rulers[2]-rulers[1])+"+"+str(self.finalxoffset)+"+"+str(rulers[1])+" '"+os.path.join(tables,"page"+str(self.data[self.currentpage][0])+"_2.jpg")+"'")
class Main(QtGui.QMainWindow):
    def __init__(self, *args, **kwargs): #, source, destination, fps, size, gui, serial

        if 'logger' in kwargs:
            self.logger = kwargs['logger']
        if 'app' in kwargs:
            self.app = kwargs['app']

        QtGui.QMainWindow.__init__(self)    
#        mw = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.resize(800,800)
        self.show()
        
        self.vb = pg.ViewBox()
        self.ui.graphicsView.setCentralItem(self.vb)
        self.vb.setAspectLocked()
        self.img = pg.ImageItem()
        self.vb.addItem(self.img)
        self.vb.setRange(QtCore.QRectF(0, 0, 512, 512))
#        self.img.setPxMode(True)
        
        self.logger.info('%s starting spotter', self)
        self.spotter = Spotter(*args, **kwargs)    
        self.spotter.gui_grabber.displayTarget = self.img
        self.logger.info('%s spotter instantiated', self)

        self.lastTime = ptime.time()
        self.fps = None

        # main window refresh timer
#        self.timer = QtCore.QTimer()
#        self.timer.timeout.connect(self.update)
#        self.timer.start(0)
        self.update()

    def update(self):
        self.logger.info('%s:Processing Events', self)
        now = ptime.time()
        dt = now - self.lastTime
        self.lastTime = now
        if self.fps is None:
            self.fps = 1.0/dt
        else:
            s = np.clip(dt*3., 0, 1)
            self.fps = self.fps * (1-s) + (1.0/dt) * s
        self.ui.fpsLabel.setText('%0.2f fps' % self.fps)
#        self.app.processEvents()  ## force complete redraw for every plot
        QtCore.QTimer.singleShot(1, self.update)
#        global ui, lastTime, fps, img
#        rv, frame = src.read()
#        # rotate frame if wanted
#        frame = np.rot90(frame, 3)
#        # flip frame
#        #frame = np.fliplr(frame)    


    def closeEvent(self, event):
        """
        Exiting the interface has to kill the spotter class and subclasses
        properly, especially the writer and serial handles, otherwise division
        by zero might be imminent.
        """
        if NO_EXIT_CONFIRMATION:
            reply = QtGui.QMessageBox.Yes
        else:
            reply = QtGui.QMessageBox.question(self,
                                               'Exiting...',
                                               'Are you sure?',
                                               QtGui.QMessageBox.Yes,
                                               QtGui.QMessageBox.No )
        if reply == QtGui.QMessageBox.Yes:
            self.spotter.stop_all()
#            time.sleep(1)
            event.accept()
        else:
            event.ignore()
예제 #18
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, cfg):
        QtGui.QMainWindow.__init__(self)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.cfg = cfg
        self.show()

        # Initialize sound output
        pygame.mixer.init()

        # Message Window
        self.messageWindow = MessageWindow(self)
        
        # Windows
        self.codeWindow = CodeWindow(self.messageWindow, self.redeemCode, self)
        self.tosWindow = TosWindow(self)
        self.screensaverWindow = ScreensaverWindow(self)
        self.adminWindow = AdminWindow(self)

        # RFID reading
        if not cfg.client.use_rfid_dummy:
            self.rfid = RFIDWorker(cfg.rfid.key)
        else:
            self.rfid = RFIDDummyWorker(cfg.rfid.key)
        self.connect(self.rfid, SIGNAL("cardRead(PyQt_PyObject)"), self.rfidUpdate)
        self.rfid.start()
 
        # Business logic stuff
        self.client = CoffeeClient()
        self.card = self.rfid.readCard()
        self.wallet = None
        self.user = None
        self.lastcard = None
        self.adminButton = None
        self.buttons = {}
        self.items = {}

        # Timer for screensaver timeouts
        self.screensaverTimer = QtCore.QTimer()
        QtCore.QObject.connect(self.screensaverTimer, QtCore.SIGNAL("timeout()"), self.screensaverTimeout)
        self.screensaverTimer.setInterval(cfg.client.screensaver_timeout * 1000)
        self.screensaverTimer.start()

         # Timer for interaction timeouts
        self.interactionTimer = QtCore.QTimer()
        QtCore.QObject.connect(self.interactionTimer, QtCore.SIGNAL("timeout()"), self.interactionTimeout)
        self.interactionTimer.setInterval(cfg.client.interaction_timeout * 1000)
        self.interactionTimer.start()
 
        # Timer for item updates
        self.itemsTimer = QtCore.QTimer()
        QtCore.QObject.connect(self.itemsTimer, QtCore.SIGNAL("timeout()"), self.rebuildItemTimeout)
        self.rebuildItems()
        self.itemsTimer.setInterval(cfg.client.item_refresh)
        self.itemsTimer.start()
        
        # Click event for message label
        self.ui.message.mousePressEvent = self.onMessageLabelClicked

    def rebuildItemTimeout(self):
        if self.card is None:
            self.rebuildItems()

    def rebuildItems(self):
        QtCore.QCoreApplication.processEvents()
        self.messageWindow.show("Items werden geupdated ...", 60)
        print "Rebuilding items..." 
        QtCore.QCoreApplication.processEvents()

        # Remove all buttons
        for i in range(self.ui.dynamicButtonLayout.count()): 
            self.ui.dynamicButtonLayout.itemAt(i).widget().deleteLater()
            self.ui.dynamicButtonLayout.itemAt(i).widget().close()

        self.buttons = {}
        
        # Add new buttons
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setWeight(75)
        font.setBold(True)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)

        # Reset item storage
        self.items = {} 

        allItems = sorted(self.client.getItems(), cmp=Item_Sort)
        enabledItems = []
        # Download all pictures, build enabledItems
        for item in allItems:
            self.items[item.id] = item

            print "Image for '" + str(item.id) + "...", 
            serverLastModified = float(self.client.getRequest("resource/item/lastModified/" + str(item.id)))
            clientLastModified = 0
            try:
                clientLastModified = os.path.getctime("resource/items/" + str(item.id) + ".png")
            except:
                pass

            # Download the item icon
            if serverLastModified > clientLastModified:
                f = open("resource/items/" + str(item.id) + ".png", "w+")
                f.write(self.client.getRequest("resource/item/image/" + str(item.id)))
                f.close()
                print "downloaded."
            else:
                print "cached."

            if item.enabled:
                enabledItems.append(item)

        itemPerColumn = 2
        itemIndex = 0
        for item in enabledItems:
            button = QtGui.QPushButton(self.ui.centralwidget)
            button.setSizePolicy(sizePolicy)
            button.setFont(font)
            button.setStyleSheet("image: url(resource/items/" + str(item.id) + ".png);")
            button.setCheckable(True)
            button.setObjectName(item.desc)
    
            if item.sold_out:
                button.setText(item.desc + "\nAusverkauft")
                button.setEnabled(False)
            else:
                button.setText(item.desc + " / " + str(item.price) + " Bits")
                button.setEnabled(True)

            if itemIndex+1 == len(enabledItems) and len(enabledItems) % 2 != 0:
                self.ui.dynamicButtonLayout.addWidget(button, itemIndex % itemPerColumn, itemIndex / itemPerColumn, 2, 1)
            else:
                self.ui.dynamicButtonLayout.addWidget(button, itemIndex % itemPerColumn, itemIndex / itemPerColumn)

            itemIndex += 1

            button.clicked.connect(partial(self.pushItemClicked, item.id))
            self.buttons[item.id] = button

        # Charge button...
        self.chargeButton = QtGui.QPushButton(self.ui.centralwidget)
        self.chargeButton.setSizePolicy(sizePolicy)
        self.chargeButton.setFont(font)
        self.chargeButton.setStyleSheet("image: url(resource/gold.png);")
        self.chargeButton.setObjectName("Aufladen")
        self.chargeButton.setText("Aufladen")
        self.ui.dynamicButtonLayout.addWidget(self.chargeButton, 0, 1337, self.ui.dynamicButtonLayout.rowCount(), 1)
        self.chargeButton.clicked.connect(self.pushChargeClicked)
 
        self.adminButton = QtGui.QPushButton(self.ui.centralwidget)
        self.adminButton.setSizePolicy(sizePolicy)
        self.adminButton.setFont(font)
        self.adminButton.setStyleSheet("image: url(resource/admin.png);")
        self.adminButton.setObjectName("Admin")
        self.adminButton.setText("Admin")
        self.adminButton.setVisible(False)
        self.ui.dynamicButtonLayout.addWidget(self.adminButton, 0, 1338, self.ui.dynamicButtonLayout.rowCount(), 1)
        self.adminButton.clicked.connect(self.pushAdminClicked)
         
        print "done"
        QtCore.QCoreApplication.processEvents()
        self.messageWindow.show("Items werden geupdated ...", 1)
        self.displayUpdate()

    def rfidUpdate(self, newcard):
        #self.lastcard = self.card
        #newcard = self.rfid.readCard()

        if newcard == None:
            self.lastcard = None
            self.card = None
            self.wallet = None
            self.user = None
            CoffeeClient().resetIds()
            self.closeAllWindows()
            self.displayUpdate()
            return

        if not newcard.isSame(self.lastcard):
            self.resetScreensaverTimeout()
            self.resetInteractionTimeout()
            self.closeAllWindows()

            self.lastcard = self.card
            self.card = newcard

            CoffeeClient().setIds(self.card.mifareid, self.card.cardid)
            self.wallet = CoffeeClient().getWallet()

            self.user = None
            if self.wallet != None:
                self.card.valid = True
                self.user = CoffeeClient().getUser()

            self.lastcard = self.card
        
        item = 0
        for i in self.buttons:
            if self.buttons[i].isChecked():
                item = i

        if self.card != None and item > 0:
            # buy item
            for i in self.buttons:
                self.buttons[i].setChecked(False)

            # Save old balance
            oldBalance = 0
            
            if self.wallet is not None:
                oldBalance = self.wallet.balance
          
            buyReq = CoffeeClient().buyItem(item)

            if buyReq == False:
                self.messageWindow.show("Nicht genug Bits.", 4)
                return
           
            self.wallet = CoffeeClient().getWallet()

            message = str(self.items[item].desc) + " gekauft\n\n"
            message += "Altes Guthaben: " + str(oldBalance) + " Bits\n"
            message += "Neues Guthaben: " + str(self.wallet.balance)+ " Bits\n\n"
            message = QtGui.QApplication.translate("", message, None, QtGui.QApplication.UnicodeUTF8)

            self.messageWindow.show(message, 4)
        self.displayUpdate()

    def redeemCode(self, token):
        code = token

        if self.card == None:
            self.codeWindow.ui.message.setText("Karte nicht angelegt?")
            return

        oldBalance = 0
        
        if self.wallet is not None:
            oldBalance = self.wallet.balance

        redeemResp = CoffeeClient().redeemToken(code)

        if redeemResp == False:
            # Plays beep
            pygame.mixer.music.load("resource/zonk.wav")
            pygame.mixer.music.play()
            self.codeWindow.ui.message.setText("Token ist falsch.")
            return
       
        self.wallet = CoffeeClient().getWallet()
        self.codeWindow.accept()

        # Plays beep
        pygame.mixer.music.load("resource/beep.wav")
        pygame.mixer.music.play()

        message = "Code eingelöst\n\n"
 
        message += "Altes Guthaben: " + str(oldBalance) + " Bits\n\n"
        message += "Neues Guthaben: " + str(self.wallet.balance)+ " Bits\n\n"
        message = QtGui.QApplication.translate("", message, None, QtGui.QApplication.UnicodeUTF8)

        self.messageWindow.show(message, 4)

        # update rfid
        self.card.valid = True
        self.rfidUpdate()

    def resetScreensaverTimeout(self):
        self.screensaverWindow.close()
        self.screensaverTimer.stop()
        self.screensaverTimer.start()

    def resetInteractionTimeout(self):
        self.interactionTimer.stop()
        self.interactionTimer.start()

    def screensaverTimeout(self):
        if self.card is None:
            self.interactionTimeout()
            self.screensaverWindow.show()

    def interactionTimeout(self):
        if self.card is not None and self.user is not None:
            return

        for i in self.buttons:
            self.buttons[i].setChecked(False)
        self.closeAllWindows()

    def closeAllWindows(self):
        self.tosWindow.close()
        self.codeWindow.close()
        self.adminWindow.close()
        self.tosWindow.close()
        self.messageWindow.close()

    def displayUpdate(self):
        cardtext = "Bitte Karte anlegen ..."
        price = ""
       
        if self.adminButton is not None:
            self.adminButton.setVisible((self.user != None and self.user.admin == True))
        
        for i in self.buttons:
            if self.buttons[i].isChecked():
                price = self.items[i].desc + " a " + str(self.items[i].price) + " Bits"

        if self.card != None:
            if self.wallet != None:
                cardtext = "Guthaben: " + str(self.wallet.balance) + " Bits"
            else:
                cardtext = "Guthaben: 0 Bits"
        elif price != "":
            cardtext += " - " + price

        messagetext = cardtext
        self.ui.message.setText(messagetext)

    def pushItemClicked(self, id):
        self.resetInteractionTimeout()
        self.resetScreensaverTimeout()
        for i in self.buttons:
            self.buttons[i].setChecked(False)

        if self.wallet is not None:
            self.buttons[id].setChecked(True)

        self.displayUpdate()

    def pushChargeClicked(self):
        self.resetInteractionTimeout()
        self.screensaverTimer.stop()
        if self.card:
            if not self.card.valid:
                if self.tosWindow.exec_() == 0:
                    self.screensaverTimer.start()
                    return
            self.codeWindow.exec_()
        self.displayUpdate()
        self.screensaverTimer.start()

    def pushAdminClicked(self):
        if self.user is not None and self.user.admin is True:
            self.itemsTimer.stop()
            self.screensaverTimer.stop()
            self.interactionTimer.stop()
            self.adminWindow.exec_()
            self.interactionTimer.start()
            self.screensaverTimer.start()
            self.itemsTimer.start()
            self.rebuildItems()
        return

    def onMessageLabelClicked(self, event):
        self.resetScreensaverTimeout()
        try:
            if self.card is not None:
                if self.card.ccBalance != None or False == True:
                    s = "CampusCard\n\nAktuelles Guthaben: %0.2f Euro\nLetztes Guthaben: %0.2f Euro" % (self.card.ccBalance, self.card.ccLastBalance)
                    self.messageWindow.show(s, 5)
        except:
            pass

    def keyPressEvent(self, e):            
        if e.key() == QtCore.Qt.Key_Escape:
            self.close()