/*
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_ext.c,v 1.1.1.1.2.1 2001/03/15 07:52:21 himi Exp $"
 */

#pragma ident	"@(#)aux_ext.c 1.8	00/09/14 SMI"


#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

#include <X11/Xmd.h>

#include <Xm/Xm.h>
#include <Xm/RowColumn.h>
#include <Xm/Text.h>
#include <Xm/PushB.h>

#include "trace_message.h"


#define HTT_AUX_EXT_NAME	"sample_ext"
#define HTT_AUX_SO_NAME		"sample_so"
#define HTT_AUX_PROP_NAME	"sample_prop"
#define HTT_AUX_PROP1_NAME	"sample_prop1"


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

Window		aux_window;

Widget		toplevel;
Widget		aux;
Widget		input;
Widget		button_text;
Widget		button_message;
Widget		button_quit;

int		icid;
int		imid;


void
ButtonTextCallback(Widget w, XtPointer client_data, XtPointer call_data)
{
	XmAnyCallbackStruct *	cb;
	char *			p;
	Display *		display;
	Window			w_so;
	unsigned char		buf[1024];
	int			size;

	display = XtDisplay(w);
	cb = (XmAnyCallbackStruct *)call_data;
	p = XmTextGetString((Widget)client_data);

	TRACE_MESSAGE('B', ("aux_ext:ButtonTextCallback: %d %s\n", cb->reason, p));
	
	if (None == (w_so = XGetSelectionOwner(display, aux_so_atom))) {
		TRACE_MESSAGE('b', ("aux_ext:ButtonTextCallback: no owner of %08x\n",
				    aux_so_atom));
		return;
	}

	TRACE_MESSAGE('B', ("aux_ext:ButtonTextCallback: owner %08x\n", w_so));

	buf[0] = ((imid & 0xff00) >> 8);
	buf[1] = ((imid & 0x00ff) >> 0);
	buf[2] = ((icid & 0xff00) >> 8);
	buf[3] = ((icid & 0x00ff) >> 0);
	size = strlen(p);
	if (((sizeof (buf)) - 4) < size) {
		size = ((sizeof (buf)) - 4);
	}
	memcpy(buf + 4, p, size);
	XChangeProperty(display, w_so, aux_prop_atom, XA_STRING,
			8, PropModeReplace, buf, size + 4);

	XFree(p);

	return;
}


void
ButtonMessageCallback(Widget w, XtPointer client_data, XtPointer call_data)
{
	Display *		display;
	Window			w_so;
	XClientMessageEvent	event;

	display = XtDisplay(w);

	if (None == (w_so = XGetSelectionOwner(display, aux_so_atom))) {
		TRACE_MESSAGE('m', ("aux_ext:ButtonMessageCallback: no owner of %08x\n",
				    aux_so_atom));
		return;
	}

	event.type = ClientMessage;
	event.serial = 0;
	event.send_event = True;
	event.display = display;
	event.window = w_so;
	event.message_type = XA_STRING;
	event.format = 8;
	event.data.b[0] = ((imid & 0xff00) >> 8);
	event.data.b[1] = ((imid & 0x00ff) >> 0);
	event.data.b[2] = ((icid & 0xff00) >> 8);
	event.data.b[3] = ((icid & 0x00ff) >> 0);
	event.data.b[4] = 'h';
	event.data.b[5] = 'o';
	event.data.b[6] = 'g';
	event.data.b[7] = 'e';
	event.data.b[8] = '\0';

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


void
ButtonQuitCallback(Widget w, XtPointer client_data, XtPointer call_data)
{
	Display *		display;
	Window			w_so;
	XClientMessageEvent	event;
	pid_t			pid;

	display = XtDisplay(w);

	if (None == (w_so = XGetSelectionOwner(display, aux_so_atom))) {
		TRACE_MESSAGE('m', ("aux_ext:ButtonMessageCallback: no owner of %08x\n",
				    aux_so_atom));
	} else {
		event.type = ClientMessage;
		event.serial = 0;
		event.send_event = True;
		event.display = display;
		event.window = w_so;
		event.message_type = aux_so_atom;
		event.format = 32;
		event.data.l[0] = 0;

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

	exit(1);
}


void
ProcessInitialPropertyNotify(void)
{
	Display *		display;
	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;
	XTextProperty		text_prop;
	Window			w_so;
	char			buf[1024];
	int			len;

	display = XtDisplay(toplevel);

	if (None == (w_so = XGetSelectionOwner(display, aux_so_atom))) {
		TRACE_MESSAGE('I', ("aux_ext:ProcessInitialPropertyNotify: no owner of %08x\n",
				    aux_so_atom));
		return;
	}

	TRACE_MESSAGE('I', ("aux_ext:ProcessInitialPropertyNotify: %08x %08x %08x\n",
			    display, w_so, aux_prop_atom));

	r = XGetWindowProperty(display, w_so,
			       aux_prop1_atom, 0, INT_MAX, True,
			       AnyPropertyType, &actual_type_return,
			       &actual_format_return, &nitem_return,
			       &bytes_after_return, &prop_return);
	if (Success != r) {
		TRACE_MESSAGE('P', ("aux_ext:ProcessInitialPropertyNotify: Fail\n"));
		return;
	}

	TRACE_MESSAGE('P',
		      ("aux_ext:ProcessInitialPropertyNotify: %x\n", actual_format_return));
	switch (actual_type_return) {
	case XA_STRING:
		TRACE_MESSAGE('P',
			      ("aux_ext:ProcessInitialPropertyNotify: \"%.*s\"\n",
			       nitem_return, prop_return));
		imid = *((CARD16 *)(prop_return + 0));
		icid = *((CARD16 *)(prop_return + 2));
		TRACE_MESSAGE('P', ("aux_ext:ProcessInitialPropertyNotify: imid=%08x icid=%08x\n",
				    imid, icid));
		len = (((nitem_return - 4) < (sizeof (buf))) ?
		       (nitem_return - 4) : ((sizeof (buf)) - 1));
		memcpy(buf, prop_return + 4, len);
		buf[len] = '\0';
		XmTextSetString(input, buf);

		break;
	case XA_INTEGER:
		break;
	}

	XFree(prop_return);
	return;
}


void
ProcessPropertyNotify(Widget w, XEvent * event)
{
	Display *		display;
	XPropertyEvent *	prop_event;
	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;
	XTextProperty		text_prop;
	char			buf[1024];
	int			len;

	prop_event = (XPropertyEvent *)event;

	display = XtDisplay(w);

	if ((prop_event->window != aux_window) ||
	    (prop_event->atom != aux_prop_atom)) {
		return;
	}

	TRACE_MESSAGE('P', ("aux_ext:ProcessPropertyNotify: %08x %08x %08x %08x %08x\n",
			    display,
			    aux_window, aux_prop_atom,
			    prop_event->window, prop_event->atom));

	r = XGetWindowProperty(display, aux_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) {
		TRACE_MESSAGE('P', ("aux_ext:ProcessPropertyNotify: Fail\n"));
		return;
	}

	switch (actual_type_return) {
	case XA_STRING:
		TRACE_MESSAGE('P',
			      ("aux_ext:ProcessPropertyNotify: \"%.*s\"\n",
			       nitem_return, prop_return));
		imid = *((CARD16 *)(prop_return + 0));
		icid = *((CARD16 *)(prop_return + 2));
		TRACE_MESSAGE('P', ("aux_ext:ProcessPropertyNotify: imid=%08x icid=%08x\n",
				    imid, icid));
		len = (((nitem_return - 4) < (sizeof (buf))) ?
		       (nitem_return - 4) : ((sizeof (buf)) - 1));
		memcpy(buf, prop_return + 4, len);
		buf[len] = '\0';
		if ('\0' != buf[0]) {
			XmTextSetString(input, buf);
		}
		break;
	case XA_INTEGER:
		break;
	}

	XFree(prop_return);
	return;
}


void
ProcessClientMessage(Widget w, XEvent * event)
{
	Display *		display;
	XClientMessageEvent *	client_message;
	int			im_id;
	int			ic_id;
	Window			w_client;
	XPoint			point;
	XWindowAttributes	attr;
	int			x;
	int			y;
	Window			w_none;

	client_message = (XClientMessageEvent *)event;

	im_id = client_message->data.s[0];
	ic_id = client_message->data.s[1];
	w_client = client_message->data.l[1];
	point.x = client_message->data.l[2];
	point.y = client_message->data.l[3];

	display = XtDisplay(w);

	if ((client_message->message_type != aux_ext_atom) ||
	    (client_message->window != aux_window)) {
		TRACE_MESSAGE('P', ("aux_ext:ProcessClientMessage "
				    "%08x im=%d ic=%d w=%08x x=%d y=%d\n",
				    aux_window,
				    im_id, ic_id, w_client, point.x, point.y));

		return;
	}

	XGetWindowAttributes(display, w_client, &attr);
	XTranslateCoordinates(display, w_client, attr.root,
			      -(attr.border_width), -(attr.border_width),
			      &x, &y, &w_none);

	TRACE_MESSAGE('P', ("aux_ext:ProcessClientMessage "
			    "%08x im=%d ic=%d w=%08x x=%d+%d+%d y=%d+%d+%d\n",
			    aux_window,
			    im_id, ic_id, w_client,
			    attr.x, point.x,
			    attr.y, point.y));

	XtMoveWidget(w, x + point.x, y + point.y);

	return;
}


void
AuxEventHandler(
	Widget		w,
	XtPointer 	client_data,
	XEvent *	event,
	Boolean *	b)
{

	TRACE_MESSAGE('E', ("aux_ext:AuxEventHandler: %d\n", event->type));

	switch (event->type) {
	case PropertyNotify:
		ProcessPropertyNotify(w, event);
		break;
	case ClientMessage:
		if (XtWindow(w) == aux_window) {
			ProcessClientMessage(w, event);
		}
		break;
	default:
		break;
	}

	return;
}


int
main(int argc, char ** argv)
{
	XtAppContext	app;
	Display *	display;
	char		atom_name[1024];

	TRACE_MESSAGE_INIT("TRACE_AUX_EXT");

	setlocale(LC_ALL, NULL);
	XtSetLanguageProc(NULL, NULL, NULL);

	toplevel = XtAppInitialize(&app, "aux", NULL, 0,
				   &argc, argv, NULL, NULL, 0);

	display = XtDisplay(toplevel);

	sprintf(atom_name, "htt_%s_%s", *(argv + 0), HTT_AUX_EXT_NAME);
	aux_ext_atom = XInternAtom(display, atom_name, False);
	sprintf(atom_name, "htt_%s_%s", *(argv + 0), HTT_AUX_SO_NAME);
	aux_so_atom = XInternAtom(display, atom_name, False);
	sprintf(atom_name, "htt_%s_%s", *(argv + 0), HTT_AUX_PROP_NAME);
	aux_prop_atom = XInternAtom(display, atom_name, False);
	sprintf(atom_name, "htt_%s_%s", *(argv + 0), HTT_AUX_PROP1_NAME);
	aux_prop1_atom = XInternAtom(display, atom_name, False);

	if (None != XGetSelectionOwner(display, aux_ext_atom)) {
		fprintf(stderr, "%s\n", gettext("aux already exists"));
		exit(1);
	}

	aux = XtVaCreateManagedWidget("aux", xmRowColumnWidgetClass,
				       toplevel, NULL, 0);

	input = XtCreateManagedWidget("input", xmTextWidgetClass,
				      aux, NULL, 0);

	button_text = XtCreateManagedWidget("text", xmPushButtonWidgetClass,
					    aux, NULL, 0);

	XtAddCallback(button_text, XmNarmCallback, ButtonTextCallback, input);

	button_message = XtCreateManagedWidget("message",
					       xmPushButtonWidgetClass,
					       aux, NULL, 0);

	XtAddCallback(button_message, XmNarmCallback,
		      ButtonMessageCallback, NULL);

	button_quit = XtCreateManagedWidget("quit", xmPushButtonWidgetClass,
					    aux, NULL, 0);

	XtAddCallback(button_quit, XmNarmCallback, ButtonQuitCallback, NULL);

	XtRealizeWidget(toplevel);

	aux_window = XtWindow(toplevel);

	if (None != XGetSelectionOwner(display, aux_ext_atom)) {
		fprintf(stderr, "%s\n", gettext("aux already exists"));
		exit(1);
	}
	XSetSelectionOwner(display, aux_ext_atom, aux_window, CurrentTime);
	if (aux_window != XGetSelectionOwner(display, aux_ext_atom)) {
		fprintf(stderr, "%s\n", gettext("aux seems existing"));
		exit(1);
	}

	XtAddEventHandler(toplevel, PropertyChangeMask, False, 
			  AuxEventHandler, NULL);

	XtAddEventHandler(toplevel, NoEventMask, True,
			  AuxEventHandler, NULL);

	ProcessInitialPropertyNotify();

	XtAppMainLoop(app);

	return 0;
}
