#!/usr/bin/env python2
 
#  Gnome15 - Suite of tools for the Logitech G series keyboards and headsets
#  Copyright (C) 2011 Brett Smith <tanktarta@blueyonder.co.uk>
#
#  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 <http://www.gnu.org/licenses/>.

import optparse
import select
import fcntl
import pyinputevent.scancodes as S
from pyinputevent.uinput import UInputDevice
from pyinputevent.pyinputevent import InputEvent, SimpleDevice
from pyinputevent.keytrans import *

EVIOCGRAB = 0x40044590

class ForwardDevice(SimpleDevice):
    def __init__(self, *args, **kwargs):
        SimpleDevice.__init__(self, *args, **kwargs)
        self.ctrl = False
        self.alt = False
        self.shift = False
            
    def monitor(self):
        poll = select.poll()
        poll.register(self, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLNVAL | select.POLLERR)
        fno = self.fileno()
        fcntl.ioctl(fno, EVIOCGRAB, 1)
        while True:
            for x, e in poll.poll():
                self.read()

    @property
    def modcode(self):
        code = 0
        if self.shift:
            code += 1
        if self.ctrl:
            code += 2
        if self.alt:
            code += 4
        return code
    
    def receive(self, event):
        print "Event: %s" % str(event)
        if event.etype == S.EV_KEY:
            key = str(event.ecode)
            if event.evalue == 2:
                print "Auto %s" % key
            else:
                if event.evalue == 1:
                    print "Down %s" % key
                else:
                    print "Up %s" % key
        elif event.etype == 0:
            print "Etype 0"
        else:
            print "Unhandled event: %s" % str(event)
    
if __name__ == "__main__":
    parser = optparse.OptionParser()
    (options, args) = parser.parse_args()
    device = ForwardDevice(args[0])
    device.monitor()
    