# include "Ximage.h"

int cursor (Graphic *graphic, Layout *layout) {

  XEvent          event;
  KeySym          keysym;
  int             status, xstatus, value;
  XComposeStatus  composestatus;
  char            string[10], line[500];
  double          x, y;
  char            buffer[1024];
  
  while (1) {
    
    status = read (layout[0].Ximage, buffer, 4);
    buffer[4] = 0;
    
    switch (status) {
    case -1:
      /* no input from pipe: continue */
      break;
      
    case 0:
      fprintf (stderr, "pipe has died!\n");
      return (FALSE);
      break;

    case 4:
      if (!strcmp (buffer, "NCUR")) {  /* stop reading cursor */
	return (TRUE);
      }
      break;

    default:
      fprintf (stderr, "weird signal: too many or few bytes!  %d\n", status);
      return (TRUE);
      break;
    }

    if ((xstatus = XCheckMaskEvent (graphic[0].display, EVENT_MASK, &event))) {
      
      switch (event.type)  {
	
      case ButtonPress:
	status = InterpretPresses (graphic, layout, (XButtonEvent *) &event);
	break;
	
      case Expose:
	if (event.xexpose.count == 0)
	  Refresh (graphic, layout, 1);
	break;
	
      case ConfigureNotify:
	status =  Reconfig (graphic, layout, &event);
	break;
	
      case MappingNotify:
	XRefreshKeyboardMapping ((XMappingEvent *) &event);
	break;
	
      case MotionNotify:
	if (XPending (graphic[0].display) < 2) {
	  UpdatePointer (graphic, layout, (XMotionEvent *) &event);
	}
	break;

      case KeyPress:
	value = XLookupString ((XKeyEvent *) &event, string, 9, &keysym, &composestatus);

	if ((event.xkey.x >= layout[0].picture.x) && (event.xkey.x <= layout[0].picture.x + layout[0].picture.dx) &&
	    (event.xkey.y >= layout[0].picture.y) && (event.xkey.y <= layout[0].picture.y + layout[0].picture.dy)) {

	  Screen_to_Image (&x, &y, (double)event.xkey.x, (double)event.xkey.y, layout);

	  if (isprint(string[0]))
	    sprintf (line, "%c %6.1f %6.1f ", string[0], x, y);
	  else {
	    sprintf (line, "X %6.1f %6.1f ", x, y);
	    break;
	  }
	  write (layout[0].Ximage, line, 16);
	}
      }
    }
  }
}
