/*
 * linux/kernel/chr_drv/keyboard.c
 *
 * Keyboard driver for Linux v0.96 using Latin-1.
 *
 * Written for linux by Johan Myreen as a translation from
 * the assembly version by Linus (with diacriticals added)
 *
 * Loadable keymaps by Risto Kankkunen, May 1993
 *
 * This file is subject to the terms and conditions of the GNU General Public
 * License.  See the file README.legal in the main directory of this archive
 * for more details.
 */

/*
 * general 680x0 support by Hamish Macdonald
 */

#include <linux/sched.h>
#include <linux/tty.h>
#include <linux/mm.h>
#include <linux/keyboard.h>
#include <linux/config.h>
#include <linux/signal.h>
#include <linux/string.h>

#include <asm/bitops.h>

#ifndef KBD_DEFFLAGS

#ifdef CONFIG_KBD_META
#define KBD_META (1 << VC_META)
#else
#define KBD_META 0
#endif

#ifdef CONFIG_KBD_NUML
#define KBD_NUML (1 << VC_NUMLOCK)
#else
#define KBD_NUML 0
#endif

#define KBD_DEFFLAGS (KBD_NUML | (1 << VC_REPEAT) | KBD_META)
#endif

extern void do_keyboard_interrupt(void);
extern void change_console(unsigned int new_console);
extern void scrollback(int);
extern void scrollfront(int);

unsigned char kbd_read_mask = 0x01;	/* modified by psaux.c */

unsigned long kbd_dead_keys = 0;
unsigned long kbd_prev_dead_keys = 0;

/* shift state counters.. */
static unsigned char k_down[NR_SHIFT] = {0, };
/* keyboard key bitmap */
static unsigned long key_down[8] = { 0, };

static int want_console = -1;
static int last_console = 0;		   /* last used VC */
static char rep = 0;			   /* flag telling character repeat */
struct kbd_struct kbd_table[NR_CONSOLES];
static struct kbd_struct *kbd = kbd_table;
static struct tty_struct *tty = NULL;

typedef void (*k_hand)(unsigned char value, char up_flag);

static void do_self(unsigned char value, char up_flag);
static void do_fn(unsigned char value, char up_flag);
static void do_spec(unsigned char value, char up_flag);
static void do_pad(unsigned char value, char up_flag);
static void do_dead(unsigned char value, char up_flag);
static void do_cons(unsigned char value, char up_flag);
static void do_cur(unsigned char value, char up_flag);
static void do_shift(unsigned char value, char up_flag);
static void do_meta(unsigned char value, char up_flag);
static void do_ascii(unsigned char value, char up_flag);
static void do_lock(unsigned char value, char up_flag);

static k_hand key_handler[] = {
	do_self, do_fn, do_spec, do_pad, do_dead, do_cons, do_cur, do_shift,
	do_meta, do_ascii, do_lock
};

/* maximum values each key_handler can handle */
const int max_vals[] = {
	255, NR_FUNC - 1, 13, 16, 4, 255, 3, NR_SHIFT,
	255, 9, 3
};

const int NR_TYPES = (sizeof(max_vals) / sizeof(int));

static int shift_state = 0;
static int diacr = -1;
static int npadch = 0;

static void put_queue(int);
static unsigned int handle_diacr(unsigned int);

void process_scancode (int scancode)
{
	char break_flag;

	kbd_prev_dead_keys |= kbd_dead_keys;
	if (!kbd_dead_keys)
		kbd_prev_dead_keys = 0;
	kbd_dead_keys = 0;
	tty = TTY_TABLE(0);
	kbd = kbd_table + fg_console;
	if (vc_kbd_flag(kbd,VC_RAW)) {
		memset(k_down, 0, sizeof(k_down));
		memset(key_down, 0, sizeof(key_down));
		shift_state = 0;
		put_queue (scancode);
		goto end_kbd_intr;
	}
	/*
	 *  Repeat a key only if the input buffers are empty or the
	 *  characters get echoed locally. This makes key repeat usable
	 *  with slow applications and under heavy loads.
	 */
	break_flag = scancode > 0x7f;
	scancode &= 0x7f;

	rep = 0;
	if (break_flag)
		clear_bit(scancode, key_down);
	else
		rep = set_bit(scancode, key_down);

	if (vc_kbd_flag(kbd, VC_MEDIUMRAW)) {
		put_queue(scancode);
		return;
	}

	if (!rep ||
	    (vc_kbd_flag(kbd,VC_REPEAT) && tty &&
	     (L_ECHO(tty) || (EMPTY(&tty->secondary) && EMPTY(&tty->read_q)))))
	{
		u_short key_code;

		key_code = key_map[shift_state][scancode];
		(*key_handler[key_code >> 8])(key_code & 0xff, break_flag);
	     }
end_kbd_intr:
	do_keyboard_interrupt();
}

void put_queue(int ch)
{
	struct tty_queue *qp;

	wake_up(&keypress_wait);
	if (!tty)
		return;
	qp = &tty->read_q;

	if (LEFT(qp)) {
		qp->buf[qp->head] = ch;
		INC(qp->head);
		wake_up_interruptible(&qp->proc_list);
	}
}

static void puts_queue(char *cp)
{
	struct tty_queue *qp;
	char ch;

	/* why interruptible here, plain wake_up above? */
	wake_up_interruptible(&keypress_wait);
	if (!tty)
		return;
	qp = &tty->read_q;

	while ((ch = *(cp++)) != 0) {
		if (LEFT(qp)) {
			qp->buf[qp->head] = ch;
			INC(qp->head);
		}
	}
	wake_up_interruptible(&qp->proc_list);
}

static void applkey(int key, char mode)
{
	static char buf[] = { 0x1b, 'O', 0x00, 0x00 };

	buf[1] = (mode ? 'O' : '[');
	buf[2] = key;
	puts_queue(buf);
}

static void enter(void)
{
	put_queue(13);
	if (vc_kbd_flag(kbd,VC_CRLF))
		put_queue(10);
}

static void caps_toggle(void)
{
	if (rep)
		return;
	chg_vc_kbd_flag(kbd,VC_CAPSLOCK);
}

static void caps_on(void)
{
	if (rep)
		return;
	set_vc_kbd_flag(kbd,VC_CAPSLOCK);
}

static void show_ptregs(void)
{
    return;
}

static void hold(void)
{
	if (rep || !tty)
		return;
	if (vc_kbd_flag(kbd, VC_SCROLLOCK))
		/* pressing srcoll lock 2nd time sends ^Q, ChN */
		put_queue(START_CHAR(tty));
	else
		/* pressing srcoll lock 1st time sends ^S, ChN */
		put_queue(STOP_CHAR(tty));
	chg_vc_kbd_flag(kbd,VC_SCROLLOCK);
}

static void num(void)
{
#if 0
	if (k_down[KG_CTRL]) {
		/* pause key pressed, sends E1 1D 45, ChN */
		chg_vc_kbd_flag(kbd,VC_PAUSE);
		return;
	}
#endif
	if (vc_kbd_flag(kbd,VC_APPLIC)) {
		applkey('P', 1);
		return;
	}
	if (!rep)       /* no autorepeat for numlock, ChN */
		chg_vc_kbd_flag(kbd,VC_NUMLOCK);
}

static void lastcons(void)
{
	/* pressing alt-printscreen switches to the last used console, ChN */
	want_console = last_console;
}

static void send_intr(void)
{
	if (tty)
		put_queue(INTR_CHAR(tty));
}

static void scrll_forw(void)
{
	scrollfront(0);
}

static void scrll_back(void)
{
	scrollback(0);
}

static void boot_it(void)
{
#if 0
	ctrl_alt_del();
#endif
}


static void do_spec(unsigned char value, char up_flag)
{
	typedef void (*fnp)(void);
	fnp fn_table[] = {
		NULL,		enter,		show_ptregs,	show_mem,
		show_state,	send_intr,	lastcons,	caps_toggle,
		num,		hold,		scrll_forw,	scrll_back,
		boot_it,	caps_on
	};

	if ((char)value >= sizeof(fn_table)/sizeof(fnp))
		return;
	if (up_flag)
		return;
	if (!fn_table[value])
		return;
	fn_table[value]();
}

static void do_self(unsigned char value, char up_flag)
{
	if (up_flag)
		return; 	/* no action, if this is a key release */

	value = handle_diacr(value);

	/* kludge... but works for ISO 8859-1 */
	if (vc_kbd_flag(kbd,VC_CAPSLOCK))
		if ((value >= 'a' && value <= 'z')
		    || (value >= 224 && value <= 254)) {
			value -= 32;
		}

	put_queue(value);
}

static unsigned char ret_diacr[] =
	{'`', '\'', '^', '~', '"' };            /* Must not end with 0 */

/* If a dead key pressed twice, output a character corresponding to it, */
/* otherwise just remember the dead key.				*/

static void do_dead(unsigned char value, char up_flag)
{
	if (up_flag)
		return;

	if (diacr == value) {   /* pressed twice */
		diacr = -1;
		put_queue(ret_diacr[value]);
		return;
	}
	diacr = value;
}

/* If no pending dead key, return the character unchanged. Otherwise,	*/
/* if space if pressed, return a character corresponding the pending	*/
/* dead key, otherwise try to combine the two.				*/

unsigned int handle_diacr(unsigned int ch)
{
	static unsigned char accent_table[5][64] = {
	" \300BCD\310FGH\314JKLMN\322PQRST\331VWXYZ[\\]^_"
	"`\340bcd\350fgh\354jklmn\362pqrst\371vwxyz{|}~",   /* accent grave */

	" \301BCD\311FGH\315JKLMN\323PQRST\332VWX\335Z[\\]^_"
	"`\341bcd\351fgh\355jklmn\363pqrst\372vwx\375z{|}~", /* accent acute */

	" \302BCD\312FGH\316JKLMN\324PQRST\333VWXYZ[\\]^_"
	"`\342bcd\352fgh\356jklmn\364pqrst\373vwxyz{|}~",   /* circumflex */

	" \303BCDEFGHIJKLM\321\325PQRSTUVWXYZ[\\]^_"
	"`\343bcdefghijklm\361\365pqrstuvwxyz{|}~",         /* tilde */

	" \304BCD\313FGH\317JKLMN\326PQRST\334VWXYZ[\\]^_"
	"`\344bcd\353fgh\357jklmn\366pqrst\374vwx\377z{|}~" /* dieresis */
	};
	int d = diacr, e;

	if (diacr == -1)
		return ch;

	diacr = -1;
	if (ch == ' ')
		return ret_diacr[d];

	if (ch >= 64 && ch <= 122) {
		e = accent_table[d][ch - 64];
		if (e != ch)
			return e;
	}
	put_queue(ret_diacr[d]);
	return ch;
}

static void do_cons(unsigned char value, char up_flag)
{
	if (up_flag)
		return;
	want_console = value;
}

static void do_fn(unsigned char value, char up_flag)
{
	if (up_flag)
		return;
	puts_queue(func_table[value]);
}

static void do_pad(unsigned char value, char up_flag)
{
	static char *pad_chars = "0123456789+-*/\015,.";
	static char *app_map = "pqrstuvwxylSRQMnn";

	if (up_flag)
		return; 	/* no action, if this is a key release */

	/* kludge... shift forces cursor/number keys */
	if (vc_kbd_flag(kbd,VC_APPLIC) && !k_down[KG_SHIFT]) {
		applkey(app_map[value], 1);
		return;
	}

	if (!vc_kbd_flag(kbd,VC_NUMLOCK))
		switch (value) {
			case KVAL(K_PCOMMA):
			case KVAL(K_PDOT):
				do_fn(KVAL(K_REMOVE), 0);
				return;
			case KVAL(K_P0):
				do_fn(KVAL(K_INSERT), 0);
				return;
			case KVAL(K_P1):
				do_fn(KVAL(K_SELECT), 0);
				return;
			case KVAL(K_P2):
				do_cur(KVAL(K_DOWN), 0);
				return;
			case KVAL(K_P3):
				do_fn(KVAL(K_PGDN), 0);
				return;
			case KVAL(K_P4):
				do_cur(KVAL(K_LEFT), 0);
				return;
			case KVAL(K_P6):
				do_cur(KVAL(K_RIGHT), 0);
				return;
			case KVAL(K_P7):
				do_fn(KVAL(K_FIND), 0);
				return;
			case KVAL(K_P8):
				do_cur(KVAL(K_UP), 0);
				return;
			case KVAL(K_P9):
				do_fn(KVAL(K_PGUP), 0);
				return;
			case KVAL(K_P5):
				applkey('G', vc_kbd_flag(kbd, VC_APPLIC));
				return;
		}

	put_queue(pad_chars[value]);
	if (value == KVAL(K_PENTER) && vc_kbd_flag(kbd, VC_CRLF))
		put_queue(10);
}

static void do_cur(unsigned char value, char up_flag)
{
	static char *cur_chars = "BDCA";
	if (up_flag)
		return;

	applkey(cur_chars[value], vc_kbd_flag(kbd,VC_CKMODE));
}

static void do_shift(unsigned char value, char up_flag)
{
	int old_state = shift_state;

	if (rep)
		return;

	/* kludge... */
	if (value == KVAL(K_CAPSSHIFT)) {
		value = KVAL(K_SHIFT);
		clr_vc_kbd_flag(kbd, VC_CAPSLOCK);
	}

	if (up_flag) {
		if (k_down[value])
			k_down[value]--;
	} else
		k_down[value]++;

	if (k_down[value])
		shift_state |= (1 << value);
	else
		shift_state &= ~ (1 << value);

	/* kludge */
	if (up_flag && shift_state != old_state && npadch != 0) {
		put_queue(npadch);
		npadch = 0;
	}
}

static void do_meta(unsigned char value, char up_flag)
{
	if (up_flag)
		return;

	if (vc_kbd_flag(kbd, VC_META)) {
		put_queue('\033');
		put_queue(value);
	} else
		put_queue(value | 0x80);
}

static void do_ascii(unsigned char value, char up_flag)
{
	if (up_flag)
		return;

	npadch = (npadch * 10 + value) % 1000;
}

/* done stupidly to avoid coding in any dependencies of
lock values, shift values and kbd flags bit positions */
static void do_lock(unsigned char value, char up_flag)
{
	if (up_flag || rep)
		return;
	switch (value) {
		case KVAL(K_SHIFTLOCK):
			chg_vc_kbd_flag(kbd, VC_SHIFTLOCK);
			do_shift(KG_SHIFT, !vc_kbd_flag(kbd, VC_SHIFTLOCK));
			break;
		case KVAL(K_CTRLLOCK):
			chg_vc_kbd_flag(kbd, VC_CTRLLOCK);
			do_shift(KG_CTRL, !vc_kbd_flag(kbd, VC_CTRLLOCK));
			break;
		case KVAL(K_ALTLOCK):
			chg_vc_kbd_flag(kbd, VC_ALTLOCK);
			do_shift(KG_ALT, !vc_kbd_flag(kbd, VC_ALTLOCK));
			break;
		case KVAL(K_ALTGRLOCK):
			chg_vc_kbd_flag(kbd, VC_ALTGRLOCK);
			do_shift(KG_ALTGR, !vc_kbd_flag(kbd, VC_ALTGRLOCK));
			break;
	}
}

unsigned long kbd_init(unsigned long kmem_start)
{
    int i;
    struct kbd_struct * kbd;

    kbd = kbd_table + 0;
    for (i = 0 ; i < NR_CONSOLES ; i++,kbd++) {
	kbd->flags = KBD_DEFFLAGS;
	kbd->default_flags = KBD_DEFFLAGS;
    }

    return mach_keyb_init (kmem_start);
}
