#include "copyright.h"

/* $XConsortium: XGetColor.c,v 11.14 88/09/06 16:07:43 jim Exp $ */
/* Copyright    Massachusetts Institute of Technology    1986	 */

/* -- MULTIPLEX extension -- */

#define NEED_REPLIES
#define NEED_EVENTS
#include "Xlibint.h"

/* -- additional includes -- */

#include "XmuXlibint.h"
#include "resources.h"
#include "map.h"

Status
XAllocNamedColor (calling_dpy, cmap, colorname, hard_def, exact_def)
/* -- must rename or else macro GetReq will fail -- */
  register Display *calling_dpy;
  Colormap cmap;
  char *colorname;		/* STRING8 */
  XColor *hard_def;		/* RETURN */
  XColor *exact_def;		/* RETURN */
{
  register Display *dpy;
  register int i, allocated;
  long nbytes;
  xAllocNamedColorReply rep;
  xAllocNamedColorReq *req;

  /*
   * -- Flush the default display's output queue -- to keep things in order
   */
  XmuXFlushDefault (calling_dpy);

  /*
   * -- must loop over all associated displays
   */
  allocated = 1;
  for (i = 0;
       (dpy = XmuXGetDisplay (calling_dpy, i)) != NULL && allocated;
       i++) {
    LockDisplay (dpy);
    GetReq (AllocNamedColor, req);

    if (i != 0)
      req->cmap = XmuXMapID (dpy, cmap, FromClient);
    else
      req->cmap = cmap;

    nbytes = req->nbytes = colorname ? strlen (colorname) : 0;
    req->length += (nbytes + 3) >> 2;	/* round up to mult of 4 */

    /*
     * -- don't use MULTIPLEXED version of _XSend here !! --
     */
    _XmuXSingleSend (dpy, colorname, nbytes);
    /* _XmuXSingleSend is more efficient that Data, since _XReply follows */
    if (!_XReply (dpy, (xReply *) & rep, 0, xTrue))
      allocated = 0;

    if (allocated) {
      if (i == 0) {
	exact_def->red = rep.exactRed;
	exact_def->green = rep.exactGreen;
	exact_def->blue = rep.exactBlue;

	hard_def->red = rep.screenRed;
	hard_def->green = rep.screenGreen;
	hard_def->blue = rep.screenBlue;

	exact_def->pixel = hard_def->pixel = rep.pixel;

	if (XmuXStoreResources (dpy)) {
	  unsigned long pixel = rep.pixel;
	  XmuXUpdateColormapInfo (dpy, cmap, &pixel, 1,
				  NULL, 0, True);
	}
      }
      else
	XmuXInsertSharedCell (dpy, req->cmap,
			      exact_def->pixel, rep.pixel);
    }
    UnlockDisplay (dpy);
    SyncHandle ();
  }
  return (allocated);
}
