summaryrefslogtreecommitdiffstats
path: root/examples/tqdir.py
blob: 99875d0a70c8418e5a644562187ec03c5f93e437 (plain)
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
324
#!/usr/bin/env python
#
# 2005-02-12    initial version    hp

from __future__ import print_function
import os
import pickle
from PyTQt.tqt 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(TQScrollView):
    def __init__(self, parent):
        TQScrollView.__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(TQColorGroup.Base))
        p.drawPixmap(0, 0, self.pixmap)


class Preview(TQWidgetStack):
    def __init__(self, parent):
        TQWidgetStack.__init__(self, parent)
        self.normalText = TQMultiLineEdit(self)
        self.normalText.setReadOnly(True)
        self.html = TQTextView(self)
        self.pixmap = PixmapView(self)
        self.raiseWidget(self.normalText)

    def showPreview(self, url, size):
        if url.isLocalFile():
            path = url.path()
            fi = TQFileInfo(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 = TQPixmap(path)
            if pix.isNull():
                if fi.isFile():
                    err = False
                    try:
                        text = open(path.latin1(), "r").read()
                    except IOError as msg:
                        text = TQString(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 TQFilePreview 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(TQFilePreview):
    pass


class PreviewWidget(TQVBox):
    def __init__(self, parent):
        TQVBox.__init__(self, parent)
        self.setSpacing( 5 )
        self.setMargin( 5 )
        row = TQHBox(self)
        row.setSpacing(5)
        TQLabel("Only show files smaller than: ", row)
        self.sizeSpinBox = TQSpinBox(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 TQFilePreview 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(TQFileDialog):
    def __init__(self, preview = False):
        TQFileDialog.__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 as 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 = TQPushButton(self)
        p.setPixmap(TQPixmap(bookmarks))
        TQToolTip.add(p, "Bookmarks")
        self.bookmarkMenu = TQPopupMenu(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 TQString &)"),
             self.setDir2)
        self.connect(self, SIGNAL("dirEntered(const TQString &)"),
             self.dirView.setDir)
        b = TQToolButton(self)
        TQToolTip.add(b, "Go Home!")
        b.setPixmap(TQPixmap(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(TQFileDialog.List)
            self.setPreviewMode(TQFileDialog.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 as msg:
                print(msg)
        return TQFileDialog.done(self, r)

    def showEvent(self, e):
        TQFileDialog.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(msg, file=sys.stderr)
        print("""\
usage: tqdir [--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 TQFileDialog 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.
""", file=sys.stderr)
        sys.exit(1)

    def main():
        options = ["help", "any", "dir", "custom", "preview", "default=", "filter="]
        mode = TQFileDialog.ExistingFile
        preview = False
        custom = False
        start = None
        filter = TQString.null
        app = TQApplication(sys.argv)
    
        try:
            optlist, args = getopt.getopt(sys.argv[1:], "h", options)
        except getopt.error as msg:
            usage(msg)
    
        for opt, par in optlist:
            if opt in ("-h", "--help"):
                usage()
            elif opt == "--any":
                mode = TQFileDialog.AnyFile
            elif opt == "--dir":
                mode = TQFileDialog.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 == TQFileDialog.Directory:
            caption = "Choose directory..."
        else:
            caption = "Choose file..."
        if not start:
            start = TQDir.currentDirPath()
        if not custom:
            fd = TQFileDialog(TQString.null, filter, None, None, True)
            fd.setMode(mode)
            if preview:
                fd.setContentsPreviewEnabled(True)
                pw = PreviewWidget(fd)
                fd.setContentsPreview(pw, pw.preview)
                fd.setViewMode(TQFileDialog.List)
                fd.setPreviewMode(TQFileDialog.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() == TQDialog.Accepted:
                print("%s\n" % fd.selectedFile().latin1())
                return 0
            else:
                return 1
        else:
            fd = CustomFileDialog(preview)
            fd.exec_loop()
        return 1

    sys.exit(main())