From 089e8beb4eddb28c19de1b570ac765aee123280b Mon Sep 17 00:00:00 2001 From: Paul Chaplin Date: Tue, 2 Feb 2010 18:48:55 +0000 Subject: [PATCH] Drag and drop now works. PEP-8 compliance a bit closer. --- dialog-warning.png | Bin 554 -> 542 bytes trimage.py | 214 +++++++++++++++++++++++---------------------- ui.py | 40 +++++++-- 3 files changed, 144 insertions(+), 110 deletions(-) diff --git a/dialog-warning.png b/dialog-warning.png index 72e52d878f927e98c1794163556798eacc2ffa51..704f1d7304568d9c5c550107453f996117fd7d40 100644 GIT binary patch delta 186 zcmZ3*GLL0LE@S;1PZ!4!iE!UD-h9mpBCQYSaZf+Jy4TVC!N2WGU4$1iyU!I}l4&b^ zV!Hf`Lf@k+ZuQE=}TUo6P8w^qKWKcZb5> zY=t+ir;cn6X^?hV=yUQxzyg+e7fKc4g_Z0hSZ|p%ZEDun-^$x!^h;ACLN{eS!{ZL^ tjZX^wisP=8p8Q;L=<>$>`M3M|+gOy8Pgg}yX-M$v z25mX~*zMA*D@Mk*L!@1MykB1vxH;{3u5Q%aWfgB-{J!7PQ(d0=;+ox`O}#SHp0C|v zl=Dc{^~tlCsPAQS+!MbGO8$JKm)doivth=m@7Zhz-k-PcTB$bu)xNI|3=9kmp00i_ I>zopr0F8xY5C8xG diff --git a/trimage.py b/trimage.py index a0da5a9..d19a4cf 100644 --- a/trimage.py +++ b/trimage.py @@ -2,139 +2,144 @@ import sys from os import system from PyQt4.QtCore import * from PyQt4.QtGui import * - from hurry.filesize import * - from ui import Ui_trimage + +DEBUG = True + + class StartQT4(QMainWindow): - def __init__(self, parent=None): - QWidget.__init__(self, parent) - self.ui = Ui_trimage() - self.ui.setupUi(self) - self.quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self); # todo use standardKey Quit. - # set recompress to false - self.ui.recompress.setEnabled(False) - self.imagelist = [] - # connect signals with slots - QObject.connect(self.ui.addfiles, SIGNAL("clicked()"), self.file_dialog) - QObject.connect(self.ui.recompress, SIGNAL("clicked()"), self.recompress_files) - QObject.connect(self.quit_shortcut, SIGNAL("activated()"), qApp, SLOT('quit()')) - QObject.connect(self.ui.processedfiles, SIGNAL("dragEnterEvent()"), self.file_drop) + def __init__(self, parent=None): + QWidget.__init__(self, parent) + self.ui = Ui_trimage() + self.ui.setupUi(self) + # todo use standardKey Quit. + self.quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self) + # set recompress to false + self.ui.recompress.setEnabled(False) + self.imagelist = [] + # connect signals with slots + QObject.connect( + self.ui.addfiles, SIGNAL("clicked()"), self.file_dialog) + QObject.connect( + self.ui.recompress, SIGNAL("clicked()"), self.recompress_files) + QObject.connect( + self.quit_shortcut, SIGNAL("activated()"), qApp, SLOT('quit()')) + QObject.connect( + self.ui.processedfiles, SIGNAL("dragEnterEvent()"), self.file_drop) - def file_drop(self): - print "booya" + def file_drop(self): + print "booya" + def file_dialog(self): + fd = QFileDialog(self) + images = fd.getOpenFileNames( + self, + "Select one or more image files to compress", + "", # directory + "Image files (*.png *.jpg)") + for image in images: + self.compress_file(image) - def file_dialog(self): - fd = QFileDialog(self) - images = fd.getOpenFileNames(self, - "Select one or more image files to compress", - "", # directory - "Image files (*.png *.jpg)") - for image in images: - self.compress_file(image) + def enable_recompress(self): + self.ui.recompress.setEnabled(True) + def recompress_files(self): + imagelistcopy = self.imagelist + self.imagelist = [] + for image in imagelistcopy: + self.compress_file(image[-1]) - def enable_recompress(self): - self.ui.recompress.setEnabled(True) + def compress_file(self, filename): + print filename + oldfile = QFileInfo(filename) + name = oldfile.fileName() + oldfilesize = oldfile.size() + oldfilesizestr = size(oldfilesize, system=alternative) + if name.endsWith("jpg"): + runstr = 'jpegoptim --strip-all -f "' + str(filename) + '"' + runfile = system(runstr) - def recompress_files(self): - imagelistcopy = self.imagelist - self.imagelist = [] - for image in imagelistcopy: - self.compress_file(image[-1]) + elif name.endsWith("png"): + #runstr = ('optipng -force -o7 "' + str(filename) + #+ '"; advpng -z4 "' + str(filename) + '"') ## don't do advpng yet + runstr = 'optipng -force -o7 "' + str(filename) + '"' + runfile = system(runstr) + if runfile == 0: + newfile = QFile(filename) + newfilesize = newfile.size() + newfilesizestr = size(newfilesize, system=alternative) - def compress_file(self, filename): - print filename - oldfile = QFileInfo(filename); - name = oldfile.fileName() - oldfilesize = oldfile.size() - oldfilesizestr = size(oldfilesize, system=alternative) + ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100) + ratiostr = "%.1f%%" % ratio - if name.endsWith("jpg"): - runstr = 'jpegoptim --strip-all -f "' + str(filename) + '"' - runfile = system(runstr) + self.imagelist.append( + (name, oldfilesizestr, newfilesizestr, ratiostr, filename)) + self.update_table() - elif name.endsWith("png"): - #runstr = 'optipng -force -o7 "' + str(filename) + '"; advpng -z4 "' + str(filename) + '"' ## don't do advpng yet - runstr = 'optipng -force -o7 "' + str(filename) + '"' - runfile = system(runstr) + else: + print "uh. not good" #throw dialogbox error or something? - if runfile == 0: - newfile = QFile(filename) - newfilesize = newfile.size() - newfilesizestr = size(newfilesize, system=alternative) + def update_table(self): + tview = self.ui.processedfiles - ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100) - ratiostr = "%.1f%%" % ratio + # set table model + tmodel = tri_table_model(self, self.imagelist, + ['Filename', 'Old Size', 'New Size', 'Compressed']) + tview.setModel(tmodel) - self.imagelist.append((name, oldfilesizestr, newfilesizestr, ratiostr, filename)) - self.update_table() + # set minimum size of table + vh = tview.verticalHeader() + vh.setVisible(False) - else: - print "uh. not good" #throw dialogbox error or something? + # set horizontal header properties + hh = tview.horizontalHeader() + hh.setStretchLastSection(True) - - def update_table(self): - tview = self.ui.processedfiles - - # set table model - tmodel = tri_table_model(self, - self.imagelist, - ['Filename', 'Old Size', 'New Size', 'Compressed']) - tview.setModel(tmodel) - - # set minimum size of table - vh = tview.verticalHeader() - vh.setVisible(False) - - # set horizontal header properties - hh = tview.horizontalHeader() - hh.setStretchLastSection(True) - - # set all row heights - nrows = len(self.imagelist) - for row in range(nrows): - tview.setRowHeight(row, 25) - tview.setColumnWidth(0,300) - tview.setDragDropMode(QAbstractItemView.DropOnly) - tview.setAcceptDrops(True) - self.enable_recompress() + # set all row heights + nrows = len(self.imagelist) + for row in range(nrows): + tview.setRowHeight(row, 25) + tview.setColumnWidth(0, 300) + #tview.setDragDropMode(QAbstractItemView.DropOnly) + #tview.setAcceptDrops(True) + self.enable_recompress() class tri_table_model(QAbstractTableModel): - def __init__(self, parent, imagelist, header, *args): - """ - mydata is list of tuples - header is list of strings - tuple length has to match header length - """ - QAbstractTableModel.__init__(self, parent, *args) - self.imagelist = imagelist - self.header = header + + def __init__(self, parent, imagelist, header, *args): + """ + mydata is list of tuples + header is list of strings + tuple length has to match header length + """ + QAbstractTableModel.__init__(self, parent, *args) + self.imagelist = imagelist + self.header = header - def rowCount(self, parent): - return len(self.imagelist) + def rowCount(self, parent): + return len(self.imagelist) - def columnCount(self, parent): - return len(self.header) + def columnCount(self, parent): + return len(self.header) - def data(self, index, role): - if not index.isValid(): - return QVariant() - elif role != Qt.DisplayRole: - return QVariant() - return QVariant(self.imagelist[index.row()][index.column()]) + def data(self, index, role): + if not index.isValid(): + return QVariant() + elif role != Qt.DisplayRole: + return QVariant() + return QVariant(self.imagelist[index.row()][index.column()]) - def headerData(self, col, orientation, role): - if orientation == Qt.Horizontal and role == Qt.DisplayRole: - return QVariant(self.header[col]) - return QVariant() + def headerData(self, col, orientation, role): + if orientation == Qt.Horizontal and role == Qt.DisplayRole: + return QVariant(self.header[col]) + return QVariant() if __name__ == "__main__": @@ -142,4 +147,3 @@ if __name__ == "__main__": myapp = StartQT4() myapp.show() sys.exit(app.exec_()) - diff --git a/ui.py b/ui.py index 198ab61..f084113 100644 --- a/ui.py +++ b/ui.py @@ -8,6 +8,36 @@ # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui +from PyQt4.QtCore import QUrl, QString +import trimage + + +class TrimageTableView(QtGui.QTableView): + def __init__(self, parent=None): + super(TrimageTableView, self).__init__(parent) + self.setAcceptDrops(True) + + def dragEnterEvent(self, event): + if event.mimeData().hasFormat("text/uri-list"): + if trimage.DEBUG: + print("Accepting event: %s" % list(event.mimeData().formats())) + event.accept() + else: + if trimage.DEBUG: + print("Rejecting event: %s" % list(event.mimeData().formats())) + event.ignore() + + def dragMoveEvent(self, event): + event.accept() + + def dropEvent(self, event): + files = str(event.mimeData().data("text/uri-list")).strip().split() + for i, file in enumerate(files): + files[i] = QUrl(QString(file)).toLocalFile() + if trimage.DEBUG: + for file in files: + print("Drop received: %s" % file) + class Ui_trimage(object): def setupUi(self, trimage): @@ -88,18 +118,18 @@ class Ui_trimage(object): self.horizontalLayout.addWidget(self.recompress) self.verticalLayout_2.addLayout(self.horizontalLayout) - self.processedfiles = QtGui.QTableView(self.frame) + self.processedfiles = TrimageTableView(self.frame) self.processedfiles.setEnabled(True) - self.processedfiles.setAcceptDrops(True) - self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly) +# self.processedfiles.setAcceptDrops(True) +# self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly) self.processedfiles.setFrameShape(QtGui.QFrame.NoFrame) self.processedfiles.setFrameShadow(QtGui.QFrame.Plain) self.processedfiles.setLineWidth(0) self.processedfiles.setMidLineWidth(0) self.processedfiles.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.processedfiles.setTabKeyNavigation(True) - self.processedfiles.setDragEnabled(False) - self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly) +# self.processedfiles.setDragEnabled(True) +# self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly) self.processedfiles.setAlternatingRowColors(True) self.processedfiles.setTextElideMode(QtCore.Qt.ElideRight) self.processedfiles.setShowGrid(True)