/*
 *	@(#)keymap.c 1.22 91/09/14 Copyright 1990-91 Sun Microsystems
 *
 * This file is a product of Sun Microsystems, Inc. and is provided for
 * unrestricted use provided that this legend is included on all tape
 * media and as a part of the software program in whole or part.  Users
 * may copy or modify this file without charge, but are not authorized to
 * license or distribute it to anyone else except as part of a product
 * or program developed by the user.
 * 
 * THIS FILE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
 * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
 * 
 * This file is provided with no support and without any obligation on the
 * part of Sun Microsystems, Inc. to assist in its use, correction,
 * modification or enhancement.
 * 
 * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
 * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS FILE
 * OR ANY PART THEREOF.
 * 
 * In no event will Sun Microsystems, Inc. be liable for any lost revenue
 * or profits or other special, indirect and consequential damages, even
 * if Sun has been advised of the possibility of such damages.
 * 
 * Sun Microsystems, Inc.
 * 2550 Garcia Avenue
 * Mountain View, California  94043
 */

#include <stdarg.h>
#include "buffer.h"
#include "keymap.h"
#include "utils.h"
#include "jed_cps.h"

static Keymap	*keystate;
Keymap		*global_map;
int		last_key_typed, last_shift_state;
object		*current_cmd;

#define keymap_ismap(obj)   ((((keymap_object *) obj)->type == full_map) || \
			     (((keymap_object *) obj)->type == sparse_map))
#define key_ref(km, key)    \
    ((sparse_entry *) &Bytestring_CharAt(&(km)->keys.sparse_map.procs, \
					 (key) * sizeof (sparse_entry)))

Keymap *
keymap_New(object_type type)
{
    Keymap  *km;

    km = (Keymap *) jot_alloc(sizeof (Keymap));
    memset((char *) km, 0, sizeof (Keymap));
    km->type = type;
    if (type == full_map) {
	km->keys.full_map = (keymap_object **) jot_alloc(NKEYS * sizeof (keymap_object *));
	memset((char *) km->keys.full_map, 0, NKEYS * sizeof (keymap_object *));
    } else {
	Bytestring_Initialize(&km->keys.sparse_map.procs, sizeof(sparse_entry));
	km->keys.sparse_map.nkeys = 0;
    }
    return km;
}

static void
keymap_Set(Keymap *km, int key, keymap_object *obj)
{
    if (km->type == full_map)
	km->keys.full_map[key] = obj;
    else {
	sparse_entry	*se, new;
	int		i;

	for (i = 0; i < km->keys.sparse_map.nkeys; i++) {
	    se = key_ref(km, i);
	    if (se->key == key) {
		se->obj = obj;
		return;
	    }
	}
	new.key = key;
	new.obj = obj;
	(void) Bytestring_Insert(&km->keys.sparse_map.procs, 0,
				 (char *) &new, sizeof (new));
	km->keys.sparse_map.nkeys += 1;
    }
}

static keymap_object *
keymap_Get(Keymap *km, int key)
{
    sparse_entry    *se;
    int		    i;

    if (km->type == full_map)
	return km->keys.full_map[key];
    for (i = 0; i < km->keys.sparse_map.nkeys; i++) {
	se = key_ref(km, i);
	if (se->key == key)
	    return se->obj;
    }
    return 0;
}

/* This baby takes an array of characters of the form '^' '[' '^' 'A'
   and fills in OUT with an array of the form "^[^A". */

static void
fixup_keys(char *in, char *out)
{
    int	c;

    while (c = *in++) {
	if (*in != '\0') {
	    if (c == '\\')
		c = *in++;
	    else if (c == '^') {
		int nextc = *in++;

		c = (nextc == '?') ? '\177' : nextc & 037;
	    }
	}
	*out++ = c;
    }
    *out = '\0';
}

void
keymap_Bind(Keymap *km, object *proc, char *in_keys)
{
    keymap_object   *obj;
    int		    key, i, nkeys;
    char	    key_buf[64], *keys = key_buf;

    fixup_keys(in_keys, keys);
    nkeys = strlen(keys);
    for (i = nkeys - 1; --i >= 0; ) {
	key = (u_char) keys[0];
	keys += 1;
	obj = keymap_Get(km, key);
	if (obj == 0 || !keymap_ismap(obj)) {
	    obj = (keymap_object *) keymap_New(sparse_map);
	    keymap_Set(km, key, obj);
	    km = (Keymap *) obj;
	} else
	    km = (Keymap *) obj;
    }
    keymap_Set(km, *((u_char *) keys), (keymap_object *) proc);
}

struct macro_entry {
    int	    last_key_typed;
    object  *execed_object;
};

#define MACRO_STACK_SIZE    64
boolean		    kbd_macro_define = FALSE;
static object	    *kbd_macro = 0;
static object	    *again_macro = 0;
static object	    *again_cmd;
static macro_exec   macro_stack[MACRO_STACK_SIZE];
static macro_exec   *macro_sp = &macro_stack[MACRO_STACK_SIZE];
static boolean	    StartNewAgainMacro = TRUE;
static boolean	    InMacroExec = FALSE;

void
macro_append(object *macro)
{
    struct macro_entry	new;

    new.last_key_typed = last_key_typed;
    new.execed_object = current_cmd;
    Bytestring_Insert(macro->datum.macro_body,
		      Bytestring_Length(macro->datum.macro_body),
		      (char *) &new, sizeof (new));
}

static struct macro_entry *
macro_next_entry()
{
    struct macro_entry	*me;
    object		*macro;
    int			length;

    if (macro_sp == &macro_stack[MACRO_STACK_SIZE])
	return 0;
    macro = macro_sp->macro;
    length = Bytestring_Length(macro->datum.macro_body) /
	    sizeof (struct macro_entry);
    if (macro_sp->offset == length) {
	macro_sp += 1;
	return macro_next_entry();
    }
    me = (struct macro_entry *)
	&Bytestring_CharAt(macro->datum.macro_body,
			   macro_sp->offset * sizeof(struct macro_entry));
    macro_sp->offset += 1;

    return me;
}

static void
macro_erase_last(object *macro)
{
    Bytestring_Delete(macro->datum.macro_body,
		      Bytestring_Length(macro->datum.macro_body),
		      -sizeof (struct macro_entry));
}

void
macro_unwind()
{
    macro_sp = &macro_sp[MACRO_STACK_SIZE];
    InMacroExec = FALSE;
}

static void
macro_clear(object *macro)
{
    Bytestring_Delete(macro->datum.macro_body, 0,
		      Bytestring_Length(macro->datum.macro_body));
}

void
start_remembering()
{
    if (kbd_macro_define) {
	signal_warning("You are already defining a keyboard macro.");
	macro_erase_last(kbd_macro);
    }
    kbd_macro_define = TRUE;
    macro_clear(kbd_macro);
    frame_Modeline(current_buffer);
}

void
stop_remembering()
{
    if (kbd_macro_define) {
	kbd_macro_define = FALSE;
	macro_erase_last(kbd_macro);
	frame_Modeline(current_buffer);
    }
}

void
exec_macro(object *obj)
{
    struct macro_entry  *me;

    if (macro_sp == macro_stack)
	signal_warning("You have overflowed your macro stack.  You \
may only execute %d macros at once.", MACRO_STACK_SIZE);
    macro_sp -= 1;
    macro_sp->offset = 0;
    macro_sp->macro = obj;
    /* Only enter this macro execution loop if we are the first
       macro on the execution stack.  Once in this loop, it will
       run until there are no macros left to execute, without a
       recursive C call (to this function) being made. */
    InMacroExec = TRUE;
    if (macro_sp == &macro_stack[MACRO_STACK_SIZE - 1]) {
	JotText_UndoBegin(current_buffer->text);
	while ((me = macro_next_entry()) != 0) {
	    last_key_typed = me->last_key_typed;
	    exec_object(me->execed_object);
	}
	InMacroExec = FALSE;
	JotText_UndoEnd(current_buffer->text);
    }
}

void
exec_object(object *obj)
{
    current_cmd = obj;

    if (!InMacroExec) {
	if (StartNewAgainMacro && obj != again_cmd) {
	    macro_clear(again_macro);
	    StartNewAgainMacro = FALSE;
	}
	if (kbd_macro_define)
	    macro_append(kbd_macro);
	if (obj != again_cmd)
	    macro_append(again_macro);
    }

    if (obj->type == builtin_proc)
	(*current_cmd->datum.proc) ();
    else if (obj->type == keyboard_macro)
	exec_macro(obj);
    else
	signal_warning("Internal error!!  An attempt to execute an object \
of type %d has been made.", obj->type);
}

void
mouse_macro_end(JotView *v, int button, int action, int pos)
{
    StartNewAgainMacro = TRUE;
}

static void
execute_again_macro()
{
    if (!StartNewAgainMacro)
	StartNewAgainMacro = TRUE;
    exec_macro(again_macro);
}

void
again_handler(JotView *v)
{
    execute_again_macro();
}

void
execute_kbd_macro()
{
    exec_object(kbd_macro);
}

void
keymap_Dispatch(int key, int shift_state)
{
    char	    ch;
    keymap_object   *obj;

    last_key_typed = key;
    last_shift_state = shift_state;
    if (current_buffer->quote_next) {
	obj = (keymap_object *) object_find("self-insert");   /* kludge!! */
	current_buffer->quote_next = FALSE;
    } else {
	if (keystate == 0)
	    keystate = global_map;
	obj = keymap_Get(keystate, key);
    }
    if (obj == 0) {
	keystate = 0;
	ps_bell();
    } else {
	if (keymap_ismap(obj))
	    keystate = (Keymap *) obj;
	else {
	    last_cmd = this_cmd;
	    this_cmd = 0;
	    keystate = 0;
	    exec_object((object *) obj);
	}
    }
}

#define HASH_SIZE   64
static object	*object_hashtable[HASH_SIZE] = {0};

static unsigned int
string_hash(char *string)
{
    unsigned int    hash = 0;
    int		    c;

    while (c = *string++)
	hash = (hash << 1) + c;
    return hash % HASH_SIZE;
}

static object *
object_define(char *name, object_type type, caddr_t datum)
{
    object *new;
    int	    hash;

    hash = string_hash(name);
    new = (object *) jot_alloc(sizeof (object));
    new->type = type;
    new->name = name;
    if (type == builtin_proc)
	new->datum.proc = (void (*)()) datum;
    else
	new->datum.dummy = datum;
    new->next = object_hashtable[hash];
    object_hashtable[hash] = new;

    return new;
}

object *
object_find(char *name)
{
    object  *proc;
    int	    hash;

    hash = string_hash(name);
    proc = object_hashtable[hash];
    for (; proc != 0; proc = proc->next)
	if (strcmp(name, proc->name) == 0)
	    break;
    return proc;
}

void
define_variable(char *name, object_type type, ...)
{
    object  *variable;
    va_list ap;

    variable = object_find(name);
    if (variable == 0)
	variable = object_define(name, type, (caddr_t) 0);
    va_start(ap, type);
    switch (type) {
    case string:
	free(variable->datum.string);
	variable->datum.string = va_arg(ap, char *);
	break;

    case number:
	variable->datum.number = va_arg(ap, int);
	break;

    case truefalse:
	variable->datum.bool = va_arg(ap, boolean);
	break;
    }
}

void
set_variable(object *var, char *value)
{
    switch (var->type) {
    case string:
	free(var->datum.string);
	var->datum.string = copystr(value);
	break;

    case number:
	var->datum.number = atoi(value);
	break;

    case truefalse:
	if (strcmp(value, "true") == 0 || strcmp(value, "yes") == 0)
	    var->datum.bool = TRUE;
	else if (strcmp(value, "false") == 0 || strcmp(value, "no") == 0)
	    var->datum.bool = FALSE;
	else
	    fprintf(stderr, "Unknown boolean name: %s\n", value);
    }
}

void
define_cmd(char *name, void (*proc)(), ...)
{
    object  *new;
    va_list ap;
    char    *keys;

    new = object_define(name, builtin_proc, (caddr_t) proc);
    va_start(ap, proc);
    while ((keys = va_arg(ap, char *)) != 0)
	keymap_Bind(global_map, new, keys);
}

char *
get_string_var(char *name)
{
    object  *obj;

    obj = object_find(name);
    if (obj == 0)
	return "";
    return obj->datum.string;
}

int
get_number_var(char *name)
{
    object  *obj;

    obj = object_find(name);
    if (obj == 0)
	return 0;		/* yes - I know 0 is legit */
    return obj->datum.number;
}

boolean
get_boolean_var(char *name)
{
    object  *obj;

    obj = object_find(name);
    if (obj == 0)
	return -1;
    return obj->datum.bool;
}

keymap_init()
{
    global_map = keymap_New(full_map);
    kbd_macro = object_define("keyboard-macro", keyboard_macro, (caddr_t) 0);
    kbd_macro->datum.macro_body = Bytestring_New(32);
    again_macro = object_define("again-macro", keyboard_macro, (caddr_t) 0);
    again_macro->datum.macro_body = Bytestring_New(32);

    define_cmd("start-remembering", start_remembering, "^X(", (char *) 0);
    define_cmd("stop-remembering", stop_remembering, "^X)", (char *) 0);
    define_cmd("execute-kbd-macro", execute_kbd_macro,
	       "^XE", "^Xe", (char *) 0);
    define_cmd("again", execute_again_macro, (char *) 0);

    JotView_SetEventHandlers(The_View, Jot_MOUSE_EVENT, mouse_macro_end,
			     Jot_AGAIN_EVENT, again_handler,
			     Jot_NULL_EVENT);
    again_cmd = object_find("again");
}

void
parse_rc_file(char *file)
{
    object  *obj;
    char    line[256], name[256], keys[64], filename[256], kind[64];
    int	    lineno = 1;
    FILE    *fp;

    if (file == 0)
	sprintf(filename, "%s/.miterc", getenv("HOME"));
    else
	strcpy(filename, file);
    if ((fp = fopen(filename, "r")) == 0)
	return;
    while (fgets(line, sizeof (line), fp) != NULL) {
	if (line[0] == '\0' || line[0] == '#')
	    continue;
	if (sscanf(line, "%s %s %s", kind, name, keys) != 3) {
	    fprintf(stderr, "\"%s\", line %d: syntax error: %s",
		    filename, lineno, line);
	    continue;
	}
	obj = object_find(name);
	if (obj == 0)
	    fprintf(stderr, "\"%s\", line %d: unknown command or variable: %s\n",
		    filename, lineno, name);
	else if (strcmp(kind, "bind") == 0)
	    keymap_Bind(global_map, obj, keys);
	else if (strcmp(kind, "set") == 0)
	    set_variable(obj, keys);
	else if (kind[0] != '#')
	    fprintf(stderr, "\"%s\", line %d: unknown directive: %s\n",
		    filename, lineno, kind);
	lineno += 1;
    }
    fclose(fp);
}
