예제 #1
0
파일: XEStrMap.c 프로젝트: aosm/X11
static void loadExtStrings(XETC *tc)
{
    char **extensionName=XListExtensions(tc->dpy,&numExtension);
    if (numExtension)
    {
        int i;
        extensionData = (_extensionData *)XtCalloc(numExtension,
                            sizeof(_extensionData));
        for (i = 0; i < numExtension; i++)
        {   /* Arrange extensions in opcode order */
            int opcode,event,error;
            if (XQueryExtension(tc->dpy,extensionName[i],&opcode,&event,
                &error))
            {
                extensionData[opcode-128].extName = extensionName[i];
                extensionData[opcode-128].extEvent = event;
            }
            else
            {   /* This extension didn't load!  Error! */
                extensionData[opcode-128].extName = "Invalid_Extension";
            }
        }
        XFreeExtensionList(extensionName);
    }
}
예제 #2
0
int main(int argc, char const *argv[])
{
	Display *dpy = XOpenDisplay(NULL);
	int nextensions, i;
	char **p, **extensionList = XListExtensions(dpy, &nextensions);
	for(p = extensionList, i = 0; nextensions; i++, nextensions--, p++)
	{
		printf("Extension %d: %s\n", i + 1, *p);
	}
	return 0;
}
예제 #3
0
//=========================================
// usage
//-----------------------------------------
int XTestRender (XInit xi) {
	// ...
	// test if the render extension is available on the
	// currently used display
	// ---
	int n = 0; 
	int i = 0;
	char **extlist = XListExtensions (xi.dpy, &n);
	for (i = 0; i < n; i++) {
	if (strcmp(extlist[i],"RENDER") == 0) {
		return(1);
	}
	}
	return(0);
}
예제 #4
0
static gboolean check_for_xquartz(GdkDisplay *dpy)
{
	int nextensions;
	int i;
	gboolean match = FALSE;
	char **extensions = XListExtensions(gdk_x11_display_get_xdisplay(dpy),
					    &nextensions);
	for (i = 0 ; extensions != NULL && i < nextensions ; i++) {
		if (strcmp(extensions[i], "Apple-WM") == 0 ||
		    strcmp(extensions[i], "Apple-DRI") == 0)
			match = TRUE;
	}
	if (extensions)
		XFreeExtensionList(extensions);

	return match;
}
예제 #5
0
static Object P_List_Extensions (Object d) {
    Object ret;
    int n;
    register int i;
    register char **p;
    GC_Node;

    Check_Type (d, T_Display);
    Disable_Interrupts;
    p = XListExtensions (DISPLAY(d)->dpy, &n);
    Enable_Interrupts;
    ret = Make_Vector (n, Null);
    GC_Link (ret);
    for (i = 0; i < n; i++) {
        Object e;

        e = Make_String (p[i], strlen (p[i]));
        VECTOR(ret)->data[i] = e;
    }
    GC_Unlink;
    XFreeExtensionList (p);
    return ret;
}
예제 #6
0
int
main(int argc, char * argv[])
{
  int           loop, num_extensions, num_devices;
  char          **extensions;
  XDeviceInfo   *devices;
  Display       *dpy;
  Window        root_win;
  unsigned long screen;
  int		list = 0;
  
  if (argc != 3) {
    fprintf(stderr, "usage : %s <device name> (ABSOLUTE|RELATIVE)\n", argv[0]);
    exit(1);
  }

  if (strcmp(argv[1], "-l") == 0) {
    list = 1;
  }
  
  dpy = XOpenDisplay(NULL);

  if (!dpy) {
    printf("unable to connect to X Server try to set the DISPLAY variable\n");
    exit(1);
  }

#ifdef DEBUG
  printf("connected to %s\n", XDisplayString(dpy));
#endif

  screen = DefaultScreen(dpy);
  root_win = RootWindow(dpy, screen);

  extensions = XListExtensions(dpy, &num_extensions);
  for (loop = 0; loop < num_extensions &&
         (strcmp(extensions[loop], "XInputExtension") != 0); loop++);
  XFreeExtensionList(extensions);
  if (loop != num_extensions)
    {
      devices = XListInputDevices(dpy, &num_devices);
      for(loop=0; loop<num_devices; loop++)
        {
          if (devices[loop].name &&
              (StrCaseCmp(devices[loop].name, argv[1]) == 0))
            if (devices[loop].use == IsXExtensionDevice)
              {
                XDevice *device;
              
#ifdef DEBUG
                fprintf(stderr, "opening device %s\n",
                        devices[loop].name ? devices[loop].name : "<noname>");
#endif
                device = XOpenDevice(dpy, devices[loop].id);
                if (device)
                  {
		    XSetDeviceMode(dpy, device, (strcmp("ABSOLUTE", argv[2]) == 0) ? Absolute
				   : Relative);
                    exit(0);
                  }
                else
                  {
                    fprintf(stderr, "error opening device\n");
                    exit(1);
                  }
              }
        }
      XFreeDeviceList(devices);
    }
  else
    {
      fprintf(stderr, "No XInput extension available\n");
      exit(1);
    }
  
  if (list) {
    exit(0);
  }
  else {
    fprintf(stderr, "Extended device %s not found\n", argv[1]);
    exit(1);
  }
}
static int
X11Error(Display *display, XErrorEvent *event) {
  // Get an indication of how long ago the request that caused the error was
  // made.
  unsigned long age = NextRequest(display) - event->serial;

  // Get a string to represent the request that caused the error.
  nsAutoCString message;
  if (event->request_code < 128) {
    // Core protocol request
    message.AppendInt(event->request_code);
  } else {
    // Extension request

    // man XSetErrorHandler says "the error handler should not call any
    // functions (directly or indirectly) on the display that will generate
    // protocol requests or that will look for input events" so we use another
    // temporary Display to request extension information.  This assumes on
    // the DISPLAY environment variable has been set and matches what was used
    // to open |display|.
    Display *tmpDisplay = XOpenDisplay(NULL);
    if (tmpDisplay) {
      int nExts;
      char** extNames = XListExtensions(tmpDisplay, &nExts);
      int first_error;
      if (extNames) {
        for (int i = 0; i < nExts; ++i) {
          int major_opcode, first_event;
          if (XQueryExtension(tmpDisplay, extNames[i],
                              &major_opcode, &first_event, &first_error)
              && major_opcode == event->request_code) {
            message.Append(extNames[i]);
            message.Append('.');
            message.AppendInt(event->minor_code);
            break;
          }
        }

        XFreeExtensionList(extNames);
      }
      XCloseDisplay(tmpDisplay);

#ifdef MOZ_WIDGET_GTK2
      // GDK2 calls XCloseDevice the devices that it opened on startup, but
      // the XI protocol no longer ensures that the devices will still exist.
      // If they have been removed, then a BadDevice error results.  Ignore
      // this error.
      if (message.EqualsLiteral("XInputExtension.4") &&
          event->error_code == first_error + 0) {
        return 0;
      }
#endif
    }
  }

  char buffer[BUFSIZE];
  if (message.IsEmpty()) {
    buffer[0] = '\0';
  } else {
    XGetErrorDatabaseText(display, "XRequest", message.get(), "",
                          buffer, sizeof(buffer));
  }

  nsAutoCString notes;
  if (buffer[0]) {
    notes.Append(buffer);
  } else {
    notes.Append("Request ");
    notes.AppendInt(event->request_code);
    notes.Append('.');
    notes.AppendInt(event->minor_code);
  }

  notes.Append(": ");

  // Get a string to describe the error.
  XGetErrorText(display, event->error_code, buffer, sizeof(buffer));
  notes.Append(buffer);

  // For requests where Xlib gets the reply synchronously, |age| will be 1
  // and the stack will include the function making the request.  For
  // asynchronous requests, the current stack will often be unrelated to the
  // point of making the request, even if |age| is 1, but sometimes this may
  // help us count back to the point of the request.  With XSynchronize on,
  // the stack will include the function making the request, even though
  // |age| will be 2 for asynchronous requests because XSynchronize is
  // implemented by an empty request from an XSync, which has not yet been
  // processed.
  if (age > 1) {
    // XSynchronize returns the previous "after function".  If a second
    // XSynchronize call returns the same function after an enable call then
    // synchronization must have already been enabled.
    if (XSynchronize(display, True) == XSynchronize(display, False)) {
      notes.Append("; sync");
    } else {
      notes.Append("; ");
      notes.AppendInt(uint32_t(age));
      notes.Append(" requests ago");
    }
  }

#ifdef MOZ_CRASHREPORTER
  switch (XRE_GetProcessType()) {
  case GeckoProcessType_Default:
  case GeckoProcessType_Plugin:
  case GeckoProcessType_Content:
    CrashReporter::AppendAppNotesToCrashReport(notes);
    break;
  default: 
    ; // crash report notes not supported.
  }
#endif

#ifdef DEBUG
  // The resource id is unlikely to be useful in a crash report without
  // context of other ids, but add it to the debug console output.
  notes.Append("; id=0x");
  notes.AppendInt(uint32_t(event->resourceid), 16);
#ifdef MOZ_X11
  // Actually, for requests where Xlib gets the reply synchronously,
  // MOZ_X_SYNC=1 will not be necessary, but we don't have a table to tell us
  // which requests get a synchronous reply.
  if (!PR_GetEnv("MOZ_X_SYNC")) {
    notes.Append("\nRe-running with MOZ_X_SYNC=1 in the environment may give a more helpful backtrace.");
  }
#endif
#endif

#ifdef MOZ_WIDGET_QT
  // We should not abort here if MOZ_X_SYNC is not set
  // until http://bugreports.qt.nokia.com/browse/QTBUG-4042
  // not fixed, just print error value
  if (!PR_GetEnv("MOZ_X_SYNC")) {
    fprintf(stderr, "XError: %s\n", notes.get());
    return 0; // temporary workaround for bug 161472
  }
#endif

  NS_RUNTIMEABORT(notes.get());
  return 0; // not reached
}
예제 #8
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;
      }
}
예제 #9
0
// create a new window and set it's characteristics
Window OpenGLPbufferDisplayDevice::open_window(char *nm, int *size, int *loc,
					int argc, char** argv
) {
  char *dispname;
  if ((dispname = getenv("VMDGDISPLAY")) == NULL)
    dispname = getenv("DISPLAY");

  if(!(glxsrv.dpy = XOpenDisplay(dispname))) {
    msgErr << "Exiting due to X-Windows GLX/OpenGL Pbuffer creation failure." << sendmsg;
    if (dispname != NULL) {
      msgErr << "Failed to open display: " << dispname << sendmsg;
    }
    return (Window)0; 
  }


  //
  // Check for "Composite" extension and any others that might cause
  // stability issues and warn the user about any potential problems...
  //
  char **xextensionlist;
  int nextensions, xtn;
  int warncompositeext=0;
  xextensionlist = XListExtensions(glxsrv.dpy, &nextensions);
  for (xtn=0; xtn<nextensions; xtn++) {
//    printf("xtn[%d]: '%s'\n", xtn, xextensionlist[xtn]);
    if (xextensionlist[xtn] && !strcmp(xextensionlist[xtn], "Composite")) {
      warncompositeext=1;
    }
  }
  if (warncompositeext) {
    msgWarn << "Detected X11 'Composite' extension: if incorrect display occurs" << sendmsg;
    msgWarn << "try disabling this X server option.  Most OpenGL drivers" << sendmsg;
    msgWarn << "disable stereoscopic display when 'Composite' is enabled." << sendmsg;
  }
  XFreeExtensionList(xextensionlist);


  //
  // get info about root window
  //
  glxsrv.dpyScreen = DefaultScreen(glxsrv.dpy);
  glxsrv.rootWindowID = RootWindow(glxsrv.dpy, glxsrv.dpyScreen);
  screenX = DisplayWidth(glxsrv.dpy, glxsrv.dpyScreen);
  screenY = DisplayHeight(glxsrv.dpy, glxsrv.dpyScreen);

  // (3) make sure the GLX extension is available
  if (!glXQueryExtension(glxsrv.dpy, NULL, NULL)) {
    msgErr << "The X server does not support the OpenGL GLX extension." 
           << "   Exiting ..." << sendmsg;
    XCloseDisplay(glxsrv.dpy);
    return (Window)0;
  }

  ext->hasstereo = TRUE;         // stereo on until we find out otherwise.
  ext->stereodrawforced = FALSE; // no need for force stereo draws initially
  ext->hasmultisample = TRUE;    // multisample on until we find out otherwise.

  // Find the best matching OpenGL framebuffer config for our purposes
  GLXFBConfig *fbc;
  fbc = vmd_get_fbconfig(&glxsrv, &ext->hasstereo, &ext->hasmultisample, &ext->nummultisamples);
  if (fbc == NULL) {
    msgErr << "No OpenGL Pbuffer configurations available" << sendmsg;
    return (Window)0;
  }

  // Create the OpenGL Pbuffer and associated GLX context
  const int pbconf[] = {GLX_PBUFFER_WIDTH, DEF_PBUFFER_XRES, 
                        GLX_PBUFFER_HEIGHT, DEF_PBUFFER_YRES,
                        GLX_LARGEST_PBUFFER, 1,
                        GLX_PRESERVED_CONTENTS, 1, 
                        None};
  GLXPbuffer PBuffer = glXCreatePbuffer(glxsrv.dpy, fbc[0], pbconf);
  glxsrv.cx = glXCreateNewContext(glxsrv.dpy, fbc[0], GLX_RGBA_TYPE, 0, GL_TRUE);
  if (PBuffer == 0 || glxsrv.cx == NULL) {
    msgErr << "A TrueColor OpenGL Pbuffer is required, but not available." << sendmsg;
    msgErr << "The X server is not capable of displaying double-buffered," << sendmsg;
    msgErr << "RGB images with a Z buffer.   Exiting ..." << sendmsg;
    XCloseDisplay(glxsrv.dpy);
    return (Window)0;
  }

  // set maximum allowable rendered image size for the Pbuffer
  // that was actually allocated, which may be smaller than we hoped...
  PbufferMaxXsz = DEF_PBUFFER_XRES;
  PbufferMaxYsz = DEF_PBUFFER_YRES;
  glXQueryDrawable(glxsrv.dpy, PBuffer, GLX_WIDTH,  &PbufferMaxXsz);
  glXQueryDrawable(glxsrv.dpy, PBuffer, GLX_HEIGHT, &PbufferMaxYsz);

  msgInfo << "OpenGL Pbuffer size: " 
          << PbufferMaxXsz << "x"
          << PbufferMaxYsz << sendmsg;

  // set default image size to incoming values, when possible.
  xSize = size[0];
  ySize = size[1];
  if (xSize < 0 || xSize > PbufferMaxXsz || 
      ySize < 0 || ySize > PbufferMaxYsz) {
    msgWarn << "Ignored out-of-range OpenGL Pbuffer image dimension request: " 
            << xSize << "x" << ySize 
            << " (max: " 
            << PbufferMaxXsz << "x" << PbufferMaxYsz << ")" << sendmsg;
    xSize = PbufferMaxXsz;
    ySize = PbufferMaxYsz;
  }

  // make the Pbuffer active
  glXMakeContextCurrent(glxsrv.dpy, PBuffer, PBuffer, glxsrv.cx);
  glXMakeCurrent(glxsrv.dpy, PBuffer, glxsrv.cx);

  // If we have acquired a multisample buffer with GLX, we
  // still need to test to see if we can actually use it.
  if (ext->hasmultisample) {
    int msampeext = 0;

    // check for ARB multisampling
    if (ext->vmdQueryExtension("GL_ARB_multisample")) {
      msampeext = 1;
    }

    if (!msampeext) {
      ext->hasmultisample = FALSE;
      ext->nummultisamples = 0;
    }
  }

  // (9) configure the rendering properly
  setup_initial_opengl_state();  // setup initial OpenGL state

  // normal return: window was successfully created
  have_window = TRUE;

  // return window id
  return PBuffer;
}
예제 #10
0
파일: main.c 프로젝트: da4089/xguess
char *keyboard_guess(Display *display) {
  XKeyEvent k;
  KeySym    key;
  char      *res, *vendor;
  char      **extensions;
  char      **ext_name;
  int       n_extensions, i;

  extensions = XListExtensions(display, &n_extensions);
  if (extensions) {

    /* Does the server have the X Keyboard (XKB) extension */
    for (i=0, ext_name = extensions; i < n_extensions; i++) {
      if (strcmp(*ext_name, XKB_EXTENSION_NAME) == 0) {
	if ((res = xguess_from_xkb())) {
	  return res;
	}
      }
      ext_name++;
    }

    /* Does the server have the Apple Window Manager (Apple-WM) extension */
    for (i=0,ext_name = extensions; i < n_extensions; i++) {
      if (strcmp(*ext_name, APPLEWM_EXTENSION_NAME) == 0) {
        if ((res = xguess_from_apple())) {
          return res;
        }
      }
      ext_name++;
    }
  }

  /*-- is hostname same as display host? */
  if (is_local_server(display)) {
    res = (char *)local_guess();
    if (res != NULL) {
      return res;
    }
  }

  /*-- dummy KeyEvent to test KeyCode->KeySym mappings */

  k.type = KeyPress;
  k.serial = 1;
  k.send_event = 0;
  k.display = display;
  k.window = (Window)NULL;
  k.root = (Window)NULL;
  k.subwindow = (Window)NULL;
  k.time = 1;
  k.x = 1;
  k.y = 1;
  k.x_root = 1;
  k.y_root = 1;
  k.state = 0x0;
  k.same_screen = 1;

  /*-- get X Server manufacturer string */
  vendor = ServerVendor(display);

  if (strcmp(vendor, "MIT X Consortium") == 0) {
    /* vanilla R4 or R5 */
  } else if (strcmp(vendor, "X Consortium") == 0) {
    /* vanilla R6 */

  } else if (strcmp(vendor, NCD) == 0) {
    return ncd_guess(display);

  } else if (strncmp(vendor, "DECWINDOWS", 10) == 0) {
    /* something with a Digital X Server */

    k.keycode = 88;  /* Control_R on a PC-style keyboard */
    key = XLookupKeysym(&k, 0);
    if ((int)key == 0xffe4) {
      /* standard PC layout, various models ... */
  
      k.keycode = 9;  /* F1 on a DEC PCXAL*/
      key = XLookupKeysym(&k, 0);
      if ((int)key == 0xffbe) {
        return strdup("pc101-dec-pcxal");  /* eg. DEC AlphaStation 250 4/266 */
      }
  
      k.keycode = 16;  /* F1 on a standard PC */
      key = XLookupKeysym(&k, 0);
      if ((int)key == 0xffbe) {
        return strdup("pc101-unknown-pc101");  /* Honeywell,DEC PC7XL */
      }
    }
  
    k.keycode = 173;  /* Compose_R on a DEC LK401 */
    key = XLookupKeysym(&k, 0);
    if ((int)key == 0xff20) {
      return strdup("lk401-dec-lk401");          /* eg. DEC 3000/400 */
    }
  
    k.keycode = 194;  /* 'a' on a DEC LK201 */
    key = XLookupKeysym(&k, 0);
    if ((int)key == 0x61) {
      return strdup("lk201-dec-lk201");          /* eg. DECstation 3100 */
    }
  }

  /*-- no idea? guesswork time ... */

  k.keycode = 120;  /* Compose_R on an NCD DEC-style keyboard */
                    /* 'F1' on an IBM PC-style */
  key = XLookupKeysym(&k, 0);
  if ((int)key == 0xff20) {
    return strdup("ncd-dec-n108lk");         /* vindaloo */
  }

  if ((int)key == 0xffbe) {
    return strdup("pc101-ibm-5168572M");        /* IBM RS/6000 C10 */
  }

  /*-- give up and go home ... */

  fprintf(stderr, "-k option unable to determine keyboard type.\n");
  return strdup("unknown-unknown-unknown");
}
예제 #11
0
int
main(int argc, char * argv[])
{
  int           loop, num_extensions, num_devices;
  char          **extensions;
  XDeviceInfo   *devices;
  Display       *dpy;
  Window        root_win;
  unsigned long screen;
  int		list = 0;
  
  if (argc != 2) {
    fprintf(stderr, "usage : %s (-l | <device name>)\n", argv[0]);
    exit(1);
  }

  if (strcmp(argv[1], "-l") == 0) {
    list = 1;
  }
  
  dpy = XOpenDisplay(NULL);

  if (!dpy) {
    printf("unable to connect to X Server try to set the DISPLAY variable\n");
    exit(1);
  }

#ifdef DEBUG
  printf("connected to %s\n", XDisplayString(dpy));
#endif

  screen = DefaultScreen(dpy);
  root_win = RootWindow(dpy, screen);

  extensions = XListExtensions(dpy, &num_extensions);
  for (loop = 0; loop < num_extensions &&
         (strcmp(extensions[loop], "XInputExtension") != 0); loop++);
  XFreeExtensionList(extensions);
  if (loop != num_extensions)
    {
      devices = XListInputDevices(dpy, &num_devices);
      for(loop=0; loop<num_devices; loop++)
        {
	  if (list) {
	      printf("\"%s\"	[", devices[loop].name ? devices[loop].name : "<noname>");
	      switch(devices[loop].use) {
	      case IsXPointer:
		  printf("XPointer]\n");
		  break;
	      case IsXKeyboard:
		  printf("XKeyboard]\n");
		  break;
	      case IsXExtensionDevice:
		  printf("XExtensionDevice]\n");
		  break;
	      default:
		  printf("invalid value]\n");
		  break;
	      }
	  }
	  else {
          if ((argc == 2) && devices[loop].name &&
              (StrCaseCmp(devices[loop].name, argv[1]) == 0))
            if (devices[loop].use == IsXExtensionDevice)
              {
                XDevice *device;
              
#ifdef DEBUG
                fprintf(stderr, "opening device %s\n",
                        devices[loop].name ? devices[loop].name : "<noname>");
#endif
                device = XOpenDevice(dpy, devices[loop].id);
                if (device)
                  {
                    XChangePointerDevice(dpy, device, 0, 1);
                    exit(0);
                  }
                else
                  {
                    fprintf(stderr, "error opening device\n");
                    exit(1);
                  }
              }
	  }
        }
      XFreeDeviceList(devices);
    }
  else
    {
      fprintf(stderr, "No XInput extension available\n");
      exit(1);
    }
  
  if (list) {
    exit(0);
  }
  else {
    fprintf(stderr, "Extended device %s not found\n", argv[1]);
    exit(1);
  }
}
예제 #12
0
void
WindowMetrics::MeasureScreen(bool waitForWM)
{
#ifdef Q_WS_X11
    //
    // Create the test window
    //
    testWindow = new TestWin;
    testWindow->show();

    //
    // Try and determine if we're displaying X11 to a Mac.
    //
    int nExt = 0, appleDisplay = 0;
    char **ext = XListExtensions(QX11Info::display(), &nExt);
    for(int e = 0; e < nExt; ++e)
    {
        if(strcmp(ext[e], "Apple-DRI") == 0 ||
                strcmp(ext[e], "Apple-WM") == 0)
        {
            appleDisplay++;
        }
    }
    XFreeExtensionList(ext);

    //
    // Calculate the metrics
    //
    CalculateScreen(testWindow, screenX, screenY, screenW, screenH);

    // We need for the window manager to put borders on the window
    // before we can determine their sizes
    if(waitForWM)
        WaitForWindowManagerToGrabWindow(testWindow);

    // We tried to put the main window at 100,100...
    // ...see where it *really* started out
    preshiftX = 100;
    preshiftY = 100;
    CalculateTopLeft(testWindow, preshiftX, preshiftY);
    preshiftX -= 100;
    preshiftY -= 100;

    // Determine the border sizes of the main window.
    CalculateBorders(testWindow, borderT, borderB, borderL, borderR);

    // Move it to the top left (we think)
    testWindow->move(borderL,borderT);
    testWindow->resize(2,2);

    if(waitForWM)
    {
        do
        {
            // If it's not at 0,0, then we have a shift
            WaitForWindowManagerToMoveWindow(testWindow);
            CalculateTopLeft(testWindow, shiftX, shiftY);
        }
        while ((shiftX == preshiftX+100  &&  shiftY == preshiftY+100) &&
                appleDisplay == 0);
        // (sometimes we need to wait for more than one ConfigureNotify)
    }
    else
        CalculateTopLeft(testWindow, shiftX, shiftY);

    // Adjust preshift to account for the actual shift
    preshiftX += (borderL - shiftX);
    preshiftY += (borderT - shiftY);

    testWindow->hide();
#else
    //
    // Calculate the metrics
    //
    CalculateScreen(0, screenX, screenY, screenW, screenH);

    //
    // Determine the border sizes of the main window.
    //
    CalculateBorders(0, borderT, borderB, borderL, borderR);

#if defined(Q_WS_WIN)
    preshiftX = shiftX = borderL;
    preshiftY = shiftY = borderT;
#endif
#endif
}