/*
	$Id: help.c,v 1.2 2000/12/30 01:29:39 rogue Exp $

	Copyright (c) 1999, 2000 Xforge project
*/

#include <Xm/Xm.h>
#include <Xm/Form.h>
#include <Xm/Separator.h>
#include <Xm/PushB.h>
#include <Xm/Text.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "xforge.h"
#include "glob.h"

/*
	free_help() free()s the help buffer and destroys the help widget.
*/

static void free_help(Widget w, char *p) {
	free(p);
	XtUnmanageChild(w);
	XtDestroyWidget(w);
}

/*
	alloc_help(path) opens file named path, allocates memory for it,
	reads it to allocated buffer and returns pointer for the buffer.
*/

static char *alloc_help(const char *path) {
	int fd;
	struct stat st;
	char *p;

	if ((fd = open(path, O_RDONLY)) == -1) {
		syserr(path);
		return NULL;
	}

	if (fstat(fd, &st)) {
		syserr(path);
		return NULL;
	}

	if (!(p = malloc(st.st_size + 1))) {
		syserr(EMEM_MSG);
		close(fd);
		return NULL;
	}

	if (read(fd, p, st.st_size) != st.st_size) {
		syserr(path);
		close(fd);
		free(p);
		return NULL;
	}

	p[st.st_size] = '\0';			/* null terminate the string */
	close(fd);
	return p;
}

/*
	spawn_help() opens file named path and displays it in XmText
	widget in a dialog.
*/

void spawn_help(const char *path) {
	Widget dialog;
	Widget w;
	char *p;

	/* just return until this is reasonably implemented */
	return;

	dialog = XmCreateFormDialog(top_wid, "helpDialog", NULL, 0);

	if (!(p = alloc_help(path)))
		return;

	w = XmCreateScrolledText(dialog, "helpText", NULL, 0);
	XtVaSetValues(w,
		XmNvalue, p,
		XmNeditable, False,
		XmNcursorPositionVisible, False,
		NULL);
	XtVaSetValues(XtParent(w),
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_NONE,
		NULL);
	XtManageChild(w);

	w = XtVaCreateManagedWidget("separator",
		xmSeparatorWidgetClass, dialog,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNtopAttachment, XmATTACH_WIDGET,
		XmNtopWidget, XtParent(w),
		NULL);

	w = XtVaCreateManagedWidget("dismiss",
		xmPushButtonWidgetClass, dialog,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNtopAttachment, XmATTACH_WIDGET,
		XmNtopWidget, w,
		XmNbottomAttachment, XmATTACH_FORM,
		NULL);

	XtVaSetValues(dialog,
		XmNdefaultButton, w,
		NULL);

	XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)free_help, p);

	XtManageChild(dialog);
}
