示例#1
0
文件: slock.c 项目: iddumied/Slock
int
main(int argc, char **argv) {
  char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
	char buf[32], passwd[256];
	int num, screen;

#ifndef HAVE_BSD_AUTH
	const char *pws;
#endif
	unsigned int len;
	Bool running = True;
	Cursor invisible;
	Display *dpy;
	KeySym ksym;
	Pixmap pmap;
	Window root, w;
	XColor black, dummy;
	XEvent ev;
	XSetWindowAttributes wa;

	if((argc == 2) && !strcmp("-v", argv[1]))
		die("slock-"VERSION", © 2006-2008 Anselm R Garbe\n");
	else if(argc != 1)
		die("usage: slock [-vb]\n");
  
  backlight_of();
  
#ifndef HAVE_BSD_AUTH
	pws = get_password();
#endif

	if(!(dpy = XOpenDisplay(0)))
		die("slock: cannot open display\n");
	screen = DefaultScreen(dpy);
	root = RootWindow(dpy, screen);

	/* init */
	wa.override_redirect = 1;
	wa.background_pixel = BlackPixel(dpy, screen);
	w = XCreateWindow(dpy, root, 0, 0, DisplayWidth(dpy, screen), DisplayHeight(dpy, screen),
			0, DefaultDepth(dpy, screen), CopyFromParent,
			DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa);
	XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy);
	pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8);
	invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0);
	XDefineCursor(dpy, w, invisible);
	XMapRaised(dpy, w);
	for(len = 1000; len; len--) {
		if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
			GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
			break;
		usleep(1000);
	}
	if((running = running && (len > 0))) {
		for(len = 1000; len; len--) {
			if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
				== GrabSuccess)
				break;
			usleep(1000);
		}
		running = (len > 0);
	}
	len = 0;
	XSync(dpy, False);

	/* main event loop */
	while(running && !XNextEvent(dpy, &ev)) {
		if(len == 0 && DPMSCapable(dpy)) {
			DPMSEnable(dpy);
			DPMSForceLevel(dpy, DPMSModeOff);
		}
		if(ev.type == KeyPress) {
			buf[0] = 0;
			num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
			if(IsKeypadKey(ksym)) {
				if(ksym == XK_KP_Enter)
					ksym = XK_Return;
				else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
					ksym = (ksym - XK_KP_0) + XK_0;
			}
			if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
					|| IsMiscFunctionKey(ksym) || IsPFKey(ksym)
					|| IsPrivateKeypadKey(ksym))
				continue;
			switch(ksym) {
			case XK_Return:
				passwd[len] = 0;
#ifdef HAVE_BSD_AUTH
				running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
				running = strcmp(crypt(passwd, pws), pws);
#endif
				if (running != 0)
					XBell(dpy, 100);
				len = 0;
				break;
			case XK_Escape:
				len = 0;
				break;
			case XK_BackSpace:
				if(len)
					--len;
				break;
			default:
				if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) { 
					memcpy(passwd + len, buf, num);
					len += num;
				}
				break;
			}
		}
	}
	XUngrabPointer(dpy, CurrentTime);
	XFreePixmap(dpy, pmap);
	XDestroyWindow(dpy, w);
	XCloseDisplay(dpy);
  backlight_on();
	return 0;
}
示例#2
0
文件: drw.c 项目: Cornu/dwm
void
drw_free(Drw *drw) {
	XFreePixmap(drw->dpy, drw->drawable);
	XFreeGC(drw->dpy, drw->gc);
	free(drw);
}
示例#3
0
gfxXlibSurface::~gfxXlibSurface()
{
    if (mPixmapTaken) {
        XFreePixmap (mDisplay, mDrawable);
    }
}
示例#4
0
static void glxtest()
{
  // we want to redirect to /dev/null stdout, stderr, and while we're at it,
  // any PR logging file descriptors. To that effect, we redirect all positive
  // file descriptors up to what open() returns here. In particular, 1 is stdout and 2 is stderr.
  int fd = open("/dev/null", O_WRONLY);
  for (int i = 1; i < fd; i++)
    dup2(fd, i);
  close(fd);

  ///// Open libGL and load needed symbols /////
#ifdef __OpenBSD__
  #define LIBGL_FILENAME "libGL.so"
#else
  #define LIBGL_FILENAME "libGL.so.1"
#endif
  void *libgl = dlopen(LIBGL_FILENAME, RTLD_LAZY);
  if (!libgl)
    fatal_error("Unable to load " LIBGL_FILENAME);
  
  typedef void* (* PFNGLXGETPROCADDRESS) (const char *);
  PFNGLXGETPROCADDRESS glXGetProcAddress = cast<PFNGLXGETPROCADDRESS>(dlsym(libgl, "glXGetProcAddress"));
  
  if (!glXGetProcAddress)
    fatal_error("Unable to find glXGetProcAddress in " LIBGL_FILENAME);

  typedef GLXFBConfig* (* PFNGLXQUERYEXTENSION) (Display *, int *, int *);
  PFNGLXQUERYEXTENSION glXQueryExtension = cast<PFNGLXQUERYEXTENSION>(glXGetProcAddress("glXQueryExtension"));

  typedef GLXFBConfig* (* PFNGLXQUERYVERSION) (Display *, int *, int *);
  PFNGLXQUERYVERSION glXQueryVersion = cast<PFNGLXQUERYVERSION>(dlsym(libgl, "glXQueryVersion"));

  typedef GLXFBConfig* (* PFNGLXCHOOSEFBCONFIG) (Display *, int, const int *, int *);
  PFNGLXCHOOSEFBCONFIG glXChooseFBConfig = cast<PFNGLXCHOOSEFBCONFIG>(glXGetProcAddress("glXChooseFBConfig"));

  typedef XVisualInfo* (* PFNGLXGETVISUALFROMFBCONFIG) (Display *, GLXFBConfig);
  PFNGLXGETVISUALFROMFBCONFIG glXGetVisualFromFBConfig = cast<PFNGLXGETVISUALFROMFBCONFIG>(glXGetProcAddress("glXGetVisualFromFBConfig"));

  typedef GLXPixmap (* PFNGLXCREATEPIXMAP) (Display *, GLXFBConfig, Pixmap, const int *);
  PFNGLXCREATEPIXMAP glXCreatePixmap = cast<PFNGLXCREATEPIXMAP>(glXGetProcAddress("glXCreatePixmap"));

  typedef GLXContext (* PFNGLXCREATENEWCONTEXT) (Display *, GLXFBConfig, int, GLXContext, Bool);
  PFNGLXCREATENEWCONTEXT glXCreateNewContext = cast<PFNGLXCREATENEWCONTEXT>(glXGetProcAddress("glXCreateNewContext"));

  typedef Bool (* PFNGLXMAKECURRENT) (Display*, GLXDrawable, GLXContext);
  PFNGLXMAKECURRENT glXMakeCurrent = cast<PFNGLXMAKECURRENT>(glXGetProcAddress("glXMakeCurrent"));

  typedef void (* PFNGLXDESTROYPIXMAP) (Display *, GLXPixmap);
  PFNGLXDESTROYPIXMAP glXDestroyPixmap = cast<PFNGLXDESTROYPIXMAP>(glXGetProcAddress("glXDestroyPixmap"));

  typedef void (* PFNGLXDESTROYCONTEXT) (Display*, GLXContext);
  PFNGLXDESTROYCONTEXT glXDestroyContext = cast<PFNGLXDESTROYCONTEXT>(glXGetProcAddress("glXDestroyContext"));

  typedef GLubyte* (* PFNGLGETSTRING) (GLenum);
  PFNGLGETSTRING glGetString = cast<PFNGLGETSTRING>(glXGetProcAddress("glGetString"));

  if (!glXQueryExtension ||
      !glXQueryVersion ||
      !glXChooseFBConfig ||
      !glXGetVisualFromFBConfig ||
      !glXCreatePixmap ||
      !glXCreateNewContext ||
      !glXMakeCurrent ||
      !glXDestroyPixmap ||
      !glXDestroyContext ||
      !glGetString)
  {
    fatal_error("glXGetProcAddress couldn't find required functions");
  }
  ///// Open a connection to the X server /////
  Display *dpy = XOpenDisplay(NULL);
  if (!dpy)
    fatal_error("Unable to open a connection to the X server");
  
  ///// Check that the GLX extension is present /////
  if (!glXQueryExtension(dpy, NULL, NULL))
    fatal_error("GLX extension missing");
  
  ///// Check that the GLX version is >= 1.3, needed for glXCreatePixmap, bug 659932 /////
  int majorVersion, minorVersion;
  if (!glXQueryVersion(dpy, &majorVersion, &minorVersion))
    fatal_error("Unable to query GLX version");

  if (majorVersion < 1 || (majorVersion == 1 && minorVersion < 3))
    fatal_error("GLX version older than the required 1.3");

  XSetErrorHandler(x_error_handler);

  ///// Get a FBConfig and a visual /////
  int attribs[] = {
    GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
    GLX_X_RENDERABLE, True,
    0
  };
  int numReturned;
  GLXFBConfig *fbConfigs = glXChooseFBConfig(dpy, DefaultScreen(dpy), attribs, &numReturned );
  if (!fbConfigs)
    fatal_error("No FBConfigs found");
  XVisualInfo *vInfo = glXGetVisualFromFBConfig(dpy, fbConfigs[0]);
  if (!vInfo)
    fatal_error("No visual found for first FBConfig");

  ///// Get a Pixmap and a GLXPixmap /////
  Pixmap pixmap = XCreatePixmap(dpy, RootWindow(dpy, vInfo->screen), 4, 4, vInfo->depth);
  GLXPixmap glxpixmap = glXCreatePixmap(dpy, fbConfigs[0], pixmap, NULL);

  ///// Get a GL context and make it current //////
  GLXContext context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, NULL, True);
  glXMakeCurrent(dpy, glxpixmap, context);

  ///// Look for this symbol to determine texture_from_pixmap support /////
  void* glXBindTexImageEXT = glXGetProcAddress("glXBindTexImageEXT"); 

  ///// Get GL vendor/renderer/versions strings /////
  enum { bufsize = 1024 };
  char buf[bufsize];
  const GLubyte *vendorString = glGetString(GL_VENDOR);
  const GLubyte *rendererString = glGetString(GL_RENDERER);
  const GLubyte *versionString = glGetString(GL_VERSION);
  
  if (!vendorString || !rendererString || !versionString)
    fatal_error("glGetString returned null");

  int length = snprintf(buf, bufsize,
                        "VENDOR\n%s\nRENDERER\n%s\nVERSION\n%s\nTFP\n%s\n",
                        vendorString,
                        rendererString,
                        versionString,
                        glXBindTexImageEXT ? "TRUE" : "FALSE");
  if (length >= bufsize)
    fatal_error("GL strings length too large for buffer size");

  ///// Clean up. Indeed, the parent process might fail to kill us (e.g. if it doesn't need to check GL info)
  ///// so we might be staying alive for longer than expected, so it's important to consume as little memory as
  ///// possible. Also we want to check that we're able to do that too without generating X errors.
  glXMakeCurrent(dpy, None, NULL); // must release the GL context before destroying it
  glXDestroyContext(dpy, context);
  glXDestroyPixmap(dpy, glxpixmap);
  XFreePixmap(dpy, pixmap);
  XCloseDisplay(dpy);
  dlclose(libgl);

  ///// Finally write data to the pipe
  write(write_end_of_the_pipe, buf, length);
}
示例#5
0
gboolean
myDisplayTestXrender (DisplayInfo *display, gdouble min_time)
{
#ifdef HAVE_RENDER
    GTimeVal t1, t2;
    gdouble dt;
    Display *dpy;
    Picture picture1, picture2, picture3;
    XRenderPictFormat *format_src, *format_dst;
    Pixmap fillPixmap, rootPixmap;
    XRenderPictureAttributes pa;
    XSetWindowAttributes attrs;
    XImage *ximage;
    Window output;
    XRenderColor c;
    Visual *visual;
    Screen *screen;
    int x, y, w, h;
    int screen_number;
    int depth;
    int iterations;

    g_return_val_if_fail (display != NULL, FALSE);
    TRACE ("entering myDisplayTesxrender");

    c.alpha = 0x7FFF;
    c.red   = 0xFFFF;
    c.green = 0xFFFF;
    c.blue  = 0xFFFF;

    dpy = display->dpy;
    screen_number = DefaultScreen (dpy);
    screen = DefaultScreenOfDisplay (dpy);
    visual = DefaultVisual (dpy, screen_number);
    depth = DefaultDepth (dpy, screen_number);

    w = WidthOfScreen(screen) / 16;
    h = HeightOfScreen(screen) / 16;
    x = (WidthOfScreen(screen) - w);
    y = (HeightOfScreen(screen) - h);

    format_dst = XRenderFindVisualFormat (dpy, visual);
    g_return_val_if_fail (format_dst != NULL , FALSE);

    format_src = XRenderFindStandardFormat (dpy, PictStandardA8);
    g_return_val_if_fail (format_src != NULL , FALSE);

    ximage = XGetImage (dpy,
                        DefaultRootWindow(dpy),
                        x, y, w, h,
                        AllPlanes, ZPixmap);
    g_return_val_if_fail (ximage != NULL , FALSE);

    rootPixmap = XCreatePixmap (dpy,
                                DefaultRootWindow(dpy),
                                w, h, depth);
    XPutImage (dpy, rootPixmap,
               DefaultGC (dpy, screen_number), ximage,
               0, 0, 0, 0, w, h);
    XDestroyImage (ximage);

    attrs.override_redirect = TRUE;
    output = XCreateWindow (dpy,
                            DefaultRootWindow(dpy),
                            x, y, w, h,
                            0, CopyFromParent, CopyFromParent,
                            (Visual *) CopyFromParent,
                            CWOverrideRedirect, &attrs);
    XMapRaised (dpy, output);

    fillPixmap = XCreatePixmap (dpy,
                                DefaultRootWindow(dpy),
                                1, 1, 8);

    g_get_current_time (&t1);

    pa.repeat = TRUE;
    picture1 = XRenderCreatePicture (dpy,
                                     rootPixmap,
                                     format_dst, 0, NULL);
    picture2 = XRenderCreatePicture (dpy,
                                     fillPixmap,
                                     format_src, CPRepeat, &pa);
    picture3 = XRenderCreatePicture (dpy,
                                     output,
                                     format_dst, 0, NULL);
    XRenderComposite (dpy, PictOpSrc,
                    picture1, None, picture3,
                    0, 0, 0, 0, 0, 0, w, h);
    XRenderFillRectangle (dpy, PictOpSrc,
                          picture2, &c, 0, 0,
                          1, 1);
    for (iterations = 0; iterations < 10; iterations++)
    {
        XRenderComposite (dpy, PictOpOver,
                        picture1, picture2, picture3,
                        0, 0, 0, 0, 0, 0, w, h);
        ximage = XGetImage (dpy, output,
                            0, 0, 1, 1,
                            AllPlanes, ZPixmap);
        if (ximage)
        {
                XDestroyImage (ximage);
        }
    }
    XRenderFreePicture (dpy, picture1);
    XRenderFreePicture (dpy, picture2);
    XRenderFreePicture (dpy, picture3);

    XFreePixmap (dpy, fillPixmap);
    XFreePixmap (dpy, rootPixmap);

    XDestroyWindow (dpy, output);

    g_get_current_time (&t2);

    dt = (gdouble) (t2.tv_sec - t1.tv_sec) * G_USEC_PER_SEC +
         (gdouble) (t2.tv_usec - t1.tv_usec) / 1000.0;

    if (dt < min_time)
    {
        TRACE ("XRender test passed (target %3.4f sec., measured %3.4f sec.).", min_time, dt);
        return TRUE;
    }
    g_print ("XRender test failed (target %3.4f sec., measured %3.4f sec.).\n", min_time, dt);
    return FALSE;
#else  /* HAVE_RENDER */
    return FALSE;
#endif /* HAVE_RENDER */
}
示例#6
0
static cairo_test_status_t
do_test (const cairo_test_context_t *ctx,
         Display        *dpy,
         unsigned char  *reference_data,
         unsigned char  *test_data,
         unsigned char  *diff_data,
         cairo_bool_t    use_pixmap,
         cairo_bool_t    set_size,
         cairo_bool_t    offscreen)
{
    cairo_surface_t *surface;
    cairo_surface_t *test_surface;
    cairo_t *test_cr;
    buffer_diff_result_t result;
    Drawable drawable;
    int screen = DefaultScreen (dpy);

    if (use_pixmap && offscreen)
        return CAIRO_TEST_SUCCESS;

    if (use_pixmap) {
        drawable = XCreatePixmap (dpy, DefaultRootWindow (dpy),
                                  SIZE, SIZE, DefaultDepth (dpy, screen));
    } else {
        XSetWindowAttributes xwa;
        int x, y;

        xwa.override_redirect = True;

        if (offscreen) {
            x = - OFFSCREEN_OFFSET;
            y = - OFFSCREEN_OFFSET;
        } else {
            x = 0;
            y = 0;
        }

        drawable = XCreateWindow (dpy, DefaultRootWindow (dpy),
                                  x, y, SIZE, SIZE, 0,
                                  DefaultDepth (dpy, screen), InputOutput,
                                  DefaultVisual (dpy, screen),
                                  CWOverrideRedirect, &xwa);
        XMapWindow (dpy, drawable);
    }

    surface = cairo_xlib_surface_create (dpy,
                                         drawable,
                                         DefaultVisual (dpy, screen),
                                         SIZE, SIZE);

    if (! surface_compare_visual_and_format (surface))
        return CAIRO_TEST_FAILURE;

    if (set_size) {
        cairo_xlib_surface_set_size (surface, SIZE, SIZE);

        if (cairo_xlib_surface_get_width (surface) != SIZE ||
                cairo_xlib_surface_get_height (surface) != SIZE)
            return CAIRO_TEST_FAILURE;
    }

    if (! check_similar_visual_and_format (surface))
        return CAIRO_TEST_FAILURE;

    draw_pattern (surface);

    test_surface = cairo_image_surface_create_for_data (test_data,
                   CAIRO_FORMAT_RGB24,
                   SIZE, SIZE,
                   SIZE * 4);

    test_cr = cairo_create (test_surface);
    cairo_set_source_surface (test_cr, surface, 0, 0);
    cairo_paint (test_cr);

    cairo_destroy (test_cr);
    cairo_surface_destroy (test_surface);

    /* We erase the surface to black in case we get the same
     * memory back again for the pixmap case.
     */
    erase_pattern (surface);
    cairo_surface_destroy (surface);

    if (use_pixmap)
        XFreePixmap (dpy, drawable);
    else
        XDestroyWindow (dpy, drawable);

    if (offscreen) {
        size_t offset = 4 * (SIZE * OFFSCREEN_OFFSET + OFFSCREEN_OFFSET);

        buffer_diff_noalpha (reference_data + offset,
                             test_data + offset,
                             diff_data + offset,
                             SIZE - OFFSCREEN_OFFSET,
                             SIZE - OFFSCREEN_OFFSET,
                             4 * SIZE,
                             &result);
    } else {
        buffer_diff_noalpha (reference_data,
                             test_data,
                             diff_data,
                             SIZE,
                             SIZE,
                             4 * SIZE,
                             &result);
    }

    cairo_test_log (ctx, "xlib-surface: %s, %s, %s: %s\n",
                    set_size ? "   size" : "no-size",
                    use_pixmap ? "pixmap" : "window",
                    use_pixmap ?  "           " : (offscreen ? ", offscreen" : ",  onscreen"),
                    image_diff_is_failure (&result, 0) ? "FAIL" : "PASS");

    if (image_diff_is_failure (&result, 0))
        return CAIRO_TEST_FAILURE;
    else
        return CAIRO_TEST_SUCCESS;
}
示例#7
0
void
init_puzzle(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	puzzlestruct *pp;
	int         x, y;
	XPoint      size;

	if (puzzles == NULL) {
		if ((puzzles = (puzzlestruct *) calloc(MI_NUM_SCREENS(mi),
					     sizeof (puzzlestruct))) == NULL)
			return;
	}
	pp = &puzzles[MI_SCREEN(mi)];

	if (pp->painted && pp->windowsize.x == MI_WIDTH(mi) &&
	    pp->windowsize.y == MI_HEIGHT(mi))
		return;		/* Debounce since refresh_puzzle is init_puzzle */

#ifdef HAVE_XPM
	if (pp->graphics_format >= IS_XPM) {
        	/* This is needed when another program changes the colormap. */
        	free_puzzle(display, pp);
	}
#endif
	if (!init_stuff(mi))
		return;
	pp->excount = MI_COUNT(mi);
	if (pp->excount < 0) {
		if (pp->fixbuff != NULL) {
			free(pp->fixbuff);
			pp->fixbuff = (int *) NULL;
		}
		pp->excount = NRAND(-pp->excount) + 1;
	}
	pp->lastbox = -1;
	pp->moves = 0;
	pp->movingBox = False;

	pp->windowsize.x = MI_WIDTH(mi);
	pp->windowsize.y = MI_HEIGHT(mi);
	if (pp->windowsize.x < 7)
		pp->windowsize.x = 7;
	if (pp->windowsize.y < 7)
		pp->windowsize.y = 7;
	pp->forward = 1;
	pp->prev = 0;
	/* don't want any exposure events from XCopyArea */
	XSetGraphicsExposures(display, pp->backGC, False);

	MI_CLEARWINDOWCOLORMAP(mi, pp->backGC, pp->black);

	if (pp->logo) {
		size.x = (pp->logo->width < pp->windowsize.x) ?
			pp->logo->width : pp->windowsize.x;
		size.y = (pp->logo->height < pp->windowsize.y) ?
			pp->logo->height : pp->windowsize.y;
	} else {
		size.x = pp->windowsize.x;
		size.y = pp->windowsize.y;
	}
	pp->boxsize.y = NRAND(1 + size.y / 4) + 6;
	pp->boxsize.x = NRAND(1 + size.x / 4) + 6;
	if ((pp->boxsize.x > 4 * pp->boxsize.y) ||
	    pp->boxsize.y > 4 * pp->boxsize.x)
		pp->boxsize.x = pp->boxsize.y = 2 * MIN(pp->boxsize.x, pp->boxsize.y);
	pp->count.x = size.x / pp->boxsize.x;
	pp->count.y = size.y / pp->boxsize.y;

	if (pp->bufferBox != None) {
		XFreePixmap(display, pp->bufferBox);
		pp->bufferBox = None;
	}
	pp->usablewindow.x = pp->count.x * pp->boxsize.x;
	pp->usablewindow.y = pp->count.y * pp->boxsize.y;
	pp->offsetwindow.x = (pp->windowsize.x - pp->usablewindow.x) / 2;
	pp->offsetwindow.y = (pp->windowsize.y - pp->usablewindow.y) / 2;

	pp->incrementOfMove = MIN(pp->usablewindow.x, pp->usablewindow.y) / 20;
	pp->incrementOfMove = MAX(pp->incrementOfMove, 1);

	if (pp->logo) {
		pp->randompos.x = NRAND(MAX((pp->windowsize.x - pp->logo->width),
					    2 * pp->offsetwindow.x + 1));
		pp->randompos.y = NRAND(MAX((pp->windowsize.y - pp->logo->height),
					    2 * pp->offsetwindow.y + 1));
		if (MI_NPIXELS(mi) <= 2)
			XSetForeground(display, pp->backGC, MI_WHITE_PIXEL(mi));
		else
			XSetForeground(display, pp->backGC, MI_PIXEL(mi, NRAND(MI_NPIXELS(mi))));
		(void) XPutImage(display, window, pp->backGC, pp->logo,
		(int) (NRAND(MAX(1, (pp->logo->width - pp->usablewindow.x)))),
				 (int) (NRAND(MAX(1, (pp->logo->height - pp->usablewindow.y)))),
				 pp->randompos.x, pp->randompos.y,
				 pp->usablewindow.x, pp->usablewindow.y);
		XSetForeground(display, pp->backGC, pp->black);
		for (x = 0; x <= pp->count.x; x++) {
			int         tempx = x * pp->boxsize.x;

			XDrawLine(display, window, pp->backGC,
				  tempx + pp->randompos.x, pp->randompos.y,
				  tempx + pp->randompos.x, pp->usablewindow.y + pp->randompos.y);
			XDrawLine(display, window, pp->backGC,
				tempx + pp->randompos.x - 1, pp->randompos.y,
				  tempx + pp->randompos.x - 1, pp->usablewindow.y + pp->randompos.y);
		}
		for (y = 0; y <= pp->count.y; y++) {
			int         tempy = y * pp->boxsize.y;

			XDrawLine(display, window, pp->backGC,
				  pp->randompos.x, tempy + pp->randompos.y,
				  pp->usablewindow.x + pp->randompos.x, tempy + pp->randompos.y);
			XDrawLine(display, window, pp->backGC,
				pp->randompos.x, tempy + pp->randompos.y - 1,
				  pp->usablewindow.x + pp->randompos.x, tempy + pp->randompos.y - 1);
		}
	}
#ifdef NUMBERED
	else {
		if (pp->image)
			(void) XDestroyImage(pp->image);
		pp->randompos.x = pp->offsetwindow.x;
		pp->randompos.y = pp->offsetwindow.y;
		if (!NumberScreen(mi)) {
			release_puzzles(mi);
			return;
		}
		if ((pp->image = XGetImage(display, window,
				      pp->offsetwindow.x, pp->offsetwindow.y,
				      pp->usablewindow.x, pp->usablewindow.y,
				      AllPlanes,
				 (MI_NPIXELS(mi) <= 2) ? XYPixmap : ZPixmap)) == None) {
			free_puzzle(display, pp);
			return;
		}
	}

	pp->row = pp->count.y - 1;
	pp->col = pp->count.x - 1;
#else
	pp->row = NRAND(pp->count.y);
	pp->col = NRAND(pp->count.x);
#endif

	if ((pp->excount) && (pp->fixbuff == NULL))
		if ((pp->fixbuff = (int *) calloc(pp->excount,
				sizeof (int))) == NULL) {
			free_puzzle(display, pp);
			return;
		}
	pp->painted = True;
}
示例#8
0
/*ARGSUSED*/
void
XmuCvtStringToCursor(XrmValuePtr args, Cardinal *num_args,
		     XrmValuePtr fromVal, XrmValuePtr toVal)
{
    static Cursor cursor;		/* static for cvt magic */
    char *name = (char *)fromVal->addr;
    Screen *screen;
    register int i;
    char maskname[PATH_MAX];
    Pixmap source, mask = 0;
    /* XXX - make fg/bg resources */
    static XColor bgColor = {0, 0xffff, 0xffff, 0xffff};
    static XColor fgColor = {0, 0, 0, 0};
    int xhot, yhot;
    int len;


    if (*num_args != 1)
     XtErrorMsg("wrongParameters","cvtStringToCursor","XtToolkitError",
             "String to cursor conversion needs screen argument",
              (String *)NULL, (Cardinal *)NULL);

    if (XmuCompareISOLatin1(name, "None") == 0)
      {
	cursor = None;
	done(&cursor, Cursor);
	return;
      }

    screen = *((Screen **) args[0].addr);

    if (0 == strncmp(FONTSPECIFIER, name, strlen(FONTSPECIFIER))) {
	char source_name[PATH_MAX], mask_name[PATH_MAX];
	int source_char, mask_char, fields = 0;
	Font source_font, mask_font;
	XrmValue fromString, toFont;
	XrmValue cvtArg;
	Boolean success;
	Display *dpy = DisplayOfScreen(screen);
	char *strspec = NULL;
	int strspeclen;
#ifdef XMU_KLUDGE
	Cardinal num;
#endif

	strspeclen = strlen("FONT %s %d %s %d") + 21;
	strspec = XtMalloc(strspeclen);
	if (strspec != NULL) {
	    snprintf(strspec, strspeclen, "FONT %%%lds %%d %%%lds %%d",
		     (unsigned long)sizeof(source_name) - 1,
		     (unsigned long)sizeof(mask_name) - 1);
	    fields = sscanf(name, strspec,
			    source_name, &source_char,
			    mask_name, &mask_char);
	    XtFree(strspec);
	}
	if (fields < 2) {
	    XtStringConversionWarning(name, XtRCursor);
	    return;
	}

	fromString.addr = source_name;
	fromString.size = strlen(source_name) + 1;
	toFont.addr = (XPointer) &source_font;
	toFont.size = sizeof(Font);
	cvtArg.addr = (XPointer) &dpy;
	cvtArg.size = sizeof(Display *);
	/* XXX using display of screen argument as message display */
#ifdef XMU_KLUDGE
	/* XXX Sacrifice caching */
	num = 1;
	success = XtCvtStringToFont(dpy, &cvtArg, &num, &fromString, &toFont,
				    NULL);
#else
	success = XtCallConverter(dpy, XtCvtStringToFont, &cvtArg,
				  (Cardinal)1, &fromString, &toFont, NULL);
#endif
	if (!success) {
	    XtStringConversionWarning(name, XtRCursor);
	    return;
	}

	switch (fields) {
	  case 2:		/* defaulted mask font & char */
	    mask_font = source_font;
	    mask_char = source_char;
	    break;

	  case 3:		/* defaulted mask font */
	    mask_font = source_font;
	    mask_char = atoi(mask_name);
	    break;

	  case 4:		/* specified mask font & char */
	    fromString.addr = mask_name;
	    fromString.size = strlen(mask_name) + 1;
	    toFont.addr = (XPointer) &mask_font;
	    toFont.size = sizeof(Font);
	    /* XXX using display of screen argument as message display */
#ifdef XMU_KLUDGE
	    /* XXX Sacrifice caching */
	    num = 1;
	    success = XtCvtStringToFont(dpy, &cvtArg, &num, &fromString,
					&toFont, NULL);
#else
	    success = XtCallConverter(dpy, XtCvtStringToFont, &cvtArg,
				      (Cardinal)1, &fromString, &toFont, NULL);
#endif
	    if (!success) {
		XtStringConversionWarning(name, XtRCursor);
		return;
	    }
	}

	cursor = XCreateGlyphCursor( DisplayOfScreen(screen), source_font,
				     mask_font, source_char, mask_char,
				     &fgColor, &bgColor );
	done(&cursor, Cursor);
	return;
    }

    i = XmuCursorNameToIndex (name);
    if (i != -1) {
	cursor = XCreateFontCursor (DisplayOfScreen(screen), i);
	done(&cursor, Cursor);
	return;
    }

    if ((source = XmuLocateBitmapFile (screen, name,
				       maskname, (sizeof maskname) - 4,
				       NULL, NULL, &xhot, &yhot)) == None) {
	XtStringConversionWarning (name, XtRCursor);
	cursor = None;
	done(&cursor, Cursor);
	return;
    }
    len = strlen (maskname);
    for (i = 0; i < 2; i++) {
	strcpy (maskname + len, i == 0 ? "Mask" : "msk");
	if ((mask = XmuLocateBitmapFile (screen, maskname, NULL, 0,
					 NULL, NULL, NULL, NULL)) != None)
	  break;
    }

    cursor = XCreatePixmapCursor( DisplayOfScreen(screen), source, mask,
				  &fgColor, &bgColor, xhot, yhot );
    XFreePixmap( DisplayOfScreen(screen), source );
    if (mask != None) XFreePixmap( DisplayOfScreen(screen), mask );

    done(&cursor, Cursor);
}
示例#9
0
enum piglit_result
piglit_glx_iterate_pixmap_fbconfigs(enum piglit_result (*draw)(Display *dpy,
						      GLXFBConfig config))
{
	int screen;
	GLXFBConfig *configs;
	int n_configs;
	int i;
	bool any_fail = false;
	bool any_pass = false;
	Window root_win;

	Display *dpy = XOpenDisplay(NULL);
	if (!dpy) {
		fprintf(stderr, "couldn't open display\n");
		piglit_report_result(PIGLIT_FAIL);
	}
	screen = DefaultScreen(dpy);
	root_win = RootWindow(dpy, screen);

	configs = glXGetFBConfigs(dpy, screen, &n_configs);
	if (!configs) {
		fprintf(stderr, "No GLX FB configs\n");
		piglit_report_result(PIGLIT_SKIP);
	}

	for (i = 0; i < n_configs; i++) {
		GLXFBConfig config = configs[i];
		enum piglit_result result;
		GLXContext ctx;
		Pixmap pix;
		GLXPixmap glx_pix;
		int draw_types;
		int depth;

		glXGetFBConfigAttrib(dpy, config, GLX_DRAWABLE_TYPE,
				     &draw_types);

		if (!(draw_types & GLX_PIXMAP_BIT))
			continue;

		glXGetFBConfigAttrib(dpy, config, GLX_BUFFER_SIZE,
				     &depth);
		ctx = glXCreateNewContext(dpy, config, GLX_RGBA_TYPE,
					  NULL, true);
		pix = XCreatePixmap(dpy, root_win,
				    piglit_width, piglit_height, depth);
		glx_pix = glXCreatePixmap(dpy, config, pix, NULL);
		glXMakeCurrent(dpy, glx_pix, ctx);

		result = draw(dpy, config);

		if (result == PIGLIT_FAIL)
			any_fail = true;
		else if (result == PIGLIT_PASS)
			any_pass = true;

		XFreePixmap(dpy, pix);
		glXDestroyContext(dpy, ctx);
	}

	if (any_fail)
		return PIGLIT_FAIL;
	else if (any_pass)
		return PIGLIT_PASS;
	else
		return PIGLIT_SKIP;
}
示例#10
0
文件: fvwm-root.c 项目: fvwmorg/fvwm
int SetRootWindow(char *tline)
{
	Pixmap shapeMask = None, temp_pix = None, alpha = None;
	int w, h;
	int depth;
	int nalloc_pixels = 0;
	Pixel *alloc_pixels = NULL;
	char *file_path;
	FvwmPictureAttributes fpa;

	if (use_our_color_limit)
	{
		PictureColorLimitOption colorLimitop = {-1, -1, -1, -1, -1};
		colorLimitop.color_limit = opt_color_limit;
		PictureInitCMapRoot(
			dpy, !NoColorLimit, &colorLimitop, True, True);
	}
	else
	{
		/* this use the default visual (not the fvwm one) as
		 * getenv("FVWM_VISUALID") is NULL in any case. But this use
		 * the same color limit than fvwm.
		 * This is "broken" when fvwm use depth <= 8 and a private
		 * color map (i.e., fvwm is started with the -visual{ID}
		 * option), because when fvwm use a private color map the
		 * default color limit is 244. There is no way to know here if
		 * getenv("FVWM_VISUALID") !=NULL.
		 * So, in this unfortunate case the user should use the
		 * --color-limit option */
		PictureInitCMap(dpy);
	}
	flib_init_graphics(dpy);
	/* try built-in image path first, but not before pwd */
	PictureSetImagePath(".:+");
	file_path = PictureFindImageFile(tline, NULL, R_OK);

	if (file_path == NULL)
	{
		file_path = tline;
	}
	fpa.mask = FPAM_NO_ALLOC_PIXELS | FPAM_NO_ALPHA;
	if (Pdepth <= 8 && !NoDither)
	{
		fpa.mask |= FPAM_DITHER;
	}
	else if (Pdepth <= 16 && Dither)
	{
		fpa.mask |= FPAM_DITHER;
	}
	if (NoColorLimit)
	{
		fpa.mask |= FPAM_NO_COLOR_LIMIT;
	}
	if (!PImageLoadPixmapFromFile(
		dpy, root, file_path, &temp_pix, &shapeMask, &alpha,
		&w, &h, &depth, &nalloc_pixels, &alloc_pixels, 0, fpa))
	{
		fprintf(
			stderr, "[fvwm-root] failed to load image file '%s'\n",
			tline);
		return -1;
	}
	if (depth == Pdepth)
	{
		rootImage = temp_pix;
	}
	else
	{
		XGCValues gcv;
		GC gc;

		gcv.background= WhitePixel(dpy, screen);
		gcv.foreground= BlackPixel(dpy, screen);
		gc = fvwmlib_XCreateGC(
			dpy, root, GCForeground | GCBackground, &gcv);
		rootImage = XCreatePixmap(dpy, root, w, h, Pdepth);
		XCopyPlane(dpy, temp_pix, rootImage, gc, 0, 0, w, h, 0, 0, 1);
		XFreePixmap(dpy, temp_pix);
		XFreeGC(dpy, gc);
	}
	XSetWindowBackgroundPixmap(dpy, root, rootImage);
	save_colors = 1;
	XClearWindow(dpy, root);

	return 0;
}
示例#11
0
ENTRYPOINT void
init_flow (ModeInfo * mi)
{
	flowstruct *sp;
	char       *name;
	
	if (flows == NULL) {
		if ((flows = (flowstruct *) calloc(MI_NUM_SCREENS(mi),
										   sizeof (flowstruct))) == NULL)
			return;
	}
	sp = &flows[MI_SCREEN(mi)];

	sp->count2 = 0;

	sp->taillen = MI_SIZE(mi);
	if (sp->taillen < -MINTRAIL) {
		/* Change by sqrt so it seems more variable */
		sp->taillen = NRAND((int)sqrt((double) (-sp->taillen - MINTRAIL + 1)));
		sp->taillen = sp->taillen * sp->taillen + MINTRAIL;
	} else if (sp->taillen < MINTRAIL) {
		sp->taillen = MINTRAIL;
	}

	if(!rotatep && !ridep) rotatep = True; /* We need at least one viewpoint */

	/* Start camera at Orbit or Bee */
	if(rotatep) {
		sp->chaseto = ORBIT;
	} else {
		sp->chaseto = BEE;
	}
	sp->chasetime = 1; /* Go directly to target */

	sp->lyap = 0;
	sp->yperiod = 0;
	sp->step2 = INITIALSTEP;

	/* Zero parameter set */
	memset(sp->par2, 0, N_PARS * sizeof(dvector));

	/* Set up standard examples */
	switch (NRAND((periodicp) ? 5 : 3)) {
	case 0:
		/*
		  x' = a(y - x)
		  y' = x(b - z) - y
		  z' = xy - cz
		 */
		name = "Lorentz";
		sp->par2[Y].x = 10 + balance_rand(5*0); /* a */
		sp->par2[X].x = - sp->par2[Y].x;        /* -a */
		sp->par2[X].y = 28 + balance_rand(5*0); /* b */
		sp->par2[XZ].y = -1;
		sp->par2[Y].y = -1;
		sp->par2[XY].z = 1;
		sp->par2[Z].z = - 2 + balance_rand(1*0); /* -c */		
		break;
	case 1:
		/*
		  x' = -(y + az)
		  y' = x + by
		  z' = c + z(x - 5.7)
		 */
		name = "Rossler";
		sp->par2[Y].x = -1;
		sp->par2[Z].x = -2 + balance_rand(1); /* a */
		sp->par2[X].y = 1;
		sp->par2[Y].y = 0.2 + balance_rand(0.1); /* b */
		sp->par2[C].z = 0.2 + balance_rand(0.1); /* c */
		sp->par2[XZ].z = 1;
		sp->par2[Z].z = -5.7;
		break;
	case 2: 
		/*
		  x' = -(y + az)
		  y' = x + by - cz^2
		  z' = 0.2 + z(x - 5.7)
		 */
		name = "RosslerCone";
		sp->par2[Y].x = -1;
		sp->par2[Z].x = -2; /* a */
		sp->par2[X].y = 1;
		sp->par2[Y].y = 0.2; /* b */
		sp->par2[ZZ].y = -0.331 + balance_rand(0.01); /* c */
		sp->par2[C].z = 0.2;
		sp->par2[XZ].z = 1;
		sp->par2[Z].z = -5.7;
		break;
	case 3:
		/*
		  x' = -z + b sin(y)
		  y' = c
		  z' = 0.7x + az(0.1 - x^2) 
		 */
		name = "Birkhoff";
		sp->par2[Z].x = -1;
		sp->par2[SINY].x = 0.35 + balance_rand(0.25); /* b */
		sp->par2[C].y = 1.57; /* c */
		sp->par2[X].z = 0.7;
		sp->par2[Z].z = 1 + balance_rand(0.5); /* a/10 */
		sp->par2[XXZ].z = -10 * sp->par2[Z].z; /* -a */
		sp->yperiod = 2 * M_PI;
		break;
	default:
		/*
		  x' = -ax - z/2 - z^3/8 + b sin(y)
		  y' = c
		  z' = 2x
		 */
		name = "Duffing";
		sp->par2[X].x = -0.2 + balance_rand(0.1); /* a */
		sp->par2[Z].x = -0.5;
		sp->par2[ZZZ].x = -0.125;
		sp->par2[SINY].x = 27.0 + balance_rand(3.0); /* b */
		sp->par2[C].y = 1.33; /* c */
		sp->par2[X].z = 2;
		sp->yperiod = 2 * M_PI;
		break;

	}

	sp->range.x = 5;
	sp->range.z = 5;

	if(sp->yperiod > 0) {
		sp->ODE = Periodic;
		/* periodic flows show either uniform distribution or a
           snapshot on the 'time' axis */
		sp->range.y = NRAND(2)? sp->yperiod : 0;
	} else {
		sp->range.y = 5;
		sp->ODE = Cubic;
	}

	/* Run discoverer to set up bounding box, etc.  Lyapunov will
	   probably be innaccurate, since we're only running it once, but
	   we're using known strange attractors so it should be ok. */
	discover(mi);
	if(MI_IS_VERBOSE(mi))
		fprintf(stdout,
				"flow: Lyapunov exponent: %g, step: %g, size: %g (%s)\n",
				sp->lyap2, sp->step2, sp->size2, name);
	/* Install new params */
	sp->lyap = sp->lyap2;
	sp->size = sp->size2;
	sp->mid = sp->mid2;
	sp->step = sp->step2;
	memcpy(sp->par, sp->par2, sizeof(sp->par2));

	sp->count2 = 0; /* Reset search */

	free_flow(sp);
	sp->beecount = MI_COUNT(mi);
	if (sp->beecount < 0) {	/* random variations */
		sp->beecount = NRAND(-sp->beecount) + 1; /* Minimum 1 */
	}

# ifdef HAVE_COCOA	/* Don't second-guess Quartz's double-buffering */
  dbufp = False;
# endif

	if(dbufp) { /* Set up double buffer */
		if (sp->buffer != None)
			XFreePixmap(MI_DISPLAY(mi), sp->buffer);
		sp->buffer = XCreatePixmap(MI_DISPLAY(mi), MI_WINDOW(mi),
								 MI_WIDTH(mi), MI_HEIGHT(mi), MI_DEPTH(mi));
	} else {
		sp->buffer = MI_WINDOW(mi);
	}
	/* no "NoExpose" events from XCopyArea wanted */
	XSetGraphicsExposures(MI_DISPLAY(mi), MI_GC(mi), False);

	/* Make sure we're using 'thin' lines */
	XSetLineAttributes(MI_DISPLAY(mi), MI_GC(mi), 0, LineSolid, CapNotLast,
					   JoinMiter);

	/* Clear the background (may be slow depending on user prefs). */
	MI_CLEARWINDOW(mi);

	/* Allocate memory. */
	if (sp->csegs == NULL) {
		allocate(sp->csegs, XSegment,
				 (sp->beecount + BOX_L) * MI_NPIXELS(mi) * sp->taillen);
		allocate(sp->cnsegs, int, MI_NPIXELS(mi));
		allocate(sp->old_segs, XSegment, sp->beecount * sp->taillen);
		allocate(sp->p, dvector, sp->beecount * sp->taillen);
	}
示例#12
0
PlatformFont::CharInfo &x86UNIXFont::getCharInfo(const UTF16 ch) const
{
  Display *display = XOpenDisplay(getenv("DISPLAY"));
  if (!display )
    AssertFatal(false, "createFont: cannot connect to X server");

  static PlatformFont::CharInfo c;
  dMemset(&c, 0, sizeof(c));
  c.bitmapIndex = 0;
  c.xOffset     = 0;
  c.yOffset     = 0;

  XftFont *fontInfo  = XftFontOpenName(display, DefaultScreen(display), mFontName);
  if (!fontInfo)
    AssertFatal(false, "createFont: cannot load font");

  int screen = DefaultScreen(display);
  // Create the pixmap to draw on.
  Drawable pixmap = XCreatePixmap(display,
				  DefaultRootWindow(display),
				  fontInfo->max_advance_width,
				  fontInfo->height,
				  DefaultDepth(display, screen));
  // And the Xft wrapper around it.
  XftDraw *draw = XftDrawCreate(display,
                                pixmap,
                                DefaultVisual(display, screen),
                                DefaultColormap(display, screen));
  // Allocate some colors, we don't use XftColorAllocValue here as that
  // Don't appear to function correctly (or I'm using it wrong) As we only do
  // this twice per new un cached font it isn't that big of a penalty. (Each
  // call to XftColorAllocName involves a round trip to the X Server)
  XftColor black, white;
  XftColorAllocName(display,
                    DefaultVisual(display, screen),
                    DefaultColormap(display, screen),
                    "black",
                    &black);
  // White
  XftColorAllocName(display,
                    DefaultVisual(display, screen),
                    DefaultColormap(display, screen),
                    "white",
                    &white);
  
  XGlyphInfo charinfo;
  XftTextExtents16(display, fontInfo, &ch, 1, &charinfo);
  c.height     = fontInfo->height;
  c.xOrigin    = 0; 
  c.yOrigin    = fontInfo->ascent;
  c.xIncrement = charinfo.xOff;
  c.width      = charinfo.xOff;
  // kick out early if the character is undrawable
  if( c.width == 0 || c.height == 0)
    return c;

  // allocate a greyscale bitmap and clear it.
  int bitmapDataSize = c.width * c.height;
  c.bitmapData = new U8[bitmapDataSize];
  dMemset(c.bitmapData, 0, bitmapDataSize);

  XftDrawRect (draw, &black, 0, 0, fontInfo->max_advance_width, fontInfo->height);
  XftDrawString16 (draw, &white, fontInfo, 0, fontInfo->ascent, &ch, 1);
  // grab the pixmap image

  XImage *ximage = XGetImage(display, pixmap, 0, 0, 
			     charinfo.xOff, fontInfo->height, 
			     AllPlanes, XYPixmap);
  if (!ximage)
    AssertFatal(false, "cannot get x image");
  int x, y;

  // grab each pixel and store it in the scratchPad
  for(y = 0; y < fontInfo->height; y++)
  {
    for(x = 0; x < charinfo.xOff; x++)
      c.bitmapData[y * charinfo.xOff + x] = static_cast<U8>(XGetPixel(ximage, x, y));
  }
  XDestroyImage(ximage);

  XftColorFree(display, DefaultVisual(display, screen),
               DefaultColormap(display, screen), &black);
  XftColorFree(display, DefaultVisual(display, screen),
               DefaultColormap(display, screen), &white);
  XftDrawDestroy(draw);
  XFreePixmap(display, pixmap);
  XCloseDisplay(display);

  return c;
}
示例#13
0
文件: csi-replay.c 项目: ghub/NVprSDK
static void
_destroy_pixmap (void *closure)
{
    XFreePixmap (_get_display(), (Pixmap) closure);
}
示例#14
0
文件: scalefilter.c 项目: Elive/ecomp
static void
scalefilterRenderFilterText (CompScreen *s)
{
    CompDisplay    *d = s->display;
    CompTextAttrib tA;
    int            stride;
    void*          data;
    int            x1, x2, y1, y2;
    int            width, height;
    REGION         reg;
    char           buffer[2 * MAX_FILTER_STRING_LEN];

    FILTER_SCREEN (s);

    if (!fs->filterInfo)
	return;

    x1 = s->outputDev[fs->filterInfo->outputDevice].region.extents.x1;
    x2 = s->outputDev[fs->filterInfo->outputDevice].region.extents.x2;
    y1 = s->outputDev[fs->filterInfo->outputDevice].region.extents.y1;
    y2 = s->outputDev[fs->filterInfo->outputDevice].region.extents.y2;

    reg.rects    = &reg.extents;
    reg.numRects = 1;

    /* damage the old draw rectangle */
    width  = fs->filterInfo->textWidth + (2 * scalefilterGetBorderSize (s));
    height = fs->filterInfo->textHeight + (2 * scalefilterGetBorderSize (s));

    reg.extents.x1 = x1 + ((x2 - x1) / 2) - (width / 2) - 1;
    reg.extents.x2 = reg.extents.x1 + width + 1;
    reg.extents.y1 = y1 + ((y2 - y1) / 2) - (height / 2) - 1;
    reg.extents.y2 = reg.extents.y1 + height + 1;

    damageScreenRegion (s, &reg);

    scalefilterFreeFilterText (s);

    if (!scalefilterGetFilterDisplay (s))
	return;

    if (fs->filterInfo->filterStringLength == 0)
	return;

    tA.maxwidth = x2 - x1 - (2 * scalefilterGetBorderSize (s));
    tA.maxheight = y2 - y1 - (2 * scalefilterGetBorderSize (s));
    tA.screen = s;
    tA.size = scalefilterGetFontSize (s);
    tA.color[0] = scalefilterGetFontColorRed (s);
    tA.color[1] = scalefilterGetFontColorGreen (s);
    tA.color[2] = scalefilterGetFontColorBlue (s);
    tA.color[3] = scalefilterGetFontColorAlpha (s);
    tA.style = (scalefilterGetFontBold (s)) ?
	       TEXT_STYLE_BOLD : TEXT_STYLE_NORMAL;
    tA.family = "Sans";
    tA.ellipsize = TRUE;

    wcstombs (buffer, fs->filterInfo->filterString, MAX_FILTER_STRING_LEN);
    tA.renderMode = TextRenderNormal;
    tA.data = (void*)buffer;

    if ((*d->fileToImage) (s->display, TEXT_ID, (char *)&tA,
			   &fs->filterInfo->textWidth,
			   &fs->filterInfo->textHeight,
			   &stride, &data))
    {
	fs->filterInfo->textPixmap = (Pixmap)data;
	if (!bindPixmapToTexture (s, &fs->filterInfo->textTexture,
				  fs->filterInfo->textPixmap,
				  fs->filterInfo->textWidth,
				  fs->filterInfo->textHeight, 32))
	{
	    compLogMessage (d, "scalefilterinfo", CompLogLevelError,
			    "Bind Pixmap to Texture failure");
	    XFreePixmap (d->display, fs->filterInfo->textPixmap);
	    fs->filterInfo->textPixmap = None;
	    return;
	}
    }
    else
    {
	fs->filterInfo->textPixmap = None;
	fs->filterInfo->textWidth = 0;
	fs->filterInfo->textHeight = 0;
    }

    /* damage the new draw rectangle */
    width  = fs->filterInfo->textWidth + (2 * scalefilterGetBorderSize (s));
    height = fs->filterInfo->textHeight + (2 * scalefilterGetBorderSize (s));

    reg.extents.x1 = x1 + ((x2 - x1) / 2) - (width / 2) - 1;
    reg.extents.x2 = reg.extents.x1 + width + 1;
    reg.extents.y1 = y1 + ((y2 - y1) / 2) - (height / 2) - 1;
    reg.extents.y2 = reg.extents.y1 + height + 1;

    damageScreenRegion (s, &reg);
}
示例#15
0
/* create a pixmap suitable for plonking on the background of a part of a
 * window */
Pixmap CreateOffsetBackgroundPixmap(
	Display *dpy, Window win, int x, int y, int width, int height,
	colorset_t *colorset, unsigned int depth, GC gc, Bool is_shape_mask)
{
	Pixmap pixmap = None;
	Pixmap cs_pixmap = None;
	XGCValues xgcv;
	static GC shape_gc = None;
	GC fill_gc = None; /* not static as dpy may change (FvwmBacker) */
	int cs_width;
	int cs_height;
	Bool cs_keep_aspect;
	Bool cs_stretch_x;
	Bool cs_stretch_y;

	if (colorset->pixmap == ParentRelative && !is_shape_mask &&
	    colorset->tint_percent > 0)
	{
		FvwmRenderAttributes fra;

		fra.mask = FRAM_DEST_IS_A_WINDOW | FRAM_HAVE_TINT;
		fra.tint = colorset->tint;
		fra.tint_percent = colorset->tint_percent;
		MyXGrabServer(dpy);
		pixmap = PGraphicsCreateTransparency(
			dpy, win, &fra, gc, x, y, width, height, True);
		MyXUngrabServer(dpy);
		if (pixmap == None)
		{
			return ParentRelative;
		}
		return pixmap;
	}
	else if (colorset->pixmap == ParentRelative && !is_shape_mask)
	{
		return ParentRelative;
	}
	else if (CSETS_IS_TRANSPARENT_ROOT(colorset) && colorset->pixmap
		 && !is_shape_mask)
	{
		int sx,sy;
		int h,w;
		XID dummy;

		cs_pixmap = colorset->pixmap;
		cs_width = colorset->width;
		cs_height = colorset->height;
		if (CSETS_IS_TRANSPARENT_ROOT_PURE(colorset))
		{
			/* check if it is still here */
			union {
				XID junk;
				unsigned int ui_junk;
				int i_junk;
			} XID_int;
			/* a priori we should grab the server, but this
			 * cause PositiveWrite error when you move a
			 * window with a transparent title bar */
			if (!XGetGeometry(
				    dpy, colorset->pixmap, &XID_int.junk,
				    &XID_int.i_junk, &XID_int.i_junk,
				    (unsigned int *)&w, (unsigned int *)&h,
				    &XID_int.ui_junk,
				    &XID_int.ui_junk) ||
			    w != cs_width || h != cs_height)
			{
				return None;
			}
		}
		XTranslateCoordinates(
			dpy, win, DefaultRootWindow(dpy), x, y, &sx, &sy,
			&dummy);
		pixmap = XCreatePixmap(dpy, win, width, height, Pdepth);
		if (!pixmap)
		{
			return None;
		}
		/* make sx and sy positif */
		while (sx < 0)
		{
			sx = sx + cs_width;
		}
		while (sy < 0)
		{
			sy = sy + cs_height;
		}
		/* make sx and sy in (0,0,cs_width,cs_height) */
		while (sx >= cs_width)
		{
			sx = sx - cs_width;
		}
		while (sy >= cs_height)
		{
			sy = sy - cs_height;
		}
		xgcv.fill_style = FillTiled;
		xgcv.tile = cs_pixmap;
		xgcv.ts_x_origin = cs_width-sx;
		xgcv.ts_y_origin = cs_height-sy;
		fill_gc = fvwmlib_XCreateGC(
			dpy, win, GCTile | GCTileStipXOrigin |
			GCTileStipYOrigin | GCFillStyle, &xgcv);
		if (fill_gc == None)
		{
			XFreePixmap(dpy, pixmap);
			return None;
		}
		XSync(dpy, False);
		is_bad_gc = 0;
		ferror_set_temp_error_handler(BadGCErrorHandler);
		XFillRectangle(dpy, pixmap, fill_gc, 0, 0, width, height);
		if (
			is_bad_gc == 0 &&
			CSETS_IS_TRANSPARENT_ROOT_PURE(colorset) &&
			colorset->tint_percent > 0)
		{
			FvwmRenderAttributes fra;

			fra.mask = FRAM_HAVE_TINT;
			fra.tint = colorset->tint;
			fra.tint_percent = colorset->tint_percent;
			PGraphicsRenderPixmaps(
				dpy, win, pixmap, None, None,
				Pdepth, &fra, pixmap,
				fill_gc, None, None,
				0, 0, width, height,
				0, 0, width, height, False);
		}
		XSync(dpy, False);
		ferror_reset_temp_error_handler();
		if (is_bad_gc == 1)
		{
			is_bad_gc = 0;
			XFreePixmap(dpy, pixmap);
			pixmap = None;
		}
		XFreeGC(dpy,fill_gc);
		return pixmap;
	}
	if (!is_shape_mask)
	{
		cs_pixmap = colorset->pixmap;
		cs_width = colorset->width;
		cs_height = colorset->height;
		cs_keep_aspect =
			(colorset->pixmap_type == PIXMAP_STRETCH_ASPECT);
		cs_stretch_x = (colorset->pixmap_type == PIXMAP_STRETCH_X)
			|| (colorset->pixmap_type == PIXMAP_STRETCH);
		cs_stretch_y = (colorset->pixmap_type == PIXMAP_STRETCH_Y)
			|| (colorset->pixmap_type == PIXMAP_STRETCH);
	}
	else
	{
		/* In spite of the name, win contains the pixmap */
		cs_pixmap = colorset->shape_mask;
		win = colorset->shape_mask;
		if (shape_gc == None)
		{
			xgcv.foreground = 1;
			xgcv.background = 0;
			/* create a gc for 1 bit depth */
			shape_gc = fvwmlib_XCreateGC(
				dpy, win, GCForeground|GCBackground, &xgcv);
		}
		gc = shape_gc;
		cs_width = colorset->shape_width;
		cs_height = colorset->shape_height;
		cs_keep_aspect = (colorset->shape_type == SHAPE_STRETCH_ASPECT);
		cs_stretch_x = !(colorset->shape_type == SHAPE_TILED);
		cs_stretch_y = !(colorset->shape_type == SHAPE_TILED);
	}

	if (cs_pixmap == None)
	{
		xgcv.foreground = colorset->bg;
		fill_gc = fvwmlib_XCreateGC(dpy, win, GCForeground, &xgcv);
		/* create a solid pixmap - not very useful most of the time */
		pixmap = XCreatePixmap(dpy, win, 1, 1, depth);
		XFillRectangle(dpy, pixmap, fill_gc, 0, 0, 1, 1);
		XFreeGC(dpy,fill_gc);
	}
	else if (cs_keep_aspect)
	{
		Bool trim_side;
		int big_width, big_height;
		Pixmap big_pixmap;
		int x, y;

		/* make a pixmap big enough to cover the destination but with
		 * the aspect ratio of the cs_pixmap */
		trim_side = get_aspect_dimensions(
			&big_width, &big_height, width, height, cs_width,
			cs_height);
		big_pixmap = CreateStretchPixmap(
			dpy, cs_pixmap, cs_width, cs_height, depth, big_width,
			big_height, gc);

		/* work out where to trim */
		x = trim_side ? (big_width - width) / 2 : 0;
		y = trim_side ? 0 : (big_height - height) / 2;

		pixmap = XCreatePixmap(dpy, cs_pixmap, width, height, depth);
		if (pixmap && big_pixmap)
		{
			XCopyArea(
				dpy, big_pixmap, pixmap, gc, x, y, width,
				height, 0, 0);
		}
		if (big_pixmap)
		{
			XFreePixmap(dpy, big_pixmap);
		}
	}
	else if (!cs_stretch_x && !cs_stretch_y)
	{
		/* it's a tiled pixmap, create an unstretched one */
		if (!is_shape_mask)
		{
			pixmap = XCreatePixmap(
				dpy, cs_pixmap, cs_width, cs_height, depth);
			if (pixmap)
			{
				XCopyArea(
					dpy, cs_pixmap, pixmap, gc, 0, 0,
					cs_width, cs_height, 0, 0);
			}
		}
		else
		{
			/* can't tile masks, create a tiled version of the
			 * mask */
			pixmap = CreateTiledPixmap(
				dpy, cs_pixmap, cs_width, cs_height, width,
				height, 1, gc);
		}
	}
	else if (!cs_stretch_x)
	{
		/* it's an HGradient */
		pixmap = CreateStretchYPixmap(
			dpy, cs_pixmap, cs_width, cs_height, depth, height, gc);
	}
	else if (!cs_stretch_y)
	{
		/* it's a VGradient */
		pixmap = CreateStretchXPixmap(
			dpy, cs_pixmap, cs_width, cs_height, depth, width, gc);
	}
	else
	{
		/* It's a full window pixmap */
		pixmap = CreateStretchPixmap(
			dpy, cs_pixmap, cs_width, cs_height, depth, width,
			height, gc);
	}

	if (x != 0 || y != 0)
	{
		Pixmap p2;

		p2 = ScrollPixmap(
			dpy, pixmap, gc, x, y, width, height,
			depth);
		if (p2 != None && p2 != ParentRelative && p2 != pixmap)
		{
			XFreePixmap(dpy, pixmap);
			pixmap = p2;
		}
	}

	return pixmap;
}
示例#16
0
文件: os_x11.cpp 项目: ScyDev/godot
void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {

	last_button_state=0;
	dpad_last[0]=0;
	dpad_last[1]=0;

	xmbstring=NULL;
	event_id=0;
	x11_window=0;
	last_click_ms=0;
	args=OS::get_singleton()->get_cmdline_args();
	current_videomode=p_desired;
	main_loop=NULL;
	last_timestamp=0;
	last_mouse_pos_valid=false;
	last_keyrelease_time=0;

	if (get_render_thread_mode()==RENDER_SEPARATE_THREAD) {
		XInitThreads();
	}
	
	/** XLIB INITIALIZATION **/
	x11_display = XOpenDisplay(NULL);
	
	char * modifiers = XSetLocaleModifiers ("@im=none");
	ERR_FAIL_COND( modifiers == NULL );
	
	xim = XOpenIM (x11_display, NULL, NULL, NULL);
	

	if (xim == NULL) {
		WARN_PRINT("XOpenIM failed");
		xim_style=NULL;
	} else {
		::XIMStyles *xim_styles=NULL;
		xim_style=0;
		char *imvalret=NULL;
		imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
		if (imvalret != NULL || xim_styles == NULL) {
			fprintf (stderr, "Input method doesn't support any styles\n");
		}
		
		if (xim_styles) {
			xim_style = 0;
			for (int i=0;i<xim_styles->count_styles;i++) {
				
				if (xim_styles->supported_styles[i] ==
				    (XIMPreeditNothing | XIMStatusNothing)) {
					    
					    xim_style = xim_styles->supported_styles[i];
					    break;
				    }
			}
			
			XFree (xim_styles);
		}
	}

	/*
	char* windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

		//freopen("/home/punto/stdout", "w", stdout);
		//reopen("/home/punto/stderr", "w", stderr);
		x11_window = atol(windowid);

		XWindowAttributes xwa;
		XGetWindowAttributes(x11_display,x11_window,&xwa);

		current_videomode.width = xwa.width;
		current_videomode.height = xwa.height;
	};
	*/

	// maybe contextgl wants to be in charge of creating the window
	//print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height));
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
	context_gl = memnew( ContextGL_X11( x11_display, x11_window,current_videomode, false ) );
	context_gl->initialize();

	if (true) {
		rasterizer = memnew( RasterizerGLES2 );
	} else {
		//rasterizer = memnew( RasterizerGLES1 );
	};

#endif
	visual_server = memnew( VisualServerRaster(rasterizer) );

	if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {

		visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD));
	}

	// borderless fullscreen window mode
	if (current_videomode.fullscreen) {
		// needed for lxde/openbox, possibly others
		Hints hints;
		Atom property;
		hints.flags = 2;
		hints.decorations = 0;
		property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
		XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
		XMapRaised(x11_display, x11_window);
		XWindowAttributes xwa;
		XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa);
		XMoveResizeWindow(x11_display, x11_window, 0, 0, xwa.width, xwa.height);

		// code for netwm-compliants
		XEvent xev;
		Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
		Atom fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);

		memset(&xev, 0, sizeof(xev));
		xev.type = ClientMessage;
		xev.xclient.window = x11_window;
		xev.xclient.message_type = wm_state;
		xev.xclient.format = 32;
		xev.xclient.data.l[0] = 1;
		xev.xclient.data.l[1] = fullscreen;
		xev.xclient.data.l[2] = 0;

		XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureNotifyMask, &xev);
	}

	// disable resizeable window
	if (!current_videomode.resizable) {
		XSizeHints *xsh;
		xsh = XAllocSizeHints();
		xsh->flags = PMinSize | PMaxSize;
		XWindowAttributes xwa;
		if (current_videomode.fullscreen) {
			XGetWindowAttributes(x11_display,DefaultRootWindow(x11_display),&xwa);
		} else {
			XGetWindowAttributes(x11_display,x11_window,&xwa);
		}
		xsh->min_width = xwa.width; 
		xsh->max_width = xwa.width;
		xsh->min_height = xwa.height;
		xsh->max_height = xwa.height;
		XSetWMNormalHints(x11_display, x11_window, xsh);
	}

	AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton();

	if (AudioDriverManagerSW::get_driver(p_audio_driver)->init()!=OK) {

		ERR_PRINT("Initializing audio failed.");
	}

	sample_manager = memnew( SampleManagerMallocSW );
	audio_server = memnew( AudioServerSW(sample_manager) );
	audio_server->init();
	spatial_sound_server = memnew( SpatialSoundServerSW );
	spatial_sound_server->init();
	spatial_sound_2d_server = memnew( SpatialSound2DServerSW );
	spatial_sound_2d_server->init();

	
	ERR_FAIL_COND(!visual_server);
	ERR_FAIL_COND(x11_window==0);

	XSetWindowAttributes new_attr;

	new_attr.event_mask=KeyPressMask | KeyReleaseMask | ButtonPressMask |
			   ButtonReleaseMask | EnterWindowMask |
			   LeaveWindowMask | PointerMotionMask |
			   Button1MotionMask |
			   Button2MotionMask | Button3MotionMask |
			   Button4MotionMask | Button5MotionMask |
			   ButtonMotionMask | KeymapStateMask |
			   ExposureMask | VisibilityChangeMask |
			   StructureNotifyMask |
			   SubstructureNotifyMask | SubstructureRedirectMask |
			   FocusChangeMask | PropertyChangeMask |
			   ColormapChangeMask | OwnerGrabButtonMask;

	XChangeWindowAttributes(x11_display, x11_window,CWEventMask,&new_attr);
	
    XClassHint* classHint;

    /* set the titlebar name */
    XStoreName(x11_display, x11_window, "Godot");

    /* set the name and class hints for the window manager to use */
    classHint = XAllocClassHint();
    if (classHint) {
        classHint->res_name = "Godot";
        classHint->res_class = "Godot";
    }
    XSetClassHint(x11_display, x11_window, classHint);
    XFree(classHint);

	wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);	
	XSetWMProtocols(x11_display, x11_window, &wm_delete, 1);
		

	if (xim && xim_style) {
		
		xic = XCreateIC (xim,XNInputStyle, xim_style,XNClientWindow,x11_window,XNFocusWindow, x11_window, (char*)NULL);
	} else {
		
		xic=NULL;
		WARN_PRINT("XCreateIC couldn't create xic");

	}	

	XcursorSetTheme(x11_display,"default");
	cursor_size = XcursorGetDefaultSize(x11_display);
	cursor_theme = XcursorGetTheme(x11_display);

	if (!cursor_theme) {
		print_line("not found theme");
		cursor_theme="default";
	}

	for(int i=0;i<CURSOR_MAX;i++) {

		cursors[i]=None;
	}

	current_cursor=CURSOR_ARROW;

	if (cursor_theme) {
		//print_line("cursor theme: "+String(cursor_theme));
		for(int i=0;i<CURSOR_MAX;i++) {

			static const char *cursor_file[]={
				"left_ptr",
				"xterm",
				"hand2",
				"cross",
				"watch",
				"left_ptr_watch",
				"fleur",
				"hand1",
				"X_cursor",
				"sb_v_double_arrow",
				"sb_h_double_arrow",
				"size_bdiag",
				"size_fdiag",
				"hand1",
				"sb_v_double_arrow",
				"sb_h_double_arrow",
				"question_arrow"
			};

			XcursorImage *img = XcursorLibraryLoadImage(cursor_file[i],cursor_theme,cursor_size);
			if (img) {
				cursors[i]=XcursorImageLoadCursor(x11_display,img);
				//print_line("found cursor: "+String(cursor_file[i])+" id "+itos(cursors[i]));
			} else {
				if (OS::is_stdout_verbose())
					print_line("failed cursor: "+String(cursor_file[i]));
			}
		}

	}


	{
		Pixmap cursormask;
		 XGCValues xgc;
		 GC gc;
		 XColor col;
		 Cursor cursor;

		 cursormask = XCreatePixmap(x11_display, RootWindow(x11_display,DefaultScreen(x11_display)), 1, 1, 1);
		 xgc.function = GXclear;
		 gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
		XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
		col.pixel = 0;
		col.red = 0;
		col.flags = 4;
		cursor = XCreatePixmapCursor(x11_display,
			      cursormask, cursormask,
			      &col, &col, 0, 0);
		 XFreePixmap(x11_display, cursormask);
		 XFreeGC(x11_display, gc);



		 if (cursor == None)
		 {
			 ERR_PRINT("FAILED CREATING CURSOR");
		 }

		 null_cursor=cursor;
	}
	set_cursor_shape(CURSOR_BUSY);


	visual_server->init();
	//
	physics_server = memnew( PhysicsServerSW );
	physics_server->init();
	physics_2d_server = memnew( Physics2DServerSW );
	physics_2d_server->init();

	input = memnew( InputDefault );

	probe_joystick();

	_ensure_data_dir();

	net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);


	//printf("got map notify\n");
		
}
示例#17
0
/* Draws a colorset background into the specified rectangle in the target
 * drawable. */
void SetClippedRectangleBackground(
	Display *dpy, Window win, int x, int y, int width, int height,
	XRectangle *clip, colorset_t *colorset,
	unsigned int depth, GC gc)
{
	GC draw_gc;
	Pixmap pixmap2;
	Pixmap pixmap = None;
	static int last_depth = -1;
	static GC last_gc = None;
	XGCValues xgcv;
	Pixmap clipmask = None;
	GC clip_gc = None;
	Bool keep_aspect = (colorset->pixmap_type == PIXMAP_STRETCH_ASPECT);
	Bool stretch_x = (colorset->pixmap_type == PIXMAP_STRETCH_X)
		|| (colorset->pixmap_type == PIXMAP_STRETCH);
	Bool stretch_y = (colorset->pixmap_type == PIXMAP_STRETCH_Y)
		|| (colorset->pixmap_type == PIXMAP_STRETCH);
	int dest_x, dest_y, dest_w, dest_h;

	if (clip)
	{
		dest_x = clip->x;
		dest_y = clip->y;
		dest_w = clip->width;
		dest_h = clip->height;
	}
	else
	{
		dest_x = x;
		dest_y = y;
		dest_w = width;
		dest_h = height;
	}
	if (CSETS_IS_TRANSPARENT_PR_TINT(colorset))
	{
		XClearArea(dpy, win, dest_x, dest_y, dest_w, dest_h, False);
		PGraphicsTintRectangle(
			dpy, win, colorset->tint, colorset->tint_percent,
			win, True, gc, None, None,
			dest_x, dest_y, dest_w, dest_h);
		return;
	}
	if (CSETS_IS_TRANSPARENT_PR_PURE(colorset))
	{
		XClearArea(dpy, win, dest_x, dest_y, dest_w, dest_h, False);
		/* don't do anything */
		return;
	}
	if (CSETS_IS_TRANSPARENT_ROOT(colorset))
	{
		/* FIXME: optimize this ! */
		x = y = 0;
		width = width + dest_x;
		height = height + dest_y;
	}
	/* minimize gc creation by remembering the last requested depth */
	if (last_gc != None && depth != last_depth)
	{
		XFreeGC(dpy, last_gc);
		last_gc = None;
	}
	if (last_gc == None)
	{
		last_gc = fvwmlib_XCreateGC(dpy, win, 0, &xgcv);
	}
	draw_gc = last_gc;
	last_depth = depth;

	if (FHaveShapeExtension && colorset->shape_mask != None)
	{
		clipmask = CreateBackgroundPixmap(
			dpy, 0, width, height, colorset, 1, None, True);
		if (clipmask)
		{
			/* create a GC for clipping */
			xgcv.clip_x_origin = x;
			xgcv.clip_y_origin = y;
			xgcv.clip_mask = clipmask;
			clip_gc = fvwmlib_XCreateGC(
				dpy, win, GCClipXOrigin | GCClipYOrigin |
				GCClipMask, &xgcv);
			draw_gc = clip_gc;
		}
	}

	if (!colorset->pixmap)
	{
		/* use the bg pixel */
		XSetForeground(dpy, draw_gc, colorset->bg);
		XFillRectangle(
			dpy, win, draw_gc, dest_x, dest_y, dest_w, dest_h);
	}
	else
	{
		pixmap = CreateBackgroundPixmap(
			dpy, win, width, height, colorset, depth, gc, False);
		if (keep_aspect)
		{
			/* nothing to do */
		}
		if (stretch_x || stretch_y)
		{
			if (!stretch_x && colorset->width != width)
			{
				pixmap2 = CreateStretchXPixmap(
					dpy, pixmap, colorset->width, height,
					depth, width, gc);
				XFreePixmap(dpy, pixmap);
				pixmap = pixmap2;
			}
			if (!stretch_y && colorset->height != height)
			{
				pixmap2 = CreateStretchYPixmap(
					dpy, pixmap, width, colorset->height,
					depth, height, gc);
				XFreePixmap(dpy, pixmap);
				pixmap = pixmap2;
			}
		}
		else
		{
			pixmap2 = CreateTiledPixmap(
				dpy, pixmap, colorset->width, colorset->height,
				width, height, depth, gc);
			XFreePixmap(dpy, pixmap);
			pixmap = pixmap2;
		}

		if (pixmap)
		{
			/* Copy the pixmap into the rectangle. */
			XCopyArea(
				dpy, pixmap, win, draw_gc,
				dest_x - x, dest_y - y, dest_w, dest_h,
				dest_x, dest_y);
			XFreePixmap(dpy, pixmap);
		}
	}

	if (FHaveShapeExtension)
	{
		if (clipmask != None)
		{
			XFreePixmap(dpy, clipmask);
		}
		if (clip_gc != None)
		{
			XFreeGC(dpy, clip_gc);
		}
	}

	return;
}
示例#18
0
void bt::BitmapLoader::unload(::Drawable &drawable) {
  if (drawable)
    XFreePixmap(_display.XDisplay(), drawable);
  drawable = 0;
}
示例#19
0
void xf_window_free(xfContext* xfc)
{
	if (xfc->gc_mono)
	{
		XFreeGC(xfc->display, xfc->gc_mono);
		xfc->gc_mono = 0;
	}

	if (xfc->window)
	{
		xf_DestroyDesktopWindow(xfc, xfc->window);
		xfc->window = NULL;
	}

	if (xfc->hdc)
	{
		gdi_DeleteDC(xfc->hdc);
		xfc->hdc = NULL;
	}

	if (xfc->xv_context)
	{
		xf_tsmf_uninit(xfc, NULL);
		xfc->xv_context = NULL;
	}

	if (xfc->bitmap_buffer)
	{
		_aligned_free(xfc->bitmap_buffer);
		xfc->bitmap_buffer = NULL;
		xfc->bitmap_size = 0;
	}

	if (xfc->image)
	{
		xfc->image->data = NULL;
		XDestroyImage(xfc->image);
		xfc->image = NULL;
	}

	if (xfc->bitmap_mono)
	{
		XFreePixmap(xfc->display, xfc->bitmap_mono);
		xfc->bitmap_mono = 0;
	}

	if (xfc->primary)
	{
		XFreePixmap(xfc->display, xfc->primary);
		xfc->primary = 0;
	}

	if (xfc->gc)
	{
		XFreeGC(xfc->display, xfc->gc);
		xfc->gc = 0;
	}

	if (xfc->modifierMap)
	{
		XFreeModifiermap(xfc->modifierMap);
		xfc->modifierMap = NULL;
	}
}
示例#20
0
void set_up_bitmaps()
{
	/*	first-stage pixmaps -- each different colored part must be created
		from a mono bitmap, and then laid atop each other to make the
		final multi-color pixmap.
	*/
	Pixmap playerbit[PLAYERPHASES][PLAYERPARTS];
	Pixmap burnbit[BURNDIRECTIONS][BURNPARTS];
	Pixmap firebit[FIREPHASES][FIREPARTS];
	Pixmap sweeperbit[SWEEPERPHASES][SWEEPERPARTS];
	Pixmap guardbit[GUARDPARTS];
	Pixmap guardlightbit[GUARDLIGHTS];
	Pixmap guardflamebit[GUARDDIRECTIONS][GUARDFLAMEPARTS];
	Pixmap explodebit[EXPLODEFRAMES];
	Pixmap skelbit[EXPLODEFRAMES];
	Pixmap doorbit[DOORFRAMES][DOORPARTS];
	Pixmap fuelbit[FUELPARTS];
	Pixmap keybit[KEYPARTS];
	Pixmap extramanbit;

	int	i, j, k, g[GUARDLIGHTS];

	/*	Each of the following sections essentially does this:
			create and erase the main pixmap
			create all the secondary pixmaps from bitmap data
			copy the secondary pixmaps onto the main pixmap with the
				proper color
	*/

	/*	Player pixmaps
	*/
	for(i=0; i<PLAYERPHASES; i++) {
		playerpix[i] = XCreatePixmap(display, gamewindow, PLAYERWIDTH,
										PLAYERHEIGHT, depth);
		XFillRectangle(display, playerpix[i], ctable[CBLACK].smallgc,
						0, 0, PLAYERWIDTH, PLAYERHEIGHT);
		for(j=0; j<PLAYERPARTS; j++) {
			playerbit[i][j] = XCreateBitmapFromData(display, gamewindow,
													player_bits[i][j],
													PLAYERWIDTH,
													PLAYERHEIGHT);
			XCopyPlane(display, playerbit[i][j], playerpix[i],
						ctable[playercolor[j]].smallgc, 0, 0,
						PLAYERWIDTH, PLAYERHEIGHT, 0, 0, 1);
		}
	}

	/*	Pixmaps for the jetpack flame
	*/
	for(i=0; i<BURNDIRECTIONS; i++) {
		burnpix[i] = XCreatePixmap(display, gamewindow, BURNWIDTH,
									BURNHEIGHT, depth);
		XFillRectangle(display, burnpix[i], ctable[CBLACK].smallgc,
						0, 0, BURNWIDTH, BURNHEIGHT);
		for(j=0; j<BURNPARTS; j++) {
			burnbit[i][j] = XCreateBitmapFromData(display, gamewindow,
													burn_bits[i][j],
													BURNWIDTH,
													BURNHEIGHT);
			XCopyPlane(display, burnbit[i][j], burnpix[i],
						ctable[burncolor[j]].smallgc, 0, 0,
						BURNWIDTH, BURNHEIGHT, 0, 0, 1);
		}
	}

	/* Wall sweeper pixmaps (very pretty)
	*/
	for(i=0; i<SWEEPERPHASES; i++) {
		sweeperpix[i] = XCreatePixmap(display, gamewindow, SWEEPERWIDTH,
										SWEEPERHEIGHT, depth);
		XFillRectangle(display, sweeperpix[i], ctable[CBLACK].smallgc,
						0, 0, SWEEPERWIDTH, SWEEPERHEIGHT);
		for(j=0; j<SWEEPERPARTS; j++) {
			sweeperbit[i][j] = XCreateBitmapFromData(display, gamewindow,
														sweeper_bits[i][j],
														SWEEPERWIDTH, 
														SWEEPERHEIGHT);
			XCopyPlane(display, sweeperbit[i][j], sweeperpix[i],
						ctable[sweepcolor[j]].smallgc, 0, 0,
						SWEEPERWIDTH, SWEEPERHEIGHT, 0, 0, 1);
		}
	}

	/*	Fireball pixmaps
	*/
	for(i=0; i<FIREPHASES; i++) {
		firepix[i] = XCreatePixmap(display, gamewindow, FIREWIDTH,
									FIREHEIGHT, depth);
		XFillRectangle(display, firepix[i], ctable[CBLACK].smallgc,
						0, 0, FIREWIDTH, FIREHEIGHT);
		for(j=0; j<FIREPARTS; j++) {
			firebit[i][j] = XCreateBitmapFromData(display, gamewindow,
													fire_bits[i][j],
													FIREWIDTH,
													FIREHEIGHT);
			XCopyPlane(display, firebit[i][j], firepix[i],
						ctable[firecolor[j]].smallgc, 0, 0,
						FIREWIDTH, FIREHEIGHT, 0, 0, 1);
		}
	}

	/*	Guard pixmaps. These are a little odd because of the random
		blinking light sequences. There are three sets of lights on the
		guard, and each can be on or off. This makes 8 different frames,
		but to cut down on bitmap data, I only made the three light
		bitmaps rather than 8.
	*/
	for(i=0; i<GUARDPARTS; i++) {
		guardbit[i] = XCreateBitmapFromData(display, gamewindow,
											guard_bits[i], GUARDWIDTH,
											GUARDHEIGHT);
		for(j=0; j<GUARDDIRECTIONS; j++) {
			guardflamebit[j][i] = XCreateBitmapFromData(display, gamewindow,
													guard_flame_bits[j][i],
													GUARDWIDTH,
													GUARDHEIGHT);
		}
	}
	for(i=0; i<GUARDLIGHTS; i++) {
		guardlightbit[i] = XCreateBitmapFromData(display, gamewindow,
											guard_light_bits[i],
											GUARDWIDTH, GUARDHEIGHT);
	}
	for(i=0; i<GUARDDIRECTIONS; i++) {
		for(j=0; j<GUARDPHASES; j++) {
			guardpix[i][j] = XCreatePixmap(display, gamewindow, GUARDWIDTH,
											GUARDHEIGHT, depth);
			XFillRectangle(display, guardpix[i][j],
							ctable[CBLACK].smallgc, 0, 0,
							GUARDWIDTH, GUARDHEIGHT);
			for(k=0; k<GUARDPARTS; k++) {
				XCopyPlane(display, guardbit[k], guardpix[i][j],
							ctable[guardcolor[k]].smallgc,
							0, 0, GUARDWIDTH, GUARDHEIGHT, 0, 0, 1);
			}
			for(k=0; k<GUARDFLAMEPARTS; k++) {
				XCopyPlane(display, guardflamebit[i][k], guardpix[i][j],
							ctable[guardflamecolor[k]].smallgc,
							0, 0, GUARDWIDTH, GUARDHEIGHT, 0, 0, 1);
			}
			/*	This initialization will need to be expanded if I add more
				lights.
			*/
			g[2] = j / 4;
			g[1] = (j % 4) / 2;
			g[0] = (j % 4) % 2;
			for(k=0; k<GUARDLIGHTS; k++) {
				if(g[k]) XCopyPlane(display, guardlightbit[k], guardpix[i][j],
									ctable[guardlightcolor].smallgc,
									0, 0, GUARDWIDTH, GUARDHEIGHT, 0, 0, 1);
			}
		}
	}

	/*	Player explosion pixmaps
	*/
	for(i=0; i<EXPLODEFRAMES; i++) {
		explodepix[i] = XCreatePixmap(display, gamewindow, EXPLODEWIDTH,
										EXPLODEHEIGHT, depth);
		XFillRectangle(display, explodepix[i], ctable[CBLACK].smallgc,
						0, 0, EXPLODEWIDTH, EXPLODEHEIGHT);
		explodebit[i] = XCreateBitmapFromData(display, gamewindow,
												explode_bits[i],
												EXPLODEWIDTH,
												EXPLODEHEIGHT);
		skelbit[i] = XCreateBitmapFromData(display, gamewindow,
												skel_bits[i], SKELWIDTH,
												SKELHEIGHT);
		XCopyPlane(display, explodebit[i], explodepix[i],
					ctable[explodecolor].smallgc, 0, 0, EXPLODEWIDTH,
					EXPLODEHEIGHT, 0, 0, 1);
		XCopyPlane(display, skelbit[i], explodepix[i],
					ctable[skelcolor].smallgc, 0, 0, SKELWIDTH,
					SKELHEIGHT, (EXPLODEWIDTH - SKELWIDTH) / 2,
					(EXPLODEWIDTH - SKELWIDTH) / 2, 1);
	}

	/*	Fuel pod pixmap
	*/
	fuelpix = XCreatePixmap(display, gamewindow, FUELWIDTH, FUELHEIGHT,
							depth);
	XFillRectangle(display, fuelpix, ctable[CBLACK].smallgc, 0, 0,
					FUELWIDTH, FUELHEIGHT);
	for(i=0; i<FUELPARTS; i++) {
			fuelbit[i] = XCreateBitmapFromData(display, gamewindow,
												fuel_bits[i],
												FUELWIDTH, FUELHEIGHT);
			XCopyPlane(display, fuelbit[i], fuelpix,
						ctable[fuelcolor[i]].smallgc, 0, 0,
						FUELWIDTH, FUELHEIGHT, 0, 0, 1);
	}

	/*	Key pixmap
	*/
	keypix = XCreatePixmap(display, gamewindow, KEYWIDTH, KEYHEIGHT,
							depth);
	XFillRectangle(display, keypix, ctable[CBLACK].smallgc, 0, 0,
					KEYWIDTH, KEYHEIGHT);
	for(i=0; i<KEYPARTS; i++) {
			keybit[i] = XCreateBitmapFromData(display, gamewindow,
												key_bits[i], KEYWIDTH,
												KEYHEIGHT);
			XCopyPlane(display, keybit[i], keypix,
						ctable[keycolor[i]].smallgc, 0, 0,
						KEYWIDTH, KEYHEIGHT, 0, 0, 1);
	}

	/*	Door pixmaps. The only difference in frames is the color, but I
		wanted it this way in case I want to animate the door in the
		future.
	*/
	for(i=0; i<DOORFRAMES; i++) {
		doorpix[i] = XCreatePixmap(display, gamewindow, DOORWIDTH,
									DOORHEIGHT, depth);
		XFillRectangle(display, doorpix[i], ctable[CBLACK].smallgc,
						0, 0, DOORWIDTH, DOORHEIGHT);
		for(j=0; j<DOORPARTS; j++) {
			doorbit[i][j] = XCreateBitmapFromData(display, gamewindow,
													door_bits[i][j], 
													DOORWIDTH, DOORHEIGHT);
			XCopyPlane(display, doorbit[i][j], doorpix[i],
						ctable[doorcolor[i][j]].smallgc, 0, 0, 
						DOORWIDTH, DOORHEIGHT, 0, 0, 1);
		}
	}

	/*	Extra player pixmap
	*/
	extramanpix = XCreatePixmap(display, gamewindow, EXTRAMANWIDTH,
								EXTRAMANHEIGHT, depth);
	XFillRectangle(display, extramanpix, ctable[CBLACK].smallgc,
					0, 0, EXTRAMANWIDTH, EXTRAMANHEIGHT);
	extramanbit = XCreateBitmapFromData(display, gamewindow, extraman_bits,
										EXTRAMANWIDTH, EXTRAMANHEIGHT);
	XCopyPlane(display, extramanbit, extramanpix,
				ctable[extramancolor].smallgc,
				0, 0, EXTRAMANWIDTH, EXTRAMANHEIGHT, 0, 0, 1);

	/*	free all the temporary pixmaps
	*/
	for(i=0; i<PLAYERPHASES; i++) {
		for(j=0; j<PLAYERPARTS; j++) {
			XFreePixmap(display, playerbit[i][j]);
		}
	}
	for(i=0; i<BURNDIRECTIONS; i++) {
		for(j=0; j<BURNPARTS; j++) {
			XFreePixmap(display, burnbit[i][j]);
		}
	}
	for(i=0; i<FIREPHASES; i++) {
		for(j=0; j<FIREPARTS; j++) {
			XFreePixmap(display, firebit[i][j]);
		}
	}
	for(i=0; i<SWEEPERPHASES; i++) {
		for(j=0; j<SWEEPERPARTS; j++) {
			XFreePixmap(display, sweeperbit[i][j]);
		}
	}
	for(i=0; i<GUARDPARTS; i++) {
		XFreePixmap(display, guardbit[i]);
	}
	for(i=0; i<GUARDLIGHTS; i++) {
		XFreePixmap(display, guardlightbit[i]);
	}
	for(i=0; i<GUARDDIRECTIONS; i++) {
		for(j=0; j<GUARDFLAMEPARTS; j++) {
			XFreePixmap(display, guardflamebit[i][j]);
		}
	}
	for(i=0; i<EXPLODEFRAMES; i++) {
		XFreePixmap(display, explodebit[i]);
		XFreePixmap(display, skelbit[i]);
	}
	for(i=0; i<DOORFRAMES; i++) {
		for(j=0; j<DOORPARTS; j++) {
			XFreePixmap(display, doorbit[i][j]);
		}
	}
	for(i=0; i<FUELPARTS; i++) {
		XFreePixmap(display, fuelbit[i]);
	}
	for(i=0; i<KEYPARTS; i++) {
		XFreePixmap(display, keybit[i]);
	}
	XFreePixmap(display, extramanbit);
}
示例#21
0
/*
 * Creates the playing windows.
 * Returns 0 on success, -1 on error.
 */
int Init_playing_windows(void)
{
    unsigned			w, h;
    Pixmap			pix;
    GC				cursorGC;

    if (!topWindow) {
	if (Init_top())
	    return -1;
    }

    Scale_dashes();

    draw_width = top_width - (256 + 2);
    draw_height = top_height;
    drawWindow = XCreateSimpleWindow(dpy, topWindow, 258, 0,
				     draw_width, draw_height,
				     0, 0, colors[BLACK].pixel);
    radarWindow = XCreateSimpleWindow(dpy, topWindow, 0, 0,
				      256, RadarHeight, 0, 0,
				      colors[BLACK].pixel);
    radar_score_mapped = true;

    /* Create buttons */
#define BUTTON_WIDTH	84
    ButtonHeight = buttonFont->ascent + buttonFont->descent + 2*BTN_BORDER;

    button_form
	= Widget_create_form(0, topWindow,
			     0, (int)RadarHeight,
			     256, ButtonHeight + 2,
			     0);
    Widget_create_activate(button_form,
			   0 + 0*BUTTON_WIDTH, 0,
			   BUTTON_WIDTH, ButtonHeight,
			   1, "QUIT",
			   Quit_callback, NULL);
    Widget_create_activate(button_form,
			   1 + 1*BUTTON_WIDTH, 0,
			   BUTTON_WIDTH, ButtonHeight,
			   1, "ABOUT",
			   About_callback, NULL);
    menu_button
	= Widget_create_menu(button_form,
			     2 + 2*BUTTON_WIDTH, 0,
			     BUTTON_WIDTH, ButtonHeight,
			     1, "MENU");
    Widget_add_pulldown_entry(menu_button,
			      "KEYS", Keys_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "CONFIG", Config_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "COLORS", Colors_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "SCORE", Score_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "PLAYER", Player_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "MOTD", Motd_callback, NULL);
    Widget_map_sub(button_form);

    /* Create score list window */
    players_width = RadarWidth;
    players_height = top_height - (RadarHeight + ButtonHeight + 2);
    playersWindow
	= XCreateSimpleWindow(dpy, topWindow,
			      0, (int)RadarHeight + ButtonHeight + 2,
			      players_width, players_height,
			      0, 0,
			      colors[windowColor].pixel);

    /*
     * Selecting the events we can handle.
     */
    XSelectInput(dpy, radarWindow, ExposureMask);
    XSelectInput(dpy, playersWindow, ExposureMask);
    XSelectInput(dpy, drawWindow, ButtonPressMask | ButtonReleaseMask);

    /*
     * Initialize misc. pixmaps if we're not color switching.
     * (This could be in dbuff_init_buffer completely IMHO, -- Metalite)
     */
    switch (dbuf_state->type) {

    case PIXMAP_COPY:
	radarPixmap
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	radarPixmap2
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	drawPixmap
	    = XCreatePixmap(dpy, drawWindow, draw_width, draw_height,
			    dispDepth);
	break;

    case MULTIBUFFER:
	radarPixmap
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	radarPixmap2
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	dbuff_init_buffer(dbuf_state);
	break;

    case COLOR_SWITCH:
	radarPixmap2 = radarWindow;
	radarPixmap = radarWindow;
	drawPixmap = drawWindow;
	Paint_sliding_radar();
	break;

    default:
	assert(0 && "Init_playing_windows: unknown dbuf state type.");
	break;
    }

    XAutoRepeatOff(dpy);	/* We don't want any autofire, yet! */
    if (kdpy)
	XAutoRepeatOff(kdpy);

    /*
     * Define a blank cursor for use with pointer control
     */
    XQueryBestCursor(dpy, drawWindow, 1, 1, &w, &h);
    pix = XCreatePixmap(dpy, drawWindow, w, h, 1);
    cursorGC = XCreateGC(dpy, pix, 0, NULL);
    XSetForeground(dpy, cursorGC, 0);
    XFillRectangle(dpy, pix, cursorGC, 0, 0, w, h);
    XFreeGC(dpy, cursorGC);
    pointerControlCursor = XCreatePixmapCursor(dpy, pix, pix, &colors[BLACK],
					       &colors[BLACK], 0, 0);
    XFreePixmap(dpy, pix);

    /*
     * Maps the windows, makes the visible. Voila!
     */
    XMapSubwindows(dpy, topWindow);
    XMapWindow(dpy, topWindow);
    XSync(dpy, False);

    if (kdpy) {
	XMapWindow(kdpy, keyboardWindow);
	XSync(kdpy, False);
    }

    Init_spark_colors();

    return 0;
}
示例#22
0
bool               P3DGLMemoryContextPixmap::Create
                                      (unsigned int        Width,
                                       unsigned int        Height,
                                       bool                NeedAlpha)
 {
  bool                                 Result;
  XVisualInfo                         *VisualInfo;

  Result = true;

  if (Connection == NULL)
   {
    OwnConnection = true;
    Connection = XOpenDisplay(NULL);

    if (Connection == NULL)
     {
      return(false);
     }
   }
  else
   {
    OwnConnection = false;
   }

  Result = true;

  if (NeedAlpha)
   {
    VisualInfo = glXChooseVisual(Connection,
                                 DefaultScreen(Connection),
                                 VisualAttrArrayAlpha);
   }
  else
   {
    VisualInfo = glXChooseVisual(Connection,
                                 DefaultScreen(Connection),
                                 VisualAttrArray);
   }

  if (VisualInfo != NULL)
   {
    TargetPixmap = XCreatePixmap(Connection,
                                 DefaultRootWindow(Connection),
                                 Width,
                                 Height,
                                 VisualInfo->depth);

    TargetGLXPixmap = glXCreateGLXPixmap(Connection,VisualInfo,TargetPixmap);

    /*FIXME: check for errors here */

    OffScreenGLXContext = glXCreateContext(Connection,VisualInfo,NULL,False);

    if (OffScreenGLXContext != NULL)
     {
      Ok = true;

      Result = MakeCurrent();

      if (Result)
       {
        Result = P3DGLExtInit();
       }

      Ok = Result;
     }
    else
     {
      Result = false;
     }

    if (!Result)
     {
      glXDestroyGLXPixmap(Connection,TargetGLXPixmap);
      XFreePixmap(Connection,TargetPixmap);
     }

    XFree(VisualInfo);
   }
  else
   {
    Result = false;
   }

  if (!Result)
   {
    if (OwnConnection)
     {
      XCloseDisplay(Connection);
     }

    Connection = NULL;
   }

  Ok = Result;

  return(Result);
 }
示例#23
0
/*
 ****************************************************************
 *	Modifica o fundo da janela				*
 ****************************************************************
 */
int
set_background (Display *dpy, Window win, XImage *ximage, const char *name)
{
	Pixmap		pic;
	int		ret = 0;

	/*
	 *	Cria o Pixmap correspondente à imagem.
	 */
	pic =	XCreatePixmap
		(	dpy, win,
			ximage->width, ximage->height,
			DefaultDepth (dpy, screen)
		);

	if (pic == 0)
	{
		msg ("\"%s\": o servidor X não pode criar o Mapa de Pixels", name);
		return (-1);
	}

	/*
	 *	Envia para o servidor o conteúdo do Pixmap (a imagem).
	 */
	if (XPutImage (dpy, pic, gc, ximage, 0, 0, 0, 0, ximage->width, ximage->height))
	{
		msg ("\"%s\": o servidor X rejeitou a imagem", name);
		XFreePixmap (dpy, pic);
		return (-1);
	}

	/*
	 *	O Pixmap torna-se o fundo da janela.
	 */
	XSetWindowBackgroundPixmap (dpy, win, pic);

	if (Rflag)
	{
		Atom		prop, type;
		uchar		*data;
		ulong		length, after;
		int		format;

		XClearWindow (dpy, win);
		XFlush (dpy);

		prop = XInternAtom (dpy, "_XSETROOT_ID", False);

		(void)XGetWindowProperty
		(	dpy, win, prop, 0, 1, True,
			AnyPropertyType, &type, &format, &length, &after, &data
		);

#if (0)	/*******************************************************/
		/* NÃO SEI BEM PARA QUE SERVIA... */

		if
		(	type == XA_PIXMAP && format == 32 && length == 1 &&
			after == 0
		)
			XKillClient (dpy, *((Pixmap *)data));
#endif	/*******************************************************/

		XChangeProperty
		(	dpy, win, prop, XA_PIXMAP, 32, PropModeReplace,
			(uchar *)&pic, 1
		);

		XSetCloseDownMode (dpy, RetainPermanent);
		XFlush (dpy);

		ret = -1;
	}

	XFreePixmap (dpy, pic);

	return (ret);

}	/* end set_background */
示例#24
0
文件: pot.c 项目: mjames-upc/garp
void FreePixmap ( Display *display, Pixmap p )
{
	assert( p );
	XFreePixmap( display, p );

}
示例#25
0
/*
    建立 Tray 
*/
void gui_tray_init(void)
{
    winlist_t *win = NULL;

    if (gui->tray_win)
    {
	//return;
	win = gui->tray_win;
    }
    else
    {
#if 0
	//manager_window = XGetSelectionOwner(gui->display, selection_atom);
	manager_window = ManagerWindow(gui->display, gui->screen);

	if (manager_window != None)
	{
	    Atom visual_atom = XInternAtom(gui->display, "_NET_SYSTEM_TRAY_VISUAL", False);

	    Atom type;
	    int format;
	    union {
		    unsigned long *prop;
		    unsigned char *prop_ch;
	    } prop = { NULL };
	    unsigned long nitems;
	    unsigned long bytes_after;
	    int result;

	    type = None;
	    result = XGetWindowProperty (gui->display,
					manager_window,
					visual_atom,
					0, sizeof(long), False,
					XA_VISUALID,
					&type, &format, &nitems,
					&bytes_after, &(prop.prop_ch));

	    Visual *default_xvisual;
	    
	    if (result == 0 &&
		type == XA_VISUALID && nitems == 1 && format == 32)
		{
		    VisualID visual_id = prop.prop[0];
		    visual = x11_screen_lookup_visual (visual_id);
		}
	}
#endif
#if 1
/*        Atom actual_type;
        int actual_format;
        unsigned long nitems, bytes_remaining;
        unsigned char *data = 0;
        int result = XGetWindowProperty(gui->display, manager_window, visual_atom, 0, 1,
                                        False, XA_VISUALID, &actual_type,
                                        &actual_format, &nitems, &bytes_remaining, &data);
        VisualID vid = 0;
        if (result == Success && data && actual_type == XA_VISUALID && actual_format == 32 &&
                nitems == 1 && bytes_remaining == 0)
            vid = *(VisualID*)data;
        if (data)
            XFree(data);
        if (vid == 0)
            return;
*/
        uint mask = VisualScreenMask;
        XVisualInfo *vi, rvi;
        int count=0, i;
        //rvi.visualid = vid;
	rvi.screen = gui->screen;
        vi = XGetVisualInfo(gui->display, mask, &rvi, &count);
	for(i=0; i<count; i++)
	{
	      if (vi[i].depth == 32 &&
		  (vi[i].red_mask   == 0xff0000 &&
		   vi[i].green_mask == 0x00ff00 &&
		   vi[i].blue_mask  == 0x0000ff))
		{
			//printf("rgba_visual=%d\n", vi[i].visual->visualid);
			visual = &vi[i];
			break;
		}
	}
        /*if (vi) {
            //visual = vi[0];
	    visual = &vi[0];
	    //return;
            //XFree((char*)vi);
        }*/
#endif

	if(visual && visual->visual)
	    win = gui_new_win_tray((XVisualInfo*)visual);
	else
	    win = gui_new_win();
    }

    /* Tray 不需要邊框 */
    XSetWindowBorderWidth(gui->display, win->window, 0);

    XSetWindowAttributes win_attr;
    win_attr.override_redirect = True;
    XChangeWindowAttributes(gui->display, win->window,
			CWOverrideRedirect, &win_attr);

    Pixmap tray, mask;
    XpmAttributes attributes;
    attributes.valuemask = 0;

    if (!ProcessTrayIcon(gui->display, win->window, oxim_tray, &icon, &icon_mask,
				&picon)) 
    {
	//fprintf(stderr, "failed to get inactive icon image\n");
	return;
    }
#if 1
    if(visual && visual->visual)
    {
	/* GCs for copy and drawing on mask */
	XGCValues gv;
	gv.foreground = BlackPixel(gui->display, gui->screen);
	gv.background = BlackPixel(gui->display, gui->screen);
	//GC gc = XCreateGC(gui->display, win->window, GCBackground|GCForeground, &gv);
	GC gc = XCreateGC(gui->display, aw, GCBackground|GCForeground, &gv);

	XSetClipMask(gui->display, gc, icon_mask);
    }
#endif
    XpmCreatePixmapFromData(gui->display, win->window,
		oxim_tray, &tray, &mask, &attributes);
    tray_w = attributes.width;
    tray_h = attributes.height;

    win->width  = tray_w;
    win->height = tray_h;

    XpmFreeAttributes(&attributes);
    XFreePixmap(gui->display, tray);
    if (mask)
    {
	XFreePixmap(gui->display, mask);
    }
    win->pos_x = 0;
    win->pos_y = 0;

    win->win_draw_func = NULL;
    win->win_event_func = gui_focus_event;

    XSizeHints *size_hints = XAllocSizeHints();
    size_hints->flags = PMinSize | PMaxSize;
    size_hints->min_width = win->width;
    size_hints->min_height = win->height;
    size_hints->max_width = win->width;
    size_hints->max_height = win->height;
    XSetWMNormalHints(gui->display, win->window, size_hints);
    XFree(size_hints);

    Atom xembed_info = XInternAtom(gui->display, "_XEMBED_INFO", False);
    unsigned int mapping[2];
    mapping[0] = 0; /* ver 0 */
    mapping[1] = 1; /* request mapping */
    XChangeProperty(gui->display, win->window, xembed_info, xembed_info,
			32, PropModeReplace, (unsigned char *)mapping, 2);
    gui->tray_win = win;
}
示例#26
0
Memimage*
_xattach(char *label, char *winsize)
{
	char *argv[2], *disp;
	int i, havemin, height, mask, n, width, x, xrootid, y;
	Rectangle r;
	XClassHint classhint;
	XDrawable pmid;
	XPixmapFormatValues *pfmt;
	XScreen *xscreen;
	XSetWindowAttributes attr;
	XSizeHints normalhint;
	XTextProperty name;
	XVisualInfo xvi;
	XWindow xrootwin;
	XWindowAttributes wattr;
	XWMHints hint;
	Atom atoms[2];

	/*
	if(XInitThreads() == 0){
		fprint(2, "XInitThreads failed\n");
		abort();
	}
	*/

	/*
	 * Connect to X server.
	 */
	_x.display = XOpenDisplay(NULL);
	if(_x.display == nil){
		disp = getenv("DISPLAY");
		werrstr("XOpenDisplay %s: %r", disp ? disp : ":0");
		free(disp);
		return nil;
	}
	_x.fd = ConnectionNumber(_x.display);
	XSetErrorHandler(xerror);
	XSetIOErrorHandler(xioerror);
	xrootid = DefaultScreen(_x.display);
	xrootwin = DefaultRootWindow(_x.display);

	/* 
	 * Figure out underlying screen format.
	 */
	if(XMatchVisualInfo(_x.display, xrootid, 24, TrueColor, &xvi)
	|| XMatchVisualInfo(_x.display, xrootid, 24, DirectColor, &xvi)){
		_x.vis = xvi.visual;
		_x.depth = 24;
	}
	else
	if(XMatchVisualInfo(_x.display, xrootid, 16, TrueColor, &xvi)
	|| XMatchVisualInfo(_x.display, xrootid, 16, DirectColor, &xvi)){
		_x.vis = xvi.visual;
		_x.depth = 16;
	}
	else
	if(XMatchVisualInfo(_x.display, xrootid, 15, TrueColor, &xvi)
	|| XMatchVisualInfo(_x.display, xrootid, 15, DirectColor, &xvi)){
		_x.vis = xvi.visual;
		_x.depth = 15;
	}
	else
	if(XMatchVisualInfo(_x.display, xrootid, 8, PseudoColor, &xvi)
	|| XMatchVisualInfo(_x.display, xrootid, 8, StaticColor, &xvi)){
		if(_x.depth > 8){
			werrstr("can't deal with colormapped depth %d screens",
				_x.depth);
			goto err0;
		}
		_x.vis = xvi.visual;
		_x.depth = 8;
	}
	else{
		_x.depth = DefaultDepth(_x.display, xrootid);
		if(_x.depth != 8){
			werrstr("can't understand depth %d screen", _x.depth);
			goto err0;
		}
		_x.vis = DefaultVisual(_x.display, xrootid);
	}

	if(DefaultDepth(_x.display, xrootid) == _x.depth)
		_x.usetable = 1;

	/*
	 * _x.depth is only the number of significant pixel bits,
	 * not the total number of pixel bits.  We need to walk the
	 * display list to find how many actual bits are used
	 * per pixel.
	 */
	_x.chan = 0;
	pfmt = XListPixmapFormats(_x.display, &n);
	for(i=0; i<n; i++){
		if(pfmt[i].depth == _x.depth){
			switch(pfmt[i].bits_per_pixel){
			case 1:	/* untested */
				_x.chan = GREY1;
				break;
			case 2:	/* untested */
				_x.chan = GREY2;
				break;
			case 4:	/* untested */
				_x.chan = GREY4;
				break;
			case 8:
				_x.chan = CMAP8;
				break;
			case 15:
				_x.chan = RGB15;
				break;
			case 16: /* how to tell RGB15? */
				_x.chan = RGB16;
				break;
			case 24: /* untested (impossible?) */
				_x.chan = RGB24;
				break;
			case 32:
				_x.chan = XRGB32;
				break;
			}
		}
	}
	if(_x.chan == 0){
		werrstr("could not determine screen pixel format");
		goto err0;
	}

	/*
	 * Set up color map if necessary.
	 */
	xscreen = DefaultScreenOfDisplay(_x.display);
	_x.cmap = DefaultColormapOfScreen(xscreen);
	if(_x.vis->class != StaticColor){
		plan9cmap();
		setupcmap(xrootwin);
	}

	/*
	 * We get to choose the initial rectangle size.
	 * This is arbitrary.  In theory we should read the
	 * command line and allow the traditional X options.
	 */
	mask = 0;
	x = 0;
	y = 0;
	if(winsize && winsize[0]){
		if(parsewinsize(winsize, &r, &havemin) < 0)
			sysfatal("%r");
	}else{
		/*
		 * Parse the various X resources.  Thanks to Peter Canning.
		 */
		char *screen_resources, *display_resources, *geom, 
			*geomrestype, *home, *file;
		XrmDatabase database;
		XrmValue geomres;

		database = XrmGetDatabase(_x.display);
		screen_resources = XScreenResourceString(xscreen);
		if(screen_resources != nil){
			XrmCombineDatabase(XrmGetStringDatabase(screen_resources), &database, False);
			XFree(screen_resources);
		}

		display_resources = XResourceManagerString(_x.display);
		if(display_resources == nil){
			home = getenv("HOME");
			if(home!=nil && (file=smprint("%s/.Xdefaults", home)) != nil){
				XrmCombineFileDatabase(file, &database, False);
				free(file);
			}
			free(home);
		}else
			XrmCombineDatabase(XrmGetStringDatabase(display_resources), &database, False);

		geom = smprint("%s.geometry", label);
		if(geom && XrmGetResource(database, geom, nil, &geomrestype, &geomres))
			mask = XParseGeometry(geomres.addr, &x, &y, (uint*)&width, (uint*)&height);
		free(geom);

		if((mask & WidthValue) && (mask & HeightValue)){
			r = Rect(0, 0, width, height);
		}else{
			r = Rect(0, 0, WidthOfScreen(xscreen)*3/4,
					HeightOfScreen(xscreen)*3/4);
			if(Dx(r) > Dy(r)*3/2)
				r.max.x = r.min.x + Dy(r)*3/2;
			if(Dy(r) > Dx(r)*3/2)
				r.max.y = r.min.y + Dx(r)*3/2;
		}
		if(mask & XNegative){
			x += WidthOfScreen(xscreen);
		}
		if(mask & YNegative){
			y += HeightOfScreen(xscreen);
		}
		havemin = 0;
	}
	screenrect = Rect(0, 0, WidthOfScreen(xscreen), HeightOfScreen(xscreen));
	windowrect = r;

	memset(&attr, 0, sizeof attr);
	attr.colormap = _x.cmap;
	attr.background_pixel = ~0;
	attr.border_pixel = 0;
	_x.drawable = XCreateWindow(
		_x.display,	/* display */
		xrootwin,	/* parent */
		x,		/* x */
		y,		/* y */
		Dx(r),		/* width */
	 	Dy(r),		/* height */
		0,		/* border width */
		_x.depth,	/* depth */
		InputOutput,	/* class */
		_x.vis,		/* visual */
				/* valuemask */
		CWBackPixel|CWBorderPixel|CWColormap,
		&attr		/* attributes (the above aren't?!) */
	);

	/*
	 * Label and other properties required by ICCCCM.
	 */
	memset(&name, 0, sizeof name);
	if(label == nil)
		label = "pjw-face-here";
	name.value = (uchar*)label;
	name.encoding = XA_STRING;
	name.format = 8;
	name.nitems = strlen((char*)name.value);

	memset(&normalhint, 0, sizeof normalhint);
	normalhint.flags = PSize|PMaxSize;
	if(winsize && winsize[0]){
		normalhint.flags &= ~PSize;
		normalhint.flags |= USSize;
		normalhint.width = Dx(r);
		normalhint.height = Dy(r);
	}else{
		if((mask & WidthValue) && (mask & HeightValue)){
			normalhint.flags &= ~PSize;
			normalhint.flags |= USSize;
			normalhint.width = width;
			normalhint.height = height;
		}
		if((mask & WidthValue) && (mask & HeightValue)){
			normalhint.flags |= USPosition;
			normalhint.x = x;
			normalhint.y = y;
		}
	}

	normalhint.max_width = WidthOfScreen(xscreen);
	normalhint.max_height = HeightOfScreen(xscreen);

	memset(&hint, 0, sizeof hint);
	hint.flags = InputHint|StateHint;
	hint.input = 1;
	hint.initial_state = NormalState;

	memset(&classhint, 0, sizeof classhint);
	classhint.res_name = label;
	classhint.res_class = label;

	argv[0] = label;
	argv[1] = nil;

	XSetWMProperties(
		_x.display,	/* display */
		_x.drawable,	/* window */
		&name,		/* XA_WM_NAME property */
		&name,		/* XA_WM_ICON_NAME property */
		argv,		/* XA_WM_COMMAND */
		1,		/* argc */
		&normalhint,	/* XA_WM_NORMAL_HINTS */
		&hint,		/* XA_WM_HINTS */
		&classhint	/* XA_WM_CLASSHINTS */
	);
	XFlush(_x.display);

	if(havemin){
		XWindowChanges ch;

		memset(&ch, 0, sizeof ch);
		ch.x = r.min.x;
		ch.y = r.min.y;
		XConfigureWindow(_x.display, _x.drawable, CWX|CWY, &ch);
		/*
		 * Must pretend origin is 0,0 for X.
		 */
		r = Rect(0,0,Dx(r),Dy(r));
	}
	/*
	 * Look up clipboard atom.
	 */
	_x.clipboard = XInternAtom(_x.display, "CLIPBOARD", False);
	_x.utf8string = XInternAtom(_x.display, "UTF8_STRING", False);
	_x.targets = XInternAtom(_x.display, "TARGETS", False);
	_x.text = XInternAtom(_x.display, "TEXT", False);
	_x.compoundtext = XInternAtom(_x.display, "COMPOUND_TEXT", False);
	_x.takefocus = XInternAtom(_x.display, "WM_TAKE_FOCUS", False);
	_x.losefocus = XInternAtom(_x.display, "_9WM_LOSE_FOCUS", False);
	_x.wmprotos = XInternAtom(_x.display, "WM_PROTOCOLS", False);

	atoms[0] = _x.takefocus;
	atoms[1] = _x.losefocus;
	XChangeProperty(_x.display, _x.drawable, _x.wmprotos, XA_ATOM, 32,
		PropModeReplace, (uchar*)atoms, 2);

	/*
	 * Put the window on the screen, check to see what size we actually got.
	 */
	XMapWindow(_x.display, _x.drawable);
	XSync(_x.display, False);

	if(!XGetWindowAttributes(_x.display, _x.drawable, &wattr))
		fprint(2, "XGetWindowAttributes failed\n");
	else if(wattr.width && wattr.height){
		if(wattr.width != Dx(r) || wattr.height != Dy(r)){
			r.max.x = wattr.width;
			r.max.y = wattr.height;
		}
	}else
		fprint(2, "XGetWindowAttributes: bad attrs\n");

	/*
	 * Allocate our local backing store.
	 */
	_x.screenr = r;
	_x.screenpm = XCreatePixmap(_x.display, _x.drawable, Dx(r), Dy(r), _x.depth);
	_x.nextscreenpm = _x.screenpm;
	_x.screenimage = _xallocmemimage(r, _x.chan, _x.screenpm);

	/*
	 * Allocate some useful graphics contexts for the future.
	 */
	_x.gcfill	= xgc(_x.screenpm, FillSolid, -1);
	_x.gccopy	= xgc(_x.screenpm, -1, -1);
	_x.gcsimplesrc 	= xgc(_x.screenpm, FillStippled, -1);
	_x.gczero	= xgc(_x.screenpm, -1, -1);
	_x.gcreplsrc	= xgc(_x.screenpm, FillTiled, -1);

	pmid = XCreatePixmap(_x.display, _x.drawable, 1, 1, 1);
	_x.gcfill0	= xgc(pmid, FillSolid, 0);
	_x.gccopy0	= xgc(pmid, -1, -1);
	_x.gcsimplesrc0	= xgc(pmid, FillStippled, -1);
	_x.gczero0	= xgc(pmid, -1, -1);
	_x.gcreplsrc0	= xgc(pmid, FillTiled, -1);
	XFreePixmap(_x.display, pmid);

	return _x.screenimage;

err0:
	/*
	 * Should do a better job of cleaning up here.
	 */
	XCloseDisplay(_x.display);
	return nil;
}
示例#27
0
文件: apc_pointer.c 项目: dk/Prima
static Bool
xlib_cursor_load( Handle self, Handle icon)
{
	XImage *im;
	Pixmap p1 = None, p2 = None;
	Bool free_pixmap = true;
	GC gc;
	XGCValues gcv;
	char c;
	int id, w = guts.cursor_width, h = guts.cursor_height;

	id = get_cursor( self, &p1, &p2, nil, nil);
	if ( id < crDefault || id > crUser)  return false;
	if ( id == crUser) {
		if ( !p1 || !p2) {
			warn( "User pointer inconsistency");
			return false;
		}
		free_pixmap = false;
	} else {
		XFontStruct *fs;
		XCharStruct *cs;
		int idx = cursor_map[id];

		if ( !load_pointer_font()) return false;
		fs = guts.pointer_font;
		if ( !fs-> per_char)
			cs = &fs-> min_bounds;
		else if ( idx < fs-> min_char_or_byte2 || idx > fs-> max_char_or_byte2) {
			int default_char = fs-> default_char;
			if ( default_char < fs-> min_char_or_byte2 || default_char > fs-> max_char_or_byte2)
				default_char = fs-> min_char_or_byte2;
			cs = fs-> per_char + default_char - fs-> min_char_or_byte2;
		} else
			cs = fs-> per_char + idx - fs-> min_char_or_byte2;

		p1 = XCreatePixmap( DISP, guts. root, w, h, 1);
		p2 = XCreatePixmap( DISP, guts. root, w, h, 1);
		gcv. background = 1;
		gcv. foreground = 0;
		gcv. font = guts.pointer_font-> fid;
		gc = XCreateGC( DISP, p1, GCBackground | GCForeground | GCFont, &gcv);
		XFillRectangle( DISP, p1, gc, 0, 0, w, h);
		gcv. background = 0;
		gcv. foreground = 1;
		XChangeGC( DISP, gc, GCBackground | GCForeground, &gcv);
		XFillRectangle( DISP, p2, gc, 0, 0, w, h);
		XDrawString( DISP, p1, gc, -cs-> lbearing, cs-> ascent, (c = (char)(idx+1), &c), 1);
		gcv. background = 1;
		gcv. foreground = 0;
		XChangeGC( DISP, gc, GCBackground | GCForeground, &gcv);
		XDrawString( DISP, p2, gc, -cs-> lbearing, cs-> ascent, (c = (char)(idx+1), &c), 1);
		XDrawString( DISP, p1, gc, -cs-> lbearing, cs-> ascent, (c = (char)idx, &c), 1);
		XFreeGC( DISP, gc);
	}
	CIcon(icon)-> create_empty( icon, w, h, imBW);
	im = XGetImage( DISP, p1, 0, 0, w, h, 1, XYPixmap);
	prima_copy_xybitmap( PIcon(icon)-> data, (Byte*)im-> data,
								PIcon(icon)-> w, PIcon(icon)-> h,
								PIcon(icon)-> lineSize, im-> bytes_per_line);
	XDestroyImage( im);
	im = XGetImage( DISP, p2, 0, 0, w, h, 1, XYPixmap);
	prima_copy_xybitmap( PIcon(icon)-> mask, (Byte*)im-> data,
								PIcon(icon)-> w, PIcon(icon)-> h,
								PIcon(icon)-> maskLine, im-> bytes_per_line);
	if ( id == crUser) {
		int i;
		Byte * mask = PIcon(icon)-> mask;
		for ( i = 0; i < PIcon(icon)-> maskSize; i++)
			mask[i] = ~mask[i];
	}
	XDestroyImage( im);
	if ( free_pixmap) {
		XFreePixmap( DISP, p1);
		XFreePixmap( DISP, p2);
	}
	return true;
}
示例#28
0
/* sets a window background from a colorset
 * if width or height are zero the window size is queried
 */
void SetWindowBackgroundWithOffset(
	Display *dpy, Window win, int x_off, int y_off, unsigned int width, unsigned int height,
	colorset_t *colorset, unsigned int depth, GC gc, Bool clear_area)
{
	Pixmap pixmap = None;
	Pixmap mask = None;
	union {
		XID junk;
		unsigned int ui_junk;
		int i_junk;
	} XID_int;
	if (0 == width || 0 == height)
	{
		if (!XGetGeometry(
			    dpy, win, &XID_int.junk,
			    &XID_int.i_junk, &XID_int.i_junk,
			    (unsigned int *)&width,
			    (unsigned int *)&height,
			    &XID_int.ui_junk,
			    &XID_int.ui_junk))
		{
			return;
		}
	}

	if (FHaveShapeExtension && colorset->shape_mask)
	{
		mask = CreateBackgroundPixmap(
			dpy, None, width, height, colorset, 1, None, True);
		if (mask != None)
		{
			FShapeCombineMask(
				dpy, win, FShapeBounding, 0, 0, mask,
				FShapeSet);
			XFreePixmap(dpy, mask);
		}
	}
	if (!colorset->pixmap)
	{
		/* use the bg pixel */
		XSetWindowBackground(dpy, win, colorset->bg);
		if (clear_area)
		{
			XClearArea(dpy, win, 0, 0, width, height, True);
		}
	}
	else
	{

		pixmap = CreateOffsetBackgroundPixmap(
			dpy, win, x_off, y_off, width, height, colorset,
			depth, gc, False);
		if (pixmap)
		{
			XSetWindowBackgroundPixmap(dpy, win, pixmap);
			if (clear_area)
			{
				XClearArea(dpy, win, 0, 0, width, height, True);
			}
			if (pixmap != ParentRelative)
			{
				XFreePixmap(dpy, pixmap);
			}
		}
	}

	return;
}
示例#29
0
void
Fake_glXUseXFont(Font font, int first, int count, int listbase)
{
   Display *dpy;
   Window win;
   Pixmap pixmap;
   GC gc;
   XGCValues values;
   unsigned long valuemask;
   XFontStruct *fs;
   GLint swapbytes, lsbfirst, rowlength;
   GLint skiprows, skippixels, alignment;
   unsigned int max_width, max_height, max_bm_width, max_bm_height;
   GLubyte *bm;
   int i;

   dpy = glXGetCurrentDisplay();
   if (!dpy)
      return;			/* I guess glXMakeCurrent wasn't called */
   win = RootWindow(dpy, DefaultScreen(dpy));

   fs = XQueryFont(dpy, font);
   if (!fs) {
      _mesa_error(NULL, GL_INVALID_VALUE,
		  "Couldn't get font structure information");
      return;
   }

   /* Allocate a bitmap that can fit all characters.  */
   max_width = fs->max_bounds.rbearing - fs->min_bounds.lbearing;
   max_height = fs->max_bounds.ascent + fs->max_bounds.descent;
   max_bm_width = (max_width + 7) / 8;
   max_bm_height = max_height;

   bm = (GLubyte *) MALLOC((max_bm_width * max_bm_height) * sizeof(GLubyte));
   if (!bm) {
      XFreeFontInfo(NULL, fs, 1);
      _mesa_error(NULL, GL_OUT_OF_MEMORY,
		  "Couldn't allocate bitmap in glXUseXFont()");
      return;
   }

#if 0
   /* get the page info */
   pages = fs->max_char_or_byte2 - fs->min_char_or_byte2 + 1;
   firstchar = (fs->min_byte1 << 8) + fs->min_char_or_byte2;
   lastchar = (fs->max_byte1 << 8) + fs->max_char_or_byte2;
   rows = fs->max_byte1 - fs->min_byte1 + 1;
   unsigned int first_char, last_char, pages, rows;
#endif

   /* Save the current packing mode for bitmaps.  */
   glGetIntegerv(GL_UNPACK_SWAP_BYTES, &swapbytes);
   glGetIntegerv(GL_UNPACK_LSB_FIRST, &lsbfirst);
   glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowlength);
   glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skiprows);
   glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skippixels);
   glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);

   /* Enforce a standard packing mode which is compatible with
      fill_bitmap() from above.  This is actually the default mode,
      except for the (non)alignment.  */
   glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
   glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
   glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
   glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
   glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

   pixmap = XCreatePixmap(dpy, win, 10, 10, 1);
   values.foreground = BlackPixel(dpy, DefaultScreen(dpy));
   values.background = WhitePixel(dpy, DefaultScreen(dpy));
   values.font = fs->fid;
   valuemask = GCForeground | GCBackground | GCFont;
   gc = XCreateGC(dpy, pixmap, valuemask, &values);
   XFreePixmap(dpy, pixmap);

#ifdef DEBUG
   if (debug_xfonts)
      dump_font_struct(fs);
#endif

   for (i = 0; i < count; i++) {
      unsigned int width, height, bm_width, bm_height;
      GLfloat x0, y0, dx, dy;
      XCharStruct *ch;
      int x, y;
      unsigned int c = first + i;
      int list = listbase + i;
      int valid;

      /* check on index validity and get the bounds */
      ch = isvalid(fs, c);
      if (!ch) {
	 ch = &fs->max_bounds;
	 valid = 0;
      }
      else {
	 valid = 1;
      }

#ifdef DEBUG
      if (debug_xfonts) {
	 char s[7];
	 sprintf(s, isprint(c) ? "%c> " : "\\%03o> ", c);
	 dump_char_struct(ch, s);
      }
#endif

      /* glBitmap()' parameters:
         straight from the glXUseXFont(3) manpage.  */
      width = ch->rbearing - ch->lbearing;
      height = ch->ascent + ch->descent;
      x0 = -ch->lbearing;
      y0 = ch->descent - 0;	/* XXX used to subtract 1 here */
      /* but that caused a conformace failure */
      dx = ch->width;
      dy = 0;

      /* X11's starting point.  */
      x = -ch->lbearing;
      y = ch->ascent;

      /* Round the width to a multiple of eight.  We will use this also
         for the pixmap for capturing the X11 font.  This is slightly
         inefficient, but it makes the OpenGL part real easy.  */
      bm_width = (width + 7) / 8;
      bm_height = height;

      glNewList(list, GL_COMPILE);
      if (valid && (bm_width > 0) && (bm_height > 0)) {

	 MEMSET(bm, '\0', bm_width * bm_height);
	 fill_bitmap(dpy, win, gc, bm_width, bm_height, x, y, c, bm);

	 glBitmap(width, height, x0, y0, dx, dy, bm);
#ifdef DEBUG
	 if (debug_xfonts) {
	    printf("width/height = %u/%u\n", width, height);
	    printf("bm_width/bm_height = %u/%u\n", bm_width, bm_height);
	    dump_bitmap(bm_width, bm_height, bm);
	 }
#endif
      }
      else {
	 glBitmap(0, 0, 0.0, 0.0, dx, dy, NULL);
      }
      glEndList();
   }

   FREE(bm);
   XFreeFontInfo(NULL, fs, 1);
   XFreeGC(dpy, gc);

   /* Restore saved packing modes.  */
   glPixelStorei(GL_UNPACK_SWAP_BYTES, swapbytes);
   glPixelStorei(GL_UNPACK_LSB_FIRST, lsbfirst);
   glPixelStorei(GL_UNPACK_ROW_LENGTH, rowlength);
   glPixelStorei(GL_UNPACK_SKIP_ROWS, skiprows);
   glPixelStorei(GL_UNPACK_SKIP_PIXELS, skippixels);
   glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
}
示例#30
0
X11Graphics::~X11Graphics()
{
    XFreeGC( XDISPLAY, m_gc );
    XDestroyRegion( m_mask );
    XFreePixmap( XDISPLAY, m_pixmap );
}