Added Browse button (variant 2)
[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, _
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 = gtk.Notebook()
120         self.nb.set_scrollable(True)
121         self.nb.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         self.nb.append_page(cr_vbox, gtk.Label(_('Criteria')))
193
194         #====================
195         # Others
196         #====================
197
198         self.statusbar = gtk.Statusbar()
199         self.statusbar.set_has_resize_grip(False)
200         self.context_id = self.statusbar.get_context_id('Current walked file')
201
202         self.vbox = gtk.VBox()
203         self.vbox.pack_start(self.nb, True, True, 0)
204         self.vbox.pack_end(self.statusbar, False, False, 0)
205
206 #        self.show_out_toplevel(config['outtype'], [(1, 'path', 'bytesize')])
207
208         self.toplevel = self.vbox
209
210     #=== Functions ============================================================
211     def browse_btn_clicked(self, btn):
212         """Open directory browser. "Browse" button clicked callback."""
213         dialog = gtk.FileChooserDialog(title=_('Choose directory'),
214                                        action='select-folder',
215                                        buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
216                                                 gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
217         path = abspath(self.path_entry.get_text())
218         dialog.set_current_folder(path)
219         dialog.show_all()
220         response = dialog.run()
221         if response == gtk.RESPONSE_OK:
222             self.path_entry.set_text(dialog.get_filename())
223         dialog.destroy()
224
225     def start_btn_released(self, btn, start_func):
226         """Start file search. Button "Go" activate callback."""
227         self.stopit = False
228         self.stop_btn.set_sensitive(True)
229         self.start_btn.set_sensitive(False)
230         start_func(self.get_criteria, self.get_stopit)
231         self.stop_btn.set_sensitive(False)
232         self.start_btn.set_sensitive(True)
233
234     def stop_btn_clicked(self, widget):
235         """Stop search. "Stop" button clicked callback."""
236         self.stopit = True
237         self.stop_btn.set_sensitive(False)
238         self.start_btn.set_sensitive(True)
239
240     def get_criteria(self):
241         """Pick search criteria from window."""
242         for btn in self.out_rbtns:
243             if btn.get_active():
244                 out = {}
245                 out['name'] = btn.get_name()
246                 out['label'] = btn.get_label()
247         return out, self.path_entry.get_text(), int(self.qty_spin.get_value())
248
249     def get_stopit(self):
250         return self.stopit
251
252     def show_current_status(self, current_path):
253         """Show current walked path in statusbar and update window."""
254         self.statusbar.push(self.context_id, current_path)
255         gtk.main_iteration()
256
257     def _new_page(self, child, label):
258         """Create new notebook page with search output."""
259         self.nb.append_page(child, gtk.Label(label))
260         #self.nb.set_current_page(-1)
261         #child.grab_focus()
262
263     def _close_page(self):
264         pass
265
266     def run(self):
267         pass
268
269     #=== Output type selecting ================================================
270     def show_out_toplevel(self, outtype, results):
271         print 'Entering <' + outtype['name'] + '> output mode...'
272         out_submodule = __import__('files.' + outtype['name'], None, None, outtype)
273
274         self.out_toplevel = out_submodule.Gtk_Presentation(results).toplevel
275
276         self._new_page(self.out_toplevel, outtype['label'])
277         self.out_toplevel.show_all()
278 ###        out_submodule.Gtk_Presentation().show_results(results)
279
280 #==============================================================================
281
282 class Hildon_Presentation(object):
283
284     def __init__(self, start_func):
285         import gtk
286         import hildon
287
288     def run(self):
289         pass