#!/usr/bin/python
#
# Copyright © 2009-2014 The Caffeine Developers
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import dbus
import logging
import argparse
import signal
from ewmh import EWMH
from gi.repository import GObject, Gtk

# Handle command-line arguments
parser = argparse.ArgumentParser(prog='caffeine', description='Prevent desktop idleness in full-screen mode')
parser.add_argument('-V', '--version', action='version', version='caffeine 2.7.2')
parser.parse_args()

ewmh = EWMH()

class Caffeine(GObject.GObject):

    def __init__(self):
        GObject.GObject.__init__(self)
        self.idlenessInhibited = False
        self.screenSaverCookie = None

        # Add hook for full-screen check (same interval as mplayer's heartbeat command)
        # FIXME: add capability to xdg-screensaver to report timeout
        GObject.timeout_add(30000, self._check_for_fullscreen)

    def _check_for_fullscreen(self):
        win = ewmh.getActiveWindow()
        inhibit = False
        if win != None:
            try:
                inhibit = '_NET_WM_STATE_FULLSCREEN' in ewmh.getWmState(win, str=True)
            except:
                pass

        # If inhibition state has changed, take action
        if self.idlenessInhibited != inhibit:
            self.idlenessInhibited = inhibit

            bus = dbus.SessionBus()
            self.susuProxy = bus.get_object('org.freedesktop.ScreenSaver', '/org/freedesktop/ScreenSaver')
            self.iface = dbus.Interface(self.susuProxy, 'org.freedesktop.ScreenSaver')

            if inhibit:
                self.screenSaverCookie = self.iface.Inhibit('net.launchpad.caffeine', "Caffeine is inhibiting desktop idleness")
                logging.info("Caffeine is inhibiting desktop idleness")
            else:
                if self.screenSaverCookie != None:
                    self.iface.UnInhibit(self.screenSaverCookie)
                logging.info("Caffeine is no longer inhibiting desktop idleness")

        # Return True so timeout is rerun
        return True


# Set up and run
logging.basicConfig(level=logging.INFO)
signal.signal(signal.SIGINT, signal.SIG_DFL)
GObject.threads_init()
Caffeine()
Gtk.main()
