#!/usr/bin/python

# kevents
#
# Copyright (C) 2013 Kano Computing Ltd.
# License:   http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#

import struct
import sys
import os

infile_path = "/dev/input/event" + (sys.argv[1] if len(sys.argv) > 1 else "0")

#long int, long int, unsigned short, unsigned short, unsigned int
FORMAT = 'llHHI'
EVENT_SIZE = struct.calcsize(FORMAT)

#open file in binary mode
in_file = open(infile_path, "rb")

event = in_file.read(EVENT_SIZE)

while event:
    (tv_sec, tv_usec, type, code, value) = struct.unpack(FORMAT, event)

#    if type != 0 or code != 0 or value != 0:
#        print("Event type %u, code %u, value: %u at %d, %d" % \
#            (type, code, value, tv_sec, tv_usec))
#    else:
#        # Events with code, type and value == 0 are "separator" events
#        print("===========================================")

    if type == 1 and code == 66 and value == 1:
        # F8 key press event
        # Switching window focus to Make Minecraft
        os.system('sudo /usr/bin/uinput')
        os.system('xdotool windowactivate $(xdotool search --name "Make Minecraft")')

    #if type == 1 and code == 66 and value == 0:
        #print 'F8 key release event'

    event = in_file.read(EVENT_SIZE)

in_file.close()
