Update translation
[findit] / src / files / search.py
index 2223540..a24026e 100755 (executable)
@@ -5,47 +5,45 @@
 from os import walk
 from os.path import join, abspath, normcase, basename, isdir, getsize
 from heapq import nlargest
-import gtk ###
 
-from misc import *
+from misc import size_hum_read, _
+from config import config
 
 #==============================================================================
 
 class Control(object):
-    
-    def __init__(self):
-        ignore_dirs = ['/dev', '/proc', '/sys', '/mnt']
-        start_path = '.'
-        count = 7
-        self.search_abstrac = Abstraction(ignore_dirs)
-        self.search_present = Gtk_Presentation(start_path, count, self.start_search)
-
-    def start_search(self, get_data, get_stopit, label, kill_func):
+
+    def __init__(self, ui, params):
+        self.present = eval(ui + '_Presentation(self.start_search, params)')
+        self.abstrac = Abstraction(self.present)
+
+        self.toplevel = self.present.toplevel
+
+    def start_search(self, get_data, get_stopit):
         filelist = []
-        start_path, count = get_data()
-        search_func = self.search_abstrac.filegetter(start_path, get_stopit, label)
+        outtype, start_path, count = get_data()
+        search_func = self.abstrac.filegetter(start_path, get_stopit)
         for fsize, fpath in nlargest(count, search_func):
-            filelist.append([fpath, size_hum_read(fsize), int(fsize)])
-        if not get_stopit():
-            #kill_func()
-            self.search_present.show_out_toplevel(None, 'outtable', filelist)
+            filelist.append([int(fsize), fpath, size_hum_read(fsize)])
+        self.present.show_out_toplevel(None, outtype, filelist)
 
     def run(self):
-        return self.search_present.get_toplevel()
+        self.present.run()
 
 #==============================================================================
 
 class Abstraction(object):
-    
-    def __init__(self, ignore_dirs):
-        self.ignore_dirs = ignore_dirs
 
-    def filegetter(self, startdir, get_stopit, label):
+    def __init__(self, presentation):
+        self.ignore_dirs = config['files']['ignore_dirs']
+        self.presentation = presentation
+
+    def filegetter(self, startdir, get_stopit):
         """Generator of file sizes and paths based on os.walk."""
-        # Проходим по всем папкам вглубь от заданного пути
-        self.full_dir_size = 0
+
+        # Walk across directory tree
         for dirpath, dirnames, fnames in walk(startdir):
-            # Исключаем каталоги из поиска в соответствии со списком исключений
+            # Eliminate unnecessary directories
             ignore_dirs = self.ignore_dirs
             for ign_dir in ignore_dirs[:]:
                 for dirname in dirnames[:]:
@@ -55,18 +53,17 @@ class Abstraction(object):
 
             for fname in fnames:
                 flpath = abspath(join(dirpath, fname))
-                # Выводим текущий опрашиваемый файл в строку статуса
-                #label.set_text(flpath)
-                # обновляем окно
-                gtk.main_iteration() ###
-                # Останавливаем цикл по нажатию кнопки стоп
+                self.presentation.show_current_status(flpath)
+
+                # Stop search via 'stopit' signal
                 stopit = get_stopit()
                 if stopit:
                     stopit = False
+                    print 'Stopped'
                     raise StopIteration
-                # Проверяем можем ли мы определить размер файла - иначе пропускаем его
+                # Query only valid files
                 try:
-                    # Возвращаем размер и полный путь файла
+                    # Return results (bytesize, path)
                     yield getsize(flpath), flpath
                 except OSError:
                     continue
@@ -74,77 +71,117 @@ class Abstraction(object):
 #==============================================================================
 
 class Cli_Presentation(object):
-    def __init__(self):
+    def __init__(self, start_func, params):
+        self.start_func = start_func
+
+        self.outtype = params['outtype']
+        self.start_path = params['start_path']
+        self.count = params['count']
         self.stopit = False
-        start_func(self.get_data, self.get_stopit, self.kill_wind)
-        pass
+
+        self.toplevel = None
+
+    def get_data(self):
+        return self.outtype, self.start_path, int(self.count)
+
+    def get_stopit(self):
+        return False
+
+    def show_out_toplevel(self, _, outtype, results):
+        out_submodule = __import__('files.' + outtype, None, None, outtype)
+        out_submodule.Cli_Presentation(results).toplevel
+
+    def show_current_status(self, current_path):
+        #pass
+        print '|' + '\r',
+        print '/' + '\r',
+        print '-' + '\r',
+        print '\\' + '\r',
+        ### print current_path
+
+    def run(self):
+        self.start_func(self.get_data, self.get_stopit)
 
 #==============================================================================
 
 class Gtk_Presentation(object):
 
-    def __init__(self, start_path, count, start_func):
+    def __init__(self, start_func, __):
         import gtk
 
         # "Start path" entry
         self.path_entry = gtk.Entry()
-        self.path_entry.set_text(start_path)
+        self.path_entry.set_text(config['files']['start_path'])
 
         # "Files quantity" label
-        qty_label = gtk.Label('Files quantity')
+        qty_label = gtk.Label(_('Files quantity'))
 
         # "Files quantity" spin
         self.qty_spin = gtk.SpinButton()
         self.qty_spin.set_numeric(True)
         self.qty_spin.set_range(0, 65536)
         self.qty_spin.set_increments(1, 10)
-        self.qty_spin.set_value(count)
+        self.qty_spin.set_value(config['files']['count'])
 
         # "Start" button
-        self.start_btn = gtk.Button('Start')
+        self.start_btn = gtk.Button(_('Start'))
         self.start_btn.connect('released', self.start_btn_released, start_func)
 
         # "Stop" button
-        self.stop_btn = gtk.Button('Stop')
+        self.stop_btn = gtk.Button(_('Stop'))
         self.stop_btn.set_sensitive(False)
         self.stop_btn.connect('clicked', self.stop_btn_clicked)
 
         # Output selection
-        outtable_rbtn = gtk.RadioButton(None, 'Table')
-        outdiagram_rbtn = gtk.RadioButton(outtable_rbtn, 'Diagram')
-        out1_rbtn = gtk.RadioButton(outtable_rbtn, 'Another 1')
-        out2_rbtn = gtk.RadioButton(outtable_rbtn, 'Another 2')
-        out_rbtns = [outtable_rbtn, outdiagram_rbtn, out1_rbtn, out2_rbtn]
+        out_table_rbtn = gtk.RadioButton(None, _('Table'))
+        out_table_rbtn.set_name('out_table')
+        out_diabar_rbtn = gtk.RadioButton(out_table_rbtn, _('Bar chart'))
+        out_diabar_rbtn.set_name('out_diabar')
+        out_diapie_rbtn = gtk.RadioButton(out_table_rbtn, _('Pie chart'))
+        out_diapie_rbtn.set_name('out_diapie')
+        out_diaold_rbtn = gtk.RadioButton(out_table_rbtn, _('Old chart'))
+        out_diaold_rbtn.set_name('out_diaold')
+        self.out_rbtns = [
+            out_table_rbtn, out_diabar_rbtn, out_diapie_rbtn, out_diaold_rbtn
+        ]
 
         hbox = gtk.HBox(False, 4)
         hbox.pack_start(qty_label, False, False, 0)
         hbox.pack_start(self.qty_spin, False, False, 0)
         hbox.pack_start(self.start_btn, False, False, 0)
         hbox.pack_start(self.stop_btn, False, False, 0)
-        for btn in reversed(out_rbtns):
+        for btn in reversed(self.out_rbtns):
             hbox.pack_end(btn, False, False, 0)
+            # Activate radio button
+            if btn.get_name() == config['outtype']:
+                btn.set_active(True)
 
-        statusbar = gtk.Statusbar()
-        context_id = statusbar.get_context_id('Current walked file')
-        statusbar.push(context_id, 'test')
+        self.statusbar = gtk.Statusbar()
+        self.context_id = self.statusbar.get_context_id('Current walked file')
 
         self.vbox = gtk.VBox(False, 4)
-        self.vbox.set_border_width(4)
         self.vbox.pack_start(self.path_entry, False, False, 0)
         self.vbox.pack_start(hbox, False, False, 0)
-        self.vbox.pack_end(statusbar, False, False, 0)
+        self.vbox.pack_end(self.statusbar, False, False, 0)
 
-#        self.show_out_toplevel(None, 'outtable')
-        self.frame = gtk.Frame('Files search')
-        self.frame.add(self.vbox)
-        self.frame.show_all()
+        self.toplevel = self.vbox
+
+        # For importing gtk only once (lambda not work)
+        def show_current_status(current_path):
+            self.statusbar.push(self.context_id, current_path)
+            gtk.main_iteration()
+        self.show_current_status = show_current_status
+
+        self.show_out_toplevel(None, config['outtype'], [(1, 'path', 'bytesize')])
 
     #=== Functions ============================================================
-    def start_btn_released(self, widget, start_func):
+    def start_btn_released(self, btn, start_func):
         self.stopit = False
         self.stop_btn.set_sensitive(True)
         self.start_btn.set_sensitive(False)
-        start_func(self.get_data, self.get_stopit, None, None)
+        start_func(self.get_data, self.get_stopit)
+        self.stop_btn.set_sensitive(False)
+        self.start_btn.set_sensitive(True)
 
     def stop_btn_clicked(self, widget):
         self.stopit = True
@@ -152,21 +189,39 @@ class Gtk_Presentation(object):
         self.start_btn.set_sensitive(True)
 
     def get_data(self):
-        return self.path_entry.get_text(), int(self.qty_spin.get_value())
+        for btn in self.out_rbtns:
+            if btn.get_active():
+                out = btn.get_name()
+        return out, self.path_entry.get_text(), int(self.qty_spin.get_value())
 
     def get_stopit(self):
         return self.stopit
 
-    #=== Toplevel widget for embedding to main window =========================
-    def get_toplevel(self):
-        return self.frame ###
+    def run(self):
+        pass
 
     #=== Output type selecting ================================================
     def show_out_toplevel(self, btn, outtype, results):
         print 'Entering <' + outtype + '> output mode...'
-        out_present = __import__('files.' + outtype, None, None, outtype)
-        toplevel = out_present.Gtk_Presentation().get_toplevel()
-        ###self.vbox.remove(self.vbox.get_children()[2])
-        #self.vbox.add(toplevel)
-        self.vbox.pack_start(toplevel)
-        print results
+        out_submodule = __import__('files.' + outtype, None, None, outtype)
+
+        try:
+            self.out_toplevel.destroy()
+        except:
+            pass
+
+        self.out_toplevel = out_submodule.Gtk_Presentation(results).toplevel
+        self.vbox.add(self.out_toplevel)
+        self.out_toplevel.show_all()
+###        out_submodule.Gtk_Presentation().show_results(results)
+
+#==============================================================================
+
+class Hildon_Presentation(object):
+
+    def __init__(self, start_func):
+        import gtk
+        import hildon
+
+    def run(self):
+        pass