Moved dbus function out to it's own abstracted class, did various code

cleanups in oblogout.py
This commit is contained in:
2009-03-29 14:52:34 +01:00
parent 83ca843372
commit e5ad550d75
2 changed files with 150 additions and 59 deletions

138
oblogout/dbushandler.py Executable file
View File

@@ -0,0 +1,138 @@
#!/usr/bin/env python
# Crunchbang Openbox Logout
# - GTK/Cairo based logout box styled for Crunchbang
#
# Andrew Williams <andy@tensixtyone.com>
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import logging
import os
import dbus
class DbusController (object):
def __init__(self):
self.logger = logging.getLogger('oblogout.obdbus')
def __check_perms(self, id):
""" Check if we have permissions for a action """
kit = dbus.SystemBus().get_object('org.freedesktop.PolicyKit','/')
if(kit == None):
print("Error: Could not get PolicyKit D-Bus Interface\n")
return False
if kit.IsProcessAuthorized(id, dbus.UInt32(os.getpid()), False):
self.logging.debug("Authorised to use %s" % id)
return True
def __auth_perms(self, id):
""" Check if we have permissions for a action, if not, try to obtain them via PolicyKit """
if self.__check_perms(id):
return True
else:
kit = dbus.SystemBus().get_object('org.freedesktop.PolicyKit','/')
if(kit == None):
print("Error: Could not get PolicyKit D-Bus Interface\n")
return False
return kit.ObtainAuthorization(id, (dbus.UInt32)(xid), (dbus.UInt32)(os.getpid()))
def __get_sessions(self):
""" Using DBus and ConsoleKit, get the number of sessions. This is used by PolicyKit to dictate the
multiple sessions permissions for the various reboot/shutdown commands """
# Check the number of active sessions
manager_obj = dbus.SystemBus().get_object ('org.freedesktop.ConsoleKit', '/org/freedesktop/ConsoleKit/Manager')
manager = dbus.Interface (manager_obj, 'org.freedesktop.ConsoleKit.Manager')
cnt = 0
seats = manager.GetSeats ()
for sid in seats:
seat_obj = dbus.SystemBus().get_object ('org.freedesktop.ConsoleKit', sid)
seat = dbus.Interface (seat_obj, 'org.freedesktop.ConsoleKit.Seat')
cnt += len(seat.GetSessions())
#print len(seat.GetSessions())
return cnt
def check_ability(self, action):
"""Check if HAL can complete action type requests, for example, suspend, hiberate, and safesuspend"""
dbus_hal = dbus.SystemBus().get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer")
pm = dbus.Interface(dbus_hal, "org.freedesktop.Hal.Device.SystemPowerManagement")
if action == 'suspend':
return pm.CanSuspend
elif action == 'hibernate':
return pm.CanHibernate
elif action == 'safesuspend':
if not pm.CanHibernate or not pm.CanSuspend:
return False
return True
def restart(self):
"""Restart the system via HAL, if we do not have permissions to do so obtain them via PolicyKit"""
if self.__get_sessions() > 1:
if self.__auth_perms("org.freedesktop.hal.power-management.reboot-multiple-sessions"):
dbus_hal = dbus.SystemBus().get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer")
pm = dbus.Interface(dbus_hal, "org.freedesktop.Hal.Device.SystemPowerManagement")
return pm.Reboot()
else:
return False
def shutdown(self):
"""Shutdown the system via HAL, if we do not have permissions to do so obtain them via PolicyKit"""
if self.__get_sessions() > 1:
if self.__auth_perms("org.freedesktop.hal.power-management.shutdown-multiple-sessions"):
dbus_hal = dbus.SystemBus().get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer")
pm = dbus.Interface(dbus_hal, "org.freedesktop.Hal.Device.SystemPowerManagement")
return pm.Shutdown()
else:
return False
print
def suspend(self):
pass
def hibernate(self):
pass
def safesuspend(self):
pass
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
t = DbusController()
t.restart()

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env python2.5
#!/usr/bin/env python
# Crunchbang Openbox Logout
# - GTK/Cairo based logout box styled for Crunchbang
@@ -189,16 +189,8 @@ class OpenboxLogout():
self.usehal = True
if self.usehal:
try:
import dbus
import dbus.exceptions
except:
print "Python DBUS modules missing, install python-dbus"
sys.exit()
self._dbus_bus = dbus.SystemBus()
dbus_hal = self._dbus_bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer")
self.dbus_powermanagement = dbus.Interface(dbus_hal, "org.freedesktop.Hal.Device.SystemPowerManagement")
from dbushandler import DbusController
self.dbus = DbusController()
# Check the looks section and load the config as required
if self.parser.has_section("looks"):
@@ -259,18 +251,9 @@ class OpenboxLogout():
list.remove(button)
else:
if self.usehal:
if button == 'suspend':
if not self.dbus_powermanagement.CanSuspend:
self.logger.warning(_("Can't Suspend, disabling button"))
list.remove(button)
elif button == 'hibernate':
if not self.dbus_powermanagement.CanHibernate:
self.logger.warning(_("Can't Hibernate, disabling button"))
list.remove(button)
elif button == 'safesuspend':
if not self.dbus_powermanagement.CanHibernate or not self.dbus_powermanagement.CanSuspend:
self.logger.warning(_("Can't Safe Suspend, disabling button"))
list.remove(button)
if not self.dbus.check_ability(button):
self.logger.warning(_("Can't %s, disabling button" % button))
list.remove(button)
if len(list) == 0:
self.logger.warning(_("No valid buttons found, resetting to defaults"))
@@ -352,30 +335,19 @@ class OpenboxLogout():
widget.pack_start(box, False, False)
def __polkit_getauth(self, id):
policykit = self._dbus_bus.get_object('org.freedesktop.PolicyKit.AuthenticationAgent', '/', "org.gnome.PolicyKit.AuthorizationManager.SingleInstance")
if(policykit == None):
print("Error: Could not get PolicyKit D-Bus Interface\n")
return policykit.ObtainAuthorization(id, (dbus.UInt32)(xid), (dbus.UInt32)(os.getpid()))
def click_button(self, widget, data=None):
if (data == 'logout'):
self.exec_cmd(self.cmd_logout)
elif (data == 'restart'):
if self.usehal:
if self.__polkit_getauth("org.freedesktop.hal.power-management.reboot-multiple-sessions"):
self.dbus_powermanagement.Reboot()
self.dbus.restart()
else:
self.exec_cmd(self.cmd_restart)
elif (data == 'shutdown'):
if self.usehal:
if self.__polkit_getauth("org.freedesktop.hal.power-management.shutdown-multiple-sessions"):
self.dbus_powermanagement.Shutdown()
self.dbus.shutdown()
else:
self.exec_cmd(self.cmd_shutdown)
@@ -383,10 +355,8 @@ class OpenboxLogout():
self.window.hide()
self.exec_cmd(self.cmd_lock)
if self.usehal:
try:
self.dbus_powermanagement.Suspend(0)
except:
pass
self.dbus.suspend()
else:
self.exec_cmd(self.cmd_suspend)
@@ -394,10 +364,7 @@ class OpenboxLogout():
self.window.hide()
self.exec_cmd(self.cmd_lock)
if self.usehal:
try:
self.dbus_powermanagement.Hiberate()
except:
pass
self.dbus.hibernate()
else:
self.__exec_cmd(self.cmd_hibernate)
@@ -405,10 +372,7 @@ class OpenboxLogout():
self.window.hide()
if self.usehal:
try:
self.dbus_powermanagement.SuspendHybrid(0)
except:
pass
self.dbus.safesuspend()
else:
self.exec_cmd(self.cmd_safesuspend)
@@ -438,14 +402,3 @@ class OpenboxLogout():
self.window.show_all()
gtk.main()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
if os.path.exists('openbox-logout.conf'):
config = 'openbox-logout.conf'
else:
config = None
app = OpenboxLogout(config)
app.run_logout()