Objects updates
[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):
16         ignore_dirs = ['/dev', '/proc', '/sys', '/mnt']
17         start_path = '.'
18         count = 7
19
20         if ui == 'cli':
21             self.present = Cli_Presentation(start_path, count, self.start_search)
22         elif ui == 'gtk':
23             self.present = Gtk_Presentation(start_path, count, self.start_search)
24
25         self.abstrac = Abstraction(ignore_dirs, self.present)
26
27     def start_search(self, get_data, get_stopit, label, kill_func):
28         filelist = []
29         start_path, count = get_data()
30         search_func = self.abstrac.filegetter(start_path, get_stopit, label)
31         for fsize, fpath in nlargest(count, search_func):
32             filelist.append([fpath, size_hum_read(fsize), int(fsize)])
33         self.present.show_out_toplevel(None, 'outtable', filelist)
34
35     def run(self):
36         return self.present.toplevel
37
38
39 #==============================================================================
40
41 class Abstraction(object):
42
43     def __init__(self, ignore_dirs, presentation):
44         self.ignore_dirs = ignore_dirs
45         self.presentation = presentation
46
47     def filegetter(self, startdir, get_stopit, label):
48         """Generator of file sizes and paths based on os.walk."""
49         # Проходим по всем папкам вглубь от заданного пути
50         self.full_dir_size = 0
51         for dirpath, dirnames, fnames in walk(startdir):
52             # Исключаем каталоги из поиска в соответствии со списком исключений
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                 self.presentation.update_window(flpath)
64
65                 # Останавливаем цикл по нажатию кнопки стоп
66                 stopit = get_stopit()
67                 if stopit:
68                     stopit = False
69                     raise StopIteration
70                     print 'Stopped'
71                 # Проверяем можем ли мы определить размер файла - иначе пропускаем его
72                 try:
73                     # Возвращаем размер и полный путь файла
74                     yield getsize(flpath), flpath
75                 except OSError:
76                     continue
77
78
79 #==============================================================================
80
81 class Cli_Presentation(object):
82     def __init__(self, start_func):
83         self.stopit = False
84                   #     get_data,      get_stopit, label, kill_func)
85         start_func(self.get_data, self.get_stopit, self.kill_wind)
86         pass
87
88     def show_current_status(self, current_path):
89         print current_path
90
91
92 #==============================================================================
93
94 class Gtk_Presentation(object):
95
96     def __init__(self, start_path, count, start_func):
97         import gtk
98
99         # "Start path" entry
100         self.path_entry = gtk.Entry()
101         self.path_entry.set_text(start_path)
102
103         # "Files quantity" label
104         qty_label = gtk.Label('Files quantity')
105
106         # "Files quantity" spin
107         self.qty_spin = gtk.SpinButton()
108         self.qty_spin.set_numeric(True)
109         self.qty_spin.set_range(0, 65536)
110         self.qty_spin.set_increments(1, 10)
111         self.qty_spin.set_value(count)
112
113         # "Start" button
114         self.start_btn = gtk.Button('Start')
115         self.start_btn.connect('released', self.start_btn_released, start_func)
116
117         # "Stop" button
118         self.stop_btn = gtk.Button('Stop')
119         self.stop_btn.set_sensitive(False)
120         self.stop_btn.connect('clicked', self.stop_btn_clicked)
121
122         # Output selection
123         outtable_rbtn = gtk.RadioButton(None, 'Table')
124         outdiagram_rbtn = gtk.RadioButton(outtable_rbtn, 'Diagram')
125         out1_rbtn = gtk.RadioButton(outtable_rbtn, 'Another 1')
126         out2_rbtn = gtk.RadioButton(outtable_rbtn, 'Another 2')
127         out_rbtns = [outtable_rbtn, outdiagram_rbtn, out1_rbtn, out2_rbtn]
128
129         hbox = gtk.HBox(False, 4)
130         hbox.pack_start(qty_label, False, False, 0)
131         hbox.pack_start(self.qty_spin, False, False, 0)
132         hbox.pack_start(self.start_btn, False, False, 0)
133         hbox.pack_start(self.stop_btn, False, False, 0)
134         for btn in reversed(out_rbtns):
135             hbox.pack_end(btn, False, False, 0)
136
137         self.statusbar = gtk.Statusbar()
138         self.context_id = self.statusbar.get_context_id('Current walked file')
139
140         self.vbox = gtk.VBox(False, 4)
141         self.vbox.pack_start(self.path_entry, False, False, 0)
142         self.vbox.pack_start(hbox, False, False, 0)
143         self.vbox.pack_end(self.statusbar, False, False, 0)
144
145         self.toplevel = self.vbox
146
147         # for importing gtk only once (lambda not work)
148         def show_current_status(current_path):
149             self.statusbar.push(self.context_id, current_path)
150             gtk.main_iteration()
151         self.update_window = show_current_status
152
153 #        self.show_out_toplevel(None, 'outtable', [(11, 22, 33)])
154
155     #=== Functions ============================================================
156     def start_btn_released(self, widget, start_func):
157         self.stopit = False
158         self.stop_btn.set_sensitive(True)
159         self.start_btn.set_sensitive(False)
160         start_func(self.get_data, self.get_stopit, None, None)
161         self.stop_btn.set_sensitive(False)
162         self.start_btn.set_sensitive(True)
163
164     def stop_btn_clicked(self, widget):
165         self.stopit = True
166         self.stop_btn.set_sensitive(False)
167         self.start_btn.set_sensitive(True)
168
169     def get_data(self):
170         return self.path_entry.get_text(), int(self.qty_spin.get_value())
171
172     def get_stopit(self):
173         return self.stopit
174
175     #=== Output type selecting ================================================
176     def show_out_toplevel(self, btn, outtype, results):
177         print 'Entering <' + outtype + '> output mode...'
178         out_submodule = __import__('files.' + outtype, None, None, outtype)
179         out_toplevel = out_submodule.Gtk_Presentation(results)
180
181 ###        self.vbox.remove(self.vbox.get_children()[2])
182         self.vbox.add(out_toplevel)
183 #        out_submodule.Gtk_Presentation().show_results(results)