/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

/*
 * "$Id: aux_so.c,v 1.1.1.1.2.1 2001/03/15 07:52:21 himi Exp $"
 */

#pragma ident	"@(#)aux_so.c 1.21	00/09/14 SMI"


#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits.h>

#include <X11/Xmd.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>

#include "iiimpAux.h"

#include "trace_message.h"


#define HASH_SIZE 137

#define ME			"aux_so"

#define HTT_AUX_EXT_NAME	"htt_aux_sample_ext"
#define HTT_AUX_SO_NAME		"htt_aux_sample_so"
#define HTT_AUX_PROP_NAME	"htt_aux_sample_prop"
#define HTT_AUX_PROP1_NAME	"htt_aux_sample_prop1"

#define	AUX_EXT			"/usr/lib/iiim/le/sampleja/aux_ext"

typedef struct _aux_icid {
	aux_t *			aux;
	int			icid;
	struct _aux_icid *	prev;
	struct _aux_icid *	next;
} aux_icid_t;


static void	aux_ext_send(aux_t *, const unsigned char *, int);
static void	process_property_notify(Display *, Window);
static void	process_client_message(Display *, Window, XEvent *);
static Bool	aux_event_filter(Display *, Window, XEvent *, XPointer);

static Bool	aux_init(aux_t *);

static void		aux_icid_init(void);
static void		aux_icid_finish(void);
static aux_icid_t *	aux_icid_get(int);
static void		aux_icid_delete(int);

static Bool	aux_Create(aux_t *);
static Bool	aux_Start(aux_t *, const unsigned char *, int);
static Bool	aux_Draw(aux_t *, const unsigned char *, int);
static Bool	aux_Done(aux_t *, const unsigned char *, int);
static Bool	aux_Switched(aux_t *, int, int);
static Bool	aux_Destroy(aux_t *);

static Bool	panel_Create(aux_t *);
static Bool	panel_Start(aux_t *, const unsigned char *, int);
static Bool	panel_Draw(aux_t *, const unsigned char *, int);
static Bool	panel_Done(aux_t *, const unsigned char *, int);
static Bool	panel_Switched(aux_t *, int, int);
static Bool	panel_Destroy(aux_t *);


/*
 * com.sun.iiim.sample.sampleja.SampleAux
*/
static CARD16	aux_name_aux_name[] = {
	0x0063, 0x006f, 0x006d, 0x002e,
	0x0073, 0x0075, 0x006e, 0x002e,
	0x0069, 0x0069, 0x0069, 0x006d,
	0x002e, 0x0073, 0x0061, 0x006d,
	0x0070, 0x006c, 0x0065, 0x002e,
	0x0073, 0x0061, 0x006d, 0x0070,
	0x006c, 0x0065, 0x006a, 0x0061,
	0x002e, 0x0053, 0x0061, 0x006d,
	0x0070, 0x006c, 0x0065, 0x0041,
	0x0075, 0x0078,
};


/*
 * com.sun.iiim.sample.sampleja.SamplePanel
*/
static CARD16	aux_name_panel_name[] = {
	0x0063, 0x006f, 0x006d, 0x002e,
	0x0073, 0x0075, 0x006e, 0x002e,
	0x0069, 0x0069, 0x0069, 0x006d,
	0x002e, 0x0073, 0x0061, 0x006d,
	0x0070, 0x006c, 0x0065, 0x002e,
	0x0073, 0x0061, 0x006d, 0x0070,
	0x006c, 0x0065, 0x006a, 0x0061,
	0x002e, 0x0053, 0x0061, 0x006d,
	0x0070, 0x006c, 0x0065, 0x0050,
	0x0061, 0x006e, 0x0065, 0x006c,
};


static aux_method_t	aux_method_aux = {
	aux_Create,
	aux_Start,
	aux_Draw,
	aux_Done,
	aux_Switched,
	aux_Destroy
};


static aux_method_t	aux_method_panel = {
	panel_Create,
	panel_Start,
	panel_Draw,
	panel_Done,
	panel_Switched,
	panel_Destroy
};


aux_dir_t	aux_dir[] = {
	{{sizeof (aux_name_aux_name),
	  aux_name_aux_name},
	 &aux_method_aux},

	{{sizeof (aux_name_panel_name),
	  aux_name_panel_name},
	 &aux_method_panel},

	{{0, NULL}, NULL}
};


static int		aux_initialized = 0;
static aux_icid_t	aux_icid[HASH_SIZE];

static Atom	aux_so_atom;
static Atom	aux_ext_atom;
static Atom	aux_prop_atom;
static Atom	aux_prop1_atom;

static Window	aux_window;


static void
aux_ext_send(aux_t * aux, const unsigned char * p, int len)
{
	Display *	display;
	Window		w_ext;

	TRACE_MESSAGE('S', (ME ":aux_ext_send: \"%.*s\" len=%d\n", len - 4, p + 4, len));
	
	display = aux->service->display(aux);

	if (None == (w_ext = XGetSelectionOwner(display, aux_ext_atom))) {
		TRACE_MESSAGE('s', (ME ":aux_ext_send: no owner of %08x (display=%08x)\n",
				    aux_ext_atom, display));
		XChangeProperty(display, aux_window, aux_prop1_atom, XA_STRING,
				8, PropModeReplace, (unsigned char *)p, len);

		return;
	}

	TRACE_MESSAGE('s', (ME ":aux_ext_send: owner %08x\n", w_ext));

	XChangeProperty(display, w_ext, aux_prop_atom, XA_STRING,
			8, PropModeReplace, (unsigned char *)p, len);

	return;
}


aux_ext_client_message(aux_t * aux, int im_id, int ic_id, const int * p, int n)
{
	Display *		display;
	Window			w_ext;
	int			i;
	XClientMessageEvent	event;

#if defined(ENABLE_TRACE)
	if (TRACE_P('S')) {
		TRACE_MESSAGE('S', (ME ":aux_ext_client_message:"));
		for (i = 0; i < n; i++) {
			TRACE_MESSAGE('S', (" %08x", *(p + i)));
		}
		TRACE_MESSAGE('S', ("\n"));
	}
#endif /* ENABLE_TRACE */

	if (4 < n) {
		n = 4;
	}

	display = aux->service->display(aux);

	if (None == (w_ext = XGetSelectionOwner(display, aux_ext_atom))) {
		TRACE_MESSAGE('s', (ME ":aux_ext_send: no owner of %08x (display=%08x)\n",
				    aux_ext_atom, display));
		return;
	}
	TRACE_MESSAGE('s', (ME ":aux_ext_send: owner %08x\n", w_ext));


	event.type = ClientMessage;
	event.serial = 0;
	event.send_event = True;
	event.display = display;
	event.window = w_ext;
	event.message_type = aux_ext_atom;
	event.format = 32;
	event.data.s[0] = im_id;
	event.data.s[1] = ic_id;
	for (i = 0; i < n; i++) {
		event.data.l[i + 1] = *(p + i);
	}
	for (i++; i < 5; i++) {
		event.data.l[i] = 0;
	}

	XSendEvent(display, w_ext, True, 0, (XEvent *)(&event));
}

static void
process_property_notify(Display * display, Window window)
{
	long		long_length;
	Atom		actual_type_return;
	int		actual_format_return;
	unsigned long	nitem_return;
	unsigned long	bytes_after_return;
	unsigned char *	prop_return;
	int		r;
	int		imid;
	int		icid;
	aux_icid_t * 	ic;
	int		size;
	aux_data_t *	aux_data;
	unsigned char *	p;
	unsigned char	buf[1024];
	const char *	inbuf;
	size_t		inbytesleft;
	char *		outbuf;
	size_t		outbytesleft;

	TRACE_MESSAGE('P', (ME ":process_property_notify: %08x %08x %08x\n",
			    display, window, aux_prop_atom));

	r = XGetWindowProperty(display, window,
			       aux_prop_atom, 0, INT_MAX, False,
			       AnyPropertyType, &actual_type_return,
			       &actual_format_return, &nitem_return,
			       &bytes_after_return, &prop_return);
	if (Success != r) {
		return;
	}

	imid = ((*(prop_return + 0) << 8) +
		(*(prop_return + 1) << 0));
	icid = ((*(prop_return + 2) << 8) +
		(*(prop_return + 3) << 0));

	TRACE_MESSAGE('P', (ME ":process_property_notify: imid=%d icid=%d \"%.*s\"\n",
			    imid, icid, nitem_return - 4, prop_return + 4));

	ic = aux_icid_get(icid);

	if (NULL == ic->aux) {
		TRACE_MESSAGE('P', (ME ":process_property_notify: no aux\n"));
		XFree(prop_return);
		return;
	}

	aux_data = (aux_data_t *)malloc(sizeof (aux_data_t));
	aux_data->type = AUX_DATA_SETVALUE;
	aux_data->im = imid;
	aux_data->ic = icid;
	aux_data->aux_index = 0;
	aux_data->aux_name = (unsigned char *)aux_name_aux_name;
	aux_data->aux_name_length = (sizeof (aux_name_aux_name));

	aux_data->integer_count = 2;
	aux_data->integer_list = (int *)malloc(2 * (sizeof (int)));
	*(aux_data->integer_list + 0) = aux_data->im;
	*(aux_data->integer_list + 1) = aux_data->ic;

	aux_data->string_count = 2;
	aux_data->string_list =
		(aux_string_t *)malloc(2 * (sizeof (aux_string_t)));

	inbuf = (const char *)(prop_return + 4);
	inbytesleft = (nitem_return - 4);
	outbuf = (char *)buf;
	outbytesleft = (sizeof (buf));
	ic->aux->service->mb_utf16(&inbuf, &inbytesleft,
				   &outbuf, &outbytesleft);

	(aux_data->string_list + 0)->ptr = buf;
	(aux_data->string_list + 0)->length = ((sizeof (buf)) - outbytesleft);

	(aux_data->string_list + 1)->ptr = buf;
	(aux_data->string_list + 1)->length = ((sizeof (buf)) - outbytesleft);
#if 0
	(aux_data->string_list + 1)->ptr = (prop_return + 4);
	(aux_data->string_list + 1)->length = ((nitem_return - 4) -
					       (nitem_return % 2));
#endif /* 0 */

	aux_data->string_ptr = NULL;

	p = ic->aux->service->compose(aux_data, &size);

#if defined(ENABLE_TRACE)
	if (TRACE_P('p')) {
		int	i;
		int	j;
		int	k;
		TRACE_MESSAGE('p', ("process_property_notify: len=%d\n", size));
		for (i = 0, k = 0; i < size; i += 4) {
			for (j = 0; j < 4; j++) {
				TRACE_MESSAGE('p', ("%02x", *(p + i + j)));
			}
			if (7 == k) {
				TRACE_MESSAGE('p', ("\n"));
				k = 0;
			} else {
				TRACE_MESSAGE('p', (" "));
				k += 1;
			}
		}
		TRACE_MESSAGE('p', ("\n"));
	}
#endif /* ENABLE_TRACE */

	ic->aux->service->aux_setvalue(ic->aux, p, size);

	free(p);
	free(aux_data->string_list);
	free(aux_data->integer_list);
	free(aux_data);
	XFree(prop_return);

	return;
}


static void
process_client_message(Display * display, Window window, XEvent * event)
{
	XClientMessageEvent *	message;
	int			imid;
	int			icid;

	message = (XClientMessageEvent *)event;

	imid = ((*(message->data.b + 0) << 8) +
		(*(message->data.b + 1) << 0));
	icid = ((*(message->data.b + 2) << 8) +
		(*(message->data.b + 3) << 0));

	if (message->message_type == aux_so_atom) {
		TRACE_MESSAGE('M',
			      (ME ":process_client_message: %08x %08x %d\n",
			       display, window, message->data.l[0]));
		TRACE_MESSAGE('M',
			      (ME ":process_client_message: exiting...\n"));
		exit(0);
	}
		
	switch (message->message_type) {
	case XA_INTEGER:
		TRACE_MESSAGE('M',
			      (ME ":process_client_message: %d %d %d\n",
			       display, window, message->data.l[0]));
		break;
	case XA_STRING:
		TRACE_MESSAGE('M',
			      (ME ":process_client_message: d=%08x w=%08x im=%d ic=%d %s\n",
			       display, window, imid, icid, message->data.b + 4));
		break;
	}

	return;
}


static Bool
aux_event_filter(
	Display *	display,
	Window		window,
	XEvent *	event,
	XPointer	pointer)
{
	switch (event->type) {
	case PropertyNotify:
		if (aux_prop_atom != ((XPropertyEvent *)event)->atom) {
			return False;
		}
		process_property_notify(display, window);
		return True;
		break;
	case ClientMessage:
		process_client_message(display, window, event);
		return True;
		break;
	}
	return False;
}


static Bool
aux_init(aux_t * aux)
{
	Display *	display;

	TRACE_MESSAGE('I', (ME ":aux_init: display = %08x\n", display));

	display = aux->service->display(aux);

	aux_ext_atom = XInternAtom(display, HTT_AUX_EXT_NAME, False);
	aux_so_atom = XInternAtom(display, HTT_AUX_SO_NAME, False);
	aux_prop_atom = XInternAtom(display, HTT_AUX_PROP_NAME, False);
	aux_prop1_atom = XInternAtom(display, HTT_AUX_PROP1_NAME, False);

	if (None != XGetSelectionOwner(display, aux_so_atom)) {
		TRACE_MESSAGE('I', (ME ":aux_init: aux_so already exists\n"));
		return False;
	}
	aux_window = XCreateSimpleWindow(display, RootWindow(display, 0),
				     0, 0, 1, 1, 0, 0, 0);

	TRACE_MESSAGE('I', (ME ":aux_init: window = %08x\n", aux_window));

	if (None != XGetSelectionOwner(display, aux_so_atom)) {
		TRACE_MESSAGE('I', (ME ":aux_init: aux_so already exists (0)\n"));
		return False;
	}
	XSetSelectionOwner(display, aux_so_atom, aux_window, CurrentTime);
	if (aux_window != XGetSelectionOwner(display, aux_so_atom)) {
		TRACE_MESSAGE('I', (ME ":aux_init: aux_so already exists (1)\n"));
		return False;
	}

	XSelectInput(display, aux_window, PropertyChangeMask);

	aux->service->register_X_filter(display, aux_window,
					PropertyNotify, PropertyNotify,
					aux_event_filter, NULL);

	aux->service->register_X_filter(display, aux_window,
					ClientMessage, ClientMessage,
					aux_event_filter, NULL);
}


static void
aux_icid_init(void)
{
	int	i;

	for (i = 0; i < HASH_SIZE; i++) {
		aux_icid[i].icid = (-1);
	}
}


static void
aux_icid_finish(void)
{
	int		i;
	aux_icid_t *	p0;
	aux_icid_t *	p1;

	for (i = 0; i < HASH_SIZE; i++) {
		p0 = aux_icid[i].next;

		for (; NULL != p0; p0 = p1) {
			free(p0);
			p1 = p0->next;
		}
	}
}


static aux_icid_t *
aux_icid_get(int icID)
{
	int		hash_value;
	aux_icid_t *	p;

	hash_value = (icID % HASH_SIZE);

	p = &(aux_icid[hash_value]);

	if ((-1) == p->icid) {
		p->icid = icID;
		return p;
	}

	for (; NULL != p; p = p->next) {
		if (icID == p->icid) {
			return p;
		}
		if (NULL == p->next) {
			p->next = malloc(sizeof (aux_icid_t));
			if (NULL == p->next) {
				return NULL;
			}
			memset(p->next, 0, (sizeof (aux_icid_t)));
			p->next->prev = p;
			return p->next;
		}
	}
	return NULL;	/* never comes here */
}


static void
aux_icid_delete(int icID)
{
	aux_icid_t *	p;

	p = aux_icid_get(icID);
	if (NULL == p) {
		return;
	}
	if (NULL != p->prev) {
		p->prev->next = p->next;
		free(p);
	}
}


static Bool
aux_Create(aux_t * aux)
{
	int		i;
	pid_t		pid;
	aux_icid_t *	aux_icid;

	TRACE_MESSAGE_INIT("TRACE_AUX_SO");

	TRACE_MESSAGE('X', (ME ":aux_Create\n"));

	if (0 == aux_initialized) {
		aux_icid_init();
	}

	if (NULL == (aux_icid = aux_icid_get(aux->service->ic_id(aux)))) {
		return False;
	}
	aux_icid->aux = aux;
	if (0 == aux_initialized) {
		aux_init(aux);
	}

	aux_initialized = 1;

#if 0
	aux->service->data_set(aux, im_id,(void *)aux_icid);
#endif /* 0 */

	pid = fork1();
	if ((pid_t)(-1) == pid) {
		return False;
	} else if (0 == pid) {
		execl(AUX_EXT, "aux", "-name", "aux", NULL);
		_exit(1);
	} else {
		return True;
	}
}


static Bool
aux_Start(aux_t * aux, const unsigned char * p, int size)
{
	TRACE_MESSAGE('X', (ME ":aux_Start: size = %d\n", size));
	return True;
}


static Bool
aux_Draw(aux_t * aux, const unsigned char * p, int size)
{
	aux_data_t *	aux_data;
	char *		string_ptr;
	char		string_buf[1024 * 128];
	int		string_len;
	Window		w;
	XPoint		point;

	TRACE_MESSAGE('X', (ME ":aux_Draw: im=%d ic=%d size = %d\n",
			    aux->service->im_id(aux),
			    aux->service->ic_id(aux),
			    size));

	*((CARD16 *)(string_buf + 0)) = aux->service->im_id(aux);
	*((CARD16 *)(string_buf + 2)) = aux->service->ic_id(aux);
	string_ptr = (string_buf + 4);
	string_len = 4;

	w = aux->service->window(aux);
	aux->service->point_caret(aux, &point);

	TRACE_MESSAGE('D', (ME ":aux_Draw: w=%08x x=%d y=%d\n", w, point.x, point.y));

	aux_data = aux->service->decompose(AUX_DATA_DRAW, p);

#if defined(ENABLE_TRACE)
	if (TRACE_P('D')) {
		char		aux_name;
		const char *	inbuf;
		size_t		inbytesleft;
		char *		outbuf;
		size_t		outbytesleft;
		char		buf[1024];

		TRACE_MESSAGE('D', (ME ":aux_Draw: aux_index = %d\n",
				    aux_data->aux_index));
		inbuf = (char *)(aux_data->aux_name);
		inbytesleft = aux_data->aux_name_length;
		outbuf = buf;
		outbytesleft = (sizeof (buf));
		aux->service->utf16_mb(&inbuf, &inbytesleft,
				       &outbuf, &outbytesleft);
		TRACE_MESSAGE('D', (ME ":aux_Draw: aux_name = \"%.*s\"\n",
				    (sizeof (buf)) - outbytesleft, buf));
	}
#endif /* ENABLE_TRACE */

	do {
		int		i;
		int		int_buf[4];
		int		im_id;
		int		ic_id;

		int_buf[0] = w;
		int_buf[1] = point.x;
		int_buf[2] = point.y;

		TRACE_MESSAGE('D', (ME ":aux_Draw: client_message: %d %d %x %d %d\n",
				    aux->service->im_id(aux),
				    aux->service->ic_id(aux),
				    w, point.x, point.y));
				    
		aux_ext_client_message(aux, 
				       aux->service->im_id(aux),
				       aux->service->ic_id(aux),
				       int_buf, 3);
	} while (0);

	if (0 < aux_data->integer_count) {
		int	i;
		TRACE_MESSAGE('D', (ME ":aux_Draw: integer_list[%d] =",
				    aux_data->integer_count));
		for (i = 0; i < aux_data->integer_count; i++) {
			TRACE_MESSAGE('D',
				      (" %d", *(aux_data->integer_list + i)));
		}
		TRACE_MESSAGE('D', ("\n"));
	} else {
		TRACE_MESSAGE('D',
			      (ME ":aux_Draw: integer_count = 0\n"));
	}
	if (0 < aux_data->string_count) {
		int	i;
		for (i = 0; i < aux_data->string_count; i++) {
			const char *	inbuf;
			size_t		inbytesleft;
			char *		outbuf;
			size_t		outbytesleft;
			int		j;

			inbuf = (char *)((aux_data->string_list + i)->ptr);
			inbytesleft = (aux_data->string_list + i)->length;
			outbuf = string_ptr;
			outbytesleft = ((sizeof (string_buf)) - string_len);

			aux->service->utf16_mb(&inbuf, &inbytesleft,
					       &outbuf, &outbytesleft);
#if defined(ENABLE_TRACE)
			j = (((sizeof (string_buf)) - string_len) - outbytesleft);
			TRACE_MESSAGE('D',
				      (ME ":aux_Draw: "
				       "*(string_list + %d) = \"%.*s\" len=%d\n",
				       i, j, string_ptr, j));
#endif /* ENABLE_TRACE */
			string_len = ((sizeof (string_buf)) - outbytesleft);
			string_ptr = (string_buf + string_len);
			switch (*(string_ptr - 1)) {
			case '\0':
				*(string_ptr - 1) = ' ';
				break;
			case ' ':
				break;
			default:
				*string_ptr = ' ';
				string_ptr += 1;
				string_len += 1;
				break;
			}
		}
	} else {
		TRACE_MESSAGE('D',
			      (ME ":aux_Draw: string_count = 0\n"));
	}

	if (0 < string_len) {
		aux_ext_send(aux, (unsigned char *)string_buf, string_len);
	}

	aux->service->decompose_free(aux_data);

	return True;
}


static Bool
aux_Done(aux_t * aux, const unsigned char * p, int size)
{
	TRACE_MESSAGE('X', (ME ":aux_Done: size = %d\n", size));
	return True;
}


static Bool
aux_Switched(aux_t * aux, int im_id, int on_off)
{
	TRACE_MESSAGE('X', (ME ":aux_Switched im_id = %d %s\n",
			    im_id, ((1 == on_off) ? "on" : "off")));

	return True;
}


static Bool
aux_Destroy(aux_t * aux)
{
	TRACE_MESSAGE('X', (ME ":aux_Destroy\n"));

	return True;
}



#define HTT_PANEL_EXT_NAME	"htt_panel_sample_ext"
#define HTT_PANEL_SO_NAME	"htt_panel_sample_so"
#define HTT_PANEL_PROP_NAME	"htt_panel_sample_prop"
#define HTT_PANEL_PROP1_NAME	"htt_panel_sample_prop1"

static void	panel_ext_send(aux_t *, const unsigned char *, int);
static void	panel_process_property_notify(Display *, Window);
static void	panel_process_client_message(Display *, Window, XEvent *);
static Bool	panel_event_filter(Display *, Window, XEvent *, XPointer);

static Bool	panel_init(aux_t *);

static void		panel_icid_init(void);
static void		panel_icid_finish(void);
static aux_icid_t *	panel_icid_get(int);
static void		panel_icid_delete(int);

static int		panel_initialized = 0;
static aux_icid_t	panel_icid[HASH_SIZE];

static Atom	panel_so_atom;
static Atom	panel_ext_atom;
static Atom	panel_prop_atom;
static Atom	panel_prop1_atom;

static Window	panel_window;


static void
panel_ext_send(aux_t * aux, const unsigned char * p, int len)
{
	Display *	display;
	Window		w_ext;

	TRACE_MESSAGE('S', (ME ":panel_ext_send: \"%.*s\" len=%d\n", len - 4, p + 4, len));
	
	display = aux->service->display(aux);

	if (None == (w_ext = XGetSelectionOwner(display, panel_ext_atom))) {
		TRACE_MESSAGE('s', (ME ":panel_ext_send: no owner of %08x (display=%08x)\n",
				    panel_ext_atom, display));

		XChangeProperty(display, panel_window, panel_prop1_atom, XA_STRING,
				8, PropModeReplace, (unsigned char *)p, len);

		return;
	}

	TRACE_MESSAGE('s', (ME ":panel_ext_send: owner %08x\n", w_ext));

	XChangeProperty(display, w_ext, panel_prop_atom, XA_STRING,
			8, PropModeReplace, (unsigned char *)p, len);

	return;
}


static void
panel_process_property_notify(Display * display, Window window)
{
	long		long_length;
	Atom		actual_type_return;
	int		actual_format_return;
	unsigned long	nitem_return;
	unsigned long	bytes_after_return;
	unsigned char *	prop_return;
	int		r;
	int		imid;
	int		icid;
	aux_icid_t * 	ic;
	int		size;
	aux_data_t *	aux_data;
	unsigned char *	p;
	unsigned char	buf[1024];
	const char *	inbuf;
	size_t		inbytesleft;
	char *		outbuf;
	size_t		outbytesleft;

	TRACE_MESSAGE('P', (ME ":panel_process_property_notify: %08x %08x %08x\n",
			    display, window, panel_prop_atom));

	r = XGetWindowProperty(display, window,
			       panel_prop_atom, 0, INT_MAX, False,
			       AnyPropertyType, &actual_type_return,
			       &actual_format_return, &nitem_return,
			       &bytes_after_return, &prop_return);
	if (Success != r) {
		return;
	}

	imid = ((*(prop_return + 0) << 8) +
		(*(prop_return + 1) << 0));
	icid = ((*(prop_return + 2) << 8) +
		(*(prop_return + 3) << 0));

	TRACE_MESSAGE('P', (ME ":panel_process_property_notify: imid=%d icid=%d \"%s\"\n",
			    imid, icid, prop_return + 4));

	ic = panel_icid_get(icid);

	if (NULL == ic->aux) {
		XFree(prop_return);
		return;
	}

	aux_data = (aux_data_t *)malloc(sizeof (aux_data_t));
	aux_data->type = AUX_DATA_SETVALUE;
	aux_data->im = imid;
	aux_data->ic = icid;
	aux_data->aux_index = 0;
	aux_data->aux_name = (unsigned char *)aux_name_panel_name;
	aux_data->aux_name_length = (sizeof (aux_name_panel_name));

	aux_data->integer_count = 2;
	aux_data->integer_list = (int *)malloc(2 * (sizeof (int)));
	*(aux_data->integer_list + 0) = aux_data->im;
	*(aux_data->integer_list + 1) = aux_data->ic;

	aux_data->string_count = 2;
	aux_data->string_list =
		(aux_string_t *)malloc(2 * (sizeof (aux_string_t)));

	inbuf = (const char *)(prop_return + 4);
	inbytesleft = (nitem_return - 4);
	outbuf = (char *)buf;
	outbytesleft = (sizeof (buf));
	ic->aux->service->mb_utf16(&inbuf, &inbytesleft,
				   &outbuf, &outbytesleft);

	(aux_data->string_list + 0)->ptr = buf;
	(aux_data->string_list + 0)->length = ((sizeof (buf)) - outbytesleft);

	(aux_data->string_list + 1)->ptr = buf;
	(aux_data->string_list + 1)->length = ((sizeof (buf)) - outbytesleft);

#if 0
	(aux_data->string_list + 1)->ptr = (prop_return + 4);
	(aux_data->string_list + 1)->length = (nitem_return - 4);
#endif /* 0 */

	aux_data->string_ptr = NULL;

	p = ic->aux->service->compose(aux_data, &size);

#if defined(ENABLE_TRACE)
	if (TRACE_P('p')) {
		int	i;
		int	j;
		int	k;
		TRACE_MESSAGE('p', ("panel_process_property_notify: len=%d\n", size));
		for (i = 0, k = 0; i < size; i += 4) {
			for (j = 0; j < 4; j++) {
				TRACE_MESSAGE('p', ("%02x", *(p + i + j)));
			}
			if (7 == k) {
				TRACE_MESSAGE('p', ("\n"));
				k = 0;
			} else {
				TRACE_MESSAGE('p', (" "));
				k += 1;
			}
		}
		TRACE_MESSAGE('p', ("\n"));
	}
#endif /* ENABLE_TRACE */

	ic->aux->service->aux_setvalue(ic->aux, p, size);

	free(p);
	free(aux_data->string_list);
	free(aux_data->integer_list);
	free(aux_data);
	XFree(prop_return);

	return;
}


static void
panel_process_client_message(Display * display, Window window, XEvent * event)
{
	XClientMessageEvent *	message;
	int			imid;
	int			icid;

	message = (XClientMessageEvent *)event;

	imid = ((*(message->data.b + 0) << 8) +
		(*(message->data.b + 1) << 0));
	icid = ((*(message->data.b + 2) << 8) +
		(*(message->data.b + 3) << 0));

	if (message->message_type == panel_so_atom) {
		TRACE_MESSAGE('M',
			      (ME ":process_client_message: %08x %08x %d\n",
			       display, window, message->data.l[0]));
		TRACE_MESSAGE('M',
			      (ME ":process_client_message: exiting...\n"));
		exit(0);
	}
		
	switch (message->message_type) {
	case XA_INTEGER:
		TRACE_MESSAGE('M',
			      (ME ":panel_process_client_message: %08x %08x %d\n",
			       display, window, message->data.l[0]));
		break;
	case XA_STRING:
		TRACE_MESSAGE('M',
			      (ME ":panel_process_client_message: d=%08x w=%08x im=%d ic=%d %s\n",
			       display, window, imid, icid, message->data.b + 4));
		break;
	}

	return;
}


static Bool
panel_event_filter(
	Display *	display,
	Window		window,
	XEvent *	event,
	XPointer	pointer)
{
	switch (event->type) {
	case PropertyNotify:
		if (panel_prop_atom != ((XPropertyEvent *)event)->atom) {
			return False;
		}
		panel_process_property_notify(display, window);
		return True;
		break;
	case ClientMessage:
		panel_process_client_message(display, window, event);
		return True;
		break;
	}
	return False;
}


static Bool
panel_init(aux_t * aux)
{
	Display *	display;

	TRACE_MESSAGE('I', (ME ":panel_init: display = %08x\n", display));

	display = aux->service->display(aux);

	panel_ext_atom = XInternAtom(display, HTT_PANEL_EXT_NAME, False);
	panel_so_atom = XInternAtom(display, HTT_PANEL_SO_NAME, False);
	panel_prop_atom = XInternAtom(display, HTT_PANEL_PROP_NAME, False);
	panel_prop1_atom = XInternAtom(display, HTT_PANEL_PROP1_NAME, False);

	if (None != XGetSelectionOwner(display, panel_so_atom)) {
		TRACE_MESSAGE('I', (ME ":panel_init: panel_so already exists\n"));
		return False;
	}
	panel_window = XCreateSimpleWindow(display, RootWindow(display, 0),
				     0, 0, 1, 1, 0, 0, 0);

	TRACE_MESSAGE('I', (ME ":panel_init: window = %08x\n", panel_window));

	if (None != XGetSelectionOwner(display, panel_so_atom)) {
		TRACE_MESSAGE('I', (ME ":panel_init: panel_so already exists (0)\n"));
		return False;
	}
	XSetSelectionOwner(display, panel_so_atom, panel_window, CurrentTime);
	if (panel_window != XGetSelectionOwner(display, panel_so_atom)) {
		TRACE_MESSAGE('I', (ME ":panel_init: panel_so already exists (1)\n"));
		return False;
	}

	XSelectInput(display, panel_window, PropertyChangeMask);

	aux->service->register_X_filter(display, panel_window,
					PropertyNotify, PropertyNotify,
					panel_event_filter, NULL);

	aux->service->register_X_filter(display, panel_window,
					ClientMessage, ClientMessage,
					panel_event_filter, NULL);
}


static void
panel_icid_init(void)
{
	int	i;

	for (i = 0; i < HASH_SIZE; i++) {
		panel_icid[i].icid = (-1);
	}
}


static void
panel_icid_finish(void)
{
	int		i;
	aux_icid_t *	p0;
	aux_icid_t *	p1;

	for (i = 0; i < HASH_SIZE; i++) {
		p0 = panel_icid[i].next;

		for (; NULL != p0; p0 = p1) {
			free(p0);
			p1 = p0->next;
		}
	}
}


static aux_icid_t *
panel_icid_get(int icID)
{
	int		hash_value;
	aux_icid_t *	p;

	hash_value = (icID % HASH_SIZE);

	p = &(panel_icid[hash_value]);

	if ((-1) == p->icid) {
		p->icid = icID;
		return p;
	}

	for (; NULL != p; p = p->next) {
		if (icID == p->icid) {
			return p;
		}
		if (NULL == p->next) {
			p->next = malloc(sizeof (aux_icid_t));
			if (NULL == p->next) {
				return NULL;
			}
			memset(p->next, 0, (sizeof (aux_icid_t)));
			p->next->prev = p;
			return p->next;
		}
	}
	return NULL;	/* never comes here */
}


static void
panel_icid_delete(int icID)
{
	aux_icid_t *	p;

	p = panel_icid_get(icID);
	if (NULL == p) {
		return;
	}
	if (NULL != p->prev) {
		p->prev->next = p->next;
		free(p);
	}
}


static Bool
panel_Create(aux_t * aux)
{
	int		i;
	pid_t		pid;
	aux_icid_t *	aux_icid;

	TRACE_MESSAGE_INIT("TRACE_AUX_SO");

	TRACE_MESSAGE('X', (ME ":panel_Create\n"));

	if (0 == panel_initialized) {
		panel_icid_init();
	}

	if (NULL == (aux_icid = panel_icid_get(aux->service->ic_id(aux)))) {
		return False;
	}
	aux_icid->aux = aux;
	if (0 == panel_initialized) {
		panel_init(aux);
	}

	panel_initialized = 1;

#if 0
	aux->service->data_set(aux, im_id,(void *)aux_icid);
#endif /* 0 */

	pid = fork1();
	if ((pid_t)(-1) == pid) {
		return False;
	} else if (0 == pid) {
		execl(AUX_EXT, "panel", "-name", "panel", NULL);
		_exit(1);
	} else {
		return True;
	}
}


static Bool
panel_Start(aux_t * aux, const unsigned char * p, int size)
{
	TRACE_MESSAGE('X', (ME ":panel_Start: size = %d\n", size));
	return True;
}


static Bool
panel_Draw(aux_t * aux, const unsigned char * p, int size)
{
	aux_data_t *	aux_data;
	char *		string_ptr;
	char		string_buf[1024 * 128];
	int		string_len;
	Window		w;
	XPoint		point;

	TRACE_MESSAGE('X', (ME ":panel_Draw: im=%d ic=%d size = %d\n",
			    aux->service->im_id(aux),
			    aux->service->ic_id(aux),
			    size));

	*((CARD16 *)(string_buf + 0)) = aux->service->im_id(aux);
	*((CARD16 *)(string_buf + 2)) = aux->service->ic_id(aux);
	string_ptr = (string_buf + 4);
	string_len = 4;

	w = aux->service->window(aux);
	aux->service->point(aux, &point);

	TRACE_MESSAGE('D', (ME ":panel_Draw: w=%08x x=%d y=%d\n", w, point.x, point.y));

	aux_data = aux->service->decompose(AUX_DATA_DRAW, p);

#if defined(ENABLE_TRACE)
	if (TRACE_P('D')) {
		char		aux_name;
		const char *	inbuf;
		size_t		inbytesleft;
		char *		outbuf;
		size_t		outbytesleft;
		char		buf[1024];

		TRACE_MESSAGE('D', (ME ":panel_Draw: aux_index = %d\n",
				    aux_data->aux_index));
		inbuf = (char *)(aux_data->aux_name);
		inbytesleft = aux_data->aux_name_length;
		outbuf = buf;
		outbytesleft = (sizeof (buf));
		aux->service->utf16_mb(&inbuf, &inbytesleft,
				       &outbuf, &outbytesleft);
		TRACE_MESSAGE('D', (ME ":panel_Draw: aux_name = \"%.*s\"\n",
				    (sizeof (buf)) - outbytesleft, buf));
	}
#endif /* ENABLE_TRACE */

	if (0 < aux_data->integer_count) {
		int	i;
		TRACE_MESSAGE('D', (ME ":panel_Draw: integer_list[%d] =",
				    aux_data->integer_count));
		for (i = 0; i < aux_data->integer_count; i++) {
			TRACE_MESSAGE('D',
				      (" %d", *(aux_data->integer_list + i)));
		}
		TRACE_MESSAGE('D', ("\n"));
	} else {
		TRACE_MESSAGE('D',
			      (ME ":panel_Draw: integer_count = 0\n"));
	}
	if (0 < aux_data->string_count) {
		int	i;
		for (i = 0; i < aux_data->string_count; i++) {
			const char *	inbuf;
			size_t		inbytesleft;
			char *		outbuf;
			size_t		outbytesleft;
			int		j;

			inbuf = (char *)((aux_data->string_list + i)->ptr);
			inbytesleft = (aux_data->string_list + i)->length;
			outbuf = string_ptr;
			outbytesleft = ((sizeof (string_buf)) - string_len);

			aux->service->utf16_mb(&inbuf, &inbytesleft,
					       &outbuf, &outbytesleft);
#if defined(ENABLE_TRACE)
			j = (((sizeof (string_buf)) - string_len) - outbytesleft);
			TRACE_MESSAGE('D',
				      (ME ":panel_Draw: "
				       "*(string_list + %d) = \"%.*s\" len=%d\n",
				       i, j, string_ptr, j));
#endif /* ENABLE_TRACE */
			string_len = ((sizeof (string_buf)) - outbytesleft);
			string_ptr = (string_buf + string_len);
			switch (*(string_ptr - 1)) {
			case '\0':
				*(string_ptr - 1) = ' ';
				break;
			case ' ':
				break;
			default:
				*string_ptr = ' ';
				string_ptr += 1;
				string_len += 1;
				break;
			}
		}
	} else {
		TRACE_MESSAGE('D',
			      (ME ":panel_Draw: string_count = 0\n"));
	}

	if (0 < string_len) {
		panel_ext_send(aux, (unsigned char *)string_buf, string_len);
	}

	aux->service->decompose_free(aux_data);

	return True;
}


static Bool
panel_Done(aux_t * aux, const unsigned char * p, int size)
{
	TRACE_MESSAGE('X', (ME ":panel_Done: size = %d\n", size));
	return True;
}


static Bool
panel_Switched(aux_t * aux, int im_id, int on_off)
{
	TRACE_MESSAGE('X', (ME ":panel_Switched im_id = %d %s\n",
			    im_id, ((1 == on_off) ? "on" : "off")));

	return True;
}


static Bool
panel_Destroy(aux_t * aux)
{
	TRACE_MESSAGE('X', (ME ":panel_Destroy\n"));

	return True;
}
