/*
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 <stdlib.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <Xm/MenuShell.h>
#include <Xm/DialogS.h>
#include <Xm/RowColumn.h>
#include <Xm/PanedW.h>
#include <Xm/MainW.h>
#include <Xm/Form.h>
#include <Xm/ScrollBar.h>
#include <Xm/ScrolledW.h>
#include <Xm/List.h>
#include <Xm/Label.h>
#include <Xm/PushB.h>
#include <Xm/MwmUtil.h>

#include "xaux_common.h"
#include "xaux_ext_common.h"

#include "sampleja3_xaux.h"

/* Define Aux class */
xaux_class_t xaux_class = {
    "com.sun.sampleja3.LookupAux", 2,
    NULL,
    (Window) 0, (Window) 0,
    (Atom) 0, (Atom) 0, (Atom) 0, {(Atom) 0}, 0, {(Atom) 0}, 0,
    NULL,
};

#define	SAMPLEJA3_LOOKUP_START	1
#define	SAMPLEJA3_LOOKUP_DRAW	2

Widget toplevel;
Widget list;
Widget list_scrolledwin;
Widget controlpane;
Widget maincontrolpane;
Widget popup_button;
Widget prev_button, next_button, test_button;
Widget buttonpane;
Widget dialog_shellform;

void xt_ext_event_handler(Widget, XtPointer, XEvent *, Boolean * b);

static xaux_class_t *xc_ = 0;
static int im_ = 0;
static int ic_ = 0;

/* Event Handler */
void
xt_ext_event_handler(
		     Widget w,
		     XtPointer client_data,
		     XEvent * event,
		     Boolean * b)
{

    switch (event->type) {
	case ClientMessage:
	xaux_ext_process_client_message(XtDisplay(w),
				     (XClientMessageEvent *) event);
	break;
    default:
	break;
    }

    return;
}

/* Methods - Start */
Bool
xaux_ext_Start(
	       xaux_class_t * xc,
	       aux_ext_data_t * aux_ext_data)
{
    return True;
}

int choice_per_window;
int ncolumns;
int nrows;
int drawUpDirection;
int n_choices;
int index_of_first_candidate;
int index_of_last_candidate;
int index_of_current_candidate;

int popuped = 0;

void popup_cb();
void popdown_cb();

/* Methods - Draw */
Bool
xaux_ext_Draw(
	      xaux_class_t * xc,
	      aux_ext_data_t * aux_ext_data)
{
    size_t i;
    char *sp;
    Bool rv = True;
    char buf[256];
    Display *display = XtDisplay(toplevel);
    int x, y;
    Window w_none;
    XWindowAttributes attr;
    char **candidates;
    char tmp[256];

    im_ = aux_ext_data->im;
    ic_ = aux_ext_data->ic;
    xc_ = xc;

    printf("ext_Draw im:0x%x, ic:0x%x\n", aux_ext_data->im, aux_ext_data->ic);

    strcpy(buf, (const char *) aux_ext_data->aux_name);

    printf("ext_Draw[%s] im:0x%x, ic:0x%x\n",
	   buf, aux_ext_data->im, aux_ext_data->ic);

    for (i = 0; i < aux_ext_data->integer_count; i++) {
	printf("\tiv[%02d]=%d\n", i, aux_ext_data->integer_list[i]);
    }

#if 0
    for (i = 0; i < aux_ext_data->string_count; i++) {
	memset(tmp, 0, sizeof(char) * 256);
	strncpy(tmp, aux_ext_data->string_list[i].ptr, aux_ext_data->string_list[i].length);
    }
#endif

    switch (aux_ext_data->integer_list[0]) {
    case SAMPLEJA3_AUXLUC_DONE:
	popdown_cb(0, 0, 0);
	break;

    case SAMPLEJA3_AUXLUC_START:

	choice_per_window = aux_ext_data->integer_list[1];
	ncolumns = aux_ext_data->integer_list[2];
	nrows = aux_ext_data->integer_list[3];
	drawUpDirection = aux_ext_data->integer_list[4];

	break;

    case SAMPLEJA3_AUXLUC_DRAW:

	index_of_current_candidate = aux_ext_data->integer_list[1];
	n_choices = aux_ext_data->integer_list[2];
	index_of_first_candidate = aux_ext_data->integer_list[3];
	index_of_last_candidate = aux_ext_data->integer_list[4];

	if (!popuped) {
	    XGetWindowAttributes(display, aux_ext_data->clientwin, &attr);
	    XTranslateCoordinates(display, aux_ext_data->clientwin, attr.root,
			 -(attr.border_width), -(attr.border_width),
				  &x, &y, &w_none);
	    XtMoveWidget(toplevel, x + aux_ext_data->point.x, y + aux_ext_data->point.y + 20);
	    popup_cb((Widget) 0, (XtPointer) NULL, (XtPointer) NULL);
	}
	candidates = (char **) calloc(aux_ext_data->string_count, sizeof(char *));
	for (i = 0; i < aux_ext_data->string_count; i++) {
	    candidates[i] = (char *) calloc(1, aux_ext_data->string_list[i].length + 1);
	    strncpy(candidates[i], (char *) aux_ext_data->string_list[i].ptr,
		    aux_ext_data->string_list[i].length);
	}

	util_SetListItems(list, candidates, aux_ext_data->string_count);
	for (i = 0; i < aux_ext_data->string_count; i++) {
	    free(candidates[i]);
	}
	free(candidates);

    case SAMPLEJA3_AUXLUC_UPDATE:
	index_of_current_candidate = aux_ext_data->integer_list[1];
	util_SetSelectPost(list, index_of_current_candidate + 1);
	break;

    }
    return True;
}

/* Methods - Done */
Bool
xaux_ext_Done(
	      xaux_class_t * xc,
	      aux_ext_data_t * aux_ext_data)
{
    popdown_cb(0, 0, 0);
    return True;
}


static XrmOptionDescRec optionDescList[] = {
    {"-session", "*session", XrmoptionSepArg, (XPointer) NULL}
};

void next_candidate();

void
ListEventHandler(
		 Widget w,
		 XtPointer client_data,
		 XEvent * event,
		 Boolean * b)
{
    XKeyEvent *key;
    int keycode, keychar, state;
    int integers[4];

    switch (event->type) {
    case KeyRelease:
	/*
	 * KeyEvent that happens on List will be sent to htt_server
	 * as AUX event
	 */
	KeyEventToVirtualKey((XKeyEvent *) event, &keycode, &keychar, &state);
	integers[0] = SAMPLEJA3_AUXSETVAL_KEYPRESS;
	integers[1] = keycode;
	integers[2] = keychar;
	integers[3] = state;

	ReturnToEngine(4, integers, 0, 0);
	break;
    default:
	break;
    }
    return;
}

void
select_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
#define IM_CTRL_MASK    (1 << 1)
    int integers[4];
    int row = util_GetSelectedPos(widget);

    integers[0] = SAMPLEJA3_AUXSETVAL_KEYPRESS;
    integers[1] = '0' + row;
    integers[2] = '0' + row;
    integers[3] = IM_CTRL_MASK;

    ReturnToEngine(4, integers, 0, 0);
}

void
dselect_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
    int integers[4];
    int row = util_GetSelectedPos(widget);

    integers[0] = SAMPLEJA3_AUXSETVAL_KEYPRESS;
    integers[1] = '0' + row;
    integers[2] = '0' + row;
    integers[3] = 0;

    ReturnToEngine(4, integers, 0, 0);
}


void
popdown_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
    popuped = 0;
    XtUnmapWidget(toplevel);
}

void
popup_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
    popuped = 1;
    XtManageChild(dialog_shellform);
    XtMapWidget(toplevel);
    XtSetKeyboardFocus(list, None);
}

void
next_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
    int integers[4];

    integers[0] = SAMPLEJA3_AUXSETVAL_KEYPRESS;
    integers[1] = ' ';
    integers[2] = ' ';
    integers[3] = 0;

    ReturnToEngine(4, integers, 0, 0);
}

void
test_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
    char *strings[4];
    int integers[4];
    integers[0] = 1;
    integers[1] = 2;		/* IM_VK_UP */
    integers[2] = 3;
    integers[3] = 4;

    strings[0] = "test_string1";
    strings[1] = "test_string2";
    strings[2] = "test_string3";
    strings[3] = "test_string4";

    ReturnToEngine(4, integers, 4, strings);
}

void
prev_cb(Widget widget, XtPointer clientData, XtPointer callData)
{
    int integers[4];
    integers[0] = SAMPLEJA3_AUXSETVAL_KEYPRESS;
    integers[1] = 0x26;		/* IM_VK_UP */
    integers[2] = 0x26;
    integers[3] = 0;

    ReturnToEngine(4, integers, 0, 0);
}

CreateUI(Widget parent)
{
    WidgetList children = NULL;
    int numChildren = 0;
    XmString label_xmstring = NULL;
    String title_str = NULL;
    int n;
    Arg args[30];

    dialog_shellform = XtVaCreateManagedWidget("dtb_module_dialog_shellform",
					       xmFormWidgetClass,
					       parent,
					       XmNnoResize, True,
					  XmNdefaultPosition, False,
					       XmNmarginHeight, 0,
					       XmNmarginWidth, 0,
					       NULL);

    n = 0;
    XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNleftOffset, 10); n++;
    XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNrightOffset, 10); n++;
    XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNtopOffset, 10); n++;
    XtSetArg(args[n], XmNorientation, XmVERTICAL); n++;
    controlpane = XmCreateRowColumn(dialog_shellform, "controlpane", args, n);

    n = 0;
    XtSetArg(args[n], XmNscrollBarDisplayPolicy, XmAUTOMATIC); ++n;
    XtSetArg(args[n], XmNlistSizePolicy, XmVARIABLE); ++n;
    XtSetArg(args[n], XmNselectionPolicy, XmBROWSE_SELECT); ++n;
    XtSetArg(args[n], XmNvisibleItemCount, 9); ++n;
    XtSetArg(args[n], XmNbottomAttachment, XmATTACH_NONE); ++n;
    XtSetArg(args[n], XmNrightOffset, 10); ++n;
    XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
    XtSetArg(args[n], XmNleftOffset, 6); ++n;
    XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
    XtSetArg(args[n], XmNtopOffset, 10); ++n;
    XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
    XtSetArg(args[n], XmNx, 6); ++n;
    XtSetArg(args[n], XmNy, 10); ++n;
    list = XmCreateScrolledList(controlpane, "list", args, n);

    list_scrolledwin = XtParent(list);

    XtUnmanageChild(list_scrolledwin);

    n = 0;
    XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNleftOffset, 10); n++;
    XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNrightOffset, 10); n++;
    XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
    XtSetArg(args[n], XmNtopOffset, 10); n++;
    XtSetArg(args[n], XmNorientation, XmHORIZONTAL); n++;

    buttonpane = XmCreateRowColumn(controlpane, "buttonpane", args, n);

    label_xmstring = XmStringCreateLocalized(" ^ ");
    prev_button = XtVaCreateManagedWidget("sort_button2",
					  xmPushButtonWidgetClass,
					  buttonpane,
					  XmNrecomputeSize, True,
				     XmNlabelString, label_xmstring,
					  NULL);
    XmStringFree(label_xmstring);

    label_xmstring = XmStringCreateLocalized(" V ");
    next_button = XtVaCreateManagedWidget("sort_button2",
					  xmPushButtonWidgetClass,
					  buttonpane,
					  XmNrecomputeSize, True,
				     XmNlabelString, label_xmstring,
					  NULL);
    XmStringFree(label_xmstring);

    label_xmstring = XmStringCreateLocalized("Test");
    test_button = XtVaCreateManagedWidget("test_button",
					  xmPushButtonWidgetClass,
					  buttonpane,
					  XmNrecomputeSize, True,
				     XmNlabelString, label_xmstring,
					  NULL);
    XmStringFree(label_xmstring);


    XtAddCallback(prev_button, XmNactivateCallback, prev_cb, NULL);
    XtAddCallback(next_button, XmNactivateCallback, next_cb, NULL);
    XtAddCallback(test_button, XmNactivateCallback, test_cb, NULL);

    XtManageChild(buttonpane);
    XtManageChild(controlpane);
    XtManageChild(list);

    XtVaGetValues(controlpane, XmNchildren, &children, XmNnumChildren, &numChildren, NULL);
    XtManageChildren(children, numChildren);

    XtAddEventHandler(list, KeyReleaseMask, False, ListEventHandler, NULL);
#if	0
    XtAddCallback(list, XmNbrowseSelectionCallback, select_cb, NULL);
#endif
    XtAddCallback(list, XmNdefaultActionCallback, dselect_cb, NULL);
}

int
main(
     int argc,
     char **argv
)
{
    XtAppContext app = (XtAppContext) NULL;
    String *fallback_resources = (String *) NULL;
    ArgList get_resources_args = (ArgList) NULL;
    Cardinal num_get_resources_args = (Cardinal) 0;
    XtLanguageProc language_proc = (XtLanguageProc) NULL;
    XtPointer language_proc_client_data = (XtPointer) NULL;

    int narg;
    Arg args[10];

    XtSetLanguageProc((XtAppContext) NULL, NULL, NULL);

    narg = 0;
    XtSetArg(args[narg], XmNmwmFunctions, MWM_FUNC_MOVE | MWM_FUNC_RESIZE); narg++;
    XtSetArg(args[narg], XmNtitle, "Motif Lookup"); narg++;

    toplevel = XtAppInitialize(&app, "Project",
			   optionDescList, XtNumber(optionDescList),
			       &argc, argv, fallback_resources,
			       args, narg);

    CreateUI(toplevel);

    XtSetMappedWhenManaged(toplevel, FALSE);

    XtRealizeWidget(toplevel);

    /* Register Aux class */
    if (xaux_ext_init_classes(XtDisplay(toplevel),
			&xaux_class, XtWindow(toplevel)) == False) {
	return 2;
    }

    /* Register event handler */
    XtAddEventHandler(toplevel, PropertyChangeMask, False,
		      xt_ext_event_handler, NULL);

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

    XtAppMainLoop(app);
    return 0;
}

util_SetListItems(Widget w, char **candidates, int num_candidates)
{
    int n;
    XmString xmstrings[50];
    char buf[255];
    for (n = 0; n < num_candidates; n++) {
	sprintf(buf, "%d. %s", n + 1, candidates[n]);
	xmstrings[n] = XmStringCreateLocalized(buf);
    }
    XtVaSetValues(w,
		  XmNitems, (XtArgVal) xmstrings,
		  XmNitemCount, (XtArgVal) num_candidates,
		  NULL);
}

util_GetSelectedPos(Widget w)
{
    int *p;
    int count;
    XmListGetSelectedPos(w, &p, &count);
    if (count == 1) {
	return (int) *p;
    }
    return 0;
}

util_SetSelectPost(Widget w, int position)
{
    XmListSelectPos(w, position, False);
}

ReturnToEngine(
	       int integer_count,
	       int *integers,
	       int string_count,
	       char **strings
)
{
    int i;

    aux_ext_data_t *aux_data;

    if (!im_ || !ic_ || !xc_)
	return;

    if (!integer_count && !string_count)
	return;

    aux_data = (aux_ext_data_t *) calloc(1, sizeof(aux_ext_data_t));

    aux_data->im = im_;
    aux_data->ic = ic_;
    aux_data->integer_count = integer_count;
    aux_data->string_count = string_count;

    if (aux_data->integer_count) {
	aux_data->integer_list = (int *) calloc(1, sizeof(int) * aux_data->integer_count);
	for (i = 0; i < aux_data->integer_count; i++) {
	    aux_data->integer_list[i] = integers[i];
	}
    }
    if (aux_data->string_count) {
	aux_data->string_list = (aux_ext_string_t *) calloc(1,
		 sizeof(aux_ext_string_t) * aux_data->string_count);
	for (i = 0; i < aux_data->string_count; i++) {
	    aux_ext_string_t *p = &aux_data->string_list[i];
	    p->length = strlen(strings[i]);
	    p->ptr = (unsigned char *) strdup(strings[i]);
	}
    }
    xaux_ext_SetValue(XtDisplay(toplevel), xc_, aux_data);

    if (aux_data->integer_list)
	free(aux_data->integer_list);
    if (aux_data->string_list) {
	for (i = 0; i < aux_data->string_count; i++) {
	    aux_ext_string_t *p = &aux_data->string_list[i];
	    if (p && p->ptr)
		free(p->ptr);
	}
	free(aux_data->string_list);
    }
    free(aux_data);
}
