Exemplo n.º 1
0
void 
xRubberBox (Display *dpy, Window win, XEvent event,
	int *x, int *y, int *width, int *height)
/*****************************************************************************
Track pointer with rubber box
******************************************************************************
Input:
dpy		display pointer
win		window ID
event		event of type ButtonPress

Output:
x		x of upper left hand corner of box in pixels
y		y of upper left hand corner of box in pixels
width		width of box in pixels
height		height of box in pixels
******************************************************************************
Notes:
xRubberBox assumes that event is a ButtonPress event for the 1st button;
i.e., it tracks motion of the pointer while the 1st button is down, and
it sets x, y, w, and h and returns after a ButtonRelease event for the
1st button.

Before calling xRubberBox, both ButtonRelease and Button1Motion events 
must be enabled.
******************************************************************************
Author:		Dave Hale, Colorado School of Mines, 01/27/90
*****************************************************************************/
{
	GC gc;
	XGCValues *values=NULL;
	XEvent eventb;
	XStandardColormap scmap;
	int scr=DefaultScreen(dpy);
	int xb,yb,w,h,x1,x2,y1,y2,xorig,yorig,xold,yold;
	unsigned long background;

	/* determine typical background color */
	/* +1 added by John Stockwell 23 Jun 1993 */
	/* to shift xwigb rubberbox from light green to red */
	if (xCreateRGBDefaultMap(dpy,&scmap))
		background = (xGetFirstPixel(dpy)+xGetLastPixel(dpy) + 1)/2;
	else
		background = WhitePixel(dpy,scr);


	/* make graphics context */
	gc = XCreateGC(dpy,win,0,values);
  	XSetFunction(dpy,gc,GXxor);
  	XSetForeground(dpy,gc,BlackPixel(dpy,scr)^background);

	/* track pointer */
	xorig = event.xbutton.x;
	yorig = event.xbutton.y;
	xold = xorig;
	yold = yorig;
	x1 = xorig;
	y1 = yorig;
	w = 0;
	h = 0;
	while(h|(~h)/*True*/) {
		XNextEvent(dpy,&eventb);
		if (eventb.type==ButtonRelease) {
			xb = eventb.xbutton.x;
			yb = eventb.xbutton.y;
			break;
		} else if (eventb.type==MotionNotify) {
			xb = eventb.xmotion.x;
			yb = eventb.xmotion.y;

			/* if box is the same, continue */
			if (xb==xold && yb==yold) 
				continue;

			/* erase old box */
			x1 = (xold<xorig)?xold:xorig;
			y1 = (yold<yorig)?yold:yorig;
			x2 = (xold>xorig)?xold:xorig;
			y2 = (yold>yorig)?yold:yorig;
			w = x2-x1;
			h = y2-y1;
			XDrawRectangle(dpy,win,gc,x1,y1,w,h);

			/* draw current box */
			x1 = (xb<xorig)?xb:xorig;
			y1 = (yb<yorig)?yb:yorig;
			x2 = (xb>xorig)?xb:xorig;
			y2 = (yb>yorig)?yb:yorig;
			w = x2-x1;
			h = y2-y1;
			XDrawRectangle(dpy,win,gc,x1,y1,w,h);

			/* remember current pointer position */
			xold = xb;
			yold = yb;
		}
	}

	/* erase rubber box */
	XDrawRectangle(dpy,win,gc,x1,y1,w,h);

	/* free graphics context */
	XFreeGC(dpy,gc);

	/* set output parameters */
	*x = x1;
	*y = y1;
	*width = w;
	*height = h;
}
Exemplo n.º 2
0
bool CWinSystemX11::CreateIconPixmap()
{
  int depth;
  XImage *img = NULL;
  Visual *vis;
  XWindowAttributes wndattribs;
  XVisualInfo visInfo;
  double rRatio;
  double gRatio;
  double bRatio;
  int outIndex = 0;
  unsigned int i,j;
  unsigned char *buf;
  uint32_t *newBuf = 0;
  size_t numNewBufBytes;

  // Get visual Info
  XGetWindowAttributes(m_dpy, m_glWindow, &wndattribs);
  visInfo.visualid = wndattribs.visual->visualid;
  int nvisuals = 0;
  XVisualInfo* visuals = XGetVisualInfo(m_dpy, VisualIDMask, &visInfo, &nvisuals);
  if (nvisuals != 1)
  {
    CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - could not find visual");
    return false;
  }
  visInfo = visuals[0];
  XFree(visuals);

  depth = visInfo.depth;
  vis = visInfo.visual;

  if (depth < 15)
  {
    CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - no suitable depth");
    return false;
  }

  rRatio = vis->red_mask / 255.0;
  gRatio = vis->green_mask / 255.0;
  bRatio = vis->blue_mask / 255.0;

  CBaseTexture *iconTexture = CBaseTexture::LoadFromFile("special://xbmc/media/icon256x256.png");

  if (!iconTexture)
    return false;

  buf = iconTexture->GetPixels();

  if (depth>=24)
    numNewBufBytes = (4 * (iconTexture->GetWidth() * iconTexture->GetHeight()));
  else
    numNewBufBytes = (2 * (iconTexture->GetWidth() * iconTexture->GetHeight()));

  newBuf = (uint32_t*)malloc(numNewBufBytes);
  if (!newBuf)
  {
    CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - malloc failed");
    return false;
  }

  for (i=0; i<iconTexture->GetHeight();++i)
  {
    for (j=0; j<iconTexture->GetWidth();++j)
    {
      unsigned int pos = i*iconTexture->GetPitch()+j*4;
      unsigned int r, g, b;
      r = (buf[pos+2] * rRatio);
      g = (buf[pos+1] * gRatio);
      b = (buf[pos+0] * bRatio);
      r &= vis->red_mask;
      g &= vis->green_mask;
      b &= vis->blue_mask;
      newBuf[outIndex] = r | g | b;
      ++outIndex;
    }
  }
  img = XCreateImage(m_dpy, vis, depth,ZPixmap, 0, (char *)newBuf,
                     iconTexture->GetWidth(), iconTexture->GetHeight(),
                     (depth>=24)?32:16, 0);
  if (!img)
  {
    CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - could not create image");
    free(newBuf);
    return false;
  }
  if (!XInitImage(img))
  {
    CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - init image failed");
    XDestroyImage(img);
    return false;
  }

  // set byte order
  union
  {
    char c[sizeof(short)];
    short s;
  } order;
  order.s = 1;
  if ((1 == order.c[0]))
  {
    img->byte_order = LSBFirst;
  }
  else
  {
    img->byte_order = MSBFirst;
  }

  // create icon pixmap from image
  m_icon = XCreatePixmap(m_dpy, m_glWindow, img->width, img->height, depth);
  GC gc = XCreateGC(m_dpy, m_glWindow, 0, NULL);
  XPutImage(m_dpy, m_icon, gc, img, 0, 0, 0, 0, img->width, img->height);
  XFreeGC(m_dpy, gc);
  XDestroyImage(img); // this also frees newBuf

  delete iconTexture;

  return true;
}
Exemplo n.º 3
0
static gboolean
effects_draw_box_animation_timeout (BoxAnimationContext *context)
{
    double elapsed;
    GTimeVal current_time;
    MetaRectangle draw_rect;
    double fraction;

#ifndef HAVE_SHAPE
    if (!context->first_time)
    {
        /* Restore the previously drawn background */
        XDrawRectangle (context->screen->display->xdisplay,
                        context->screen->xroot,
                        context->gc,
                        context->last_rect.x, context->last_rect.y,
                        context->last_rect.width, context->last_rect.height);
    }
    else
        context->first_time = FALSE;

#endif /* !HAVE_SHAPE */

    g_get_current_time (&current_time);

    /* We use milliseconds for all times */
    elapsed =
        ((((double)current_time.tv_sec - context->start_time.tv_sec) * G_USEC_PER_SEC +
          (current_time.tv_usec - context->start_time.tv_usec))) / 1000.0;

    if (elapsed < 0)
    {
        /* Probably the system clock was set backwards? */
        meta_warning ("System clock seemed to go backwards?\n");
        elapsed = G_MAXDOUBLE; /* definitely done. */
    }

    if (elapsed > context->millisecs_duration)
    {
        /* All done */
#ifdef HAVE_SHAPE
        XDestroyWindow (context->screen->display->xdisplay,
                        context->wireframe_xwindow);
#else
        meta_display_ungrab (context->screen->display);
        meta_ui_pop_delay_exposes (context->screen->ui);
        XFreeGC (context->screen->display->xdisplay,
                 context->gc);
#endif /* !HAVE_SHAPE */

        graphics_sync (context);

        context->finished(context->finished_data);

        g_free (context);
        return FALSE;
    }

    g_assert (context->millisecs_duration > 0.0);
    fraction = elapsed / context->millisecs_duration;

    draw_rect = context->start_rect;

    /* Now add a delta proportional to elapsed time. */
    draw_rect.x += (context->end_rect.x - context->start_rect.x) * fraction;
    draw_rect.y += (context->end_rect.y - context->start_rect.y) * fraction;
    draw_rect.width += (context->end_rect.width - context->start_rect.width) * fraction;
    draw_rect.height += (context->end_rect.height - context->start_rect.height) * fraction;

    /* don't confuse X or gdk-pixbuf with bogus rectangles */
    if (draw_rect.width < 1)
        draw_rect.width = 1;
    if (draw_rect.height < 1)
        draw_rect.height = 1;

#ifdef HAVE_SHAPE
    update_wireframe_window (context->screen->display,
                             context->wireframe_xwindow,
                             &draw_rect);
#else
    context->last_rect = draw_rect;

    /* Draw the rectangle */
    XDrawRectangle (context->screen->display->xdisplay,
                    context->screen->xroot,
                    context->gc,
                    draw_rect.x, draw_rect.y,
                    draw_rect.width, draw_rect.height);

#endif /* !HAVE_SHAPE */

    /* kick changes onto the server */
    graphics_sync (context);

    return TRUE;
}
Exemplo n.º 4
0
/* Render a character. */
static int
x_render_char(gx_xfont * xf, gx_xglyph xg, gx_device * dev,
	      int xo, int yo, gx_color_index color, int required)
{
    x_xfont *xxf = (x_xfont *) xf;
    char chr = (char)xg;
    gs_point wxy;
    gs_int_rect bbox;
    int x, y, w, h;
    int code;

    if (dev->dname == gs_x11_device.dname && !((gx_device_X *)dev)->is_buffered) {
	gx_device_X *xdev = (gx_device_X *)dev;

	code = (*xf->common.procs->char_metrics) (xf, xg, 0, &wxy, &bbox);
	if (code < 0)
	    return code;
	/* Buffer text for more efficient X interaction. */
	if (xdev->text.item_count == MAX_TEXT_ITEMS ||
	    xdev->text.char_count == MAX_TEXT_CHARS ||
	    (IN_TEXT(xdev) &&
	     (yo != xdev->text.origin.y || color != xdev->fore_color ||
	      xxf->font->fid != xdev->fid))
	    ) {
	    DRAW_TEXT(xdev);
	    xdev->text.item_count = xdev->text.char_count = 0;
	}
	if (xdev->text.item_count == 0) {
	    X_SET_FILL_STYLE(xdev, FillSolid);
	    X_SET_FORE_COLOR(xdev, color);
	    X_SET_FUNCTION(xdev, GXcopy);
	    xdev->text.origin.x = xdev->text.x = xo;
	    xdev->text.origin.y = yo;
	    xdev->text.items[0].font = xdev->fid = xxf->font->fid;
	}
	/*
	 * The following is wrong for rotated text, but it doesn't matter,
	 * because the next call of x_render_char will have a different Y.
	 */
	{
	    int index = xdev->text.item_count;
	    XTextItem *item = &xdev->text.items[index];
	    char *pchar = &xdev->text.chars[xdev->text.char_count++];
	    int delta = xo - xdev->text.x;

	    *pchar = chr;
	    if (index > 0 && delta == 0) {
		/* Continue the same item. */
		item[-1].nchars++;
	    } else {
		/* Start a new item. */
		item->chars = pchar;
		item->nchars = 1;
		item->delta = delta;
		if (index > 0)
		    item->font = None;
		xdev->text.item_count++;
	    }
	    xdev->text.x = xo + wxy.x;
	}
	if (xdev->bpixmap != (Pixmap) 0) {
	    x = xo + bbox.p.x;
	    y = yo + bbox.p.y;
	    w = bbox.q.x - bbox.p.x;
	    h = bbox.q.y - bbox.p.y;
	    fit_fill(dev, x, y, w, h);
	    x_update_add(xdev, x, y, w, h);
	}
	return 0;
    } else if (!required)
	return -1;		/* too hard */
    else {
	/* Display on an intermediate bitmap, then copy the bits. */
	gx_device_X *xdev = xxf->xdev;
	int wbm, raster;
	int i;
	XImage *xim;
	Pixmap xpm;
	GC fgc;
	byte *bits;

	dev_proc_copy_mono((*copy_mono)) = dev_proc(dev, copy_mono);

	code = (*xf->common.procs->char_metrics) (xf, xg, 0, &wxy, &bbox);
	if (code < 0)
	    return code;
	w = bbox.q.x - bbox.p.x;
	h = bbox.q.y - bbox.p.y;
	wbm = ROUND_UP(w, align_bitmap_mod * 8);
	raster = wbm >> 3;
	bits = (byte *) gs_malloc(xdev->memory, h, raster, "x_render_char");
	if (bits == 0)
	    return gs_error_limitcheck;
	xpm = XCreatePixmap(xdev->dpy, xdev->win, w, h, 1);
	fgc = XCreateGC(xdev->dpy, xpm, None, NULL);
	XSetForeground(xdev->dpy, fgc, 0);
	XFillRectangle(xdev->dpy, xpm, fgc, 0, 0, w, h);
	XSetForeground(xdev->dpy, fgc, 1);
	XSetFont(xdev->dpy, fgc, xxf->font->fid);
	XDrawString(xdev->dpy, xpm, fgc, -bbox.p.x, -bbox.p.y, &chr, 1);
	xim = XGetImage(xdev->dpy, xpm, 0, 0, w, h, 1, ZPixmap);
	i = 0;
	for (y = 0; y < h; y++) {
	    char b = 0;

	    for (x = 0; x < wbm; x++) {
		b = b << 1;
		if (x < w)
		    b += XGetPixel(xim, x, y);
		if ((x & 7) == 7)
		    bits[i++] = b;
	    }
	}
	code = (*copy_mono) (dev, bits, 0, raster, gx_no_bitmap_id,
			     xo + bbox.p.x, yo + bbox.p.y, w, h,
			     gx_no_color_index, color);
	gs_free(xdev->memory, (char *)bits, h, raster, "x_render_char");
	XFreePixmap(xdev->dpy, xpm);
	XFreeGC(xdev->dpy, fgc);
	XDestroyImage(xim);
	return (code < 0 ? code : 0);
    }
}
Exemplo n.º 5
0
void
XmLStringDrawDirection(Display *dpy,
		       Window win,
		       XmFontList fontlist,
		       XmString string,
		       GC gc,
		       int x,
		       int y,
		       Dimension width,
		       unsigned char alignment,
		       unsigned char layout_direction,
		       unsigned char drawing_direction)
{
	Screen *screen;
	XFontStruct *fontStruct;
	XImage *sourceImage, *destImage;
	Pixmap pixmap;
	GC pixmapGC;
	/*	int sourceWidth, sourceHeight;*/
	int destWidth, destHeight;
	int stringWidth, stringHeight;
	int i, j, bytesPerLine;
	Dimension dW, dH;
	char *data;

	screen = DefaultScreenOfDisplay(dpy);
	XmStringExtent(fontlist, string, &dW, &dH);
	stringWidth = (int)dW;
	stringHeight = (int)dH;
	if (!stringWidth || !stringHeight)
		return;

	/* draw string into 1 bit deep pixmap */
	pixmap = XCreatePixmap(dpy, win, stringWidth, stringHeight, 1);
	pixmapGC = XCreateGC(dpy, pixmap, 0, NULL);
	fontStruct = XLoadQueryFont(dpy, "fixed");
	if (!fontStruct)
		{
		fprintf(stderr, "XmLStringDrawDirection: error - ");
		fprintf(stderr, "can't load fixed font\n");
		return;
		}
	XSetFont(dpy, pixmapGC, fontStruct->fid);
	XSetBackground(dpy, pixmapGC, 0L);
	XSetForeground(dpy, pixmapGC, 0L);
	XFillRectangle(dpy, pixmap, pixmapGC, 0, 0, stringWidth, stringHeight);
	XSetForeground(dpy, pixmapGC, 1L);
	XmStringDraw(dpy, pixmap, fontlist, string, pixmapGC, 0, 0, stringWidth,
		XmALIGNMENT_BEGINNING, layout_direction, 0);
	XFreeFont(dpy, fontStruct);

	/* copy 1 bit deep pixmap into source image */
	sourceImage = XGetImage(dpy, pixmap, 0, 0, stringWidth, stringHeight,
		1, XYPixmap);
	XFreePixmap(dpy, pixmap);

	/* draw rotated text into destination image */
	if (drawing_direction == XmSTRING_UP || drawing_direction == XmSTRING_DOWN)
		{
		destWidth = stringHeight;
		destHeight = stringWidth;
		}
	else
		{
		destWidth = stringWidth;
		destHeight = stringHeight;
		}
	bytesPerLine  = (destWidth - 1) / 8 + 1;
	data = (char *)malloc(bytesPerLine * destHeight);
	destImage = XCreateImage(dpy, DefaultVisualOfScreen(screen),
	    1, XYBitmap, 0, data, destWidth, destHeight, 8, 0);
	for (i = 0; i < stringWidth; i++)
		for (j = 0; j < stringHeight; j++)
			{
			if (drawing_direction == XmSTRING_UP)
				XPutPixel(destImage, j, i,
					XGetPixel(sourceImage, stringWidth - i - 1, j));
			else if (drawing_direction == XmSTRING_DOWN)
				XPutPixel(destImage, stringHeight - j - 1, stringWidth - i - 1,
					XGetPixel(sourceImage, stringWidth - i - 1, j));
			else if (drawing_direction == XmSTRING_LEFT)
				XPutPixel(destImage, i, stringHeight - j - 1,
					XGetPixel(sourceImage, stringWidth - i - 1, j));
			else
				XPutPixel(destImage, i, j,
					XGetPixel(sourceImage, i, j));
			}
	XDestroyImage(sourceImage);

	/* copy rotated image into 1 bit deep pixmap */
	pixmap = XCreatePixmap(dpy, win, destWidth, destHeight, 1);
	XPutImage(dpy, pixmap, pixmapGC, destImage, 0, 0, 0, 0,
	    destWidth, destHeight);
	XDestroyImage(destImage);
	XFreeGC(dpy, pixmapGC);

	/* adjust position for alignment */
	if (drawing_direction == XmSTRING_UP || drawing_direction == XmSTRING_DOWN)
		{
		if (alignment == XmALIGNMENT_BEGINNING)
			;
		else if (alignment == XmALIGNMENT_CENTER)
			y += width / 2 - stringWidth / 2;
		else if (alignment == XmALIGNMENT_END)
			y += (int)width - stringWidth;
		}
	else
		{
		if (alignment == XmALIGNMENT_BEGINNING)
			;
		else if (alignment == XmALIGNMENT_CENTER)
			x += width / 2 - stringWidth / 2;
		else if (alignment == XmALIGNMENT_END)
			x += (int)width - stringWidth;
		}

	/* draw the pixmap as a stipple in the window */
	XSetStipple(dpy, gc, pixmap);
	XSetFillStyle(dpy, gc, FillStippled);
	XSetTSOrigin(dpy, gc, x % destWidth, y % destHeight);
	XFillRectangle(dpy, win, gc, x, y, destWidth, destHeight);
	XFreePixmap(dpy, pixmap);
	XSetFillStyle(dpy, gc, FillSolid);
	}
Exemplo n.º 6
0
int Disp_DestroyGC(Disp disp, GC gc)
{
  XFreeGC(disp->display, gc);
  return (0);
}
Exemplo n.º 7
0
XsOutline::~XsOutline ( )
{
   XFreeGC (XtDisplay (_w), _gc);
}
Exemplo n.º 8
0
static void displayDTIcon(DTIconRec *dticon)
{
 XGCValues xgcv;
 GC shapeGC;
 Window shellwin;
 XmString labelstr;
 Dimension labelwidth, labelheight, togglewidth, toggleheight;
 Dimension tgl_offs_x, lbl_offs_x, lbl_offs_y;
 Atom targets[2];
 Boolean is_file = False;
 int i;

 targets[0] = dragAtoms.file;
 targets[1] = dragAtoms.filelist;
 drop_args[0].value = (XtArgVal) targets;

 dticon->app.form = XtVaCreateManagedWidget("form", xmFormWidgetClass, dticon->cont, XmNtranslations, XtParseTranslationTable(form_translations), XmNbackground, resources.dticon_color, XmNforeground, resources.label_color, XmNborderWidth, 0, XmNshadowThickness, 0, XmNhighlightThickness, 0, XmNx, 0, XmNy, 0, NULL);

 if (dticon->app.fname[0])
 {
     char path[MAXPATHLEN];
     struct stat stats;
     int errfl = 0;

     if (dticon->app.directory[0])
     {
	 strcpy(path, dticon->app.directory);
	 fnexpand(path);
	 errfl = chdir(path);
     }
     else  errfl = chdir(user.home);
     if (!errfl && !(stat(dticon->app.fname, &stats)) && S_ISREG(stats.st_mode))
	 is_file = True;
 }
 if (is_file)
 {
     for (i=0; i < XtNumber(file_popup_menu); i++)
	 file_popup_menu[i].callback_data = dticon;
     dticon->popup = BuildMenu(dticon->app.form, XmMENU_POPUP, "Button Actions", 0, False, file_popup_menu);
     if (resources.auto_save)
	 XtVaSetValues(file_popup_menu[5].object, XmNsensitive, False, NULL);
 }
 else
 {
     for (i=0; i < XtNumber(file_popup_menu); i++)
	 popup_menu[i].callback_data = dticon;
     dticon->popup = BuildMenu(dticon->app.form, XmMENU_POPUP, "Button Actions", 0, False, popup_menu);
     if (resources.auto_save)
	 XtVaSetValues(popup_menu[3].object, XmNsensitive, False, NULL);
 }

 labelstr = XmStringCreateLocalized(dticon->app.name);
 labelwidth = XmStringWidth((XmFontList) resources.icon_font, labelstr) + 2;
 togglewidth = dticon->app.icon_pm.width;
 toggleheight = dticon->app.icon_pm.height;
 if (labelwidth > togglewidth)
 {
     tgl_offs_x = (labelwidth - togglewidth) / 2;
     lbl_offs_x = 0;
 }
 else
 {
     tgl_offs_x = 0;
     lbl_offs_x = (togglewidth - labelwidth) / 2;
 }
 lbl_offs_y = dticon->app.icon_pm.height + 2;

 dticon->app.toggle = XtVaCreateManagedWidget("picture", xmLabelWidgetClass, dticon->app.form, XmNlabelType, XmPIXMAP, XmNlabelPixmap, dticon->app.icon_pm.bm, XmNtranslations, trans, XmNborderWidth, 0, XmNhighlightThickness, 0, XmNbackground, resources.dticon_color, XmNforeground, resources.label_color, XmNx, tgl_offs_x, XmNy, 0, NULL);
/*  RBW - 2001/08/15  */
XtInsertEventHandler(dticon->app.toggle,
                     EnterWindowMask|LeaveWindowMask,
                     False,
                     (XtEventHandler)CatchEntryLeave2,
                     (XtPointer)0,
                     XtListHead);

 dticon->app.label = XtVaCreateManagedWidget("label", xmLabelWidgetClass, dticon->app.form, XmNlabelString, labelstr, XmNfontList, resources.icon_font, XmNtranslations, trans, XmNbackground, resources.dticon_color, XmNforeground, resources.label_color, XmNborderWidth, 0, XmNhighlightThickness, 0, XmNx, lbl_offs_x, XmNy, lbl_offs_y, NULL);
/*  RBW - 2001/08/15  */
XtInsertEventHandler(dticon->app.label,
                     EnterWindowMask|LeaveWindowMask,
                     False,
                     (XtEventHandler)CatchEntryLeave2,
                     (XtPointer)0,
                     XtListHead);

 XmStringFree(labelstr);

 XtRealizeWidget(dticon->shell);
 shellwin = XtWindow(dticon->shell);

 XtVaGetValues(dticon->app.label, XmNwidth, &labelwidth, XmNwidth, &labelheight, NULL);
 labelheight += 2;
 dticon->label_mask = XCreatePixmap(dpy, shellwin, labelwidth, labelheight, 1);
 shapeGC = XCreateGC(dpy, dticon->label_mask, 0, &xgcv);
 XSetForeground(dpy, shapeGC, 1);
 XFillRectangle(dpy, dticon->label_mask, shapeGC, 0, 0, labelwidth, labelheight);
 XFreeGC(dpy, shapeGC);
 if (dticon->app.icon_pm.mask == None)
 {
     dticon->app.icon_pm.mask = XCreatePixmap(dpy, shellwin, dticon->app.icon_pm.width, dticon->app.icon_pm.height, 1);
     shapeGC = XCreateGC(dpy, dticon->app.icon_pm.mask, 0, &xgcv);
     XSetForeground(dpy, shapeGC, 1);
     XFillRectangle(dpy, dticon->app.icon_pm.mask, shapeGC, 0, 0, togglewidth, toggleheight);
     XFreeGC(dpy, shapeGC);
 }
 XShapeCombineMask(dpy, shellwin, ShapeBounding, tgl_offs_x + 2, 2, dticon->app.icon_pm.mask, ShapeSet);
 XShapeCombineMask(dpy, shellwin, ShapeBounding, lbl_offs_x + 2, lbl_offs_y + 2, dticon->label_mask, ShapeUnion);
 XShapeCombineMask(dpy, XtWindow(dticon->app.form), ShapeClip, tgl_offs_x + 2, 2, dticon->app.icon_pm.mask, ShapeSet);
 XShapeCombineMask(dpy, XtWindow(dticon->app.form), ShapeClip, lbl_offs_x + 2, lbl_offs_y + 2, dticon->label_mask, ShapeUnion);
 XShapeCombineMask(dpy, XtWindow(dticon->app.toggle), ShapeClip, 2, 2, dticon->app.icon_pm.mask, ShapeSet);

 XtVaGetValues(dticon->shell, XmNwidth, &dticon->width, XmNheight, &dticon->height, NULL);

 dticon->drop_pixmap = XCreatePixmap(dpy, shellwin, dticon->width, dticon->height, DefaultDepth(dpy, DefaultScreen(dpy)));
 shapeGC = XCreateGC(dpy, dticon->drop_pixmap, 0, &xgcv);
 XSetForeground(dpy, shapeGC, resources.drop_color);
 XFillRectangle(dpy, dticon->drop_pixmap, shapeGC, 0, 0, dticon->width, dticon->height);
 XFreeGC(dpy, shapeGC);
 drop_args[4].value = (XtArgVal) dticon->drop_pixmap;

 if (dticon->app.drop_action[0])
     XmDropSiteRegister(dticon->app.form, drop_args, XtNumber(drop_args));

}
Exemplo n.º 9
0
/* Main method runs initialize() and update() */
int main(int argc, char **argv) {
    /* get num bodies from the command line */
    int num_bodies;
    num_bodies = (argc == 2) ? atoi(argv[1]) : DEF_NUM_BODIES;
    printf("Universe has %d bodies.\n", num_bodies);

    /* set up the universe */
    time_t cur_time;
    time(&cur_time);
    srand48((long)cur_time); // seed the RNG used in create_world
    struct world *world = create_world(num_bodies);

    /* set up graphics using Xlib */
    Display *disp = XOpenDisplay(NULL);
    int scr = DefaultScreen(disp);
    Window win = XCreateSimpleWindow(
            disp,
            RootWindow(disp, scr),
            0, 0,
            WIDTH, HEIGHT,
            0,
            BlackPixel(disp, scr), WhitePixel(disp, scr));
    XStoreName(disp, win, "N-Body Simulator");

    Pixmap back_buf = XCreatePixmap(disp, RootWindow(disp, scr),
            WIDTH, HEIGHT, DefaultDepth(disp, scr));
    GC gc = XCreateGC(disp, back_buf, 0, 0);

    // Make sure we're only looking for messages about closing the window
    Atom del_window = XInternAtom(disp, "WM_DELETE_WINDOW", 0);
    XSetWMProtocols(disp, win, &del_window, 1);

    XSelectInput(disp, win, StructureNotifyMask);
    XMapWindow(disp, win);
    XEvent event;
    // wait until window is mapped
    while (1) {
        XNextEvent(disp, &event);
        if (event.type == MapNotify) {
            break;
        }
    }

    struct timespec delay={0, 1000000000 / 60}; // for 60 FPS
    struct timespec remaining;
    int frame_num = 0;
    while (1) {
        // check if the window has been closed
        if (XCheckTypedEvent(disp, ClientMessage, &event)) {
            break;
        }

        // we first draw to the back buffer then copy it to the front (`win`)
        draw_world(disp, back_buf, gc, world);
        XCopyArea(disp, back_buf, win, gc, 0, 0, WIDTH, HEIGHT, 0, 0);

        step_world(world, 0.1);
        frame_num++;
        nanosleep(&delay, &remaining);
    }

    XFreeGC(disp, gc);
    XFreePixmap(disp, back_buf);
    XDestroyWindow(disp, win);
    XCloseDisplay(disp);

    return 0;
}
Exemplo n.º 10
0
Pixmap LoadJpeg(Display *disp, Drawable draw, char *filename, XpmAttributes *xpa)
{
  struct jpeg_decompress_struct dobj;
  struct jerrstruct jerr;
  FILE *jpg_file = NULL;
  Pixmap ret = None;
  XGCValues xgcv;
  GC gc;
  JSAMPROW *rows = NULL;
  XColor col;
  int b;
  unsigned long d;
/* we need these to be static to make sure they won't be affected by longjmp */
  static XImage *image = NULL;
  static JSAMPLE *data = NULL;
  static unsigned long *idata = NULL;
  static int  c = 0;

  if(!(jpg_file = fopen(filename,"rb"))) return(None);
  xpa->pixels = NULL;

  if(setjmp(jerr.jb)) {
/*    printf("\bprocessing of jpeg file %s aborted!\n",filename);*/
    jpeg_destroy_decompress(&dobj);
    if(data)           free(data);
    if(jpg_file)       fclose(jpg_file);
    if(xpa->pixels)  { XFreeColors(disp, xpa->colormap, xpa->pixels, c, 0);
                       free(xpa->pixels);}
    if(idata)          free(idata);
    if(image)        { image->data = NULL;
                       XDestroyImage(image);}
    return(None);
  }

  dobj.err = jpeg_std_error(&jerr.mgr);
  jerr.mgr.error_exit = my_jpeg_error_exit_handler;
  jerr.mgr.emit_message = my_jpeg_error_handler;
  jpeg_create_decompress(&dobj);
  jpeg_stdio_src(&dobj, jpg_file);
  jpeg_read_header(&dobj, TRUE);

  dobj.out_color_space = JCS_RGB;
  dobj.quantize_colors = TRUE;

  jpeg_start_decompress(&dobj);

  xpa->width = dobj.output_width;
  xpa->height = dobj.output_height;
  if(!(xpa->valuemask & XpmVisual))
    xpa->visual = DefaultVisual(disp,DefaultScreen(disp));
  xpa->depth = DefaultDepth(disp,DefaultScreen(disp));
  if(!(xpa->valuemask & XpmColormap))
    xpa->colormap = DefaultColormap(disp,DefaultScreen(disp));
  xpa->pixels = NULL;

  if((!(data = calloc(dobj.output_components * dobj.output_width 
               * dobj.output_height, sizeof(JSAMPLE)))) 
     || (!(rows = calloc(dobj.output_height, sizeof(JSAMPROW))))) {
    longjmp(jerr.jb, 1);
  }

  for(b=0;b<dobj.output_height;b++) rows[b] = data + b * dobj.output_components 
                                              * dobj.output_width * sizeof(JSAMPLE);

  while(dobj.output_scanline < dobj.output_height)
    if(!jpeg_read_scanlines(&dobj, &rows[dobj.output_scanline], dobj.output_height)){
      longjmp(jerr.jb, 1);
    }

  free(rows); rows = NULL;

  xpa->npixels = dobj.actual_number_of_colors;

  if((!(xpa->pixels = calloc(dobj.actual_number_of_colors, sizeof(*(xpa->pixels))))) 
     || (!(idata = calloc(dobj.output_components * dobj.output_width 
                   * dobj.output_height, sizeof(unsigned long))))
     || (!(image = XCreateImage(disp, xpa->visual, xpa->depth, ZPixmap, 0, (char *)idata,
                   dobj.output_width, dobj.output_height, 8 * sizeof(unsigned long),
                   dobj.output_width * dobj.output_components * sizeof(unsigned long))))){
    longjmp(jerr.jb, 1);
  }

#ifdef WORDS_BIGENDIAN
  image->byte_order = MSBFirst;
#else
  image->byte_order = LSBFirst;
#endif
  image->bits_per_pixel = 8 * sizeof(unsigned long);

/*  _XInitImageFuncPtrs(image);  *** Not quite sure if this is needed, works fine ***/
   /*** without it on my system and the function is to be considered private to Xlib ***/

  for(c=0; c < dobj.actual_number_of_colors; c++) {
    col.red = dobj.colormap[0][c] << (8 * sizeof(col.red) - BITS_IN_JSAMPLE);
    col.green = dobj.colormap[1][c] << (8 * sizeof(col.green) - BITS_IN_JSAMPLE);
    col.blue = dobj.colormap[2][c] << (8 * sizeof(col.blue) - BITS_IN_JSAMPLE);
    col.flags = DoRed | DoGreen | DoBlue;
    if(!XAllocColor(disp, xpa->colormap, &col)) {
      longjmp(jerr.jb, 1);
    }
    xpa->pixels[c] = col.pixel;
  }

  for(d=0; d < (dobj.output_components * dobj.output_width * dobj.output_height); d++)
    idata[d] = xpa->pixels[data[d]];
  
  jpeg_finish_decompress(&dobj);
  fclose(jpg_file); jpg_file = NULL;
  jpeg_destroy_decompress(&dobj);
  free(data);

  if(None == (ret = XCreatePixmap(disp, draw, dobj.output_width,
                                  dobj.output_height, image->depth))){
    free(idata);
    XFreeColors(disp, xpa->colormap, xpa->pixels, xpa->npixels, 0);
    free(xpa->pixels);
    XDestroyImage(image);
    return(None);
  }

  xgcv.function = GXcopy;
  gc = XCreateGC(disp, ret, GCFunction, &xgcv);
  XPutImage(disp, ret, gc, image, 0, 0, 0, 0, image->width, image->height);
  XFreeGC(disp, gc);

  free(image->data);                  /*** don't forget: image->date == idata!!! ***/
  image->data = NULL;
  XDestroyImage(image);

  xpa->alloc_pixels = xpa->pixels;
  xpa->nalloc_pixels = xpa->npixels;
  xpa->valuemask = XpmVisual | XpmColormap | XpmDepth | XpmSize | XpmColorTable 
                   | XpmReturnColorTable | XpmReturnAllocPixels;
  return(ret);
}
/*
 * close_window:
 *  returns window resources
 */
void close_window() {
    XFreeGC(display, gc);
    XDestroyWindow(display, window);
    XCloseDisplay(display);
}
Exemplo n.º 12
0
int main(int argc, char **argv)
{
	XGCValues gcv;
	unsigned long gcm;
	int exact,left,right,device_index,i;
	XpmAttributes xpmattr;
	XpmColorSymbol xpmcsym[4];
	elementinfo *e;

	scanArgs(argc, argv);
	initXWin(argc, argv);
	exact=left=right=device_index=-1;

	init_mixer();
	cure=element;
	e=element;
	while(e)
	{
		if(!strcasecmp(e->info.eid.name,"Master Volume"))
			e->icon=0;
		else if(!strcasecmp(e->info.eid.name,"PCM Volume"))
			e->icon=1;
		else if(!strcasecmp(e->info.eid.name,"MIC Volume"))
			e->icon=5;
		else if(!strcasecmp(e->info.eid.name,"Line Volume"))
			e->icon=4;
		else if(!strcasecmp(e->info.eid.name,"CD Volume"))
			e->icon=3;
		else if(!strcasecmp(e->info.eid.name,"Synth Volume"))
			e->icon=2;
		else if(!strcasecmp(e->info.eid.name,"PC Speaker Volume"))
			e->icon=6;
		/*
		 * bass = 7
		 * treble = 8
		 */
		else
			e->icon=9;
		e=e->next;
	}

	gcm=GCGraphicsExposures;
	gcv.graphics_exposures=0;
	gc_gc=XCreateGC(d_display, w_root, gcm, &gcv);

	color[0]=mixColor(ledcolor, 0, backcolor, 100);
	color[1]=mixColor(ledcolor, 100, backcolor, 0);
	color[2]=mixColor(ledcolor, 60, backcolor, 40);
	color[3]=mixColor(ledcolor, 25, backcolor, 75);

	xpmcsym[0].name="back_color";
	xpmcsym[0].value=NULL;;
	xpmcsym[0].pixel=color[0];
	xpmcsym[1].name="led_color_high";
	xpmcsym[1].value=NULL;;
	xpmcsym[1].pixel=color[1];
	xpmcsym[2].name="led_color_med";
	xpmcsym[2].value=NULL;;
	xpmcsym[2].pixel=color[2];
	xpmcsym[3].name="led_color_low";
	xpmcsym[3].value=NULL;;
	xpmcsym[3].pixel=color[3];
	xpmattr.numsymbols=4;
	xpmattr.colorsymbols=xpmcsym;
	xpmattr.exactColors=0;
	xpmattr.closeness=40000;
	xpmattr.valuemask=XpmColorSymbols | XpmExactColors | XpmCloseness;
	XpmCreatePixmapFromData(d_display, w_root, wmmixer_xpm, &pm_main, &pm_mask, &xpmattr);
	XpmCreatePixmapFromData(d_display, w_root, tile_xpm, &pm_tile, NULL, &xpmattr);
	XpmCreatePixmapFromData(d_display, w_root, icons_xpm, &pm_icon, NULL, &xpmattr);
	pm_disp=XCreatePixmap(d_display, w_root, 64, 64, DefaultDepth(d_display, DefaultScreen(d_display)));

	if(wmaker || ushape || astep)
		XShapeCombineMask(d_display, w_activewin, ShapeBounding, winsize/2-32, winsize/2-32, pm_mask, ShapeSet);
	else
		XCopyArea(d_display, pm_tile, pm_disp, gc_gc, 0, 0, 64, 64, 0, 0);

	XSetClipMask(d_display, gc_gc, pm_mask);
	XCopyArea(d_display, pm_main, pm_disp, gc_gc, 0, 0, 64, 64, 0, 0);
	XSetClipMask(d_display, gc_gc, None);

	if(count==0)
		fprintf(stderr,"%s : Sorry, no supported channels found.\n", NAME);
	else
	{
		int done=0;
		XEvent xev;

		checkVol();
		XSelectInput(d_display, w_activewin, ExposureMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask);
		XMapWindow(d_display, w_main);

		while(!done)
		{
			while(XPending(d_display))
			{
				XNextEvent(d_display, &xev);
				switch(xev.type)
				{
					case Expose:
						repaint();
						break;
					case ButtonPress:
						pressEvent(&xev.xbutton);
						break;
					case ButtonRelease:
						releaseEvent(&xev.xbutton);
						break;
					case MotionNotify:
						motionEvent(&xev.xmotion);
						break;
					case ClientMessage:
						if(xev.xclient.data.l[0]==deleteWin)
							done=1;
						break;
				}
			}

			if(btnstate & (BTNPREV | BTNNEXT))
			{
				rpttimer++;
				if(rpttimer>=RPTINTERVAL)
				{
					if(btnstate & BTNNEXT)
					{
						cure=cure->next;
						if(!cure)
							cure=element;
					}
					else
					{
						cure=cure->prev;
						if(!cure)
						{
							elementinfo *e;
							e=element;
							while(e->next)
								e=e->next;
							cure=e;
						}
					}
					checkVol();
					rpttimer=0;
				}
			}
			else
				checkVol();
			XFlush(d_display);
			usleep(50000);
		}
	}
	XFreeGC(d_display, gc_gc);
	XFreePixmap(d_display, pm_main);
	XFreePixmap(d_display, pm_tile);
	XFreePixmap(d_display, pm_disp);
	XFreePixmap(d_display, pm_mask);
	XFreePixmap(d_display, pm_icon);
	freeXWin();
	return 0;
}
Exemplo n.º 13
0
/**********************************************************************
 *           ExtEscape  (X11DRV.@)
 */
static INT X11DRV_ExtEscape( PHYSDEV dev, INT escape, INT in_count, LPCVOID in_data,
                      INT out_count, LPVOID out_data )
{
    X11DRV_PDEVICE *physDev = get_x11drv_dev( dev );

    switch(escape)
    {
    case QUERYESCSUPPORT:
        if (in_data && in_count >= sizeof(DWORD))
        {
            switch (*(const INT *)in_data)
            {
            case X11DRV_ESCAPE:
                return TRUE;
            }
        }
        break;

    case X11DRV_ESCAPE:
        if (in_data && in_count >= sizeof(enum x11drv_escape_codes))
        {
            switch(*(const enum x11drv_escape_codes *)in_data)
            {
            case X11DRV_SET_DRAWABLE:
                if (in_count >= sizeof(struct x11drv_escape_set_drawable))
                {
                    const struct x11drv_escape_set_drawable *data = in_data;
                    physDev->dc_rect = data->dc_rect;
                    physDev->drawable = data->drawable;
                    XFreeGC( gdi_display, physDev->gc );
                    physDev->gc = XCreateGC( gdi_display, physDev->drawable, 0, NULL );
                    XSetGraphicsExposures( gdi_display, physDev->gc, False );
                    XSetSubwindowMode( gdi_display, physDev->gc, data->mode );
                    TRACE( "SET_DRAWABLE hdc %p drawable %lx dc_rect %s\n",
                           dev->hdc, physDev->drawable, wine_dbgstr_rect(&physDev->dc_rect) );
                    return TRUE;
                }
                break;
            case X11DRV_GET_DRAWABLE:
                if (out_count >= sizeof(struct x11drv_escape_get_drawable))
                {
                    struct x11drv_escape_get_drawable *data = out_data;
                    data->drawable = physDev->drawable;
                    return TRUE;
                }
                break;
            case X11DRV_FLUSH_GL_DRAWABLE:
                if (in_count >= sizeof(struct x11drv_escape_flush_gl_drawable))
                {
                    const struct x11drv_escape_flush_gl_drawable *data = in_data;
                    RECT rect = physDev->dc_rect;

                    OffsetRect( &rect, -physDev->dc_rect.left, -physDev->dc_rect.top );
                    /* The GL drawable may be lagged behind if we don't flush first, so
                     * flush the display make sure we copy up-to-date data */
                    XFlush( gdi_display );
                    XSetFunction( gdi_display, physDev->gc, GXcopy );
                    XCopyArea( gdi_display, data->gl_drawable, physDev->drawable, physDev->gc,
                               0, 0, rect.right, rect.bottom,
                               physDev->dc_rect.left, physDev->dc_rect.top );
                    add_device_bounds( physDev, &rect );
                    return TRUE;
                }
                break;
            case X11DRV_START_EXPOSURES:
                XSetGraphicsExposures( gdi_display, physDev->gc, True );
                physDev->exposures = 0;
                return TRUE;
            case X11DRV_END_EXPOSURES:
                if (out_count >= sizeof(HRGN))
                {
                    HRGN hrgn = 0, tmp = 0;

                    XSetGraphicsExposures( gdi_display, physDev->gc, False );
                    if (physDev->exposures)
                    {
                        for (;;)
                        {
                            XEvent event;

                            XWindowEvent( gdi_display, physDev->drawable, ~0, &event );
                            if (event.type == NoExpose) break;
                            if (event.type == GraphicsExpose)
                            {
                                RECT rect;

                                rect.left   = event.xgraphicsexpose.x - physDev->dc_rect.left;
                                rect.top    = event.xgraphicsexpose.y - physDev->dc_rect.top;
                                rect.right  = rect.left + event.xgraphicsexpose.width;
                                rect.bottom = rect.top + event.xgraphicsexpose.height;
                                if (GetLayout( dev->hdc ) & LAYOUT_RTL)
                                    mirror_rect( &physDev->dc_rect, &rect );

                                TRACE( "got %s count %d\n", wine_dbgstr_rect(&rect),
                                       event.xgraphicsexpose.count );

                                if (!tmp) tmp = CreateRectRgnIndirect( &rect );
                                else SetRectRgn( tmp, rect.left, rect.top, rect.right, rect.bottom );
                                if (hrgn) CombineRgn( hrgn, hrgn, tmp, RGN_OR );
                                else
                                {
                                    hrgn = tmp;
                                    tmp = 0;
                                }
                                if (!event.xgraphicsexpose.count) break;
                            }
                            else
                            {
                                ERR( "got unexpected event %d\n", event.type );
                                break;
                            }
                        }
                        if (tmp) DeleteObject( tmp );
                    }
                    *(HRGN *)out_data = hrgn;
                    return TRUE;
                }
                break;
            default:
                break;
            }
        }
        break;
    }
    return 0;
}
Exemplo n.º 14
0
Arquivo: TextField.c Projeto: att/uwin
void DestroyTextField(struct XObj *xobj)
{
 XFreeFont(dpy,xobj->xfont);
 XFreeGC(dpy,xobj->gc);
 XDestroyWindow(dpy,xobj->win);
}
Exemplo n.º 15
0
void draw( Display *dsp, Drawable *win )
{
  GC gc = XCreateGC(dsp, *win, 0, NULL);     
  char Buf[100] = { 0 }, Buf1[100] = { 0 }, Buf2[100] = { 0 }, Buf3[100] = { 0 }, Buf4[100] = { 0 };

  XSetForeground(dsp, gc, black);
  XFillRectangle(dsp, *win, gc, 0, 0, 600, 800);

  XTextItem titem_time[] = { Buf, strlen(Buf), -3, None },
	    titem_bufx[] = { Buf1, strlen(Buf1), -3, None },
            titem_bufy[] = { Buf2, strlen(Buf2), -3, None },
	    titem_bufp[] = { Buf3, strlen(Buf3), -3, None },
	    titem_bufr[] = { Buf4, strlen(Buf4), -3, None };

  XSetBackground(dsp, gc, black);
  XSetForeground(dsp, gc, white);

  XImage *img = XGetImage(dsp, *win, 0, 100, img_width, img_height, AllPlanes, ZPixmap);

  /* The main part */
  drawing_time = getTime(); 
  fillbuf(img->data, img_width, img_height, img->bytes_per_line);
  drawing_time = getTime() - drawing_time;
  /*****************/

  XPutImage(dsp, *win, gc, img, 0, 0, 0, 100, 600, 600);

  sprintf(titem_time[0].chars, "Time: %llu\0", drawing_time);
  titem_time[0].nchars = strlen(titem_time[0].chars);


  switch (cur_renderer)
  {
  case C_RENDERER:
    sprintf(titem_bufr[0].chars, "Render type: C ");	  
    break;
  case ASM1_RENDERER:
    sprintf(titem_bufr[0].chars, "Render type: simple asm ");	  
    break;
  case ASM2_RENDERER:
    sprintf(titem_bufr[0].chars, "Render type: asm modified (2) ");	  
    break;
  }

  titem_bufr[0].nchars = strlen(titem_bufr[0].chars);

  sprintf(titem_bufx[0].chars, "X modifier: %i\0", x_modif);
  titem_bufx[0].nchars = strlen(titem_bufx[0].chars);
  
  sprintf(titem_bufy[0].chars, "Y modifier: %i\0", y_modif);
  titem_bufy[0].nchars = strlen(titem_bufy[0].chars);
  
  sprintf(titem_bufp[0].chars, "Number of points: %i\0", points_number);
  titem_bufp[0].nchars = strlen(titem_bufp[0].chars);

  XDrawText(dsp, *win, gc, 10, 30, titem_time, 1);
  XDrawText(dsp, *win, gc, 10, 50, titem_bufr, 1); 
  XDrawText(dsp, *win, gc, 450, 40, titem_bufx, 1);
  XDrawText(dsp, *win, gc, 450, 60, titem_bufy, 1);
  XDrawText(dsp, *win, gc, 450, 80, titem_bufp, 1);

  XFreeGC(dsp, gc);
}
Exemplo n.º 16
0
X11Graphics::~X11Graphics()
{
    XFreeGC( XDISPLAY, m_gc );
    XDestroyRegion( m_mask );
    XFreePixmap( XDISPLAY, m_pixmap );
}
Exemplo n.º 17
0
Arquivo: pixmap.c Projeto: mcgrew/lxvt
/* EXTPROTO */
void
rxvt_resize_pixmap(rxvt_t *r, int page)
{
    XGCValues	    gcvalue;
    GC		    gc;
    unsigned int    width = VT_WIDTH(r);
    unsigned int    height = VT_HEIGHT(r);

    if (IS_PIXMAP(PVTS(r, page)->pixmap))
	XFreePixmap(r->Xdisplay, PVTS(r, page)->pixmap);

    if (NOT_PIXMAP(PVTS(r, page)->bg.pixmap))
	/* So be it: I'm not using pixmaps */
	return;

    gcvalue.foreground = r->pixColorsFocus[Color_bg];
    gc = XCreateGC(r->Xdisplay, PVTS(r, page)->vt, GCForeground, &gcvalue);

    if (IS_GC(gc) && IS_PIXMAP(PVTS(r, page)->bg.pixmap)) {
	/* we have a specified pixmap */
	unsigned int	w = PVTS(r, page)->bg.w;
	unsigned int	h = PVTS(r, page)->bg.h;
	unsigned int	x = PVTS(r, page)->bg.x;
	unsigned int	y = PVTS(r, page)->bg.y;
	unsigned int	xpmh = PVTS(r, page)->xpm_attr.height;
	unsigned int	xpmw = PVTS(r, page)->xpm_attr.width;
	unsigned int	pixmapw, pixmaph;

	/*
	 * don't zoom pixmap too much nor expand really small pixmaps
	 */
	if (w > 1000 || h > 1000)
	    w = 1;
	else if (width > (10 * xpmw)
	     || height > (10 * xpmh))
	    w = 0;	/* tile */

	if (w == 0) {
	    /* basic X tiling - let the X server do it */
	    PVTS(r, page)->pixmap = XCreatePixmap(r->Xdisplay,
		PVTS(r, page)->vt, xpmw, xpmh, (unsigned int)XDEPTH);
	    XCopyArea(r->Xdisplay, PVTS(r, page)->bg.pixmap,
		PVTS(r, page)->pixmap, gc, 0, 0, xpmw, xpmh, 0, 0);

	    pixmapw = xpmw;
	    pixmaph = xpmh;
	}
	else {
	    float	  incr, p;
	    Pixmap	  tmp;

	    PVTS(r, page)->pixmap = XCreatePixmap(r->Xdisplay,
		PVTS(r, page)->vt, width, height, (unsigned int)XDEPTH);

	    /* horizontal scaling */
	    rxvt_pixmap_incr(&w, &x, &incr, &p, width, xpmw);

	    tmp = XCreatePixmap(r->Xdisplay, PVTS(r, page)->vt,
		    width, xpmh, (unsigned int)XDEPTH);
	    XFillRectangle(r->Xdisplay, tmp, gc, 0, 0, width,
		   xpmh);

	    for ( /*nil */ ; x < w; x++, p += incr) {
		if (p >= xpmw)
		    p = 0;
		/* copy one column from the original pixmap to the
		** tmp pixmap */
		XCopyArea(r->Xdisplay, PVTS(r, page)->bg.pixmap, tmp,
		    gc, (int)p, 0, 1, xpmh, (int)x, 0);
	    }

	    /* vertical scaling */
	    rxvt_pixmap_incr(&h, &y, &incr, &p, height, xpmh);

	    if (y > 0)
		XFillRectangle(r->Xdisplay, PVTS(r, page)->pixmap, gc,
		    0, 0, width, y);
	    if (h < height)
		XFillRectangle(r->Xdisplay, PVTS(r, page)->pixmap, gc,
		    0, (int)h, width, height - h + 1);
	    for ( /*nil */ ; y < h; y++, p += incr) {
		if (p >= xpmh)
		    p = 0;
		/* copy one row from the tmp pixmap to the main
		** pixmap */
		XCopyArea(r->Xdisplay, tmp, PVTS(r, page)->pixmap, gc,
		    0, (int)p, width, 1, 0, (int)y);
	    }
	    XFreePixmap(r->Xdisplay, tmp);

	    pixmapw = width;
	    pixmaph = height;
	}

#ifdef TINTING_SUPPORT
# ifdef HAVE_LIBXRENDER
	xrenderShadeParentPixmap( r, PVTS(r, page)->pixmap,
		0, 0, pixmapw, pixmaph, False);
# else
	rxvt_shade_pixmap( r, PVTS(r, page)->pixmap,
		0, 0, pixmapw, pixmaph);
# endif
#endif	/* TINTING_SUPPORT */

	/* Free gc */
	XFreeGC(r->Xdisplay, gc);
    }

    XSetWindowBackgroundPixmap(r->Xdisplay, PVTS(r, page)->vt,
	PVTS(r, page)->pixmap);
# ifdef TRANSPARENT
    r->h->am_transparent = 0;
    r->h->am_pixmap_trans = 0;
# endif

    XClearWindow(r->Xdisplay, PVTS(r, page)->vt);

    XSync(r->Xdisplay, False);
}
Exemplo n.º 18
0
Arquivo: x.c Projeto: Limsik/e17
void
EXFreeGC(GC gc)
{
   if (gc)
      XFreeGC(disp, gc);
}
Exemplo n.º 19
0
void
window_loop()
{
    XSetWindowAttributes	win_attrib;
    unsigned long		win_mask;
    //XSizeHints		win_hints;
    XEvent			event;
    int			running = 1;

    win_attrib.border_pixel      = BlackPixel(disp, screen);
    win_attrib.background_pixel  = BlackPixel(disp, screen);
    win_attrib.override_redirect = 0;
    win_mask		     = CWBackPixel | CWBorderPixel;

    window			     = XCreateWindow(disp,
                                         DefaultRootWindow(disp),
                                         0, 0, gwidth, gheight,
                                         0, depth,
                                         InputOutput,
                                         CopyFromParent,
                                         win_mask,
                                         &win_attrib);

    xim = XCreateImage(disp, CopyFromParent, depth, ZPixmap, 0,
                       (char *)gbuf, gwidth, gheight, 32, gwidth * 4);

    gc  = XCreateGC(disp, window, 0, 0);

    XMapWindow(disp, window);
    XChangeProperty(disp, window, WM_PROTOCOLS, XA_ATOM, 32, 0,
                    (unsigned char *)&WM_DELETE_WINDOW, 1);
    XSelectInput(disp, window, ExposureMask | StructureNotifyMask);

    gactive = 1;

    while (running) {
        XNextEvent(disp, &event);
        switch (event.type) {
        case Expose:
            XPutImage(disp, window, gc, xim,
                      0, 0, 0, 0,
                      gwidth, gheight);
            XFlush(disp);

            break;

        case KeyPress:
            if (XLookupKeysym(&event.xkey, 0)
                    == XK_Escape) {
                running = 0;
            }

            break;

        case DestroyNotify:
            running = 0;
            break;

        case ClientMessage:
            if ((Atom)(event.xclient.data.l[0])
                    == WM_DELETE_WINDOW) {
                running = 0;
            }

            break;
        }
    }

    XUnmapWindow(disp, window);
    XFreeGC(disp, gc);

    /* Note that XDestroyImage() frees image data set by XCreateImage(). */
    XDestroyImage(xim);
    XDestroyWindow(disp, window);
    XCloseDisplay(disp);
}
Exemplo n.º 20
0
void X11EmbedContainer::setBackgroundPixmap(QPixmap background)
{
    if (!clientWinId()) {
        return;
    }

    Display *display = QX11Info::display();
    Pixmap bg = XCreatePixmap(display, clientWinId(), width(), height(), d->attr.depth);

    XRenderPictFormat *format = XRenderFindVisualFormat(display, d->attr.visual);
    Picture picture = XRenderCreatePicture(display, bg, format, 0, 0);

    //Prevent updating the background-image if possible. Updating can cause a very annoying flicker due to the XClearArea, and thus has to be kept to a minimum
    QImage image;
    if (background.paintEngine()->type() != QPaintEngine::X11)
      image = background.toImage(); // With the raster graphics system this call just returns the backing image, so the image data isn't copied.
    else
      image = background.copy().toImage(); //With the X11 graphics engine, we have to create a copy first, else we get a crash

    if(d->oldBackgroundImage == image) {
      XFreePixmap(display, bg);
      XRenderFreePicture(display, picture);
      return;
    }
    d->oldBackgroundImage = image;

    if (background.paintEngine()->type() != QPaintEngine::X11) {

        XRenderPictFormat *format = 0;
        int depth = 0;
        int bpp = 0;

        if (image.format() == QImage::Format_ARGB32_Premultiplied) {
            format = XRenderFindStandardFormat(display, PictStandardARGB32);
            depth = 32;
            bpp = 32;
        } else if (image.format() == QImage::Format_RGB32) {
            format = XRenderFindStandardFormat(display, PictStandardRGB24);
            depth = 24;
            bpp = 32;
        } else if (image.format() == QImage::Format_RGB16) {
            bpp = 16;
            depth = 16;

            // Try to find a picture format that matches the image format.
            // The Render spec doesn't require the X server to support 16bpp formats,
            // so this call can fail.
            XRenderPictFormat templ;
            templ.type             = PictTypeDirect;
            templ.direct.alpha     = 0;
            templ.direct.alphaMask = 0;
            templ.depth            = 16;
            templ.direct.red       = 11;
            templ.direct.redMask   = 0x1f;
            templ.direct.green     = 5;
            templ.direct.greenMask = 0x3f;
            templ.direct.blue      = 0;
            templ.direct.blueMask  = 0x1f;
            format = XRenderFindFormat(display, PictFormatType | PictFormatDepth | PictFormatAlpha |
                                       PictFormatAlphaMask | PictFormatRed | PictFormatRedMask |
                                       PictFormatGreen | PictFormatGreenMask | PictFormatBlue |
                                       PictFormatBlueMask, &templ, 0);
        }

        if (format == 0)
        {
            // Convert the image to a standard format.
            if (image.hasAlphaChannel()) {
                image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
                format = XRenderFindStandardFormat(display, PictStandardARGB32);
                depth = 32;
            } else { 
                image = image.convertToFormat(QImage::Format_RGB32);
                format = XRenderFindStandardFormat(display, PictStandardRGB24);
                depth = 24;
            }
            bpp = 32;
        }

        if (image.format() == QImage::Format_RGB32) {
            // Make sure the would be alpha bits are set to 1.
            quint32 * const pixels = (quint32*)(const_cast<const QImage*>(&image)->bits());
            for (int i = 0; i < image.width() * image.height(); i++) {
                pixels[i] |= 0xff000000;
            }
        }

        Q_ASSERT(format != 0);

        // Get the image data into a pixmap
        XImage ximage;
        ximage.width            = image.width(); 
        ximage.height           = image.height();
        ximage.xoffset          = 0; 
        ximage.format           = ZPixmap;
        // This is a hack to prevent the image data from detaching
        ximage.data             = (char*) const_cast<const QImage*>(&image)->bits();
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
        ximage.byte_order       = MSBFirst;
#else
        ximage.byte_order       = LSBFirst;
#endif
        ximage.bitmap_unit      = bpp;
        ximage.bitmap_bit_order = ximage.byte_order;
        ximage.bitmap_pad       = bpp;
        ximage.depth            = depth;
        ximage.bytes_per_line   = image.bytesPerLine();
        ximage.bits_per_pixel   = bpp;
        if (depth > 16) {
            ximage.red_mask     = 0x00ff0000;
            ximage.green_mask   = 0x0000ff00;
            ximage.blue_mask    = 0x000000ff;
        } else {
            // r5g6b5
            ximage.red_mask     = 0xf800;
            ximage.green_mask   = 0x07e0;
            ximage.blue_mask    = 0x001f;
        }
        ximage.obdata           = 0;
        if (XInitImage(&ximage) == 0) {
            XRenderFreePicture(display, picture);
            XFreePixmap(display, bg);
            return;
        }

        Pixmap pm = XCreatePixmap(display, clientWinId(), width(), height(), ximage.depth);
        GC gc = XCreateGC(display, pm, 0, 0);
        XPutImage(display, pm, gc, &ximage, 0, 0, 0, 0, width(), height());
        XFreeGC(display, gc);

        Picture pict = XRenderCreatePicture(display, pm, format, 0, 0);
        XRenderComposite(display, PictOpSrc, pict, None, picture,
                         0, 0, 0, 0, 0, 0, width(), height());
        XRenderFreePicture(display, pict);
        XFreePixmap(display, pm);
    } else {
        XRenderComposite(display, PictOpSrc, background.x11PictureHandle(),
                         None, picture, 0, 0, 0, 0, 0, 0, width(), height());
    }

    XSetWindowBackgroundPixmap(display, clientWinId(), bg);

    XRenderFreePicture(display, picture);
    XFreePixmap(display, bg);

    XClearArea(display, clientWinId(), 0, 0, 0, 0, True);
}
void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset)
{
    Q_D(QRasterWindowSurface);

    // Not ready for painting yet, bail out. This can happen in
    // QWidget::create_sys()
    if (!d->image || rgn.rectCount() == 0)
        return;

#ifdef Q_WS_WIN
    QRect br = rgn.boundingRect();

#ifndef Q_WS_WINCE
    if (!qt_widget_private(window())->isOpaque
        && window()->testAttribute(Qt::WA_TranslucentBackground)
        && (qt_widget_private(window())->data.window_flags & Qt::FramelessWindowHint))
    {
        QRect r = window()->frameGeometry();
        QPoint frameOffset = qt_widget_private(window())->frameStrut().topLeft();
        QRect dirtyRect = br.translated(offset + frameOffset);

        SIZE size = {r.width(), r.height()};
        POINT ptDst = {r.x(), r.y()};
        POINT ptSrc = {0, 0};
        BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * window()->windowOpacity()), Q_AC_SRC_ALPHA};
        RECT dirty = {dirtyRect.x(), dirtyRect.y(),
            dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()};
        Q_UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, d->image->hdc, &ptSrc, 0, &blend, Q_ULW_ALPHA, &dirty};
        ptrUpdateLayeredWindowIndirect(window()->internalWinId(), &info);
    } else
#endif
    {
        QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft();

        HDC widget_dc = widget->getDC();

        QRect wbr = br.translated(-wOffset);
        BitBlt(widget_dc, wbr.x(), wbr.y(), wbr.width(), wbr.height(),
               d->image->hdc, br.x() + offset.x(), br.y() + offset.y(), SRCCOPY);
        widget->releaseDC(widget_dc);
    }

#ifndef QT_NO_DEBUG
    static bool flush = !qgetenv("QT_FLUSH_WINDOWSURFACE").isEmpty();
    if (flush) {
        SelectObject(qt_win_display_dc(), GetStockObject(BLACK_BRUSH));
        Rectangle(qt_win_display_dc(), 0, 0, d->image->width() + 2, d->image->height() + 2);
        BitBlt(qt_win_display_dc(), 1, 1, d->image->width(), d->image->height(),
               d->image->hdc, 0, 0, SRCCOPY);
    }
#endif

#endif

#ifdef Q_WS_X11
    extern void *qt_getClipRects(const QRegion &r, int &num); // in qpaintengine_x11.cpp
    extern QWidgetData* qt_widget_data(QWidget *);
    QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft();

    if (widget->window() != window()) {
        XFreeGC(X11->display, d_ptr->gc);
        d_ptr->gc = XCreateGC(X11->display, widget->handle(), 0, 0);
    }

    QRegion wrgn(rgn);
    if (!wOffset.isNull())
        wrgn.translate(-wOffset);
    QRect wbr = wrgn.boundingRect();

    if (wrgn.rectCount() != 1) {
        int num;
        XRectangle *rects = (XRectangle *)qt_getClipRects(wrgn, num);
        XSetClipRectangles(X11->display, d_ptr->gc, 0, 0, rects, num, YXBanded);
    }

    QRect br = rgn.boundingRect().translated(offset);
#ifndef QT_NO_MITSHM
    if (d_ptr->image->xshmpm) {
        XCopyArea(X11->display, d_ptr->image->xshmpm, widget->handle(), d_ptr->gc,
                  br.x(), br.y(), br.width(), br.height(), wbr.x(), wbr.y());
        XSync(X11->display, False);
    } else if (d_ptr->image->xshmimg) {
        const QImage &src = d->image->image;
        br = br.intersected(src.rect());
        XShmPutImage(X11->display, widget->handle(), d_ptr->gc, d_ptr->image->xshmimg,
                     br.x(), br.y(), wbr.x(), wbr.y(), br.width(), br.height(), False);
        XSync(X11->display, False);
    } else
#endif
    {
        const QImage &src = d->image->image;
        br = br.intersected(src.rect());
        if (src.format() != QImage::Format_RGB32 || widget->x11Info().depth() < 24) {
            Q_ASSERT(src.depth() >= 16);
            const QImage sub_src(src.scanLine(br.y()) + br.x() * (uint(src.depth()) / 8),
                                 br.width(), br.height(), src.bytesPerLine(), src.format());
            QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType);
            data->xinfo = widget->x11Info();
            data->fromImage(sub_src, Qt::NoOpaqueDetection);
            QPixmap pm = QPixmap(data);
            XCopyArea(X11->display, pm.handle(), widget->handle(), d_ptr->gc, 0 , 0 , br.width(), br.height(), wbr.x(), wbr.y());
        } else {
            // qpaintengine_x11.cpp
            extern void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const QImage &image, Drawable hd, GC gc, Display *dpy, Visual *visual, int depth);
            qt_x11_drawImage(br, wbr.topLeft(), src, widget->handle(), d_ptr->gc, X11->display, (Visual *)widget->x11Info().visual(), widget->x11Info().depth());
        }
    }

    if (wrgn.rectCount() != 1)
        XSetClipMask(X11->display, d_ptr->gc, XNone);
#endif // FALCON

#ifdef Q_WS_MAC

//     qDebug() << "Flushing" << widget << rgn << offset;

//     d->image->image.save("flush.png");

    Q_UNUSED(offset);
    // Get a context for the widget.
#ifndef QT_MAC_USE_COCOA
    CGContextRef context;
    CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
    QDBeginCGContext(port, &context);
#else
    extern CGContextRef qt_mac_graphicsContextFor(QWidget *);
    CGContextRef context = qt_mac_graphicsContextFor(widget);
#endif
    CGContextSaveGState(context);

    // Flip context.
    CGContextTranslateCTM(context, 0, widget->height());
    CGContextScaleCTM(context, 1, -1);

    // Clip to region.
    const QVector<QRect> &rects = rgn.rects();
    for (int i = 0; i < rects.size(); ++i) {
        const QRect &rect = rects.at(i);
        CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()));
    }
    CGContextClip(context);

    QRect r = rgn.boundingRect();
    const CGRect area = CGRectMake(r.x(), r.y(), r.width(), r.height());
    CGImageRef image = CGBitmapContextCreateImage(d->image->cg);
    CGImageRef subImage = CGImageCreateWithImageInRect(image, area);

    qt_mac_drawCGImage(context, &area, subImage);
    CGImageRelease(subImage);
    CGImageRelease(image);

//     CGSize size = { d->image->image.width(), d->image->image.height() };
//     CGLayerRef layer = CGLayerCreateWithContext(d->image->cg, size, 0);
//     CGPoint pt = { 0, 0 };
//     CGContextDrawLayerAtPoint(context, pt, layer);
//     CGLayerRelease(layer);

    // Restore context.
    CGContextRestoreGState(context);
#ifndef QT_MAC_USE_COCOA
    QDEndCGContext(port, &context);
#endif
#endif // Q_WS_MAC

#ifdef Q_OS_SYMBIAN
    Q_UNUSED(widget);
    Q_UNUSED(rgn);
    Q_UNUSED(offset);
#endif
}
Exemplo n.º 22
0
Bool
dfb_x11_open_window( DFBX11 *x11, XWindow** ppXW, int iXPos, int iYPos, int iWidth, int iHeight, DFBSurfacePixelFormat format )
{
     XWindow              *xw;
     XSetWindowAttributes  attr = { .background_pixmap = 0 };
     void                 *old_error_handler = 0;
     unsigned int          cw_mask = CWEventMask;

     D_DEBUG_AT( X11_Window, "Creating %4dx%4d %s window...\n", iWidth, iHeight, dfb_pixelformat_name(format) );

     xw = D_CALLOC( 1, sizeof(XWindow) );
     if (!xw)
          return D_OOM();

     /* We set the structure as needed for our window */
     xw->width   = iWidth;
     xw->height  = iHeight;
     xw->display = x11->display;

     xw->screenptr = DefaultScreenOfDisplay(xw->display);
     xw->screennum = DefaultScreen(xw->display);
     xw->depth     = DefaultDepthOfScreen(xw->screenptr);
     xw->visual    = DefaultVisualOfScreen(xw->screenptr);

     attr.event_mask =
            ButtonPressMask
          | ButtonReleaseMask
          | PointerMotionMask
          | KeyPressMask
          | KeyReleaseMask
          | ExposureMask
          | StructureNotifyMask;

     if (dfb_config->x11_borderless) {
          attr.override_redirect = True;

          cw_mask |= CWOverrideRedirect;
     }

     XLockDisplay( x11->display );

     old_error_handler = XSetErrorHandler( error_handler );

     error_code = 0;

     xw->window = XCreateWindow( xw->display,
                                 RootWindowOfScreen(xw->screenptr),
                                 iXPos, iYPos, iWidth, iHeight, 0, xw->depth, InputOutput,
                                 xw->visual, cw_mask, &attr );
     XSync( xw->display, False );
     if (!xw->window || error_code) {
          D_FREE( xw );
          XUnlockDisplay( x11->display );
          return False;
     }


     XSizeHints Hints;

     /*
      * Here we inform the function of what we are going to change for the
      * window (there's also PPosition but it's obsolete)
      */
     Hints.flags    =    PSize | PMinSize | PMaxSize;

     /*
      * Now we set the structure to the values we need for width & height.
      * For esthetic reasons we set Width=MinWidth=MaxWidth.
      * The same goes for Height. You can try whith differents values, or
      * let's use Hints.flags=Psize; and resize your window..
      */
     Hints.min_width          =    Hints.max_width          =    Hints.base_width    =    xw->width;
     Hints.min_height    =    Hints.max_height    =    Hints.base_height   =    xw->height;

     /* Now we can set the size hints for the specified window */
     XSetWMNormalHints(xw->display,xw->window,&Hints);

     /* We change the title of the window (default:Untitled) */
     XStoreName(xw->display,xw->window,"DFB X11 system window");

     xw->gc = XCreateGC(xw->display, xw->window, 0, NULL);

#if 0
     // Create a null cursor
     Pixmap  pixmp1;
     Pixmap  pixmp2;
     XColor  fore;
     XColor  back;
     char    zero = 0;

     pixmp1 = XCreateBitmapFromData( xw->display, xw->window, &zero, 1, 1 );
     pixmp2 = XCreateBitmapFromData( xw->display, xw->window, &zero, 1, 1 );

     xw->NullCursor = XCreatePixmapCursor( xw->display, pixmp1, pixmp2, &fore, &back, 0, 0 );

     XFreePixmap ( xw->display, pixmp1 );
     XFreePixmap ( xw->display, pixmp2 );

     XDefineCursor( xw->display, xw->window, xw->NullCursor );
#endif

     /* maps the window and raises it to the top of the stack */
     XMapRaised( xw->display, xw->window );


     if (x11->use_shm) {
          // Shared memory
          xw->shmseginfo=(XShmSegmentInfo *)D_CALLOC(1, sizeof(XShmSegmentInfo));
          if (!xw->shmseginfo) {
               x11->use_shm = false;
               goto no_shm;
          }

          xw->ximage=XShmCreateImage(xw->display, xw->visual, xw->depth, ZPixmap,
                                     NULL,xw->shmseginfo, xw->width, xw->height * 2);
          XSync( xw->display, False );
          if (!xw->ximage || error_code) {
               D_ERROR("X11: Error creating shared image (XShmCreateImage) \n");
               x11->use_shm = false;
               D_FREE(xw->shmseginfo);
               error_code = 0;
               goto no_shm;
          }

          xw->bpp = (xw->ximage->bits_per_pixel + 7) / 8;

          /* we firstly create our shared memory segment with the size we need, and
          correct permissions for the owner, the group and the world --> 0777 */
          xw->shmseginfo->shmid=shmget(IPC_PRIVATE,
                                       xw->ximage->bytes_per_line * xw->ximage->height * 2,
                                       IPC_CREAT|0777);

          if (xw->shmseginfo->shmid<0) {
               x11->use_shm = false;
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
               goto no_shm;
          }

          /* Then, we have to attach the segment to our process, and we let the
          function search the correct memory place --> NULL. It's safest ! */
          xw->shmseginfo->shmaddr = shmat( xw->shmseginfo->shmid, NULL, 0 );
          if (!xw->shmseginfo->shmaddr) {
               x11->use_shm = false;
               shmctl(xw->shmseginfo->shmid,IPC_RMID,NULL);
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
               goto no_shm;
          }

          /* We set the buffer in Read and Write mode */
          xw->shmseginfo->readOnly=False;

          xw->virtualscreen= xw->ximage->data = xw->shmseginfo->shmaddr;


          XSetErrorHandler( error_handler_shm );

          XShmAttach(x11->display,xw->shmseginfo);

          XShmPutImage(x11->display, xw->window, xw->gc, xw->ximage,
                       0, 0, 0, 0, 1, 1, False);

          XSync(x11->display, False);

          XSetErrorHandler( error_handler );

          if (!x11->use_shm) {
               shmdt(xw->shmseginfo->shmaddr);
               shmctl(xw->shmseginfo->shmid,IPC_RMID,NULL);
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
          }
     }

no_shm:
     if (!x11->use_shm) {
          int pitch;

          xw->bpp = (xw->depth > 16) ? 4 :
                    (xw->depth >  8) ? 2 : 1;

          pitch = (xw->bpp * xw->width + 3) & ~3;

          /* Use malloc(), not D_MALLOC() here, because XCreateImage()
           * will call free() on this data.
           */
          xw->virtualscreen = malloc ( 2 * xw->height * pitch );

          xw->ximage = XCreateImage( xw->display, xw->visual, xw->depth, ZPixmap, 0,
                                     xw->virtualscreen, xw->width, xw->height * 2, 32, pitch );
          XSync( xw->display, False );
          if (!xw->ximage || error_code) {
               D_ERROR( "X11/Window: XCreateImage( Visual %02lu, depth %d, size %dx%d, buffer %p [%d] ) failed!\n",
                        xw->visual->visualid, xw->depth, xw->width, xw->height * 2, xw->virtualscreen, pitch );
               XFreeGC(xw->display,xw->gc);
               XDestroyWindow(xw->display,xw->window);
               XSetErrorHandler( old_error_handler );
               XUnlockDisplay( x11->display );
               D_FREE( xw );
               return False;
          }
     }

     XSetErrorHandler( old_error_handler );

     XUnlockDisplay( x11->display );

     D_INFO( "X11/Display: %ssing XShm.\n", x11->use_shm ? "U" : "Not u" );

     (*ppXW) = xw;

     return True;
}

void
dfb_x11_close_window( DFBX11 *x11, XWindow* xw )
{
     if (x11->use_shm) {
          XShmDetach( xw->display, xw->shmseginfo );
          shmdt( xw->shmseginfo->shmaddr );
          shmctl( xw->shmseginfo->shmid, IPC_RMID, NULL );
          D_FREE( xw->shmseginfo );
     }

     XDestroyImage( xw->ximage );

     XFreeGC( xw->display, xw->gc );
     XDestroyWindow( xw->display, xw->window );
#if 0
     XFreeCursor( xw->display, xw->NullCursor );
#endif

     D_FREE( xw );
}
Exemplo n.º 23
0
void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {

	last_button_state=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=0L;
	} else {
		::XIMStyles *xim_styles=NULL;
		xim_style=0L;
		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 = 0L;
			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);
		}
		XFree( imvalret );
	}

	/*
	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();

	rasterizer = memnew( RasterizerGLES2 );

#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));
	}

#if 1
	// NEW_WM_API
	// 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 resizable 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);
		XFree(xsh);
	}
#else
	capture_idle = 0;
	minimized = false;
	maximized = false;

	if (current_videomode.fullscreen) {
		//set_wm_border(false);
		set_wm_fullscreen(true);
	}
	if (!current_videomode.resizable) {
		int screen = get_current_screen();
		Size2i screen_size = get_screen_size(screen);
		set_window_size(screen_size);
		set_window_resizable(false);
	}
#endif

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

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

		bool success=false;
		audio_driver_index=-1;
		for(int i=0;i<AudioDriverManagerSW::get_driver_count();i++) {
			if (i==p_audio_driver)
				continue;
			AudioDriverManagerSW::get_driver(i)->set_singleton();
			if (AudioDriverManagerSW::get_driver(i)->init()==OK) {
				success=true;
				print_line("Audio Driver Failed: "+String(AudioDriverManagerSW::get_driver(p_audio_driver)->get_name()));
				print_line("Using alternate audio driver: "+String(AudioDriverManagerSW::get_driver(i)->get_name()));
				audio_driver_index=i;
				break;
			}
		}
		if (!success) {
			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 = (char *)"Godot";
		classHint->res_class = (char *)"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;
		img[i]=NULL;
	}

	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"
			};

			img[i] = XcursorLibraryLoadImage(cursor_file[i],cursor_theme,cursor_size);
			if (img[i]) {
				cursors[i]=XcursorImageLoadCursor(x11_display,img[i]);
				//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 = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
	physics_2d_server->init();

	input = memnew( InputDefault );
#ifdef JOYDEV_ENABLED
	joystick = memnew( joystick_linux(input));
#endif
	_ensure_data_dir();
}
Exemplo n.º 24
0
void	*mlx_int_parse_xpm(t_xvar *xvar,void *info,int info_size,char *(*f)())
{
  int	pos;
  char	*line;
  char	**tab;
  char	*data;
  char	*clip_data;
  int	nc;
  int	opp;
  int	cpp;
  int	col;
  int	rgb_col;
  int	col_name;
  int	method;
  int	x;
  int	i;
  int	j;
  t_img	*img;
  t_xpm_col	*colors;
  int		*colors_direct;
  int	width;
  int	height;
  XImage	*clip_img;
  XGCValues	xgcv;
  Pixmap	clip_pix;

  colors = 0;
  colors_direct = 0;
  img = 0;
  tab = 0;
  pos = 0;
  if (!(line = f(info,&pos,info_size)) ||
      !(tab = mlx_int_str_to_wordtab(line)) || !(width = atoi(tab[0])) ||
      !(height = atoi(tab[1])) || !(nc = atoi(tab[2])) ||
      !(cpp = atoi(tab[3])) )
    RETURN;
  free(tab);
  tab = 0;

  method = 0;
  if (cpp<=2)
    {
      method = 1;
      if (!(colors_direct = malloc((cpp==2?65536:256)*sizeof(int))))
	RETURN;
    }
  else
    if (!(colors = malloc(nc*sizeof(*colors))))
      RETURN;

  clip_data = 0;

  i = nc;
  while (i--)
    {
      if (!(line = f(info,&pos,info_size)) ||
	  !(tab = mlx_int_str_to_wordtab(line+cpp)) )
	RETURN;
      j = 0;
      while (tab[j] && strcmp(tab[j++],"c"));

      if (!tab[j])
	RETURN;
      
      if ((rgb_col = mlx_int_get_text_rgb(tab[j], tab[j+1]))==-1)
	{
	  if (!(clip_data = malloc(4*width*height)) ||   /* ok, nice size .. */
	      !(clip_img = XCreateImage(xvar->display, xvar->visual,
					1, XYPixmap, 0, clip_data,
					width, height, 8, (width+7)/8)) )
	    RETURN;
	  memset(clip_data, 0xFF, 4*width*height);
	}

      if (method)
	colors_direct[mlx_int_get_col_name(line,cpp)] =
	  rgb_col>=0?mlx_get_color_value(xvar, rgb_col):rgb_col;
      else
	{
	  colors[i].name = mlx_int_get_col_name(line,cpp);
	  colors[i].col = rgb_col>=0?mlx_get_color_value(xvar,rgb_col):rgb_col;
	}
      free(tab);
    }

  if (!(img = mlx_new_image(xvar,width,height)))
    RETURN;
  opp = img->bpp/8;


  i = height;
  data = img->data;
  while (i--)
    {
      if (!(line = f(info,&pos,info_size)))
	RETURN;
      x = 0;
      while (x<width)
	{
	  col = 0;
	  col_name = mlx_int_get_col_name(line+cpp*x,cpp);
	  if (method)
	    col = colors_direct[col_name];
	  else
	    {
	      j = nc;
	      while (j--)
		if (colors[j].name==col_name)
		  {
		    col = colors[j].col;
		    j = 0;
		  }
	    }
	  if (col==-1)
	    XPutPixel(clip_img, x, height-1-i, 0);
	  else
	    mlx_int_xpm_set_pixel(img, data, opp, col, x);
	  x ++;
	}
      data += img->size_line;
    }
  if (clip_data)
    {
      if (!(clip_pix = XCreatePixmap(xvar->display, xvar->root,
					   width, height, 1)) )
	RETURN;
      img->gc = XCreateGC(xvar->display, clip_pix, 0, &xgcv);
      XPutImage(xvar->display, clip_pix, img->gc, clip_img,
		0, 0, 0, 0, width, height);
      XFreeGC(xvar->display, img->gc);
      xgcv.clip_mask = clip_pix;
      xgcv.function = GXcopy;
      xgcv.plane_mask = AllPlanes;
      img->gc = XCreateGC(xvar->display, xvar->root, GCClipMask|GCFunction|
			  GCPlaneMask, &xgcv);
      XSync(xvar->display, False);
      XDestroyImage(clip_img);
    }
  if (colors)
    free(colors);
  if (colors_direct)
    free(colors_direct);
  return (img);
}
Exemplo n.º 25
0
Arquivo: textbox.c Projeto: bjauy/xoat
void textbox_draw(textbox *tb)
{
	int i;
	XGlyphInfo extents;

	GC context    = XCreateGC(display, tb->window, 0, 0);
	Pixmap canvas = XCreatePixmap(display, tb->window, tb->w, tb->h, DefaultDepth(display, DefaultScreen(display)));
	XftDraw *draw = XftDrawCreate(display, canvas, DefaultVisual(display, DefaultScreen(display)), DefaultColormap(display, DefaultScreen(display)));

	// clear canvas
	XftDrawRect(draw, &tb->color_bg, 0, 0, tb->w, tb->h);

	char *line   = tb->text,
		*text   = tb->text ? tb->text: "",
		*prompt = tb->prompt ? tb->prompt: "";

	int text_len    = strlen(text);
	int length      = text_len;
	int line_height = tb->font->ascent + tb->font->descent;

	int cursor_x      = 0;
	int cursor_offset = 0;
	int cursor_width  = MAX(2, line_height/10);

	if (tb->flags & TB_EDITABLE)
	{
		int prompt_len = strlen(prompt);
		length = text_len + prompt_len;
		cursor_offset = MIN(tb->cursor + prompt_len, length);

		char eline[length + 10]; line = eline;
		sprintf(line, "%s%s", prompt, text);

		// replace spaces so XftTextExtents8 includes their width
		for (i = 0; i < length; i++) if (isspace(line[i])) line[i] = '_';

		// calc cursor position
		XftTextExtents8(display, tb->font, (unsigned char*)line, cursor_offset, &extents);
		cursor_x = extents.width;

		// restore correct text string with spaces
		sprintf(line, "%s%s", prompt, text);
	}

	// calc full input text width
	XftTextExtents8(display, tb->font, (unsigned char*)line, length, &extents);
	int line_width = extents.width;

	int x = 0, y = tb->font->ascent;
	if (tb->flags & TB_RIGHT)  x = tb->w - line_width;
	if (tb->flags & TB_CENTER) x = MAX(0, (tb->w - line_width) / 2);

	// draw the text, including any prompt in edit mode
	XftDrawString8(draw, &tb->color_fg, tb->font, x, y, (unsigned char*)line, length);

	// draw the cursor
	if (tb->flags & TB_EDITABLE)
		XftDrawRect(draw, &tb->color_fg, cursor_x, 2, cursor_width, line_height-4);

	// flip canvas to window
	XCopyArea(display, canvas, tb->window, context, 0, 0, tb->w, tb->h, 0, 0);

	XFreeGC(display, context);
	XftDrawDestroy(draw);
	XFreePixmap(display, canvas);
}
Exemplo n.º 26
0
/*
 * Flashes one entire screen.  This is done by making a window the size of the
 * whole screen (or reusing the old one, if it's still around), mapping it,
 * painting it white and then black, and then unmapping it. We set saveunder so
 * that all the windows behind it come back immediately.
 *
 * Unlike frame flashes, we don't do fullscreen flashes with a timeout; rather,
 * we do them in one go, because we don't have to rely on the theme code
 * redrawing the frame for us in order to do the flash.
 *
 * \param display  The display which owns the screen (rather redundant)
 * \param screen   The screen to flash
 *
 * \bug The way I read it, this appears not to do the flash
 * the first time we flash a particular display. Am I wrong?
 *
 * \bug This appears to destroy our current XSync status.
 */
static void
bell_flash_screen (MetaDisplay *display, 
			MetaScreen  *screen)
{
  Window root = screen->xroot;
  int width = screen->rect.width;
  int height = screen->rect.height;
  
  if (screen->flash_window == None)
    {
      Visual *visual = (Visual *)CopyFromParent;
      XSetWindowAttributes xswa;
      int depth = CopyFromParent;
      xswa.save_under = True;
      xswa.override_redirect = True;
      /* 
       * TODO: use XGetVisualInfo and determine which is an
       * overlay, if one is present, and use the Overlay visual
       * for this window (for performance reasons).  
       * Not sure how to tell this yet... 
       */
      screen->flash_window = XCreateWindow (display->xdisplay, root,
					    0, 0, width, height,
					    0, depth,
					    InputOutput,
					    visual,
				    /* note: XSun doesn't like SaveUnder here */
					    CWSaveUnder | CWOverrideRedirect,
					    &xswa);
      XSelectInput (display->xdisplay, screen->flash_window, ExposureMask);
      XMapWindow (display->xdisplay, screen->flash_window);
      XSync (display->xdisplay, False);
      XFlush (display->xdisplay);
      XUnmapWindow (display->xdisplay, screen->flash_window);
    }
  else
    {
      /* just draw something in the window */
      GC gc = XCreateGC (display->xdisplay, screen->flash_window, 0, NULL);
      XMapWindow (display->xdisplay, screen->flash_window);
      XSetForeground (display->xdisplay, gc,
		      WhitePixel (display->xdisplay, 
				  XScreenNumberOfScreen (screen->xscreen)));
      XFillRectangle (display->xdisplay, screen->flash_window, gc,
		      0, 0, width, height);
      XSetForeground (display->xdisplay, gc,
		      BlackPixel (display->xdisplay, 
				  XScreenNumberOfScreen (screen->xscreen)));
      XFillRectangle (display->xdisplay, screen->flash_window, gc,
		      0, 0, width, height);
      XFlush (display->xdisplay);
      XSync (display->xdisplay, False);
      XUnmapWindow (display->xdisplay, screen->flash_window);
      XFreeGC (display->xdisplay, gc);
    }

  if (meta_prefs_get_focus_mode () != C_DESKTOP_FOCUS_MODE_CLICK &&
      !display->mouse_mode)
    meta_display_increment_focus_sentinel (display);
  XFlush (display->xdisplay);
}
Exemplo n.º 27
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;
	}
}
PUBLIC void
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 */
   i = DefaultScreen(dpy);
   win = RootWindow(dpy, i);

   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);
}
Exemplo n.º 29
0
	int main(int argc, char **argv)
	{
		static char *string = "Hello World!";
		Display *display;
		int screen_num;
		Window win;			//窗口ID
		unsigned int width, height;	//窗口尺寸
		unsigned int border_width = 4;	//边界空白
		unsigned int display_width, display_height;//屏幕尺寸
		int count;
		XEvent report;
		GC gc;
		unsigned long valuemask = 0;
		XGCValues values;
		char *display_name = NULL;
	
		// 和X 服务器连接
		if ( (display=XOpenDisplay(display_name)) == NULL )
		{
			printf("Cannot connect to X server %s\n", 
					XDisplayName(display_name));
			exit(-1);
		}

		//获得缺省的 screen_num
		screen_num = DefaultScreen(display);

		//获得屏幕的宽度和高度
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);
	
		//指定所建立窗口的宽度和高度
		width = display_width/3;
		height = display_height/4;
	
		//建立窗口
		win = XCreateSimpleWindow(display, 	//display
			RootWindow(display,screen_num), //父窗口
			0, 0, width, height, 		//位置和大小
			border_width, 			//边界宽度
			BlackPixel(display,screen_num), //前景色
			WhitePixel(display,screen_num));//背景色
	
		//选择窗口感兴趣的事件掩码
		XSelectInput(display, win, 
			ExposureMask | KeyPressMask | 
			ButtonPressMask | StructureNotifyMask);

		//建立GC
		gc = DefaultGC(display, screen_num);

		//显示窗口
		XMapWindow(display, win);

		//进入事件循环
		while (1)  {

			//取得队列中的事件
			XNextEvent(display, &report);
			switch  (report.type) {

			//曝光事件, 窗口应重绘
			case Expose:
				//取得最后一个曝光事件
				if (report.xexpose.count != 0) break;
				break;

			//窗口尺寸改变, 重新取得窗口的宽度和高度
			case ConfigureNotify:
				break;

			//鼠标点击显示窗口的某些属性
			case ButtonPress:
				{
				XWindowAttributes xa;
				Window root;
				int x, y;
				unsigned int w, h, border, depth;
					
				XGetWindowAttributes(display,win,&xa);
				printf("geometry:%d %d %d %d\n",
					xa.x,xa.y, xa.width, xa.height);
				printf("override redirect:%d\n", 
					xa.override_redirect);
				XGetGeometry(display,win,&root, &x, &y,
					&w, &h, &border, &depth);
				printf("attrib: x:%d y:%d w:%d h:%d "
					"border:%d depth: %d\n",
					x, y, w, h, border, depth);
				}
				break;
			case KeyPress:
				XFreeGC(display, gc);
				exit(1);
			default:
				
				break;
			}
		}
	}
Exemplo n.º 30
0
static DFBResult
x11DeallocateBuffer( CoreSurfacePool       *pool,
                     void                  *pool_data,
                     void                  *pool_local,
                     CoreSurfaceBuffer     *buffer,
                     CoreSurfaceAllocation *allocation,
                     void                  *alloc_data )
{
     DFBResult          ret   = DFB_OK;
     x11AllocationData *alloc = alloc_data;
     x11PoolLocalData  *local = pool_local;
     DFBX11            *x11   = local->x11;

     D_DEBUG_AT( X11_Surfaces, "%s()\n", __FUNCTION__ );

     D_MAGIC_ASSERT( pool, CoreSurfacePool );

     CORE_SURFACE_ALLOCATION_ASSERT( allocation );

     XLockDisplay( x11->display );

     if (alloc->gc)
          XFreeGC( x11->display, alloc->gc );

     switch (alloc->type) {
          case X11_ALLOC_WINDOW:
               D_ASSUME( x11->showing != alloc->window );

               if (x11->showing == alloc->window) {
                    D_LOG( X11_Surfaces, VERBOSE, "  -> Hiding window 0x%08lx that is to be destroyed!!!\n", x11->showing );
                    XUnmapWindow( x11->display, x11->showing );

                    x11->showing = 0;
               }

          case X11_ALLOC_PIXMAP:
               if (allocation->type & CSTF_PREALLOCATED) {
                    // don't delete
               }
               else if (alloc->created) {
                    if (alloc->xid != alloc->window) {
                         D_INFO( "X11/Windows: Free Pixmap 0x%08lx\n", alloc->xid );
                         XFreePixmap( x11->display, alloc->xid );
                    }

                    if (alloc->window) {
                         D_INFO( "X11/Windows: Destroy Window 0x%08lx\n", alloc->window );
                         XDestroyWindow( x11->display, alloc->window );
                    }
               }
               break;

          default:
               D_BUG( "unexpected allocation type %d\n", alloc->type );
               ret = DFB_BUG;
     }

     XUnlockDisplay( x11->display );

     return ret;
}