/***************************************************************************/
/***************************************************************************/
/*                                                                         */
/*   (c) 1995-1999.  The Regents of the University of California.  All     */
/*   rights reserved.                                                      */
/*                                                                         */
/*   This work was produced at the University of California, Lawrence      */
/*   Livermore National Laboratory (UC LLNL) under contract no.            */
/*   W-7405-ENG-48 (Contract 48) between the U.S. Department of Energy     */
/*   (DOE) and The Regents of the University of California (University)    */
/*   for the operation of UC LLNL.  Copyright is reserved to the           */
/*   University for purposes of controlled dissemination,                  */
/*   commercialization through formal licensing, or other disposition      */
/*   under terms of Contract 48; DOE policies, regulations and orders;     */
/*   and U.S. statutes.  The rights of the Federal Government are          */
/*   reserved under Contract 48 subject to the restrictions agreed upon    */
/*   by the DOE and University.                                            */
/*                                                                         */
/*                                                                         */
/*                              DISCLAIMER                                 */
/*                                                                         */
/*   This software was prepared as an account of work sponsored by an      */
/*   agency of the United States Government.  Neither the United States    */
/*   Government nor the University of California nor any of their          */
/*   employees, makes any warranty, express or implied, or assumes any     */
/*   liability or responsibility for the accuracy, completeness, or        */
/*   usefulness of any information, apparatus, product, or process         */
/*   disclosed, or represents that its specific commercial products,       */
/*   process, or service by trade name, trademark, manufacturer, or        */
/*   otherwise, does not necessarily constitute or imply its               */
/*   endorsement, recommendation, or favoring by the United States         */
/*   Government or the University of California. The views and opinions    */
/*   of the authors expressed herein do not necessarily state or reflect   */
/*   those of the United States Government or the University of            */
/*   California, and shall not be used for advertising or product          */
/*   endorsement purposes.                                                 */
/*                                                                         */
/*   Permission to use, copy, modify and distribute this software and its  */
/*   documentation for any non-commercial purpose, without fee, is         */
/*   hereby granted, provided that the above copyright notice and this     */
/*   permission notice appear in all copies of the software and            */
/*   supporting documentation, and that all UC LLNL identification in      */
/*   the user interface remain unchanged.  The title to copyright LLNL     */
/*   XDIR shall at all times remain with The Regents of the University     */
/*   of California and users agree to preserve same. Users seeking the     */
/*   right to make derivative works with LLNL XDIR for commercial          */
/*   purposes may obtain a license from the Lawrence Livermore National    */
/*   Laboratory's Technology Transfer Office, P.O. Box 808, L-795,         */
/*   Livermore, CA 94550.                                                  */
/*                                                                         */
/***************************************************************************/
/***************************************************************************/

#include <Xm/Form.h>
#include <Xm/PushB.h>
#include <Xm/Label.h>
#include <Xm/List.h>
#include <Xm/Separator.h>
#include "history.h"
#include "xdir.h"

static struct {
	Widget w_dialog;
	Widget w_actionArea;
	Widget w_okButton;
	Widget w_cancelButton;
	Widget w_helpButton;
	Widget w_separator;
	Widget w_controlArea;
	Widget w_hostsLabel;
	Widget w_deleteHostButton;
	Widget w_hosts;
	Widget w_categoriesLabel;
	Widget w_categories;
	Widget w_itemsLabel;
	Widget w_deleteItemButton;
	Widget w_items;
} hedit;

static char *hedit_help[] = {
	"This dialog allows the user to remove unwanted history information. ",
	"(LLNL XDIR automatically saves certain information, such as the",
	"paths of previously visited directories, for future use.)\n",
	"\n",
	"Four categories of history information are saved for each host:",
	"(1) paths of previously visited directories, (2) wildcard expressions",
	"used in selecting directory entries, (3) user names used in connecting",
	"to the host, and (4) low-level \"quoted\" commands sent to the host's",
	"FTP server.\n",
	"\n",
	"An entire host's history information may be removed by selecting an",
	"entry in the \"Hosts\" list and then clicking the DELETE HOST",
	"button.\n",
	"\n",
	"A single item may be removed by using the three lists to specify",
	"host, category and item, and then clicking the DELETE ITEM",
	"button.\n",
	"\n",
	"Click the OK button to cause the changes to take effect (and remove",
	"the dialog).  Click the CANCEL button to undo the changes (and",
	"remove the dialog).",
	NULL
};

static struct history_st *temp_history;

static char *category_name[] = {
	"Directory Path",
	"Wildcard Exp",
	"User Name",
	"Quoted Cmd"
};

extern struct history_st *history;

struct history_st *copy_history();
struct host_link *find_host_name();
char *get_selected_item();
char *cstring_to_text();
void cb_map_dialog();
void cb_hedit_cancel();
void cb_hedit_ok();
void cb_hedit_cancel();
void cb_hedit_help();
void cb_hedit_delete_host();
void cb_hedit_delete_item();
void cb_hedit_hosts_single();
void cb_hedit_categories_single();
void cb_hedit_items_single();
void create_edit_history_dialog();
void free_history();
void load_hosts_list();


/*
 * cb_edit_history - Callback to pop up Edit History Dialog.
 */
void
cb_edit_history(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	struct dirwin_st *dirwin = (struct dirwin_st *)client_data;

	/* Clear error flag */
	raise_okflag();

	/* Create "Edit History" Dialog */
	create_edit_history_dialog(dirwin);

	/* Make temporary copy of the history */
	temp_history = copy_history(history);

	/* Initialize the "Edit History" Dialog */
	load_hosts_list();

	/* Pop up the "Edit History" Dialog */
	XtManageChild(hedit.w_dialog);
	traverse_to_widget(hedit.w_okButton);
}


/*
 * create_edit_history_dialog - Create dialog for editing history.  "dirwin"
 *                              is the directory window to center the Edit
 *                              History dialog over.
 */
void
create_edit_history_dialog(dirwin)
struct dirwin_st *dirwin;
{
	int i;
	Arg args[4];

	/* Create form dialog */
	i = 0;
	XtSetArg(args[i], XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL); i++;
	XtSetArg(args[i], XmNautoUnmanage, False); i++;
	XtSetArg(args[i], XmNresizePolicy, XmRESIZE_NONE); i++;
	hedit.w_dialog = XmCreateFormDialog(dirwin->w_shell, "editHistory", args,i);
	XtAddCallback(hedit.w_dialog, XmNmapCallback, cb_map_dialog,
		(XtPointer)XtWindow(dirwin->w_shell));

	/* Add callback for the WM_DELETE_WINDOW protocol */
	add_wm_delete_window_cb(hedit.w_dialog, cb_hedit_cancel, NULL, False);

	/* Create form for action area */
    hedit.w_actionArea = XtVaCreateWidget(
        "actionArea",
        xmFormWidgetClass,
        hedit.w_dialog,
		XmNmarginHeight,		10,
		XmNbottomAttachment,	XmATTACH_FORM,
		XmNleftAttachment,		XmATTACH_FORM,
		XmNrightAttachment,		XmATTACH_FORM,
        NULL
    );

	/* Create OK pushbutton */
    hedit.w_okButton = XtVaCreateManagedWidget(
        "okButton",
        xmPushButtonWidgetClass,
        hedit.w_actionArea,
		XmNdefaultButtonShadowThickness,	1,
		XmNmarginHeight,					4,
		XmNtopAttachment,					XmATTACH_FORM,
        XmNbottomAttachment,    			XmATTACH_FORM,
        XmNleftAttachment,      			XmATTACH_POSITION,
        XmNleftPosition,        			5,
        XmNrightAttachment,     			XmATTACH_POSITION,
        XmNrightPosition,       			23,
        NULL
    );
    XtAddCallback(hedit.w_okButton, XmNactivateCallback, cb_hedit_ok,
        (XtPointer)NULL);
	XtVaSetValues(hedit.w_dialog, XmNdefaultButton, hedit.w_okButton, NULL);

	/* Create Cancel pushbutton */
    hedit.w_cancelButton = XtVaCreateManagedWidget(
        "cancelButton",
        xmPushButtonWidgetClass,
        hedit.w_actionArea,
		XmNdefaultButtonShadowThickness,	1,
		XmNmarginHeight,					4,
		XmNtopAttachment,					XmATTACH_FORM,
        XmNbottomAttachment,    			XmATTACH_FORM,
        XmNleftAttachment,      			XmATTACH_POSITION,
        XmNleftPosition,        			41,
        XmNrightAttachment,     			XmATTACH_POSITION,
        XmNrightPosition,       			59,
        NULL
    );
    XtAddCallback(hedit.w_cancelButton, XmNactivateCallback, cb_hedit_cancel,
        (XtPointer)NULL);

	/* Create Help pushbutton */
    hedit.w_helpButton = XtVaCreateManagedWidget(
        "helpButton",
        xmPushButtonWidgetClass,
        hedit.w_actionArea,
		XmNdefaultButtonShadowThickness,	1,
		XmNmarginHeight,					4,
		XmNtopAttachment,					XmATTACH_FORM,
        XmNbottomAttachment,    			XmATTACH_FORM,
        XmNleftAttachment,      			XmATTACH_POSITION,
        XmNleftPosition,        			77,
        XmNrightAttachment,     			XmATTACH_POSITION,
        XmNrightPosition,       			95,
        NULL
    );
    XtAddCallback(hedit.w_helpButton, XmNactivateCallback, cb_hedit_help,
        (XtPointer)NULL);

	XtManageChild(hedit.w_actionArea);

    /* Create separator */
    hedit.w_separator = XtVaCreateManagedWidget(
        "separator",
        xmSeparatorWidgetClass,
        hedit.w_dialog,
        XmNbottomAttachment,    XmATTACH_WIDGET,
        XmNbottomWidget,        hedit.w_actionArea,
        XmNleftAttachment,      XmATTACH_FORM,
        XmNrightAttachment,     XmATTACH_FORM,
        NULL
    );

	/* Create form for control area */
	hedit.w_controlArea = XtVaCreateWidget(
		"controlArea",
		xmFormWidgetClass,
		hedit.w_dialog,
		XmNtopAttachment,		XmATTACH_FORM,
		XmNleftAttachment,		XmATTACH_FORM,
		XmNrightAttachment,		XmATTACH_FORM,
		XmNbottomAttachment,	XmATTACH_WIDGET,
		XmNbottomWidget,		hedit.w_separator,
		XmNmarginHeight,		10,
		XmNmarginWidth,			10,
		NULL
	);

	/* Create label for scrolled list of hosts */
	hedit.w_hostsLabel = XtVaCreateManagedWidget(
		"hostsLabel",
		xmLabelWidgetClass,
		hedit.w_controlArea,
		XmNtopAttachment,		XmATTACH_FORM,
		XmNleftAttachment,		XmATTACH_FORM,
		XmNrightAttachment,		XmATTACH_POSITION,
		XmNrightPosition,		37,
		NULL
	);

	/* Create "Delete Host" pushbutton */
	hedit.w_deleteHostButton = XtVaCreateManagedWidget(
		"deleteHostButton",
		xmPushButtonWidgetClass,
		hedit.w_controlArea,
		XmNleftAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNleftWidget,			hedit.w_hostsLabel,
		XmNleftOffset,			42,
		XmNrightAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNrightWidget,			hedit.w_hostsLabel,
		XmNrightOffset,			42,
		XmNbottomAttachment,	XmATTACH_FORM,
		NULL
	);
    XtAddCallback(hedit.w_deleteHostButton, XmNactivateCallback,
		cb_hedit_delete_host, (XtPointer)NULL);

	/* Create scrolled list of hosts */
	i = 0;
	XtSetArg(args[i], XmNselectionPolicy, XmSINGLE_SELECT); i++;
	XtSetArg(args[i], XmNlistSizePolicy, XmCONSTANT); i++;
	hedit.w_hosts = XmCreateScrolledList(hedit.w_controlArea, "hosts", args,
		i);
	XtVaSetValues(
		XtParent(hedit.w_hosts),
		XmNtopAttachment,		XmATTACH_WIDGET,
		XmNtopWidget,			hedit.w_hostsLabel,
		XmNtopOffset,			5,
		XmNbottomAttachment,	XmATTACH_WIDGET,
		XmNbottomWidget,		hedit.w_deleteHostButton,
		XmNbottomOffset,		10,
		XmNleftAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNleftWidget,			hedit.w_hostsLabel,
		XmNrightAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNrightWidget,			hedit.w_hostsLabel,
		NULL
	);
	XtManageChild(hedit.w_hosts);
	XtAddCallback(hedit.w_hosts, XmNsingleSelectionCallback,
		cb_hedit_hosts_single, (XtPointer)NULL);

	/* Create label for scrolled list of categories */
	hedit.w_categoriesLabel = XtVaCreateManagedWidget(
		"categoriesLabel",
		xmLabelWidgetClass,
		hedit.w_controlArea,
		XmNtopAttachment,		XmATTACH_FORM,
		XmNleftAttachment,		XmATTACH_POSITION,
		XmNleftPosition,		39,
		XmNrightAttachment,		XmATTACH_POSITION,
		XmNrightPosition,		61,
		NULL
	);

	/* Create scrolled list of categories */
	i = 0;
	XtSetArg(args[i], XmNselectionPolicy, XmSINGLE_SELECT); i++;
	XtSetArg(args[i], XmNlistSizePolicy, XmCONSTANT); i++;
	hedit.w_categories = XmCreateScrolledList(hedit.w_controlArea, "categories",
		args, i);
	XtVaSetValues(
		XtParent(hedit.w_categories),
		XmNtopAttachment,			XmATTACH_WIDGET,
		XmNtopWidget,				hedit.w_categoriesLabel,
		XmNtopOffset,				5,
		XmNbottomAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNbottomWidget,			hedit.w_hosts,
		XmNleftAttachment,			XmATTACH_OPPOSITE_WIDGET,
		XmNleftWidget,				hedit.w_categoriesLabel,
		XmNrightAttachment,			XmATTACH_OPPOSITE_WIDGET,
		XmNrightWidget,				hedit.w_categoriesLabel,
		NULL
	);
	XtManageChild(hedit.w_categories);
	XtAddCallback(hedit.w_categories, XmNsingleSelectionCallback,
		cb_hedit_categories_single, (XtPointer)NULL);

	/* Create label for scrolled list of items */
	hedit.w_itemsLabel = XtVaCreateManagedWidget(
		"itemsLabel",
		xmLabelWidgetClass,
		hedit.w_controlArea,
		XmNtopAttachment,		XmATTACH_FORM,
		XmNleftAttachment,		XmATTACH_POSITION,
		XmNleftPosition,		63,
		XmNrightAttachment,		XmATTACH_FORM,
		NULL
	);

	/* Create "Delete Item" pushbutton */
	hedit.w_deleteItemButton = XtVaCreateManagedWidget(
		"deleteItemButton",
		xmPushButtonWidgetClass,
		hedit.w_controlArea,
		XmNleftAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNleftWidget,			hedit.w_itemsLabel,
		XmNleftOffset,			42,
		XmNrightAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNrightWidget,			hedit.w_itemsLabel,
		XmNrightOffset,			42,
		XmNbottomAttachment,	XmATTACH_FORM,
		NULL
	);
    XtAddCallback(hedit.w_deleteItemButton, XmNactivateCallback,
		cb_hedit_delete_item, (XtPointer)NULL);

	/* Create scrolled list of items */
	i = 0;
	XtSetArg(args[i], XmNselectionPolicy, XmSINGLE_SELECT); i++;
	XtSetArg(args[i], XmNlistSizePolicy, XmCONSTANT); i++;
	hedit.w_items = XmCreateScrolledList(hedit.w_controlArea, "items", args, i);
	XtVaSetValues(
		XtParent(hedit.w_items),
		XmNtopAttachment,		XmATTACH_WIDGET,
		XmNtopWidget,			hedit.w_itemsLabel,
		XmNtopOffset,			5,
		XmNbottomAttachment,	XmATTACH_WIDGET,
		XmNbottomWidget,		hedit.w_deleteItemButton,
		XmNbottomOffset,		10,
		XmNleftAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNleftWidget,			hedit.w_itemsLabel,
		XmNrightAttachment,		XmATTACH_OPPOSITE_WIDGET,
		XmNrightWidget,			hedit.w_itemsLabel,
		NULL
	);
	XtManageChild(hedit.w_items);
	XtAddCallback(hedit.w_items, XmNsingleSelectionCallback,
		cb_hedit_items_single, (XtPointer)NULL);

	XtManageChild(hedit.w_controlArea);
}


/*
 * cb_hedit_ok - Callback that applies current history and then closes
 *               Edit History dialog.
 */
void
cb_hedit_ok(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	/* Keep the changes made to the temporary history */
	free_history(history);
	history = temp_history;

	/* Get rid of Edit History Dialog */
	XtUnmanageChild(hedit.w_dialog);
	XtDestroyWidget(XtParent(hedit.w_dialog));
}


/*
 * cb_hedit_cancel - Callback that restores old history and then closes
 *                   Edit History dialog.
 */
void
cb_hedit_cancel(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	/* Free temporary history */
	free_history(temp_history);

	/* Get rid of Edit History Dialog */
	XtDestroyWidget(XtParent(hedit.w_dialog));
}


/*
 * cb_hedit_help - Callback that displays help info for the Edit History
 *                 dialog.
 */
void
cb_hedit_help(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	help_dialog(widget, True, "Edit History", hedit_help);
}


/*
 * cb_hedit_delete_host - Callback that deletes selected item in the Hosts
 *                        list.
 */
void
cb_hedit_delete_host(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	int i;
	char *host_name;
	struct host_link *hptr;
	struct item_link *cptr;
	int *positions;
	int npositions;
	int pos;

	/* Get selected item */
	host_name = get_selected_item(hedit.w_hosts);
	hptr = find_host_name(temp_history, host_name);
	XtFree(host_name);

	/* Delete host from temp history */
	if (hptr == temp_history->host_head)
		temp_history->host_head = hptr->next;
	else
		hptr->prev->next = hptr->next;
	if (hptr == temp_history->host_tail)
		temp_history->host_tail = hptr->prev;
	else
		hptr->next->prev = hptr->prev;
	XtFree(hptr->host_name);
	for (i=0; i<NUMKINDS; i++)
		while (hptr->kind[i].head) {
			XtFree(hptr->kind[i].head->value);
			cptr = hptr->kind[i].head;
			hptr->kind[i].head =  hptr->kind[i].head->next;
			XtFree((char *)cptr);
		}
	XtFree((char *)hptr);
	temp_history->host_count--;

	/* Delete item from Hosts list and select neighboring item */
	if (!XmListGetSelectedPos(hedit.w_hosts, &positions, &npositions))
		npositions = 0;
	if (npositions != 1)   /* Sanity check */
		fatal_error("Bug in cb_hedit_delete_host()");
	pos = positions[0];
	XtFree((char *)positions);
	XmListDeletePos(hedit.w_hosts, pos);
	if (temp_history->host_count >= pos)
		XmListSelectPos(hedit.w_hosts, pos, True);
	else if (temp_history->host_count > 0)
		XmListSelectPos(hedit.w_hosts, temp_history->host_count, True);
	else {
		XmListDeleteAllItems(hedit.w_categories);
		XmListDeleteAllItems(hedit.w_items);
		XtSetSensitive(hedit.w_deleteHostButton, False);
		XtSetSensitive(hedit.w_deleteItemButton, False);
	}
}


/*
 * cb_hedit_delete_item - Callback that deletes the selected item in the
 *                        Items list.
 */
void
cb_hedit_delete_item(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	char *host_name;
	char *category;
	char *item_name;
	int cindx;
	struct host_link *hptr;
	struct item_link *cptr;
	int *positions;
	int npositions;
	int pos;

	/* Delete item from temporary history */
	host_name = get_selected_item(hedit.w_hosts);
	hptr = find_host_name(temp_history, host_name);
	XtFree(host_name);
	category = get_selected_item(hedit.w_categories);
	cindx = category_indx(category);
	XtFree(category);
	item_name = get_selected_item(hedit.w_items);
	cptr = hptr->kind[cindx].head;
	while (cptr) {
		if (!strcmp(cptr->value, item_name))
			break;
		cptr = cptr->next;
	}
	if (cptr == NULL)
		fatal_error("Bug in cb_hedit_delete_item()");
	XtFree(item_name);
	if (cptr == hptr->kind[cindx].head)
		hptr->kind[cindx].head = cptr->next;
	else
		cptr->prev->next = cptr->next;
	if (cptr == hptr->kind[cindx].tail)
		hptr->kind[cindx].tail = cptr->prev;
	else
		cptr->next->prev = cptr->prev;
	XtFree(cptr->value);
	XtFree((char *)cptr);
	hptr->kind[cindx].count--;

	/* Delete item from Items list and select neighboring item */
	if (!XmListGetSelectedPos(hedit.w_items, &positions, &npositions))
		npositions = 0;
	if (npositions != 1)   /* Sanity check */
		fatal_error("Bug in cb_hedit_delete_item()");
	pos = positions[0];
	XtFree((char *)positions);
	XmListDeletePos(hedit.w_items, pos);
	if (hptr->kind[cindx].count >= pos)
		XmListSelectPos(hedit.w_items, pos, True);
	else if (hptr->kind[cindx].count > 0)
		XmListSelectPos(hedit.w_items, hptr->kind[cindx].count, True);

	/* Adjust sensitivity of "Delete Item" button */
	if (hptr->kind[cindx].count > 0)
		XtSetSensitive(hedit.w_deleteItemButton, True);
	else
		XtSetSensitive(hedit.w_deleteItemButton, False);
}


/*
 * copy_history - Return a pointer to a copy of the data structure pointed
 *                to by "hist".  Call free_history() to release returned
 *                memory.
 */
struct history_st *
copy_history(hist)
struct history_st *hist;
{
	struct history_st *thist;
	struct host_link *hptr;
	struct host_link *thptr;
	struct item_link *cptr;
	struct item_link *tcptr;
	int i;

	/* Initialize data structure */
	thist = XtNew(struct history_st);
	thist->host_head = NULL;
	thist->host_tail = NULL;
	thist->host_count = hist->host_count;

	/* Now make a copy */
	hptr = hist->host_head;
	while (hptr) {
		thptr = XtNew(struct host_link);
		thptr->host_name = XtNewString(hptr->host_name);
		thptr->prev = thist->host_tail;
		thptr->next = NULL;
		if (thist->host_tail)
			thist->host_tail->next = thptr;
		thist->host_tail = thptr;
		if (thist->host_head == NULL)
			thist->host_head = thptr;
		for (i=0; i<NUMKINDS; i++) {
			thptr->kind[i].count = hptr->kind[i].count;
			thptr->kind[i].head = NULL;
			thptr->kind[i].tail = NULL;
			cptr = hptr->kind[i].head;
			while (cptr) {
				tcptr = XtNew(struct item_link);
				tcptr->value = XtNewString(cptr->value);
				tcptr->prev = thptr->kind[i].tail;
				tcptr->next = NULL;
				if (thptr->kind[i].tail)
					thptr->kind[i].tail->next = tcptr;
				if (thptr->kind[i].head == NULL)
					thptr->kind[i].head = tcptr;
				thptr->kind[i].tail = tcptr;
				cptr = cptr->next;
			}
		}
		hptr = hptr->next;
	}

	return thist;
}


/*
 * free_history - Release memory pointed to by "hist".
 */
void
free_history(hist)
struct history_st *hist;
{
	struct host_link *hptr;
	struct host_link *hnext;
	struct item_link *cptr;
	struct item_link *cnext;
	int i;

	hptr = hist->host_head;
	while (hptr) {
		XtFree(hptr->host_name);
		for (i=0; i<NUMKINDS; i++) {
			cptr = hptr->kind[i].head;
			while (cptr) {
				XtFree(cptr->value);
				cnext = cptr->next;
				XtFree((char *)cptr);
				cptr = cnext;
			}
		}
		hnext = hptr->next;
		XtFree((char *)hptr);
		hptr = hnext;
	}

	XtFree((char *)hist);
}


/*
 * load_hosts_list - Display the current list of hosts in the Edit History
 *                   dialog.
 */
void
load_hosts_list()
{
	struct host_link* hptr;
	XmStringTable items;
	int indx;
	int i;
	
	/* Enter host names into scrolled list */
	items = (XmStringTable)XtMalloc(sizeof(XmString)*temp_history->host_count);
	indx = 0;
	hptr = temp_history->host_head;
	while (hptr) {
		items[indx++] = XmStringCreateSimple(hptr->host_name);
		hptr = hptr->next;
	}
	if (indx != temp_history->host_count)   /* Sanity check */
		fatal_error("Bug in load_hosts_list()");
	XtVaSetValues(
		hedit.w_hosts,
		XmNitems,		items,
		XmNitemCount,	temp_history->host_count,
		NULL
	);

	/* Select the first host (if there is one) */
	if (temp_history->host_count > 0)
		XmListSelectPos(hedit.w_hosts, 1, True);

	/* Adjust sensitivity of "Delete Host" button */
	if (temp_history->host_count > 0)
		XtSetSensitive(hedit.w_deleteHostButton, True);
	else
		XtSetSensitive(hedit.w_deleteHostButton, False);

	/* Free stuff */
	for (i=0; i<temp_history->host_count; i++)
		XmStringFree(items[i]);
	XtFree((char *)items);
}


/*
 * load_categories_list - Display the current list of nonempty categories
 *                        for "hostname" in the Edit History dialog.
 */
void
load_categories_list(host_name)
char *host_name;
{
	int *positions;
	int npositions;
	struct host_link* hptr;
	XmStringTable items;
	int i;
	int count;
	int indx;

	/* Search for host name */
	hptr = find_host_name(temp_history, host_name);

	/* How many categories have items? */
	count = 0;
	for (i=0; i<NUMKINDS; i++)
		if (hptr->kind[i].count > 0)
			count++;
	
	/* Enter category names into scrolled list */
	items = (XmStringTable)XtMalloc(sizeof(XmString)*count);
	indx = 0;
	for (i=0; i<NUMKINDS; i++)
		if (hptr->kind[i].count > 0)
			items[indx++] = XmStringCreateSimple(category_name[i]);
	XtVaSetValues(
		hedit.w_categories,
		XmNitems,		items,
		XmNitemCount,	count,
		NULL
	);

	/* Make sure that something is selected */
	if (!XmListGetSelectedPos(hedit.w_categories, &positions, &npositions))
		npositions = 0;
	if (npositions > 1)   /* Sanity check */
		fatal_error("Bug in load_categories_list()");
	else if (npositions == 1) {
		XmListSelectPos(hedit.w_categories, positions[0], True);
		XtFree((char *)positions);
	} else if (npositions == 0) {
		if (count > 0)
			XmListSelectPos(hedit.w_categories, 1, True);
		else {
			XmListDeleteAllItems(hedit.w_categories);
			XmListDeleteAllItems(hedit.w_items);
			XtSetSensitive(hedit.w_deleteItemButton, False);
		}
	}

	/* Free stuff */
	for (i=0; i<count; i++)
		XmStringFree(items[i]);
	XtFree((char *)items);
}


/*
 * load_items_list - Display the current list of items for "hostname" and
 *                   "category" in the Edit History dialog.
 */
void
load_items_list(host_name, category)
char *host_name;
char *category;
{
	struct host_link* hptr;
	struct item_link *cptr;
	XmStringTable items;
	int i;
	int indx;
	int cindx;

	/* Enter items into scrolled list */
	hptr = find_host_name(temp_history, host_name);
	cindx = category_indx(category);
	items = (XmStringTable)XtMalloc(sizeof(XmString)*hptr->kind[cindx].count);
	indx = 0;
	cptr = hptr->kind[cindx].head;
	while (cptr) {
		items[indx++] = XmStringCreateSimple(cptr->value);
		cptr = cptr->next;
	}
	XtVaSetValues(
		hedit.w_items,
		XmNitems,		items,
		XmNitemCount,	hptr->kind[cindx].count,
		NULL
	);

	/* Free stuff */
	for (i=0; i< hptr->kind[cindx].count; i++)
		XmStringFree(items[i]);
	XtFree((char *)items);

	/* Select first item (if there is one) */
	if (hptr->kind[cindx].count > 0)
		XmListSelectPos(hedit.w_items, 1, True);

	/* Adjust sensitivity of "Delete Item" button */
	if (hptr->kind[cindx].count > 0)
		XtSetSensitive(hedit.w_deleteItemButton, True);
	else
		XtSetSensitive(hedit.w_deleteItemButton, False);
}


/*
 * cb_hedit_hosts_single - This callback is invoked when an item in the
 *                         Hosts list is selected.
 */
void
cb_hedit_hosts_single(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	XmListCallbackStruct *cbs = (XmListCallbackStruct *)call_data;
	int *positions;
	int npositions;
	char *host_name;

	/* Don't let user deselect item */
	if (XmListGetSelectedPos(hedit.w_hosts, &positions, &npositions))
		XtFree((char *)positions);
	else
		XmListSelectPos(hedit.w_hosts, cbs->item_position, False);

	/* Display categories for selected host */
	host_name = get_selected_item(hedit.w_hosts);
	load_categories_list(host_name);
	XtFree(host_name);
}


/*
 * cb_hedit_categories_single - This callback is invoked when an item in
 *                              the Categories list is selected.
 */
void
cb_hedit_categories_single(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	XmListCallbackStruct *cbs = (XmListCallbackStruct *)call_data;
	char *host_name;
	char *category;
	int *positions;
	int npositions;

	/* Don't let user deselect item */
	if (XmListGetSelectedPos(hedit.w_categories, &positions, &npositions))
		XtFree((char *)positions);
	else
		XmListSelectPos(hedit.w_categories, cbs->item_position, False);

	/* Display items for selected host/category */
	category = get_selected_item(hedit.w_categories);
	host_name = get_selected_item(hedit.w_hosts);
	load_items_list(host_name, category);
	XtFree(host_name);
	XtFree(category);
}


/*
 * cb_hedit_items_single - This callback is invoked when an item in the
 *                         Items list is selected.
 */
void
cb_hedit_items_single(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
	XmListCallbackStruct *cbs = (XmListCallbackStruct *)call_data;
	int *positions;
	int npositions;

	/* Don't let user deselect item */
	if (XmListGetSelectedPos(hedit.w_items, &positions, &npositions))
		XtFree((char *)positions);
	else
		XmListSelectPos(hedit.w_items, cbs->item_position, False);
}


/*
 * category_indx - Return the index into category_name of the entry that
 *                 matches "name".  Fatal error if no match.
 */
category_indx(name)
char *name;
{
	int cindx;

	for (cindx=0; cindx<NUMKINDS; cindx++)
		if (!strcmp(name, category_name[cindx]))
			return cindx;
	
	fatal_error("Bug in category_indx()");

	return 0;   /* Necessary to keep gcc compiler happy */
}


/*
 * find_host_name - Return a pointer to the node in "hist" that contains
 *                  the host "name".  Its a fatal error if the host is not
 *                  found.
 */
struct host_link *
find_host_name(hist, name)
struct history_st *hist;
char *name;
{
	struct host_link *hptr = hist->host_head;

	while (hptr) {
		if (!strcmp(hptr->host_name, name))
			return hptr;
		hptr = hptr->next;
	}

	fatal_error("Bug in find_host_name()");
	return (struct host_link *)NULL;   /* Make Insight happy */
}


/*
 * get_selected_item - Return pointer to string of selected item in the
 *                     list "w_list".  Fatal error if there is not exactly
 *                     one selected item in the list.  Caller responsible
 *                     for freeing returned string with a call to XtFree().
 */
char *
get_selected_item(w_list)
Widget w_list;
{
	XmStringTable selected_items;
	int nselected_items;

	/* Get selected item */
	XtVaGetValues(
		w_list,
		XmNselectedItemCount,   &nselected_items,
		XmNselectedItems,       &selected_items,
		NULL
	);

	/* Sanity check */
	if (nselected_items != 1)
		fatal_error("Bug in get_selected_item()");

	return cstring_to_text(selected_items[0]);
}



syntax highlighted by Code2HTML, v. 0.9.1