/*
 * dialog.c : A popup string entry box
 *
 * George Ferguson, ferguson@cs.rochester.edu, 20 Oct 1991.
 *
 */

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>
#include <X11/Xaw/Dialog.h>
#include <X11/Xaw/Cardinals.h>
#include <stdio.h>
extern Widget toplevel;			/* this is the only external */

/*
 * Functions defined here
 */
char *dialog0();			/* main public routine */
void dialogOk(), dialogCancel();	/* public action procedures */

static Widget dialogShell,dialogDialog;
static Boolean dialogDone;
static char *dialogResult;

char *
dialog(str,value)
char *str,*value;
{
    Arg args[2];
    XEvent event;
    Window rwin,child;
    int rx,ry,cx,cy,x,y;
    unsigned int but;
    Dimension w,h;

    /* Go synchronous or the widgets don't resize properly */
    XSynchronize(XtDisplay(toplevel),True);
    if (dialogShell == NULL) {
	dialogShell = XtCreatePopupShell("dialogShell",
					 transientShellWidgetClass,
					 toplevel,NULL,ZERO);
	dialogDialog = XtCreateManagedWidget("dialogDialog",
					     dialogWidgetClass,
					     dialogShell,NULL,ZERO);
	XawDialogAddButton(dialogDialog,"okButton",dialogOk,NULL);
	XawDialogAddButton(dialogDialog,"cancelButton",dialogCancel,NULL);
	XtRealizeWidget(dialogShell);
    }
    /* Set the label and initial value */
    XtSetArg(args[0],XtNlabel,str);
    XtSetArg(args[1],XtNvalue,(value ? value : ""));
    XtSetValues(dialogDialog,args,TWO);
    /* Center the popup over the mouse */
    XtSetArg(args[0],XtNwidth,&w);
    XtSetArg(args[1],XtNheight,&h);
    XtGetValues(dialogShell,args,TWO);
    XQueryPointer(XtDisplay(toplevel),XtWindow(toplevel),
					&rwin,&child,&rx,&ry,&cx,&cy,&but);
    x = rx-w/2;
    if (x < 0)
	x = 0;
    else if (x > WidthOfScreen(XtScreen(toplevel))-w)
	x = WidthOfScreen(XtScreen(toplevel))-w;
    y = ry-h/2;
    if (y < 0)
	y = 0;
    else if (y > HeightOfScreen(XtScreen(toplevel))-h)
	y = WidthOfScreen(XtScreen(toplevel))-h;
    XtSetArg(args[0],XtNx,x);
    XtSetArg(args[1],XtNy,y);
    XtSetValues(dialogShell,args,TWO);
    /* Pop it up and block until one of the buttons is clicked */
    dialogDone = False;
    XtPopup(dialogShell,XtGrabExclusive);
    while (!dialogDone) {
	XtAppNextEvent(XtWidgetToApplicationContext(toplevel),&event);
	XtDispatchEvent(&event);
    }
    /* Okay, pop it down */
    XtPopdown(dialogShell);
    /* Back to normal */
    XSynchronize(XtDisplay(toplevel),False);
    /* And here's the entered value */
    return(dialogResult);
}

/*ARGSUSED*/
void
dialogOk(w,event,params,num_params)
Widget w;
XEvent *event;
String *params;
Cardinal *num_params;
{
    dialogResult = XawDialogGetValueString(dialogDialog);
    dialogDone = True;
}

/*ARGSUSED*/
void
dialogCancel(w,event,params,num_params)
Widget w;
XEvent *event;
String *params;
Cardinal *num_params;
{
    dialogResult = NULL;
    dialogDone = True;
}
