/*
* work_window.c: attaching an event handler to the work_window of a XmHTML
* widget.
*/
#include <XmHTML.h>

void
attachInfoHandler(Widget html, Widget popup)
{
	Widget work_window;

	XtVaGetValues(html, XmNworkWindow, &work_window, NULL);

	/*
	* Add an event handler which responds to mouse clicks. "popup" is the
	* popup menu which is to be displayed, it is stored as client_data
	* for the event handler.
	*/
	XtAddEventHandler(work_window, ButtonPressMark, 0,
		(XtEventHandler)infoHandler, popup);
}

void
infoHandler(Widget work_window, Widget popup, XButtonPressedEvent *event)
{
	XmHTMLInfoPtr info;
	Widget html_w;
	WidgetList children;

	/* we only take events generated by button 3 */
	if(event->button != 3)
		return;

	/*
	* The work_window is a child of a XmHTML widget, so we can get a handle
	* to the XmHTML widget itself by using Xt's XtParent routine.
	*/
	html_w = XtParent(work_window);

	/* get the info for the selected position.  */
	info = XmHTMLXYToInfo(html_w, event->x, event->y);

	/*
	* Check the returned info structure. There will be nothing to display
	* if the pointer wasn't over an image or anchor when the mouse was
	* clicked.
	*/
	if(info == NULL || (info->image == NULL && info->anchor == NULL))
		return;

	/*
	* For this example we assume that the popup menu has two buttons:
	* a hyperlink button and an image button. We retrieve these children
	* of the popup menu using the XmNchildren resource of Motif's
	* rowColumn widget.
	*/
	XtVaGetValues(popup, XmNchildren, &children, NULL);

	/* check if the info structure has an anchor */
	if(info->anchor)
	{
		XmString label;
		label = XmStringCreateLocalized(info->anchor->href);
		XtVaSetValues(children[0], XmNlabelString, label, NULL);
		XmStringFree(label);
		XtManageChild(children[0]);
	}
	else
		XtUnmanageChild(children[0]);

	/* check if the info structure has an image */
	if(info->image)
	{
		XmString label;
		label = XmStringCreateLocalized(info->image->url);
		XtVaSetValues(children[1], XmNlabelString, label, NULL);
		XmStringFree(label);
		XtManageChild(children[1]);
	}
	else
		XtUnmanageChild(children[1]);

	/* the "popup" menu has now been configured, pop it up */
	XmMenuPosition(popup, event);
	XtManageChild(popup);
}
