#! /usr/bin/env python

#
# Log file viewer for gDesklets.
#

from main import LOGFILE, ICON
from main import _
import utils
from utils.HIGDialog import HIGDialog
from utils.LogView import LogView

import gtk
import threading
import fcntl
import os
import sys
import errno



#
# Class for viewing log files.
#
class LogViewer(HIGDialog, threading.Thread):

    def __init__(self, logfile):

        threading.Thread.__init__(self, name = "LogViewer")

        self.__stop = threading.Event()
        self.__logfile = logfile

        HIGDialog.__init__(self, buttons=(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
        self.set_property("title", _("Log Messages"))

        # set the icon
        self.set_icon(gtk.gdk.pixbuf_new_from_file(ICON))

        self.__logview = LogView()
        self.__logview.set_size_request(-1, 240)

        scrwin = gtk.ScrolledWindow()
        scrwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scrwin.add(self.__logview)

        align = gtk.Alignment(0.0, 0.0, 0.0, 0.0)
        align.set_property("border-width", 6)
        align.add(scrwin)

        self.vbox.pack_start(align, False, False, 0)
        self.show_all()

        def stop(*args):
            self.__halt()
            gtk.main_quit()
            sys.exit(0)

        button = self.action_area.get_children()[-1]
        button.connect("clicked", stop)
        self.connect("destroy", stop)


    def __del__(self):
        # ensure that the thread stops
        self.__halt()


    def __halt(self):
        self.__stop.set()
        self.join()


    def __append_log(self, text, attributes):

        text = text.ljust(80)
        if (attributes):
            tag = self.__log.create_tag(None, **attributes)
            self.__log.insert_with_tags(self.__log.get_end_iter(), text + "\n",
                                        tag)
        else:
            self.__log.insert(self.__log.get_end_iter(), text + "\n")



    def run(self):

        fdesc = open(self.__logfile)
        fcntl.fcntl(fdesc, fcntl.F_SETFL, os.O_NONBLOCK)

        while not self.__stop.isSet():

            try:
                while True:

                    if self.__stop.isSet():
                        break
                    
                    line = fdesc.readline()
                    if not line:
                        break

                    utils.run_in_main_thread(self.__logview.append, line)

            except IOError, exc:
                if exc.errno != errno.EAGAIN:
                    raise

            self.__stop.wait(0.5)

        fdesc.close()



if (not os.path.exists(LOGFILE)):
    print "No log file available."
    sys.exit(1)

gtk.threads_init()
viewer = LogViewer(LOGFILE)
viewer.start()
gtk.main()
