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