| 1 |
#!/usr/bin/env python3 |
| 2 |
# |
| 3 |
# Copyright © 2015-2016 Reuben Thomas |
| 4 |
# |
| 5 |
# This program is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# This program is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
import argparse |
| 19 |
import importlib.metadata |
| 20 |
import signal |
| 21 |
import sys |
| 22 |
from subprocess import run |
| 23 |
|
| 24 |
from Xlib import display |
| 25 |
|
| 26 |
|
| 27 |
PROGRAM_NAME = "caffeinate" |
| 28 |
VERSION = importlib.metadata.version("cups-of-caffeine") |
| 29 |
|
| 30 |
def die(err): |
| 31 |
sys.exit(PROGRAM_NAME + ': ' + err) |
| 32 |
|
| 33 |
# Handle command line arguments |
| 34 |
parser = argparse.ArgumentParser(prog=PROGRAM_NAME, description='Inhibit desktop idleness for the duration of COMMAND') |
| 35 |
parser.add_argument('COMMAND', help='command to run') |
| 36 |
parser.add_argument('ARGUMENT', nargs='*', help='arguments to COMMAND', default=None) |
| 37 |
parser.add_argument('-V', '--version', action='version', version=PROGRAM_NAME + ' ' + VERSION) |
| 38 |
args = parser.parse_args() |
| 39 |
|
| 40 |
def make_unmapped_window(wm_name): |
| 41 |
screen = display.Display().screen() |
| 42 |
window = screen.root.create_window(0, 0, 1, 1, 0, screen.root_depth) |
| 43 |
window.set_wm_name(wm_name) |
| 44 |
window.set_wm_protocols([]) |
| 45 |
return window |
| 46 |
|
| 47 |
# Create window to use with xdg-screensaver |
| 48 |
window = make_unmapped_window("caffeinate") |
| 49 |
wid = hex(window.id) |
| 50 |
|
| 51 |
# Catch signals, to do our best to ensure inhibition is removed |
| 52 |
def signal_action(*args): |
| 53 |
release() |
| 54 |
sys.exit(1) |
| 55 |
|
| 56 |
def release(): |
| 57 |
if run(['xdg-screensaver', 'resume', wid]).returncode != 0: |
| 58 |
die("could not uninhibit desktop idleness") |
| 59 |
|
| 60 |
for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGHUP]: |
| 61 |
signal.signal(sig, signal_action) |
| 62 |
|
| 63 |
# Run command, bracketed by xdg-screensaver suspend/resume |
| 64 |
if run(['xdg-screensaver', 'suspend', wid]).returncode != 0: |
| 65 |
die("could not inhibit desktop idleness") |
| 66 |
run([args.COMMAND] + args.ARGUMENT) |
| 67 |
release() |