Added file filter to files Cli_Presentation
[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, isdir, getsize
7 from heapq import nlargest
8 from fnmatch import fnmatch
9
10 from misc import size_hum_read, _
11 from config import config
12
13 OUTTYPES = [
14     ('out_table',  _('Table')),
15     ('out_diabar', _('Bar chart')),
16     ('out_diapie', _('Pie chart')),
17     ('out_diaold', _('Old chart')),
18 ]
19
20 #==============================================================================
21
22 class Control(object):
23
24     def __init__(self, ui, params):
25         self.present = eval(ui + '_Presentation(self.start_search, params)')
26         self.abstrac = Abstraction(self.present)
27
28         self.toplevel = self.present.toplevel
29
30     def start_search(self, get_criteria, get_stopit):
31         filelist = []
32         outtype, start_path, count, file_filter = get_criteria()
33         search_func = self.abstrac.filegetter(start_path, file_filter, get_stopit)
34         for fsize, fpath in nlargest(count, search_func):
35             filelist.append([int(fsize), fpath, size_hum_read(fsize)])
36         self.present.show_out_toplevel(outtype, filelist)
37
38     def run(self):
39         self.present.run()
40
41 #==============================================================================
42
43 class Abstraction(object):
44
45     def __init__(self, presentation):
46         self.ignore_dirs = config['files']['ignore_dirs']
47         self.presentation = presentation
48
49     def filegetter(self, startdir, file_filter, get_stopit):
50         """Generator of file sizes and paths based on os.walk."""
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                 # Store only necessary files
63                 for mask in file_filter:
64                     if fnmatch(fname, mask):
65                         flpath = abspath(join(dirpath, fname))
66                         # Show current path
67                         self.presentation.show_current_status(flpath)
68                         # Stop search via 'stopit' signal
69                         stopit = get_stopit()
70                         if stopit:
71                             stopit = False
72                             print 'Stopped'
73                             raise StopIteration
74                         # Query only valid files
75                         try:
76                             # Return results (bytesize, path)
77                             yield getsize(flpath), flpath
78                         except OSError:
79                             continue
80
81 #==============================================================================
82
83 class Cli_Presentation(object):
84     def __init__(self, start_func, params):
85         self.start_func = start_func
86
87         self.outtype = params['outtype']
88         self.start_path = params['start_path']
89         self.count = params['count']
90         self.file_filter = params['file_filter'].split(';')
91         self.stopit = False
92
93         self.toplevel = None
94
95     def get_data(self):
96         return self.outtype, self.start_path, int(self.count), self.file_filter
97
98     def get_stopit(self):
99         return False
100
101     def show_out_toplevel(self, outtype, results):
102         out_submodule = __import__('files.' + outtype, None, None, outtype)
103         out_submodule.Cli_Presentation(results).toplevel
104
105     def show_current_status(self, current_path):
106         #pass
107         print '|' + '\r',
108         print '/' + '\r',
109         print '-' + '\r',
110         print '\\' + '\r',
111         ### print current_path
112
113     def run(self):
114         self.start_func(self.get_data, self.get_stopit)
115
116 #==============================================================================
117
118 class Gtk_Presentation(object):
119
120     def __init__(self, start_func, __):
121         import gtk
122         global gtk  # for show_current_status()
123         from misc import NotebookWCloseBtns
124
125         self.nb = NotebookWCloseBtns()
126         self.nb.notebook.set_scrollable(True)
127         self.nb.notebook.set_border_width(2)
128
129         #====================
130         # Notebook
131         #====================
132
133         # "Start path" label
134         self.path_label = gtk.Label(_('Path'))
135         # "Start path" entry
136         self.path_entry = gtk.Entry()
137         self.path_entry.set_text(config['files']['start_path'])
138         # "Browse" button
139         self.browse_btn = gtk.Button('Browse...')
140         self.browse_btn.connect('clicked', self.browse_btn_clicked)
141
142         # "Files quantity" label
143         qty_label = gtk.Label(_('Files quantity'))
144         # "Files quantity" spin
145         self.qty_spin = gtk.SpinButton()
146         self.qty_spin.set_numeric(True)
147         self.qty_spin.set_range(0, 65536)
148         self.qty_spin.set_increments(1, 10)
149         self.qty_spin.set_value(config['files']['count'])
150
151         # "Filter" label
152         filter_label = gtk.Label(_('Filter'))
153         # "Filter" entry
154         self.filter_entry = gtk.Entry()
155         self.filter_entry.set_text(config['files']['filter'])
156
157         # "Output" label
158         out_label = gtk.Label(_('Output'))
159         # Output selection
160         btn = gtk.RadioButton(None, OUTTYPES[0][1])
161         btn.set_name(OUTTYPES[0][0])
162         self.out_rbtns = []
163         self.out_rbtns.append(btn)
164         for name, label in OUTTYPES[1:]:
165             btn = gtk.RadioButton(self.out_rbtns[0], label)
166             btn.set_name(name)
167             self.out_rbtns.append(btn)
168
169         # "Start" button
170         self.start_btn = gtk.Button(_('Start'))
171         self.start_btn.connect('released', self.start_btn_released, start_func)
172         # "Stop" button
173         self.stop_btn = gtk.Button(_('Stop'))
174         self.stop_btn.set_sensitive(False)
175         self.stop_btn.connect('clicked', self.stop_btn_clicked)
176
177         path_hbox = gtk.HBox(False, 2)
178         path_hbox.pack_start(self.path_label, False, False, 4)
179         path_hbox.pack_start(self.path_entry, True, True, 0)
180         path_hbox.pack_start(self.browse_btn, False, False, 0)
181
182         qty_hbox = gtk.HBox(False, 2)
183         qty_hbox.pack_start(qty_label, False, False, 4)
184         qty_hbox.pack_start(self.qty_spin, False, False, 0)
185
186         filter_hbox = gtk.HBox(False, 2)
187         filter_hbox.pack_start(filter_label, False, False, 4)
188         filter_hbox.pack_start(self.filter_entry, True, True, 0)
189
190         out_hbox = gtk.HBox(False, 2)
191         out_hbox.pack_start(out_label, False, False, 4)
192         for btn in self.out_rbtns:
193             out_hbox.pack_start(btn, False, False, 0)
194             # Activate radio button
195             if btn.get_name() == config['outtype']:
196                 btn.set_active(True)
197
198         control_hbox = gtk.HBox(True, 2)
199         control_hbox.pack_start(self.start_btn, True, True, 0)
200         control_hbox.pack_start(self.stop_btn, True, True, 0)
201
202         cr_vbox = gtk.VBox(False, 2)
203         cr_vbox.set_border_width(2)
204         cr_vbox.pack_start(path_hbox, False, False, 0)
205         cr_vbox.pack_start(qty_hbox, False, False, 0)
206         cr_vbox.pack_start(filter_hbox, False, False, 0)
207         cr_vbox.pack_start(out_hbox, False, False, 0)
208         cr_vbox.pack_end(control_hbox, False, False, 0)
209
210         self.nb.new_tab(cr_vbox, _('Criteria'), noclose=True)
211
212         #====================
213         # Others
214         #====================
215
216         self.statusbar = gtk.Statusbar()
217         self.statusbar.set_has_resize_grip(False)
218         self.context_id = self.statusbar.get_context_id('Current walked file')
219
220         self.vbox = gtk.VBox()
221         self.vbox.pack_start(self.nb.notebook, True, True, 0)
222         self.vbox.pack_end(self.statusbar, False, False, 0)
223
224 #        self.show_out_toplevel(config['outtype'], [(1, 'path', 'bytesize')])
225
226         self.toplevel = self.vbox
227
228     #=== Functions ============================================================
229     def browse_btn_clicked(self, btn):
230         """Open directory browser. "Browse" button clicked callback."""
231         dialog = gtk.FileChooserDialog(title=_('Choose directory'),
232                                        action='select-folder',
233                                        buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
234                                                 gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
235         path = abspath(self.path_entry.get_text())
236         dialog.set_current_folder(path)
237         dialog.show_all()
238         response = dialog.run()
239         if response == gtk.RESPONSE_OK:
240             self.path_entry.set_text(dialog.get_filename())
241         dialog.destroy()
242
243     def start_btn_released(self, btn, start_func):
244         """Start file search. Button "Go" activate callback."""
245         self.stopit = False
246         self.stop_btn.set_sensitive(True)
247         self.start_btn.set_sensitive(False)
248         start_func(self.get_criteria, self.get_stopit)
249         self.stop_btn.set_sensitive(False)
250         self.start_btn.set_sensitive(True)
251
252     def stop_btn_clicked(self, widget):
253         """Stop search. "Stop" button clicked callback."""
254         self.stopit = True
255         self.stop_btn.set_sensitive(False)
256         self.start_btn.set_sensitive(True)
257
258     def get_criteria(self):
259         """Pick search criteria from window."""
260         for btn in self.out_rbtns:
261             if btn.get_active():
262                 out = {}
263                 out['name'] = btn.get_name()
264                 out['label'] = btn.get_label()
265         file_filter = self.filter_entry.get_text().split(';')
266         # If no filter - show all files
267         if file_filter == ['']:
268             file_filter = ['*.*']
269         return out, \
270             self.path_entry.get_text(), int(self.qty_spin.get_value()), \
271             file_filter
272
273     def get_stopit(self):
274         return self.stopit
275
276     def show_current_status(self, current_path):
277         """Show current walked path in statusbar and update window."""
278         self.statusbar.push(self.context_id, current_path)
279         gtk.main_iteration()
280
281     def run(self):
282         pass
283
284     #=== Output type selecting ================================================
285     def show_out_toplevel(self, outtype, results):
286         out_submodule = __import__('files.' + outtype['name'], None, None, outtype)
287         self.out_toplevel = out_submodule.Gtk_Presentation(results).toplevel
288         self.nb.new_tab(self.out_toplevel, outtype['label'])
289 ###        out_submodule.Gtk_Presentation().show_results(results)
290
291 #==============================================================================
292
293 class Hildon_Presentation(object):
294
295     def __init__(self, start_func):
296         import gtk
297         import hildon
298
299     def run(self):
300         pass