Example #1
0
int graphics_init (void)
{
    if (currprefs.x11_use_mitshm && ! shmavail) {
	write_log ("MIT-SHM extension not supported by X server.\n");
    }
    if (currprefs.color_mode > 5)
	write_log ("Bad color mode selected. Using default.\n"), currprefs.color_mode = 0;

    x11_init_ok = 0;
    need_dither = 0;
    screen_is_picasso = 0;
    dgamode = 0;

    init_dispinfo (&ami_dinfo);
    init_dispinfo (&pic_dinfo);

    write_log ("Using %d bit visual, %d bits per pixel\n", bitdepth, bit_unit);

    fixup_prefs_dimensions (&currprefs);

    gfxvidinfo.width = currprefs.gfx_width_win;
    gfxvidinfo.height = currprefs.gfx_height_win;
    current_width = currprefs.gfx_width_win;
    current_height = currprefs.gfx_height_win;

    cmap = XCreateColormap (display, rootwin, vis, AllocNone);
    cmap2 = XCreateColormap (display, rootwin, vis, AllocNone);
    if (visualInfo.VI_CLASS == GrayScale || visualInfo.VI_CLASS == PseudoColor) {
	XAllocColorCells (display, cmap, 0, 0, 0, pixel_return, 1 << bitdepth);
	XAllocColorCells (display, cmap2, 0, 0, 0, pixel_return, 1 << bitdepth);
    }

    if (bitdepth < 8 || (bitdepth == 8 && currprefs.color_mode == 3)) {
	gfxvidinfo.pixbytes = 2;
	currprefs.x11_use_low_bandwidth = 0;
	need_dither = 1;
    } else {
	gfxvidinfo.pixbytes = bit_unit >> 3;
    }

    if (! init_colors ())
	return 0;

    blankCursor = XCreatePixmapCursor (display,
				       XCreatePixmap (display, rootwin, 1, 1, 1),
				       XCreatePixmap (display, rootwin, 1, 1, 1),
				       &black, &white, 0, 0);
    xhairCursor = XCreateFontCursor (display, XC_crosshair);

    graphics_subinit ();

    grabbed = 0;

    return x11_init_ok = 1;
}
Example #2
0
int
GetNumAvailableColors(Display * display, Screen * screen, unsigned map_entries) {
    unsigned long pmr[1];
    unsigned long pr[SPLASH_COLOR_MAP_SIZE];
    unsigned nFailed, nAllocated, done = 0, nPlanes = 0;
    Colormap cmap;
    unsigned numColors = SPLASH_COLOR_MAP_SIZE; // never try allocating more than that

    if (numColors > map_entries) {
        numColors = map_entries;
    }
    cmap = XDefaultColormapOfScreen(screen);
    nAllocated = 0;             /* lower bound */
    nFailed = numColors + 1;    /* upper bound */

    /* Binary search to determine the number of available cells */
    for (done = 0; !done;) {
        if (XAllocColorCells(display, cmap, 0, pmr, nPlanes, pr, numColors)) {
            nAllocated = numColors;
            XFreeColors(display, cmap, pr, numColors, 0);
            if (nAllocated < (nFailed - 1)) {
                numColors = (nAllocated + nFailed) / 2;
            } else
                done = 1;
        } else {
            nFailed = numColors;
            if (nFailed > (nAllocated + 1))
                numColors = (nAllocated + nFailed) / 2;
            else
                done = 1;
        }
    }
    return nAllocated;
}
Example #3
0
void redocolors() {
										
  int i;
  for (i = 0; i < COLORS; i++) {	/* Set up the colors gradient */
		// myRGB r=myRGB(thru,thru,thru);
		// myRGB r=( thru < 1 ? myRGB(0.0,thru*5.0,0.0)
						             // : myRGB(thru*2.0-1.0,1.0,thru*2.0-1.0)
						// );
    float thru=4.0*(float)((frameno*palspeed+i/2)%colors)/(float)COLORS;
		myRGB r;
		if (thru<1.0)
			r=myRGB(0.0,thru,0.0);
		else if (thru<2.0)
			r=myRGB(thru-1.0,1.0,thru-1.0);
		else if (thru<3.0)
			r=myRGB(1.0-(thru-2.0),1.0-(thru-2.0),1.0);
		else
			r=myRGB(0.0,0.0,1.0-(thru-3.0));

    #ifdef X11GFX
      xrgb[i].red = 65535 * r.r/255; // (1.0 - 1.0 * i / COLORS);
      xrgb[i].green = 65535 * r.g/255;
      xrgb[i].blue = 65535 * r.b/255;
      xrgb[i].flags = DoRed | DoGreen | DoBlue;
      xrgb[i].pixel=i;
    #endif

    #ifdef ALLEGRO
      RGB algrgb;
      algrgb.r=r.r/4;
      algrgb.g=r.g/4;
      algrgb.b=r.b/4;
      set_color(i,&algrgb);
    #endif

  }

    #ifdef X11GFX
			if (stylee == styleeTrueColor) {
        // XInstallColormap (d, colormap);
			  for (int i=0;i<colors;i++) {
				  if ( XAllocColor(d,colormap,&xrgb[i]) == 0 )
					  printf("Error allocating %i\n",i);
				  // works for true-color
			  }
			} else {
			XAllocColorCells(d,colormap,1,0,0,color,colors);

			  // for (int i=0;i<colors;i++) {
				  // xrgb[i].pixel=color[i];
			  // }
			  XStoreColors(d,colormap,xrgb,COLORS);
			  XSetWindowColormap(d,win,colormap);
        // fputs("Couldn't allocate enough colors cells.\n", 
        // stderr), exit(1);
			}

    #endif

}
Example #4
0
static void
allocate_writable_colors(Display * dpy, Colormap cmap,
			 unsigned long *pixels, int *ncolorsP)
{
	int         desired = *ncolorsP;
	int         got = 0;
	int         requested = desired;
	unsigned long *new_pixels = pixels;

	*ncolorsP = 0;
	while (got < desired
	       && requested > 0) {
		if (desired - got < requested)
			requested = desired - got;

		if (XAllocColorCells(dpy, cmap, False, 0, 0, new_pixels, requested)) {
			/* Got all the pixels we asked for. */
			new_pixels += requested;
			got += requested;
		} else {
			/* We didn't get all/any of the pixels we asked for.  This time, ask
			   for half as many.  (If we do get all that we ask for, we ask for
			   the same number again next time, so we only do O(log(n)) server
			   roundtrips.)
			 */
			requested = requested / 2;
		}
	}
	*ncolorsP += got;
}
/*
 Assumes a Pseudo graphic display.
 */
void init_colormaps (Display *dpy)
{
   screen = XDefaultScreen (dpy);

   fprintf(stderr, "Number of display cells = %d\n",
	   XDisplayCells(dpy, screen));
   fprintf(stderr, "Number of display planes = %d\n",
	   XDisplayPlanes(dpy, screen));

   colormap = XDefaultColormap(dpy, screen);
   while (XAllocColorCells(display_, colormap, False, NULL, 0, 
			   &(pixels[cmapsize]), 1))
     cmapsize++;
   
   cmapsize = (cmapsize > 60) ? 60 : cmapsize;
   fprintf(stderr, "Number of colors available = %d\n", cmapsize);

   if (cmapsize<5)
     {
	fprintf(stderr, "Number of colors available = %d\n", cmapsize);
	fprintf(stderr, "This is too few to run the display software.\n");
	fprintf(stderr, "Shut down windows, or restart X server.\n");
	exit(-1);      
     }
  
   /* build a grey scale colormap as a default, so that other programs */
   /* can't grab the colors*/
   {
      XColor xcolor;
      int i;
      
      xcolor.flags= DoRed | DoGreen | DoBlue;
      for (i = 0 ; i < cmapsize; i++) {
	 xcolor.pixel = pixels[i];
	 xcolor.red = (unsigned short) (i<<8);
	 xcolor.green = (unsigned short) (i<<8);
	 xcolor.blue = (unsigned short) (i<<8);
	 XStoreColor (display_, colormap, &xcolor);
      }
   }
   
  /* Generate global gamma correction table for this display */
  {
    Pixel index;
    double gamma = 1.0/1.0;
    
    for(index =0; index < 255; index++) {
      GammaCorrect[index] = (Pixel)(0.5 + 255.0 * 
				     (double) pow((double)(index)/255.0, 
						  gamma));
    }
  }

  /* Set up the internal histogram tables*/
  translate_init();

  return;
}
Example #6
0
Colormap
AllocColors(Display * display, Screen * screen, int numColors,
        unsigned long *pr) {
    unsigned long pmr[1];
    Colormap cmap = XDefaultColormapOfScreen(screen);

    XAllocColorCells(display, cmap, 0, pmr, 0, pr, numColors);
    return cmap;
}
Example #7
0
static int
allocate_color_planes (Display *dpy, Colormap cmap,
		       int nplanes, unsigned long *plane_masks,
		       unsigned long *base_pixel_ret)
{
  while (nplanes > 1 &&
	 !XAllocColorCells (dpy, cmap, False, plane_masks, nplanes,
			    base_pixel_ret, 1))
    nplanes--;

  return nplanes;
}
Example #8
0
Colormap CreateColorMap(Widget main)
{
    Colormap cmap,def_cmap;
    XColor Colors[256];
    int i,ncolors;
    unsigned long pixels[256],planes[1];

    /* Find out how many colors are available on the default colormap */
        cmap = DefaultColormap (dpy, DefaultScreen (dpy));
        ncolors = 256;
        while(ncolors>1) {
                if (XAllocColorCells(dpy,cmap,0,planes,0,pixels,ncolors)) break;
                ncolors--;
        }
        if(ncolors>1) XFreeColors(dpy,cmap,pixels,ncolors,0);

    /* If there are not enough colors available, create a new colormap */
    if(ncolors < 5) {
        ncolors = 5;
        def_cmap = DefaultColormap (dpy, DefaultScreen(dpy));
        for(i=0; i<200; i++) {
            Colors[i].pixel = i;
            Colors[i].flags = DoRed|DoGreen|DoBlue;
        }
        XQueryColors(dpy,def_cmap,Colors,200);
        cmap = XCreateColormap(dpy,DefaultRootWindow(dpy),
            DefaultVisual(dpy,DefaultScreen(dpy)),
            AllocNone);
        XAllocColorCells(dpy,cmap,1,planes,0,pixels,200);
        //XStoreColors(dpy,cmap,Colors,200);
    }

    /* Map the colors we will use */
    memset(color,0,sizeof(unsigned long)*256);
    for(i=0; i<5; i++) MapColor(cmap,i,Color[i][0],Color[i][1],Color[i][2]);

    /* Return the colormap */
    return(cmap);
}
Example #9
0
void HGU_XmCreatePrivateColormap(Widget w)
{
  Display	*dpy;
  Window	win;
  Visual	*visual;
  Colormap	cmap, def_cmap;
  XColor	colorcell;
  unsigned long	plane_masks[1], pixels[256];
  unsigned int	n_pixels;
  int			i;

  /* create a private colormap */
  if( (dpy = XtDisplayOfObject( w )) == NULL )
    return;
  win = RootWindow( dpy, DefaultScreen( dpy ) );
  visual = HGU_XGetVisual(dpy, DefaultScreen( dpy ), PseudoColor, 8);
  if( visual == NULL ){
    visual = DefaultVisual( dpy, DefaultScreen( dpy ) );
  }
  cmap = XCreateColormap( dpy, win, visual, AllocNone );
  def_cmap = DefaultColormap( dpy, DefaultScreen( dpy ) );
    
  /* copy all existing colours */
  n_pixels = 0;
  colorcell.flags = DoRed|DoGreen|DoBlue;
  for(i=0; i < 256; i++){

    if( XAllocColorCells(dpy, cmap, False, plane_masks,
			 0, &(pixels[n_pixels]), 1) == 0 )
      continue;
    if( i >= 32 )	/* only free colours over pixel value 32 */
      n_pixels++;

    colorcell.pixel = i;
    XQueryColor(dpy, def_cmap, &colorcell);
    XStoreColor(dpy, cmap, &colorcell);
  }

  XFreeColors(dpy, cmap, pixels, n_pixels, 0);
    
  /* set the colormap as the widget resource */
  XtVaSetValues(w, XmNcolormap, cmap, NULL);
  globals.cmap = cmap;

  return;
}
Example #10
0
int
AllocCells(Display *dsply, Colormap colorMap, int smoothHue)
{
    unsigned long plane_masks[1];
    int i, count;
    float lightness;
    RGB rgb;
    XColor xcolor;
    HLS hls;

    count = 0;
    for (i = 0; i < (smoothConst + 1); i++) {
        lightness = (float) (i) / (float) (smoothConst);
        hls.h = (float) smoothHue;
        hls.l = lightness;
        hls.s = saturation;
        rgb = HLStoRGB(hls);
        xcolor.red    = rgb.r *((1<<16)-1);
        xcolor.green  = rgb.g *((1<<16)-1);
        xcolor.blue   = rgb.b *((1<<16)-1);
        xcolor.flags = DoRed | DoGreen | DoBlue;
        /*
          fprintf(stderr,"%f\t%f\t%f\n",rgb.r,rgb.g,rgb.b);
          fprintf(stderr,"%d\t%d\t%d\n",xcolor.red,xcolor.green,xcolor.blue);
          */
        if (XAllocColor(dsply, colorMap, &xcolor)) {
            pixels[count] = xcolor.pixel;
            count++;
        }
    }
    /* count says how many succeeded */
    if (count != (smoothConst+1) ) {
      /* we have failed to get all of them - free the ones we got */
      FreePixels(dsply,colorMap,count);
      return (0);
    }
    if (XAllocColorCells(dsply, colorMap, False,
                          plane_masks, 0, pixels, smoothConst + 1)) {
        return (smoothConst + 1);
    }
    else {
        return (0);
    }
}
Example #11
0
int ph_window_alloc_palette (int writable_colors)
{
#if 0
   int i;
   
   if(!(pseudo_color_lookup = malloc(writable_colors * sizeof(unsigned long))))
   {
      fprintf(stderr_file, "error: malloc failed for pseudo color lookup table\n");
      return -1;
   }
   
   /* set the palette to black */
   for (i = 0; i < writable_colors; i++)
      pseudo_color_lookup[i] = black_pen;

   /* allocate color cells */
   if (XAllocColorCells (display, colormap, 0, 0, 0, pseudo_color_lookup,
      writable_colors))
   {
      pseudo_color_use_rw_palette = 1;
      fprintf (stderr_file, "info: using r/w palette entries to speed up, good\n");
      for (i = 0; i < writable_colors; i++)
         if (pseudo_color_lookup[i] != i) break;
   }
   else
   {
      if (!(pseudo_color_allocated = calloc(writable_colors, sizeof(char))))
      {
         fprintf(stderr_file, "error: malloc failed for pseudo color lookup table\n");
         free(pseudo_color_lookup);
         pseudo_color_lookup=NULL;
         return -1;
      }
   }
   
   display_palette_info.writable_colors = writable_colors;
#endif
   return 0;
}
Example #12
0
static void 
initColor (struct state *st, double r, double g, double b)
{
  int n,n1;
  unsigned long pixels[12];
  unsigned long dummy;
  
  st->cmap = st->xgwa.colormap;
  
  if(st->hsvcycl!=0.0 && XAllocColorCells(st->dpy, st->cmap, 0, &dummy, 0, pixels, 12))
    {
      for(n1=0;n1<12;n1++)
	{
	  st->colors[n1].pixel=pixels[n1];
	  st->colors[n1].flags=DoRed | DoGreen | DoBlue;
	}
      
      changeColor(st,r,g,b);
    }
  else
    {
      n1=0;
      for(n=30;n<64;n+=3)
	{
	  st->colors[n1].red   =1023+ n*(int)(1024.*r);
	  st->colors[n1].blue  =1023+ n*(int)(1024.*b);
	  st->colors[n1].green =1023+ n*(int)(1024.*g);
	  
	  if (!(XAllocColor (st->dpy, st->cmap, &st->colors[n1]))) {
	    fprintf (stderr, "Error:  Cannot allocate colors\n");
	    exit (1);
	  }
	  
	  n1++;
	}
    }
}
Example #13
0
uint QGLContext::colorIndex( const QColor& c ) const
{
    int screen = ((XVisualInfo *)vi)->screen;
    if ( isValid() ) {
	if ( format().plane()
	     && c.pixel( screen ) == overlayTransparentColor().pixel( screen ) )
	    return c.pixel( screen );		// Special; don't look-up
	if ( ((XVisualInfo*)vi)->visualid ==
	     XVisualIDFromVisual( (Visual*)QPaintDevice::x11AppVisual( screen ) ) )
	    return c.pixel( screen );		// We're using QColor's cmap

	XVisualInfo *info = (XVisualInfo *) vi;
	CMapEntry *x = cmap_dict->find( (long) info->visualid + ( info->screen * 256 ) );
	if ( x && !x->alloc) {		// It's a standard colormap
	    int rf = (int)(((float)c.red() * (x->scmap.red_max+1))/256.0);
	    int gf = (int)(((float)c.green() * (x->scmap.green_max+1))/256.0);
	    int bf = (int)(((float)c.blue() * (x->scmap.blue_max+1))/256.0);
	    uint p = x->scmap.base_pixel
		     + ( rf * x->scmap.red_mult )
		     + ( gf * x->scmap.green_mult )
		     + ( bf * x->scmap.blue_mult );
	    return p;
	} else {
	    if (!qglcmap_dict) {
		qglcmap_dict = new QIntDict< QMap<int, QRgb> >;
	    }
	    QMap<int, QRgb> *cmap;
	    if ((cmap = qglcmap_dict->find((long) info->visualid)) == 0) {
		cmap = new QMap<int, QRgb>;
		qglcmap_dict->insert((long) info->visualid, cmap);
	    }

	    // already in the map?
	    QRgb target = c.rgb();
	    QMap<int, QRgb>::Iterator it = cmap->begin();
	    for (; it != cmap->end(); ++it) {
		if ((*it) == target)
		    return it.key();
	    }

	    // need to alloc color
	    unsigned long plane_mask[2];
	    unsigned long color_map_entry;
	    if (!XAllocColorCells (QPaintDevice::x11AppDisplay(), x->cmap, TRUE, plane_mask, 0,
				   &color_map_entry, 1))
		return c.pixel(screen);

	    XColor col;
	    col.flags = DoRed | DoGreen | DoBlue;
	    col.pixel = color_map_entry;
	    col.red   = (ushort)((qRed(c.rgb()) / 255.0) * 65535.0 + 0.5);
	    col.green = (ushort)((qGreen(c.rgb()) / 255.0) * 65535.0 + 0.5);
	    col.blue  = (ushort)((qBlue(c.rgb()) / 255.0) * 65535.0 + 0.5);
	    XStoreColor(QPaintDevice::x11AppDisplay(), x->cmap, &col);

	    cmap->insert(color_map_entry, target);
	    return color_map_entry;
	}
    }
    return 0;
}
Example #14
0
uint QGLContext::colorIndex(const QColor& c) const
{
    Q_D(const QGLContext);
    int screen = ((XVisualInfo *)d->vi)->screen;
    QColormap colmap = QColormap::instance(screen);
    if (isValid()) {
        if (format().plane() && c == Qt::transparent) {
            return qt_transparent_pixel(((XVisualInfo *)d->vi)->visualid,
                                        ((XVisualInfo *)d->vi)->screen);
        }
        if (((XVisualInfo*)d->vi)->visualid ==
             XVisualIDFromVisual((Visual *) QX11Info::appVisual(screen)))
            return colmap.pixel(c);                // We're using QColor's cmap

        XVisualInfo *info = (XVisualInfo *) d->vi;
        CMapEntryHash *hash = cmap_handler()->cmap_hash;
        CMapEntryHash::ConstIterator it = hash->constFind(long(info->visualid)
                + (info->screen * 256));
        QCMapEntry *x = 0;
        if (it != hash->constEnd())
            x = it.value();
        if (x && !x->alloc) {                // It's a standard colormap
            int rf = (int)(((float)c.red() * (x->scmap.red_max+1))/256.0);
            int gf = (int)(((float)c.green() * (x->scmap.green_max+1))/256.0);
            int bf = (int)(((float)c.blue() * (x->scmap.blue_max+1))/256.0);
            uint p = x->scmap.base_pixel
                     + (rf * x->scmap.red_mult)
                     + (gf * x->scmap.green_mult)
                     + (bf * x->scmap.blue_mult);
            return p;
        } else {
            QMap<int, QRgb> &cmap = (*cmap_handler()->qglcmap_hash)[(long)info->visualid];

            // already in the map?
            QRgb target = c.rgb();
            QMap<int, QRgb>::Iterator it = cmap.begin();
            for (; it != cmap.end(); ++it) {
                if ((*it) == target)
                    return it.key();
            }

            // need to alloc color
            unsigned long plane_mask[2];
            unsigned long color_map_entry;
            if (!XAllocColorCells (QX11Info::display(), x->cmap, true, plane_mask, 0,
                                   &color_map_entry, 1))
                return colmap.pixel(c);

            XColor col;
            col.flags = DoRed | DoGreen | DoBlue;
            col.pixel = color_map_entry;
            col.red   = (ushort)((qRed(c.rgb()) / 255.0) * 65535.0 + 0.5);
            col.green = (ushort)((qGreen(c.rgb()) / 255.0) * 65535.0 + 0.5);
            col.blue  = (ushort)((qBlue(c.rgb()) / 255.0) * 65535.0 + 0.5);
            XStoreColor(QX11Info::display(), x->cmap, &col);

            cmap.insert(color_map_entry, target);
            return color_map_entry;
        }
    }
    return 0;
}
Example #15
0
void
do_setcustompalette (XColor * inpal)
{
  int i, n, me = 0, flag[256], vid;
  int depth;
  long unsigned int plane_masks[3];
  XColor pal[256];
  int writeable_p;

  display.cmap = XDefaultColormap (display.dpy, display.screen);
  depth = DefaultDepth (display.dpy, display.screen);

  /* Decide, if the colormap is writable */
  {
    Visual *visual = DefaultVisual (display.dpy, display.screen);
#if defined(__cplusplus) || defined(c_plusplus)
    int visual_class = visual->c_class;
#else
    int visual_class = visual->class;
#endif
    writeable_p = (visual_class == PseudoColor || visual_class == GrayScale);
  }

  if (writeable_p)
    {
      if (XAllocColorCells (display.dpy, display.cmap, 0
			    ,plane_masks, 0, colour_table, 256) == 0)
	{
	  me = (*DefaultVisual (display.dpy, display.screen)).map_entries;
	  vid = (*DefaultVisual (display.dpy, display.screen)).visualid;
	  display.cmap = XCreateColormap (display.dpy, display.win
				,DefaultVisual (display.dpy, display.screen)
	  /*      ,PseudoColor */
					  ,AllocNone);
	  if (me == 256 && depth != 24)
	    {
	      if (XAllocColorCells (display.dpy, display.cmap, 0
				    ,plane_masks, 0, colour_table, 256) != 0) {
		  /* printf ("Allocated 256 cells\n"); */
	      }
	      else {
		  printf ("Couldn't allocate 256 cells\n");
	      }
	    }
	  else
	    for (i = 0; i < 256; i++)
	      colour_table[i] = i;
	}
      if (!display.cmap)
	HandleError ("No default colour map", FATAL);
    }

  for (i = 0; i < 256; i++)
    flag[i] = 0;

  for (n = 0; n < 256; n++)
    {
      pal[n].red = inpal[n].red << 10;
      pal[n].green = inpal[n].green << 10;
      pal[n].blue = inpal[n].blue << 10;
      pal[n].flags = DoRed | DoGreen | DoBlue;
      if (writeable_p)
	pal[n].pixel = colour_table[n];
      else
	{
	  if (XAllocColor (display.dpy
			   ,display.cmap, &(pal[n])) == 0)
	    HandleError ("alloc colour failed"
			 ,FATAL);
	  colour_table[n] = pal[n].pixel;
	  XSetForeground (display.dpy
			  ,display.pixcolour_gc[n]
			  ,colour_table[n]);
	}
      flag[n] = 1;
    }

  if (writeable_p)
    {
      XStoreColors (display.dpy, display.cmap, pal, 256);
      XFlush (display.dpy);
    }
  XSetWindowColormap (display.dpy, display.win, display.cmap);
}
Example #16
0
static      vmResult
X_video_restart(void)
{
	/*  Allocate colors every time we enable, 
	   in case some color-hogging apps have left. */

	int         tries = 0;
	int         x, alloced;

	//  Allocate our colors.  For using_palette, allocate read/write
	//  colorcells for 17 colors (bg and text fg change).  Else,
	//  allocate 15 colors.
	//  Either way, cmap[] maps each color to the pixel used to
	//  display it.

	x11_cmap = DefaultColormap(x11_dpy, x11_screen);

	//  Go through twice:  first time, try to allocate colors
	//  from default colormap.  If this fails sufficiently,
	//  allocate a virtual colormap.
	do {

		//  This tells us if colors 0 and 16 (for video reg 7)
		//  can change at will, or if we need to redraw the screen for them
		using_palette = x11_class != TrueColor
			&& x11_class != StaticColor && x11_class != StaticGray;

		//  Get 15 immutable cells
		alloced = 0;
		for (x = 1; x < 16; x++) {
			XColor      color;
			XcmsColor   cmClrScrn, cmClrExact;
			XcmsColorFormat cmFmt;

			color.red = RGB_8_TO_16(vdp_palette[x][0]);
			color.green = RGB_8_TO_16(vdp_palette[x][1]);
			color.blue = RGB_8_TO_16(vdp_palette[x][2]);
			color.flags = DoRed | DoGreen | DoBlue;

			if (!XAllocColor(x11_dpy, x11_cmap, &color)) {
				if (!XAllocNamedColor(x11_dpy, x11_cmap, Xcolornames[x],
									  &color, &color)) {
					module_logger(&X_Video, _L|L_1, _("could not allocate color %d\n"), x);
					//return vmInternalError;
				} else {
					module_logger(&X_Video, _L|L_1, _("color #%d:  got named color '%s'\n"), x,
						 Xcolornames[x]);
					alloced++;
				}
			} else {
				module_logger(&X_Video, _L|L_1, _("color #%d:  got RGB color\n"), x);
				alloced += 2;
			}

			colormap[x] = color.pixel;

		}

		//  Get fg/bg colors
		if (using_palette) {
			if (!XAllocColorCells(x11_dpy, x11_cmap, False /* contiguous */ ,
								  x11_planes, 0, colormap, 1)) {
				using_palette = false;
			} else
				if (!XAllocColorCells
					(x11_dpy, x11_cmap, False /* contiguous */ ,
					 x11_planes, 0, colormap + 16, 1)) {
				using_palette = false;
				// free the one color we got
				XFreeColors(x11_dpy, x11_cmap, colormap, 1, x11_planes[0]);
			}
			if (!using_palette)
				module_logger(&X_Video, _L|LOG_ERROR |L_1,
					 _("Could not allocate 2 read/write colorcells\n"));
		}
//		if (!using_palette) {
//			cmap[0] = cmap[1];
//			cmap[16] = cmap[15];
//		}

		//  If we got an insufficient number of colors,
		//  try for virtual colormap.
		module_logger(&X_Video, _L|L_1, _("alloced = %d\n"), alloced);
		if (!tries && alloced < 16 &&
			(x11_class == GrayScale || x11_class == PseudoColor)) {
			x11_cmap = XCreateColormap(x11_dpy, vwin, x11_visual, AllocNone);
			XSetWindowColormap(x11_dpy, vwin, x11_cmap);
			module_logger(&X_Video, _L|LOG_USER, _("allocated custom colormap for window\n"));
		} else {
			tries = 1;
		}

	} while (++tries < 2);

	XSetWindowColormap(x11_dpy, vwin, x11_cmap);

	XSetWMNormalHints(x11_dpy, vwin, vwin_size_hints);
	XMapWindow(x11_dpy, vwin);

//	x_dirty_screen(0, 0, 32, 24);
	return vmOk;
}
Example #17
0
void 
SRGP__initColor (requested_planes)
{
   srgp__available_depth = DefaultDepth(srgpx__display, srgpx__screen);

   if (srgp__available_depth == 1) {

      /***** PERFORMED FOR BILEVEL DISPLAYS */

      SRGP_BLACK = BlackPixel(srgpx__display,srgpx__screen);
      SRGP_WHITE = WhitePixel(srgpx__display,srgpx__screen);
      srgp__application_depth = 
	 srgp__max_pixel_value = 1;
      srgp__base_colorindex = 0;
   }
   

   else {

      /****** PERFORMED FOR COLOR DISPLAYS */

      SRGP_BLACK = 1;
      SRGP_WHITE = 0;

      if (requested_planes < 0) {
	 fprintf (stderr, "Fatal Error: insane parameter to SRGP_begin()\n\
            Application requesting negative number of planes.\n");
	 exit(1);
      }
      if ((requested_planes == 0) || 
	  (requested_planes > srgp__available_depth)) 
	 srgp__application_depth = srgp__available_depth;
      else
	 srgp__application_depth = requested_planes;
      srgp__max_pixel_value = (1 << srgp__application_depth) - 1;

      if (srgp__application_depth == srgp__available_depth) {

	 /***** APPL WANTS ENTIRE COLOR TABLE! */
	 srgpx__colormap = 
	    XCreateColormap (srgpx__display, 
			     srgp__curActiveCanvasSpec.drawable.win,
			     DefaultVisual(srgpx__display,srgpx__screen),
			     AllocAll);
	 XSetWindowColormap (srgpx__display, 
			     srgp__curActiveCanvasSpec.drawable.win,
			     srgpx__colormap);
      }
      else {

	 /***** APPL WANTS TO SHARE COLOR TABLE WITH THE OTHER CLIENTS */
	 unsigned long return_masks_here[8];
	 unsigned long return_pixels_here[1];
	 Status result;

	 srgpx__colormap = DefaultColormap(srgpx__display,srgpx__screen);

	 result = 
	    XAllocColorCells (srgpx__display,
			      srgpx__colormap,
			      TRUE /* contiguous planes desired */,
			      return_masks_here,
			      srgp__application_depth,
			      return_pixels_here,
			      1);
	 if (result == 0) {
	    fprintf (stderr, "%s\n%s\n%s\n%s\n%s\n",
		     "Fatal error: Color table too full to share.",
		     "A solution is to have the SRGP application request",
		     "   0 planes in the 4th parameter to SRGP_begin.",
		     "This gives SRGP permission to use its own complete",
		     "   color table, rather than try to share.");
	    exit(1);
	 }
	 
	 srgp__base_colorindex = return_pixels_here[0];
      }

      /* Only first two entries of LUT are init'd */
      XStoreNamedColor 
	 (srgpx__display, srgpx__colormap, "white", COLORINDEX(0), -1);
      XStoreNamedColor 
	 (srgpx__display, srgpx__colormap, "black", COLORINDEX(1), -1);
   }
Example #18
0
File: clr.c Project: satish2/Learn
void
initColormap ( JNIEnv* env, Toolkit* Tlk, Colormap cm, Rgb2Pseudo* map )
{
  jclass   clazz;
  jfieldID fid;
  jarray   rgbRequests = 0;
  jboolean isCopy;
  jint     *jrgbs = 0;
  int      nReq = 0;
  unsigned long  pixels[MAX_REQUESTS];
  jint     req[MAX_REQUESTS];
  unsigned long  planeMasks[1];
  int      n, i, j, k, l, m, pix;
  Visual   *v = DefaultVisualOfScreen( DefaultScreenOfDisplay( Tlk->dsp));
  XColor   xclr;
  int      r, g, b;
  char     blackSeen = 0;
  unsigned char (*mp)[8][8][8] = alloca( 8*8*8 * sizeof( char));

  memset( *mp, 0, 8*8*8);

  /* get the java.awt.DefaultsRGB.RgbRequests field */
  if ( (clazz = (*env)->FindClass( env, "java/awt/Defaults")) ){
	if ( (fid = (*env)->GetStaticFieldID( env, clazz, "RgbRequests", "[I")) ){
	  if ( (rgbRequests = (*env)->GetStaticObjectField( env, clazz, fid)) ){
		jrgbs = (*env)->GetIntArrayElements( env, rgbRequests, &isCopy);
		nReq = (*env)->GetArrayLength( env, rgbRequests);

		if ( nReq > MAX_REQUESTS )
		  nReq = MAX_REQUESTS;

		memcpy( req, jrgbs, nReq * sizeof( jint));
		(*env)->ReleaseIntArrayElements( env, rgbRequests, jrgbs, JNI_ABORT);
	  }
	}
  }
  
  /*
   * Determine how many RW cells there are available. Don't try to grab
   * too many cells, since this might disturb other apps and could end up
   * in even worse results
   */
  for ( n= 10; n; n-- ) {
	if ( XAllocColorCells( Tlk->dsp, cm, False, planeMasks, 0, pixels, n) )
	  break;
  }

  xclr.red = 0; xclr.green = 0; xclr.blue = 0;
  xclr.flags = DoRed | DoGreen | DoBlue;

  /* mark all of our cells (so that we don't rely on their current values) */
  for ( i=0; i<n; i++ ){
	xclr.pixel = pixels[i];
	XStoreColor( Tlk->dsp, cm, &xclr);
  }

  /* check which of our rgb requests are already in the colormap */
  for ( l=0; l<v->map_entries; l++ ) {
	xclr.pixel = l;
	XQueryColor( Tlk->dsp, cm, &xclr);
	r = xclr.red >> 8;
	g = xclr.green >> 8;
	b = xclr.blue >> 8;

	i = JI8(r);
	j = JI8(g);
	k = JI8(b);

	if ( r | g | b ) {
	  for ( m=0; m<nReq; m++ ) {
		if ( req[m] &&
			 colorDiff( JRED(req[m]), JGREEN(req[m]), JBLUE(req[m]), r, g, b) < CLR_DIST ) {
           req[m] = 0;                 /* mark color request as satisfied */
		   (*mp)[i][j][k] = 1;         /* mark cube cell (i,j,k) as requested */
		   break;
		}
	  }
	}

	/*
	 * we start to populate the color cube as we go (XQueryColor might be expensive),
	 * but we don't overwrite an already set cell with a worse match (if we don't
	 * have a standard system colormap, there is a good chance that several
	 * colormap cells will map to the same indices of our 3/3/3 color cube). We also
	 * shouldn't overwrite requested colors with better cube-cell matches (hence the
	 * 'mp' check)
	 */
	if ( !(i|j|k) && blackSeen++ ) /* don't overwrite real black with avail cell */
	  continue;
	if ( ((*mp)[i][j][k] < 2) && (!(pix = map->pix [i][j][k]) || 
						  (colorDiff( r, g, b, rgb8[i], rgb8[j], rgb8[k]) <
						   colorDiff( map->rgb[pix].r, map->rgb[pix].g, map->rgb[pix].b,
									  rgb8[i], rgb8[j], rgb8[k]))) ) {
	  if ( (*mp)[i][j][k] ) /* prevent cube cell from being overwritten, again */
		(*mp)[i][j][k] ++;

	  map->pix [i][j][k] = l;
	  map->rgb[l].r = r;
	  map->rgb[l].g = g;
	  map->rgb[l].b = b;
	}
  }

  /* set cells of not-yet satisfied rgb requests */
  for ( i=0, j=0; (i<nReq) && (i<n); i++ ) {
	if ( req[i] ){
	  r = JRED( req[i]);
	  g = JGREEN( req[i]);
	  b = JBLUE( req[i]);

	  xclr.pixel = pixels[j++];
	  xclr.red   = r << 8;
	  xclr.green = g << 8;
	  xclr.blue  = b << 8;
	  XStoreColor( Tlk->dsp, cm, &xclr);

	  map->pix [JI8(r)] [JI8(g)] [JI8(b)] = xclr.pixel;
	  map->rgb[xclr.pixel].r = r;
	  map->rgb[xclr.pixel].g = g;
	  map->rgb[xclr.pixel].b = b;
	}
  }

  /*
   * initalize rest of cube cells by computing their nearest rgb value, optionally
   * allocating new cells for the worst mismatches (if there still are colors avail)
   */
  fillUpColorCube( map, cm, (n - j), pixels+j, mp );
}
Example #19
0
Colormap XtcwpCreateRGBColormap (Display *dpy, Window win)
/*****************************************************************************
create a colormap with an RGB color scale in contiguous cells
******************************************************************************
Input:
dpy		display
win		window
******************************************************************************
Notes:
The returned colormap is only created; the window's colormap attribute
is not changed, and the colormap is not installed by this function.
The returned colormap is a copy of the window's current colormap, but 
with an RGB color scale allocated in the range of contiguous cells
determined by XA_RGB_DEFAULT_MAP.  If it does not already exist,
XA_RGB_DEFAULT_MAP will be created.
******************************************************************************
Author:  Dave Hale, Colorado School of Mines, 09/29/90
*****************************************************************************/
{
	Screen *scr=XDefaultScreenOfDisplay(dpy);
	Window root=XRootWindowOfScreen(scr);
	Colormap cmap,wcmap;
	XStandardColormap scmap;
	XColor color;
	XWindowAttributes wa;
	unsigned long i,ncells,npixels;
	unsigned long bpixel,epixel,pixel[4096];
	
	/* determine beginning and ending pixels in contiguous range */
	bpixel = XtcwpGetFirstPixel(dpy);
	epixel = XtcwpGetLastPixel(dpy);
	if (epixel<=bpixel) return None;
	
	/* get standard colormap XA_RGB_DEFAULT_MAP */
	if (!XGetStandardColormap(dpy,root,&scmap,XA_RGB_DEFAULT_MAP))
		if (!XtcwpCreateRGBDefaultMap(dpy,&scmap))
			return None;
	
	/* determine window's current colormap */
	XGetWindowAttributes(dpy,win,&wa);
	wcmap = wa.colormap;
	
	/* create new colormap and allocate all cells read/write */
	cmap = XCreateColormap(dpy,win,DefaultVisualOfScreen(scr),AllocNone);
	ncells = CellsOfScreen(scr);
	XAllocColorCells(dpy,cmap,True,NULL,0,pixel,(unsigned int)ncells);
	
	/* copy color cells from window's colormap to new colormap */
	for (i=0; i<ncells; ++i) {
		if (i<bpixel || i>epixel) {
			color.pixel = i;
			XQueryColor(dpy,wcmap,&color);
			XFreeColors(dpy,cmap,&i,1,0);
			XAllocColor(dpy,cmap,&color);
		}
	}
	
	/* copy RGB color scale from XA_RGB_DEFAULT_MAP to new colormap */
	npixels = epixel-bpixel+1;
	for (i=0; i<npixels; ++i) {
		color.pixel = bpixel+i;
		XQueryColor(dpy,scmap.colormap,&color);
		XStoreColor(dpy,cmap,&color);
	}
	
	/* return colormap */
	return cmap;
}
Example #20
0
main()
{
      Window w2;

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);
      Screen *scr = DefaultScreenOfDisplay(dpy);

      // CreateWindow

      Window w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent,
			       CopyFromParent, CopyFromParent,
			       0, NIL);

      XDestroyWindow(dpy, w);

      // CreateWindow with arguments

      XSetWindowAttributes swa;
      swa.background_pixel = WhitePixelOfScreen(scr);
      swa.bit_gravity = NorthWestGravity;
      swa.border_pixel = BlackPixelOfScreen(scr);
      swa.colormap = DefaultColormapOfScreen(scr);
      swa.cursor = None;
      swa.win_gravity = NorthGravity;

      w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent,
			CopyFromParent, CopyFromParent,
			CWBackPixel | CWBitGravity | CWBorderPixel | CWColormap | CWCursor | CWWinGravity, 
			&swa);
      
      // CreateWindow with other arguments

      XDestroyWindow(dpy, w);

      Pixmap pixmap = XCreatePixmap(dpy, RootWindowOfScreen(scr), 45, 25, DefaultDepthOfScreen(scr));
      assert(pixmap);

      swa.background_pixmap = pixmap;
      swa.border_pixmap = pixmap;

      w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent,
			CopyFromParent, CopyFromParent,
			CWBackPixmap | CWBorderPixmap,
			&swa);
      
      // ChangeWindowAttributes

      swa.backing_planes = 0x1;
      swa.backing_pixel = WhitePixelOfScreen(scr);
      swa.save_under = True;
      swa.event_mask = KeyPressMask | KeyReleaseMask;
      swa.do_not_propagate_mask = ButtonPressMask | Button4MotionMask;
      swa.override_redirect = False;
      XChangeWindowAttributes(dpy, w, CWBackingPlanes | CWBackingPixel | CWSaveUnder | CWEventMask
			      | CWDontPropagate | CWOverrideRedirect, &swa);

      // GetWindowAttributes

      XWindowAttributes wa;
      Status success = XGetWindowAttributes(dpy, w, &wa);

      // DestroyWindow (done)

      // DestroySubwindows

      w2 = XCreateWindow(dpy, w, 20, 30, 40, 50, 3, CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL);
      XDestroySubwindows(dpy, w);

      // ChangeSaveSet

//        Display *dpy2 = XOpenDisplay(NIL);
//        assert(dpy2);
//        XAddToSaveSet(dpy2, w);
//        XCloseDisplay(dpy2);

      // ReparentWindow

      w2 = XCreateWindow(dpy, RootWindowOfScreen(scr), 20, 30, 40, 50, 3, 
			 CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL);
      XReparentWindow(dpy, w2, w, 10, 5);

      // MapWindow

      XMapWindow(dpy, w);

      // MapSubwindows
      
      XMapSubwindows(dpy, w);

      // UnmapWindow
      
      XUnmapWindow(dpy, w);

      // UnmapSubwindows

      XMapWindow(dpy, w);
      XUnmapSubwindows(dpy, w2);
      XMapSubwindows(dpy, w);

      // ConfigureWindow

      Window w3 = XCreateWindow(dpy, w, 10, 50, 100, 10, 2,
			 CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL);

      XMapWindow(dpy, w3);

      XWindowChanges wc;
      wc.x = -5;
      wc.y = -10;
      wc.width = 50;
      wc.height = 40;
      wc.border_width = 7;
      wc.sibling = w2;
      wc.stack_mode = Opposite;
      XConfigureWindow(dpy, w3, 
		       CWX | CWY | CWWidth | CWHeight | CWBorderWidth | CWSibling | CWStackMode, 
		       &wc);

      // CirculateWindow

      XCirculateSubwindows(dpy, w, RaiseLowest);

      // GetGeometry

      Window root;
      int x, y;
      unsigned width, height, border_width, depth;
      XGetGeometry(dpy, w, &root, &x, &y, &width, &height, &border_width, &depth);

      // QueryTree

      Window parent;
      Window *children;
      unsigned nchildren;
      success = XQueryTree(dpy, w, &root, &parent, &children, &nchildren);
      XFree(children);

      // InternAtom

      Atom a = XInternAtom(dpy, "WM_PROTOCOLS", True);

      // GetAtomName

      char *string = XGetAtomName(dpy, XA_PRIMARY);
      XFree(string);

      // ChangeProperty

      XStoreName(dpy, w, "test window");

      // DeleteProperty

      XDeleteProperty(dpy, w, XA_WM_NAME);

      // GetProperty
      // TODO

      // ListProperties

      int num_prop;
      Atom *list = XListProperties(dpy, w, &num_prop);
      XFree(list);

      // SetSelectionOwner

      XSetSelectionOwner(dpy, XA_PRIMARY, w, 12000);
      XSetSelectionOwner(dpy, XA_SECONDARY, w, CurrentTime);

      // GetSelectionOwner

      Window wx = XGetSelectionOwner(dpy, XA_PRIMARY);

      // ConvertSelection

      XConvertSelection(dpy, XA_SECONDARY, XA_CURSOR, XA_POINT, w, CurrentTime);

      // SendEvent

      // GrabPointer

      std::cerr << "Grabbing" << std::endl;
      int res = XGrabPointer(dpy, w, False, Button5MotionMask | PointerMotionHintMask,
			     GrabModeSync, GrabModeAsync, w, None, CurrentTime);
      XSync(dpy, False);
//      sleep(5);

      // UngrabPointer

      std::cerr << "Ungrabbing" << std::endl;
      XUngrabPointer(dpy, CurrentTime);

      // GrabButton

      XGrabButton(dpy, 3, ShiftMask | ControlMask, w, False, PointerMotionHintMask | Button2MotionMask, 
		  GrabModeAsync, GrabModeSync, None, None);
		  
      XGrabButton(dpy, 2, AnyModifier, w, False, PointerMotionHintMask | Button2MotionMask, 
		  GrabModeAsync, GrabModeSync, None, None);
		  
      // UngrabButton

      XUngrabButton(dpy, 2, LockMask, w);

      // ChangeActivePointerGrab

      XChangeActivePointerGrab(dpy, ButtonPressMask, None, CurrentTime);

      // GrabKeyboard

      XGrabKeyboard(dpy, w, True, GrabModeSync, GrabModeSync, 12000);

      // UngrabKeyboard

      XUngrabKeyboard(dpy, 13000);

      // GrabKey

      XGrabKey(dpy, XKeysymToKeycode(dpy, XK_Tab), ShiftMask | Mod3Mask, w, True, GrabModeSync,
	       GrabModeSync);

      // UngrabKey

      XUngrabKey(dpy, AnyKey, AnyModifier, w);

      // AllowEvents

      XAllowEvents(dpy, AsyncPointer, 14000);

      // GrabServer

      XGrabServer(dpy);

      // UngrabServer

      XUngrabServer(dpy);

      // QueryPointer

      Window child;
      int root_x, root_y, win_x, win_y;
      unsigned mask;
      Bool bres = XQueryPointer(dpy, w, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask);

      // GetMotionEvents

      int nevents;
      XGetMotionEvents(dpy, w, 15000, 16000, &nevents);

      // TranslateCoordinates

      int dest_x, dest_y;

      XTranslateCoordinates(dpy, w, w2, 10, 20, &dest_x, &dest_y, &child);

      // WarpPointer

      XWarpPointer(dpy, w, w2, 0, 0, 100, 100, 20, 30);

      // SetInputFocus

      XSetInputFocus(dpy,w, RevertToPointerRoot, 17000);
      XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, 17000);

      // GetInputFocus

      Window focus;
      int revert_to;
      XGetInputFocus(dpy, &focus, &revert_to);

      // QueryKeymap

      char keys_return[32];
      XQueryKeymap(dpy, keys_return);

      // OpenFont

      Font fid = XLoadFont(dpy, "cursor");

      // CloseFont

      XUnloadFont(dpy, fid);

      // QueryFont

      XFontStruct *fs = XLoadQueryFont(dpy, "cursor");
      assert(fs);

      // QueryTextExtents

      int direction, font_ascent, font_descent;
      XCharStruct overall;
      XQueryTextExtents(dpy, fs -> fid, "toto", 4, &direction, &font_ascent, &font_descent, &overall);
      XQueryTextExtents(dpy, fs -> fid, "odd__length", 11, &direction, &font_ascent, &font_descent, &overall);

      XChar2b c2bs;
      c2bs.byte1 = '$';
      c2bs.byte2 = 'B';
      XQueryTextExtents16(dpy, fs -> fid, &c2bs, 1, &direction, &font_ascent, &font_descent, &overall);

      XQueryTextExtents(dpy, fs -> fid, longString, strlen(longString), &direction, &font_ascent, 
			&font_descent, &overall);

      // ListFonts

      int actual_count;
      char **fontList = XListFonts(dpy, "*", 100, &actual_count);
      XFree((char *)fontList);

      // ListFontsWithInfo

      int count;
      XFontStruct *info;
      char **names = XListFontsWithInfo(dpy, "*", 100, &count, &info);
      XFreeFontInfo(names, info, count);

      // SetFontPath
      // GetFontPath

      int npaths;
      char **charList = XGetFontPath(dpy, &npaths);

      char **charList2 = new char *[npaths + 1];
      memcpy(charList2, charList, npaths * sizeof(char *));
      charList2[npaths] = charList2[0];

      XSetFontPath(dpy, charList2, npaths + 1);
      XSetFontPath(dpy, charList, npaths); // Reset to some reasonnable value

      XFreeFontPath(charList);
      delete [] charList2;

      // CreatePixmap

      Pixmap pix2 = XCreatePixmap(dpy, w, 100, 200, DefaultDepthOfScreen(scr));

      // FreePixmap

      XFreePixmap(dpy, pix2);

      // CreateGC

      Pixmap bitmap = XCreateBitmapFromData(dpy, RootWindowOfScreen(scr), 
					    "\000\000\001\000\000\001\000\000\001\377\377\377", 3, 4);

      XGCValues gcv;
      gcv.function = GXand;
      gcv.plane_mask = 0x1;
      gcv.foreground = WhitePixelOfScreen(scr);
      gcv.background = BlackPixelOfScreen(scr);
      gcv.line_width = 2;
      gcv.line_style = LineDoubleDash;
      gcv.cap_style = CapProjecting;
      gcv.join_style = JoinRound;
      gcv.fill_style = FillStippled;
      gcv.fill_rule = EvenOddRule;
      gcv.arc_mode = ArcPieSlice;
      gcv.tile = pixmap;
      gcv.stipple = bitmap;
      gcv.ts_x_origin = 3;
      gcv.ts_y_origin = 4;
      gcv.font = fs -> fid;
      gcv.subwindow_mode = ClipByChildren;
      gcv.graphics_exposures = True;
      gcv.clip_x_origin = 5;
      gcv.clip_y_origin = 6;
      gcv.clip_mask = bitmap;
      gcv.dash_offset = 1;
      gcv.dashes = 0xc2;
      
      GC gc = XCreateGC(dpy, w, 
			  GCFunction | GCPlaneMask | GCForeground | GCBackground | GCLineWidth
			| GCLineStyle | GCCapStyle | GCJoinStyle | GCFillStyle | GCFillRule | GCTile
			| GCStipple | GCTileStipXOrigin | GCTileStipYOrigin | GCFont | GCSubwindowMode
			| GCGraphicsExposures | GCClipXOrigin | GCClipYOrigin | GCClipMask | GCDashOffset
			| GCDashList | GCArcMode,
			&gcv);

      // ChangeGC

      gcv.function = GXandReverse;

      // Only a few of these should appear, since the values are cached on the client side by the Xlib.

      XChangeGC(dpy, gc, GCFunction | GCLineStyle | GCStipple | GCGraphicsExposures | GCDashList, &gcv);

      // CopyGC
      
      GC gc2 = XCreateGC(dpy, w, 0, NIL);
      XCopyGC(dpy, gc, GCFunction | GCLineStyle | GCStipple | GCGraphicsExposures | GCDashList, gc2);

      // SetDashes

      XSetDashes(dpy, gc, 3, "\001\377\001", 3);

      // SetClipRectangles

      XRectangle rectangles[] = { { 10, 20, 30, 40 }, { 100, 200, 5, 3 }, { -5, 1, 12, 24 } };
      XSetClipRectangles(dpy, gc, 12, 9, rectangles, SIZEOF(rectangles), Unsorted);

      // FreeGC

	    // done already

      // ClearArea

      XClearArea(dpy, w, 30, 10, 10, 100, False);

      // CopyArea

      XCopyArea(dpy, w, pixmap, gc, 0, 0, 100, 100, 10, 10);

      // CopyPlane

      // This won't work if the Screen doesn't have at least 3 planes
      XCopyPlane(dpy, pixmap, w, gc, 20, 10, 40, 30, 0, 0, 0x4);

      // PolyPoint

      XDrawPoint(dpy, w, gc, 1, 2);

      XPoint points[] = { { 3, 4 }, { 5, 6 } };
      XDrawPoints(dpy, w, gc, points, SIZEOF(points), CoordModeOrigin);

      // PolyLine

      XDrawLines(dpy, w, gc, points, SIZEOF(points), CoordModePrevious);

      // PolySegment

      XSegment segments[] = { { 7, 8, 9, 10 }, { 11, 12, 13, 14 }, { 15, 16, 17, 18 } };
      XDrawSegments(dpy, w, gc, segments, SIZEOF(segments));

      // PolyRectangle

      XDrawRectangles(dpy, w, gc, rectangles, SIZEOF(rectangles));

      // PolyArc

      XArc arcs[] = { { 10, 20, 30, 40, 50, 60 }, { -70, 80, 90, 100, 110, 120 }, 
		      { 10, 20, 30, 40, 50, -30 } };

      XDrawArcs(dpy, w, gc, arcs, SIZEOF(arcs));

      // FillPoly

      XFillPolygon(dpy, w, gc, points, SIZEOF(points), Convex, CoordModePrevious);

      // PolyFillRectangle
      
      XFillRectangles(dpy, w, gc, rectangles, SIZEOF(rectangles));

      // PolyFillArc
      
      XFillArcs(dpy, w, gc, arcs, SIZEOF(arcs));

      // PutImage
      // GetImage

      XImage *image = XGetImage(dpy, w, 10, 20, 40, 30, AllPlanes, ZPixmap);
      XPutImage(dpy, w, gc, image, 0, 0, 50, 60, 40, 30);
      XSync(dpy, False); // Make the next request starts at the beginning of a packet

      // PolyText8
      XTextItem textItems[3];
      textItems[0].chars = "toto";
      textItems[0].nchars = strlen(textItems[0].chars);
      textItems[0].delta = -3;
      textItems[0].font = fs->fid;
      textItems[1].chars = "titi";
      textItems[1].nchars = strlen(textItems[1].chars);
      textItems[1].delta = 3;
      textItems[1].font = None;
      textItems[2].chars = "tutu";
      textItems[2].nchars = strlen(textItems[2].chars);
      textItems[2].delta = 0;
      textItems[2].font = fs->fid;

      XDrawText(dpy, w, gc, 10, 10, textItems, 3);


      XTextItem textItems2[3];
      textItems2[0].chars = "totox";
      textItems2[0].nchars = strlen(textItems2[0].chars);
      textItems2[0].delta = -3;
      textItems2[0].font = fs->fid;
      textItems2[1].chars = "titi";
      textItems2[1].nchars = strlen(textItems2[1].chars);
      textItems2[1].delta = 3;
      textItems2[1].font = None;
      textItems2[2].chars = "tutu";
      textItems2[2].nchars = strlen(textItems2[2].chars);
      textItems2[2].delta = 0;
      textItems2[2].font = fs->fid;

      XDrawText(dpy, w, gc, 10, 10, textItems2, 3);

      // PolyText16

      XChar2b c2b2[] = { 0, 't', 0, 'x' };

      XTextItem16 items16[] = { { &c2bs, 1, -5, None }, { NULL, 0, 0, None }, { c2b2, 2, 0, fs -> fid } };
      XDrawText16(dpy, w, gc, 10, 0, items16, SIZEOF(items16));

      // ImageText8

      XDrawImageString(dpy, w, gc, 10, 10, "toto", 4);

      // ImageText16

      XDrawImageString16(dpy, w, gc, 10, 10, &c2bs, 1);
      XDrawImageString16(dpy, w, gc, 10, 20, c2b2, 2);

      // CreateColormap
      // Don't forget to tell the kids how it was when we had only 8 bits per pixel.

      Colormap colormap = XCreateColormap(dpy, w, DefaultVisualOfScreen(scr), None);

      // FreeColormap

      XFreeColormap(dpy, colormap);
      colormap = XCreateColormap(dpy, w, DefaultVisualOfScreen(scr), None);

      // CopyColormapAndFree

      Colormap colormap2 = XCopyColormapAndFree(dpy, colormap);

      // InstallColormap

      XInstallColormap(dpy, colormap2);

      // UninstallColormap

      XUninstallColormap(dpy, colormap2);

      // ListInstalledColormaps

      int num;
      Colormap *colormapList = XListInstalledColormaps(dpy, w, &num);

      // AllocColor

      XColor screen;
      screen.red = 0;
      screen.green = 32767;
      screen.blue = 65535;
      screen.flags = DoRed | DoGreen | DoBlue;
      success = XAllocColor(dpy, colormap, &screen);

      // AllocNamedColor

      XColor screen2, exact;
      success = XAllocNamedColor(dpy, colormap, "Wheat", &screen2, &exact);

      // AllocColorCells

      unsigned long plane_masks, pixels;
      success = XAllocColorCells(dpy, colormap, False, &plane_masks, 1, &pixels, 1);

      // AllocColorPlanes

      unsigned long rmask, gmask, bmask;
      success = XAllocColorPlanes(dpy, colormap, False, &pixels, 1, 0, 0, 0, &rmask, &gmask, &bmask);

      // FreeColors

      unsigned long pixels2[2] = { screen.pixel, screen2.pixel };
      XFreeColors(dpy, colormap, pixels2, 2, 0);

      // StoreColors

      success = XAllocColorCells(dpy, colormap, False, NIL, 0, pixels2, 2);

      // On many contemporary (that is, year 2000) video cards, you can't allocate read / write cells
      // I want my requests to be sent, however.
      if (!success) {
	    XSetErrorHandler(errorHandler);
      }

      XColor colors[2];
      colors[0] = screen;  colors[0].pixel = pixels2[0];
      colors[1] = screen2; colors[1].pixel = pixels2[1];
      XStoreColors(dpy, colormap, colors, 2);

      // StoreNamedColor

      XStoreNamedColor(dpy, colormap, "Wheat", colors[0].pixel, DoBlue);

      XSync(dpy, False);
      XSetErrorHandler(NIL); // Restore the default handler

      // QueryColors

      screen2.pixel = WhitePixelOfScreen(scr);
      XQueryColor(dpy, colormap, &screen2);

      // LookupColor

      success = XLookupColor(dpy, colormap, "DarkCyan", &exact, &screen);

      // CreateCursor

      Cursor cursor = XCreatePixmapCursor(dpy, pixmap, None, &exact, colors, 10, 10);

      // CreateGlyphCursor
      
      Cursor cursor2 = XCreateGlyphCursor(dpy, fs -> fid, fs -> fid, 'X', 0, &exact, colors);

      // FreeCursor
      
      XFreeCursor(dpy, cursor2);

      // RecolorCursor

      XRecolorCursor(dpy, cursor, colors, &exact);

      // QueryBestSize

      success = XQueryBestSize(dpy, CursorShape, RootWindowOfScreen(scr), 100, 20, &width, &height);

      // QueryExtension

      int major_opcode, first_event, first_error;
      XQueryExtension(dpy, "toto", &major_opcode, &first_event, &first_error);

      // ListExtensions

      int nextensions;
      char **extensionList = XListExtensions(dpy, &nextensions);
      for(char **p = extensionList; nextensions; nextensions--, p++) std::cout << *p << std::endl;
      XFree(extensionList);

      // ChangeKeyboardMapping
      // GetKeyboardMapping

      int min_keycodes, max_keycodes;
      XDisplayKeycodes(dpy, &min_keycodes, &max_keycodes);

      int keysyms_per_keycode;
      KeySym *keysyms = XGetKeyboardMapping(dpy, min_keycodes, max_keycodes - min_keycodes + 1,
					    &keysyms_per_keycode);
      XChangeKeyboardMapping(dpy, min_keycodes, keysyms_per_keycode, keysyms, 
			     max_keycodes - min_keycodes + 1);

      // ChangeKeyboardControl
      // GetKeyboardControl

      XKeyboardState keyboardState;
      XGetKeyboardControl(dpy, &keyboardState);

      XKeyboardControl keyboardValues;
      keyboardValues.key_click_percent = keyboardState.key_click_percent;
      keyboardValues.bell_percent = keyboardState.bell_percent;
      keyboardValues.bell_pitch = keyboardState.bell_pitch;
      keyboardValues.bell_duration = keyboardState.bell_duration;
      keyboardValues.led = 1;
      keyboardValues.led_mode = LedModeOn;
      keyboardValues.key = min_keycodes;
      keyboardValues.auto_repeat_mode = AutoRepeatModeDefault;
      XChangeKeyboardControl(dpy, 
			       KBKeyClickPercent | KBBellPercent | KBBellPitch | KBBellDuration
			     | KBLed | KBLedMode | KBKey | KBAutoRepeatMode,
			     &keyboardValues);

      // Bell

      XBell(dpy, 90);

      // ChangePointerControl
      // GetPointerControl

      int accel_numerator, accel_denominator, threshold;
      XGetPointerControl(dpy, &accel_numerator, &accel_denominator, &threshold);

      XChangePointerControl(dpy, True, True, accel_numerator, accel_denominator, threshold);

      // SetScreenSaver
      // GetScreenSaver

      int timeout, interval, prefer_blanking, allow_exposures;
      XGetScreenSaver(dpy, &timeout, &interval, &prefer_blanking, &allow_exposures);
      XSetScreenSaver(dpy, timeout, interval, prefer_blanking, allow_exposures);

      // ChangeHosts
      // ListHosts

      int nhosts;
      Bool state;
      XHostAddress *hostList = XListHosts(dpy, &nhosts, &state);

      XHostAddress host;
      host.family = FamilyInternet;
      host.length = 4;
      host.address = "\001\002\003\004";
      XAddHost(dpy, &host);

      // SetAccessControl

      XSetAccessControl(dpy, EnableAccess);

      // SetCloseDownMode

      XSetCloseDownMode(dpy, RetainTemporary);

      // KillClient

      XKillClient(dpy, AllTemporary);

      // RotateProperties

      Atom properties[] = { XInternAtom(dpy, "CUT_BUFFER0", False), 
			    XInternAtom(dpy, "CUT_BUFFER1", False),
			    XInternAtom(dpy, "CUT_BUFFER2", False) };
      XRotateWindowProperties(dpy, RootWindowOfScreen(scr), properties, SIZEOF(properties), -1);

      // ForceScreenSaver

      XForceScreenSaver(dpy, ScreenSaverReset);

      // SetPointerMapping
      // GetPointerMapping

      unsigned char map[64];
      int map_length = XGetPointerMapping(dpy, map, 64);
      XSetPointerMapping(dpy, map, map_length);

      // SetModifierMapping
      // GetModifierMapping

      XModifierKeymap *modmap = XGetModifierMapping(dpy);
      XSetModifierMapping(dpy, modmap);

      // NoOperation

      XNoOp(dpy);

      for(;;) {
	    XEvent e;
	    XNextEvent(dpy, &e);
	    std::cout << "Got an event of type " << e.type << std::endl;
      }
}
Example #21
0
Colormap XtcwpCreateGrayColormap (Display *dpy, Window win)
/*****************************************************************************
create a colormap with a gray scale in contiguous cells
******************************************************************************
Input:
dpy		display
win		window
******************************************************************************
Notes:
The returned colormap is only created; the window's colormap attribute
is not changed, and the colormap is not installed by this function.
The returned colormap is a copy of the window's current colormap, but 
with a gray scale (black to white) allocated in the range of contiguous
cells determined by XA_RGB_DEFAULT_MAP.  If it does not already exist,
XA_RGB_DEFAULT_MAP will be created.
******************************************************************************
Author:  Dave Hale, Colorado School of Mines, 09/29/90
*****************************************************************************/
{
	Screen *scr=XDefaultScreenOfDisplay(dpy);
	Colormap cmap,wcmap;
	XColor color;
	XWindowAttributes wa;
	unsigned long i,ncells,npixels;
	unsigned long bpixel,epixel,pixel[4096];
	
	/* determine beginning and ending pixels in contiguous range */
	bpixel = XtcwpGetFirstPixel(dpy);
	epixel = XtcwpGetLastPixel(dpy);
	if (epixel<=bpixel) return None;
	
	/* determine window's current colormap */
	XGetWindowAttributes(dpy,win,&wa);
	wcmap = wa.colormap;
	
	/* create new colormap and allocate all cells read/write */
	cmap = XCreateColormap(dpy,win,DefaultVisualOfScreen(scr),AllocNone);
	ncells = CellsOfScreen(scr);
	XAllocColorCells(dpy,cmap,True,NULL,0,pixel,(unsigned int)ncells);
	
	/* copy color cells from window's colormap to new colormap */
	for (i=0; i<ncells; ++i) {
		if (i<bpixel || i>epixel) {
			color.pixel = i;
			XQueryColor(dpy,wcmap,&color);
			XFreeColors(dpy,cmap,&i,1,0);
			XAllocColor(dpy,cmap,&color);
		}
	}
	
	/* build gray scale in contiguous cells in new colormap */
	npixels = epixel-bpixel+1;
	for (i=0; i<npixels; ++i) {
		color.pixel = bpixel+i;
		color.red = (unsigned short) (65535*i/(npixels-1));
		color.green = color.red;
		color.blue = color.red;
		color.flags = DoRed|DoGreen|DoBlue;
		XStoreColor(dpy,cmap,&color);
	}
	
	/* return colormap */
	return cmap;
}
Example #22
0
Colormap XtcwpCreateHueColormap (Display *dpy, Window win,
	float fhue, float lhue, float sat, float bright)
/*****************************************************************************
create a colormap with varying hues (user-specified) in contiguous cells
******************************************************************************
Input:
dpy		display
win		window
fhue		first hue in colormap
lhue		last hue in colormap
sat		saturation
bright		brightness
******************************************************************************
Notes:
The returned colormap is only created; the window's colormap attribute
is not changed, and the colormap is not installed by this function.
The returned colormap is a copy of the window's current colormap, but 
with varying hues (blue to red) allocated in the range of contiguous
cells determined by XA_RGB_DEFAULT_MAP.  If it does not already exist,
XA_RGB_DEFAULT_MAP will be created.
******************************************************************************
Author:  Dave Hale, Colorado School of Mines, 09/29/90
Modified:  Craig Artley, Colorado School of Mines, 11/22/93
	   Saturation, brightness, and range of hues now user-specified.
*****************************************************************************/
{
	Screen *scr=XDefaultScreenOfDisplay(dpy);
	Colormap cmap,wcmap;
	XColor color;
	XWindowAttributes wa;
	unsigned long i,ncells,npixels;
	unsigned long bpixel,epixel,pixel[4096];
	float red=0,green=0,blue=0;

	/* determine beginning and ending pixels in contiguous range */
	bpixel = XtcwpGetFirstPixel(dpy);
	epixel = XtcwpGetLastPixel(dpy);
	if (epixel<=bpixel) return None;

	/* determine window's current colormap */
	XGetWindowAttributes(dpy,win,&wa);
	wcmap = wa.colormap;

	/* create new colormap and allocate all cells read/write */
	cmap = XCreateColormap(dpy,win,DefaultVisualOfScreen(scr),AllocNone);
	ncells = CellsOfScreen(scr);
	XAllocColorCells(dpy,cmap,True,NULL,0,pixel,(unsigned int) ncells);

	/* copy color cells from window's colormap to new colormap */
	for (i=0; i<ncells; ++i) {
		if (i<bpixel || i>epixel) {
			color.pixel = i;
			XQueryColor(dpy,wcmap,&color);
			XFreeColors(dpy,cmap,&i,1,0);
			XAllocColor(dpy,cmap,&color);
		}
	}

	/* build hues in contiguous cells in new colormap */
	npixels = epixel-bpixel+1;
	for (i=0; i<npixels; ++i) {
		color.pixel = bpixel+i;
		hsvrgb(fhue+(lhue-fhue)*((float)i)/((float)(npixels-1)),sat,bright,
			&red,&green,&blue);
		color.red = 65535*red;
		color.green = 65535*green;
		color.blue = 65535*blue;
		color.flags = DoRed|DoGreen|DoBlue;
		XStoreColor(dpy,cmap,&color);
	}

	/* return colormap */
	return cmap;
}
Example #23
0
  int main (void)
  {
    int i;
  
    int allocateOK;
  
    ximg = NULL;
  
  	
    d = XOpenDisplay (NULL);
  
    if (!d)
      fputs ("Couldn't open display\n", stderr), exit (1);
  
    screen = DefaultScreen (d);
    gc = DefaultGC (d, screen);
  
    /* Find a visual */
  
    vis.screen = screen;
    vlist = XGetVisualInfo (d, VisualScreenMask, &vis, &match);
  
    if (!vlist)
      fputs ("No matched visuals\n", stderr), exit (1);
  
    vis = vlist[0];
    XFree (vlist);
		
  	// That's not a fair comparison colormap_size is depth in bits!
    // if (vis.colormap_size < COLORS)
      // printf("Colormap is too small: %i.\n",vis.colormap_size); // , exit (1);
		printf("Colour depth: %i\n",vis.colormap_size);
  
    win = XCreateSimpleWindow (d, DefaultRootWindow (d),
			       0, 0, WIN_W, WIN_H, 0,
			       WhitePixel (d, screen), BlackPixel (d, screen));
  
	  int xclass=get_xvisinfo_class(vis);
		// printf("class = %i\n",xclass);
	  stylee = ( vis.depth > 8 ? styleeTrueColor : styleePrivate );
	  // printf("stylee=%i\n",stylee);
  
    if ( get_xvisinfo_class(vis) % 2 == 1) {	/* The odd numbers can redefine colors */
  
			  // printf("%i\n",get_xvisinfo_class(vis));
	  	
      colormap = DefaultColormap (d, screen);
		  Visual *defaultVisual=DefaultVisual(d,screen);
	  	
      /* Allocate cells */
      allocateOK = (XAllocColorCells (d, colormap, 1,
							      NULL, 0, color, COLORS) != 0);

			// printf("Allocated OK? %i\n",allocateOK);
			
      if (allocateOK) {
  
			  // printf("Allocated OK\n");
        // This doesn't work for installed colormap!
  
        /* Modify the colorcells */
        for (i = 0; i < COLORS; i++)
				  xrgb[i].pixel = color[i];
  
        XStoreColors (d, colormap, xrgb, COLORS);
  
		  } else {

			  colormap = XCreateColormap(d,win,defaultVisual,AllocNone);
		  	
    	  // redocolors();
					  	
      }
  
		  // black = XBlackPixel(d,screen);
		  // white = XWhitePixel(d,screen);
  
    } else if ( get_xvisinfo_class(vis) == TrueColor) {
      colormap = DefaultColormap (d, screen);
					  // printf("TrueColor %i = %i\n",xclass,TrueColor);
      /* This will lookup the color and sets the xrgb[i].pixel value */
      // for (i = 0; i < COLORS; i++)
        // XAllocColor (d, colormap, &xrgb[i]);
    } else
      fprintf (stderr, "Not content with visual class %d.\n",
	       get_xvisinfo_class(vis) ), exit (1);
  
    /* Find out if MITSHM is supported and useable */
    printf ("MITSHM: ");
  
    if (XShmQueryVersion (d, &mitshm_major_code,
			  &mitshm_minor_code, &shared_pixmaps)) {
      int (*handler) (Display *, XErrorEvent *);
      ximg = XShmCreateImage (d, vis.visual,
			     vis.depth, XShmPixmapFormat (d),
			     NULL, &shminfo, WIN_W, WIN_H);
      shminfo.shmid = shmget (IPC_PRIVATE,
			      ximg->bytes_per_line * ximg->height,
			      IPC_CREAT | 0777);
      shminfo.shmaddr = (char *)shmat (shminfo.shmid, 0, 0);
		  ximg->data = (char *)shminfo.shmaddr;
  
      handler = XSetErrorHandler (mitshm_handler);
      XShmAttach (d, &shminfo);	/* Tell the server to attach */
      XSync (d, 0);
      XSetErrorHandler (handler);
  
      shmctl (shminfo.shmid, IPC_RMID, 0);
      /* Mark this shm segment for deletion at once. The segment will
       * automatically become released when both the server and this
       * client have detached from it.
       * (Process termination automagically detach shm segments) */
  
      if (!can_use_mitshm) {
        shmdt (shminfo.shmaddr);
        ximg = NULL;
      }
    }
  
    if (ximg == NULL) {
      can_use_mitshm = 0;
      /* XInitImage(ximg); */
      ximg = XCreateImage (d, vis.visual, vis.depth, ZPixmap,
			  0, (char *)malloc (WIN_W * WIN_H), WIN_W, WIN_H, 8, 0);
    }
  
    if (can_use_mitshm)
      printf ("YES!\n");
    else
      printf ("NO, using fallback instead.\n");
  
    // DrawFractal (ximg,xrgb);
  
    XSelectInput (d, win, ButtonPressMask | ExposureMask);
    XMapWindow (d, win);
  
  
  
  
    real_main();


  
      // XNextEvent (d, &ev);
      // switch (ev.type) {
      // case ButtonPress:
        // should_quit = 1;
        // break;
      // case Expose:
        // if (can_use_mitshm)
				  // XShmPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H, True);
        // else
				  // XPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H);
        // break;
      // default:
			  // break;
      // }
  
  
  
    if (get_xvisinfo_class(vis) % 2 == 1 || get_xvisinfo_class(vis) == TrueColor) {
      unsigned long color[COLORS];
  
      if (allocateOK) {
        for (i = 0; i < COLORS; i++)
				  color[i] = xrgb[i].pixel;
        XFreeColors (d, colormap, color, COLORS, 0);
      }				/* Allocated colors freed */
    } else {
      XUninstallColormap (d, colormap);
    }
  
    if (can_use_mitshm) {
      XShmDetach (d, &shminfo);	/* Server detached */
      XDestroyImage (ximg);	/* Image struct freed */
      shmdt (shminfo.shmaddr);	/* We're detached */
    } else
      XDestroyImage (ximg);	/* Image struct freed */
  
    XDestroyWindow (d, win);	/* Window removed */
    XCloseDisplay (d);		/* Display disconnected */
  
    /* So you can see how your computer compares to your friend's */
    getrusage (RUSAGE_SELF, &resource_utilization);
		float seconds=(float)resource_utilization.ru_utime.tv_sec
						     +(float)resource_utilization.ru_utime.tv_usec*0.000000001;
		printf("CPU seconds per frame: %f\n",seconds/(float)frameno);
    // printf ("CPU seconds consumed: %ds and %dµs\n",
	    // (int) resource_utilization.ru_utime.tv_sec,
	    // (int) resource_utilization.ru_utime.tv_usec);
  
    return 0;
  }
Example #24
0
void init_3DView_cmap(
Widget	w)
{
  Display		*dpy = XtDisplay( w );
  Colormap		cmap;
  unsigned long		plane_masks[1], free_pixels[256];
  unsigned int		n_free_pixels;
  unsigned long		min_required_val, max_required_val;
  XColor		colorcells[256];
  int			i, j;

  /* allocate the colours we need */
  n_free_pixels = 0;
  min_required_val = 64;
  max_required_val = 255;
  cmap = globals.cmap;

  for(i=0; i < 256; i++){
    
    if( XAllocColorCells(dpy, cmap, False, plane_masks,
			 0, &(free_pixels[n_free_pixels]), 1) == 0 )
      continue;
    
    /* check if required */
    if(free_pixels[n_free_pixels] >= min_required_val &&
       free_pixels[n_free_pixels] <= max_required_val){
      continue;
    } else {
      n_free_pixels++;
    }
  }

  /* free unwanted colorcells */
  XFreeColors(dpy, cmap, free_pixels, n_free_pixels, 0);


  /* set 64-127 to greys */
  for(i=0, j=64; j < 128; i++, j++){
    colorcells[i].red   = (j - 64) * 4 * 256;
    colorcells[i].green = (j - 64) * 4 * 256;
    colorcells[i].blue  = (j - 64) * 4 * 256;
    colorcells[i].pixel = j;
    colorcells[i].flags = DoRed | DoGreen | DoBlue;
  }

  /* set a load of colors for the remaining values
     so that the drawn polylines are visible */
  for(; j < 255; i++, j++){
    colorcells[i].red   = ((j%3)?0:255) * 256;
    colorcells[i].green = (((j+1)%3)?0:255) * 256;
    colorcells[i].blue  = (((j+2)%3)?0:255) * 256;
    colorcells[i].pixel = j;
    colorcells[i].flags = DoRed | DoGreen | DoBlue;
  }

  XStoreColors(dpy, cmap, colorcells, i);

  /* set a few extra colors */
  (void) HGU_XGetColorPixel(XtDisplay(w), cmap, 1.0, 0.0, 0.0);
  (void) HGU_XGetColorPixel(XtDisplay(w), cmap, 0.0, 1.0, 0.0);
  (void) HGU_XGetColorPixel(XtDisplay(w), cmap, 0.0, 0.0, 1.0);

  return;
}
Example #25
0
Colormap XtcwpCreateSatColormap (Display *dpy, Window win,
	float fhue, float lhue, float wfrac, float bright)
/*****************************************************************************
create a colormap with varying saturations in contiguous cells
******************************************************************************
Input:
dpy		display
win		window
fhue		first hue in colormap (saturation=1)
lhue		last hue in colormap (saturation=1)
wfrac		fractional position of white within the colormap (saturation=0)
bright		brightness
******************************************************************************
Notes:
The returned colormap is only created; the window's colormap attribute
is not changed, and the colormap is not installed by this function.
The returned colormap is a copy of the window's current colormap, but 
with varying hues (blue to red) allocated in the range of contiguous
cells determined by XA_RGB_DEFAULT_MAP.  If it does not already exist,
XA_RGB_DEFAULT_MAP will be created.
******************************************************************************
Author:  Craig Artley, Colorado School of Mines, 11/22/93
*****************************************************************************/
{
	Screen *scr=XDefaultScreenOfDisplay(dpy);
	Colormap cmap,wcmap;
	XColor color;
	XWindowAttributes wa;
	unsigned long i,j,ncells,npixels,nfpixels,nlpixels;
	unsigned long bpixel,epixel,pixel[4096];
	long  ltemp;
	float red=0,green=0,blue=0;

	/* determine beginning and ending pixels in contiguous range */
	bpixel = XtcwpGetFirstPixel(dpy);
	epixel = XtcwpGetLastPixel(dpy);
	if (epixel<=bpixel) return None;

	/* determine window's current colormap */
	XGetWindowAttributes(dpy,win,&wa);
	wcmap = wa.colormap;

	/* create new colormap and allocate all cells read/write */
	cmap = XCreateColormap(dpy,win,DefaultVisualOfScreen(scr),AllocNone);
	ncells = CellsOfScreen(scr);
	XAllocColorCells(dpy,cmap,True,NULL,0,pixel,(unsigned int) ncells);

	/* copy color cells from window's colormap to new colormap */
	for (i=0; i<ncells; ++i) {
		if (i<bpixel || i>epixel) {
			color.pixel = i;
			XQueryColor(dpy,wcmap,&color);
			XFreeColors(dpy,cmap,&i,1,0);
			XAllocColor(dpy,cmap,&color);
		}
	}

	/* devide colormap into 3 regions: fhues, white, and lhues */
	npixels = epixel-bpixel+1;
	ltemp = (long) (wfrac*((float) npixels));
	nfpixels = (ltemp<0) ? 0: ltemp;
	if (nfpixels>npixels-1) nfpixels = npixels-1;
	nlpixels = npixels-nfpixels-1;

	/* pixels from fhue to just under white */
	for (i=0; i<nfpixels; ++i) {
		color.pixel = bpixel+i;
		hsvrgb(fhue,((float)(nfpixels-i))/((float) nfpixels),bright,
			&red,&green,&blue);
		color.red = 65535*red;
		color.green = 65535*green;
		color.blue = 65535*blue;
		color.flags = DoRed|DoGreen|DoBlue;
		XStoreColor(dpy,cmap,&color);
	}

	/* white pixel */
	color.pixel = bpixel+i;
	hsvrgb(fhue,0.0,bright,&red,&green,&blue);
	color.red = 65535*red;
	color.green = 65535*green;
	color.blue = 65535*blue;
	color.flags = DoRed|DoGreen|DoBlue;
	XStoreColor(dpy,cmap,&color);
	++i;

	/* pixels from just under white to lhue */
	for (j=0; j<nlpixels; ++i,++j) {
		color.pixel = bpixel+i;
		hsvrgb(lhue,((float)(j+1))/((float) nlpixels),bright,&red,&green,&blue);
		color.red = 65535*red;
		color.green = 65535*green;
		color.blue = 65535*blue;
		color.flags = DoRed|DoGreen|DoBlue;
		XStoreColor(dpy,cmap,&color);
	}

	/* return colormap */
	return cmap;
}
Example #26
0
static BOOL CreateDeviceColormap(Display *display, int screen,
	int minplanes, int maxplanes)
{
	int i, j;
	unsigned long *pixels, planes[32];

	/* pass 1: allocate colors from default colormap
	 * pass 2: create colormap & allocate colors from new colormap
	 */
	DeviceColormapSize = (XDefaultVisual(display, screen))->map_entries;
	for (i = 0; i < 2; i++)
	{
		/* pass 1: get default colormap
		 * pass 2: create custom colormap
		 */
		if (i == 0)
		{
			DeviceColormap = XDefaultColormap(display, screen);
		}
		else
		{
			DeviceColormap = XCreateColormap(display,
				XRootWindow(display, screen),
				XDefaultVisual(display, screen),
				AllocNone);
		}
		/* pass 1: save default colormap colors for pass 2
		 * pass 2: initialize with default colormap colors to minimize
		 *	   techni-color(tm) effect
		 */
		if (i == 0)
		{
			DeviceColormapValues = (XColor *)
				WinMalloc(DeviceColormapSize * sizeof(XColor));
			for (j = 0; j < DeviceColormapSize; j++)
			{
				DeviceColormapValues[j].pixel = j;
			}
			XQueryColors(display, DeviceColormap,
				DeviceColormapValues,
				DeviceColormapSize);
		}
		else
		{
			pixels = (unsigned long *) WinMalloc(DeviceColormapSize *
				sizeof(unsigned long));
			XAllocColorCells(display, DeviceColormap, True,
				planes, 0, pixels, DeviceColormapSize);
			XStoreColors(display, DeviceColormap,
				DeviceColormapValues,
				DeviceColormapSize);
			XFreeColors(display, DeviceColormap, pixels,
				DeviceColormapSize, 0L);
		}
		/* allocate as many color planes as possible */
		if ((minplanes < 1) || (maxplanes < 1))
			break;
		for (j = maxplanes; j >= minplanes; j--)
		{
			if (!XAllocColorCells(display, DeviceColormap, True,
				pixel_masks, j, &pixel0, 1))
			{
				continue;
			}
			pixel_numplanes = j;
			pixel_mask0 = ~0;
			for (pixel_mask = 0, j = 0; j < pixel_numplanes; j++)
			{
				pixel_mask |= pixel_masks[j];
				pixel_mask0 = min(pixel_mask0, pixel_masks[j]);
			}
			break;
		}
		if (j >= minplanes)
			break;
	}
	if (i == 2)
	{
		ERRSTR((LF_WARNING, 
			"%s: Unable to alloc %d to %d planes.\n",
			"CreateDeviceColormap",
			minplanes, maxplanes));
		return (FALSE);
	}

	/* success */
	return (TRUE);

}
Example #27
0
void
WindowDevice::initWindow(void) {
    // set the display and screen variables
#ifdef _UNIX
    theDisplay = XOpenDisplay("");	// init a display connection
    if (theDisplay == 0) {              // and check we got one
	opserr << "WindowDevice::initX11() - could not connect to display\n";
	exit(-1);
    }

    theScreen = DefaultScreen(theDisplay);
    
    // set the defualt foreground and background colors
    //    foreground = BlackPixel(theDisplay, theScreen);
    // background = WhitePixel(theDisplay, theScreen);    

    // lets try using the default colormap
    cmap = DefaultColormap(theDisplay, theScreen);

    // we now try to allocate some color cells from the colormap
    // we start by tring to obtain 256 colors, then 192, finally 64
    // if we can't get these (and as a last resort) we create a new color map

    if (XAllocColorCells(theDisplay, cmap, false, NULL, 0, pixels, 256) != 0) {
	// we were able to allocate 256 colors from the table for our use
	colorFlag = 0;
	int cnt = 0;
	for (int red =0; red <8; red++) {
	    for (int green = 0; green<8; green++) {
		for (int blue =0; blue<4; blue++) {
		    colors[cnt].pixel = pixels[32*red + 4*green + blue];
		    colors[cnt].red = (65536/7)*red;
		    colors[cnt].green = (65536/7)*green;
		    colors[cnt].blue = (65536/3)*blue;
		    colors[cnt].flags = DoRed | DoGreen | DoBlue;
		    cnt++;
		}			
	    }
	}
	XStoreColors(theDisplay, cmap, colors, cnt);
	foreground = pixels[0];
	background = pixels[255];
	
    } else if (XAllocColorCells(theDisplay, cmap, false, NULL, 0, pixels, 192) != 0) {
	// we were able to allocate 192 colors from the table for our use	
	colorFlag = 1;	
	int cnt = 0;
	for (int red =0; red <8; red++) {
	    for (int green = 0; green<6; green++) {
		for (int blue =0; blue<4; blue++) {
		    colors[cnt].pixel = pixels[24*red + 4*green + blue];
		    colors[cnt].red = (65536/7)*red;
		    colors[cnt].green = (65536/5)*green;
		    colors[cnt].blue = (65536/3)*blue;
		    colors[cnt].flags = DoRed | DoGreen | DoBlue;
		    cnt++;
		}			
	    }
	}
	XStoreColors(theDisplay, cmap, colors, cnt);
	foreground = pixels[0];
	background = pixels[191];
    } else if (XAllocColorCells(theDisplay, cmap, false, NULL, 0, pixels, 64) != 0) {
	colorFlag = 2;	
	int cnt = 0;
	for (int red =0; red <4; red++) {
	    for (int green = 0; green<4; green++) {
		for (int blue =0; blue<4; blue++) {
		    colors[cnt].pixel = pixels[16*red + 4*green + blue];
		    colors[cnt].red = (65536/3)*red;
		    colors[cnt].green = (65536/3)*green;
		    colors[cnt].blue = (65536/3)*blue;
		    colors[cnt].flags = DoRed | DoGreen | DoBlue;
		    cnt++;
		}			
	    }
	}
	XStoreColors(theDisplay, cmap, colors, cnt);
	foreground = pixels[0];
	background = pixels[63];
    } else {
	colorFlag = 3;
	// lets create our own color table - 
	// problem with this is that screen colors change as we enter
	opserr << "WindowDevice::initWindow() - could not add any colors to the\n";
	opserr << "existing colormap - will try to create our own colormap\n";
    }
#else


#endif
}    
Example #28
0
XilLookup XILWindowAssistor::create_cmap(
    Colormap *cmap, int type, XilIndexList *ilist, 
    XilLookup yuvtorgb, XilLookup colorcube
) {
    unsigned long tmp_colors[256], pixels[256], mask;
    XColor	cdefs[256];
    int		top_colors = 2;	/* colormap indices 255 and 254 */
    int		i, t;
    Xil_unsigned8 *data;
    XilLookup	lut;
    int		cmapsize;
    Display	*display = Tk_Display(window_->tkwin());
    Window	window = Tk_WindowId(window_->tkwin());
    int		screen = Tk_ScreenNumber(window_->tkwin());

    //fprintf(stderr,"XILWindowAssistor::"__FUNCTION__"\n");

    /* Get colormap size */
    switch(type)
    {
    case FT_JPEG:
    case FT_H261:
        cmapsize = xil_lookup_get_num_entries(yuvtorgb);
        break;

    case FT_CELLB:
    default: /* hmm */
        xil_cis_get_attribute(cis_,"DECOMPRESSOR_MAX_CMAP_SIZE", (void**)&cmapsize);
        break;
    } 

    /* Create an X colormap for the cis.*/
    *cmap = XCreateColormap(display, window, DefaultVisual(display,screen), AllocNone);

    /* Allocate X Colormap cells
     *
     * If we do not need the entire colormap, allocate `cmapsize'
     * entries just below the top of the colormap.  Here's how:
     *    Temporarily allocate some entries at the front of the cmap.  
     *    Don't allocate the top_colors (the top two color indices 
     *	  are often used by other applications). 
     *    Allocate the needed entries in the next cmap section
     *    Free the temporary entries.
     * This allows the X-Window manager to use them and reduces the
     * chances of of your window colormap flashing.
     */

    if (cmapsize < 256-top_colors) {
        if (!XAllocColorCells(display, *cmap, 0, &mask, 0,
	        tmp_colors, 256 - cmapsize - top_colors)) {
            fprintf(stderr, " XAllocColorCells for cmap_create failed(1)\n");
        }
    }
  
    if (!XAllocColorCells(display, *cmap, 0, &mask, 0, pixels, cmapsize)) {
        fprintf(stderr, " XAllocColorCells for cmap_create failed(2)\n");
    }
    /* The remaining code assumes that the values returned in pixels[0] through
     * pixels[cmapsize-1] are a contiguous range.
     */

    /* Free the unused colors in the front */
    if (cmapsize < 256-top_colors)
        XFreeColors(display, *cmap, tmp_colors, 256 - cmapsize - top_colors, 0);

#if 0
    if (type == CELLB) {

        /* Initialize the XilIndexList to use when setting the RDWR_INDICES
         * attribute.  In this example, we make all of the indices writable.
         */
        if ( (ilist->pixels = (Xil_unsigned32 *)
                malloc(sizeof(Xil_unsigned32) * cmapsize) ) == NULL ) {
            fprintf(stderr, " out of memory for ilist->pixels create\n");
        }
        ilist->ncolors = cmapsize;

        /* Copy the color cells returned by XAllocColorCells into the ilist */
        for (i = 0; i < cmapsize; i++)
            ilist->pixels[i] = (Xil_unsigned32) pixels[i];
    }
#else 
UNUSED(ilist);
#endif

    /* Allocate memory to hold colormap data. */
    if ( (data = (Xil_unsigned8 *)
            malloc(sizeof(Xil_unsigned8) * cmapsize * 3) ) == NULL ) {
        fprintf(stderr, "xilcis_color: out of memory for cmap data create\n");
    }  

    /* Get the entries for the colormap. The method depends on the compression
     * type.  For CELL, get the entries in the current default colormap.
     * For JPEG, get the entries from the standard lookup table
     * yuv_to_rgb.
     */
    switch(type_) {
#if 0
/*    case FT_CELLB:*/

        /* Get the current values in the colormap */
        for (i = 0; i < cmapsize; i++)
            cdefs[i].pixel = i + pixels[0];

        XQueryColors(display, DefaultColormap(display, screen), cdefs,
                     cmapsize);

        /* Convert the values read from the colormap to an array that can
         * be read by xil_lookup_create.  Note that the colormap values are
         * are stored in the XilLookup in BGR order.
         */
        for (i = 0, j = 0; i < cmapsize; i++, j += 3) {
            data[j] = cdefs[i].blue >> 8;
            data[j + 1] = cdefs[i].green >> 8;
            data[j + 2] = cdefs[i].red >> 8;
        }

        lut = xil_lookup_create(xil_, XIL_BYTE, XIL_BYTE, 3, cmapsize,
				(int)pixels[0], data);
        break;
#endif
    case FT_JPEG:
    case FT_H261:
    case FT_CELLB:
        xil_lookup_get_values(yuvtorgb, xil_lookup_get_offset(yuvtorgb),
                              cmapsize, data);
        xil_lookup_set_offset(colorcube, (unsigned int)pixels[0]);
        for (i = 0, t = 0; i < cmapsize; i++, t += 3) {
            cdefs[i].pixel = pixels[i];
            cdefs[i].flags = DoRed | DoGreen | DoBlue;
            cdefs[i].blue = data[t] << 8;  
            cdefs[i].green = data[t+1] << 8; 
            cdefs[i].red = data[t+2] << 8;  
        }
        XStoreColors(display, *cmap, cdefs, cmapsize);
        lut = yuvtorgb;
        break;
     }

    Tk_SetWindowColormap(window_->tkwin(),*cmap);
    free(data);
    return(lut);
}
Example #29
0
void x_create_colormap( char *name, unsigned char r[256], unsigned char g[256], unsigned char b[256] )
{
        Colormap        orig_colormap, new_colormap;
        Display         *display;
        int             i, status=0, enabled;
        XColor          *color;
        unsigned long   plane_masks[1], pixels[1];
        Cmaplist        *cmaplist, *cml;
        static int      first_time_through = FALSE;
	char		sl_cmap_name[1020];
	Stringlist	*sl;

	/*
	printf( "----------------------\n" );
	printf( "in x_create_colormap, here is state stringlist:\n" );
	stringlist_dump( read_in_state );
	printf( "----------------------\n" );
	*/

        display = XtDisplay( topLevel );

        if( colormap_list == NULL )
                first_time_through = TRUE;
        else
                first_time_through = FALSE;

        /* Make a new Cmaplist structure, and link it into the list */
        new_cmaplist( &cmaplist );
        cmaplist->name = (char *)malloc( (strlen(name)+1)*sizeof(char) );
        strcpy( cmaplist->name, name );

	/* Figure out if, according to our saved state, this colormap
	 * should be enabled or not. If we don't find this colormap 
	 * in the list, default to 'Enabled' 
	 */
	if( strlen(name) > 1000 ) {
		fprintf( stderr, "Error, colormap name is too long: %s\n", name );
		exit(-1);
		}
	snprintf( sl_cmap_name, 1018, "CMAP_%s", name );
	sl = stringlist_match_string_exact( read_in_state, sl_cmap_name );
	if( sl == NULL ) {
		/* People seem to find this message confusing
		printf( "did not find color map %s in state file: enabling by default\n", sl_cmap_name );
		*/
	 	cmaplist->enabled = 1;
		}
	else
		{
		if( sl->sltype != SLTYPE_INT ) {
			fprintf( stderr, "Error, saved TYPE for colormap %s is not an int\n", sl_cmap_name );
			enabled = 1;
			}
		else
			enabled = *((int *)(sl->aux));
		cmaplist->enabled = enabled;
		}

        if( first_time_through )
                colormap_list = cmaplist;
        else
                {
                cml = colormap_list;
                while( cml->next != NULL )
                        cml = cml->next;
                cml->next      = cmaplist;
                cmaplist->prev = cml;
                }

        if( first_time_through ) {

                /* First time through, allocate the read/write entries in the colormap.
                 * We always do ten more than the number of colors requested so that
                 * black can indicate 'fill_value' entries, and the other color entries
                 * (which are the window elements) can be colored as desired.
                 */
                current_colormap_list = cmaplist;

                /* TrueColor device */
                if( options.display_type == TrueColor ) {
                        for( i=0; i<(options.n_colors+options.n_extra_colors); i++ ) {
                                (cmaplist->color_list+i)->pixel = (long)i;
                                *(cmaplist->pixel_transform+i)  = (ncv_pixel)i;
                                }
                        }

                /* Shared colormap, PseudoColor device */
                if( (!options.private_colormap) && (options.display_type == PseudoColor) ) {
                        /* Try the standard colormap, and see if
                         * it has enough available colorcells.
                         */
                        orig_colormap    = DefaultColormap( display, 0 );
                        current_colormap = orig_colormap;
                        i      = 0;
                        status = 1;
                        while( (i < (options.n_colors+options.n_extra_colors)) && (status != 0) ) {
                                status = XAllocColorCells( display, orig_colormap, True,
                                        plane_masks, 0, pixels, 1 );
                                (cmaplist->color_list+i)->pixel = *pixels;
                                *(cmaplist->pixel_transform+i)   = (ncv_pixel)*pixels;
                                i++;
                                }
                        }

                /* standard colormap failed for PseudoColor, allocate a private colormap */
                if( (options.display_type == PseudoColor) &&
                                ((status == 0) || (options.private_colormap)) ) {
                        printf( "Using private colormap...\n" );
                        new_colormap  = XCreateColormap(
                                display,
                                RootWindow( display, DefaultScreen( display ) ),
                                XDefaultVisualOfScreen( XtScreen( topLevel ) ),
                                AllocNone );
                        current_colormap = new_colormap;
                        for( i=0; i<(options.n_colors+options.n_extra_colors); i++ )
                                {
                                status = XAllocColorCells( display, new_colormap,
                                                True, plane_masks,
                                                0, pixels, 1 );
                                if( status == 0 ) {
                                        fprintf( stderr, "ncview: x_create_colormap: couldn't allocate \n" );
                                        fprintf( stderr, "requested number of colorcells in a private colormap\n" );
                                        fprintf( stderr, "Try requesting fewer colors with the -nc option\n" );
                                        exit( -1 );
                                        }
                                (cmaplist->color_list+i)->pixel = *pixels;
                                *(cmaplist->pixel_transform+i)  = (ncv_pixel)*pixels;
                                }
                        }
                pixel_transform = cmaplist->pixel_transform;
                }
        else
                {
                /* if NOT the first time through, just set the pixel values */
                for( i=0; i<options.n_colors+options.n_extra_colors; i++ ) {
                        (cmaplist->color_list+i)->pixel =
                                (current_colormap_list->color_list+i)->pixel;
                        *(cmaplist->pixel_transform+i)   =
                                (ncv_pixel)(current_colormap_list->color_list+i)->pixel;
                        }
                }

        /* Set the first ten colors including black, the color used for "Fill_Value" entries */
        for( i=0; i<options.n_extra_colors; i++ ) {
                color        = cmaplist->color_list+i;
                color->flags = DoRed | DoGreen | DoBlue;
                color->red   = 256*(unsigned int)255;
                color->green = 256*(unsigned int)255;
                color->blue  = 256*(unsigned int)255;
                }
        color        = cmaplist->color_list+1;
        color->flags = DoRed | DoGreen | DoBlue;
        color->red   = 256*(unsigned int)0;
        color->green = 256*(unsigned int)0;
        color->blue  = 256*(unsigned int)0;

        for( i=options.n_extra_colors; i<options.n_colors+options.n_extra_colors; i++ )
                {
                color        = cmaplist->color_list+i;
                color->flags = DoRed | DoGreen | DoBlue;
                color->red   = (unsigned int)
                                (256*interp( i-options.n_extra_colors, options.n_colors, r, 256 ));
                color->green = (unsigned int)
                                (256*interp( i-options.n_extra_colors, options.n_colors, g, 256 ));
                color->blue  = (unsigned int)
                                (256*interp( i-options.n_extra_colors, options.n_colors, b, 256 ));
                }

        if( (options.display_type == PseudoColor) && first_time_through )
                XStoreColors( XtDisplay(topLevel), current_colormap, current_colormap_list->color_list,
                        options.n_colors+options.n_extra_colors );
}
Example #30
0
int XAbstractGui::SetColors(Display *dpy)
{
    int screen;
    XcmsColor xcolor;
    XcmsColor exact;
    int i, scale;
    int rw_color;   /* is it a read/write color ?*/
    int visualClass;
    unsigned long pixels[1 << COLOR_PLANES];

    screen = DefaultScreen(dpy);
    visual = GetBestVisual(dpy, &visualClass, &depth);

    if (!visual)
    {
        fprintf(stderr, "Unable to find an appropriate visual\n");
        return 0;
    }

    rw_color = (visualClass == DirectColor || visualClass == PseudoColor ||
                visualClass == GrayScale);
    cmap = DefaultColormap(dpy, screen);

    if (rw_color)
    {
        /* on visuals with read/write color cells
           first allocate them */
        if (!XAllocColorCells(dpy, cmap, False, nullptr, 0, pixels,
                              1 << COLOR_PLANES))
        {
            /* try again with a own colormap */
            cmap = XCreateColormap(dpy,
                                   RootWindow(dpy, screen),
                                   visual, AllocNone);
            own_cmap = 1;

            if (!XAllocColorCells(dpy, cmap, False, nullptr, 0,
                                  pixels, 1 << COLOR_PLANES))
            {
                fprintf(stderr, "Unable to allocate %d colors\n",
                        1 << COLOR_PLANES);
                return 0; /* failed even with own colormap */
            }
        }
    }

    if (!XcmsLookupColor(dpy, cmap, color.c_str(), &xcolor, &exact,
                         XcmsRGBiFormat))
    {
        exact.spec.RGBi.blue  = 1.0;
        exact.spec.RGBi.red   = 1.0;
        exact.spec.RGBi.green = 1.0;
    }

    xcolor.format = XcmsRGBiFormat;

    for (i = 0; i < (1 << COLOR_PLANES); i++)
    {
        if (withColorScale)
        {
            // DEPENDANCIES:
            // the color plane masks used here depend on
            // the same masks used in CopyToZPixmap
            scale  = i & 0x20 ? 2 : 0;
            scale |= i & 0x04 ? 1 : 0;
            xcolor.spec.RGBi.green = 1.0 * scale / 3;
            scale  = i & 0x10 ? 2 : 0;
            scale |= i & 0x02 ? 1 : 0;
            xcolor.spec.RGBi.red   = 1.0 * scale / 3;
            scale  = i & 0x08 ? 2 : 0;
            scale |= i & 0x01 ? 1 : 0;
            xcolor.spec.RGBi.blue  = 1.0 * scale / 3;
        }
        else
        {
            xcolor.spec.RGBi.blue  =
                exact.spec.RGBi.blue  * i / (1 << COLOR_PLANES);
            xcolor.spec.RGBi.red   =
                exact.spec.RGBi.red   * i / (1 << COLOR_PLANES);
            xcolor.spec.RGBi.green =
                exact.spec.RGBi.green * i / (1 << COLOR_PLANES);
        }

        if (rw_color)
        {
            xcolor.pixel = pixels[i];

            if (XcmsStoreColor(dpy, cmap,
                               &xcolor) == XcmsFailure)
            {
                fprintf(stderr, "Error storing a color\n");
                return 0;
            }
        }
        else
        {
            if (XcmsAllocColor(dpy, cmap,
                               &xcolor, XcmsRGBiFormat) == XcmsFailure)
            {
                fprintf(stderr, "Error allocating a color\n");
                return 0;
            }
        }

        pens[i] = xcolor.pixel;
    }

    //gcVal.plane_mask = 0xFFFFFFFF;

    return 1;
}