/*
 *	Mouse and keyboard event handling for T3X programs.
 *	DOS-specific routines.
 *	Copyright (C) 1997,1998 Nils M. Holm
 *	See the file LICENSE for conditions of use.
 *
 *	VIO is required for keyboard input.
 */

#ifdef GRAPHICS_EXT

#include <dos.h>

#include "gfx.h"
#include "vio.h"

#define MOUSE_INT	0x33


extern far	_delay();


void mouse_on() {
	union REGS  regs;

	regs.x.ax = 1;
	int86(MOUSE_INT, &regs, &regs);
}


void mouse_off() {
	union REGS  regs;

	regs.x.ax = 2;
	int86(MOUSE_INT, &regs, &regs);
}


int mouse_button() {
	union REGS  regs;

	regs.x.ax = 3;
	int86(MOUSE_INT, &regs, &regs);
	return(regs.h.bl);
}


void get_mousepos(x, y)
int  *x, *y;
{
	union REGS  regs;

	regs.x.ax = 3;
	int86(MOUSE_INT, &regs, &regs);
	*x = regs.x.cx;
	*y = regs.x.dx;
}


void set_mousepos(x, y)
int  x, y;
{
	union REGS  regs;

	regs.x.ax = 4;
	regs.x.cx = x;
	regs.x.dx = y;
	int86(MOUSE_INT, &regs, &regs);
}


void set_mousearea(x, y, dx, dy)
int  x, y, dx, dy;
{
	union REGS  regs;

	regs.x.ax = 7;
	regs.x.cx = x;
	regs.x.dx = dx;
	int86(MOUSE_INT, &regs, &regs);
	regs.x.ax = 8;
	regs.x.cx = y;
	regs.x.dx = dy;
	int86(MOUSE_INT, &regs, &regs);
	set_mousepos(x, y);
}


void mouse_hardcsr() {
	union REGS  regs;
   
	regs.x.ax = 10;
	regs.x.bx = 1;
	regs.x.cx = 0;
	regs.x.dx = 0;
	int86(MOUSE_INT, &regs, &regs);
}


void init_mouse(x, y, dx, dy)
{
	int  i;

	if (dx < x) {
		i = x; x = dx; dx = i;
	}
	if (dy < y) {
		i = y; y = dy; dy = i;
	}
	set_mousearea(x, y, dx, dy);
	set_mousepos(x+(dx-x)/2, y+(dy-y)/2);
}


int e_init() {
	union REGS  regs;

	regs.x.ax = 0;
	int86(MOUSE_INT, &regs, &regs);
	if (regs.x.ax == 0) g_error("No pointing device found");
	init_mouse(0, 0, 640, 480);
	return(0);
}


extern int Fx, Fy;
int g_event(struct event *e, int block);
int g_event(e, block)
struct event	*e;
int		block;
{
	int		x, y, r = 0;
	static int	ob = 0;

	mouse_on();
	/*XXX
	 * Without the following delay loop, the mouse
	 * cursor startts flirring and motions become
	 * jerky. To be improved...
	 * Yes, I HAVE thought about turning off the
	 * cursor only when really drawing something,
	 * but it's too slow.
	 */
	if (!block) _delay(30);
	e->buttons = 0;
	e->key = -1;
	while (!r){
		get_mousepos(&x, &y);
		e->x = x * Fx - XLIM;
		e->y = y * Fy - YLIM;
		e->buttons = mouse_button() & 7; /* three buttons? */
		if (vio_query()) {
			e->key = vio_getc();
			if (!e->key) e->key = vio_getc()+256;
		}
		if (e->key != -1 || e->buttons != ob) r = -1;
		if (!block) break;
	}
	ob = e->buttons;
	mouse_off();
	return(r);
}


int g_wait(msec) {
	_delay(msec);
}


void g_sync() {
	/* Nothing to do here */
}

#endif	/* GRAPHICS_EXT */
