Small improvement in output radio buttons
[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 *
10
11 #==============================================================================
12
13 class Control(object):
14
15     def __init__(self, ui, config):
16
17         if ui == 'cli':
18             self.present = Cli_Presentation(config)
19         elif ui == 'gtk':
20             self.present = Gtk_Presentation(config, self.start_search)
21         elif ui == 'hildon':
22             self.present = Hildon_Presentation(config, self.start_search)
23
24         # self.present - for updating windows in interactive presentations
25         self.abstrac = Abstraction(config, self.present)
26
27         # Used only in non-interactive presentations
28         self.present.start_search(self.start_search)
29
30     def start_search(self, get_data, get_stopit):
31         filelist = []
32         outtype, start_path, count = get_data()
33         search_func = self.abstrac.filegetter(start_path, get_stopit)
34         for fsize, fpath in nlargest(count, search_func):
35             filelist.append([int(fsize), fpath, size_hum_read(fsize)])
36         self.present.show_out_toplevel(None, outtype, filelist)
37
38     def run(self):
39         return self.present.toplevel
40
41 #==============================================================================
42
43 class Abstraction(object):
44
45     def __init__(self, config, presentation):
46         self.ignore_dirs = config['ignore_dirs']
47         self.presentation = presentation
48
49     def filegetter(self, startdir, get_stopit):
50         """Generator of file sizes and paths based on os.walk."""
51
52         # Walk across directory tree
53         for dirpath, dirnames, fnames in walk(startdir):
54             # Eliminate unnecessary directories
55             ignore_dirs = self.ignore_dirs
56             for ign_dir in ignore_dirs[:]:
57                 for dirname in dirnames[:]:
58                     if ign_dir == normcase(join(abspath(dirpath), dirname)):
59                         dirnames.remove(dirname)
60                         ignore_dirs.remove(ign_dir)
61
62             for fname in fnames:
63                 flpath = abspath(join(dirpath, fname))
64                 self.presentation.show_current_status(flpath)
65
66                 # Stop search via 'stopit' signal
67                 stopit = get_stopit()
68                 if stopit:
69                     stopit = False
70                     raise StopIteration
71                 # Query only valid files
72                 try:
73                     # Return results (bytesize, path)
74                     yield getsize(flpath), flpath
75                 except OSError:
76                     continue
77
78 #==============================================================================
79
80 class Cli_Presentation(object):
81     def __init__(self, config):
82         self.outtype = config['outtype']
83         self.start_path = config['start_path']
84         self.count = config['count']
85         self.stopit = False
86
87         self.toplevel = None
88
89     def get_data(self):
90         return self.outtype, self.start_path, int(self.count)
91
92     def get_stopit(self):
93         return False
94
95     def show_out_toplevel(self, _, outtype, results):
96         out_submodule = __import__('files.' + outtype, None, None, outtype)
97         out_submodule.Cli_Presentation(results).toplevel
98
99     def show_current_status(self, current_path):
100         pass
101         #print current_path
102
103     def start_search(self, start_func):
104         start_func(self.get_data, self.get_stopit)
105
106 #==============================================================================
107
108 class Gtk_Presentation(object):
109
110     def __init__(self, config, start_func):
111         import gtk
112
113         self.config = config
114
115         # "Start path" entry
116         self.path_entry = gtk.Entry()
117         self.path_entry.set_text(self.config['start_path'])
118
119         # "Files quantity" label
120         qty_label = gtk.Label('Files quantity')
121
122         # "Files quantity" spin
123         self.qty_spin = gtk.SpinButton()
124         self.qty_spin.set_numeric(True)
125         self.qty_spin.set_range(0, 65536)
126         self.qty_spin.set_increments(1, 10)
127         self.qty_spin.set_value(self.config['count'])
128
129         # "Start" button
130         self.start_btn = gtk.Button('Start')
131         self.start_btn.connect('released', self.start_btn_released, start_func)
132
133         # "Stop" button
134         self.stop_btn = gtk.Button('Stop')
135         self.stop_btn.set_sensitive(False)
136         self.stop_btn.connect('clicked', self.stop_btn_clicked)
137
138         # Output selection
139         outtable_rbtn = gtk.RadioButton(None, 'Table')
140         outtable_rbtn.set_name('outtable')
141         outdiagram_rbtn = gtk.RadioButton(outtable_rbtn, 'Diagram')
142         outdiagram_rbtn.set_name('outdiagram')
143         out1_rbtn = gtk.RadioButton(outtable_rbtn, 'Another 1')
144         out1_rbtn.set_name('outanother1')
145         out2_rbtn = gtk.RadioButton(outtable_rbtn, 'Another 2')
146         out2_rbtn.set_name('outanother2')
147         self.out_rbtns = [outtable_rbtn, outdiagram_rbtn, out1_rbtn, out2_rbtn]
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() == self.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, self.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     # Empty because search start by button
202     def start_search(self, start_func):
203         pass
204
205     #=== Output type selecting ================================================
206     def show_out_toplevel(self, btn, outtype, results):
207         print 'Entering <' + outtype + '> output mode...'
208         out_submodule = __import__('files.' + outtype, None, None, outtype)
209
210         try:
211             self.current_outtoplevel.destroy()
212         except:
213             pass
214
215         out_toplevel = out_submodule.Gtk_Presentation(results).toplevel
216         self.current_outtoplevel = out_toplevel
217         self.vbox.add(out_toplevel)
218         out_toplevel.show_all()
219 #        out_submodule.Gtk_Presentation().show_results(results)
220
221 #==============================================================================
222
223 class Hildon_Presentation(object):
224
225     def __init__(self, config, start_func):
226         import gtk
227         import hildon
228
229         self.config = config
230
231     def start_search(self, start_func):
232         pass