/*
 *  $Id: Table.c,v 1.6 1992/06/13 00:09:37 marc Exp marc $
 */

/* Table widget .c file, subclass of (my new) List widget.  Subclassed
as specified in the R5 intrinsics doc, section 1.6.4 */

#include <X11/IntrinsicP.h>
#include <X11/StringDefs.h>

#include <X11/Xaw/TableP.h>

#include <ctype.h>

/* 
 * Default Translation table.
 */

static char defaultTranslations[] =  
  "<Btn1Down>:   SetLine()\n\
   <Btn1Up>:     Notify()";

/* Private Data */

#define offset(field) XtOffset(TableWidget, field)

static XtResource resources[] = {
   {XtNcolumnOrder, XtCColumnOrder, XtRColumnOrder, sizeof(XtColumnOrder),
       offset(table.order), XtRString, (caddr_t) "..."},
   {XtNrowSorting, XtCRowSorting, XtRColumnOrder, sizeof(XtColumnOrder),
       offset(table.sorting), XtRString, (caddr_t) ""},
};

/* need to define fct's below */

static void Notify(), Set(), Toggle(), Unset();
static void SetLine(), ToggleLine(), UnsetLine();

static XtActionsRec actions[] = {
      {"Notify",         Notify},
      {"Set",            Set},
      {"Toggle",         Toggle},
      {"Unset",          Unset},
      {"SetLine",        SetLine},
      {"ToggleLine",     ToggleLine},
      {"UnsetLine",      UnsetLine},
};

static void TableClassPartInit();
static void Initialize();
static void Destroy();
static Boolean SetValues();
static void PaintItemName();
static void Notify(), SetLine(), ToggleLine(), UnsetLine();

TableClassRec tableClassRec = {
  {
/* core_class fields */	
#define super_class		(&listClassRec)
    /* superclass	  	*/	(WidgetClass) super_class,
    /* class_name	  	*/	"Table",
    /* widget_size	  	*/	sizeof(TableRec),
    /* class_initialize   	*/	NULL,
    /* class_part_initialize	*/	TableClassPartInit,
    /* class_inited       	*/	FALSE,
    /* initialize	  	*/	Initialize,
    /* initialize_hook		*/	NULL,
    /* realize		  	*/	XtInheritRealize,
    /* actions		  	*/	actions,
    /* num_actions	  	*/	XtNumber(actions),
    /* resources	  	*/	resources,
    /* num_resources	  	*/	XtNumber(resources),
    /* xrm_class	  	*/	NULLQUARK,
    /* compress_motion	  	*/	TRUE,
    /* compress_exposure  	*/	FALSE,
    /* compress_enterleave	*/	TRUE,
    /* visible_interest	  	*/	FALSE,
    /* destroy		  	*/	Destroy,
    /* resize		  	*/	XtInheritResize,
    /* expose		  	*/	XtInheritExpose,
    /* set_values	  	*/	SetValues,
    /* set_values_hook		*/	NULL,
    /* set_values_almost	*/	XtInheritSetValuesAlmost,
    /* get_values_hook		*/	NULL,
    /* accept_focus	 	*/	NULL,
    /* version			*/	XtVersion,
    /* callback_private   	*/	NULL,
    /* tm_table		   	*/	defaultTranslations,
    /* query_geometry		*/      XtInheritQueryGeometry,
  },
/* Simple class fields initialization */
  {
    /* change_sensitive		*/	XtInheritChangeSensitive
  },
/* List class fields initialization */
  {
    /* paint_item_name */		PaintItemName,
    /* cvt_to_item */			ListInheritCvtToItem
  }
};

/* do I need this? */
WidgetClass tableWidgetClass = (WidgetClass) &tableClassRec;

#define CTI (((ListWidgetClass) tw->core.widget_class) \
	     ->list_class.cvt_to_item)

static char *my_strdup(char *str)
{
   char *dup;

   dup = (char *) XtMalloc(strlen(str)+1);
   strcpy(dup, str);
   return(dup);
}

/*ARGSUSED*/
static Boolean CvtStringToColumnOrder(Display *d,
				      XrmValue *args, Cardinal *num_args,
				      XrmValue *from, XrmValue *to, 
				      XtPointer *converter_data)
{
   static XtColumnOrder comem;
   XtColumnOrder *co;
   char *fstr = from->addr;
   int num = 1;
   int *cols;

   if (to->addr && to->size < sizeof(XtColumnOrder)) {
      to->size = sizeof(XtColumnOrder);
      return(False);
   }
   if (! to->addr) {
      to->size = sizeof(XtColumnOrder);
      to->addr = (XPointer) &comem;
   }

   co = (XtColumnOrder *) to->addr;

   while(*fstr) {
      if (isspace(*fstr)) num++;
      fstr++;
   }

   co->columns = cols = (int *) XtMalloc(num * sizeof(int));
   co->ncols = 0;
   co->cont = 0;

   fstr = from->addr;
   while(*fstr && isspace(*fstr)) fstr++;

   while(*fstr) {
      if (strncmp(fstr,"...",3) == 0) {
	 co->contofs = co->ncols?(co->columns[co->ncols-1] - co->ncols + 1):0;
	 co->cont = 1;
	 break;
      }
      *cols++ = atoi(fstr);
      co->ncols++;
      while(*fstr && !isspace(*fstr)) fstr++;
      while(*fstr && isspace(*fstr)) fstr++;
   }

   co->columns = (int *) XtRealloc((XtPointer) co->columns,
				   co->ncols*sizeof(int));

   *converter_data = (XtPointer) co->columns;

   return(True);
}
   
/*ARGSUSED*/
static void CvtTableDestructor(XtAppContext app, XrmValue *to,
			       XtPointer converter_data,
			       XrmValue *args, Cardinal *num_args)
{
   XtFree(converter_data);
}

static void TableClassPartInit()
{
   XtSetTypeConverter(XtRString, XtRColumnOrder, CvtStringToColumnOrder,
		      NULL, 0, XtCacheAll | XtCacheRefCount,
		      CvtTableDestructor);
}

/* The following three functions encapsulate all knowledge
of going to and from list item number and row/column number */

int FieldToCol(TablePart *tw, int field)
{
   if (field < tw->order.ncols) {
      return(tw->order.columns[field]);
   } else if (! tw->order.cont) {
      return(-1);
   } else {
      return(field+tw->order.contofs);
   }
}

char *FieldToStr(TablePart *tw, int line, int field)
{
   int temp = FieldToCol(tw,field);

   if (temp == -1) {
      return("");
   } else if (temp < tw->lines[line].line.nelem) {
      return(tw->lines[line].line.element[temp]);
   } else {
      return("");
   }
}

/* converts from x event to external(row,col); */

static Boolean CvtToCoord(Widget w, XEvent *event, int *row, int *col)
{
   TableWidget tw = (TableWidget) w;
   int item;

   if (CTI(w, event->xbutton.x, event->xbutton.y, &item) == OUT_OF_RANGE) {
      return(False);
   } else if (item >= tw->table.nlelems) {
      return(False);
   } else {
      if (row) *row = tw->table.tablerow[item];
      if (col) *col = tw->table.tablecol[item];
      return(True);
   }
}

static TablePart *sortingtw;

static int IntLineCompare(XawTableInt *a, XawTableInt *b)
{
   int n = 0;
   int c, ret;

   while(1) {
      if (n < sortingtw->sorting.ncols) {
	 c = sortingtw->sorting.columns[n];
      } else if (sortingtw->sorting.cont) {
	 c = n+sortingtw->sorting.contofs;
      } else {
	 return(0);
      }
      n++;

      if (a->line.nelem < c) {
	 if (b->line.nelem < c) {
	    return(0);
	 } else {
	    return(-1);
	 }
      } else if (b->line.nelem < c) {
	 return(1);
      } else {
	 ret = strcasecmp(a->line.element[c],b->line.element[c]);
	 if (ret) return(ret);
      }
   }
}

static void MakeList(Widget new, int longest, Boolean resize)
{
   int i,r,c;

   TablePart *tw = &(((TableWidget) new)->table);

   if (tw->order.cont) {
      tw->numcols = 0;
      for (i=0; i<tw->numlines; i++)
	 if (tw->numcols < tw->lines[i].line.nelem)
	    tw->numcols = tw->lines[i].line.nelem;
      tw->numcols -= tw->order.contofs;
      if (tw->numcols < 1) tw->numcols = 1;
   } else {
      tw->numcols = tw->order.ncols;
   }

   for (i=0; i<tw->nlelems; i++) XtFree(tw->listelems[i]);

   tw->nlelems = tw->numcols*tw->numlines;

   tw->listelems = (char **) XtRealloc((XtPointer) tw->listelems,
				       tw->nlelems*sizeof(char *));
   tw->tablerow = (int *) XtRealloc((XtPointer) tw->tablerow,
				    tw->nlelems*sizeof(int));
   tw->tablecol = (int *) XtRealloc((XtPointer) tw->tablecol,
				    tw->nlelems*sizeof(int));

   sortingtw = tw;
   qsort(tw->lines, tw->numlines, sizeof(XawTableInt), IntLineCompare);

   tw->intline = (int *) XtRealloc((XtPointer) tw->intline,
				   tw->numlines*sizeof(int));
   for (r=0; r<tw->numlines; r++)
      tw->intline[tw->lines[r].extline] = r;

   for (r=0; r<tw->numlines; r++)
      for (c=0; c<tw->numcols; c++) {
	 tw->listelems[r*tw->numcols+c] = my_strdup(FieldToStr(tw,r,c));
	 tw->tablerow[r*tw->numcols+c] = tw->lines[r].extline;
	 tw->tablecol[r*tw->numcols+c] = FieldToCol(tw,c);
      }

   XtVaSetValues(new,
		 XtNdefaultColumns, tw->numcols,
		 XtNforceColumns, True,
		 (char *) NULL);

   XawListChange(new, tw->nlelems?tw->listelems:NULL, tw->nlelems,
		 longest, resize);
}

/* copies lines to tw.  Modifies tw->lines, tw->numlines */
static void CopyTable(TablePart *tw, XawTableLine *lines, int nlines)
{
   int r,c;

   tw->lines = (XawTableInt *) XtRealloc((XtPointer) tw->lines,
					 nlines*sizeof(XawTableInt));

   for (r=0; r<nlines; r++) {
      if (r >= tw->numlines)
	 tw->lines[r].line.element = NULL;
      tw->lines[r].line.element =
	 (XawTableElement *) XtRealloc((XtPointer) tw->lines[r].line.element,
				       lines[r].nelem*
				       sizeof(XawTableElement));
      for (c=0; c<lines[r].nelem; c++) {
	 if (r < tw->numlines && c < tw->lines[r].line.nelem)
	    XtFree(tw->lines[r].line.element[c]);
	 tw->lines[r].line.element[c] = my_strdup(lines[r].element[c]);
      }
      tw->lines[r].line.nelem = lines[r].nelem;
      tw->lines[r].extline = r;
   }
   tw->numlines = nlines;
}

/*ARGSUSED*/
static void Initialize(Widget junk, Widget new)
{
   TablePart *tw = &(((TableWidget) new)->table);

   tw->lines = NULL;
   tw->intline = NULL;
   tw->numlines = 0;

   CopyTable(tw, NULL, 0);

   /* Normally, I would sort the table here, but there's only one row, so
      that would be kind of a waste */

   /* no hilite to start */

   tw->hilite.type = XawTableReturnNone;

   /* filler values for other fields */

   tw->numcols = 1;
   tw->listelems = NULL;
   tw->tablerow = NULL;
   tw->tablecol = NULL;
   tw->nlelems = 0;

   MakeList(new, 0, True);
}

static void Destroy(Widget w)
{
   int i;
   TableWidget tw = (TableWidget) w;

   for (i=0; i<tw->table.nlelems; i++) XtFree(tw->table.listelems[i]);

   XtFree((XtPointer) tw->table.listelems);
   XtFree((XtPointer) tw->table.tablerow);
   XtFree((XtPointer) tw->table.tablecol);
}

static Boolean SetValues(Widget current, Widget request, Widget new)
{
   TableWidget ct = (TableWidget) current;
   TableWidget rt = (TableWidget) request;
   TableWidget nt = (TableWidget) new;
   Boolean rebuild = False;

   if ((ct->table.order.ncols != rt->table.order.ncols) ||
       (ct->table.order.cont != rt->table.order.cont) ||
       (ct->table.order.contofs != rt->table.order.contofs) ||
       (memcmp(ct->table.order.columns,rt->table.order.columns,
	       rt->table.order.ncols*sizeof(int)))) {
      nt->table.order.ncols = rt->table.order.ncols;
      nt->table.order.cont = rt->table.order.cont;
      nt->table.order.columns =
	 (int *) XtRealloc((XtPointer) nt->table.order.columns,
			   rt->table.order.ncols*sizeof(int));
      memcpy(nt->table.order.columns, rt->table.order.columns,
	     rt->table.order.ncols*sizeof(int));
      rebuild = True;
   }

   if ((ct->table.sorting.ncols != rt->table.sorting.ncols) ||
       (ct->table.sorting.cont != rt->table.sorting.cont) ||
       (ct->table.sorting.contofs != rt->table.sorting.contofs) ||
       (memcmp(ct->table.sorting.columns,rt->table.sorting.columns,
	       rt->table.sorting.ncols*sizeof(int)))) {
      nt->table.sorting.ncols = rt->table.sorting.ncols;
      nt->table.sorting.cont = rt->table.sorting.cont;
      nt->table.sorting.columns =
	 (int *) XtRealloc((XtPointer) nt->table.sorting.columns,
			   rt->table.sorting.ncols*sizeof(int));
      memcpy(nt->table.sorting.columns, rt->table.sorting.columns,
	     rt->table.sorting.ncols*sizeof(int));
      rebuild = True;
   }

   /* crock: reset core.window to make the toolkit think the list is
      unrealized, so that it won't repaint here */

   if (rebuild == True) {
      Window win;

      win = ct->core.window;
      ct->core.window = None;

      MakeList(new, 0, True);

      ct->core.window = win;

      return(True);
   } else {
      return(False);
   }
}

static void PaintItemName(Widget w, int item)
{
   TableWidget tw = (TableWidget) w;

   if (!XtIsRealized(w)) return; /* Just in case... */
   
   /* set up state to fool superclass's paint_item_name to do what I want */
   /* to highlight item:   is_highlighted = item, highlight = item
      to unhighlight item: is_highlighted = item, highlight = NO_HIGHLIGHT */

   tw->list.is_highlighted = item;
   tw->list.highlight = NO_HIGHLIGHT;
   tw->list.paint_full_width = True;

   switch (tw->table.hilite.type) {
    case XawTableReturnLine:
      if (tw->table.tablerow[item] == tw->table.hilite.row)
	 tw->list.highlight = item;
      break;
    case XawTableReturnElement:
      if ((tw->table.tablerow[item] == tw->table.hilite.row) &&
	  (tw->table.tablecol[item] == tw->table.hilite.col) &&
	  (tw->table.listelems[item][0])) {
	 tw->list.highlight = item;
	 tw->list.paint_full_width = False;
      }
      break;
   }

   (listClassRec.list_class.paint_item_name)(w, item);
}

/** Advertised functions **/

void XawTableChange
   (
#if NeedFunctionPrototypes
    Widget		w,
    XawTableLine *	lines,
    int			nlines,
    int			longest,
#if NeedWidePrototypes
    /* Boolean */ int	resize
#else
    Boolean		resize
#endif
#endif
    )
{
   TablePart *tw = &(((TableWidget) w)->table);

   CopyTable(tw, lines, nlines);

   tw->hilite.type = XawTableReturnNone;

   MakeList(w, longest, resize);
}

extern void XawTableUnhighlight
   (
#if NeedFunctionPrototypes
    Widget		w
#endif
    )
{
   TableWidget tw = (TableWidget) w;
   XawTableReturnStruct trs;
   int c;

   if (tw->table.hilite.type == XawTableReturnNone) return;

   trs = tw->table.hilite;
   tw->table.hilite.type = XawTableReturnNone;

   for (c=0; c<tw->table.numcols; c++) {
      if (trs.type == XawTableReturnLine) {
	 /* paint all the items in the row */
	 PaintItemName(w, tw->table.intline[trs.row]*tw->table.numcols+c);
      } else if (FieldToCol(&(tw->table),c) == trs.col) {
	 /* only paint the items which match .col */
	 PaintItemName(w, tw->table.intline[trs.row]*tw->table.numcols+c);
      }
   }
}

extern void XawTableHighlight
   (
#if NeedFunctionPrototypes
    Widget		w,
    XawTableReturnStruct *frob
#endif
    )
{
   TableWidget tw = (TableWidget) w;
   int c;

   if ((tw->table.hilite.type != frob->type) ||
       (((tw->table.hilite.type != XawTableReturnNone)) &&
	((tw->table.hilite.type != XawTableReturnLine) ||
	 (tw->table.hilite.row != frob->row)) &&
	((tw->table.hilite.type != XawTableReturnElement) ||
	 (tw->table.hilite.row != frob->row) ||
	 (tw->table.hilite.col != frob->col)))) {

      XawTableUnhighlight(w);

      /* don't highlight "empty" cells */

      if ((frob->type == XawTableReturnElement) &&
	  (frob->col >= 
	   tw->table.lines[tw->table.intline[frob->row]].line.nelem))
	 return;

      tw->table.hilite = *frob;

      if (tw->table.hilite.type == XawTableReturnNone) return;

      for (c=0; c<tw->table.numcols; c++) {
	 if (tw->table.hilite.type == XawTableReturnLine) {
	    /* paint all the items in the row */
	    PaintItemName(w, tw->table.intline[tw->table.hilite.row]*
			  tw->table.numcols+c);
	 } else if (FieldToCol(&(tw->table), c) == tw->table.hilite.col) {
	    /* only paint the items which match .col */
	    PaintItemName(w, tw->table.intline[tw->table.hilite.row]*
			  tw->table.numcols+c);
	 }
      }
   }
}

static void fill_in_trs(TableWidget tw, XawTableReturnStruct *ret)
{
   if (ret->type == XawTableReturnLine) {
      ret->line = &tw->table.lines[tw->table.intline[ret->row]].line;
   } else if (ret->type == XawTableReturnElement) {
      ret->line = &tw->table.lines[tw->table.intline[ret->col]].line;
      ret->element = ret->line->element + ret->col;
   }
}

extern XawTableReturnStruct *XawTableShowCurrent
   (
#if NeedFunctionPrototypes
    Widget		w
#endif
    )
{
   TableWidget tw = (TableWidget) w;

   static XawTableReturnStruct ret;

   ret = tw->table.hilite;

   fill_in_trs(tw, &ret);
   
   return(&ret);
}

Boolean XawTableGetClicked
   (
#if NeedFunctionPrototypes
    Widget		w,
    XEvent *		ev,
    XawTableReturnType	type,
    XawTableReturnStruct *ret
#endif
    )
{
   TableWidget tw = (TableWidget) w;

   if (CvtToCoord(w, ev, &(ret->row), &(ret->col))) {
      ret->type = type;
      fill_in_trs(tw, ret);
      return(True);
   } else {
      ret->type = XawTableReturnNone;
      return(False);
   }
}   

/*ARGSUSED*/
static void Set(Widget w, XEvent *event, String params, Cardinal num_params)
{
   TableWidget tw = (TableWidget) w;
   XawTableReturnStruct trs;

   if (CvtToCoord(w, event, &trs.row, &trs.col)) {
      trs.type = XawTableReturnElement;
      XawTableHighlight(w, &trs);
   } else {
      XawTableUnhighlight(w);
   }
}

/*ARGSUSED*/
static void SetLine(Widget w, XEvent *event, String params,
		    Cardinal num_params)
{
   TableWidget tw = (TableWidget) w;
   XawTableReturnStruct trs;

   if (CvtToCoord(w, event, &trs.row, NULL)) {
      trs.type = XawTableReturnLine;
      XawTableHighlight(w, &trs);
   } else {
      XawTableUnhighlight(w);
   }
}

/*ARGSUSED*/
static void Unset(Widget w, XEvent *event, String params, Cardinal num_params)
{
   XawTableUnhighlight(w);
}

/*ARGSUSED*/
static void UnsetLine(Widget w, XEvent *event, String params,
		      Cardinal num_params)
{
   XawTableUnhighlight(w);
}

/*ARGSUSED*/
static void Toggle(Widget w, XEvent *event, String params, Cardinal num_params)
{
   TableWidget tw = (TableWidget) w;
   int row, col;
   XawTableReturnStruct trs;

   if (CvtToCoord(w, event, &row, &col) &&
       (tw->table.hilite.type != XawTableReturnElement ||
	tw->table.hilite.row != row ||
	tw->table.hilite.col != col)) {
      trs.type = XawTableReturnElement;
      trs.row = row;
      trs.col = col;
      XawTableHighlight(w, &trs);
   } else {
      XawTableUnhighlight(w);
   }
}

/*ARGSUSED*/
static void ToggleLine(Widget w, XEvent *event, String params,
		       Cardinal num_params)
{
   TableWidget tw = (TableWidget) w;
   int row;
   XawTableReturnStruct trs;

   if (CvtToCoord(w, event, &row, NULL) &&
       (tw->table.hilite.type != XawTableReturnLine ||
	tw->table.hilite.row != row)) {
      trs.type = XawTableReturnLine;
      trs.row = row;
      XawTableHighlight(w, &trs);
   } else {
      XawTableUnhighlight(w);
   }
}

/*ARGSUSED*/
static void Notify(Widget w, XEvent *event, String params,
		   Cardinal num_params)
{
   XtCallCallbacks(w, XtNcallback, XawTableShowCurrent(w));
}
