#!/usr/bin/perl
# $Id: input-xboxir 238 2008-04-20 15:04:43Z bd $

# Copyright 2004 Bjorn Danielsson
# http://glotv.dax.nu/
#
# This file is part of GLOTV. GLOTV is free software; you can redistribute
# it and/or modify it under the terms of the GNU General Public License as
# published at this URL: http://www.gnu.org/licenses/gpl.html.

use vars qw(%config);
use Tk;
use Tk::CursorControl;			# Note: This is a separate CPAN module!
use strict;

my $PATHPREFIX = "/usr/local/glotv";
do "$PATHPREFIX/etc/glotv.conf" or die "Failed reading configuration file";

my $xirname = $config{xboxir_codes};

my $emergency_exit = 0;

# Initialize Tk 
my $MW = MainWindow->new();
####$MW->geometry("+32000+32000");
$MW->bind('<Control-c>' => \&exit);
$MW->bind('<q>' => \&exit);
$MW->overrideredirect(1);
$MW->focusmodel('active');

my $cursor = $MW->CursorControl;

my $nothing = "*****";
my $xirlabel = $nothing;

my $text = $MW->Label(-width => 10, -textvariable => \$xirlabel);
$text->pack();

sub grab_console {
    $MW->grabGlobal();
    $cursor->warpto($MW);
    $cursor->hide($MW);
    $MW->focusForce();
}

sub press_key {
    my $keycode = $Tk::event->k;
    my $keyname = $$xirname{$keycode};
    if ($keycode == 151) {
	$emergency_exit++;
    } else {
	$emergency_exit = 0;
    }
    $xirlabel = "$keyname";
    print STDOUT "$keyname 1\n";
    print STDERR "press_key $keycode $keyname\n";
}

sub release_key {
    my $keysym = $Tk::event->K;
    my $keyname = $$xirname{$Tk::event->k};
    $xirlabel = $nothing;
    print STDERR "release_key $keyname\n";
    print STDOUT "$keyname 0\n";
    exit 0 if $keysym eq 'x' || $emergency_exit >= 5;
}

$MW->bind('<KeyPress>' => \&press_key);
$MW->bind('<KeyRelease>' => \&release_key);
$MW->bind('<Map>' => \&grab_console);

$|=1;

MainLoop();
