-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilelistmodel.py
More file actions
213 lines (155 loc) · 7.47 KB
/
filelistmodel.py
File metadata and controls
213 lines (155 loc) · 7.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# -*- coding: utf-8 -*-
# Copyright (c) 2011--2012 Peter Dinges <pdinges@acm.org>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Standard Python imports.
import os
import os.path
import sys
# Package imports.
from PyQt4 import QtCore, QtGui
# The one MIME type this model supports: a '|'-separated list of row indices.
ROW_MIME_TYPE = "x-application/shellgame-sorter-rows"
class ImageListModel(QtCore.QAbstractListModel):
"""An image file name list model that supports arranging the images
in arbitrary order. Orders can be imported and exported as lists.
Beside the programmatic reordering, the model implements manual
arrangement via drag and drop move actions: moving an item A onto
another item B places A before B in the list.
"""
def __init__(self, path, extensions, order=None, parent=None):
QtCore.QAbstractListModel.__init__(self, parent)
self._path = os.path.abspath(str(path))
self._extensions = extensions
# Load existing
def isImage(f):
if not os.path.isfile(os.path.join(self._path, f)):
return False
for e in extensions:
if f.lower().endswith("." + e):
return True
return False
try:
self._files = [ QtCore.QFileInfo(os.path.join(self._path, f))
for f in os.listdir(self._path) if isImage(f) ]
except (OSError, IOError) as e:
msg = "WARNING: Cannot read images from path '{0}'.\n"
sys.stderr.write(msg.format(self._path))
self._files = []
if order:
self.order(order)
self.__thumbnailCache = QtGui.QPixmapCache()
def images(self):
"""Get the list of file information objects in their current order."""
return self._files[:]
def image_names(self):
"""Get the list of image names in their current order."""
return [ f.fileName() for f in self._files ]
def order(self, order):
"""Arrange the model's image file names in the given order.
Invalid (non-existing) files will be ignored; files not mentioned
are moved to the end of the list keeping their relative
current order.
"""
self.beginResetModel()
# Map file names to ranks in the given order
ranking = dict([ (f, i) for i, f in enumerate(order) ])
l = len(ranking)
def cmp(f1, f2):
# Compare tuples (new rank, old rank)
r1 = ranking.get(f1.fileName(), l + self._files.index(f1))
r2 = ranking.get(f2.fileName(), l + self._files.index(f2))
if r1 < r2:
return -1
elif r1 == r2:
return 0
else:
return 1
self._files = list(sorted(self._files[:], cmp=cmp))
self.endResetModel()
def rowCount( self, parent = QtCore.QModelIndex() ):
return len( self._files )
def data( self, index, role = QtCore.Qt.DisplayRole ):
if not index.isValid() or index.row() >= len(self._files):
return QtCore.QVariant()
fileInfo = self._files[ index.row() ]
if role == QtCore.Qt.DisplayRole:
return QtCore.QVariant( fileInfo.fileName() )
elif role == QtCore.Qt.DecorationRole:
thumbnail = self.__thumbnailCache.find(fileInfo.absoluteFilePath())
if not thumbnail:
# The thumbnail is a centered square with maximal sides.
pixmap = QtGui.QPixmap(fileInfo.absoluteFilePath())
pixmap = pixmap.scaled(100, 100, QtCore.Qt.KeepAspectRatioByExpanding)
quad = QtCore.QRect(0, 0, 100, 100)
quad.moveCenter(QtCore.QPoint(pixmap.width() / 2, pixmap.height() / 2))
thumbnail = pixmap.copy(quad)
self.__thumbnailCache.insert(fileInfo.absoluteFilePath(), thumbnail)
return QtCore.QVariant( thumbnail )
return QtCore.QVariant()
#- Drag and Drop ----------------------------------------------------------
def flags(self, index):
f = QtCore.QAbstractListModel.flags(self, index)
if index.isValid():
f |= QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled
return f
def supportedDragActions(self):
return QtCore.Qt.MoveAction
def supportedDropActions(self):
return QtCore.Qt.MoveAction
def mimeTypes(self):
"""List the supported MIME types. This model only exports
'|'-separated lists of row numbers in the model.
"""
# Drag and drop ceases to work if the custom MIME type is not announced.
return [ ROW_MIME_TYPE ]
def mimeData(self, indexes):
mimeData = QtCore.QMimeData()
rowString = "|".join([ str(i.row()) for i in indexes if i.isValid() ])
mimeData.setData(ROW_MIME_TYPE, rowString)
return mimeData
def dropMimeData(self, data, action, row, column, parentIndex):
"""Insert the items with the listed row numbers before the parentIndex.
Their current relative order is preserved. An invalid parentIndex
moves the items to the end of the list.
"""
if action == QtCore.Qt.IgnoreAction:
return True
if column > 0:
return False
# An invalid parent index will move the items to the end of the list.
if parentIndex.isValid():
targetRow = parentIndex.row()
else:
targetRow = self.rowCount()
if data and data.hasFormat(ROW_MIME_TYPE):
sourceRows = [ int(r) for r in data.data(ROW_MIME_TYPE).split("|") ]
sourceItems = [ self._files[r] for r in sourceRows ]
for sourceRow in sorted(sourceRows, reverse=True):
self.beginRemoveRows(QtCore.QModelIndex(), sourceRow, sourceRow)
del self._files[sourceRow]
self.endRemoveRows()
if sourceRow < targetRow:
targetRow -= 1
self.beginInsertRows(QtCore.QModelIndex(), targetRow, targetRow + len(sourceItems))
self._files = self._files[:targetRow] + sourceItems + self._files[targetRow:]
self.endInsertRows()
return True
return False