implement threading

This commit is contained in:
Kilian Valkhof 2010-02-04 11:57:40 +01:00
parent 64883dffd2
commit 0e928e496b

View file

@ -17,6 +17,9 @@ DEBUG = True
#init imagelist #init imagelist
imagelist = [] imagelist = []
# show application on load (or not if there are command line options)
showapp = True
class StartQT4(QMainWindow): class StartQT4(QMainWindow):
def __init__(self, parent=None): def __init__(self, parent=None):
@ -29,12 +32,14 @@ class StartQT4(QMainWindow):
# disable recompress # disable recompress
self.ui.recompress.setEnabled(False) self.ui.recompress.setEnabled(False)
# show application on load (or not if there are command line options)
self.showapp = True
# activate command line options # activate command line options
self.commandline_options() self.commandline_options()
# make a worker thread
self.thread = Worker()
# connect signals with slots # connect signals with slots
QObject.connect(self.ui.addfiles, SIGNAL("clicked()"), QObject.connect(self.ui.addfiles, SIGNAL("clicked()"),
self.file_dialog) self.file_dialog)
@ -44,6 +49,9 @@ class StartQT4(QMainWindow):
qApp, SLOT('quit()')) qApp, SLOT('quit()'))
QObject.connect(self.ui.processedfiles, SIGNAL("fileDropEvent"), QObject.connect(self.ui.processedfiles, SIGNAL("fileDropEvent"),
self.file_drop) self.file_drop)
QObject.connect(self.thread, SIGNAL("finished()"), self.update_table)
QObject.connect(self.thread, SIGNAL("terminated()"), self.update_table)
QObject.connect(self.thread, SIGNAL("updateUi"), self.update_table)
def commandline_options(self): def commandline_options(self):
"""Set up the command line options.""" """Set up the command line options."""
@ -68,25 +76,24 @@ class StartQT4(QMainWindow):
def dir_from_cmd(self, directory): def dir_from_cmd(self, directory):
"""Read the files in the directory and send all files to """Read the files in the directory and send all files to
compress_file.""" compress_file."""
self.showapp = False showapp = False
imagedir = listdir(directory) imagedir = listdir(directory)
for image in imagedir: for image in imagedir:
image = path.join(directory, image) image = path.join(directory, image)
name = QFileInfo(image).fileName() self.delegator(imagedir)
if self.checkname(name):
self.compress_file(image)
def file_from_cmd(self, image): def file_from_cmd(self, image):
"""Get the file and send it to compress_file""" """Get the file and send it to compress_file"""
self.showapp = False showapp = False
if self.checkname(image): filecmdlist = []
self.compress_file(image) filecmdlist.append(image)
self.delegator(filecmdlist)
def file_drop(self, image): def file_drop(self, image):
"""Get a file from the drag and drop handler and send it to """Get a file from the drag and drop handler and send it to
compress_file.""" compress_file."""
if self.checkname(image): if self.checkname(image):
self.compress_file(image) self.delegator(image)
def file_dialog(self): def file_dialog(self):
"""Open a file dialog and send the selected images to compress_file.""" """Open a file dialog and send the selected images to compress_file."""
@ -96,74 +103,29 @@ class StartQT4(QMainWindow):
"", # directory "", # directory
# this is a fix for file dialog differenciating between cases # this is a fix for file dialog differenciating between cases
"Image files (*.png *.jpg *.jpeg *.PNG *.JPG *.JPEG)") "Image files (*.png *.jpg *.jpeg *.PNG *.JPG *.JPEG)")
for image in images: self.delegator(images)
if self.checkname(image):
self.compress_file(image)
def recompress_files(self): def recompress_files(self):
"""Send each file in the current file list to compress_file again.""" """Send each file in the current file list to compress_file again."""
imagelistcopy = imagelist self.delegator(imagelist)
imagelist = []
for image in imagelistcopy:
self.compress_file(image[-1])
""" """
Compress functions Compress functions
""" """
def compress_file(self, filename): def delegator(self, images):
"""Compress the given file, get data from it and call update_table.""" delegatorlist = []
for image in images:
if self.checkname(image):
delegatorlist.append((image, QIcon(image)))
self.thread.compress_file(delegatorlist)
#gather old file data
oldfile = QFileInfo(filename)
name = oldfile.fileName()
oldfilesize = oldfile.size()
oldfilesizestr = size(oldfilesize, system=alternative)
#decide with tool to use
if path.splitext(str(filename))[1].lower() in [".jpg", ".jpeg"]:
runstr = 'jpegoptim -f --strip-all "' + str(filename) + '"'
try:
retcode = call(runstr, shell=True, stdout=PIPE)
runfile = retcode
except OSError, e:
runfile = e
elif path.splitext(str(filename))[1].lower() in [".png"]:
runstr = ('optipng -force -o7 "' + str(filename)
+ '"; advpng -z4 "' + str(filename) + '"')
try:
retcode = call(runstr, shell=True, stdout=PIPE)
runfile = retcode
except OSError, e:
runfile = e
if runfile == 0:
#gather new file data
newfile = QFile(filename)
newfilesize = newfile.size()
newfilesizestr = size(newfilesize, system=alternative)
#calculate ratio and make a nice string
ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100)
ratiostr = "%.1f%%" % ratio
# append current image to list
imagelist.append(
(name, oldfilesizestr, newfilesizestr, ratiostr, filename, QIcon(filename)))
self.update_table()
if self.showapp != True:
# we work via the commandline
print("File:" + filename + ", Old Size:" + oldfilesizestr +
", New Size:" + newfilesizestr + ", Ratio:" + ratiostr)
else:
# TODO nice error recovery
print("uh. not good")
""" """
UI Functions UI Functions
""" """
def update_table(self): def update_table(self):
"""Update the table view with the latest file data.""" """Update the table view with the latest file data."""
tview = self.ui.processedfiles tview = self.ui.processedfiles
# set table model # set table model
tmodel = TriTableModel(self, imagelist, tmodel = TriTableModel(self, imagelist,
["Filename", "Old Size", "New Size", "Compressed"]) ["Filename", "Old Size", "New Size", "Compressed"])
@ -187,6 +149,7 @@ class StartQT4(QMainWindow):
# enable recompress button # enable recompress button
self.enable_recompress() self.enable_recompress()
""" """
Helper functions Helper functions
""" """
@ -235,16 +198,84 @@ class TriTableModel(QAbstractTableModel):
def headerData(self, col, orientation, role): def headerData(self, col, orientation, role):
"""Get header data.""" """Get header data."""
if orientation == Qt.Horizontal and (role == Qt.DisplayRole or role == Qt.DecorationRole): if orientation == Qt.Horizontal and (role == Qt.DisplayRole or
role == Qt.DecorationRole):
return QVariant(self.header[col]) return QVariant(self.header[col])
return QVariant() return QVariant()
class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.exiting = False
def __del__(self):
self.exiting = True
self.wait()
def compress_file(self, images):
self.images = images
self.start()
def run(self):
"""Compress the given file, get data from it and call update_table."""
for image in self.images:
#gather old file data
filename = image[0]
icon = image[1]
oldfile = QFileInfo(filename)
name = oldfile.fileName()
oldfilesize = oldfile.size()
oldfilesizestr = size(oldfilesize, system=alternative)
#decide with tool to use
if path.splitext(str(filename))[1].lower() in [".jpg", ".jpeg"]:
runstr = 'jpegoptim -f --strip-all "' + str(filename) + '"'
try:
retcode = call(runstr, shell=True, stdout=PIPE)
runfile = retcode
except OSError, e:
runfile = e
elif path.splitext(str(filename))[1].lower() in [".png"]:
runstr = ('optipng -force -o7 "' + str(filename)
+ '"; advpng -z4 "' + str(filename) + '"')
try:
retcode = call(runstr, shell=True, stdout=PIPE)
runfile = retcode
except OSError, e:
runfile = e
if runfile == 0:
#gather new file data
newfile = QFile(filename)
newfilesize = newfile.size()
newfilesizestr = size(newfilesize, system=alternative)
#calculate ratio and make a nice string
ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100)
ratiostr = "%.1f%%" % ratio
# append current image to list
imagelist.append((name, oldfilesizestr, newfilesizestr, ratiostr,
filename, icon))
self.emit(SIGNAL("updateUi"))
if showapp != True:
# we work via the commandline
print("File:" + filename + ", Old Size:" + oldfilesizestr +
", New Size:" + newfilesizestr + ", Ratio:" + ratiostr)
else:
# TODO nice error recovery
print("uh. not good")
if __name__ == "__main__": if __name__ == "__main__":
app = QApplication(sys.argv) app = QApplication(sys.argv)
myapp = StartQT4() myapp = StartQT4()
if myapp.showapp: if showapp:
# no command line options called # no command line options called
myapp.show() myapp.show()
else: else: