The gnome-screensaver FAQ provides detail on the dbus signal fired when gnome-screensaver activates and deactivates. The FAQ even has sample perl code to respond to the signal. Unfortunately the sample code polls dbus-monitor which is too inefficient for script I plan to run in the background on my laptop.
Python offers a great dbus library which allows signal receivers to be registered with dbus resulting in an efficient event listener.
On to the script.
Step 1: Setup the required files and directories
- Make a directory for your work:
sudo mkdir -p /opt/ssTrigger
- Change yourself the owner of the new directory:
sudo chown `whoami`:`whoami` /opt/ssTrigger
- Create stubs for the scripts to be used
touch /opt/ssTrigger/ssTrigger /opt/ssTrigger/ssStart /opt/ssTrigger/ssStop
- Make the stub scripts executable:
chmod 755 /opt/ssTrigger/*
Step 2: Edit the ssTrigger script
- Open the ssTriger file created earlier:
gedit /opt/ssTrigger/ssTrigger
- Add the following to ssTrigger:
#!/usr/bin/env python from gobject import MainLoop from dbus import SessionBus from dbus.mainloop.glib import DBusGMainLoop from subprocess import Popen class SSTrigger: def __init__(self): DBusGMainLoop(set_as_default=True) self.mem='ActiveChanged' self.dest='org.gnome.ScreenSaver' self.bus=SessionBus() self.loop=MainLoop() self.bus.add_signal_receiver(self.catch,self.mem,self.dest) def catch(self,ssOn): if ssOn == 1: #Screensaver turned on Popen(["/opt/ssTrigger/ssStart"]) else: #Screensaver turned off Popen(["/opt/ssTrigger/ssStop"]) SSTrigger().loop.run()
- Save and close the file.
Step 3: Set ssTrigger to start when you login:
- Open the Startup Applications menu:
System -> Preferences -> Startup Applications
- Click "Add" to create a new startup application.
- Enter the following details:
Name: Screensaver Trigger Script
Command: /opt/ssTrigger/ssTrigger
- Click "Add" to save your new application.
- Restart your computer.
Finishing up:
Once you have restarted you can run:
ps aux | grep ssTriggerCheck the output to make sure the ssTrigger script has started at login.
Edit the ssStart and ssStop scripts to run commands as gnome-screensaver starts and stops respectively.