First tabbed version
[findit] / src / files / search.py
1 #!/usr/bin/env python
2 # -*-coding: utf-8 -*-
3 # vim: sw=4 ts=4 expandtab ai
4
5 from os import walk
6 from os.path import join, abspath, normcase, basename, isdir, getsize
7 from heapq import nlargest
8
9 from misc import size_hum_read, _
10 from config import config
11
12 OUTTYPES = [
13     ('out_table',  _('Table')),
14     ('out_diabar', _('Bar chart')),
15     ('out_diapie', _('Pie chart')),
16     ('out_diaold', _('Old chart')),
17 ]
18
19 #==============================================================================
20
21 class Control(object):
22
23     def __init__(self, ui, params):
24         self.present = eval(ui + '_Presentation(self.start_search, params)')
25         self.abstrac = Abstraction(self.present)
26
27         self.toplevel = self.present.toplevel
28
29     def start_search(self, get_criteria, get_stopit):
30         filelist = []
31         outtype, start_path, count = get_criteria()
32         search_func = self.abstrac.filegetter(start_path, get_stopit)
33         for fsize, fpath in nlargest(count, search_func):
34             filelist.append([int(fsize), fpath, size_hum_read(fsize)])
35         self.present.show_out_toplevel(outtype, filelist)
36
37     def run(self):
38         self.present.run()
39
40 #==============================================================================
41
42 class Abstraction(object):
43
44     def __init__(self, presentation):
45         self.ignore_dirs = config['files']['ignore_dirs']
46         self.presentation = presentation
47
48     def filegetter(self, startdir, get_stopit):
49         """Generator of file sizes and paths based on os.walk."""
50
51         # Walk across directory tree
52         for dirpath, dirnames, fnames in walk(startdir):
53             # Eliminate unnecessary directories
54             ignore_dirs = self.ignore_dirs
55             for ign_dir in ignore_dirs[:]:
56                 for dirname in dirnames[:]:
57                     if ign_dir == normcase(join(abspath(dirpath), dirname)):
58                         dirnames.remove(dirname)
59                         ignore_dirs.remove(ign_dir)
60
61             for fname in fnames:
62                 flpath = abspath(join(dirpath, fname))
63                 self.presentation.show_current_status(flpath)
64
65                 # Stop search via 'stopit' signal
66                 stopit = get_stopit()
67                 if stopit:
68                     stopit = False
69                     print 'Stopped'
70                     raise StopIteration
71                 # Query only valid files
72                 try:
73                     # Return results (bytesize, path)
74                     yield getsize(flpath), flpath
75                 except OSError:
76                     continue
77
78 #==============================================================================
79
80 class Cli_Presentation(object):
81     def __init__(self, start_func, params):
82         self.start_func = start_func
83
84         self.outtype = params['outtype']
85         self.start_path = params['start_path']
86         self.count = params['count']
87         self.stopit = False
88
89         self.toplevel = None
90
91     def get_data(self):
92         return self.outtype, self.start_path, int(self.count)
93
94     def get_stopit(self):
95         return False
96
97     def show_out_toplevel(self, outtype, results):
98         out_submodule = __import__('files.' + outtype, None, None, outtype)
99         out_submodule.Cli_Presentation(results).toplevel
100
101     def show_current_status(self, current_path):
102         #pass
103         print '|' + '\r',
104         print '/' + '\r',
105         print '-' + '\r',
106         print '\\' + '\r',
107         ### print current_path
108
109     def run(self):
110         self.start_func(self.get_data, self.get_stopit)
111
112 #==============================================================================
113
114 class Gtk_Presentation(object):
115
116     def __init__(self, start_func, __):
117         import gtk
118         global gtk  # for show_current_status()
119
120         self.nb = gtk.Notebook()
121         self.nb.set_scrollable(True)
122
123         #====================
124         # Notebook
125         #====================
126
127         # "Start path" entry
128         self.path_entry = gtk.Entry()
129         self.path_entry.set_text(config['files']['start_path'])
130
131         # "Files quantity" label
132         qty_label = gtk.Label(_('Files quantity'))
133
134         # "Files quantity" spin
135         self.qty_spin = gtk.SpinButton()
136         self.qty_spin.set_numeric(True)
137         self.qty_spin.set_range(0, 65536)
138         self.qty_spin.set_increments(1, 10)
139         self.qty_spin.set_value(config['files']['count'])
140
141         # "Start" button
142         self.start_btn = gtk.Button(_('Start'))
143         self.start_btn.connect('released', self.start_btn_released, start_func)
144
145         # "Stop" button
146         self.stop_btn = gtk.Button(_('Stop'))
147         self.stop_btn.set_sensitive(False)
148         self.stop_btn.connect('clicked', self.stop_btn_clicked)
149
150         # Output selection
151         btn = gtk.RadioButton(None, OUTTYPES[0][1])
152         btn.set_name(OUTTYPES[0][0])
153         self.out_rbtns = []
154         self.out_rbtns.append(btn)
155         for name, label in OUTTYPES[1:]:
156             btn = gtk.RadioButton(self.out_rbtns[0], label)
157             btn.set_name(name)
158             self.out_rbtns.append(btn)
159
160         hbox1 = gtk.HBox(False, 2)
161         hbox1.pack_start(qty_label, False, False, 0)
162         hbox1.pack_start(self.qty_spin, False, False, 0)
163
164         hbox2 = gtk.HBox(False, 2)
165         for btn in self.out_rbtns:
166             hbox2.pack_start(btn, False, False, 0)
167             # Activate radio button
168             if btn.get_name() == config['outtype']:
169                 btn.set_active(True)
170
171         hbox3 = gtk.HBox(True, 2)
172         hbox3.pack_start(self.start_btn, True, True, 0)
173         hbox3.pack_start(self.stop_btn, True, True, 0)
174
175         cr_vbox = gtk.VBox(False, 2)
176         cr_vbox.pack_start(self.path_entry, False, False, 0)
177         cr_vbox.pack_start(hbox1, False, False, 0)
178         cr_vbox.pack_start(hbox2, False, False, 0)
179         cr_vbox.pack_end(hbox3, False, False, 0)
180         self.nb.append_page(cr_vbox, gtk.Label(_('Criteria')))
181
182         #====================
183         # Others
184         #====================
185
186         self.statusbar = gtk.Statusbar()
187         self.context_id = self.statusbar.get_context_id('Current walked file')
188
189         self.vbox = gtk.VBox(False, 2)
190         self.vbox.pack_start(self.nb, True, True, 0)
191         self.vbox.pack_end(self.statusbar, False, False, 0)
192
193 #        self.show_out_toplevel(config['outtype'], [(1, 'path', 'bytesize')])
194
195         self.toplevel = self.vbox
196
197     #=== Functions ============================================================
198     def start_btn_released(self, btn, start_func):
199         self.stopit = False
200         self.stop_btn.set_sensitive(True)
201         self.start_btn.set_sensitive(False)
202         start_func(self.get_criteria, self.get_stopit)
203         self.stop_btn.set_sensitive(False)
204         self.start_btn.set_sensitive(True)
205
206     def stop_btn_clicked(self, widget):
207         self.stopit = True
208         self.stop_btn.set_sensitive(False)
209         self.start_btn.set_sensitive(True)
210
211     def get_criteria(self):
212         for btn in self.out_rbtns:
213             if btn.get_active():
214                 out = {}
215                 out['name'] = btn.get_name()
216                 out['label'] = btn.get_label()
217         return out, self.path_entry.get_text(), int(self.qty_spin.get_value())
218
219     def get_stopit(self):
220         return self.stopit
221
222     def show_current_status(self, current_path):
223         self.statusbar.push(self.context_id, current_path)
224         gtk.main_iteration()
225
226     def _new_page(self, child, label):
227         self.nb.append_page(child, gtk.Label(label))
228         #self.nb.set_current_page(-1)
229         #child.grab_focus()
230
231     def _close_page(self):
232         pass
233
234     def run(self):
235         pass
236
237     #=== Output type selecting ================================================
238     def show_out_toplevel(self, outtype, results):
239         print 'Entering <' + outtype['name'] + '> output mode...'
240         out_submodule = __import__('files.' + outtype['name'], None, None, outtype)
241
242         self.out_toplevel = out_submodule.Gtk_Presentation(results).toplevel
243
244         self._new_page(self.out_toplevel, outtype['label'])
245         self.out_toplevel.show_all()
246 ###        out_submodule.Gtk_Presentation().show_results(results)
247
248 #==============================================================================
249
250 class Hildon_Presentation(object):
251
252     def __init__(self, start_func):
253         import gtk
254         import hildon
255
256     def run(self):
257         pass