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