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