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