#import <appkit/Application.h>
#import <appkit/ScrollView.h>
#import "Appender.h"
#import "EtermHandle.h"

extern int kc_keyforcode(int code, int flags);

@implementation EtermHandle

- (BOOL)acceptsFirstResponder
{
    return YES;
}

// We shouldn't give up first responder status since we have to catch
// the keyDown event. Other events will however be passed to next
// responder if there is any.

- resignFirstResponder;		
{
    return nil;
};

/*
 * Keyboard input is given to the child apps process.
 */

- keyDown: (NXEvent *)theEvent;
{
    NXEvent eventbuf;
    static char buf[1024];
    int i = 0;
    int code;

    if (theEvent->flags & NX_NUMERICPADMASK &&
	theEvent->data.key.charCode >= 0xac &&
	theEvent->data.key.charCode <= 0xaf) {
	/* Arrow keys (left, up, right, down) */
	buf[i++] = "\002\020\006\016"[theEvent->data.key.charCode - 0xac];
    }
    else if (theEvent->flags & NX_NUMERICPADMASK &&
	     theEvent->data.key.charCode == 0x03) {
	/* Enter key */
	buf[i++] = '\r';
    }
    else if (theEvent->flags & NX_ALTERNATEMASK) {
	/* Handle ALT key as a META key */
	code = kc_keyforcode(theEvent->data.key.keyCode, theEvent->flags);
	if (code != -1) {
	    buf[i++] = code | 0x80;
	}
    }
    else buf[i++] = theEvent->data.key.charCode;

    /* Grab as many keypressed events as we can from a modal event loop */
    while (i < sizeof(buf) &&
	   (theEvent = [NXApp peekNextEvent:NX_ALLEVENTS into:&eventbuf]) &&
	   theEvent->type == NX_KEYDOWN &&
	   !(theEvent->flags & NX_COMMANDMASK)) {
	theEvent = [NXApp getNextEvent:NX_ALLEVENTS];

	if (theEvent->flags & NX_NUMERICPADMASK &&
	    theEvent->data.key.charCode >= 0xac &&
	    theEvent->data.key.charCode <= 0xaf) {
	    /* Arrow keys (left, up, right, down) */
	    buf[i++] = "\002\020\006\016"[theEvent->data.key.charCode - 0xac];
	}
	else if (theEvent->flags & NX_NUMERICPADMASK &&
		 theEvent->data.key.charCode == 0x03) {
	    /* Enter key */
	    buf[i++] = '\r';
	}
	else if (theEvent->flags & NX_ALTERNATEMASK) {
	    /* Handle ALT key as a META key */
	    code = kc_keyforcode(theEvent->data.key.keyCode, theEvent->flags);
	    if (code != -1) {
		buf[i++] = code | 0x80;
	    }
	}
	else buf[i++] = theEvent->data.key.charCode;
    }

    buf[i] = 0;			// close the string

    [deputy inputToApp:buf];

    return self;
}

- window;
{
    return responseWindow;
};

- windowDidBecomeKey:sender;
{
    [responseWindow makeFirstResponder:self];
    [self setNextResponder: [deputy docView]];

    return self;
};

@end
