#!/usr/bin/env python

import libglade
import gtk

import locale
locale.setlocale(locale.LC_ALL,'')

import os,stat

import re #fnmatch doesn't support *.{png,tiff}"
match_pics=re.compile(r".*\.(png|tiff|jpg|jpeg|xpm)$")

import sys

class PyView(libglade.GladeWrapper):

    def __init__(self, Filename, WindowName, start_dir="."):
        libglade.GladeWrapper.__init__(self, Filename, WindowName)

        #self.files.get_selection().set_mode(gtk.SELECTION_BROWSE)
        """
        GTK_SELECTION_NONE,     /* Nothing can be selected */
        GTK_SELECTION_SINGLE,   /* One can be selected (default) */
        GTK_SELECTION_BROWSE,   /* One must be selected */
        GTK_SELECTION_MULTIPLE, /* Multiple can be selected */
        """
        self.status_id = self.status.get_context_id("file")

        self.files_model=gtk.ListStore(str)
        self.files.set_model(self.files_model)
        files_column = gtk.TreeViewColumn("", gtk.CellRendererText(), text=0)
        self.files.append_column(files_column)

        self.dirs_model=gtk.ListStore(str)
        self.dirs.set_model(self.dirs_model)
        dirs_column = gtk.TreeViewColumn("", gtk.CellRendererText(), text=0)
        self.dirs.append_column(dirs_column)

        self._chdir(start_dir)

    def show_window(self):
        gtk.main()

    def _chdir(self,newdir):
        try:
            os.chdir(newdir)
            direntries=os.listdir(".")
            direntries.sort()
            direntries.insert(0,"..")
        except:
            return
        self.files_model.clear()
        self.dirs_model.clear()
        for direntry in direntries:
            mode=os.stat(direntry).st_mode
            if stat.S_ISREG(mode):
                if match_pics.match(direntry):
                    iter=self.files_model.append()
                    self.files_model.set(iter,0,direntry)
            elif stat.S_ISDIR(mode):
                iter=self.dirs_model.append()
                self.dirs_model.set(iter,0,direntry)

    #################
    # Signal handlers
    #################

    def on_dirs_row_activated(self, tv, *args):
        model, iter = tv.get_selection().get_selected()
        self._chdir(model.get_value(iter,0))
        tv.set_cursor(0)

    def on_files_row_selected(self, tv, *args):
        self.status.pop(self.status_id)
        model, iter = tv.get_selection().get_selected()
        filename=model.get_value(iter,0)
        self.image.set_from_file(filename)
        size=locale.format("%d",os.stat(filename).st_size,1)
        #self.status.push(self.status_id,size+" bytes")
        self.status.push(self.status_id,os.getcwd()+"/"+filename)

    def quit(self, *args):
        #gtk.main_quit()
		pass

    def on_pyview_destroy(self, event):
        self.quit()


if __name__ == "__main__":
	if len(sys.argv) == 2:
		start_dir=sys.argv[1]
	else:
		start_dir="./"
	pv = PyView("./pyview.glade", "pyview", start_dir)
	pv.show_window()