3 # vim: sw=4 ts=4 expandtab ai
4 # pylint: disable-msg=C0301
6 from gtkmvc import Controller
10 from os.path import join, abspath, normcase, getsize
11 from heapq import nlargest
13 from views.filesearch import FilesearchView
14 from misc.functions import *
17 class FilesearchCtrl(Controller):
18 """Controller of the files search plugin"""
20 def __init__(self, model):
21 Controller.__init__(self, model)
23 def register_view(self, view):
24 Controller.register_view(self, view)
26 # connects the signals:
27 self.view['start_btn'].connect('released', self.start_btn_released_cb)
28 self.view['stop_btn'].connect('clicked', self.on_stop_btn_clicked)
29 self.view['qty_spin'].connect("value_changed", self.on_qty_spin_value_changed)
31 # sets initial values for the view
32 self.view.set_quantity_value(self.model.quantity)
33 self.view.set_start_path_value(self.model.start_path)
35 # -----------------------------------------------------
37 # -----------------------------------------------------
39 def filegetter(self, startdir): #, obj):
40 """Generator of file sizes and paths based on os.walk."""
41 # Список игнорируемых каталогов:
42 ignore_dirs = ['/dev', '/proc', '/sys', '/mnt']
43 # Проходим по всем папкам вглубь от заданного пути
44 for dirpath, dirnames, fnames in walk(startdir):
45 # Исключаем каталоги из поиска в соответствии со списком исключений
46 for ign_dir in ignore_dirs[:]:
47 for dirname in dirnames[:]:
48 if ign_dir == normcase(join(abspath(dirpath), dirname)):
49 dirnames.remove(dirname)
50 ignore_dirs.remove(ign_dir)
53 flpath = abspath(join(dirpath, fname))
54 # Выводим текущий опрашиваемый файл в строку статуса
55 self.view['statusbar'].push(self.view['context_id'], flpath)
58 # Останавливаем цикл по нажатию кнопки стоп
60 self.model.stopit = False
62 # Проверяем можем ли мы определить размер файла - иначе пропускаем его
64 # Возвращаем размер и полный путь файла
65 yield getsize(flpath), flpath
69 # -----------------------------------------------------
71 # -----------------------------------------------------
73 def on_qty_spin_value_changed(self, sb):
74 # Получаем значение количества файлов из SpinButton
75 self.model.quantity = sb.get_value_as_int()
77 def start_btn_released_cb(self, btn):
78 """Start file search. Button "Go" activate callback."""
80 # Получаем значение начального пути из Entry
81 start_path = self.view['path_entry'].get_text()
83 self.view['start_btn'].set_sensitive(False)
84 self.view['stop_btn'].set_sensitive(True)
87 self.view['liststore'].clear()
89 # Выравниваем размер колонок
90 self.view['treeview'].columns_autosize()
92 # Получаем нужное количество самых больших файлов
93 #for fsize, fpath in nlargest(self.model.quantity, self.filegetter(self.model.start_path)):
94 for fsize, fpath in nlargest(self.model.quantity, self.filegetter(start_path)):
95 # Заполняем treemodel: путь, размер в Мб строкой, размер в байтах
97 self.view['liststore'].append([fpath, size_convert(fsize), fsize])
99 # print type(fpath), type(self.size_convert(fsize)), type(fsize)
101 self.view['start_btn'].set_sensitive(True)
102 self.view['stop_btn'].set_sensitive(False)
103 self.view['path_entry'].grab_focus()
105 def on_stop_btn_clicked(self, btn):
106 """Stop search. "Stop" button clicked callback."""
108 self.model.stopit = True
110 # -----------------------------------------------------
111 # observable properties
112 # -----------------------------------------------------
114 def property_quantity_value_change(self, model, old, new):
116 #self.view.set_quantity_value(new)
118 def property_start_path_value_change(self, model, old, new):
119 print model, old, new
120 self.view.set_start_path_value(new)
122 def property_stopit_value_change(self, model, old, new):
123 self.view.set_stopit_value(new)