Esempio n. 1
0
void alloc_color(int32_t i, int32_t r, int32_t g, int32_t b)
{
    XColor col;

    col.red =	r; col.green = g; col.blue = b;
    col.flags = DoRed | DoGreen | DoBlue;
    if (XAllocColor(G->display, cmap, &col))
    {
	idx[i].pixel = col.pixel;
    }else
    {
	if (cmap == DefaultColormap(G->display, G->screen_number))
	{
	    cmap = XCopyColormapAndFree(G->display, cmap);
	    XSetWindowColormap(G->display, G->imagewindow, cmap);
	    col.red =	r; col.green = g; col.blue = b;
	    col.flags = DoRed | DoGreen | DoBlue;
	    if (XAllocColor(G->display, cmap, &col))
	    {
		idx[i].pixel = col.pixel;
		fprintf(stderr,"allocating pixel %d: %d %d %d\n",i,r,g,b);
	    } else {
		fprintf(stderr,"unable to allocate color %d: %d %d %d\n",i,r,g,b);
	    }
	}
    }
}
Esempio n. 2
0
long x11_allocate_color(GUI *gui, const RGB *rgb)
{
    X11Stuff *xstuff = gui->xstuff;
    XColor xc;
    
    xc.pixel = 0;
    xc.flags = DoRed | DoGreen | DoBlue;
    
    xc.red   = rgb->red   << (16 - CANVAS_BPCC);
    xc.green = rgb->green << (16 - CANVAS_BPCC);
    xc.blue  = rgb->blue  << (16 - CANVAS_BPCC);

    if (XAllocColor(xstuff->disp, xstuff->cmap, &xc)) {
        return xc.pixel;
    } else
    if (gui->install_cmap != CMAP_INSTALL_NEVER && 
        gui->private_cmap == FALSE) {
        xstuff->cmap = XCopyColormapAndFree(xstuff->disp, xstuff->cmap);
        gui->private_cmap = TRUE;
        
        /* try to allocate the same color in the private colormap */
        return x11_allocate_color(gui, rgb);
    } else {
        return -1;
    }
}
Esempio n. 3
0
int x11_init(GraceApp *gapp)
{
    X11Stuff *xstuff = gapp->gui->xstuff;
    XGCValues gc_val;
    long mrsize;
    int max_path_limit;
    
    xstuff->screennumber = DefaultScreen(xstuff->disp);
    xstuff->root = RootWindow(xstuff->disp, xstuff->screennumber);
 
    xstuff->gc = DefaultGC(xstuff->disp, xstuff->screennumber);
    
    xstuff->depth = DisplayPlanes(xstuff->disp, xstuff->screennumber);

    /* init colormap */
    xstuff->cmap = DefaultColormap(xstuff->disp, xstuff->screennumber);
    /* redefine colormap, if needed */
    if (gapp->gui->install_cmap == CMAP_INSTALL_ALWAYS) {
        xstuff->cmap = XCopyColormapAndFree(xstuff->disp, xstuff->cmap);
        gapp->gui->private_cmap = TRUE;
    }
    
    /* set GCs */
    if (gapp->gui->invert) {
        gc_val.function = GXinvert;
    } else {
        gc_val.function = GXxor;
    }
    gcxor = XCreateGC(xstuff->disp, xstuff->root, GCFunction, &gc_val);

    /* XExtendedMaxRequestSize() appeared in X11R6 */
#if XlibSpecificationRelease > 5
    mrsize = XExtendedMaxRequestSize(xstuff->disp);
#else
    mrsize = 0;
#endif
    if (mrsize <= 0) {
        mrsize = XMaxRequestSize(xstuff->disp);
    }
    max_path_limit = (mrsize - 3)/2;
    if (max_path_limit < get_max_path_limit(grace_get_canvas(gapp->grace))) {
        char buf[128];
        sprintf(buf,
            "Setting max drawing path length to %d (limited by the X server)",
            max_path_limit);
        errmsg(buf);
        set_max_path_limit(grace_get_canvas(gapp->grace), max_path_limit);
    }
    
    xstuff->dpi = rint(MM_PER_INCH*DisplayWidth(xstuff->disp, xstuff->screennumber)/
        DisplayWidthMM(xstuff->disp, xstuff->screennumber));

    return RETURN_SUCCESS;
}
Esempio n. 4
0
void XfsmInitializeColorMap()
{
  Display *ADisplay;
  Screen  *AScreen;

  ADisplay      = XtDisplay( XfsmTopLevel );
  AScreen       = XtScreen( XfsmTopLevel );
  XfsmColorMap = DefaultColormapOfScreen( AScreen );

  if ( XFSM_SWITCH_COLOR_MAP )
  {
    XfsmColorMap = XCopyColormapAndFree( ADisplay, XfsmColorMap );
    XInstallColormap( ADisplay, XfsmColorMap );
    XtVaSetValues( XfsmTopLevel, XmNcolormap, XfsmColorMap, NULL );
  }
}
Esempio n. 5
0
/*************************************************************
...
*************************************************************/
void color_error(void)
{
    static int using_private_cmap;

    if(using_private_cmap) {
        log(LOG_FATAL, "Private colormap ran out of entries -  exiting");
        exit(1);
    }
    else {
        log(LOG_NORMAL, "Ran out of colors -  trying with a private colormap");
        cmap=XCopyColormapAndFree(display, cmap);
        XtVaSetValues(toplevel, XtNcolormap, cmap, NULL);
        using_private_cmap=1;
    }

}
Esempio n. 6
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);
}
Esempio n. 7
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;
      }
}
Esempio n. 8
0
void init_graphics (char *window_name) {

 /* Open the toplevel window, get the colors, 2 graphics  *
  * contexts, load a font, and set up the toplevel window *
  * Calls build_menu to set up the menu.                  */

 char *display_name = NULL;
 int x, y;                                   /* window position */
 unsigned int border_width = 2;  /* ignored by OpenWindows */
 XTextProperty windowName;

/* X Windows' names for my colours. */
 char *cnames[NUM_COLOR] = {"white", "black", "grey55", "grey75", "blue", 
        "green", "yellow", "cyan", "red", "RGBi:0.0/0.5/0.0" };

 XColor exact_def;
 Colormap cmap;
 int i;
 unsigned long valuemask = 0; /* ignore XGCvalues and use defaults */
 XGCValues values;
 XEvent event;


 disp_type = SCREEN;         /* Graphics go to screen, not ps */

 for (i=0;i<=MAX_FONT_SIZE;i++) 
    font_is_loaded[i] = 0;     /* No fonts loaded yet. */

 /* connect to X server */
        /* connect to X server */
 if ( (display=XOpenDisplay(display_name)) == NULL )
 {
     fprintf( stderr, "Cannot connect to X server %s\n",
                          XDisplayName(display_name));
     exit( -1 );
 }

 /* get screen size from display structure macro */
 screen_num = DefaultScreen(display);
 display_width = DisplayWidth(display, screen_num);
 display_height = DisplayHeight(display, screen_num);

 x = y = 0;
        
 top_width = 2*display_width/3;
 top_height = 4*display_height/5;
 
 cmap = DefaultColormap(display, screen_num);
 private_cmap = None;

 for (i=0;i<NUM_COLOR;i++) {
    if (!XParseColor(display,cmap,cnames[i],&exact_def)) {
       fprintf(stderr, "Color name %s not in database", cnames[i]);
       exit(-1);
    }
    if (!XAllocColor(display, cmap, &exact_def)) {
       fprintf(stderr, "Couldn't allocate color %s.\n",cnames[i]); 

       if (private_cmap == None) {
          fprintf(stderr, "Will try to allocate a private colourmap.\n");
          fprintf(stderr, "Colours will only display correctly when your "
                          "cursor is in the graphics window.\n"
                          "Exit other colour applications and rerun this "
                          "program if you don't like that.\n\n");
                    
          private_cmap = XCopyColormapAndFree (display, cmap);
          cmap = private_cmap;
          if (!XAllocColor (display, cmap, &exact_def)) {
             fprintf (stderr, "Couldn't allocate color %s as private.\n",
                 cnames[i]);
             exit (1);
          }
       }

       else {
          fprintf (stderr, "Couldn't allocate color %s as private.\n",
              cnames[i]);
          exit (1);
       }
    }
    colors[i] = exact_def.pixel;
 }

 toplevel = XCreateSimpleWindow(display,RootWindow(display,screen_num),
          x, y, top_width, top_height, border_width, colors[BLACK],
          colors[WHITE]);  

 if (private_cmap != None) 
     XSetWindowColormap (display, toplevel, private_cmap);

 /* hints stuff deleted. */

 XSelectInput (display, toplevel, ExposureMask | StructureNotifyMask |
       ButtonPressMask);
 

 /* Create default Graphics Contexts.  valuemask = 0 -> use defaults. */
 gc = XCreateGC(display, toplevel, valuemask, &values);
 gc_menus = XCreateGC(display, toplevel, valuemask, &values);

 /* Create XOR graphics context for Rubber Banding */
 values.function = GXxor;   
 values.foreground = colors[BLACK];
 gcxor = XCreateGC(display, toplevel, (GCFunction | GCForeground),
       &values);
 
 /* specify font for menus.  */
 load_font(menu_font_size);
 font_is_loaded[menu_font_size] = 1;
 XSetFont(display, gc_menus, font_info[menu_font_size]->fid);

/* Set drawing defaults for user-drawable area.  Use whatever the *
 * initial values of the current stuff was set to.                */
 force_setfontsize(currentfontsize);
 force_setcolor (currentcolor);
 force_setlinestyle (currentlinestyle);
 force_setlinewidth (currentlinewidth);
 
 XStringListToTextProperty(&window_name, 1, &windowName);
 XSetWMName (display, toplevel, &windowName);
/* XSetWMIconName (display, toplevel, &windowName); */

 
 /* set line attributes */
/* XSetLineAttributes(display, gc, line_width, line_style,
           cap_style, join_style); */
 
 /* set dashes */
 /* XSetDashes(display, gc, dash_offset, dash_list, list_length); */

 XMapWindow (display, toplevel);
 build_textarea();
 build_menu();
 
/* The following is completely unnecessary if the user is using the       *
 * interactive (event_loop) graphics.  It waits for the first Expose      *
 * event before returning so that I can tell the window manager has got   *
 * the top-level window up and running.  Thus the user can start drawing  *
 * into this window immediately, and there's no danger of the window not  *
 * being ready and output being lost.                                     */

 XPeekIfEvent (display, &event, test_if_exposed, NULL); 
}
Esempio n. 9
0
void
fixColormap(ModeInfo * mi, int ncolors, float saturation,
	    Bool mono, Bool install, Bool inroot, Bool inwindow, Bool verbose)
{
	Display    *display = MI_DISPLAY(mi);
	Window     window = MI_WINDOW(mi);
	Screen     *scr = MI_SCREENPTR(mi);
	Colormap    cmap = MI_COLORMAP(mi);
	Colormap    dcmap = DefaultColormapOfScreen(scr);
	XColor      xcolor;
	unsigned char *red = (unsigned char *) NULL,
		*green = (unsigned char *) NULL,
		*blue = (unsigned char *) NULL;
	int         colorcount, i, fixed, visualclass;

#ifndef COMPLIANT_COLORMAP
	Bool        retry = False;

#endif

	if (mono || CellsOfScreen(scr) <= 2) {
		if (MI_PIXELS(mi))
			return;
		if ((MI_PIXELS(mi) = (unsigned long *) calloc(2,
				sizeof (unsigned long))) == NULL) {
			(void) fprintf(stderr, "could not get the 2 colors for mono\n");
		}

		monoColormap(scr, MI_SCREENINFO(mi), foreground, background);
		return;
	}
	colorcount = ncolors;
	if (((  red = (unsigned char *) calloc(ncolors,
			sizeof (unsigned char))) == NULL) ||
	    ((green = (unsigned char *) calloc(ncolors,
			sizeof (unsigned char))) == NULL) ||
	    (( blue = (unsigned char *) calloc(ncolors,
			sizeof (unsigned char))) == NULL)) {
		(void) fprintf(stderr, "could not get the %d colors\n", ncolors);
		if (red != NULL)
			free(red);
		if (green != NULL)
			free(green);
		return;
	}

	visualclass = MI_VISUALCLASS(mi);
	fixed = (visualclass == StaticGray) || (visualclass == StaticColor) ||
		(visualclass == TrueColor);
	if (
#ifdef USE_DTSAVER
		   dtsaver ||	/* needs to be in focus without mouse */

#endif
		   inroot || (!install && !fixed) || cmap == None) {
		cmap = dcmap;
	}
	if (cmap != dcmap && MI_PIXELS(mi)) {
		XFreeColors(display, cmap, MI_PIXELS(mi), MI_NPIXELS(mi), 0);
#ifndef COMPLIANT_COLORMAP
		XFreeColors(display, cmap, &(MI_BLACK_PIXEL(mi)), 1, 0);
		XFreeColors(display, cmap, &(MI_WHITE_PIXEL(mi)), 1, 0);
#endif
		XFreeColors(display, cmap, &(MI_BG_PIXEL(mi)), 1, 0);
		XFreeColors(display, cmap, &(MI_FG_PIXEL(mi)), 1, 0);
	}
	/* else if (cmap) { (void) printf("cmap: this case is possible?\n");  } */
	if (MI_PIXELS(mi))
		free(MI_PIXELS(mi));
	if ((MI_PIXELS(mi) = (unsigned long *) calloc(ncolors,
			sizeof (unsigned long))) == NULL) {
		(void) fprintf(stderr, "could not get the %d colors\n", ncolors);
	}
	/* "allocate" the black and white pixels, so that they
	   will be included by XCopyColormapAndFree() if it gets called */
#ifdef COMPLIANT_COLORMAP
	MI_BLACK_PIXEL(mi) = BlackPixelOfScreen(scr);
	MI_WHITE_PIXEL(mi) = WhitePixelOfScreen(scr);
#else
	MI_BLACK_PIXEL(mi) = allocPixel(display, cmap, "Black", "Black");
	MI_WHITE_PIXEL(mi) = allocPixel(display, cmap, "White", "White");
#endif
	MI_BG_PIXEL(mi) = allocPixel(display, cmap, background, "White");
	MI_FG_PIXEL(mi) = allocPixel(display, cmap, foreground, "Black");
	hsbramp(0.0, saturation, 1.0, 1.0, saturation, 1.0, colorcount,
		red, green, blue);

	MI_NPIXELS(mi) = 0;
	for (i = 0; i < colorcount; i++) {
		xcolor.red = red[i] << 8;
		xcolor.green = green[i] << 8;
		xcolor.blue = blue[i] << 8;
		xcolor.flags = DoRed | DoGreen | DoBlue;

		if (!XAllocColor(display, cmap, &xcolor)) {
#ifdef COMPLIANT_COLORMAP
			if (!install || cmap != dcmap)
				break;
			if ((cmap = XCopyColormapAndFree(display, cmap)) == dcmap)
				break;
			if (verbose)
				(void) fprintf(stderr, "using private colormap\n");
			if (!XAllocColor(display, cmap, &xcolor))
				break;
#else
			if (verbose)
				(void) fprintf(stderr, "ran out of colors on colormap\n");
			if ((saturation != 1.0 || ncolors != 64) && MI_NPIXELS(mi) < 2) {
				if (verbose)
					(void) fprintf(stderr,
						       "retrying with saturation = 1.0 and ncolors = 64\n");
				retry = True;
			}
			break;
#endif
		}
		MI_PIXELS(mi)[i] = xcolor.pixel;
		MI_NPIXELS(mi)++;
	}
	free(red);
	free(green);
	free(blue);
	if (verbose)
		(void) fprintf(stderr, "%d pixel%s allocated\n", MI_NPIXELS(mi),
			       (MI_NPIXELS(mi) == 1) ? "" : "s");
	if (MI_NPIXELS(mi) <= 4) {
		XFreeColors(display, cmap, MI_PIXELS(mi), MI_NPIXELS(mi), 0);
#ifndef COMPLIANT_COLORMAP
		XFreeColors(display, cmap, &(MI_BLACK_PIXEL(mi)), 1, 0);
		XFreeColors(display, cmap, &(MI_WHITE_PIXEL(mi) ), 1, 0);
#endif
		XFreeColors(display, cmap, &(MI_BG_PIXEL(mi)), 1, 0);
		XFreeColors(display, cmap, &(MI_FG_PIXEL(mi)), 1, 0);
#ifndef COMPLIANT_COLORMAP
		if (retry) {
			fixColormap(mi, 64, 1.0,
				    mono, install, inroot, inwindow, verbose);
			return;
		}
#endif
		monoColormap(scr, MI_SCREENINFO(mi), foreground, background);
		MI_COLORMAP(mi) = cmap = DefaultColormapOfScreen(scr);
		return;
	}
	MI_COLORMAP(mi) = cmap;
	if ((install || fixed) && !inroot && MI_NPIXELS(mi) > 2) {
#if 0
		(void) XGetWindowAttributes(display, window, &xgwa);
		if (cmap != xgwa.colormap)
#endif
#if 1				/* Turn off to simulate fvwm and tvwm */
			setColormap(display, window, cmap, inwindow);
#endif
	}
#if 0
	else {
		/* white and black colors may not be right for GL modes so lets set them */
		MI_BLACK_PIXEL(mi) = BlackPixelOfScreen(scr);
		MI_WHITE_PIXEL(mi) = WhitePixelOfScreen(scr);
		/* foreground and background colors may not be right.... */
		BlackPixelOfScreen(scr) = MI_BLACK_PIXEL(mi);
		WhitePixelOfScreen(scr) = MI_WHITE_PIXEL(mi);
	}
#endif
}