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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
|
#!/usr/bin/env python
#
# 2005-02-12 initial version hp
import os
import pickle
from qt import *
from dirview import Directory, DirectoryView
bookmarks = [
"22 14 8 1",
"# c #000080",
"a c #585858",
"b c #000000",
"c c #ffffff",
"d c #ffffff",
"e c #ffffff",
"f c #000000",
". c None",
"...bb.................",
"..bacb....bbb.........",
"..badcb.bbccbab.......",
"..bacccbadccbab.......",
"..baecdbcccdbab.......",
"..bacccbacccbab.......",
"..badcdbcecdfab.......",
"..bacecbacccbab.......",
"..baccdbcccdbab.......",
"...badcbacdbbab.......",
"....bacbcbbccab.......",
".....babbaaaaab.......",
".....bbabbbbbbb.......",
"......bb.............."
]
home = [
"16 15 4 1",
"# c #000000",
"a c #ffffff",
"b c #c0c0c0",
". c None",
".......##.......",
"..#...####......",
"..#..#aabb#.....",
"..#.#aaaabb#....",
"..##aaaaaabb#...",
"..#aaaaaaaabb#..",
".#aaaaaaaaabbb#.",
"###aaaaaaaabb###",
"..#aaaaaaaabb#..",
"..#aaa###aabb#..",
"..#aaa#.#aabb#..",
"..#aaa#.#aabb#..",
"..#aaa#.#aabb#..",
"..#aaa#.#aabb#..",
"..#####.######.."
]
class PixmapView(QScrollView):
def __init__(self, parent):
QScrollView.__init__(self, parent)
self.pixmap = None
self.viewport().setBackgroundMode(self.PaletteBase)
def setPixmap(self, pix):
self.pixmap = pix
self.resizeContents(pix.size().width(), pix.size().height())
self.viewport().repaint(False)
def drawContents(self, p, cx, cy, cw, ch):
p.fillRect(cx, cy, cw, ch, self.colorGroup().brush(QColorGroup.Base))
p.drawPixmap(0, 0, self.pixmap)
class Preview(QWidgetStack):
def __init__(self, parent):
QWidgetStack.__init__(self, parent)
self.normalText = QMultiLineEdit(self)
self.normalText.setReadOnly(True)
self.html = QTextView(self)
self.pixmap = PixmapView(self)
self.raiseWidget(self.normalText)
def showPreview(self, url, size):
if url.isLocalFile():
path = url.path()
fi = QFileInfo(path)
if fi.isFile() and fi.size() > size * 1000:
self.normalText.setText(
"The File\n%s\nis too large, so I don't show it!" % path)
self.raiseWidget(self.normalText)
return
pix = QPixmap(path)
if pix.isNull():
if fi.isFile():
err = False
try:
text = open(path.latin1(), "r").read()
except IOError, msg:
text = QString(str(msg))
err = True
if not err and fi.extension().lower().contains("htm"):
url = self.html.mimeSourceFactory().makeAbsolute(
path, self.html.context())
self.html.setText(text, url)
self.raiseWidget(self.html)
return
else:
self.normalText.setText(text)
self.raiseWidget(self.normalText)
return
else:
self.normalText.setText("")
self.raiseWidget(self.normalText)
else:
self.pixmap.setPixmap(pix)
self.raiseWidget(self.pixmap)
else:
self.normalText.setText("I only show local files!")
self.raiseWidget(self.normalText)
# We can't instantiate QFilePreview directly because it is abstract. Note that
# the previewUrl() abstract is patched in later to work around the fact that
# you can't multiply inherit from more than one wrapped class.
class FilePreview(QFilePreview):
pass
class PreviewWidget(QVBox):
def __init__(self, parent):
QVBox.__init__(self, parent)
self.setSpacing( 5 )
self.setMargin( 5 )
row = QHBox(self)
row.setSpacing(5)
QLabel("Only show files smaller than: ", row)
self.sizeSpinBox = QSpinBox(1, 10000, 1, row)
self.sizeSpinBox.setSuffix(" KB")
self.sizeSpinBox.setValue(128)
row.setFixedHeight(10 + self.sizeSpinBox.sizeHint().height())
self.__preview = Preview(self)
# workaround sip inability of multiple inheritance
# create a local QFilePreview instance and redirect
# the method, which is called on preview, to us
self.preview = FilePreview()
self.preview.previewUrl = self.previewUrl
def previewUrl(self, url):
self.__preview.showPreview(url, self.sizeSpinBox.value())
class CustomFileDialog(QFileDialog):
def __init__(self, preview = False):
QFileDialog.__init__(self, None, None, True)
self.bookmarkFile = ".pybookmarks"
self.bookmarkList = []
if os.path.exists(self.bookmarkFile):
try:
self.bookmarkList = pickle.loads(open(self.bookmarkFile, "rb").read())
except IOError, msg:
print msg
self.setDir("/")
self.dirView = DirectoryView(self, None, True)
self.dirView.addColumn("")
self.dirView.header().hide()
root = Directory(self.dirView, "/")
root.setOpen(True)
self.dirView.setFixedWidth(200)
self.addLeftWidget(self.dirView)
p = QPushButton(self)
p.setPixmap(QPixmap(bookmarks))
QToolTip.add(p, "Bookmarks")
self.bookmarkMenu = QPopupMenu(self)
self.connect(self.bookmarkMenu, SIGNAL("activated(int)"),
self.bookmarkChosen)
self.addId = self.bookmarkMenu.insertItem("Add bookmark")
self.bookmarkMenu.insertSeparator()
for l in self.bookmarkList:
self.bookmarkMenu.insertItem(l)
p.setPopup(self.bookmarkMenu)
self.addToolButton(p, True)
self.connect(self.dirView, PYSIGNAL("folderSelected(const QString &)"),
self.setDir2)
self.connect(self, SIGNAL("dirEntered(const QString &)"),
self.dirView.setDir)
b = QToolButton(self)
QToolTip.add(b, "Go Home!")
b.setPixmap(QPixmap(home))
self.connect(b, SIGNAL("clicked()"), self.goHome)
self.addToolButton(b)
if preview:
self.setContentsPreviewEnabled(True)
pw = PreviewWidget(self)
self.setContentsPreview(pw, pw.preview)
self.setViewMode(QFileDialog.List)
self.setPreviewMode(QFileDialog.Contents)
w = self.width()
h = self.height()
if preview:
self.resize(w + w / 2, h + h / 3)
else:
self.resize(w + w / 3, h + h / 4)
def done(self, r):
if self.bookmarkList:
try:
open(self.bookmarkFile, "wb").write(pickle.dumps(self.bookmarkList))
except IOError, msg:
print msg
return QFileDialog.done(self, r)
def showEvent(self, e):
QFileDialog.showEvent(self, e)
self.dirView.setDir(self.dirPath())
def setDir2(self, path):
self.blockSignals(True)
self.setDir(path)
self.blockSignals(False)
def bookmarkChosen(self, i):
if i == self.addId:
# keep bookmarks pythonic
dp = self.dirPath().latin1()
if dp not in self.bookmarkList:
self.bookmarkList.append(dp)
self.bookmarkMenu.insertItem(dp)
else:
self.setDir(self.bookmarkMenu.text(i))
def goHome(self):
if os.getenv("HOME"):
self.setDir(os.getenv("HOME"))
else:
self.setDir("/")
if __name__ == '__main__':
import sys
import getopt
def usage(msg = None):
if msg:
print >> sys.stderr, msg
print >> sys.stderr, """\
usage: qdir [--any | --dir | --custom] [--preview] [--default f] {--filter f} [caption ...]
--any Get any filename, need not exist.
--dir Return a directory rather than a file.
--custom Opens a customized QFileDialog with
dir browser, bookmark menu, etc.
--preview Show a preview widget.
--default f Start from directory/file f.
--filter f eg. '*.gif' '*.bmp'
caption ... Caption for dialog.
"""
sys.exit(1)
def main():
options = ["help", "any", "dir", "custom", "preview", "default=", "filter="]
mode = QFileDialog.ExistingFile
preview = False
custom = False
start = None
filter = QString.null
app = QApplication(sys.argv)
try:
optlist, args = getopt.getopt(sys.argv[1:], "h", options)
except getopt.error, msg:
usage(msg)
for opt, par in optlist:
if opt in ("-h", "--help"):
usage()
elif opt == "--any":
mode = QFileDialog.AnyFile
elif opt == "--dir":
mode = QFileDialog.Directory
elif opt == "--default":
start = par
elif opt == "--filter":
filter = par
elif opt == "--preview":
preview = True
elif opt == "--custom":
custom = True
if args:
caption = " ".join(args)
elif mode == QFileDialog.Directory:
caption = "Choose directory..."
else:
caption = "Choose file..."
if not start:
start = QDir.currentDirPath()
if not custom:
fd = QFileDialog(QString.null, filter, None, None, True)
fd.setMode(mode)
if preview:
fd.setContentsPreviewEnabled(True)
pw = PreviewWidget(fd)
fd.setContentsPreview(pw, pw.preview)
fd.setViewMode(QFileDialog.List)
fd.setPreviewMode(QFileDialog.Contents)
w = fd.width()
h = fd.height()
fd.resize(w + w / 3, h + h / 4)
fd.setCaption(caption)
fd.setSelection(start)
if fd.exec_loop() == QDialog.Accepted:
print "%s\n" % fd.selectedFile().latin1()
return 0
else:
return 1
else:
fd = CustomFileDialog(preview)
fd.exec_loop()
return 1
sys.exit(main())
|