1# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
2#
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 2 of the License, or
6# (at your option) any later version.
7
8import os
9import sys
10
11if os.name == "nt" or sys.platform == "darwin":
12    from quodlibet.plugins import PluginNotSupportedError
13    raise PluginNotSupportedError
14
15from gi.repository import Gio
16from gi.repository import GLib
17
18from quodlibet import _
19from quodlibet import app
20from quodlibet.qltk import Icons
21from quodlibet.plugins.events import EventPlugin
22
23
24def get_toplevel_xid():
25    if app.window.get_window():
26        try:
27            return app.window.get_window().get_xid()
28        except AttributeError:  # non x11
29            pass
30    return 0
31
32
33class InhibitFlags(object):
34    LOGOUT = 1
35    USERSWITCH = 1 << 1
36    SUSPEND = 1 << 2
37    IDLE = 1 << 3
38
39
40class SessionInhibit(EventPlugin):
41    PLUGIN_ID = "screensaver_inhibit"
42    PLUGIN_NAME = _("Inhibit Screensaver")
43    PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
44                    " a song is playing.")
45    PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
46
47    DBUS_NAME = "org.gnome.SessionManager"
48    DBUS_INTERFACE = "org.gnome.SessionManager"
49    DBUS_PATH = "/org/gnome/SessionManager"
50
51    APPLICATION_ID = "quodlibet"
52    INHIBIT_REASON = _("Music is playing")
53
54    __cookie = None
55
56    def __get_dbus_proxy(self):
57        bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
58        return Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
59                                      self.DBUS_NAME,
60                                      self.DBUS_PATH,
61                                      self.DBUS_INTERFACE,
62                                      None)
63
64    def enabled(self):
65        if not app.player.paused:
66            self.plugin_on_unpaused()
67
68    def disabled(self):
69        if not app.player.paused:
70            self.plugin_on_paused()
71
72    def plugin_on_unpaused(self):
73        xid = get_toplevel_xid()
74        flags = InhibitFlags.IDLE
75
76        try:
77            dbus_proxy = self.__get_dbus_proxy()
78            self.__cookie = dbus_proxy.Inhibit('(susu)',
79                                               self.APPLICATION_ID, xid,
80                                               self.INHIBIT_REASON, flags)
81        except GLib.Error:
82            pass
83
84    def plugin_on_paused(self):
85        if self.__cookie is None:
86            return
87
88        try:
89            dbus_proxy = self.__get_dbus_proxy()
90            dbus_proxy.Uninhibit('(u)', self.__cookie)
91            self.__cookie = None
92        except GLib.Error:
93            pass
94