/*
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.

*/

#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	AUX_EXT			"/usr/lib/im/locale/zh_CN/newpy/aux_win"

typedef struct _aux_icid {
        aux_t *                 aux;
        int                     icid;
        struct _aux_icid *      prev;
        struct _aux_icid *      next;
} aux_icid_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.newpy.NewPYPanel
*/

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,
	0x006e, 0x0065, 0x0077, 0x0070,
	0x0079, 0x002e, 0x004e, 0x0065, 
	0x0077, 0x0050, 0x0059, 0x0050,
	0x0061, 0x006e, 0x0065, 0x006c,
};

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_panel_name),
	  aux_name_panel_name},
	 &aux_method_panel},

	{{0, NULL}, NULL}
};

#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 */

#ifdef HAVE_FORK1
	pid = fork1();
#else
	pid = fork();
#endif
	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];
	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;
}
