'''
Some code to monitor xscreensaver
'''

import gobject

class XScreenSaverMonitor(gobject.GObject):

    __gsignals__ = { 'state-changed': (gobject.SIGNAL_RUN_LAST, None,
                                       (str,)) }

    def __init__(self):
        '''Starts monitoring xscreensaver; raises GError if xscreensaver-command not available'''
        gobject.GObject.__init__(self)
        pid, _, stdout, _ = gobject.spawn_async(
            [ 'xscreensaver-command', '-watch'],
            standard_input=False, standard_output=True, standard_error=False,
            flags=gobject.SPAWN_SEARCH_PATH)
        chan = gobject.IOChannel(filedes=stdout)
        chan.set_flags(gobject.IO_FLAG_NONBLOCK)
        chan.add_watch(gobject.IO_IN, self.__io_cb)

    def __io_cb(self, chan, condition):
        if condition & gobject.IO_IN:
            line = chan.readline()
            if line:
                state = line.split(' ', 1)[0]
                self.emit('state-changed', state)
        return True
        

if __name__ == '__main__':
    def state_changed_cb(obj, state):
        print "*** ", state
    XScreenSaverMonitor().connect("state-changed", state_changed_cb)
    gobject.MainLoop().run()

