/***************************************************************************
 kevent.c Copyright (C) 1999 Christoph Reichenbach


 This program may be modified and copied freely according to the terms of
 the GNU general public license (GPL), as long as the above copyright
 notice and the licensing information contained herein are preserved.

 Please refer to www.gnu.org for licensing details.

 This work is provided AS IS, without warranty of any kind, expressed or
 implied, including but not limited to the warranties of merchantibility,
 noninfringement, and fitness for a specific purpose. The author will not
 be held liable for any damage caused by this work or derivatives of it.

 By using this source code, you agree to the licensing terms as stated
 above.


 Please contact the maintainer for bug reports or inquiries.

 Current Maintainer:

    Christoph Reichenbach (CJR) [jameson@linuxgames.com]

***************************************************************************/

/* OpenVMS: auto-enable the OPENVMS code paths on any VMS compiler (Compaq/DEC
** C and VSI C predefine __VMS) so the debug traps and VMS fixes are NOT lost
** when a build forgets the /DEFINE=OPENVMS (gcc uses -DOPENVMS; CC uses
** /DEFINE). Must come before any #include so engine.h's own #ifdef OPENVMS
** blocks see it too. */
#if defined(__VMS) && !defined(OPENVMS)
#  define OPENVMS 1
#endif

#include <engine.h>

#ifdef OPENVMS
#include <errno.h>   /* errno for the probe-log open-failure report */
#include <string.h>  /* strerror() */
#endif

int stop_on_event;

#ifdef OPENVMS
/* TEMP burst tracer arm-count, consumed by the [KCALL] tracer in vm.c.
 * Armed on each mouse press below. Remove after char-select diagnosis. */
int _openvms_kcall_trace = 0;

/* Debug-log enable flag. OFF by default; set to 1 by main.c when the user
 * passes -L / --log. When off, _openvms_probe_log() returns NULL and every
 * trap becomes a no-op, so a normal run has zero logging overhead and never
 * touches the disk. */
int _openvms_log_enabled = 0;

/* TEMP: shared probe log file. Lazily opened on first use so kevent.c, vm.c
 * and kgraphics.c all write to the same file. Remove after diagnosis.
 *
 * Returns NULL when logging is disabled (no -L) OR when the file cannot be
 * opened -- callers MUST null-check and skip. We deliberately do NOT fall back
 * to stderr: on OpenVMS the freesci/SDL console is unreliable and stderr
 * redirection "never worked", so the file is the only trustworthy sink.
 *
 * Path: "sys$disk:[]freesci_probe.log" forces the CURRENT default directory
 * ([]), the VMS equivalent of "./", with a stream-LF record format so ordinary
 * tools (TYPE, EDIT, SEARCH, ports of grep) read it cleanly. If that open
 * fails we print the RMS/errno reason ONCE so a permissions/quota problem is
 * visible rather than silent. */
FILE *
_openvms_probe_log(void)
{
	static FILE *f = NULL;
	static int tried = 0;

	if (!_openvms_log_enabled)
		return NULL;

	if (!f && !tried) {
		tried = 1;
		f = fopen("sys$disk:[]freesci_probe.log", "w",
			  "rfm=stmlf", "rat=cr");
		if (f)
			fprintf(stderr, "[PROBE] logging to "
				"sys$disk:[]freesci_probe.log (current directory)\n");
		else
			fprintf(stderr, "[PROBE] could not open "
				"sys$disk:[]freesci_probe.log: %s "
				"(logging disabled)\n", strerror(errno));
	}
	return f;
}
#endif

void
kGetEvent(state_t *s, int funct_nr, int argc, heap_ptr argp)
{
	int mask = UPARAM(0);
	heap_ptr obj = UPARAM(1);
	sci_event_t e;
	int oldx, oldy;

	if (s->kernel_opt_flags & KERNEL_OPT_FLAG_GOT_2NDEVENT) {
		/* Penalty time- too many requests to this function without
		** waiting!  */
		gfxop_usleep(s->gfx_state, 1000000 / 60);
	}
  
	/*If there's a simkey pending, and the game wants a keyboard event, use the
	 *simkey instead of a normal event*/
	if (_kdebug_cheap_event_hack && (mask & SCI_EVT_KEYBOARD)) {
		PUT_SELECTOR(obj, type, SCI_EVT_KEYBOARD); /*Keyboard event*/
		s->acc=1;
		PUT_SELECTOR(obj, message, _kdebug_cheap_event_hack);
		PUT_SELECTOR(obj, modifiers, SCI_EVM_NUMLOCK); /*Numlock on*/
		PUT_SELECTOR(obj, x, s->gfx_state->pointer_pos.x);
		PUT_SELECTOR(obj, y, s->gfx_state->pointer_pos.y);
		_kdebug_cheap_event_hack = 0;
		return;
	}
  
	oldx=s->gfx_state->pointer_pos.x;
	oldy=s->gfx_state->pointer_pos.y;
	e = gfxop_get_event(s->gfx_state, mask);

	s->parser_event = 0; /* Invalidate parser event */

	PUT_SELECTOR(obj, x, s->gfx_state->pointer_pos.x);
	PUT_SELECTOR(obj, y, s->gfx_state->pointer_pos.y);

	/*  gfxop_set_pointer_position(s->gfx_state, gfx_point(s->gfx_state->pointer_pos.x, s->gfx_state->pointer_pos.y)); */


	if (e.type)
		s->kernel_opt_flags &= ~(KERNEL_OPT_FLAG_GOT_EVENT
					 | KERNEL_OPT_FLAG_GOT_2NDEVENT);
	else {
		if (s->kernel_opt_flags & KERNEL_OPT_FLAG_GOT_EVENT)
			s->kernel_opt_flags |= KERNEL_OPT_FLAG_GOT_2NDEVENT;
		else
			s->kernel_opt_flags |= KERNEL_OPT_FLAG_GOT_EVENT;
	}

	switch(e.type)
		{
		case SCI_EVT_QUIT:
			quit_vm();
			break;

		case SCI_EVT_KEYBOARD: {

			if ((e.buckybits & SCI_EVM_LSHIFT) && (e.buckybits & SCI_EVM_RSHIFT)
			    && (e.data == '-')) {

				sciprintf("Debug mode activated\n");

				script_debug_flag = 1; /* Enter debug mode */
				_debug_seeking = _debug_step_running = 0;
				s->onscreen_console = 0;

			} else if ((e.buckybits & SCI_EVM_CTRL) && (e.data == '`')) {

				script_debug_flag = 1; /* Enter debug mode */
				_debug_seeking = _debug_step_running = 0;
				s->onscreen_console = 1;

			} else if ((e.buckybits & SCI_EVM_CTRL) && (e.data == '1')) {

				if (s->visual)
					s->visual->print(GFXW(s->visual), 0);

			} else {

				PUT_SELECTOR(obj, type, SCI_EVT_KEYBOARD); /*Keyboard event*/
				s->acc=1;
				PUT_SELECTOR(obj, message, e.character);
				/* We only care about the translated
				** character  */
				PUT_SELECTOR(obj, modifiers, e.buckybits);

			}
		} break;

		case SCI_EVT_MOUSE_RELEASE:
		case SCI_EVT_MOUSE_PRESS: {
			int extra_bits=0;

			if(mask & e.type) {
				switch(e.data) {
				case 2: extra_bits=SCI_EVM_LSHIFT|SCI_EVM_RSHIFT; break;
				case 3: extra_bits=SCI_EVM_CTRL;
				default:break;
				}

				PUT_SELECTOR(obj, type, e.type);
				PUT_SELECTOR(obj, message, 1);
				PUT_SELECTOR(obj, modifiers, e.buckybits|extra_bits);
				s->acc=1;
			}
#ifdef OPENVMS
			/* TEMP one-shot probe: report first 40 mouse events reaching
			 * the script, with the pos written to the event object and the
			 * mask the game requested. Also directly scan the visual/priority/
			 * control maps at the click point so we can see what the engine
			 * "sees" there independent of game-script logic.
			 * Remove after char-select diagnosis. */
			{
				static int _me_probe = 0;
				FILE *lf = _openvms_probe_log();
				if (lf && _me_probe < 40) {
					int px = s->gfx_state->pointer_pos.x;
					int py = s->gfx_state->pointer_pos.y;
					int v_hit = gfxop_scan_bitmask(s->gfx_state, gfx_rect(px, py, 1, 1), GFX_MASK_VISUAL);
					int p_hit = gfxop_scan_bitmask(s->gfx_state, gfx_rect(px, py, 1, 1), GFX_MASK_PRIORITY);
					int c_hit = gfxop_scan_bitmask(s->gfx_state, gfx_rect(px, py, 1, 1), GFX_MASK_CONTROL);
					++_me_probe;
					fprintf(lf, "[PROBE Mouse #%d] type=%d mask=0x%x pos=(%d,%d) matched=%d | scan vis=%d pri=%d ctl=%d\n",
						_me_probe, e.type, mask, px, py,
						(mask & e.type) ? 1 : 0, v_hit, p_hit, c_hit);
					fflush(lf);
					/* Arm the vm.c kernel-call burst tracer on a PRESS so
					 * we capture how the script dispatches this click. */
					if (e.type == SCI_EVT_MOUSE_PRESS) {
						fprintf(lf, "--- KCALL burst for press #%d at (%d,%d) ctl=%d ---\n",
							_me_probe, px, py, c_hit);
						fflush(lf);
						_openvms_kcall_trace = 150;
					}
				}
			}
#endif
			return;
		} break;

		default: {
			s->acc = 0; /* Unknown or no event */
		}
		}
    
	if ((s->acc) && (stop_on_event)) {
		stop_on_event = 0;
		script_debug_flag = 1;
	}  
}

void
kMapKeyToDir(state_t *s, int funct_nr, int argc, heap_ptr argp)
{
	heap_ptr obj = UPARAM(0);

	if (GET_SELECTOR(obj, type) == SCI_EVT_KEYBOARD) { /* Keyboard */
		int mover = -1;
		switch (GET_SELECTOR(obj, message)) {
		case SCI_K_HOME: mover = 8; break;
		case SCI_K_UP: mover = 1; break;
		case SCI_K_PGUP: mover = 2; break;
		case SCI_K_LEFT: mover = 7; break;
		case SCI_K_CENTER:
		case 76: mover = 0; break;
		case SCI_K_RIGHT: mover = 3; break;
		case SCI_K_END: mover = 6; break;
		case SCI_K_DOWN: mover = 5; break;
		case SCI_K_PGDOWN: mover = 4; break;
		default: break;
		}

		if (mover >= 0) {
			PUT_SELECTOR(obj, type, SCI_EVT_JOYSTICK);
			PUT_SELECTOR(obj, message, mover);
			s->acc = 1;
		} else s->acc = 0;
	}
}


void
kGlobalToLocal(state_t *s, int funct_nr, int argc, heap_ptr argp)
{
	heap_ptr obj = UPARAM_OR_ALT(0, 0);

	if (obj) {
		int x = GET_SELECTOR(obj, x);
		int y = GET_SELECTOR(obj, y);

		PUT_SELECTOR(obj, x, x - s->port->zone.x);
		PUT_SELECTOR(obj, y, y - s->port->zone.y);
	}
}


void
kLocalToGlobal(state_t *s, int funct_nr, int argc, heap_ptr argp)
{
	heap_ptr obj = UPARAM_OR_ALT(0, 0);

	if (obj) {
		int x = GET_SELECTOR(obj, x);
		int y = GET_SELECTOR(obj, y);

		PUT_SELECTOR(obj, x, x + s->port->zone.x);
		PUT_SELECTOR(obj, y, y + s->port->zone.y);
	}
}

void /* Not implemented */
kJoystick(state_t *s, int funct_nr, int argc, heap_ptr argp)
{
	SCIkdebug(SCIkSTUB, "Unimplemented syscall 'Joystick()'\n", funct_nr);
	s->acc = 0;
}


