Example #1
0
void    MGLAPI XWIN8_realizePalette(MGLDC *dc,palette_t *pal,int num,int index,int waitVRT)
/****************************************************************************
*
* Function:		XWIN8_realizePalette
* Parameters:	dc		- Device context
*               pal		- Palette of values to program
*               num		- Number of entries to program
*				index	- Index to start programming at
*
* Description:	Program the X11 colormap. First we need to translate the
*				values from the MGL internal format into the 16 bit RGB
*				format used by X11.
*
****************************************************************************/
{
	int i;
	XColor *cols = MGL_malloc(sizeof(XColor) * num);
	xwindc_vars *v = &dc->wm.xwindc;
	
	for(i=0; i<num; i++){
		cols[i].flags = DoRed | DoGreen | DoBlue;
		cols[i].pixel = i+index;
		cols[i].red   = pal[i].red << 8;
		cols[i].green = pal[i].green << 8;
		cols[i].blue  = pal[i].blue << 8;
	}
	XStoreColors(v->dpy, v->hpal, cols, num);
	XFlush(v->dpy);
	MGL_free(cols);
}
Example #2
0
static void SetColormap(CanvasExtension *CE) {

    /* Calculate colormap entries. */

    for (int i=0; i<Shades; i++) {
        int (*Scaler)(int,int);
        if (CE->GammaCorrect)
            Scaler=&GammaCorrected;
        else
            Scaler=&LinearScale;
        if (CE->Mask==ALL_COLORS) {
            CE->Colors[i].red=(*Scaler)(i%Reds,Reds)<<8;
            CE->Colors[i].green=(*Scaler)((i/Reds)%Greens,Greens)<<8;
            CE->Colors[i].blue=(*Scaler)(i/(Reds*Greens),Blues)<<8;
        } else if (CE->Mask==ONLY_RED) {
            CE->Colors[i].red=(*Scaler)(i,Shades)<<8;
            CE->Colors[i].green=CE->Colors[i].blue=0;
        } else if (CE->Mask==ONLY_GREEN) {
            CE->Colors[i].green=(*Scaler)(i,Shades)<<8;
            CE->Colors[i].red=CE->Colors[i].blue=0;
        } else if (CE->Mask==ONLY_BLUE) {
            CE->Colors[i].blue=(*Scaler)(i,Shades)<<8;
            CE->Colors[i].red=CE->Colors[i].green=0;
        }
    }

    /* Update server. */

    XStoreColors(Disp,CE->CMap,CE->Colors,Shades);
}
Example #3
0
/* _xdga2_set_palette_range:
 *  Sets palette entries.
 */
static void _xdga2_set_palette_range(AL_CONST PALETTE p, int from, int to, int vsync)
{
   int i;
   static XColor color[256];

   XLOCK();
   
   if (vsync) {
      XSync(_xwin.display, False);
   }

   if (dga_device->mode.depth == 8) {
      for (i = from; i <= to; i++) {
         color[i].flags = DoRed | DoGreen | DoBlue;
         color[i].pixel = i;
         color[i].red = ((p[i].r & 0x3F) * 65535L) / 0x3F;
         color[i].green = ((p[i].g & 0x3F) * 65535L) / 0x3F;
         color[i].blue = ((p[i].b & 0x3F) * 65535L) / 0x3F;
      }
      XStoreColors(_xwin.display, _dga_cmap, color + from, to - from + 1);
      XSync(_xwin.display, False);
   }

   XUNLOCK();
}
Example #4
0
///////////////////////////////////////////////////////////
// Palette stuff.
//
static void I_UploadNewPalette(int pal)
{
  // This is used to replace the current 256 colour cmap with a new one
  // Used by 256 colour PseudoColor modes

  // Array of XColor structs used for setting the 256-colour palette 
  static XColor* colours;
  static int cachedgamma;
  static size_t num_pals;

  if ((colours == NULL) || (cachedgamma != usegamma)) {
    int            lump = W_GetNumForName("PLAYPAL");
    const byte *palette = W_CacheLumpNum(lump);
    register const byte *const gtable = gammatable[cachedgamma = usegamma];
    register int i;

    num_pals = W_LumpLength(lump) / (3*256);
    num_pals *= 256;

    if (!colours) {
      // First call - allocate and prepare colour array
      colours = malloc(sizeof(*colours)*num_pals);
      for (i=0 ; i<num_pals ; i++) {
	colours[i].pixel = i & 0xff;
	colours[i].flags = DoRed|DoGreen|DoBlue;
      }
    }

    // set the X colormap entries
    for (i=0 ; i<num_pals ; i++) {
      register int c;
      c = gtable[palette[0]];
      colours[i].red = (c<<8) + c;
      c = gtable[palette[1]];
      colours[i].green = (c<<8) + c;
      c = gtable[palette[2]];
      colours[i].blue = (c<<8) + c;
      palette += 3;
    }
  
    W_UnlockLumpNum(lump);
    num_pals/=256;
  }

#ifdef RANGECHECK
  if (pal >= num_pals) 
    I_Error("I_UploadNewPalette: Palette number out of range (%d>=%d)", 
	    pal, num_pals);
#endif
  
  // store the colors to the current colormap
  XStoreColors(X_display, X_cmap, colours + 256*pal, 256);

#ifdef HAVE_LIBXXF86DGA
  /* install DGA colormap */
  if(doDga)
     XF86DGAInstallColormap(X_display, X_screen, X_cmap);
#endif

}
Example #5
0
static void
initialize_transparency_colormap (Display *dpy, Colormap cmap,
				  int nplanes,
				  unsigned long base_pixel,
				  unsigned long *plane_masks,
				  XColor *colors,
				  Bool additive_p , ModeInfo* mi )
{
  int i;
  int total_colors = i_exp (2, nplanes);
  XColor *all_colors = (XColor *) calloc (total_colors, sizeof (XColor));

  for (i = 0; i < nplanes; i++)
    colors[i].pixel = base_pixel | plane_masks [i];
  permute_colors (colors, all_colors, nplanes, plane_masks, additive_p);

  /* clone the default background of the window into our "base" pixel */
  all_colors [total_colors - 1].pixel = MI_BLACK_PIXEL( mi );
  XQueryColor (dpy, cmap, &all_colors [total_colors - 1]);
  all_colors [total_colors - 1].pixel = base_pixel;

  for (i = 0; i < total_colors; i++)
    all_colors[i].flags = DoRed|DoGreen|DoBlue;
  XStoreColors (dpy, cmap, all_colors, total_colors);
  XFree ((XPointer) all_colors);
}
Example #6
0
void
rotate_colors(Display * dpy, Colormap cmap,
	      XColor * colors, int ncolors, int distance)
{
	int         i;
	XColor     *colors2 = (XColor *) malloc(sizeof (XColor) * ncolors);

	if (ncolors < 2)
		return;
	distance = distance % ncolors;
	for (i = 0; i < ncolors; i++) {
		int         j = i - distance;

		if (j >= ncolors)
			j -= ncolors;
		if (j < 0)
			j += ncolors;
		colors2[i] = colors[j];
		colors2[i].pixel = colors[i].pixel;
	}
	XStoreColors(dpy, cmap, colors2, ncolors);
	XFlush(dpy);
	(void) memcpy((char *) colors, colors2, sizeof (*colors) * ncolors);
	free(colors2);
}
Example #7
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 #8
0
static void
changeColor (struct state *st, double r, double g, double b)
{
  int n,n1;
  
  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);
      
      n1++;
    }
  
  XStoreColors (st->dpy, st->cmap, st->colors, 12);
}
Example #9
0
void S9xSetPalette ()
{
	int		Brightness;

	if (ourvideo.bitdepth != 8)
		return;

	Brightness = IPPU.MaxBrightness *138;

	for (int i = 0; i < 256; i++) {
		colors[i].red = ((PPU.CGDATA[i] >> 0) & 0x1F) * Brightness;
		colors[i].green = ((PPU.CGDATA[i] >> 5) & 0x1F) * Brightness;
		colors[i].blue = ((PPU.CGDATA[i] >> 10) & 0x1F) * Brightness;
	}

	XStoreColors (ourdisp, cmap, colors, 256);
	XF86DGAInstallColormap (ourdisp, ourscreen, cmap);
}
Example #10
0
void
WindowDevice::WINOPEN(const char *_title, int _xLoc, int _yLoc, int _width, int _height)
{
    // set the WindowDevices title, height, wdth, xLoc and yLoc
    strcpy(title, _title);

    height = _height;
    width = _width;  
    xLoc = _xLoc;
    yLoc = _yLoc;

#ifdef _UNIX
    if (winOpen == 0) { // we must close the old window
	XFreeGC(theDisplay, theGC);
	XDestroyWindow(theDisplay, theWindow); 
    }

    // define the position and size of the window - only hints
    hints.x = _xLoc;
    hints.y = _yLoc;
    hints.width = _width;
    hints.height = _height;
    hints.flags = PPosition | PSize;

    // set the defualt foreground and background colors
    XVisualInfo visual; 
    visual.visual = 0;
    int depth = DefaultDepth(theDisplay, theScreen);

    if (background == 0) {
      if (XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual) == 0) {
	  foreground = BlackPixel(theDisplay, theScreen);
	  background = WhitePixel(theDisplay, theScreen);    

      } else {
	foreground = 0;
	background = 255;
      }
    }

    // now open a window
    theWindow = XCreateSimpleWindow(theDisplay,RootWindow(theDisplay,0),
				    hints.x, hints.y,
				    hints.width,hints.height,4,
				    foreground, background);

    if (theWindow == 0) {
	opserr << "WindowDevice::WINOPEN() - could not open a window\n";
	exit(-1);
    }	
    
    XSetStandardProperties(theDisplay, theWindow, title, title, None, 0, 0, &hints);
    
    // create a graphical context
    theGC = XCreateGC(theDisplay, theWindow, 0, 0);

    // if we were unable to get space for our colors
    // we must create and use our own colormap
    if (colorFlag == 3 ) {

      // create the colormap if the 1st window
      if (numWindowDevice == 1) {
	int fail = false;
	//	XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual);
	if (XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual) == 0) {
	  opserr << "WindowDevice::initX11() - could not get a visual for PseudoColor\n";
	  opserr << "Colors diplayed will be all over the place\n";
	  cmap = DefaultColormap(theDisplay, theScreen);
	  fail = true;
        } else {
	  opserr << "WindowDevice::WINOPEN have created our own colormap, \n";
	  opserr << "windows may change color as move mouse from one window to\n";
	  opserr << "another - depends on your video card to use another colormap\n\n";	

	  cmap = XCreateColormap(theDisplay,theWindow,
				 visual.visual, AllocAll);
	}


	/*
	cmap = XCreateColormap(theDisplay,theWindow,
			   DefaultVisual(theDisplay,0),AllocAll);
	*/

	if (cmap == 0) {
	    opserr << "WindowDevice::initX11() - could not get a new color table\n";
	    exit(-1);
	}	    

	// we are going to try to allocate 256 new colors -- need 8 planes for this
	depth = DefaultDepth(theDisplay, theScreen);
	if (depth < 8) {
	    opserr << "WindowDevice::initX11() - needed at least 8 planes\n";
	    exit(-1);
	}	    
	if (fail == false) {
	  int cnt = 0;
	  for (int red = 0; red < 8; red++) {
	    for (int green = 0; green < 8; green++) {
		for (int blue = 0; blue < 4; blue++) {
		  pixels[32*red + 4*green + blue] = cnt;
		  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++;
		}			
	    }
	  }
	  background = 0; //pixels[0];
	  foreground = 255; // pixels[255];
	  XStoreColors(theDisplay, cmap, colors, cnt);			    
	}
      }

      // now set the windows to use the colormap
      XSetWindowColormap(theDisplay, theWindow, cmap);    
    
    }

    XSetBackground(theDisplay, theGC, background);
    XSetForeground(theDisplay, theGC, foreground);

    XMapWindow(theDisplay,theWindow);
    XClearWindow(theDisplay, theWindow);      
    XFlush(theDisplay);

#else
    //    auxInitDisplayMode(AUX_SINGLE | AUX_RGBA);
    //    auxInitPosition(100,100,_width,_height);
    //    auxInitWindow("G3");

    if (winOpen == 0)
      oglDestroyWindow(title,theWND, theHRC, theHDC);      

    theWND = oglCreateWindow(title, xLoc, yLoc, width, height, &theHRC, &theHDC);
    if (theWND == NULL)
      exit(1);
    winOpen = 0;

    wglMakeCurrent(theHDC, theHRC);
    glClearColor(1.0f,1.0f,1.0f,1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
//    gluOrtho2D(0.0, (GLdouble)width, 0.0, (GLdouble)height);
    glFlush();

#endif

    winOpen = 0;
}
Example #11
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 #12
0
void
make_random_colormap(ModeInfo * mi, Colormap cmap,
		     XColor * colors, int *ncolorsP,
		     Bool bright_p,
		     Bool allocate_p,
		     Bool * writable_pP)
{
	Bool        wanted_writable = (allocate_p && writable_pP && *writable_pP);
	int         ncolors = *ncolorsP;
	int         i;

	if (*ncolorsP <= 0)
		return;

	/* If this visual doesn't support writable cells, don't bother trying. */
	if (wanted_writable && !has_writable_cells(mi))
		*writable_pP = False;

	for (i = 0; i < ncolors; i++) {
		colors[i].flags = DoRed | DoGreen | DoBlue;
		if (bright_p) {
			int         H = (int) LRAND() % 360;	/* range 0-360    */
			double      S = ((double) (LRAND() % 70) + 30) / 100.0;		/* range 30%-100% */
			double      V = ((double) (LRAND() % 34) + 66) / 100.0;		/* range 66%-100% */

			hsv_to_rgb(H, S, V,
			  &colors[i].red, &colors[i].green, &colors[i].blue);
		} else {
			colors[i].red = (unsigned short) (LRAND() % 0xFFFF);
			colors[i].green = (unsigned short) (LRAND() % 0xFFFF);
			colors[i].blue = (unsigned short) (LRAND() % 0xFFFF);
		}
	}

	if (!allocate_p)
		return;

      RETRY_NON_WRITABLE:
	if (writable_pP && *writable_pP) {
		unsigned long *pixels = (unsigned long *)
		malloc(sizeof (unsigned long) * (ncolors + 1));

		allocate_writable_colors(MI_DISPLAY(mi), cmap, pixels, &ncolors);
		if (ncolors > 0)
			for (i = 0; i < ncolors; i++)
				colors[i].pixel = pixels[i];
		free(pixels);
		if (ncolors > 0)
			XStoreColors(MI_DISPLAY(mi), cmap, colors, ncolors);
	} else {
		for (i = 0; i < ncolors; i++) {
			XColor      color;

			color = colors[i];
			if (!XAllocColor(MI_DISPLAY(mi), cmap, &color))
				break;
			colors[i].pixel = color.pixel;
		}
		ncolors = i;
	}

	/* If we tried for writable cells and got none, try for non-writable. */
	if (allocate_p && ncolors == 0 && writable_pP && *writable_pP) {
		ncolors = *ncolorsP;
		*writable_pP = False;
		goto RETRY_NON_WRITABLE;
	}
	if (MI_IS_VERBOSE(mi) || MI_IS_DEBUG(mi))
		complain(*ncolorsP, ncolors, wanted_writable,
			 wanted_writable && *writable_pP);

	*ncolorsP = ncolors;
}
Example #13
0
void Window2d::setup_window()
{
  int status;
  unsigned long plane_masks[8];
  XSetWindowAttributes attrib;
  static char default_font[] = "8x13";

  psize = 1;

  /* Open a connection to the display. */
 /* if ((display = XOpenDisplay (NULL)) == NULL) {
    printf ("Couldn't open display:\n");
    printf ("Make sure X11 is running and DISPLAY is set correctly\n");
    exit (-1);
  }
  screen = XDefaultScreen (display);
  */
  num_colors = 30;

/*
XSetErrorHandler (my_error_handler);
*/

  /* set up foreground, background colors (to Xdefaults, if any) */
 // if (XDisplayCells (display, screen) > 2)	/* this is a color display */
  //  defColormap = XDefaultColormap (display, screen);

 // foregrnd = XWhitePixel (display, screen);
 // backgrnd = XBlackPixel (display, screen);

  /* set up default depth, visual params */
 // defDepth = XDefaultDepth (display, screen);
 // defVisual = XDefaultVisual (display, screen);

  /* set up fonts */

 // RegFont   = XLoadQueryFont (display, "8x13");
 // SmallFont = XLoadQueryFont (display, "6x10");
 // BigFont   = XLoadQueryFont (display, "9x15");

  if (RegFont == NULL || SmallFont == NULL || BigFont == NULL) {
    printf ("Couldn't find all fonts.\n");
  }

  /* create root cursor (left arrow) */
  //root_cursor = XCreateFontCursor (display, 68);

  /* create root window */
  attrib.background_pixel = backgrnd;
  attrib.border_pixel = foregrnd;
  attrib.override_redirect = False;
  /*
  attrib.override_redirect = True;
  */
  attrib.event_mask = ButtonPressMask | ButtonReleaseMask | ExposureMask |
		      StructureNotifyMask;
  attrib.cursor = root_cursor;
 // root = XCreateWindow (display, RootWindow(display, screen),
//	      xorg, yorg,
//	      xsize, ysize, 1, defDepth, InputOutput,
//	      defVisual, CWBackPixel|CWBorderPixel|CWOverrideRedirect|
//	      CWEventMask|CWCursor, &attrib);
 // XChangeProperty (display, root, XA_WM_NAME, XA_STRING, 8, PropModeReplace,
 //     (unsigned char *) "Icon", 5);

  /* set up some graphics contexts */

  gcvalues.foreground = foregrnd;
  gcvalues.background = backgrnd;
  gcvalues.line_width = 1;
  gcvalues.font = RegFont->fid;
 // gc_reg_font = XCreateGC (display, root,
//		  GCForeground|GCBackground|GCLineWidth|GCFont,
//		  &gcvalues);
  gcvalues.font = SmallFont->fid;
  //gc_small_font = XCreateGC (display, root,
//		  GCForeground|GCBackground|GCLineWidth|GCFont,
//		  &gcvalues);
  gcvalues.font = BigFont->fid;
 // gc_big_font = XCreateGC (display, root,
//		  GCForeground|GCBackground|GCLineWidth|GCFont,
//		  &gcvalues);

  /* set up drawing parameters */

  //status = XAllocColorCells (display, defColormap,
//	   0, plane_masks, 0, pixels, num_colors);

  if (status == 0) {
    printf ("bad status from XAllocColorCells\n");
    return;
  }

  gray_ramp();

#if 0
  /* create grey ramp */

  for (int i = 0; i < num_colors; i++) {
    t = 65535 * i / (num_colors - 1.0);
    colors[i].red   = (unsigned short) t;
    colors[i].green = (unsigned short) t;
    colors[i].blue  = (unsigned short) t;
    colors[i].pixel = pixels[i];
    colors[i].flags = DoRed | DoGreen | DoBlue;
  }

  XStoreColors (display, defColormap, colors, num_colors);
#endif

  gcvalues.foreground = foregrnd;
  gcvalues.background = backgrnd;
 // gc = XCreateGC (display, root, GCForeground|GCBackground, &gcvalues);

  /* set all callbacks to NULL */

  press1 = NULL;
  press2 = NULL;
  press3 = NULL;
  release1 = NULL;
  release2 = NULL;
  release3 = NULL;
  escape_callback = NULL;
  redraw_callback = NULL;

  /* save a pointer to this window */
  window_list[num_windows++] = this;
}
Example #14
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 #15
0
//////////////////////////////////////////////////////////////////////
// Main
//////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
	int i;

	fprintf(stderr, "\n%s v%s (Build %s)\n\n", bench_name, __VERSION, __BUILD);

	if(argc>1) for(i=1; i<argc; i++)
	{
		if(!stricmp(argv[i], "-checkdb"))
		{
			checkdb=1;
			fprintf(stderr, "Checking double buffering.  Watch for flashing to indicate that it is\n");
			fprintf(stderr, "not enabled.  Performance will be sub-optimal.\n");
		}
		if(!stricmp(argv[i], "-noshm"))
		{
			doshm=0;
		}
		if(!stricmp(argv[i], "-verbose"))
		{
			fbx_printwarnings(stderr);
		}
	}

	try {

	#ifdef FBXWIN32

	WNDCLASSEX wndclass;  MSG msg;
	wndclass.cbSize = sizeof(WNDCLASSEX);
	wndclass.style = CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc = WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = GetModuleHandle(NULL);
	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = bench_name;
	wndclass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
	tryw32(RegisterClassEx(&wndclass));
	width=GetSystemMetrics(SM_CXSCREEN);
	height=GetSystemMetrics(SM_CYSCREEN);

	#else

	if(!XInitThreads()) {fprintf(stderr, "ERROR: Could not initialize Xlib thread safety\n");  exit(1);}
	XSetErrorHandler(xhandler);
	if(!(wh.dpy=XOpenDisplay(0))) {fprintf(stderr, "Could not open display %s\n", XDisplayName(0));  exit(1);}
	width=DisplayWidth(wh.dpy, DefaultScreen(wh.dpy));
	height=DisplayHeight(wh.dpy, DefaultScreen(wh.dpy));

	#endif

	if(width<MIN_SCREEN_WIDTH && height<MIN_SCREEN_HEIGHT)
	{
		fprintf(stderr, "ERROR: Please switch to a screen resolution of at least %d x %d.\n", MIN_SCREEN_WIDTH, MIN_SCREEN_HEIGHT);
		exit(1);
	}
	width=WIDTH;
	height=HEIGHT;

	#ifdef FBXWIN32

	int bw=GetSystemMetrics(SM_CXFIXEDFRAME)*2;
	int bh=GetSystemMetrics(SM_CYFIXEDFRAME)*2+GetSystemMetrics(SM_CYCAPTION);
	tryw32(wh=CreateWindowEx(0, bench_name, bench_name, WS_OVERLAPPED |
		WS_SYSMENU | WS_CAPTION | WS_VISIBLE, 0,  0, width+bw, height+bh, NULL,
		NULL, GetModuleHandle(NULL), NULL));
	UpdateWindow(wh);
	BOOL ret;
	while(1)
	{
		if((ret=GetMessage(&msg, NULL, 0, 0))==-1) _throww32();
		else if(ret==0) break;
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return (int)msg.wParam;

	#else

	XVisualInfo vtemp, *v=NULL;  int n=0;
	XSetWindowAttributes swa;
	Window root=DefaultRootWindow(wh.dpy);

	vtemp.depth=24;  vtemp.c_class=TrueColor;
	if((v=XGetVisualInfo(wh.dpy, VisualDepthMask|VisualClassMask, &vtemp, &n))!=NULL && n!=0)
	{
		swa.colormap=XCreateColormap(wh.dpy, root, v->visual, AllocNone);
		swa.border_pixel=0;
		swa.event_mask=0;
		errifnot(wh.win=XCreateWindow(wh.dpy, root, 0, 0, width, height, 0,
			v->depth, InputOutput, v->visual, CWBorderPixel|CWColormap|CWEventMask,
			&swa));
		errifnot(XMapRaised(wh.dpy, wh.win));
		XSync(wh.dpy, False);
		display();
		XDestroyWindow(wh.dpy, wh.win);
		XFree(v);  v=NULL;
	}
	else fprintf(stderr, "No RGB visuals available.  Skipping those tests.\n\n");

	vtemp.depth=8;  vtemp.c_class=PseudoColor;
	if((v=XGetVisualInfo(wh.dpy, VisualDepthMask|VisualClassMask, &vtemp, &n))!=NULL && n!=0)
	{
		swa.colormap=XCreateColormap(wh.dpy, root, v->visual, AllocAll);
		swa.border_pixel=0;
		swa.event_mask=0;
    XColor xc[32];  int i;
		errifnot(v->colormap_size==256);
		for(i=0; i<32; i++)
		{
			xc[i].red=(i<16? i*16:255)<<8;
			xc[i].green=(i<16? i*16:255-(i-16)*16)<<8;
			xc[i].blue=(i<16? 255:255-(i-16)*16)<<8;
			xc[i].flags = DoRed | DoGreen | DoBlue;
			xc[i].pixel=i;
		}
		XStoreColors(wh.dpy, swa.colormap, xc, 32);
		errifnot(wh.win=XCreateWindow(wh.dpy, root, 0, 0, width, height, 0,
			v->depth, InputOutput, v->visual, CWBorderPixel|CWColormap|CWEventMask,
			&swa));
		errifnot(XMapRaised(wh.dpy, wh.win));
		XSync(wh.dpy, False);
		display();
		XDestroyWindow(wh.dpy, wh.win);
		XFreeColormap(wh.dpy, swa.colormap);
		XFree(v);  v=NULL;
	}
	else fprintf(stderr, "No Pseudocolor visuals available.  Skipping those tests.\n\n");

	return 0;

	#endif

	} catch(rrerror &e) {fprintf(stderr, "%s\n", e.getMessage());}
}
Example #16
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 #17
0
 void backmen_butm(Widget iw_temp, XtPointer data, 
                                   XtPointer call_data)

 {
 int             nindex, ival, iflags, indx;  
 float           fval,ft;
 int             ngo_com, nend_com;  

 /* Get new ngo & nend */
 XmScaleGetValue(iw_ngob,  &ngo_com);
 XmScaleGetValue(iw_nendb, &nend_com);

 if (nend_com < ngo_com)
    { spout("*** Upper value must be > lower value"); return;}
 else if (ngo_com < imagego)                                            
    { spout("*** Lower value outside of image ramp"); return;}
 else if (nend_com > imageend)                                         
    { spout("*** Upper value outside of image ramp"); return;}

 // Use ngo to signal ramp info
 ngo  = ngo_com;
 nend = nend_com;
 
#ifdef WEB_TRUE
// WEB_TRUE ------------------------------------------- WEB_TRUE

 // Uses virtual cmap
 newvmap(ngo,nend,vmap);
 neednewmap = TRUE;

 // Applies virtual cmap
 expos_cb(NULL,NULL,NULL);

#else
// WEB_24 --------------------------------------------- WEB_24


 /* Set the colors in the image portion of the colormap, only */ 

 iflags = DoRed | DoGreen | DoBlue; 
 indx   = 0;
 ft     = 65535.0 / ((float) (nend - ngo));

 for (nindex = mapgo; nindex <= imageend; nindex++)
    {
    colort[indx].pixel = ispicol[nindex];
    colort[indx].flags = iflags;

    if (nindex <= ngo) 
       { ival = 0; }     /* Set this color to black */
    else if (nindex < nend)
       {                 
       /* Interpolate shade */
       fval = (float)(nindex - ngo) * ft;
       ival = fval;
       }
    else 
       { ival = 65535; } /* Set this color to white */

    colort[indx].red     = ival;
    colort[indx].green   = ival;
    colort[indx++].blue  = ival;
    }
 
 /* Put the colors in the desired colormap */
 XStoreColors(idispl, map, colort, indx);

// BOTH --------------------------------------------- BOTH
#endif

 XFlush(idispl);
 return;
 }
Example #18
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 #19
0
/****************************************************************************************************
 * This returns the name of the newly installed colormap.  If do_widgets_flag
 * is false, don't install colormaps on the widgets, just on the topLevel.
 */
char *x_change_colormap( int delta, int do_widgets_flag )
{
	int	dump_cmap_list, n_enabled;
	Cmaplist *cursor;

	dump_cmap_list = 0;	/* for debugging */

	if( dump_cmap_list ) {
		printf( "---- on entry to x_change_colormap, here is colormap_list\n" );
		dump_Cmaplist( colormap_list );
		}

	/* Make sure at least one colormap is enabled. As a failsafe, is none
	 * are enabled, enable the first one on the list
	 */
	cursor = colormap_list;
	if( check_cmaplist_magic( cursor ) != 0 ) {
		fprintf( stderr, "Error, trying to change colormaps in a cmaplist with an invalid element\n" );
		exit(-1);
		}
	n_enabled = colormap_list->enabled;
	while( cursor->next != NULL ) {
		if( check_cmaplist_magic( cursor ) != 0 ) {
			fprintf( stderr, "Error, trying to change colormaps in a cmaplist with an invalid element\n" );
			exit(-1);
			}
		cursor = cursor->next;
		n_enabled = n_enabled + cursor->enabled;
		}
	if( n_enabled == 0 ) {
		printf( "Warning, no colormaps enabled in x_change_colormap -- using first on list\n" );
		colormap_list->enabled = 1;
		}

        if( delta > 0 ) {
		/* Advance to next enabled colormap. Might have to wrap
		 * around to the start to encounter an enabled one.
		 */
	 	if( current_colormap_list->next == NULL )
			current_colormap_list = colormap_list;	/* go to head of list */
		else
			current_colormap_list = current_colormap_list->next;
		while( current_colormap_list->enabled == 0 ) {
			if( current_colormap_list->next == NULL )
				current_colormap_list = colormap_list;
			else
				current_colormap_list = current_colormap_list->next;
			}
                }

        else if( delta < 0 ) {
		/* delta < 0, go backwards on the list */
                if( current_colormap_list->prev == NULL ) {
			/* Go to last colormap */
                        while( current_colormap_list->next != NULL )
                                current_colormap_list = current_colormap_list->next;
			}
		else
			current_colormap_list = current_colormap_list->prev;

		/* Now go to an enabled colormap */
		while( current_colormap_list->enabled == 0 ) {
			if( current_colormap_list->prev == NULL ) {
				/* Go to last colormap */
				while( current_colormap_list->next != NULL )
					current_colormap_list = current_colormap_list->next;
				}
			else
				current_colormap_list = current_colormap_list->prev;
			}
                }
	else
		{
		;	/* We can be called with delta=0, if we changed to a new colormap in the options selection widget */
		}

        if( options.display_type == PseudoColor )
                XStoreColors( XtDisplay(topLevel), current_colormap,
                        current_colormap_list->color_list,
                        options.n_colors+1 );
        pixel_transform = current_colormap_list->pixel_transform;

        return( current_colormap_list->name );
}
Example #20
0
void
SplashInitPlatform(Splash * splash) {
    int shapeVersionMajor, shapeVersionMinor;

    // This setting enables the synchronous Xlib mode!
    // Don't use it == 1 in production builds!
#if (defined DEBUG)
    _Xdebug = 1;
#endif

    pthread_mutex_init(&splash->lock, NULL);

    // We should not ignore any errors.
    //XSetErrorHandler(HandleError);
//    XSetIOErrorHandler(HandleIOError);
    XSetIOErrorHandler(NULL);
    splash->display = XOpenDisplay(NULL);
    if (!splash->display) {
        splash->isVisible = -1;
        return;
    }

    shapeSupported = XShapeQueryExtension(splash->display, &shapeEventBase,
            &shapeErrorBase);
    if (shapeSupported) {
        XShapeQueryVersion(splash->display, &shapeVersionMajor,
                &shapeVersionMinor);
    }

    splash->screen = XDefaultScreenOfDisplay(splash->display);
    splash->visual = XDefaultVisualOfScreen(splash->screen);
    switch (splash->visual->class) {
    case TrueColor: {
            int depth = XDefaultDepthOfScreen(splash->screen);

            splash->byteAlignment = 1;
            splash->maskRequired = shapeSupported;
            initFormat(&splash->screenFormat, splash->visual->red_mask,
                    splash->visual->green_mask, splash->visual->blue_mask, 0);
            splash->screenFormat.byteOrder =
                (XImageByteOrder(splash->display) == LSBFirst ?
                 BYTE_ORDER_LSBFIRST : BYTE_ORDER_MSBFIRST);
            splash->screenFormat.depthBytes = (depth + 7) / 8;
            // TrueColor depth probably can't be less
            // than 8 bits, and it's always byte padded
            break;
        }
    case PseudoColor: {
            int availableColors;
            int numColors;
            int numComponents[3];
            unsigned long colorIndex[SPLASH_COLOR_MAP_SIZE];
            XColor xColors[SPLASH_COLOR_MAP_SIZE];
            int i;
            int depth = XDefaultDepthOfScreen(splash->screen);
            int scale = 65535 / MAX_COLOR_VALUE;

            availableColors = GetNumAvailableColors(splash->display, splash->screen,
                    splash->visual->map_entries);
            numColors = quantizeColors(availableColors, numComponents);
            if (numColors > availableColors) {
                // Could not allocate the color cells. Most probably
                // the pool got exhausted. Disable the splash screen.
                XCloseDisplay(splash->display);
                splash->isVisible = -1;
                splash->display = NULL;
                splash->screen = NULL;
                splash->visual = NULL;
                fprintf(stderr, "Warning: unable to initialize the splashscreen. Not enough available color cells.\n");
                return;
            }
            splash->cmap = AllocColors(splash->display, splash->screen,
                    numColors, colorIndex);
            for (i = 0; i < numColors; i++) {
                splash->colorIndex[i] = colorIndex[i];
            }
            initColorCube(numComponents, splash->colorMap, splash->dithers,
                    splash->colorIndex);
            for (i = 0; i < numColors; i++) {
                xColors[i].pixel = colorIndex[i];
                xColors[i].red = (unsigned short)
                    QUAD_RED(splash->colorMap[colorIndex[i]]) * scale;
                xColors[i].green = (unsigned short)
                    QUAD_GREEN(splash->colorMap[colorIndex[i]]) * scale;
                xColors[i].blue = (unsigned short)
                    QUAD_BLUE(splash->colorMap[colorIndex[i]]) * scale;
                xColors[i].flags = DoRed | DoGreen | DoBlue;
            }
            XStoreColors(splash->display, splash->cmap, xColors, numColors);
            initFormat(&splash->screenFormat, 0, 0, 0, 0);
            splash->screenFormat.colorIndex = splash->colorIndex;
            splash->screenFormat.depthBytes = (depth + 7) / 8;  // or always 8?
            splash->screenFormat.colorMap = splash->colorMap;
            splash->screenFormat.dithers = splash->dithers;
            splash->screenFormat.numColors = numColors;
            splash->screenFormat.byteOrder = BYTE_ORDER_NATIVE;
            break;
        }
    default:
        ; /* FIXME: should probably be fixed, but javaws splash screen doesn't support other visuals either */
    }
}
Example #21
0
dsxc_lutput (void)

/* C-- */
{
    float tcol[LVX*3];
    int   k, istat, ka, kdiv;

    char  flags;
    unsigned short int j;
    /* Cbegin */


    DSOPEN = F77_NAMED_COMMON(ds_genb).dsopen;
    PDSOPEN = F77_NAMED_COMMON(ds_panelb).pdsopen;
    NUMDDCOL = F77_NAMED_COMMON(lutacom).numddcol;

    (void) dsxc_lutload ( tcol );	 			/* Load LUT into working LUT */

    flags = DoRed | DoGreen | DoBlue;

    if ( DSOPEN || PDSOPEN ) {

        if ( OWNCOL ) {

            kdiv = LVX/NUMDDCOL;
            for ( k = 15; k<15+LVX; k++ ) {
                ka = 15 + ((k-15)/kdiv);
                COLOUR[ka].pixel = PC_ID[ka];
                COLOUR[ka].flags = flags;
                j = tcol[3*(k-15)+0]*65535.0;
                COLOUR[ka].red = j;
                j = tcol[3*(k-15)+1]*65535.0;
                COLOUR[ka].green = j;
                j = tcol[3*(k-15)+2]*65535.0;
                COLOUR[ka].blue = j;
            }

            XStoreColors ( VD_ID, CM_ID, COLOUR, 15+NUMDDCOL );
            XInstallColormap ( VD_ID, CM_ID );
            XFlush ( VD_ID );
        }
        else {

            for ( k = 15; k < 15+LVX; k++ ) {
                COLOUR[k].flags = flags;
                j = tcol[3*(k-15)+0]*65535.0;
                COLOUR[k].red = j;
                j = tcol[3*(k-15)+1]*65535.0;
                COLOUR[k].green = j;
                j = tcol[3*(k-15)+2]*65535.0;
                COLOUR[k].blue = j;
                istat = XAllocColor ( VD_ID, CM_ID, &COLOUR[k] );
                if ( istat==0 ) {
                    (void) c_printo ( "ERROR: Colour pixel not allocated" );
                    PC_ID[k] = 0 ;
                }
                else
                    PC_ID[k] = COLOUR[k].pixel;
            }
            XFlush ( VD_ID );

        }

    }


}
Example #22
0
dsxc_lutcol (void)

/* C-- */
{
    int   k, ka, kdiv;
    Status istat;
    unsigned short int c;
    char flags;
    /* Cbegin */


    DSOPEN = F77_NAMED_COMMON(ds_genb).dsopen;
    PDSOPEN = F77_NAMED_COMMON(ds_panelb).pdsopen;
    NUMDDCOL = F77_NAMED_COMMON(lutacom).numddcol;

    flags = DoRed | DoGreen | DoBlue;

    if ( DSOPEN || PDSOPEN ) {

        (void) dsxc_lutvget();

        if ( OWNCOL ) {

            kdiv = LVX/NUMDDCOL;
            for ( k = 15; k<15+LVX; k++ ) {
                ka = 15 + ((k-15)/kdiv);
                COLOUR[ka].pixel = PC_ID[ka];
                COLOUR[ka].flags = flags;
                c = LUTC_VAL[(k-15)][0]*65535.0;
                COLOUR[ka].red = c;
                c = LUTC_VAL[(k-15)][1]*65535.0;
                COLOUR[ka].green = c;
                c = LUTC_VAL[(k-15)][2]*65535.0;
                COLOUR[ka].blue = c;
            }

            XStoreColors ( VD_ID, CM_ID, COLOUR, 15+NUMDDCOL );
            XInstallColormap ( VD_ID, CM_ID );
            XFlush ( VD_ID );

        }
        else {

            for (k = 15; k<15+LVX; k++ ) {
                COLOUR[k].flags = flags;
                c = LUTC_VAL[(k-15)][0]*65535.0;
                COLOUR[k].red = c;
                c = LUTC_VAL[(k-15)][1]*65535.0;
                COLOUR[k].green = c;
                c = LUTC_VAL[(k-15)][2]*65535.0;
                COLOUR[k].blue = c;
                istat = XAllocColor ( VD_ID, CM_ID, &COLOUR[k] );
                if ( istat==0 ) {
                    (void) c_printo ( "ERROR,x_lut: Colour pixel not allocated" );
                    PC_ID[k] = 0;
                }
                else
                    PC_ID[k] = COLOUR[k].pixel;
            }
            XFlush ( VD_ID );

        }

    }

}
Example #23
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 #24
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 #25
0
static void
make_color_path(Display * dpy, Colormap cmap,
		int npoints, int *h, double *s, double *v,
		XColor * colors, int *ncolorsP,
		Bool allocate_p,
		Bool writable_p)
{
	int         i, k;
	int         total_ncolors = *ncolorsP;

	int         ncolors[MAXPOINTS];		/* number of pixels per edge */
	double      dh[MAXPOINTS];	/* distance between pixels, per edge (0 - 360.0) */
	double      ds[MAXPOINTS];	/* distance between pixels, per edge (0 - 1.0) */
	double      dv[MAXPOINTS];	/* distance between pixels, per edge (0 - 1.0) */

	if (npoints == 0) {
		*ncolorsP = 0;
		return;
	} else if (npoints == 2) {	/* using make_color_ramp() will be faster */
		make_color_ramp(dpy, cmap,
				h[0], s[0], v[0], h[1], s[1], v[1],
				colors, ncolorsP,
				True,	/* closed_p */
				allocate_p, writable_p);
		return;
	} else if (npoints >= MAXPOINTS) {
		npoints = MAXPOINTS - 1;
	}
      AGAIN:

	{
		double      DH[MAXPOINTS];	/* Distance between H values in the shortest

						   direction around the circle, that is, the
						   distance between 10 and 350 is 20.
						   (Range is 0 - 360.0.)
						 */
		double      edge[MAXPOINTS];	/* lengths of edges in unit HSV space. */
		double      ratio[MAXPOINTS];	/* proportions of the edges (total 1.0) */
		double      circum = 0;
		double      one_point_oh = 0;	/* (debug) */

		for (i = 0; i < npoints; i++) {
			int         j = (i + 1) % npoints;
			double      d = ((double) (h[i] - h[j])) / 360;

			if (d < 0)
				d = -d;
			if (d > 0.5)
				d = 0.5 - (d - 0.5);
			DH[i] = d;
		}

		for (i = 0; i < npoints; i++) {
			int         j = (i + 1) % npoints;

			edge[i] = sqrt((DH[i] * DH[j]) +
				       ((s[j] - s[i]) * (s[j] - s[i])) +
				       ((v[j] - v[i]) * (v[j] - v[i])));
			circum += edge[i];
		}

#ifdef DEBUG
		(void) fprintf(stderr, "\ncolors:");
		for (i = 0; i < npoints; i++)
			(void) fprintf(stderr, " (%d, %.3f, %.3f)", h[i], s[i], v[i]);
		(void) fprintf(stderr, "\nlengths:");
		for (i = 0; i < npoints; i++)
			(void) fprintf(stderr, " %.3f", edge[i]);
#endif /* DEBUG */

		if (circum < 0.0001)
			goto FAIL;

		for (i = 0; i < npoints; i++) {
			ratio[i] = edge[i] / circum;
			one_point_oh += ratio[i];
		}

#ifdef DEBUG
		(void) fprintf(stderr, "\nratios:");
		for (i = 0; i < npoints; i++)
			(void) fprintf(stderr, " %.3f", ratio[i]);
#endif /* DEBUG */

		if (one_point_oh < 0.99999 || one_point_oh > 1.00001)
			abort();

		/* space the colors evenly along the circumference -- that means that the
		   number of pixels on a edge is proportional to the length of that edge
		   (relative to the lengths of the other edges.)
		 */
		for (i = 0; i < npoints; i++)
			ncolors[i] = (int) (total_ncolors * ratio[i]);


#ifdef DEBUG
		(void) fprintf(stderr, "\npixels:");
		for (i = 0; i < npoints; i++)
			(void) fprintf(stderr, " %d", ncolors[i]);
		(void) fprintf(stderr, "  (%d)\n", total_ncolors);
#endif /* DEBUG */

		for (i = 0; i < npoints; i++) {
			int         j = (i + 1) % npoints;

			if (ncolors[i] > 0) {
				dh[i] = 360 * (DH[i] / ncolors[i]);
				ds[i] = (s[j] - s[i]) / ncolors[i];
				dv[i] = (v[j] - v[i]) / ncolors[i];
			}
		}
	}

	(void) memset(colors, 0, (*ncolorsP) * sizeof (*colors));

	k = 0;
	for (i = 0; i < npoints; i++) {
		int         distance, direction, j;

		distance = h[(i + 1) % npoints] - h[i];
		direction = (distance >= 0 ? -1 : 1);

		if (distance > 180)
			distance = 180 - (distance - 180);
		else if (distance < -180)
			distance = -(180 - ((-distance) - 180));
		else
			direction = -direction;

#ifdef DEBUG
		(void) fprintf(stderr, "point %d: %3d %.2f %.2f\n",
			i, h[i], s[i], v[i]);
		(void) fprintf(stderr, "  h[i]=%d  dh[i]=%.2f  ncolors[i]=%d\n",
			h[i], dh[i], ncolors[i]);
#endif /* DEBUG */
		for (j = 0; j < ncolors[i]; j++, k++) {
			double      hh = (h[i] + (j * dh[i] * direction));

			if (hh < 0)
				hh += 360;
			else if (hh > 360)
				hh -= 0;
			colors[k].flags = DoRed | DoGreen | DoBlue;
			hsv_to_rgb((int)
				   hh,
				   (s[i] + (j * ds[i])),
				   (v[i] + (j * dv[i])),
			  &colors[k].red, &colors[k].green, &colors[k].blue);
#ifdef DEBUG
			(void) fprintf(stderr, "point %d+%d: %.2f %.2f %.2f  %04X %04X %04X\n",
				i, j,
				hh,
				(s[i] + (j * ds[i])),
				(v[i] + (j * dv[i])),
			     colors[k].red, colors[k].green, colors[k].blue);
#endif /* DEBUG */
		}
	}

	/* Floating-point round-off can make us decide to use fewer colors. */
	if (k < *ncolorsP) {
		*ncolorsP = k;
		if (k <= 0)
			return;
	}
	if (!allocate_p)
		return;

	if (writable_p) {
		unsigned long *pixels = (unsigned long *)
		malloc(sizeof (unsigned long) * ((*ncolorsP) + 1));

		/* allocate_writable_colors() won't do here, because we need exactly this
		   number of cells, or the color sequence we've chosen won't fit. */
		if (!XAllocColorCells(dpy, cmap, False, 0, 0, pixels, *ncolorsP)) {
			free(pixels);
			goto FAIL;
		}
		for (i = 0; i < *ncolorsP; i++)
			colors[i].pixel = pixels[i];
		free(pixels);

		XStoreColors(dpy, cmap, colors, *ncolorsP);
	} else {
		for (i = 0; i < *ncolorsP; i++) {
			XColor      color;

			color = colors[i];
			if (XAllocColor(dpy, cmap, &color)) {
				colors[i].pixel = color.pixel;
			} else {
				free_colors(dpy, cmap, colors, i);
				goto FAIL;
			}
		}
	}

	return;

      FAIL:
	/* we weren't able to allocate all the colors we wanted;
	   decrease the requested number and try again.
	 */
	total_ncolors = (total_ncolors > 170 ? total_ncolors - 20 :
			 total_ncolors > 100 ? total_ncolors - 10 :
			 total_ncolors > 75 ? total_ncolors - 5 :
			 total_ncolors > 25 ? total_ncolors - 3 :
			 total_ncolors > 10 ? total_ncolors - 2 :
			 total_ncolors > 2 ? total_ncolors - 1 :
			 0);
	*ncolorsP = total_ncolors;
	if (total_ncolors > 0)
		goto AGAIN;
}
Example #26
0
/*---------------------------- HandleEvent --------------------------*/
int HandleEvent(XEvent *event)
{
  int	i;
    
  if(theEvent.xany.window==mainW) {

    switch (event->type) {
    case Expose: {
      XExposeEvent *exp_event = (XExposeEvent *) event;
 
      if (exp_event->window==mainW) {
	DrawWindow(exp_event->x,exp_event->y,
		   exp_event->width, exp_event->height);
      }
    }
    break;

    case EnterNotify: {
      if (Selected_Visual_Class==DirectColor)
	XStoreColors(theDisp,NewCmap,newC,ColorMapSize);
      if (Selected_Visual_Class!=TrueColor)
	XInstallColormap(theDisp,NewCmap);
    }
    break;
    
    case LeaveNotify: {
      if (Selected_Visual_Class==DirectColor)
	XStoreColors(theDisp,NewCmap,rootC,ColorMapSize); 
    }
    break;

    case KeyPress: {	/* allow a quit from the image window */
      Handle_KeyPress(event);
    }
    break;

    case MotionNotify: {
      Handle_Motion(event);
    }
    break;

    case ConfigureNotify: {
      XConfigureEvent *conf_event = (XConfigureEvent *) event;

      if (conf_event->window == cmdW && 
	  (conf_event->width != cmd_width ||
	   conf_event->height != cmd_height))
	XResizeWindow(theDisp,cmdW,cmd_width,cmd_height);
      if (conf_event->window == mainW && 
	  (conf_event->width != zWidth+(color_bar?color_bar_width:0) ||
	   conf_event->height != zHeight+info_height))
	Resize(conf_event->width-(color_bar?color_bar_width:0),
	       conf_event->height-info_height);
    }
    break;

    case ButtonPress: {
      if (theEvent.xbutton.button==Button1) {
	if (selzoom_active) {
	  Selective_Zoom((caddr_t)&one);
	  break;
	}
	XDefineCursor(theDisp,mainW,roiCursor);
	XFlush(theDisp);
	if (roi_present) draw_roi(roi_x1, roi_y1, roi_x2, roi_y2);
	roi_active = 1;
	roi_x1 = theEvent.xmotion.x < zWidth ?
	  (theEvent.xmotion.x>0 ?
	   theEvent.xmotion.x : 0) : zWidth-1;
	roi_y1 = theEvent.xmotion.y < zHeight ?
	  (theEvent.xmotion.y>0 ?
	   theEvent.xmotion.y : 0) : zHeight-1;
	roi_x2 = roi_x1;
	roi_y2 = roi_y1;
	draw_roi(roi_x1, roi_y1, roi_x2, roi_y2);
	break;
      } 
      if (theEvent.xbutton.button==Button2) {
	XDefineCursor(theDisp,mainW,wlCursor);
	XClearArea(theDisp,mainW,0,zHeight,
		   zWidth,zHeight+info_height,False);
	XDrawImageString(theDisp,mainW,theMGC,
			 zWidth-XTextWidth(ol_text_finfo,
					   wl_msg,strlen(wl_msg))-4,
			 zHeight+info_height-4,wl_msg,strlen(wl_msg));
	XDrawImageString(theDisp,mainW,theMGC,4,
			 zHeight+info_height-4,loc_msg,strlen(loc_msg));
	XFlush(theDisp);
	break;
      } 
      if (theEvent.xbutton.button==Button3) {
	/* note: not really 'iconic' anymore, simply map or unmap */
	if (cmdW_State==NormalState) {
	  XUnmapWindow(theDisp,cmdW);
	  cmdW_State = IconicState;
	}
	else {
	  XMapWindow(theDisp,cmdW);
	  cmdW_State = NormalState;
	}
	break;
      } 
    }
    break;

    case ButtonRelease: {
      int xa, xb, ya, yb;
      if (theEvent.xbutton.button==Button1 && roi_active) {
	roi_active = 0;
	xa = roi_x1*(Width-1)/(zWidth-1);
	xb = roi_x2*(Width-1)/(zWidth-1);
	ya = roi_y1*(Height-1)/(zHeight-1);
	yb = roi_y2*(Height-1)/(zHeight-1);
	roi_stats(xa, ya, xb, yb, 0);
	XDefineCursor(theDisp,mainW,mainCursor);
	XFlush(theDisp);
      }
      if (theEvent.xbutton.button==Button2) {
	XDefineCursor(theDisp,mainW,mainCursor);
	XFlush(theDisp);               
	if (Scale_Data && (oUpper != Upper || oLower != Lower)) {
	  Rescale();
	  Window_Level(Lower,Upper); 
	  oLower=Lower; oUpper=Upper; 
	}
	XClearArea(theDisp,mainW,0,zHeight,
		   zWidth,zHeight+info_height,False);
	if (wl_display) 
	  XDrawImageString(theDisp,mainW,theMGC,
			   zWidth-XTextWidth(ol_text_finfo,wl_msg,strlen(wl_msg))-4,
			   zHeight+info_height-4,wl_msg,strlen(wl_msg));
	XDrawImageString(theDisp,mainW,theMGC,4,
			 zHeight+info_height-4,loc_msg,strlen(loc_msg));
	update_sliders();
	update_msgs();
      }
    }
    break;

    case UnmapNotify: {
      if (bitmap_pad==8) {
	if (Interpolation_Type==BILINEAR) {
	  bilinear_byte_to_byte(byte_Image, Width, Height,
				icon_byte_image, ICON_WIDTH, ICON_HEIGHT);
	}
	else {
	  nneighbour_byte_to_byte(byte_Image, Width, Height,
				  icon_byte_image, ICON_WIDTH, ICON_HEIGHT);
	}
      }
      else {
	if (Interpolation_Type==BILINEAR) {
	  bilinear_rgbp_to_rgbp(byte_Image, Width, Height,
				icon_byte_image, ICON_WIDTH, ICON_HEIGHT);
	}
	else {
	  nneighbour_rgbp_to_rgbp(byte_Image, Width, Height,
				  icon_byte_image, ICON_WIDTH, ICON_HEIGHT);
	}
      }
      XPutImage(theDisp,iconW,theMGC,iconImage,0,0,0,0,
		ICON_WIDTH, ICON_HEIGHT);
    }
    break;
                
    case CirculateNotify:
    case MapNotify:
    case DestroyNotify:
    case GravityNotify:
    case ReparentNotify:
    default: 
    break;
    }  /* end of switch */
  }

  /* other command Window events */
  if(theEvent.xany.window==cmdW) {

    switch (event->type) {
    case Expose: {
      update_msgs();
    }
    break;

    case EnterNotify: {
      if (Selected_Visual_Class==DirectColor)
	XStoreColors(theDisp,NewCmap,newC,ColorMapSize); 
      if (Selected_Visual_Class!=TrueColor)
	XInstallColormap(theDisp,NewCmap);
    }
    break;

    case LeaveNotify: {
      if (Selected_Visual_Class==DirectColor)
	XStoreColors(theDisp,NewCmap,rootC,ColorMapSize); 
    }
    break;

    case UnmapNotify: {
      cmdW_State = IconicState;
    }
    break;
            
    case MapNotify: {
      cmdW_State = NormalState;
    }
    break;

    case ConfigureNotify: {
      XConfigureEvent *conf_event = (XConfigureEvent *) event;

      if (conf_event->window == cmdW && 
	  (conf_event->width != cmd_width ||
	   conf_event->height != cmd_height))
	XResizeWindow(theDisp,cmdW,cmd_width,cmd_height);
    }
    break;

    default: break;
    }
  }

  /* button press events */
  if (XFindContext(theDisp, theEvent.xany.window, xwin_context,
		   (caddr_t *) &which_xwin)==0) {
    if(*(which_xwin->event_handler)!=NULL)
      (*(which_xwin->event_handler))(which_xwin);
    if (Scale_Data && (oUpper != Upper || oLower != Lower)) {
      Rescale();
      oLower=Lower; oUpper=Upper;
    }
  }
}
Example #27
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 #28
0
/* copied from make_random_colormap in colors.c */
static void
make_mondrian_colormap (Screen *screen, Visual *visual, Colormap cmap,
		      XColor *colors, int *ncolorsP,
		      Bool allocate_p,
		      Bool *writable_pP,
		      Bool verbose_p)
{
  Display *dpy = DisplayOfScreen (screen);
  Bool wanted_writable = (allocate_p && writable_pP && *writable_pP);
  int ncolors = 8;
  int i;

  if (*ncolorsP <= 0) return;

  /* If this visual doesn't support writable cells, don't bother trying. */
  if (wanted_writable && !has_writable_cells(screen, visual))
    *writable_pP = False;

  for (i = 0; i < ncolors; i++)
  {
      colors[i].flags = DoRed|DoGreen|DoBlue;
      colors[i].red = 0;
      colors[i].green = 0;
      colors[i].blue = 0;

      switch(i) {
	  case 0: case 1: case 2: case 3: case 7: /* white */
	      colors[i].red = 0xE800;
	      colors[i].green = 0xE800;
	      colors[i].blue  = 0xE800;
	      break;
	  case 4:
	      colors[i].red = 0xCFFF; break; /* red */
	  case 5:
	      colors[i].red = 0x2000;
	      colors[i].blue = 0xCFFF; break; /* blue */
	  case 6:
	      colors[i].red = 0xDFFF; /* yellow */
	      colors[i].green = 0xCFFF; break;
      }
  }

  if (!allocate_p)
    return;

 RETRY_NON_WRITABLE:
  if (writable_pP && *writable_pP)
    {
      unsigned long *pixels = (unsigned long *)
	malloc(sizeof(*pixels) * (ncolors + 1));

      allocate_writable_colors (screen, cmap, pixels, &ncolors);
      if (ncolors > 0)
	for (i = 0; i < ncolors; i++)
	  colors[i].pixel = pixels[i];
      free (pixels);
      if (ncolors > 0)
	XStoreColors (dpy, cmap, colors, ncolors);
    }
  else
    {
      for (i = 0; i < ncolors; i++)
	{
	  XColor color;
	  color = colors[i];
	  if (!XAllocColor (dpy, cmap, &color))
	    break;
	  colors[i].pixel = color.pixel;
	}
      ncolors = i;
    }

  /* If we tried for writable cells and got none, try for non-writable. */
  if (allocate_p && ncolors == 0 && writable_pP && *writable_pP)
    {
      ncolors = *ncolorsP;
      *writable_pP = False;
      goto RETRY_NON_WRITABLE;
    }

#if 0
  /* I don't think we need to bother copying or linking to the complain
     function. */
  if (verbose_p)
    complain(*ncolorsP, ncolors, wanted_writable,
	     wanted_writable && *writable_pP);
#endif

  *ncolorsP = ncolors;
}
Example #29
0
/*-------------------------------------------------------------*/
void setup_display(Widget w)
{
    int i,j, cindex;
    int theScreen;
    XColor *colors = NULL;
    XGCValues     xgcv;
    Colormap      theColormap;
    XVisualInfo   *p_visinfo;
    XVisualInfo   *vis_list;
    XVisualInfo   vis_template;
    Widget *list_w = NULL;    /* List of widgets with its own colormap */

    theScreen = DefaultScreen(XtDisplay(w));
    vis_template.screen = theScreen;
    vis_list = XGetVisualInfo(XtDisplay(w),VisualScreenMask, &vis_template, &j);
    for (i=0, p_visinfo = vis_list; i<j;i++, p_visinfo++)
    {
    if(p_visinfo->class == PseudoColor && p_visinfo->depth == 8)
    { theVisual = p_visinfo->visual;
      vis_depth = p_visinfo->depth;
      break;
    }
    }

    theVisual = DefaultVisual(XtDisplay(w),theScreen);
    vis_depth = 8;  
    /* Create the XColor entries for the colormap */
    if((colors = (XColor *)calloc(COLORMAP_SIZE, sizeof(XColor))) == NULL) {
	fprintf(stderr, "No memory for setting up colormap\n");
	exit(1);
    }

    /* Set up the color cells to greyscale */
    for(cindex = 0; cindex < COLORMAP_SIZE; cindex++) {
	colors[cindex].red   = CSCALE * cindex;
	colors[cindex].green = CSCALE * cindex;
	colors[cindex].blue  = CSCALE * cindex;
	colors[cindex].pixel = cindex;
	colors[cindex].flags = DoRed | DoGreen | DoBlue;
    }

    /* Create the colormap */
    theColormap = XCreateColormap(XtDisplay(top_level), RootWindow(XtDisplay(top_level), theScreen),
				 theVisual, AllocAll);

    /* Store the colors into the colormap */
    XStoreColors(XtDisplay(top_level), theColormap, colors, COLORMAP_SIZE); 

    /* Set the background and foreground colors before free(colors) */
    bg = colors[0].pixel;
    fg = colors[255].pixel; 

    ysmap=XCopyColormapAndFree(XtDisplay(top_level), theColormap);

    /* Now we can release the memory used by the colors   */
    /* because the X server already has this information. */
    free(colors);

    /* Set background, foreground, visual_depth and colormap for draw_1 */
    argcount = 0;
    XtSetArg(args[argcount], XmNforeground, fg         ); argcount++;
    XtSetArg(args[argcount], XmNbackground, bg         ); argcount++;
    XtSetArg(args[argcount], XmNdepth     , vis_depth  ); argcount++;
    XtSetArg(args[argcount], XmNcolormap  , theColormap); argcount++; 
    XtSetValues(draw_1, args, argcount);

    /* Set background, foreground, visual_depth and colormap for draw_2 */
    argcount = 0;
    XtSetArg(args[argcount], XmNforeground, fg         ); argcount++;
    XtSetArg(args[argcount], XmNbackground, bg         ); argcount++;
    XtSetArg(args[argcount], XmNdepth     , vis_depth  ); argcount++;
    XtSetArg(args[argcount], XmNcolormap  , theColormap); argcount++; 
    XtSetValues(draw_2, args, argcount);
    
    /* Set the WM_COLORMAP_WINDOWS property so that the Motif */ 
    /* window manager knows about the windows that have their */
    /* own colormap.                                          */
    if(theColormap != DefaultColormap(XtDisplay(top_level), theScreen)) {
	list_w = (Widget *) malloc(2*sizeof(Widget));
	list_w[0] = draw_1;
	list_w[1] = draw_2;
	XtSetWMColormapWindows(top_level, list_w, (Cardinal) 2);
    } 
    
    /* Define a GC for both drawing areas with these colors */
    xgcv.foreground = fg;
    xgcv.background = bg;
    image_gc_1 = XCreateGC(XtDisplay(w), XtWindow(draw_1),
				(GCForeground | GCBackground), &xgcv);
    image_gc_2 = XCreateGC(XtDisplay(w), XtWindow(draw_2),
				(GCForeground | GCBackground), &xgcv);

    /* Define a GC to be used in editing image operations*/
    xgcv.foreground = fg ^ bg;
    xgcv.background = bg;
    xgcv.function = GXxor;
    xorGC = XtGetGC(draw_1, GCForeground | GCBackground | GCFunction, &xgcv);

    xgcv.foreground = fg;
    xgcv.background = bg;
    theGC = XtGetGC(draw_1, GCForeground | GCBackground, &xgcv);
}
Example #30
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;
  }