/* $Header: /afs/athena.mit.edu/astaff/project/atdev/src/plotter/RCS/TextPlot.c,v 3.2 94/09/23 12:14:59 dot Exp $ */

/*******************************************************************
  Copyright (C) 1990 by the Massachusetts Institute of Technology

   Export of this software from the United States of America is assumed
   to require a specific license from the United States Government.
   It is the responsibility of any person or organization contemplating
   export to obtain such a license before exporting.

WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
distribute this software and its documentation for any purpose and
without fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation, and that
the name of M.I.T. not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.  M.I.T. makes no representations about the suitability of
this software for any purpose.  It is provided "as is" without express
or implied warranty.

***************************************************************** */

#include <stdio.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>

#ifdef _AtDevelopment_
#include "Scale.h"    
#include "TextPlotP.h"
#include "AtConverters.h"
#else
#include <At/Scale.h>
#include <At/TextPlotP.h>
#include <At/AtConverters.h>
#endif  

static double zero = 0.0;

#define offset(field) XtOffset(AtTextPlotWidget, field)
static XtResource resources[] = {
  {XtNlabel, XtCLabel, XtRString, sizeof(String),
     offset(textplot.label), XtRString, NULL},
  {XtNfontFamily, XtCFontFamily, XtRString, sizeof(String),
     offset(textplot.fontFamily), XtRString, "new century schoolbook"},
  {XtNfontSize, XtCFontSize, XtRFontSize, sizeof(int),
     offset(textplot.fontSize), XtRImmediate, (caddr_t)AtFontNORMAL},
  {XtNjustify, XtCJustify, XtRAtJustify, sizeof(int),
     offset(textplot.justify), XtRImmediate, (caddr_t)AtTextJUSTIFY_CENTER},
  {XtNx, XtCPosition, XtRInt, sizeof(int),
     offset(textplot.x), XtRImmediate, (caddr_t)0},
  {XtNy, XtCPosition, XtRInt, sizeof(int),
     offset(textplot.y), XtRImmediate, (caddr_t)0},
  {XtNfloatingPosition, XtCFloatingPosition, XtRBoolean, sizeof(Boolean),
     offset(textplot.floatingPosition), XtRImmediate, (caddr_t)True},
  {XtNfloatingX, XtCFloatingX, XtRDouble, sizeof(double),
     offset(textplot.floatingX), XtRDouble, (caddr_t)&zero},
  {XtNfloatingY, XtCFloatingY, XtRDouble, sizeof(double),
     offset(textplot.floatingY), XtRDouble, (caddr_t)&zero},
};
  
#undef offset

static void ClassInitialize();
static void Initialize(AtTextPlotWidget, AtTextPlotWidget);
static void Destroy(AtTextPlotWidget);
static Boolean SetValues(AtTextPlotWidget, AtTextPlotWidget, AtTextPlotWidget);
static void Draw(Display *, Window, AtPlotWidget, AtScale *, AtScale *, Region);
static void Resize(AtPlotWidget, AtScale *, AtScale *);
static void Rescale(AtPlotWidget, AtScale *, AtScale *);
static void DrawPS(FILE *, AtPlotWidget, AtScale * , AtScale *);
static Boolean CheckHit(AtPlotWidget, int, int);

AtTextPlotClassRec atTextPlotClassRec = {
{ /* core part */
    /* superclass         */    (WidgetClass)&atPlotClassRec,
    /* class_name         */    "AtTextPlot",
    /* widget_size        */    sizeof(AtTextPlotRec),
    /* class_initialize   */    ClassInitialize,
    /* class_part_initialize*/  NULL,
    /* class_inited       */    FALSE,
    /* initialize         */    (XtInitProc) Initialize,
    /* initialize_hook    */    NULL,
    /* pad                */    NULL,
    /* pad                */    NULL,
    /* pad                */    0,
    /* resources          */    resources,
    /* num_resources      */    XtNumber(resources),
    /* xrm_class          */    NULLQUARK,
    /* pad                */    FALSE,
    /* pad                */    FALSE,
    /* pad                */    FALSE,
    /* pad                */    FALSE,
    /* destroy            */    (XtWidgetProc)Destroy,
    /* pad                */    NULL,
    /* pad                */    NULL,
    /* set_values         */    (XtSetValuesFunc) SetValues,
    /* set_values_hook    */    NULL,
    /* pad                */    NULL,
    /* get_values_hook    */    NULL,
    /* pad                */    NULL,
    /* version            */    XtVersion,
    /* callback_offsets   */    NULL,
    /* pad                */    NULL,
    /* pad                */    NULL,
    /* pad                */    NULL,
    /* extension            */  NULL
},
/* AtPlotClassPart initialization */
{
    /* draw()       */   Draw,
    /* drawIcon()   */   NULL,
    /* resize()     */   Resize,
    /* rescale()    */   Rescale,
    /* drawPS()     */	 DrawPS,
    /* drawIconPS() */   NULL,
    /* checkhit()   */   CheckHit,
}
};

WidgetClass atTextPlotWidgetClass = (WidgetClass) &atTextPlotClassRec;

static void ClassInitialize()
{
    AtRegisterFontSizeConverter();
    AtRegisterJustifyConverter();
    AtRegisterDoubleConverter();
}

static void Initialize(AtTextPlotWidget request, AtTextPlotWidget new)
{
    if (new->textplot.label == NULL)
	new->textplot.label = XtNewString("");
    else
	new->textplot.label = XtNewString(new->textplot.label);

    new->textplot.fontFamily = XtNewString(new->textplot.fontFamily);

    new->textplot.ff = AtFontFamilyGet(XtDisplay(XtParent((Widget)new)),
				       new->textplot.fontFamily);
    new->textplot.labelText = AtTextCreate(new->textplot.label,
					   new->textplot.ff,
					   new->textplot.fontSize);
    new->textplot.xpercent = -1.0;
    new->textplot.ypercent = -1.0;
    new->textplot.valid = False;
}

static void Destroy(AtTextPlotWidget w)
{
    AtTextDestroy(w->textplot.labelText);
    AtFontFamilyRelease(w->textplot.ff);
    XtFree(w->textplot.label);
    XtFree(w->textplot.fontFamily);
}

static Boolean SetValues(AtTextPlotWidget current,
			 AtTextPlotWidget request,
			 AtTextPlotWidget new)
{
    Boolean string_changed = False;
    Boolean family_changed = False;
    Boolean redisplay = False;
#define Changed(field) (new->textplot.field != current->textplot.field)

    if (strcasecmp (new->textplot.fontFamily, current->textplot.fontFamily)) {
	XtFree(current->textplot.fontFamily);
	AtFontFamilyRelease(new->textplot.ff);
	new->textplot.fontFamily = XtNewString(new->textplot.fontFamily);
	new->textplot.ff = AtFontFamilyGet (XtDisplay(XtParent((Widget)new)),
					    new->textplot.fontFamily);
	family_changed = True;
	redisplay = True;
    }

    if (strcmp (new->textplot.label, current->textplot.label)) {
	XtFree(current->textplot.label);
	AtTextDestroy (new->textplot.labelText);
	new->textplot.label = XtNewString(new->textplot.label);
	new->textplot.labelText = AtTextCreate(new->textplot.label,
					       new->textplot.ff,
					       new->textplot.fontSize);
	string_changed = True;
	redisplay = True;
    }
    else
	 new->textplot.label = current->textplot.label;

    if (!string_changed && (family_changed || Changed(fontSize))) {
	AtTextReformat(new->textplot.labelText,
		       new->textplot.ff,
		       new->textplot.fontSize);
	redisplay = True;
    }

    if (Changed(x) || Changed(y) || Changed(floatingPosition) ||
	Changed(floatingX) || Changed(floatingY)) {
	new->textplot.valid = False;
	redisplay = True;
    }
    
    /*
     * if the plot needs a redisplay, and if the plot is not a subclass
     * of us, ask to be redisplayed.  If the plot is a subclass,
     * then the subclass will handle redisplay.
     */
    if (redisplay && (new->object.widget_class == atTextPlotWidgetClass)) {
	Arg a;
	XtSetArg(a, XtNneedsRedraw, True);
	XtSetValues(new, &a, 1);        /* set a constraint resource */
    }
    
    return False;
#undef Changed    
}


static void Resize(AtPlotWidget plot, AtScale *xscale , AtScale *yscale)
{
    AtTextPlotWidget p = (AtTextPlotWidget) plot;
    int min, max;

    /*
     * a textplot is positioned either at a pair of real coordinates,
     * or at a pair of pixel coordinates.  These pixels are converted
     * into  percentages of the total width and height of the window,
     * and when the window grows or shrinks, the textplot location is
     * proportionally adjusted.
     */
    
    if (p->textplot.floatingPosition) {
	p->textplot.x = AtScaleUserToPixel(xscale, p->textplot.floatingX);
	p->textplot.y = AtScaleUserToPixel(yscale, p->textplot.floatingY);
    }
    else {
	min = AtScaleGetLowPix(xscale);
	max = AtScaleGetHighPix(xscale);
	if (p->textplot.valid)
	    p->textplot.x = min + (int)((max - min) * p->textplot.xpercent);
	else
	    p->textplot.xpercent = (p->textplot.x-min)/(double)(max-min);
	
	min = AtScaleGetHighPix(yscale);
	max = AtScaleGetLowPix(yscale);
	if (p->textplot.valid)
	    p->textplot.y = min + (int)((max - min) * p->textplot.ypercent);
	else
	    p->textplot.ypercent = (p->textplot.y-min)/(double)(max-min);
    }

    p->textplot.ypos = p->textplot.y;
    switch (p->textplot.justify) {
    case AtTextJUSTIFY_LEFT:
	p->textplot.xpos= p->textplot.x;
	break;
    case AtTextJUSTIFY_CENTER:
	p->textplot.xpos = p->textplot.x - AtTextWidth(p->textplot.labelText)/2;
	break;
    case AtTextJUSTIFY_RIGHT:
	p->textplot.xpos = p->textplot.x - AtTextWidth(p->textplot.labelText);
	break;
    }

    p->textplot.valid = True;
}

static void Rescale(AtPlotWidget plot, AtScale *xscale , AtScale *yscale)
{
    AtTextPlotWidget p = (AtTextPlotWidget) plot;
    
    if (p->textplot.floatingPosition) {
	Resize(plot, xscale, yscale);
    }
}


static void Draw(Display *dpy, Window win, AtPlotWidget plot,
		 AtScale *xscale, AtScale *yscale, Region region)
{
    AtTextPlotWidget p = (AtTextPlotWidget) plot;

    if (p->textplot.valid == False) Resize(plot, xscale, yscale);

    AtTextDraw(dpy, win, p->plot.gc, p->textplot.labelText,
	       p->textplot.xpos, p->textplot.ypos);
}


static void DrawPS(FILE *f, AtPlotWidget plot, AtScale *xs, AtScale *ys)
{
    AtTextPlotWidget p = (AtTextPlotWidget) plot;
    int x, y;
    int xmin, xmax, ymin, ymax;

    if (p->textplot.floatingPosition) {
	x = AtScaleUserToPixel(xs, p->textplot.floatingX);
	y = AtScaleUserToPixel(ys, p->textplot.floatingY);
    }
    else {
	xmin = AtScaleGetLowPix(xs);
	xmax = AtScaleGetHighPix(xs);
	ymin = AtScaleGetLowPix(ys);
	ymax = AtScaleGetHighPix(ys);
	x = xmin + (xmax - xmin) * p->textplot.xpercent;
	y = ymin + (ymax - ymin) * p->textplot.ypercent;
    }

    switch (p->textplot.justify) {
    case AtTextJUSTIFY_CENTER:
        x -= AtTextPSWidth(p->textplot.labelText)/2;
	break;
    case AtTextJUSTIFY_RIGHT:
	x -= - AtTextPSWidth(p->textplot.labelText);
	break;
    }

    AtTextPSDraw(f, p->textplot.labelText, x, y);
}


static Boolean CheckHit(AtPlotWidget plot, int x, int y)
{
    AtTextPlotWidget p = (AtTextPlotWidget) plot;

    if (p->textplot.valid == False) return False;

    if ((x > p->textplot.xpos) &&
	(x < p->textplot.xpos + AtTextWidth(p->textplot.labelText)) &&
	(y > p->textplot.ypos - AtTextAscent(p->textplot.labelText)) &&
	(y < p->textplot.ypos + AtTextDescent(p->textplot.labelText)))
	return True;
    else
	return False;
}
