/
treefilebrowser.py
489 lines (381 loc) · 16.2 KB
/
treefilebrowser.py
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# -*- coding: utf-8 -*-
"""
TreeFileBrowser a tree-like Gtk file browser
Copyright (C) 2006-2008 Adolfo González Blázquez <code@infinicode.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
If you find any bugs or have any suggestions email: code@infinicode.org
"""
#try:
# import pyGtk
# pyGtk.require('2.0')
#except:
# print "PyGtk 2.0 or later required for this app to run"
# raise SystemExit
#try:
# import Gtk
# import GObject
#except:
# raise SystemExit
#from gettext import gettext as _
from gi.repository import GObject, Gtk
try:
from os import path as ospath
import dircache
except:
raise SystemExit
class TreeFileBrowser(GObject.GObject):
""" A widget that implements a tree-like file browser, like the
one used on Nautilus spatial view in list mode """
__gproperties__ = {
'show-hidden': (GObject.TYPE_BOOLEAN, 'show hidden files',
'show hidden files and folders', False, GObject.PARAM_READWRITE),
'show-only-dirs': (GObject.TYPE_BOOLEAN, 'show only directories',
'show only directories, not files', True, GObject.PARAM_READWRITE),
'rules-hint': (GObject.TYPE_BOOLEAN, 'rules hint',
'show rows background in alternate colors', True, GObject.PARAM_READWRITE),
'root': (GObject.TYPE_STRING, 'initial path',
'initial path selected on tree browser', '/', GObject.PARAM_READWRITE)
}
__gsignals__ = { 'row-expanded' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,)),
'cursor-changed' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,))
}
def __init__(self, root=None):
""" Path is where we wan the tree initialized """
GObject.GObject.__init__(self)
self.show_hidden = False
self.show_only_dirs = True
self.show_rules_hint = True
self.root = '/'
if root != None and ospath.isdir(root): self.root = root
#elif root != None: print "ERROR: %s doesn't exist." % root
self.view, self.scrolled = self.make_view()
self.create_new()
self.create_popup()
#####################################################
# Accessors and Mutators
def do_get_property(self, property):
""" GObject get_property method """
if property.name == 'show-hidden':
return self.show_hidden
elif property.name == 'show-only-dirs':
return self.show_only_dirs
elif property.name == 'rules-hint':
return self.show_rules_hint
elif property.name == 'path':
return self.root
else:
raise AttributeError, 'unknown property %s' % property.name
def do_set_property(self, property, value):
""" GObject set_property method """
if property.name == 'show-hidden':
self.show_hidden = value
elif property.name == 'show-only-dirs':
self.show_only_dirs = value
elif property.name == 'rules-hint':
self.show_rules_hint = value
elif property.name == 'path':
self.root = value
else:
raise AttributeError, 'unknown property %s' % property.name
def get_view(self):
return self.view
def get_scrolled(self):
return self.scrolled
def set_show_hidden(self, hidden):
self.show_hidden = hidden
activedir = self.get_selected()
self.create_new()
if activedir != None:
if "/." in activedir: self.set_active_dir(self.root)
else: self.set_active_dir(activedir)
self.hidden_check_menu.set_active(hidden)
def get_show_hidden(self):
return self.show_hidden
def set_rules_hint(self, rules):
self.show_rules_hint = rules
self.view.set_rules_hint(rules)
def get_rules_hint(self):
return self.show_rules_hint
def set_show_only_dirs(self, only_dirs):
self.show_only_dirs = only_dirs
self.create_new()
def get_show_only_dirs(self):
return self.show_only_dirs
def get_selected(self):
""" Returns selected item in browser """
model, iter = self.view.get_selection().get_selected()
if iter != None:
return model.get_value(iter, 2)
else:
return None
#####################################################
# Callbacks
def row_expanded(self, treeview, iter, path):
""" CALLBACK: a row is expanded """
model = treeview.get_model()
model.set_value(iter, 0, self.get_folder_opened_icon())
self.get_file_list(model, iter, model.get_value(iter,2))
self.remove_empty_child(model, iter)
# Send signal with path of expanded row
self.emit('row-expanded', model.get_value(iter,2))
def row_collapsed(self, treeview, iter, path):
""" CALLBACK: a row is collapsed """
model = treeview.get_model()
model.set_value(iter, 0, self.get_folder_closed_icon())
while model.iter_has_child(iter):
child = model.iter_children(iter)
model.remove(child)
self.add_empty_child(model, iter)
def row_activated(self, treeview, path, view_column):
""" CALLBACK: row activated using return, double-click, shift-right, etc. """
if treeview.row_expanded(path):
treeview.collapse_row(path)
else:
treeview.expand_row(path, False)
def cursor_changed(self, treeview):
""" CALLBACK: a new row has been selected """
model, iter = treeview.get_selection().get_selected()
# Send signal with path of expanded row
if iter == None:
path = treeview.get_cursor()[0]
iter = self.model.get_iter(path)
self.emit('cursor-changed', model.get_value(iter,2))
def button_pressed(self, widget, event):
""" CALLBACK: clicked on widget """
if event.button == 3:
x = int(event.x)
y = int(event.y)
time = event.time
pthinfo = self.view.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
#self.view.grab_focus()
#self.view.set_cursor( path, col, 0)
self.popup.popup( None, None, None, event.button, time)
return 1
def show_hidden_toggled(self, widget):
""" CALLBACK: Show hidden files on context menu toggled """
state = widget.get_active()
self.set_show_hidden(state)
#####################################################
# Directories and files, nodes and icons
def set_cursor_on_first_row(self):
model = self.view.get_model()
iter = model.get_iter_root()
path = model.get_path(iter)
self.view.set_cursor(path)
def check_active_dir(self, directory):
rootdir = self.root
if not ospath.isdir(directory):
return False
if not (rootdir in directory):
return False
if directory == rootdir:
return True
return True
def set_active_dir(self, directory):
rootdir = self.root
# Expand root
model = self.view.get_model()
iter = model.get_iter_root()
path = model.get_path(iter)
self.view.expand_row(path, False)
iter = model.iter_children(iter)
# Add trailing / to paths
if len(directory) > 1 and directory[-1] != '/': directory += '/'
if len(rootdir) > 1 and rootdir[-1] != '/': rootdir += '/'
if not ospath.isdir(directory):
#print "ERROR: %s doesn't exist." % directory
self.set_cursor_on_first_row()
return False
if not (rootdir in directory):
#print "ERROR: %s is not on root path." % directory
self.set_cursor_on_first_row()
return False
if directory == rootdir:
self.set_cursor_on_first_row()
return True
else:
# Now we check if the desired dir is valid
# Convert the given '/home/user/dir/' to ['/', 'home/', 'user/', 'dir/']
if len(directory) > 1:
dirtree = directory.split('/')
dirtree.pop(-1)
else: dirtree = ['/']
if len(dirtree) > 1:
dirtree[0] = '/'
for i in range(len(dirtree)-1): dirtree[i+1] = dirtree[i+1] + '/'
# Convert root to '/home/user/dir/' to ['/', 'home/', 'user/', 'dir/']
if len(rootdir) > 1:
roottree = rootdir.split('/')
roottree.pop(-1)
else: roottree = ['/']
if len(roottree) > 1:
roottree[0] = '/'
for i in range(len(roottree)-1): roottree[i+1] = roottree[i+1] + '/'
# Check if the dir is in the same path as the desired root
long = len(roottree)
for i in range(long):
if roottree[i] != dirtree[i]: return False
# End checking
# Star expanding
# Count how many iterations we need
depth = len(dirtree) - len(roottree)
# Expand baby expand!
exp = len(roottree)
for i in range(depth):
newpath = dirtree[i+exp]
if iter == None: continue
val = model.get_value(iter, 1).replace('/','') + '/'
while val != newpath:
iter = model.iter_next(iter)
val = model.get_value(iter, 1).replace('/','') + '/'
path = model.get_path(iter)
self.view.expand_row(path, False)
iter = model.iter_children(iter)
# Don't expand last row
self.view.collapse_row(path)
# Set the cursor
self.view.set_cursor(path)
return True
def add_empty_child(self, model, iter):
""" Adds a empty child to a node.
Used when we need a folder that have children to show the expander arrow """
model.insert_before(iter, None)
def remove_empty_child(self, model, iter):
""" Delete empty child from a node.
Used to remove the extra child used to show the expander arrow
on folders with children """
newiter = model.iter_children(iter)
model.remove(newiter)
def get_file_list(self, model, iter, dir):
""" Get the file list from a given directory """
ls = dircache.listdir(dir)
ls.sort(key=str.lower)
for i in ls:
path = ospath.join(dir,i)
if ospath.isdir(path) or not self.show_only_dirs :
if i[0] != '.' or (self.show_hidden and i[0] == '.'):
newiter = model.append(iter)
if ospath.isdir(path): icon = self.get_folder_closed_icon()
else: icon = self.get_file_icon()
model.set_value(newiter, 0, icon)
model.set_value(newiter, 1, i)
model.set_value(newiter, 2, path)
if ospath.isdir(path):
try: subdir = dircache.listdir(path)
except: subdir = []
if subdir != []:
for i in subdir:
if ospath.isdir(ospath.join(path,i)) or not self.show_only_dirs:
if i[0] != '.' or (self.show_hidden and i[0] == '.'):
self.add_empty_child(model, newiter)
break
def create_root(self):
model = self.view.get_model()
if self.root != '/':
if self.root[-1] == '/': self.root = self.root.rsplit('/',1)[0] # Remove last / if neccesary
directory = self.root.split('/')[-1]
else: directory = self.root
iter = model.insert_before(None, None)
model.set_value(iter, 0, self.get_folder_opened_icon())
model.set_value(iter, 1, directory)
model.set_value(iter, 2, self.root)
iter = model.insert_before(iter, None)
return iter
def create_new(self):
""" Create tree from scratch """
model = self.view.get_model()
model.clear()
iter = self.create_root()
self.get_file_list(self.view.get_model(), iter, self.root)
def create_popup(self):
""" Create popup menu for right click """
self.popup = Gtk.Menu()
self.hidden_check_menu = Gtk.CheckMenuItem(_("Show hidden files"))
self.hidden_check_menu.connect('toggled', self.show_hidden_toggled)
self.popup.add(self.hidden_check_menu)
self.popup.show_all()
def get_folder_closed_icon(self):
""" Returns a pixbuf with the current theme closed folder icon """
icon_theme = Gtk.icon_theme_get_default()
try:
icon = icon_theme.load_icon("gnome-fs-directory", 16, 0)
return icon
except GObject.GError, exc:
#print "Can't load icon", exc
try:
icon = icon_theme.load_icon("Gtk-directory", 16, 0)
return icon
except:
#print "Can't load default icon"
return None
def get_folder_opened_icon(self):
""" Returns a pixbuf with the current theme opened folder icon """
icon_theme = Gtk.icon_theme_get_default()
try:
icon = icon_theme.load_icon("gnome-fs-directory-accept", 16, 0)
return icon
except GObject.GError, exc:
#print "Can't load icon", exc
try:
icon = icon_theme.load_icon("Gtk-directory", 16, 0)
return icon
except:
#print "Can't load default icon"
return None
def get_file_icon(self):
""" Returns a pixbuf with the current theme file icon """
icon_theme = Gtk.icon_theme_get_default()
try:
icon = icon_theme.load_icon("text-x-generic", Gtk.ICON_SIZE_MENU, 0)
return icon
except GObject.GError, exc:
#print "Can't load icon", exc
return None
#####################################################
# Model, treeview and scrolledwindow
def make_view(self):
""" Create the view itself.
(Icon, dir name, path) """
self.model = Gtk.TreeStore(Gtk.gdk.Pixbuf, GObject.TYPE_STRING, GObject.TYPE_STRING)
view = Gtk.TreeView(self.model)
view.set_headers_visible(False)
view.set_enable_search(True)
view.set_reorderable(False)
view.set_rules_hint(self.show_rules_hint)
view.connect('row-expanded', self.row_expanded)
view.connect('row-collapsed', self.row_collapsed)
view.connect('row-activated', self.row_activated)
view.connect('cursor-changed', self.cursor_changed)
view.connect('button_press_event', self.button_pressed)
col = Gtk.TreeViewColumn()
# The icon
render_pixbuf = Gtk.CellRendererPixbuf()
col.pack_start(render_pixbuf, expand=False)
col.add_attribute(render_pixbuf, 'pixbuf', 0)
# The dir name
render_text = Gtk.CellRendererText()
col.pack_start(render_text, expand=True)
col.add_attribute(render_text, 'text', 1)
view.append_column(col)
view.show()
# Create scrollbars around the view
scrolled = Gtk.ScrolledWindow()
scrolled.set_policy(Gtk.POLICY_AUTOMATIC, Gtk.POLICY_AUTOMATIC)
scrolled.set_shadow_type(Gtk.SHADOW_ETCHED_IN)
scrolled.add(view)
scrolled.show()
return view, scrolled
GObject.type_register(TreeFileBrowser)
# End TreeFileBrowser