#!/usr/bin/env python
"""A bloated program that runs a command in a terminal on a keypress.

Needs Python KDE bindings. Guess where the bloat comes from.

Usage:

  ./sleeper.py <command>

<F12> is used for running the command by default, but you can change it below.

"""

import sys
import os
import threading
import signal
from kdecore import *

RUN_KEY = 'F12'

lock = threading.Lock()
anticipated = False


class RunnerThread(threading.Thread):

    command = ''

    def run(self):
        global anticipated, cmd
        while anticipated:
            anticipated = False
            print 'Running', self.command
            os.system(self.command)
            self.printBanner()
        lock.release()

    def printBanner(self):
        color = '\033[33m' # yellow
        reset = '\033[0;0m'
        print color + '='*79 + reset


def callback():
    global anticipated
    anticipated = True # XXX race condition
    if lock.acquire(False):
        # No processes running in the background.
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        thread = RunnerThread()
        thread.start()


RunnerThread.command = ' '.join(sys.argv[1:])
sys.argv = sys.argv[:1]

app = KApplication(sys.argv, "Sleeper")
accels = KGlobalAccel(None)

# Register the shortcut
shortcut = KShortcut(RUN_KEY)
assert shortcut.keyCodeQt(), RUN_KEY
name = "sleep"
accels.insert(name, name, name, shortcut, shortcut, callback)
accels.updateConnections()

# Handle Ctrl+C properly.
signal.signal(signal.SIGINT, signal.SIG_DFL)

# XXX Does not work
def proxy(*ignored):
    print 'OK'
    callback()
signal.signal(signal.SIGUSR1, proxy)

# Initial run
callback()

app.exec_loop()

