/*
 * $XConsortium: Clock.c,v 1.28 94/04/17 20:37:56 rws Exp $
 *
Copyright (c) 1989  X Consortium

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
 */

/*
 * Clock.c
 *
 * a NeWS clone clock
 */

#include <X11/IntrinsicP.h>
#include <X11/StringDefs.h>
#include <X11/Xmu/Converters.h>
#include "ClockP.h"
#include <X11/Xos.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <X11/extensions/shape.h>

#ifdef X_NOT_STDC_ENV
extern struct tm *localtime();
#define Time_t long
extern Time_t time();
#else
#include <time.h>
#define Time_t time_t
#endif

#ifndef PI	/* may be found in <math.h> */
# define PI (3.14159265358979323846)
#endif

#define POINTS_PER_SEGMENT 5

#define offset(field) XtOffsetOf(ClockRec, clock.field)
#define goffset(field) XtOffsetOf(WidgetRec, core.field)

#define min(a,b) (((a) < (b)) ? (a) : (b))

static XtResource resources[] = {
    {XtNwidth, XtCWidth, XtRDimension, sizeof(Dimension),
        goffset(width), XtRImmediate, (XtPointer) 120},
    {XtNheight, XtCHeight, XtRDimension, sizeof(Dimension),
	goffset(height), XtRImmediate, (XtPointer) 120},
    {XtNcurve, XtCForeground, XtRPixel, sizeof (Pixel),
	offset(curve), XtRString, XtDefaultForeground},
    {XtNbackingStore, XtCBackingStore, XtRBackingStore, sizeof (int),
    	offset (backing_store), XtRString, "default"},
    {XtNborderSize, XtCBorderSize, XtRFloat, sizeof (float),
	offset (border_size), XtRString, "0.1"},
    {XtNcurveSize, XtCBorderSize, XtRFloat, sizeof (float),
	offset (curve_size), XtRString, "0.1"},
    {XtNshapeWindow, XtCShapeWindow, XtRBoolean, sizeof (Boolean),
	offset (shape_window), XtRImmediate, (XtPointer) True},
    {XtNtransparent, XtCTransparent, XtRBoolean, sizeof (Boolean),
	offset (transparent), XtRImmediate, (XtPointer) False},
};

#undef offset
#undef goffset

static void 	new_time();

static void Initialize(), Realize(), Destroy(), Redisplay(), Resize();
void paint_curve (ClockWidget w, Drawable d, GC gc);

#define BORDER_SIZE(w)		((w)->clock.border_size)
#define WINDOW_WIDTH(w)		(2.0 - BORDER_SIZE(w)*2)
#define WINDOW_HEIGHT(w)	(2.0 - BORDER_SIZE(w)*2)
#define CURVE_SIZE(w)		((w)->clock.curve_size)
#define SECOND_LENGTH(w)	(1.0 - BORDER_SIZE(w) - CURVE_SIZE(w))
#define MINUTE_LENGTH(w)	(SECOND_LENGTH(w) * 0.9)
#define HOUR_LENGTH(w)		(SECOND_LENGTH(w) * 0.6)

static void ClassInitialize();

ClockClassRec clockClassRec = {
    { /* core fields */
    /* superclass		*/	&widgetClassRec,
    /* class_name		*/	"Clock",
    /* size			*/	sizeof(ClockRec),
    /* class_initialize		*/	ClassInitialize,
    /* class_part_initialize	*/	NULL,
    /* class_inited		*/	FALSE,
    /* initialize		*/	Initialize,
    /* initialize_hook		*/	NULL,
    /* realize			*/	Realize,
    /* actions			*/	NULL,
    /* num_actions		*/	0,
    /* resources		*/	resources,
    /* num_resources		*/	XtNumber(resources),
    /* xrm_class		*/	NULLQUARK,
    /* compress_motion		*/	TRUE,
    /* compress_exposure	*/	TRUE,
    /* compress_enterleave	*/	TRUE,
    /* visible_interest		*/	FALSE,
    /* destroy			*/	Destroy,
    /* resize			*/	Resize,
    /* expose			*/	Redisplay,
    /* set_values		*/	NULL,
    /* set_values_hook		*/	NULL,
    /* set_values_almost	*/	NULL,
    /* get_values_hook		*/	NULL,
    /* accept_focus		*/	NULL,
    /* version			*/	XtVersion,
    /* callback_private		*/	NULL,
    /* tm_table			*/	NULL,
    /* query_geometry		*/	XtInheritQueryGeometry,
    }
};

static void ClassInitialize()
{
    XtAddConverter( XtRString, XtRBackingStore, XmuCvtStringToBackingStore,
		    NULL, 0 );
}

WidgetClass clockWidgetClass = (WidgetClass) &clockClassRec;

/* ARGSUSED */
static void Initialize (greq, gnew, args, num_args)
    Widget greq, gnew;
    ArgList args;
    Cardinal *num_args;
{
    ClockWidget w = (ClockWidget)gnew;
    int shape_event_base, shape_error_base;

    w->clock.curveGC = 0;
    w->clock.eraseGC = 0;

    /* wait for Realize to add the timeout */
    w->clock.interval_id = 0;

    if (w->clock.shape_window && !XShapeQueryExtension (XtDisplay (w), 
							&shape_event_base, 
							&shape_error_base))
    	w->clock.shape_window = False;
    w->clock.shape_mask = None;
    w->clock.shapeGC = 0;
    w->clock.shape_width = 0;
    w->clock.shape_height = 0;
    w->clock.pm = None;
    w->clock.pm_width = 0;
    w->clock.pm_height = 0;
}

static void Resize (widget)
    Widget	widget;
{
    ClockWidget	w = (ClockWidget) widget;
    XGCValues	xgcv;
    Widget	parent;
    XWindowChanges	xwc;
    int		face_width, face_height;
    int		x, y;
    Pixmap	shape_mask;

    if (!XtIsRealized((Widget) w))
	return;

    /*
     * compute desired border size
     */

    SetTransform (&w->clock.maskt,
		  0, w->core.width,
		  w->core.height, 0,
		  -1.0, 1.0,
 		  -1.0, 1.0);

    face_width = abs (Xwidth (BORDER_SIZE(w), BORDER_SIZE(w), &w->clock.maskt));
    face_height = abs (Xheight (BORDER_SIZE(w), BORDER_SIZE(w), &w->clock.maskt));

    /*
     *  shape the windows and borders
     */

    if (w->clock.shape_window) {

	SetTransform (&w->clock.t,
		      face_width, w->core.width - face_width,
		      w->core.height - face_height, face_height,
		      -WINDOW_WIDTH(w)/2, WINDOW_WIDTH(w)/2,
		      -WINDOW_HEIGHT(w)/2, WINDOW_HEIGHT(w)/2);
    
	/*
	 * allocate a pixmap to draw shapes in
	 */

	if (w->clock.shape_mask &&
	    (w->clock.shape_width != w->core.width ||
	     w->clock.shape_height != w->core.height))
	{
	    XFreePixmap (XtDisplay (w), w->clock.shape_mask);
	    w->clock.shape_mask = None;
	}
	
	if (!w->clock.shape_mask)
	{
	    w->clock.shape_mask = XCreatePixmap (XtDisplay (w), XtWindow (w),
				    w->core.width, w->core.height, 1);
	    w->clock.shape_width = w->core.width;
	    w->clock.shape_height = w->core.height;
	}
	shape_mask = w->clock.shape_mask;

	xgcv.line_width = min (abs(Xwidth (CURVE_SIZE (w), CURVE_SIZE (w), &w->clock.t)),
			       abs(Xheight (CURVE_SIZE (w), CURVE_SIZE (w), &w->clock.t)));
    	if (!w->clock.shapeGC)
    	{
    	    xgcv.cap_style = CapRound;
            xgcv.join_style = JoinRound;
            w->clock.shapeGC = XCreateGC (XtDisplay (w), shape_mask, GCCapStyle |
            				  GCJoinStyle | GCLineWidth, &xgcv);
        }
        else
            XChangeGC (XtDisplay (w), w->clock.shapeGC, GCLineWidth, &xgcv);


	/* erase the pixmap */
    	XSetForeground (XtDisplay (w), w->clock.shapeGC, 0);
    	XFillRectangle (XtDisplay (w), shape_mask, w->clock.shapeGC,
			0, 0, w->core.width, w->core.height);
    	XSetForeground (XtDisplay (w), w->clock.shapeGC, 1);

	/*
	 * draw the bounding shape.  Doing this first
	 * eliminates extra exposure events.
	 */

	if (w->clock.border_size > 0.0 || !w->clock.transparent)
	{
	    TFillArc (XtDisplay (w), shape_mask,
			    w->clock.shapeGC, &w->clock.maskt,
			    -1.0, -1.0,
			    2.0, 2.0,
			    0, 360 * 64);
	}

	if (w->clock.transparent)
	{
	    if (w->clock.border_size > 0.0)
	    {
	    	XSetForeground (XtDisplay (w), w->clock.shapeGC, 0);
	    	TFillArc (XtDisplay (w), shape_mask,
			    	w->clock.shapeGC, &w->clock.t,
			    	-WINDOW_WIDTH(w)/2, -WINDOW_HEIGHT(w)/2,
			    	WINDOW_WIDTH(w), WINDOW_HEIGHT(w),
			    	0, 360 * 64);
	    	XSetForeground (XtDisplay (w), w->clock.shapeGC, 1);
	    }
	    paint_curve (w, shape_mask, w->clock.shapeGC);
	}
	/*
	 * Find the highest enclosing widget and shape it
	 */

	x = 0;
	y = 0;
	for (parent = (Widget) w; XtParent (parent); parent = XtParent (parent))
	{
	    x = x + parent->core.x + parent->core.border_width;
	    y = y + parent->core.y + parent->core.border_width;
	}

	XShapeCombineMask (XtDisplay (parent), XtWindow (parent), ShapeBounding,
			    x, y, shape_mask, ShapeSet);

	/* erase the pixmap */
    	XSetForeground (XtDisplay (w), w->clock.shapeGC, 0);
    	XFillRectangle (XtDisplay (w), shape_mask, w->clock.shapeGC,
			0, 0, w->core.width, w->core.height);
    	XSetForeground (XtDisplay (w), w->clock.shapeGC, 1);

	/*
	 * draw the clip shape
	 */

	if (w->clock.transparent)
	{
	    paint_curve (w, shape_mask, w->clock.shapeGC);
	}
	else
	{
	    TFillArc (XtDisplay (w), shape_mask,
		      w->clock.shapeGC, &w->clock.t,
		      -WINDOW_WIDTH(w)/2, -WINDOW_HEIGHT(w)/2,
		      WINDOW_WIDTH(w), WINDOW_HEIGHT(w),
		      0, 360 * 64);
	}

	XShapeCombineMask (XtDisplay (w), XtWindow (w), ShapeClip, 
		    0, 0, shape_mask, ShapeSet);

    } else
    {
    	/*
     	 * reconfigure the widget to split the availible
     	 * space between the window and the border
     	 */

     	if (face_width > face_height)
	    xwc.border_width = face_height;
    	else
	    xwc.border_width = face_width;
    	xwc.width = w->core.width - xwc.border_width * 2;
    	xwc.height = w->core.height - xwc.border_width * 2;
    	XConfigureWindow (XtDisplay (w), XtWindow (w),
			    CWWidth|CWHeight|CWBorderWidth,
			    &xwc);
    
    	SetTransform (&w->clock.t,
	    0, xwc.width,
	    xwc.height, 0,
	    -WINDOW_WIDTH(w)/2, WINDOW_WIDTH(w)/2,
	    -WINDOW_HEIGHT(w)/2, WINDOW_HEIGHT(w)/2);
    }
    xgcv.line_width = min (abs(Xwidth (CURVE_SIZE (w), CURVE_SIZE (w), &w->clock.t)),
			   abs(Xheight (CURVE_SIZE (w), CURVE_SIZE (w), &w->clock.t)));
    XChangeGC (XtDisplay (w), w->clock.curveGC, GCLineWidth, &xgcv);
    XChangeGC (XtDisplay (w), w->clock.eraseGC, GCLineWidth, &xgcv);
}
 
static void Realize (gw, valueMask, attrs)
     Widget gw;
     XtValueMask *valueMask;
     XSetWindowAttributes *attrs;
{
    ClockWidget	w = (ClockWidget)gw;
    XGCValues values;

    if (w->clock.backing_store != Always + WhenMapped + NotUseful) {
     	attrs->backing_store = w->clock.backing_store;
	*valueMask |= CWBackingStore;
    }
    if (w->clock.transparent)
    {
	attrs->background_pixel = w->clock.curve;
	*valueMask |= CWBackPixel;
	*valueMask &= ~CWBackPixmap;
    }
    XtCreateWindow( gw, (unsigned)InputOutput, (Visual *)CopyFromParent,
		     *valueMask, attrs );
		     
    values.foreground = w->clock.curve;
    values.cap_style = CapRound;
    values.join_style = JoinRound;
    w->clock.curveGC = XCreateGC (XtDisplay (w), XtWindow (w),
    				  GCForeground | GCCapStyle | GCJoinStyle, &values);
    values.foreground = w->core.background_pixel;
    w->clock.eraseGC = XCreateGC (XtDisplay (w), XtWindow (w),
    				  GCForeground | GCCapStyle | GCJoinStyle, &values);
    if (!w->clock.transparent)
	Resize (w);
    new_time ((XtPointer) gw, 0);
}

static void Destroy (gw)
     Widget gw;
{
     ClockWidget w = (ClockWidget)gw;
     if (w->clock.interval_id)
        XtRemoveTimeOut (w->clock.interval_id);
     if (w->clock.eraseGC)
	XFreeGC(XtDisplay(gw), w->clock.eraseGC);
     if (w->clock.curveGC)
	XFreeGC(XtDisplay(gw), w->clock.curveGC);
     if (w->clock.shapeGC)
	XFreeGC(XtDisplay(gw), w->clock.shapeGC);
     if (w->clock.shape_mask)
	XFreePixmap (XtDisplay (w), w->clock.shape_mask);
     if (w->clock.pm)
	XFreePixmap (XtDisplay (w), w->clock.pm);
}

/* ARGSUSED */
static void Redisplay(gw, event, region)
     Widget gw;
     XEvent *event;
     Region region;
{
    ClockWidget	w;

    w = (ClockWidget) gw;
    if (!w->clock.transparent)
    {
	paint_curve (w, XtWindow (w), w->clock.curveGC);
    }
}

/*
 * routines to draw the hands and jewel
 */

/*
 * converts a number from 0..1 representing a clockwise radial distance
 * from the 12 bclock position to a radian measure of the counter-clockwise
 * distance from the 3 bclock position
 */

/* ARGSUSED */
static void new_time (client_data, id)
     XtPointer client_data;
     XtIntervalId *id;		/* unused */
{
        ClockWidget	w = (ClockWidget)client_data;
	Time_t		now;
	struct tm	*tm;
	double second_fraction, minute_fraction, hour_fraction;
		
	/*
	 * add the timeout before painting the hands, that may
	 * take a while and we'd like the clock to keep up
	 * with time changes.
	 */
	w->clock.interval_id = 
	    XtAppAddTimeOut (XtWidgetToApplicationContext((Widget) w),
			     1000, new_time, client_data);

	(void) time (&now);
	tm = localtime (&now);
	if (tm->tm_hour >= 12)
		tm->tm_hour -= 12;
	
	second_fraction = ((double) tm->tm_sec) / 60.0;
	minute_fraction = ((double) tm->tm_min + second_fraction) / 60.0;
	hour_fraction = ((double) tm->tm_hour + minute_fraction) / 12.0;
	
	w->clock.second_angle = 2.0 * PI * second_fraction;
	w->clock.minute_angle = 2.0 * PI * minute_fraction;
	w->clock.hour_angle = 2.0 * PI * hour_fraction;

	if (w->clock.transparent)
	    Resize (w);
	else
	{
	    if (w->clock.pm &&
	        (w->clock.pm_width != w->core.width ||
	         w->clock.pm_height != w->core.height))
	    {
	      XFreePixmap (XtDisplay (w), w->clock.pm);
	      w->clock.pm = None;
	    }
	    
	    if (!w->clock.pm)
	    {
	      w->clock.pm = XCreatePixmap (XtDisplay (w), XtWindow (w),
				           w->core.width, w->core.height,
				           DefaultDepthOfScreen (XtScreen(w)));
	      w->clock.pm_width = w->core.width;
	      w->clock.pm_height = w->core.height;
	    }
	    XFillRectangle (XtDisplay (w), w->clock.pm, w->clock.eraseGC, 0, 0,
	    		    w->core.width, w->core.height);
	    paint_curve (w, w->clock.pm, w->clock.curveGC);
	    XCopyArea (XtDisplay (w), w->clock.pm, XtWindow (w),
	    	       w->clock.curveGC, 0, 0,
	    	       w->core.width, w->core.height, 0, 0);
	}
} /* new_time */

TPoint *
bezier_points (int npoints, TPoint control_points[4])
{
  int i;
  TPoint *points = NULL;
  if (npoints < 8 || control_points == NULL)
    {
      fprintf (stderr, "bezier_points: invalid parameters\n");
      return NULL;
    }
  if ((points = malloc (npoints * sizeof (*points))) == NULL)
    {
      fprintf (stderr, "bezier_points: out of memory error !\n");
      return NULL;
    }
  for (i = 0; i < npoints; i++)
    {
      double array[4];
      double u, u2, u3;

      u = (double) i / (double) (npoints - 1);
      u2 = u * u;
      u3 = u2 * u;
      array[0] = -u3 + 3. * u2 - 3. * u + 1.;
      array[1] = 3. * u3 - 6. * u2 + 3. * u;
      array[2] = -3. * u3 + 3. * u2;
      array[3] = u3;
      points[i].x = array[0] * control_points[0].x + array[1] * control_points[1].x + array[2] * control_points[2].x + array[3] * control_points[3].x;
      points[i].y = array[0] * control_points[0].y + array[1] * control_points[1].y + array[2] * control_points[2].y + array[3] * control_points[3].y;
    }
  return points;
}

void
paint_curve (ClockWidget w, Drawable d, GC gc)
{
  TPoint *b_points = NULL;
  XPoint *x_points = NULL;
  TPoint control_points[4];

  if (CURVE_SIZE (w) <= 0.0)
    return;

  control_points[0].x = MINUTE_LENGTH (w) * sin (w->clock.minute_angle);
  control_points[0].y = MINUTE_LENGTH (w) * cos (w->clock.minute_angle);
  control_points[1].x = SECOND_LENGTH (w) * sin (w->clock.second_angle);
  control_points[1].y = SECOND_LENGTH (w) * cos (w->clock.second_angle);
  control_points[2].x = 0.0;
  control_points[2].y = 0.0;
  control_points[3].x = HOUR_LENGTH (w) * sin (w->clock.hour_angle);
  control_points[3].y = HOUR_LENGTH (w) * cos (w->clock.hour_angle);

  b_points = bezier_points (4 * POINTS_PER_SEGMENT, control_points);
  if (b_points == NULL)
    return;
  
  x_points = TranslatePoints (b_points, 4 * POINTS_PER_SEGMENT, &w->clock.t, CoordModeOrigin);
  if (x_points == NULL)
  {
    fprintf (stderr, "paint_curve: error translating points !\n");
    return;
  }
  
  if (gc == 0)
  {
    fprintf (stderr, "paint_curve: invalid parameters !\n");
    return;
  }
    
  XDrawLines (XtDisplay (w), d, gc, x_points, 4 * POINTS_PER_SEGMENT, CoordModeOrigin);
  
  if (b_points)
    free (b_points);
  if (x_points)
    free (x_points);
}
