Advertisement
Guest User

lorena project

a guest
Apr 6th, 2012
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.34 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import sys
  5. import os
  6. import subprocess
  7. from PyQt4 import QtCore, QtGui, uic
  8. import sqlite3 as lite
  9. from xml.etree import ElementTree as ET
  10. import resources
  11.  
  12. class Init(QtGui.QMainWindow):
  13.     def __init__(self):
  14.         super(Init, self).__init__()
  15.         self.initUI()
  16.        
  17.     def initUI(self):
  18.         uic.loadUi(os.path.join(os.getcwd(), "ui/lory.ui"), self)
  19.        
  20.         self.progressbar = QtGui.QProgressDialog("Generating Mame game list...\nThis process may take a few minutes to complete.", "Abort", 0, 0, self);
  21.         self.progressbar.setWindowTitle("Lorena")
  22.         self.progressbar.setWindowModality(QtCore.Qt.WindowModal);
  23.         self.progressbar.setAutoReset(True)
  24.         self.progressbar.setAutoClose(True)
  25.  
  26.         #self.show()
  27.         self.buildGamelist()
  28.         #self.animateMng("nrallyx.mng")
  29.         self.show()
  30.  
  31.     def buildGamelist(self):
  32.         if not os.path.isfile('lory.db'):
  33.             con = self.dbConnection()
  34.             item = 0
  35.             with con:
  36.                 # Create a library of games table
  37.                 cur_libname = con.cursor()
  38.                 cur_libname.execute("CREATE TABLE libraryname (id INTEGER PRIMARY KEY ASC, name TEXT)")
  39.                 cur_libname.execute("INSERT INTO libraryname (name) VALUES ('Recently Played')")
  40.                 cur_libname.execute("INSERT INTO libraryname (name) VALUES ('Top Rated')")
  41.                 cur_libgame = con.cursor()
  42.                 cur_libgame.execute("CREATE TABLE library(id INTEGER PRIMARY KEY ASC, idgame INTEGER, idlibname INTEGER)")
  43.                
  44.                 # Create a games list table
  45.                 cur_game = con.cursor()    
  46.                 cur_game.execute("CREATE TABLE game (id INTEGER PRIMARY KEY ASC, name TEXT, sourcefile TEXT, cloneof TEXT, romof TEXT, description TEXT, year TEXT, manufacturer TEXT, picture TEXT, video TEXT, rating INTEGER, lastplayed DATE, playcount INTEGER, status INTEGER)")
  47.                
  48.                 total = self.mameExec('-ll | wc -l')
  49.                 self.progressbar.setMinimum(1)
  50.                 self.progressbar.setMaximum(int(total))
  51.                                
  52.                 games = self.mameExec('-ll | awk \'{print $1}\'')
  53.                 for i in games.splitlines()[1:]:
  54.                     xmllist = self.mameExec('-lx -norc ', i)
  55.                     xmlresult = self.xmlParse(xmllist)
  56.                     item += 1
  57.                     self.progressbar.setValue(item)
  58.                     if self.progressbar.wasCanceled():
  59.                         break                        
  60.                     sql = """INSERT INTO game (name, sourcefile, cloneof, romof, description, year, manufacturer, picture, video, playcount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
  61.                     cur_game.execute(sql, [xmlresult[0], xmlresult[1], xmlresult[2], xmlresult[3], xmlresult[4], xmlresult[5], xmlresult[6], xmlresult[0] + ".png", xmlresult[0] + ".mng", 0])
  62.             con.commit()
  63.             self.progressbar.cancel()
  64.  
  65.         self.populateLibrary()
  66.         self.populateGame()
  67.  
  68.     def populateLibrary(self):
  69.         # populate category
  70.         self.trLibraries.clear()
  71.         querylib = self.queryLibrary()
  72.         for l in querylib:
  73.             item = QtGui.QTreeWidgetItem(self.trLibraries)
  74.             item.setText(0, l[1])
  75.  
  76.     def populateGame(self):
  77.         # populate game
  78.         self.gamebox = []
  79.         self.scene = QtGui.QGraphicsScene()
  80.        
  81.         self.tableWidget.setColumnCount(7)
  82.         self.tableWidget.setHorizontalHeaderLabels(["Game", "Name", "Year", "Manufacturer", "Last Played", "Play Count", "Rating"])
  83.         hitem = QtGui.QTableWidgetItem("Game")
  84.         hitem.setTextAlignment(QtCore.Qt.AlignLeft)
  85.         self.tableWidget.setHorizontalHeaderItem(0, hitem)
  86.         hitem = QtGui.QTableWidgetItem("Name")
  87.         hitem.setTextAlignment(QtCore.Qt.AlignLeft)
  88.         self.tableWidget.setHorizontalHeaderItem(1, hitem)
  89.         hitem = QtGui.QTableWidgetItem("Manufacturer")
  90.         hitem.setTextAlignment(QtCore.Qt.AlignLeft)
  91.         self.tableWidget.setHorizontalHeaderItem(3, hitem)
  92.  
  93.         self.tableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows);
  94.         self.tableWidget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection);
  95.  
  96.         querygame, querygametotal = self.queryGame()
  97.         self.statusBar().showMessage("Total Games: " + str(querygametotal[0]))
  98.         col = 0
  99.         lin = 0
  100.         tableline = 0
  101.         for l in querygame:
  102.             gameid = l[0]
  103.             gamename = l[1]
  104.             gamedescription = l[5]
  105.             gameyear = l[6]
  106.             gamemanufaturer = l[7]
  107.             gamepicture = l[8]
  108.             gamevideo = l[9]
  109.             gamerating = l[10]
  110.             gamelastplay = l[11]
  111.             gameplaycount = l[12]
  112.             gamestdout = self.mameExec("-verifyroms", gamename)
  113.             errcheck = gamestdout.find("is good") >= 0
  114.             if errcheck:
  115.                 gamestatus = True
  116.             else:
  117.                 gamestatus = False
  118.                
  119.             self.tableWidget.setRowCount(querygametotal[0])
  120.             item = QtGui.QTableWidgetItem(tableline)
  121.  
  122.             if gamestatus:
  123.                 item.setIcon(QtGui.QIcon(QtGui.QPixmap("ui/pixmaps/ok.png")))
  124.                 item.setText(str(gamedescription))
  125.                 self.tableWidget.setItem(tableline, 0, item)
  126.             else:
  127.                 item.setIcon(QtGui.QIcon(QtGui.QPixmap("ui/pixmaps/error.png")))
  128.                 item.setText(str(gamedescription))
  129.                 self.tableWidget.setItem(tableline, 0, item)
  130.             item = QtGui.QTableWidgetItem(str(gamename))
  131.             item.setTextAlignment(QtCore.Qt.AlignLeft)
  132.             self.tableWidget.setItem(tableline, 1, item)
  133.             item = QtGui.QTableWidgetItem(str(gameyear))
  134.             item.setTextAlignment(QtCore.Qt.AlignHCenter)
  135.             self.tableWidget.setItem(tableline, 2, item)
  136.             item = QtGui.QTableWidgetItem(str(gamemanufaturer))
  137.             item.setTextAlignment(QtCore.Qt.AlignLeft)
  138.             self.tableWidget.setItem(tableline, 3, item)
  139.             item = QtGui.QTableWidgetItem(str(gamerating))
  140.             item.setTextAlignment(QtCore.Qt.AlignHCenter)
  141.             self.tableWidget.setItem(tableline, 4, item)
  142.             item = QtGui.QTableWidgetItem(str(gamelastplay))
  143.             item.setTextAlignment(QtCore.Qt.AlignHCenter)
  144.             self.tableWidget.setItem(tableline, 5, item)
  145.             item = QtGui.QTableWidgetItem(str(gameplaycount))
  146.             item.setTextAlignment(QtCore.Qt.AlignHCenter)
  147.             self.tableWidget.setItem(tableline, 6, item)
  148.  
  149.             self.tableWidget.resizeColumnsToContents()
  150.  
  151.             tableline += 1
  152.  
  153.             picture = "/home/junix/snap/" + gamepicture
  154.             if os.path.isfile(picture) and gamestatus:
  155.                 scaledpicture = QtGui.QPixmap(picture).scaled(238, 174, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.FastTransformation)
  156.                 picitem = QtGui.QGraphicsPixmapItem(scaledpicture)
  157.                 picitem.setPos((260 * col), lin)
  158.                 self.scene.addItem(picitem)
  159.  
  160.                 col += 1
  161.                 if col >= 6:
  162.                     lin += 220
  163.                     col = 0
  164.  
  165.         self.graphicsView.setScene(self.scene)
  166.         #self.gamebox.append(item)
  167.  
  168.     def dbConnection(self):
  169.         try:
  170.             con = lite.connect("lory.db")
  171.  
  172.         except lite.Error, e:
  173.             print "Error %s:" % e.args[0]
  174.             sys.exit(1)
  175.  
  176.         return con
  177.            
  178.     def queryLibrary(self):
  179.         # Generate a library
  180.         con = self.dbConnection()
  181.         cur_lib = con.cursor()
  182.         cur_lib.execute("SELECT * FROM libraryname")
  183.         data_lib = cur_lib.fetchall()
  184.         con.close()
  185.         return data_lib
  186.    
  187.     def queryGame(self):
  188.         # Generate a games list
  189.         con = self.dbConnection()
  190.         cur_game = con.cursor()    
  191.         cur_game.execute("SELECT * FROM game")
  192.         data_game = cur_game.fetchall()
  193.         cur_game.execute("SELECT COUNT(*) FROM game")
  194.         data_game_count = cur_game.fetchone()
  195.  
  196.         con.close()
  197.         return data_game, data_game_count
  198.  
  199.     def mameExec(self, parameter1, parameter2):
  200.         mamebin = os.popen("/usr/bin/which mame").read()
  201.         if not mamebin:
  202.             QMessageBox.about(self, "Lorena", "Error on execute shell command.", "")
  203.             return False
  204.  
  205.         command = subprocess.Popen([mamebin.strip(), parameter1, parameter2], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  206.         (standardout, standarderr) = command.communicate()
  207.         return standardout
  208.  
  209.     def getNodetext(self, elem,node_name,default_value=None):
  210.         node = elem.find(node_name)
  211.         if node == None:
  212.             return default_value
  213.         return node.text
  214.  
  215.     def xmlParse(self, xmllist):
  216.         doc = ET.ElementTree(ET.fromstring(xmllist))
  217.         game_nodes = doc.getroot().findall("game")
  218.         for game_node in game_nodes:
  219.             name = game_node.attrib.get("name",None)
  220.             sourcefile = game_node.attrib.get("sourcefile",None)
  221.             cloneof = game_node.attrib.get("cloneof",None)
  222.             romof = game_node.attrib.get("romof",None)
  223.             description = self.getNodetext(game_node,"description","")
  224.             year = self.getNodetext(game_node,"year","")
  225.             manufacturer = self.getNodetext(game_node,"manufacturer","")
  226.             xmlresult = [name, sourcefile, cloneof, romof, description, year, manufacturer]            
  227.         return xmlresult
  228.  
  229.     def animateMng(self, gamename):
  230.         movie = QtGui.QMovie(os.path.join(os.getcwd(), gamename), parent=self.lblMovie)
  231.         movie.setCacheMode(QtGui.QMovie.CacheAll)
  232.         self.lblMovie.setMovie(movie)
  233.         movie.start()
  234.  
  235.     def mousePressEvent(self, event):
  236.         if (event.button() != QtCore.Qt.LeftButton):
  237.             return
  238.         x = event.globalX()
  239.         y = event.globalY()
  240.         print x, y
  241.         self.selectItem(x, y)
  242.  
  243.     def selectItem(self, x, y):
  244.         selected = self.scene.itemAt(x,y)
  245.         print selected
  246.         if selected:
  247.             selected.setSelected(True)
  248.        
  249.  
  250.  
  251.  
  252.  
  253. def main():
  254.     app = QtGui.QApplication(sys.argv)
  255.     ex = Init()
  256.     sys.exit(app.exec_())
  257.  
  258.  
  259. if __name__ == '__main__':
  260.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement