#!/usr/bin/env python3 # # Copyright © 2015-2016 Reuben Thomas # # 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 . import argparse import importlib.metadata import signal import sys from subprocess import run from Xlib import display PROGRAM_NAME = "caffeinate" VERSION = importlib.metadata.version("cups-of-caffeine") def die(err): sys.exit(PROGRAM_NAME + ': ' + err) # Handle command line arguments parser = argparse.ArgumentParser(prog=PROGRAM_NAME, description='Inhibit desktop idleness for the duration of COMMAND') parser.add_argument('COMMAND', help='command to run') parser.add_argument('ARGUMENT', nargs='*', help='arguments to COMMAND', default=None) parser.add_argument('-V', '--version', action='version', version=PROGRAM_NAME + ' ' + VERSION) args = parser.parse_args() def make_unmapped_window(wm_name): screen = display.Display().screen() window = screen.root.create_window(0, 0, 1, 1, 0, screen.root_depth) window.set_wm_name(wm_name) window.set_wm_protocols([]) return window # Create window to use with xdg-screensaver window = make_unmapped_window("caffeinate") wid = hex(window.id) # Catch signals, to do our best to ensure inhibition is removed def signal_action(*args): release() sys.exit(1) def release(): if run(['xdg-screensaver', 'resume', wid]).returncode != 0: die("could not uninhibit desktop idleness") for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGHUP]: signal.signal(sig, signal_action) # Run command, bracketed by xdg-screensaver suspend/resume if run(['xdg-screensaver', 'suspend', wid]).returncode != 0: die("could not inhibit desktop idleness") run([args.COMMAND] + args.ARGUMENT) release()