Ejemplo n.º 1
0
Window mume_x11_create_window(
    Display *display, int type, Window parent,
    int x, int y, unsigned int width, unsigned int height,
    unsigned int clazz, int eventmask)
{
    int screen;
    int depth;
    Visual *visual;
    unsigned long valuemask;
    XSetWindowAttributes attributes;
    XSizeHints *size_hints;
    XWMHints *wm_hints;
    XClassHint *class_hints;
    Window window;

    screen = DefaultScreen(display);
    visual = DefaultVisual(display, screen);

    if (clazz != InputOnly) {
        depth = DefaultDepth(display, screen);
        valuemask = CWBackPixel | CWBorderPixel;
        attributes.background_pixel = WhitePixel(display, screen);
        attributes.border_pixel = BlackPixel(display, screen);

        if (MUME_BACKWIN_MENU == type) {
            assert(RootWindow(display, screen) == parent);

            valuemask |= CWSaveUnder | CWOverrideRedirect;
            attributes.save_under = True;
            attributes.override_redirect = True;
        }
    }
    else {
        depth = 0;
        valuemask = 0;
    }

    if (None == parent)
        parent = RootWindow(display, screen);

    window = XCreateWindow(
        display, parent, x, y, width, height, 0, depth,
        clazz, visual, valuemask, &attributes);

    if (clazz != InputOnly) {
        /* Setup standard properties. */
        if (!(size_hints = XAllocSizeHints()))
            mume_abort(("allocating memory failed!\n"));

        if (!(wm_hints = XAllocWMHints()))
            mume_abort(("allocating memory failed!\n"));

        if (!(class_hints = XAllocClassHint()))
            mume_abort(("allocating memory failed!\n"));

        size_hints->flags = PPosition | PSize | PMinSize;
        size_hints->min_width = 0;
        size_hints->min_height = 0;
        wm_hints->initial_state = NormalState;
        wm_hints->input = True;
        /* wm_hints->icon_pixmap = icon_pixmap; */
        wm_hints->flags = StateHint/* | IconPixmapHint*/ | InputHint;
        class_hints->res_name = "mume";
        class_hints->res_class = "mume";

        /* or use XSizeHints, XSetClassHint, XSetWMHints */
        XmbSetWMProperties(display, window, "mume", "mume",
                           NULL, 0, size_hints, wm_hints, class_hints);

        XFree(wm_hints);
        XFree(class_hints);
        XFree(size_hints);
    }

    /* Select event */
    XSelectInput(display, window, eventmask);

    return window;
}
Ejemplo n.º 2
0
void xskin_start_interface( int pipe_in ) {

  int xskin_sc;
  XEvent xskin_e;
  XSetWindowAttributes xskin_attr;

  XSizeHints xskin_hint;
  XClassHint xskin_chint;
  XTextProperty ct;
  char *namlist[2];


  /* setup window */

  xskin_d     = XOpenDisplay( NULL );
  xskin_sc    = DefaultScreen( xskin_d );
  xskin_r     = RootWindow( xskin_d, xskin_sc );
  xskin_gc    = DefaultGC( xskin_d, xskin_sc );
  xskin_vis   = DefaultVisual( xskin_d, xskin_sc );
  xskin_depth = DefaultDepth( xskin_d, xskin_sc );

  xskin_w = XCreateSimpleWindow( xskin_d, xskin_r, 0, 0,
				 skin_width, skin_height, 0,
				 WhitePixel( xskin_d, xskin_sc ),
				 BlackPixel( xskin_d, xskin_sc ) );

  xskin_attr.backing_store = True;
  xskin_attr.override_redirect = False;
  XChangeWindowAttributes( xskin_d, xskin_w,
			   CWBackingStore|CWOverrideRedirect, &xskin_attr );

  XSelectInput( xskin_d, xskin_w,
		KeyPressMask|ExposureMask|
		EnterWindowMask|LeaveWindowMask|
		ButtonPressMask|ButtonReleaseMask|
		Button1MotionMask );

  xskin_hint.flags = USSize | PMinSize | PMaxSize | USPosition;
  xskin_hint.width = xskin_hint.min_width = xskin_hint.max_width
    = skin_width;
  xskin_hint.height = xskin_hint.min_height = xskin_hint.max_height
    = skin_height;
  XSetNormalHints( xskin_d, xskin_w, &xskin_hint );

  xskin_chint.res_name  = XSKIN_RES_NAME;
  xskin_chint.res_class = XSKIN_RES_CLASS;
  XSetClassHint( xskin_d, xskin_w, &xskin_chint );

  namlist[0]=(char *)safe_malloc(strlen(XSKIN_WINDOW_NAME)+1);
  strcpy( namlist[0], XSKIN_WINDOW_NAME );
  XmbTextListToTextProperty( xskin_d, namlist, 1, XCompoundTextStyle, &ct );
  XSetWMName( xskin_d, xskin_w, &ct );
  XSetWMIconName( xskin_d, xskin_w, &ct );
  free(namlist[0]);


  /* setup pixmaps */

  if ( load_skins()!=0 ) goto finish;

  XSetWindowBackgroundPixmap( xskin_d, xskin_w, xskin_back );
  XClearWindow( xskin_d, xskin_w );

  XMapWindow( xskin_d, xskin_w );
  while( 1 ) {
    XNextEvent( xskin_d, &xskin_e );
    if ( xskin_e.type == Expose ) break; 
  }

  fshuf=0;
  frep=0;
  fequ=1;
  fpll=1;
  fplay=0;
  fpause=0;
  fremain=0;
  play_val=1;
  vol_val=50;
  last_current_time=0;
  total_time=0;
  speana_buf = NULL;
  strcpy( last_text, "welcome to timidity" );

  install_sighandler();

  repaint();
  ts_spectrum( -1, speana_buf );

  XFlush(xskin_d);

  xskin_jobs( pipe_in );   /* tskin main jobs */

finish:
  signal_vector(0);  /* finish */
}
Ejemplo n.º 3
0
int main(int ac, char **av)
{
    Display *xDpy = XOpenDisplay(NULL);
    int screenId;
    GC gc;
    XGCValues values;
    Pixmap blendPixmap;
    vertexDataRec warpData[6];
    int nvDpyId;

    if (!xDpy) {
        fprintf (stderr, "Could not open X Display %s!\n", XDisplayName(NULL));
        return 1;
    }

    screenId = XDefaultScreen(xDpy);

    if (ac != 2) {
        fprintf (stderr, "Usage: ./nv-control-warpblend nvDpyId\n");
        fprintf (stderr, "See 'nvidia-settings -q CurrentMetaMode' for currently connected DPYs.\n");
        return 1;
    }

    nvDpyId = atoi(av[1]);

    // Start with two screen-aligned triangles, and warp them using the sample
    // keystone matrix in transformPoint. Make sure we save W for correct
    // perspective and pass it through as the last texture coordinate component.
    warpData[0].pos.x = 0.0f;
    warpData[0].pos.y = 0.0f;
    warpData[0].tex.x = 0.0f;
    warpData[0].tex.y = 0.0f;
    warpData[0].tex2.x = 0.0f;
    warpData[0].tex2.y = transformPoint(&warpData[0].pos);

    warpData[1].pos.x = 1.0f;
    warpData[1].pos.y = 0.0f;
    warpData[1].tex.x = 1.0f;
    warpData[1].tex.y = 0.0f;
    warpData[1].tex2.x = 0.0f;
    warpData[1].tex2.y = transformPoint(&warpData[1].pos);

    warpData[2].pos.x = 0.0f;
    warpData[2].pos.y = 1.0f;
    warpData[2].tex.x = 0.0f;
    warpData[2].tex.y = 1.0f;
    warpData[2].tex2.x = 0.0f;
    warpData[2].tex2.y = transformPoint(&warpData[2].pos);

    warpData[3].pos.x = 1.0f;
    warpData[3].pos.y = 0.0f;
    warpData[3].tex.x = 1.0f;
    warpData[3].tex.y = 0.0f;
    warpData[3].tex2.x = 0.0f;
    warpData[3].tex2.y = transformPoint(&warpData[3].pos);

    warpData[4].pos.x = 1.0f;
    warpData[4].pos.y = 1.0f;
    warpData[4].tex.x = 1.0f;
    warpData[4].tex.y = 1.0f;
    warpData[4].tex2.x = 0.0f;
    warpData[4].tex2.y = transformPoint(&warpData[4].pos);

    warpData[5].pos.x = 0.0f;
    warpData[5].pos.y = 1.0f;
    warpData[5].tex.x = 0.0f;
    warpData[5].tex.y = 1.0f;
    warpData[5].tex2.x = 0.0f;
    warpData[5].tex2.y = transformPoint(&warpData[5].pos);

    // Prime the random number generator, since the helper functions need it.
    srand(time(NULL));

    // Apply our transformed warp data to the chosen display.
    XNVCTRLSetScanoutWarping(xDpy,
                             screenId,
                             nvDpyId,
                             NV_CTRL_WARP_DATA_TYPE_MESH_TRIANGLES_XYUVRQ,
                             6, // 6 vertices for two triangles
                             (float *)warpData);

    // Create a sample blending pixmap; let's make it solid white with a grey
    // border and rely on upscaling with filtering to feather the edges.

    // Start with a 32x32 pixmap.
    blendPixmap = XCreatePixmap(xDpy, RootWindow(xDpy, screenId), 32, 32, DefaultDepth(xDpy, screenId));

    values.foreground = 0x77777777;
    gc = XCreateGC(xDpy, blendPixmap, GCForeground, &values);

    // Fill it fully with grey.
    XFillRectangle(xDpy, blendPixmap, gc, 0, 0, 32, 32);

    values.foreground = 0xffffffff;
    XChangeGC(xDpy, gc, GCForeground, &values);

    // Fill everything but a one-pixel border with white.
    XFillRectangle(xDpy, blendPixmap, gc, 1, 1, 30, 30);

    // Apply it to the display. blendAfterWarp is FALSE, so the edges will be
    // blended in warped space.
    XNVCTRLSetScanoutIntensity(xDpy,
                               screenId,
                               nvDpyId,
                               blendPixmap,
                               False);

    return 0;
}
Ejemplo n.º 4
0
static int alock_bg_shade_init(const char* args, struct aXInfo* xinfo) {

    char* color_name = strdup("black");
    unsigned int shade = 80;

    Pixmap src_pm = None;
    Pixmap dst_pm = None;

    int width = 0;
    int height = 0;

    if (!xinfo || !args)
        return 0;

    if (strstr(args, "shade:") == args && strlen(&args[6]) > 0) {
        char* arguments = strdup(&args[6]);
        char* tmp;
        char* arg = NULL;
        for (tmp = arguments; tmp; ) {
            arg = strsep(&tmp, ",");
            if (arg) {
                if (strstr(arg, "color=") == arg && strlen(arg) > 6 && strlen(&arg[6])) {
                    free(color_name);
                    color_name = strdup(&arg[6]);
                }
                else if (strstr(arg, "shade=") == arg && strlen(arg) > 6 && strlen(&arg[6])) {
                    long int tmp_shade;
                    char* tmp_char;
                    tmp_shade = strtol(&arg[6], &tmp_char, 0);
                    if ((!tmp_shade || tmp_char != &arg[6]) && tmp_shade > 0 && tmp_shade < 100)
                        shade = tmp_shade;
                    else {
                        printf("%s", "alock: error, given value invalid or out of range for [shade].\n");
                        free(arguments);
                        free(color_name);
                        return 0;
                    }
                }
            }
        }
        free(arguments);
    }

    if (!alock_check_xrender(xinfo)) {
        free(color_name);
        return 0;
    }

    {
        window = (Window*)calloc(xinfo->nr_screens, sizeof(Window));
        color = (XColor*)calloc(xinfo->nr_screens, sizeof(XColor));
    }

    {
        int scr;
        for (scr = 0; scr < xinfo->nr_screens; scr++) {

            /* get a color from color_name */
            alock_alloc_color(xinfo, scr, color_name, "black", &color[scr]);

            width = xinfo->width_of_root[scr];
            height = xinfo->height_of_root[scr];

            { /* xrender stuff */
                Display* dpy = xinfo->display;
                Window root = xinfo->root[scr];
                int depth = DefaultDepth(dpy, scr);
                GC gc = DefaultGC(dpy, scr);

                { /* grab whats on the screen */
                    XImage* image = XGetImage(dpy, root, 0, 0, width, height, AllPlanes, ZPixmap);
                    src_pm = XCreatePixmap(dpy, root, width, height, depth);
                    XPutImage(dpy, src_pm, gc, image, 0, 0, 0, 0, width, height);
                    XDestroyImage(image);
                }

                dst_pm = XCreatePixmap(dpy, root, width, height, depth);

                { /* tint the dst*/
                    GC tintgc;
                    XGCValues tintval;

                    tintval.foreground = color[scr].pixel;
                    tintgc = XCreateGC(dpy, dst_pm, GCForeground, &tintval);
                    XFillRectangle(dpy, dst_pm, tintgc, 0, 0, width, height);
                    XFreeGC(dpy, tintgc);
                }

                alock_shade_pixmap(xinfo, scr, src_pm, dst_pm, shade, 0, 0, 0, 0, width, height);
            }

            { /* create final window */
                XSetWindowAttributes xswa;
                long xsmask = 0;

                xswa.override_redirect = True;
                xswa.colormap = xinfo->colormap[scr];
                xswa.background_pixmap = dst_pm;

                xsmask |= CWOverrideRedirect;
                xsmask |= CWBackPixmap;
                xsmask |= CWColormap;

                window[scr] = XCreateWindow(xinfo->display, xinfo->root[scr],
                                  0, 0, width, height,
                                  0, /* borderwidth */
                                  CopyFromParent, /* depth */
                                  InputOutput, /* class */
                                  CopyFromParent, /* visual */
                                  xsmask, &xswa);
                XFreePixmap(xinfo->display, src_pm);
                XFreePixmap(xinfo->display, dst_pm);
            }

            if (window[scr])
                xinfo->window[scr] = window[scr];
        }
        free(color_name);
    }

    return 1;
}
Ejemplo n.º 5
0
void
setup(int topbar, const char *bg, unsigned int lines) {
    int x = 0, y = 0; /* position of the window */
    /* if (!dc) { */
        dc = initdc();
    /* } */
    initfont(dc, font);
    XInitThreads();
    screen = DefaultScreen(dc->dpy);
    Window root = RootWindow(dc->dpy, screen);
    XSetWindowAttributes swa;
    XIM xim;
#ifdef XINERAMA
    int n;
    XineramaScreenInfo *info;
#endif

    clip = XInternAtom(dc->dpy, "CLIPBOARD",   False);
    utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);

    /* calculate menu geometry */
    bh = dc->font.height + 2;
    lines = MAX(lines, 0);
    mh = (lines + 1) * bh;
#ifdef XINERAMA
    if((info = XineramaQueryScreens(dc->dpy, &n))) {
        int a, j, di, i = 0, area = 0;
        unsigned int du;
        Window w, pw, dw, *dws;
        XWindowAttributes wa;

        XGetInputFocus(dc->dpy, &w, &di);
        if(w != root && w != PointerRoot && w != None) {
            /* find top-level window containing current input focus */
            do {
                if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
                    XFree(dws);
            } while(w != root && w != pw);
            /* find xinerama screen with which the window intersects most */
            if(XGetWindowAttributes(dc->dpy, pw, &wa))
                for(j = 0; j < n; j++)
                    if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
                        area = a;
                        i = j;
                    }
        }
        /* no focused window is on screen, so use pointer location instead */
        if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
            for(i = 0; i < n; i++)
                if(INTERSECT(x, y, 1, 1, info[i]))
                    break;

        x = info[i].x_org;
        y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
        mw = info[i].width;
        XFree(info);
    }
    else
#endif
    {
        x = 0;
        y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
        mw = DisplayWidth(dc->dpy, screen);
    }

    /* create menu window */
    swa.override_redirect = True;
    swa.background_pixel = getcolor(dc, bg);
    swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
    win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
            DefaultDepth(dc->dpy, screen), CopyFromParent,
            DefaultVisual(dc->dpy, screen),
            CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);

    XResizeWindow(dc->dpy, win, mw, mh);
    /* open input methods */
    xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
    xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
            XNClientWindow, win, XNFocusWindow, win, NULL);

    XMapRaised(dc->dpy, win);
    resizedc(dc, mw, mh);
    mapdc(dc, win, mw, mh);
}
Ejemplo n.º 6
0
XImage *xNewImage (Display *dpy         /* display pointer */, 
		   unsigned long pmin   /* minimum pixel value (corresponding to byte=0) */, 
		   unsigned long pmax   /* maximum pixel value (corresponding to byte=255) */,
		   int width            /* number of bytes in x dimension */, 
		   int height           /* number of bytes in y dimension */, 
		   float blank          /* portion for blanking (0 to 1) */, 
		   unsigned char *bytes /* unsigned bytes to be mapped to an image */)
/*< make a new image of pixels from bytes >*/
/******************************************************************************
Author:		Dave Hale, Colorado School of Mines, 06/08/90
*****************************************************************************/
{
	int scr=DefaultScreen(dpy);
	int i,j,k,line,iline,jline,widthpad;
	float base,scale;
	unsigned long map[256],bkgnd;
	unsigned char *data;
	int byte_perpixel;
	unsigned int depth;
	XImage *xim;
	
	xim=(XImage *) NULL;

	depth=(unsigned int)DefaultDepth(dpy,scr);	
	byte_perpixel=4;
	if(depth<=8) byte_perpixel=1;
	else if(depth<=16) byte_perpixel=2;

/*	else if(depth<=24) byte_perpixel=3;*/



	/* build map for translating bytes to pixels */
	base = ((double) pmin)+0.499;
	scale = ((double) (pmax-pmin))/255.0;
	for (i=0; i<=255; ++i){
		map[i] = base+i*scale;
	}

	/* blanking */
	bkgnd = (unsigned long) WhitePixel(dpy,scr);
	j = SF_MAX(0,SF_MIN(256,(int)(256*blank)));
	for (i = 0; i < j; i++)
		map[255-i] = bkgnd;

	/* allocate memory for image data */
	widthpad = (1+(width-1)/(BitmapPad(dpy)/8))*BitmapPad(dpy)/8;
	data = (unsigned char*) sf_alloc(widthpad*height,byte_perpixel);

	xim=XCreateImage(	(Display *) dpy,
				(Visual *) DefaultVisual(dpy,scr),
				(unsigned int) DefaultDepth(dpy,scr),
				(int) ZPixmap,
				(int) 0,
				(char *) data,
				(unsigned int) widthpad,
				(unsigned int) height,
/*				(int) BitmapPad(dpy),
				(int) widthpad*byte_perpixel
*/
				8,0);
	byte_perpixel=xim->bits_per_pixel/8;
/*	fprintf(stderr,"\nbyte_perpixel = %d, depth= %d\n", byte_perpixel,depth); */

	/* translate bytes to pixels, padding scanlines as necessary */
	for (line=0; line<height; line++) {
		iline = line*width;
		jline = line*widthpad;
		for (i=iline,j=jline,k=0; k<width; ++i,++j,++k)
		{       if(byte_perpixel==1)
			((unsigned char *)data)[j] =(unsigned char)map[bytes[i]];
			if(byte_perpixel==2)
			  {
			    int edn=xim->byte_order;
			    if(edn==LSBFirst){
			      ((unsigned char *)data)[j*2+0] =(unsigned char)(truecolor_pixel[bytes[i]]);
			      ((unsigned char *)data)[j*2+1] =(unsigned char)(truecolor_pixel[bytes[i]]>>8);
			    }else{
			      ((unsigned char *)data)[j*2+0] =(unsigned char)(truecolor_pixel[bytes[i]]>>24); 
			      ((unsigned char *)data)[j*2+1] =(unsigned char)(truecolor_pixel[bytes[i]]>>16);
			      }

			    /*((unsigned short *)data)[j] =(unsigned short)(truecolor_pixel[bytes[i]]);*/
			  }	
Ejemplo n.º 7
0
void CGX_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
{
#if 0
	SDL_Surface *sicon;
	XWMHints *wmhints;
	XImage *icon_image;
	Pixmap icon_pixmap;
	Pixmap mask_pixmap;
#ifdef USE_ICON_WINDOW
	Window icon_window;
#endif
	GC GC;
	XGCValues GCvalues;
	int i, b, dbpp;
	SDL_Rect bounds;
	Uint8 *LSBmask, *color_tried;
	Visual *dvis;

	/* Lock the event thread, in multi-threading environments */
	SDL_Lock_EventThread();

	/* The icon must use the default visual, depth and colormap of the
	   screen, so it might need a conversion */
	dbpp = DefaultDepth(SDL_Display, SDL_Screen);
	switch(dbpp) {
	case 15:
	    dbpp = 16; break;
	case 24:
	    dbpp = 32; break;
	}
	dvis = DefaultVisual(SDL_Display, SDL_Screen);

	/* The Visual struct is supposed to be opaque but we cheat a little */
	sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
				     dbpp,
				     dvis->red_mask, dvis->green_mask,
				     dvis->blue_mask, 0);

	if ( sicon == NULL ) {
		goto done;
	}
	/* If we already have allocated colours from the default colormap,
	   copy them */
	if(SDL_Visual == dvis && SDL_XColorMap == SDL_DisplayColormap
	   && this->screen->format->palette && sicon->format->palette) {
	    memcpy(sicon->format->palette->colors,
		   this->screen->format->palette->colors,
		   this->screen->format->palette->ncolors * sizeof(SDL_Color));
	}

	bounds.x = 0;
	bounds.y = 0;
	bounds.w = icon->w;
	bounds.h = icon->h;
	if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 )
		goto done;

	/* Lock down the colors used in the colormap */
	color_tried = NULL;
	if ( sicon->format->BitsPerPixel == 8 ) {
		SDL_Palette *palette;
		Uint8 *p;
		XColor wanted;

		palette = sicon->format->palette;
		color_tried = malloc(palette->ncolors);
		if ( color_tried == NULL ) {
			goto done;
		}
		if ( SDL_iconcolors != NULL ) {
			free(SDL_iconcolors);
		}
		SDL_iconcolors = malloc(palette->ncolors
					* sizeof(*SDL_iconcolors));
		if ( SDL_iconcolors == NULL ) {
			free(color_tried);
			goto done;
		}
		memset(color_tried, 0, palette->ncolors);
		memset(SDL_iconcolors, 0,
		       palette->ncolors * sizeof(*SDL_iconcolors));

		p = (Uint8 *)sicon->pixels; 
		for ( i = sicon->w*sicon->h; i > 0; --i, ++p ) {
			if ( ! color_tried[*p] ) {
				wanted.pixel = *p;
				wanted.red   = (palette->colors[*p].r<<8);
				wanted.green = (palette->colors[*p].g<<8);
				wanted.blue  = (palette->colors[*p].b<<8);
				wanted.flags = (DoRed|DoGreen|DoBlue);
				if (XAllocColor(SDL_Display,
						SDL_DisplayColormap, &wanted)) {
					++SDL_iconcolors[wanted.pixel];
				}
				color_tried[*p] = 1;
			}
		}
	}
	if ( color_tried != NULL ) {
		free(color_tried);
	}

	/* Translate mask data to LSB order and set the icon mask */
	i = (sicon->w/8)*sicon->h;
	LSBmask = (Uint8 *)malloc(i);
	if ( LSBmask == NULL ) {
		goto done;
	}
	memset(LSBmask, 0, i);
	while ( --i >= 0 ) {
		for ( b=0; b<8; ++b )
			LSBmask[i] |= (((mask[i]>>b)&0x01)<<(7-b));
	}
	mask_pixmap = XCreatePixmapFromBitmapData(SDL_Display, WMwindow,
					LSBmask, sicon->w, sicon->h, 1L, 0L, 1);

	/* Transfer the image to an X11 pixmap */
	icon_image = XCreateImage(SDL_Display,
			DefaultVisual(SDL_Display, SDL_Screen),
			DefaultDepth(SDL_Display, SDL_Screen),
			ZPixmap, 0, (char *)sicon->pixels, sicon->w, sicon->h,
			((sicon->format)->BytesPerPixel == 3) ? 32 :
				(sicon->format)->BytesPerPixel*8, 0);
	icon_pixmap = XCreatePixmap(SDL_Display, SDL_Root, sicon->w, sicon->h,
			DefaultDepth(SDL_Display, SDL_Screen));
	GC = XCreateGC(SDL_Display, icon_pixmap, 0, &GCvalues);
	XPutImage(SDL_Display, icon_pixmap, GC, icon_image,
					0, 0, 0, 0, sicon->w, sicon->h);
	XFreeGC(SDL_Display, GC);
	XDestroyImage(icon_image);
	free(LSBmask);
	sicon->pixels = NULL;

#ifdef USE_ICON_WINDOW
	/* Create an icon window and set the pixmap as its background */
	icon_window = XCreateSimpleWindow(SDL_Display, SDL_Root,
					0, 0, sicon->w, sicon->h, 0,
					CopyFromParent, CopyFromParent);
	XSetWindowBackgroundPixmap(SDL_Display, icon_window, icon_pixmap);
	XClearWindow(SDL_Display, icon_window);
#endif

	/* Set the window icon to the icon pixmap (and icon window) */
	wmhints = XAllocWMHints();
	wmhints->flags = (IconPixmapHint | IconMaskHint);
	wmhints->icon_pixmap = icon_pixmap;
	wmhints->icon_mask = mask_pixmap;
#ifdef USE_ICON_WINDOW
	wmhints->flags |= IconWindowHint;
	wmhints->icon_window = icon_window;
#endif
	XSetWMHints(SDL_Display, WMwindow, wmhints);
	XFree(wmhints);
	XSync(SDL_Display, False);

  done:
	SDL_Unlock_EventThread();
	if ( sicon != NULL ) {
		SDL_FreeSurface(sicon);
	}
#endif
	return;
}
Ejemplo n.º 8
0
XSilChessWindow::XSilChessWindow(XtAppContext app, Widget toplevel,
                                 Visual * vsl, int vsldepth, Colormap cmap)
{
	char tmp[512];
	Arg al[10];
	int i;
	XmString xms;

	// Initialize member variables
	App=app;
	TopLevel=toplevel;
	Disp=XtDisplay(TopLevel);
	Vsl=vsl;
	VslDepth=vsldepth;
	CMap=cmap;
	DlgVsl=DefaultVisual(Disp,XScreenNumberOfScreen(XtScreen(TopLevel)));
	DlgVslDepth=DefaultDepth(Disp,XScreenNumberOfScreen(XtScreen(TopLevel)));
	DlgCMap=DefaultColormap(Disp,XScreenNumberOfScreen(XtScreen(TopLevel)));
	PixelSize=(VslDepth<=8 ? 1 : (VslDepth<=16 ? 2 : 4));
	RedMask=Vsl->red_mask;
	GreenMask=Vsl->green_mask;
	BlueMask=Vsl->blue_mask;
	SelX=SelY-1;
	IsSearching=false;
	AbortSearching=false;
	NeedPainting=false;
	IsPainting=false;
	HintWanted=false;
	HintValid=false;

	// Create main window
	MainWin=XtVaCreateManagedWidget(
		"mainWin",xmMainWindowWidgetClass,TopLevel,
		(char*)NULL
	);

	// Create main menu bar
	MainMenu=XmCreateMenuBar(MainWin,(char*)"mainMenu",NULL,0);
	XtManageChild(MainMenu);

	// Create menu item: file
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	FileMenu=XmCreatePulldownMenu(MainMenu,(char*)"fileMenu",al,3);
	BFile=XtVaCreateManagedWidget(
		"file",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,FileMenu,
		(char*)NULL
	);

	// Create menu item: file/load
	BFileLoad=XtVaCreateManagedWidget(
		"load",xmPushButtonWidgetClass,FileMenu,
		(char*)NULL
	);
	XtAddCallback(BFileLoad,XmNactivateCallback,HandleCallback,this);

	// Create menu item: file/save
	BFileSave=XtVaCreateManagedWidget(
		"save",xmPushButtonWidgetClass,FileMenu,
		(char*)NULL
	);
	XtAddCallback(BFileSave,XmNactivateCallback,HandleCallback,this);

	// Create menu item: file/exit
	XtVaCreateManagedWidget(
		"separator",xmSeparatorWidgetClass,FileMenu,
		(char*)NULL
	);
	BFileExit=XtVaCreateManagedWidget(
		"exit",xmPushButtonWidgetClass,FileMenu,
		(char*)NULL
	);
	XtAddCallback(BFileExit,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	GameMenu=XmCreatePulldownMenu(MainMenu,(char*)"gameMenu",al,3);
	BGame=XtVaCreateManagedWidget(
		"game",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,GameMenu,
		(char*)NULL
	);

	// Create menu item: game/new
	BGameNew=XtVaCreateManagedWidget(
		"new",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameNew,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game/flip
	BGameFlip=XtVaCreateManagedWidget(
		"flip",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameFlip,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game/undo
	BGameUndo=XtVaCreateManagedWidget(
		"undo",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameUndo,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game/list
	BGameList=XtVaCreateManagedWidget(
		"list",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameList,XmNactivateCallback,HandleCallback,this);

	// Create menu item: computer
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	CompMenu=XmCreatePulldownMenu(MainMenu,(char*)"compMenu",al,3);
	BComp=XtVaCreateManagedWidget(
		"comp",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,CompMenu,
		(char*)NULL
	);

	// Create menu item: computer/hint
	BCompHint=XtVaCreateManagedWidget(
		"hint",xmPushButtonWidgetClass,CompMenu,
		(char*)NULL
	);
	XtAddCallback(BCompHint,XmNactivateCallback,HandleCallback,this);

	// Create menu item: computer/depth
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	XtSetArg(al[3],XmNradioBehavior,True);
	DepthMenu=XmCreatePulldownMenu(CompMenu,(char*)"depthMenu",al,4);
	BCompDepth=XtVaCreateManagedWidget(
		"depth",xmCascadeButtonWidgetClass,CompMenu,
		XmNsubMenuId,DepthMenu,
		(char*)NULL
	);

	// Create menu items: computer/depth/1...
	for (i=0; i<=SilChessMachine::MAX_SEARCH_DEPTH; i++) {
		sprintf(tmp,"%d",i);
		BDepth[i]=XtVaCreateManagedWidget(
			tmp,xmToggleButtonWidgetClass,DepthMenu,
			(char*)NULL
		);
		XtAddCallback(BDepth[i],XmNvalueChangedCallback,HandleCallback,this);
	}

	// Create menu item: help
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	HelpMenu=XmCreatePulldownMenu(MainMenu,(char*)"helpMenu",al,3);
	BHelp=XtVaCreateManagedWidget(
		"help",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,HelpMenu,
		(char*)NULL
	);
	XtVaSetValues(MainMenu,XmNmenuHelpWidget,BHelp,(char*)NULL);

	// Create menu item: help/about
	BHelpAbout=XtVaCreateManagedWidget(
		"about",xmPushButtonWidgetClass,HelpMenu,
		(char*)NULL
	);
	XtAddCallback(BHelpAbout,XmNactivateCallback,HandleCallback,this);

	// Create a parent for status bar and view
	MainForm=XtVaCreateManagedWidget(
		"mainForm",xmFormWidgetClass,MainWin,
		(char*)NULL
	);

	// Create status line
	StatusFrame=XtVaCreateManagedWidget(
		"statusFrame",xmFrameWidgetClass,MainForm,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNtopAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	StatusLabel=XtVaCreateManagedWidget(
		"statusLabel",xmLabelWidgetClass,StatusFrame,
		XmNalignment, XmALIGNMENT_BEGINNING,
		(char*)NULL
	);

	// Create the chess board view
	ViewFrame=XtVaCreateManagedWidget(
		"viewFrame",xmFrameWidgetClass,MainForm,
		XmNtopAttachment,XmATTACH_WIDGET,
		XmNtopWidget,StatusFrame,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	ViewArea=XtVaCreateManagedWidget(
		"viewArea",xmDrawingAreaWidgetClass,ViewFrame,
		XmNtopAttachment,XmATTACH_FORM,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	XtAddCallback(ViewArea,XmNexposeCallback,HandleCallback,this);
	XtAddCallback(ViewArea,XmNresizeCallback,HandleCallback,this);
	XtAddEventHandler(
		ViewArea,ButtonPressMask|ButtonMotionMask|ButtonReleaseMask|
		StructureNotifyMask,False,HandleEvent,this
	);
	XtVaGetValues(ViewArea,XmNwidth,&ViewWidth,(char*)NULL);
	XtVaGetValues(ViewArea,XmNheight,&ViewHeight,(char*)NULL);
	ViewWin=0;
	ViewGC=NULL;

	// Create dialog: load game
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage,True);
	LoadDialog=XmCreateFileSelectionDialog(TopLevel,(char*)"loadDialog",al,4);
	XtAddCallback(LoadDialog,XmNokCallback,HandleCallback,this);
	XtUnmanageChild(XmFileSelectionBoxGetChild(LoadDialog,XmDIALOG_HELP_BUTTON));

	// Create dialog: save game
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage, True);
	SaveDialog=XmCreateFileSelectionDialog(TopLevel,(char*)"saveDialog",al,4);
	XtAddCallback(SaveDialog,XmNokCallback,HandleCallback,this);
	XtUnmanageChild(XmFileSelectionBoxGetChild(SaveDialog,XmDIALOG_HELP_BUTTON));

	// Create dialog: file exists, overwrite?
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage, True);
	OverwriteDialog=XmCreateWarningDialog(TopLevel,(char*)"overwriteDialog",al,4);
	XtUnmanageChild(XmMessageBoxGetChild(OverwriteDialog,XmDIALOG_HELP_BUTTON));
	XtAddCallback(OverwriteDialog,XmNokCallback,HandleCallback,this);

	// Create dialog: error message
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage, True);
	ErrorBox=XmCreateWarningDialog(TopLevel,(char*)"errorBox",al,4);
	XtUnmanageChild(XmMessageBoxGetChild(ErrorBox,XmDIALOG_CANCEL_BUTTON));
	XtUnmanageChild(XmMessageBoxGetChild(ErrorBox,XmDIALOG_HELP_BUTTON));

	// Create dialog: list of moves
	ListDialogPopup=XtVaCreateWidget(
		"listDialog_popup",xmDialogShellWidgetClass,TopLevel,
		XmNvisual,DlgVsl,
		XmNdepth,DlgVslDepth,
		XmNcolormap,DlgCMap,
		(char*)NULL
	);
	ListDialog=XtVaCreateWidget(
		"listDialog",xmFormWidgetClass,ListDialogPopup,
		(char*)NULL
	);
	LDClose=XtVaCreateManagedWidget(
		"close",xmPushButtonWidgetClass,ListDialog,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	XtAddCallback(LDClose,XmNactivateCallback,HandleCallback,this);
	LDScroll=XtVaCreateManagedWidget(
		"scroll",xmScrolledWindowWidgetClass,ListDialog,
		XmNscrollingPolicy,XmAUTOMATIC,
		XmNscrollBarDisplayPolicy,XmAS_NEEDED,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNtopAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_WIDGET,
		XmNbottomWidget,LDClose,
		(char*)NULL
	);
	LDList=XtVaCreateManagedWidget(
		"list",xmLabelGadgetClass,LDScroll,
		XmNalignment,XmALIGNMENT_BEGINNING,
		(char*)NULL
	);

	// Create dialog: about
	xms=XmStringCreateLtoR((char*)AboutText,XmFONTLIST_DEFAULT_TAG);
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage,True);
	XtSetArg(al[4],XmNmessageString,xms);
	XtSetArg(al[5],XmNmessageAlignment,XmALIGNMENT_CENTER);
	AboutDialog=XmCreateMessageDialog(TopLevel,(char*)"aboutDialog",al,6);
	XmStringFree(xms);
	XtUnmanageChild(XmMessageBoxGetChild(AboutDialog,XmDIALOG_CANCEL_BUTTON));
	XtUnmanageChild(XmMessageBoxGetChild(AboutDialog,XmDIALOG_HELP_BUTTON));

	// Set main window areas
	XmMainWindowSetAreas(MainWin,MainMenu,NULL,NULL,NULL,MainForm);

	// Create chess machine
	Machine = new SilChessMachine();

	// Setup ray tracer
	RT.SetViewSize(ViewWidth,ViewHeight);
	RT.SetWorld(Machine);

	// Update all
	UpdateStatusBar();
	UpdateMovesList();
	UpdateView();
	UpdateDepthMenu();
}
Ejemplo n.º 9
0
Archivo: slock.c Proyecto: eepp/slock
static Lock *
lockscreen(Display *dpy, int screen) {
	char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
	unsigned int len;
	Lock *lock;
	XColor color;
	XSetWindowAttributes wa;
	Cursor invisible;
	int hue1, hue2;

	if(dpy == NULL || screen < 0)
		return NULL;

	lock = malloc(sizeof(Lock));
	if(lock == NULL)
		return NULL;

	lock->screen = screen;
	lock->root = RootWindow(dpy, lock->screen);

	/* init */
	wa.override_redirect = 1;
	lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
			0, DefaultDepth(dpy, lock->screen), CopyFromParent,
			DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
	
	/* locked color */
	hue1 = rand() % 360;
	gen_random_pastel(&color, hue1);
	XAllocColor(dpy, DefaultColormap(dpy, lock->screen), &color);
	lock->colors[0] = color.pixel;
	XSetWindowBackground(dpy, lock->win, lock->colors[0]);
	
	/* trying to unlock color */
	hue2 = hue1 + 180;
	if (hue2 >= 360) {
		hue2 -= 360;
	}
	gen_random_pastel(&color, hue2);
	XAllocColor(dpy, DefaultColormap(dpy, lock->screen), &color);
	lock->colors[1] = color.pixel;
	
	lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
	invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
	XDefineCursor(dpy, lock->win, invisible);
	XMapRaised(dpy, lock->win);
	for(len = 1000; len; len--) {
		if(XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
			GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
			break;
		usleep(1000);
	}
	if(running && (len > 0)) {
		for(len = 1000; len; len--) {
			if(XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
				== GrabSuccess)
				break;
			usleep(1000);
		}
	}

	running &= (len > 0);
	if(!running) {
		unlockscreen(dpy, lock);
		lock = NULL;
	}
	else 
		XSelectInput(dpy, lock->root, SubstructureNotifyMask);

	return lock;
}
Ejemplo n.º 10
0
int Init_X (int swidth, int sheight)
{
    XGCValues vals;
    Colormap TheColormap;
    XColor TheColor;
    int i;

    TheWidth = swidth ;
    TheHeight = sheight ;


    TheDisplay = XOpenDisplay("\0");
    TheRootWindow = DefaultRootWindow(TheDisplay);
    TheScreenNumber = DefaultScreen(TheDisplay); 
    TheDepth = DefaultDepth(TheDisplay, TheScreenNumber);
    if (TheDepth != 24) {
      printf("24 bit color not supported.\n") ;
      printf("Color function not likely to work.\n") ;
    }
    TheWindow = XCreateSimpleWindow(TheDisplay, TheRootWindow,
                        0, 0, TheWidth, TheHeight, 0, 0, 0);

    if (!TheWindow) return 0 ;

    ThePixmap = XCreatePixmap(TheDisplay, TheRootWindow, TheWidth, TheHeight, 
				TheDepth);

    if (!ThePixmap) return 0 ;

    TheDrawable = ThePixmap;

    
    XMapWindow(TheDisplay, TheWindow);
    XSelectInput(TheDisplay, TheWindow, ExposureMask |
					StructureNotifyMask |
					PointerMotionMask | 
					ButtonPressMask |
					KeyPressMask );




    /*
    TheWindowContext = XCreateGC(TheDisplay, TheWindow, 0, 0);
    // this is a bad idea ... see test t02.c for an example
    // of what can happen to the behavior of the event handler,
    //       int Handle_Events_X(int *px, int *py)
    // if you do this, you'll get runaway calls to Handle_Events
    // with the default condition being met and this produces
    // a great deal of tearing in the animation of t02.c
    */




    /* also a bad idea...same behavior as above
    vals.graphics_exposures = 1; // True
    */

    // so this is what you want :
    vals.graphics_exposures = 0; // False
    TheWindowContext = XCreateGC(TheDisplay, TheWindow,
                                 GCGraphicsExposures, &vals);
    if (!TheWindowContext) return 0;


    ThePixmapContext = XCreateGC(TheDisplay, ThePixmap, 0, 0);
    if (!ThePixmapContext) return 0;


    TheColormap = DefaultColormap(TheDisplay, TheScreenNumber);
    for(i = 0; i < 256; i++) {
	TheColor.green = TheColor.blue = TheColor.red = (i << 8) | i;
	TheColor.flags = DoRed | DoGreen | DoBlue;
	XAllocColor(TheDisplay, TheColormap, &TheColor);
	Grays[i] = TheColor.pixel;
    }
 

    TheFontInfo = XLoadQueryFont(TheDisplay, TheFont) ;
    XSetFont(TheDisplay, TheWindowContext, TheFontInfo->fid) ;




    //   XClearWindow(TheDisplay, TheWindow);
    //   XClearArea(TheDisplay, TheWindow, 0,0,0,0,False); // same as above
    XClearArea(TheDisplay, TheWindow, 0,0,0,0,True); 
                  // Does the boolean matter here?


    // most people expect a white piece of paper
    // with a black pencil
    Set_Color_Rgb_X (255,255,255) ; // white
    Clear_Buffer_X() ; // otherwise you can inherit garbage
    // from the parent window

    //    Set_Color_Rgb_X (255,0,255) ; // purple
    //    Fill_Rectangle_X(10,10,50,80) ;
    // above was just a test

    Copy_Buffer_X() ;
    XFlush(TheDisplay);  

    // XSync(TheDisplay, False) ; // seems unnecessary

    Set_Color_Rgb_X (0,0,0) ; // black pencil
    return 1 ;
}
Ejemplo n.º 11
0
        short    WPwcic(
        Window   px_id,
        short    x,
        short    y,
        short    bw,
        char    *fnam,
        short    cb,
        short    cf,
        WPICON **outptr)

/*      Create WPICON.
 *
 *      In: px_id  = Parent window X-id.
 *          x      = X-position.
 *          y      = Y-position.
 *          fnam   = Pixmap file.
 *          cb     = Not used.
 *          cf     = Not used.
 *
 *      Ut: *outptr = Ptr to a WPICON.
 *
 *      Felkod: WP1212 = Can't load pixmap file %s
 *              WP1292 = Can't malloc()
 *              WP1712 = XPM error code = %s
 *
 *      (C)microform ab 13/1/94 J. Kjellander
 *
 *      2007-06-17 Xpm, J.Kjellander
 *
 ********************************************************/

  {
    char                 errbuf[V3STRLEN];
    XSetWindowAttributes xwina;
    unsigned long        xwinm;
    unsigned int         dx,dy;
    int                  status;
    Window               xwin_id;
    Pixmap               icon_pixmap,icon_mask;
    XGCValues            values;
    XpmAttributes        attributes;
    WPICON              *icoptr;

/*
***Read the xpm-file and create a pixmap. Set attributes to XpmSize so
***that the size of the icon is returned.
***XpmColorError  =  1
***XpmSuccess     =  0
***XpmOpenFailed  = -1
***XpmFileInvalid = -2
***XpmNoMemory    = -3
***XpmColorFailed = -4
*/
    attributes.valuemask = XpmSize;

    status = XpmReadFileToPixmap(xdisp,px_id,fnam,&icon_pixmap,&icon_mask,&attributes);

    if ( status != XpmSuccess )
      {
      sprintf(errbuf,"%d",status);
      erpush("WP1712",errbuf);
      return(erpush("WP1212",fnam));
      }

    dx = attributes.width;
    dy = attributes.height;
/*
***Create the X window.
*/
    xwina.background_pixel  = WPgcol(cb);
    xwina.border_pixel      = WPgcol(WP_BGND2);
    xwina.override_redirect = True;
    xwina.save_under        = False;

    xwinm = ( CWBackPixel        | CWBorderPixel |
              CWOverrideRedirect | CWSaveUnder );  

    if ( bw > 0 )
      {
      dx += 2*bw + 2;
      dy += 2*bw + 2;
      }

    xwin_id = XCreateWindow(xdisp,px_id,x,y,dx,dy,bw,
                            DefaultDepth(xdisp,xscr),
                            InputOutput,CopyFromParent,xwinm,&xwina);
/*
***Input events.
*/
    if ( bw > 0 ) XSelectInput(xdisp,xwin_id,ButtonPressMask   |
                                             ButtonReleaseMask |
                                             EnterWindowMask   |
                                             LeaveWindowMask);
/*
***Create a WPICON.
*/
    if ( (icoptr=(WPICON *)v3mall(sizeof(WPICON),"WPwcic")) == NULL )
       return(erpush("WP1292",fnam));

    icoptr->id.w_id = (wpw_id)NULL;
    icoptr->id.p_id = (wpw_id)NULL;
    icoptr->id.x_id = xwin_id;

    icoptr->geo.x =  x;
    icoptr->geo.y =  y;
    icoptr->geo.dx =  (short)dx;
    icoptr->geo.dy =  (short)dy;
    icoptr->geo.bw =  bw;
    icoptr->pixmap = icon_pixmap;
    icoptr->mask   = icon_mask;
    icoptr->tt_str[0] = '\0';
/*
***Set up a private GC for this icon.
*/
    icoptr->gc = XCreateGC(xdisp,icoptr->id.x_id,0,&values);
    XSetClipMask(xdisp,icoptr->gc,icoptr->mask);

   *outptr = icoptr;
/*
***The end.
*/
    return(0);
  }
Ejemplo n.º 12
0
Archivo: x11_out.c Proyecto: erelh/gpac
/*
 * Setup X11 wnd System
 */
void
X11_SetupWindow (GF_VideoOutput * vout)
{
	X11VID ();
	const char *sOpt;
        Bool autorepeat, supported;

	xWindow->display = XOpenDisplay (NULL);
	xWindow->screennum = DefaultScreen (xWindow->display);
	xWindow->screenptr = DefaultScreenOfDisplay (xWindow->display);
	xWindow->visual = DefaultVisualOfScreen (xWindow->screenptr);
	xWindow->depth = DefaultDepth (xWindow->display, xWindow->screennum);

	{
		Float screenWidth = (Float)XWidthOfScreen(xWindow->screenptr);
		Float screenWidthIn = (Float)XWidthMMOfScreen(xWindow->screenptr) / 25.4f;
		Float screenHeight = (Float)XHeightOfScreen(xWindow->screenptr);
		Float screenHeightIn = (Float)XHeightMMOfScreen(xWindow->screenptr) / 25.4f;
		vout->dpi_x = (u32)(screenWidth / screenWidthIn);
		vout->dpi_y = (u32)(screenHeight / screenHeightIn);
	}

	switch (xWindow->depth) {
	case 8:
		xWindow->pixel_format = GF_PIXEL_GREYSCALE;
		break;
	case 16:
		xWindow->pixel_format = GF_PIXEL_RGB_565;
		break;
	case 24:
		xWindow->pixel_format = GF_PIXEL_RGB_32;
		break;
	default:
		xWindow->pixel_format = GF_PIXEL_GREYSCALE;
		break;
	}
	xWindow->bpp = xWindow->depth / 8;
	xWindow->bpp = xWindow->bpp == 3 ? 4 : xWindow->bpp;

xWindow->screennum=0;
	vout->max_screen_width = DisplayWidth(xWindow->display, xWindow->screennum);
	vout->max_screen_height = DisplayHeight(xWindow->display, xWindow->screennum);
	/*
	 * Full screen wnd
	 */
	xWindow->full_wnd = XCreateWindow (xWindow->display,
								   RootWindowOfScreen (xWindow->screenptr),
								   0, 0,
								   vout->max_screen_width,
								   vout->max_screen_height, 0,
								   xWindow->depth, InputOutput,
								   xWindow->visual, 0, NULL);

	XSelectInput(xWindow->display, xWindow->full_wnd,
					FocusChangeMask | ExposureMask | PointerMotionMask | ButtonReleaseMask | ButtonPressMask | KeyPressMask | KeyReleaseMask);

	if (!xWindow->par_wnd) {
		xWindow->w_width = 320;
		xWindow->w_height = 240;
		xWindow->wnd = XCreateWindow (xWindow->display,
					   RootWindowOfScreen(xWindow->screenptr), 0, 0,
					   xWindow->w_width, xWindow->w_height, 0,
					   xWindow->depth, InputOutput,
					   xWindow->visual, 0, NULL);
		XMapWindow (xWindow->display, (Window) xWindow->wnd);
	} else {
		XWindowAttributes pwa;
		XGetWindowAttributes(xWindow->display, xWindow->par_wnd, &pwa);
		xWindow->w_width = pwa.width;
		xWindow->w_height = pwa.height;
		xWindow->wnd = XCreateWindow (xWindow->display, xWindow->par_wnd, pwa.x, pwa.y,
					xWindow->w_width, xWindow->w_height, 0,
					   xWindow->depth, InputOutput,
					   xWindow->visual, 0, NULL);
		XMapWindow (xWindow->display, (Window) xWindow->wnd);
	}

	XSync(xWindow->display, False);
	XUnmapWindow (xWindow->display, (Window) xWindow->wnd);
	XSync(xWindow->display, False);
	old_handler = XSetErrorHandler(X11_BadAccess_ByPass);
	selectinput_err = 0;
	XSelectInput(xWindow->display, xWindow->wnd,
		FocusChangeMask | StructureNotifyMask | PropertyChangeMask | ExposureMask |
		PointerMotionMask | ButtonReleaseMask | ButtonPressMask |
		KeyPressMask | KeyReleaseMask);
	XSync(xWindow->display, False);
	XSetErrorHandler(old_handler);
	if (selectinput_err) {
	       	XSelectInput(xWindow->display, xWindow->wnd,
			StructureNotifyMask | PropertyChangeMask | ExposureMask |
			KeyPressMask | KeyReleaseMask);

		GF_LOG(GF_LOG_ERROR, GF_LOG_MMIO, ("[X11] Cannot select input focus\n"));
	}
	XSync(xWindow->display, False);
	XMapWindow (xWindow->display, (Window) xWindow->wnd);

	XSizeHints *Hints = XAllocSizeHints ();
	Hints->flags = PSize | PMinSize;
	Hints->min_width = 64;
	Hints->min_height = 64;
	Hints->max_height = 4096;
	Hints->max_width = 4096;
	if (!xWindow->par_wnd) {
		XSetWMNormalHints (xWindow->display, xWindow->wnd, Hints);
		XStoreName (xWindow->display, xWindow->wnd, "GPAC X11 Output");
	}
	Hints->x = 0;
	Hints->y = 0;
	Hints->flags |= USPosition;
	XSetWMNormalHints (xWindow->display, xWindow->full_wnd, Hints);

	autorepeat = 1;
	XkbSetDetectableAutoRepeat(xWindow->display, autorepeat, &supported);


	if (xWindow->init_flags & GF_TERM_WINDOW_NO_DECORATION) {
#define PROP_MOTIF_WM_HINTS_ELEMENTS 5
#define MWM_HINTS_DECORATIONS (1L << 1)
	  struct {
	    unsigned long flags;
	    unsigned long functions;
	    unsigned long decorations;
	    long inputMode;
	    unsigned long status;
	  } hints = {2, 0, 0, 0, 0};

	  hints.flags = MWM_HINTS_DECORATIONS;
	  hints.decorations = 0;

	  XChangeProperty(xWindow->display, xWindow->wnd, XInternAtom(xWindow->display,"_MOTIF_WM_HINTS", False), XInternAtom(xWindow->display, "_MOTIF_WM_HINTS", False), 32, PropModeReplace, (unsigned char *)&hints, PROP_MOTIF_WM_HINTS_ELEMENTS);

	}

	xWindow->the_gc = XCreateGC (xWindow->display, xWindow->wnd, 0, NULL);
	xWindow->use_shared_memory = 0;

#ifdef GPAC_HAS_X11_SHM
	sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "UseHardwareMemory");
        if (sOpt && !strcmp(sOpt, "yes")) {
	  int XShmMajor, XShmMinor;
	  Bool XShmPixmaps;
	  if (XShmQueryVersion(xWindow->display, &XShmMajor, &XShmMinor, &XShmPixmaps)) {
		xWindow->use_shared_memory = 1;
		GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using X11 Shared Memory\n"));
		if ((XShmPixmaps==True) && (XShmPixmapFormat(xWindow->display)==ZPixmap)) {
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] X11 Shared Memory Pixmaps available\n"));
		}
	  }
	}

#endif

#ifdef GPAC_HAS_X11_XV
	sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "DisableColorKeying");
	if (sOpt && !strcmp(sOpt, "yes")) {
		xWindow->xvport = X11_GetXVideoPort(vout, GF_PIXEL_I420, 0);
	} else {
		xWindow->xvport = X11_GetXVideoPort(vout, GF_PIXEL_I420, 1);
		if (xWindow->xvport<0) {
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Hardware has no color keying\n"));
			vout->overlay_color_key = 0;
			xWindow->xvport = X11_GetXVideoPort(vout, GF_PIXEL_I420, 0);
		} else {
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Hardware uses color key %08x\n", vout->overlay_color_key));
		}
	}
	if (xWindow->xvport>=0) {
		XvUngrabPort(xWindow->display, xWindow->xvport, CurrentTime );
		xWindow->xvport = -1;
		vout->yuv_pixel_format = X11_GetPixelFormat(xWindow->xv_pf_format);
		vout->Blit = X11_Blit;
		vout->hw_caps |= GF_VIDEO_HW_HAS_YUV_OVERLAY;
		GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using XV YUV Overlays\n"));

#ifdef GPAC_HAS_X11_SHM
		/*if user asked for YUV->RGB on offscreen, do it (it may crash the system)*/
		sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "EnableOffscreenYUV");
		if (sOpt && !strcmp(sOpt, "yes")) {
			vout->hw_caps |= GF_VIDEO_HW_HAS_YUV;
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using XV Offscreen YUV2RGB acceleration\n"));
		}
#endif
	}
#endif

	XSetWindowAttributes xsw;
	xsw.border_pixel = WhitePixel (xWindow->display, xWindow->screennum);
	xsw.background_pixel = BlackPixel (xWindow->display, xWindow->screennum);
	xsw.win_gravity = NorthWestGravity;
	XChangeWindowAttributes (xWindow->display, xWindow->wnd, CWBackPixel | CWWinGravity, &xsw);

	xsw.override_redirect = True;
	XChangeWindowAttributes(xWindow->display, xWindow->full_wnd,
				CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWWinGravity, &xsw);

	if (!xWindow->par_wnd) {
		xWindow->WM_DELETE_WINDOW = XInternAtom (xWindow->display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(xWindow->display, xWindow->wnd, &xWindow->WM_DELETE_WINDOW, 1);
	}


	{
		XEvent ev;
		long mask;

		memset (&ev, 0, sizeof (ev));
		ev.xclient.type = ClientMessage;
		ev.xclient.window = RootWindowOfScreen (xWindow->screenptr);
		ev.xclient.message_type = XInternAtom (xWindow->display, "KWM_KEEP_ON_TOP", False);
		ev.xclient.format = 32;
		ev.xclient.data.l[0] = xWindow->full_wnd;
		ev.xclient.data.l[1] = CurrentTime;
		mask = SubstructureRedirectMask;
		XSendEvent (xWindow->display,RootWindowOfScreen (xWindow->screenptr), False,
			    mask, &ev);
	}

	/*openGL setup*/
#ifdef GPAC_HAS_OPENGL
	{
	  int attribs[64];
	  int i, nb_bits;

	  sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "GLNbBitsPerComponent");
	  /* Most outputs are 24/32 bits these days, use 8 bits per channel instead of 5, works better on MacOS X */
	  nb_bits = sOpt ? atoi(sOpt) : 8;
          if (!sOpt){
             gf_modules_set_option((GF_BaseInterface *)vout, "Video", "GLNbBitsPerComponent", "8");
          }
	  i=0;
	  attribs[i++] = GLX_RGBA;
	  attribs[i++] = GLX_RED_SIZE;
	  attribs[i++] = nb_bits;
	  attribs[i++] = GLX_GREEN_SIZE;
	  attribs[i++] = nb_bits;
	  attribs[i++] = GLX_BLUE_SIZE;
	  attribs[i++] = nb_bits;
	  sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "GLNbBitsDepth");
	  nb_bits = sOpt ? atoi(sOpt) : 16;
          if (!sOpt){
             gf_modules_set_option((GF_BaseInterface *)vout, "Video", "GLNbBitsDepth", "16");
          }
	  if (nb_bits) {
		  attribs[i++] = GLX_DEPTH_SIZE;
		  attribs[i++] = nb_bits;
	  }
	  sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "UseGLDoubleBuffering");
          if (!sOpt){
             gf_modules_set_option((GF_BaseInterface *)vout, "Video", "UseGLDoubleBuffering", "yes");
          }
	  if (!sOpt || !strcmp(sOpt, "yes")) attribs[i++] = GLX_DOUBLEBUFFER;
	  attribs[i++] = None;
	  xWindow->glx_visualinfo = glXChooseVisual(xWindow->display, xWindow->screennum, attribs);
	  if (!xWindow->glx_visualinfo) {
		  GF_LOG(GF_LOG_ERROR, GF_LOG_MMIO, ("[X11] Error selecting GL display\n"));
	  }
	}

	xWindow->gl_wnd = XCreateWindow (xWindow->display, RootWindowOfScreen (xWindow->screenptr),
								   0,
								   0,
								   200,
								   200, 0,
								   xWindow->depth, InputOutput,
								   xWindow->visual, 0, NULL);

	XSync(xWindow->display, False);
	XUnmapWindow(xWindow->display, (Window) xWindow->gl_wnd);
	XSync(xWindow->display, False);

	sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "X113DOffscreenMode");
	if (!sOpt)
		gf_modules_set_option((GF_BaseInterface *)vout, "Video", "X113DOffscreenMode", "Pixmap");
        if (sOpt && !strcmp(sOpt, "Window")) {
		xWindow->offscreen_type = 1;
        } else if (sOpt && !strcmp(sOpt, "VisibleWindow")) {
		xWindow->offscreen_type = 2;
		XSetWMNormalHints (xWindow->display, xWindow->gl_wnd, Hints);
       } else if (sOpt && !strcmp(sOpt, "Pixmap")) {
		xWindow->offscreen_type = 0;
	} else {
		xWindow->offscreen_type = 0;
	}
#endif


	/*turn off xscreensaver*/
	X11_XScreenSaverState(xWindow, 0);

	xWindow->setup_done = 1;
	XFree (Hints);
}
Ejemplo n.º 13
0
XImage *
read_ppm_file(Display *disp, Colormap cmap, int depth, IOSTREAM *fd)
{ XImage *img;
  long here = Stell(fd);
  int c;
  int fmt, encoding;
  int width, height, bytes_per_line, scale=0;
  char *data;
  int allocdepth;
  int pad = XBitmapPad(disp);
  Visual *v = DefaultVisual(disp, DefaultScreen(disp));

  ncolours = nmapped = nfailed = 0;	/* statistics */
  assert(pad%8 == 0);

  if ( (c=Sgetc(fd)) != 'P' )
  { Sungetc(c, fd);
    return NULL;
  }

  if ( !cmap )
    cmap = DefaultColormap(disp, DefaultScreen(disp));

  c = Sgetc(fd);
  if ( c < '1' || c > '9' )
    goto errout;
  c -= '0';
  fmt      = ((c - 1) % 3) + 1;
  encoding = c - fmt;

  width = getNum(fd);
  height = getNum(fd);

  if ( fmt == PNM_PBM )
  { depth = 1;
  } else
  { scale = getNum(fd);
    if ( !depth )
      depth = DefaultDepth(disp, DefaultScreen(disp));
  }

  if ( width < 0 || height < 0 || scale < 0 )
    goto errout;

  allocdepth = (depth >= 24 ? 32 : depth);
  bytes_per_line = roundup((width*allocdepth+7)/8, pad/8);
  data = (char *)pceMalloc(height * bytes_per_line);

  img = XCreateImage(disp,
		     v,
		     depth,
		     fmt == PNM_PBM ? XYBitmap : ZPixmap,
		     0,
		     data,
		     width, height,
		     pad, bytes_per_line);
  if ( !img )
  { perror("XCreateImage");
    pceFree(data);
    goto errout;
  }
  img->bits_per_pixel = depth;

  switch(encoding)
  { int x, y;

    case PNM_ASCII:
    { switch(fmt)
      { case PNM_PBM:
	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int value = getNum(fd);

	      if ( value < 0 || value > 1 )
		goto errout;

	      XPutPixel(img, x, y, value);
	    }
	  }
	  break;
	case PNM_PGM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int g = getNum(fd);
	      unsigned long pixel;

	      if ( g < 0 || g > scale )
		goto errout;
	      if ( scale != 255 )
		g = rescale(g, scale, 255);

	      pixel = colourPixel(disp, depth, cmap, t, g, g, g);
	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	case PNM_PPM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int r = getNum(fd);
	      int g = getNum(fd);
	      int b = getNum(fd);
	      unsigned long pixel;

	      if ( r < 0 || r > scale ||
		   g < 0 || g > scale ||
		   b < 0 || b > scale )
		goto errout;

	      if ( scale != 255 )
	      { r = rescale(r, scale, 255);
		g = rescale(g, scale, 255);
		b = rescale(b, scale, 255);
	      }

	      pixel = colourPixel(disp, depth, cmap, t, r, g, b);

	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	break;
      }
      break;
    }
    case PNM_RAWBITS:
    { switch(fmt)
      { case PNM_PBM:
	{ int byte = 0;
	  int bit = 0;

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { if ( !bit )
	      { byte = Sgetc(fd);
		bit = 8;
	      }

	      bit--;
	      XPutPixel(img, x, y, (byte & (1<<bit)) ? 1 : 0);
	    }
	    bit = 0;			/* scanlines are byte-aligned */
	  }
	  break;
	}
	case PNM_PGM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int g;
	      unsigned long pixel;

	      if ( Sfeof(fd) || (g=Sgetc(fd)) > scale )
		goto errout;
	      if ( scale != 255 )
		g = rescale(g, scale, 255);

	      pixel = colourPixel(disp, depth, cmap, t, g, g, g);
	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	case PNM_PPM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int r, g, b;
	      unsigned long pixel;

	      if ( Sfeof(fd) ||
		   (r=Sgetc(fd)) > scale ||
		   (g=Sgetc(fd)) > scale ||
		   (b=Sgetc(fd)) > scale )
		goto errout;

	      if ( scale != 255 )
	      { r = rescale(r, scale, 255);
		g = rescale(g, scale, 255);
		b = rescale(b, scale, 255);
	      }

	      pixel = colourPixel(disp, depth, cmap, t, r, g, b);

	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	break;
      }
      break;
    }
    case PNM_RUNLEN:
    { int rlen = 0;
      unsigned long cpixel = NOPIXEL;

      switch(fmt)
      { case PNM_PGM:
	{ Table t = newTable(64);

	  DEBUG(NAME_pnm, Cprintf("Reading runlength encoded graymap\n"));

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { if ( rlen-- > 0 )
	      { XPutPixel(img, x, y, cpixel);
	      } else
	      { int g;

		if ( (g=Sgetc(fd)) > scale ||
		     (rlen = Sgetc(fd)) == EOF )
		  goto errout;
		rlen &= 0xff;
		if ( scale != 255 )
		  g = rescale(g, scale, 255);

		cpixel = colourPixel(disp, depth, cmap, t, g, g, g);
		XPutPixel(img, x, y, cpixel);
		rlen--;
	      }
	    }
	  }
	  freeTable(t);

	  break;
	}
	case PNM_PPM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { if ( rlen-- > 0 )
	      { XPutPixel(img, x, y, cpixel);
	      } else
	      { int r, g, b;

		if ( (r=Sgetc(fd)) > scale ||
		     (g=Sgetc(fd)) > scale ||
		     (b=Sgetc(fd)) > scale ||
		     (rlen = Sgetc(fd)) == EOF )
		  goto errout;

		rlen &= 0xff;
		if ( scale != 255 )
		{ r = rescale(r, scale, 255);
		  g = rescale(g, scale, 255);
		  b = rescale(b, scale, 255);
		}

		cpixel = colourPixel(disp, depth, cmap, t, r, g, b);

		XPutPixel(img, x, y, cpixel);
		rlen--;
	      }
	    }
	  }
	  freeTable(t);

	  break;
	}
      }
    }
  }

  DEBUG(NAME_ppm,
	Cprintf("PNM: Converted %dx%dx%d image, %d colours (%d mapped, %d failed)\n",
		width, height, depth, ncolours, nmapped, nfailed));

  return img;

errout:
  DEBUG(NAME_ppm,
	Cprintf("PNM: Format error, index = %d\n", Stell(fd)));
  Sseek(fd, here, SEEK_SET);
  return NULL;
}
Ejemplo n.º 14
0
bool GlxBackend::initDrawableConfigs()
{
    const int attribs[] = {
        GLX_RENDER_TYPE,    GLX_RGBA_BIT,
        GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT | GLX_PIXMAP_BIT,
        GLX_X_VISUAL_TYPE,  GLX_TRUE_COLOR,
        GLX_X_RENDERABLE,   True,
        GLX_CONFIG_CAVEAT,  int(GLX_DONT_CARE), // The ARGB32 visual is marked non-conformant in Catalyst
        GLX_RED_SIZE,       5,
        GLX_GREEN_SIZE,     5,
        GLX_BLUE_SIZE,      5,
        GLX_ALPHA_SIZE,     0,
        GLX_STENCIL_SIZE,   0,
        GLX_DEPTH_SIZE,     0,
        0
    };

    int count = 0;
    GLXFBConfig *configs = glXChooseFBConfig(display(), DefaultScreen(display()), attribs, &count);

    if (count < 1) {
        qCritical() << "Could not find any usable framebuffer configurations.";
        return false;
    }

    for (int i = 0; i <= 32; i++) {
        fbcdrawableinfo[i].fbconfig            = NULL;
        fbcdrawableinfo[i].bind_texture_format = 0;
        fbcdrawableinfo[i].texture_targets     = 0;
        fbcdrawableinfo[i].y_inverted          = 0;
        fbcdrawableinfo[i].mipmap              = 0;
    }

    // Find the first usable framebuffer configuration for each depth.
    // Single-buffered ones will appear first in the list.
    const int depths[] = { 15, 16, 24, 30, 32 };
    for (unsigned int i = 0; i < sizeof(depths) / sizeof(depths[0]); i++) {
        const int depth = depths[i];

        for (int j = 0; j < count; j++) {
            int alpha_size, buffer_size;
            glXGetFBConfigAttrib(display(), configs[j], GLX_ALPHA_SIZE,  &alpha_size);
            glXGetFBConfigAttrib(display(), configs[j], GLX_BUFFER_SIZE, &buffer_size);

            if (buffer_size != depth && (buffer_size - alpha_size) != depth)
                continue;

            if (depth == 32 && alpha_size != 8)
                continue;

            XVisualInfo *vi = glXGetVisualFromFBConfig(display(), configs[j]);
            if (vi == NULL)
                continue;

            int visual_depth = vi->depth;
            XFree(vi);

            if (visual_depth != depth)
                continue;

            int bind_rgb, bind_rgba;
            glXGetFBConfigAttrib(display(), configs[j], GLX_BIND_TO_TEXTURE_RGBA_EXT, &bind_rgba);
            glXGetFBConfigAttrib(display(), configs[j], GLX_BIND_TO_TEXTURE_RGB_EXT,  &bind_rgb);

            // Skip this config if it cannot be bound to a texture
            if (!bind_rgb && !bind_rgba)
                continue;

            int texture_format;
            if (depth == 32)
                texture_format = bind_rgba ? GLX_TEXTURE_FORMAT_RGBA_EXT : GLX_TEXTURE_FORMAT_RGB_EXT;
            else
                texture_format = bind_rgb ? GLX_TEXTURE_FORMAT_RGB_EXT : GLX_TEXTURE_FORMAT_RGBA_EXT;

            int y_inverted, texture_targets;
            glXGetFBConfigAttrib(display(), configs[j], GLX_BIND_TO_TEXTURE_TARGETS_EXT, &texture_targets);
            glXGetFBConfigAttrib(display(), configs[j], GLX_Y_INVERTED_EXT, &y_inverted);

            fbcdrawableinfo[depth].fbconfig            = configs[j];
            fbcdrawableinfo[depth].bind_texture_format = texture_format;
            fbcdrawableinfo[depth].texture_targets     = texture_targets;
            fbcdrawableinfo[depth].y_inverted          = y_inverted;
            fbcdrawableinfo[depth].mipmap              = 0;
            break;
        }
    }

    if (count)
        XFree(configs);

    if (fbcdrawableinfo[DefaultDepth(display(), DefaultScreen(display()))].fbconfig == NULL) {
        qCritical() << "Could not find a framebuffer configuration for the default depth.";
        return false;
    }

    if (fbcdrawableinfo[32].fbconfig == NULL) {
        qCritical() << "Could not find a framebuffer configuration for depth 32.";
        return false;
    }

    for (int i = 0; i <= 32; i++) {
        if (fbcdrawableinfo[i].fbconfig == NULL)
            continue;

        int vis_drawable = 0;
        glXGetFBConfigAttrib(display(), fbcdrawableinfo[i].fbconfig, GLX_VISUAL_ID, &vis_drawable);

        qDebug() << "Drawable visual (depth " << i << "): 0x" << QString::number(vis_drawable, 16);
    }

    return true;
}
Ejemplo n.º 15
0
static void
setup(void)
{
	int x, y;
	XSetWindowAttributes swa;
	XIM xim;
#ifdef XINERAMA
	XineramaScreenInfo *info;
	Window w, pw, dw, *dws;
	XWindowAttributes wa;
	int a, j, di, n, i = 0, area = 0;
	unsigned int du;
#endif

	/* init appearance */
	scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
	scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
	scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
	scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
	scheme[SchemeOut].bg = drw_clr_create(drw, outbgcolor);
	scheme[SchemeOut].fg = drw_clr_create(drw, outfgcolor);

	clip = XInternAtom(dpy, "CLIPBOARD",   False);
	utf8 = XInternAtom(dpy, "UTF8_STRING", False);

	/* calculate menu geometry */
	bh = drw->fonts[0]->h + 2;
	lines = MAX(lines, 0);
	mh = (lines + 1) * bh;
#ifdef XINERAMA
	if ((info = XineramaQueryScreens(dpy, &n))) {
		XGetInputFocus(dpy, &w, &di);
		if (mon != -1 && mon < n)
			i = mon;
		else if (w != root && w != PointerRoot && w != None) {
			/* find top-level window containing current input focus */
			do {
				if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
					XFree(dws);
			} while (w != root && w != pw);
			/* find xinerama screen with which the window intersects most */
			if (XGetWindowAttributes(dpy, pw, &wa))
				for (j = 0; j < n; j++)
					if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
						area = a;
						i = j;
					}
		}
		/* no focused window is on screen, so use pointer location instead */
		if (mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
			for (i = 0; i < n; i++)
				if (INTERSECT(x, y, 1, 1, info[i]))
					break;

		x = info[i].x_org;
		y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
		mw = info[i].width;
		XFree(info);
	} else
#endif
	{
		x = 0;
		y = topbar ? 0 : sh - mh;
		mw = sw;
	}
	promptw = (prompt && *prompt) ? TEXTW(prompt) : 0;
	inputw = MIN(inputw, mw/3);
	fuzzymatch();

	/* create menu window */
	swa.override_redirect = True;
	swa.background_pixel = scheme[SchemeNorm].bg->pix;
	swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
	win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
	                    DefaultDepth(dpy, screen), CopyFromParent,
	                    DefaultVisual(dpy, screen),
	                    CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);

	/* open input methods */
	xim = XOpenIM(dpy, NULL, NULL, NULL);
	xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
	                XNClientWindow, win, XNFocusWindow, win, NULL);

	XMapRaised(dpy, win);
	drw_resize(drw, mw, mh);
	drawmenu();
}
Ejemplo n.º 16
0
/**
 * Initialize the x11 grab device demuxer (public device demuxer API).
 *
 * @param s1 Context from avformat core
 * @param ap Parameters from avformat core
 * @return <ul>
 *          <li>AVERROR(ENOMEM) no memory left</li>
 *          <li>AVERROR(EIO) other failure case</li>
 *          <li>0 success</li>
 *         </ul>
 */
static int
x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
{
    struct x11_grab *x11grab = s1->priv_data;
    Display *dpy;
    AVStream *st = NULL;
    enum PixelFormat input_pixfmt;
    XImage *image;
    int x_off = 0;
    int y_off = 0;
    int screen;
    int use_shm;
    char *param, *offset;
    int ret = 0;
    AVRational framerate;

    param = av_strdup(s1->filename);
    offset = strchr(param, '+');
    if (offset) {
        sscanf(offset, "%d,%d", &x_off, &y_off);
        x11grab->draw_mouse = !strstr(offset, "nomouse");
        *offset= 0;
    }

    if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {
        av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
        goto out;
    }
    if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {
        av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);
        goto out;
    }
    av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
           s1->filename, param, x_off, y_off, x11grab->width, x11grab->height);

    dpy = XOpenDisplay(param);
    if(!dpy) {
        av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
        ret = AVERROR(EIO);
        goto out;
    }

    st = avformat_new_stream(s1, NULL);
    if (!st) {
        ret = AVERROR(ENOMEM);
        goto out;
    }
    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    screen = DefaultScreen(dpy);

    if (x11grab->follow_mouse) {
        int screen_w, screen_h;
        Window w;

        screen_w = DisplayWidth(dpy, screen);
        screen_h = DisplayHeight(dpy, screen);
        XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);
        x_off -= x11grab->width / 2;
        y_off -= x11grab->height / 2;
        x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
        y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
        av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);
    }

    use_shm = XShmQueryExtension(dpy);
    av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");

    if(use_shm) {
        int scr = XDefaultScreen(dpy);
        image = XShmCreateImage(dpy,
                                DefaultVisual(dpy, scr),
                                DefaultDepth(dpy, scr),
                                ZPixmap,
                                NULL,
                                &x11grab->shminfo,
                                x11grab->width, x11grab->height);
        x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
                                        image->bytes_per_line * image->height,
                                        IPC_CREAT|0777);
        if (x11grab->shminfo.shmid == -1) {
            av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
            ret = AVERROR(ENOMEM);
            goto out;
        }
        x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
        x11grab->shminfo.readOnly = False;

        if (!XShmAttach(dpy, &x11grab->shminfo)) {
            av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
            /* needs some better error subroutine :) */
            ret = AVERROR(EIO);
            goto out;
        }
    } else {
        image = XGetImage(dpy, RootWindow(dpy, screen),
                          x_off,y_off,
                          x11grab->width, x11grab->height,
                          AllPlanes, ZPixmap);
    }

    switch (image->bits_per_pixel) {
    case 8:
        av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
        input_pixfmt = PIX_FMT_PAL8;
        break;
    case 16:
        if (       image->red_mask   == 0xf800 &&
                   image->green_mask == 0x07e0 &&
                   image->blue_mask  == 0x001f ) {
            av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
            input_pixfmt = PIX_FMT_RGB565;
        } else if (image->red_mask   == 0x7c00 &&
                   image->green_mask == 0x03e0 &&
                   image->blue_mask  == 0x001f ) {
            av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
            input_pixfmt = PIX_FMT_RGB555;
        } else {
            av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
            ret = AVERROR(EIO);
            goto out;
        }
        break;
    case 24:
        if (        image->red_mask   == 0xff0000 &&
                    image->green_mask == 0x00ff00 &&
                    image->blue_mask  == 0x0000ff ) {
            input_pixfmt = PIX_FMT_BGR24;
        } else if ( image->red_mask   == 0x0000ff &&
                    image->green_mask == 0x00ff00 &&
                    image->blue_mask  == 0xff0000 ) {
            input_pixfmt = PIX_FMT_RGB24;
        } else {
            av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
            ret = AVERROR(EIO);
            goto out;
        }
        break;
    case 32:
        input_pixfmt = PIX_FMT_RGB32;
        break;
    default:
        av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
        ret = AVERROR(EINVAL);
        goto out;
    }

    x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
    x11grab->dpy = dpy;
    x11grab->time_base  = (AVRational){framerate.den, framerate.num};
    x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
    x11grab->x_off = x_off;
    x11grab->y_off = y_off;
    x11grab->image = image;
    x11grab->use_shm = use_shm;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codec->codec_id = CODEC_ID_RAWVIDEO;
    st->codec->width  = x11grab->width;
    st->codec->height = x11grab->height;
    st->codec->pix_fmt = input_pixfmt;
    st->codec->time_base = x11grab->time_base;
    st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;

out:
    return ret;
}
Ejemplo n.º 17
0
Visual *XAbstractGui::GetBestVisual(Display *dpy, int *vClass, int *depth)
{
    int default_depth;
    XVisualInfo vTemplate;
    XVisualInfo *visualList = nullptr;
    Visual *visual = nullptr;
    int nrOfVisuals;

    vTemplate.screen = DefaultScreen(dpy);
    default_depth = DefaultDepth(dpy, vTemplate.screen);

    switch (default_depth)
    {
        case 8:
            *vClass = vTemplate.c_class  = PseudoColor;
            visualList = XGetVisualInfo(dpy,
                                        VisualScreenMask | VisualClassMask,
                                        &vTemplate, &nrOfVisuals);

            if (nrOfVisuals > 0)
            {
                *depth = visualList[0].depth;
                visual = visualList[0].visual;
            }
            else
            {
                *vClass = vTemplate.c_class = TrueColor;
                visualList = XGetVisualInfo(dpy,
                                            VisualScreenMask | VisualClassMask,
                                            &vTemplate, &nrOfVisuals);

                if (nrOfVisuals > 0)
                {
                    *depth = visualList[0].depth;
                    visual = visualList[0].visual;
                }
                else
                {
                    *vClass = vTemplate.c_class  = GrayScale;
                    visualList = XGetVisualInfo(dpy, VisualScreenMask |
                                                VisualClassMask, &vTemplate,
                                                &nrOfVisuals);

                    if (nrOfVisuals > 0)
                    {
                        *depth = visualList[0].depth;
                        visual = visualList[0].visual;
                    }
                }
            }

            break;

        case 16:
        case 24:
        case 32:
            *vClass = vTemplate.c_class  = TrueColor;
            visualList = XGetVisualInfo(dpy,
                                        VisualScreenMask | VisualClassMask,
                                        &vTemplate, &nrOfVisuals);

            if (nrOfVisuals > 0)
            {
                *depth = visualList[0].depth;
                visual = visualList[0].visual;
            }

            break;
    }

    XFree(visualList);
    return visual;
}
Ejemplo n.º 18
0
int UISymbolEdit(DBObjTable *symbols, int symbolType) {
    int symNum;
    static int changed, save;
    static Widget dShell = NULL;
    XmString string;
    UISymbol **editSymbols;
    DBObjRecord *symRecord;

    if (dShell == NULL) {
        char symString[20];
        int depth;
        Pixel foreground, background;
        XGCValues xgcv;
        GC gc;
        Widget mainForm, scrolledW, list, label, button, text, foreMenu, backMenu, rowCol, symMenu;
        Pixmap markerPixmap, labelPixmap;

        dShell = UIDialogForm((char *) "Symbol Edit");
        mainForm = UIDialogFormGetMainForm(dShell);
        scrolledW = XtVaCreateManagedWidget("UISymScrolledWindow", xmScrolledWindowWidgetClass, mainForm,
                                            XmNtopAttachment, XmATTACH_FORM,
                                            XmNleftAttachment, XmATTACH_FORM,
                                            XmNrightAttachment, XmATTACH_FORM,
                                            NULL);
        list = XtVaCreateManagedWidget(UISymListName + 1, xmListWidgetClass, scrolledW,
                                       XmNvisibleItemCount, 6,
                                       XmNselectionPolicy, XmBROWSE_SELECT,
                                       XmNscrollBarDisplayPolicy, XmSTATIC,
                                       NULL);
        XtAddCallback(list, XmNbrowseSelectionCallback, (XtCallbackProc) _UISymbolListSelectCBK, dShell);
        string = XmStringCreate((char *) "Symbol", UICharSetNormal);
        label = XtVaCreateManagedWidget("UISymbolLabel", xmLabelWidgetClass, mainForm,
                                        XmNtopAttachment, XmATTACH_WIDGET,
                                        XmNtopWidget, scrolledW,
                                        XmNleftAttachment, XmATTACH_FORM,
                                        XmNlabelString, string,
                                        NULL);
        XmStringFree(string);
        string = XmStringCreate((char *) "Load Names", UICharSetNormal);
        button = XtVaCreateManagedWidget(UISymLoadNamesButtonName + 1, xmPushButtonWidgetClass, mainForm,
                                         XmNtopAttachment, XmATTACH_WIDGET,
                                         XmNtopWidget, label,
                                         XmNrightAttachment, XmATTACH_FORM,
                                         XmNlabelString, string,
                                         NULL);
        XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) _UISymbolLoadNamesCBK, list);
        XmStringFree(string);
        text = XtVaCreateManagedWidget(UISymTextFieldName + 1, xmTextFieldWidgetClass, mainForm,
                                       XmNtopAttachment, XmATTACH_WIDGET,
                                       XmNtopWidget, label,
                                       XmNleftAttachment, XmATTACH_FORM,
                                       XmNrightAttachment, XmATTACH_WIDGET,
                                       XmNrightWidget, button,
                                       XmNrightOffset, 5,
                                       NULL);
        XtAddCallback(text, XmNvalueChangedCallback, (XtCallbackProc) _UISymbolTextValueChangedCBK, list);
        XtAddCallback(text, XmNvalueChangedCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK, &changed);

        foreMenu = XmCreatePulldownMenu(mainForm, (char *) "UISymForegroundMenuPane", NULL, 0);
        backMenu = XmCreatePulldownMenu(mainForm, (char *) "UISymBackgroundMenuPane", NULL, 0);

        for (symNum = 0; symNum < UIColorNum(UIColorStandard); symNum++) {
            foreground = UIColor(UIColorStandard, symNum);
            _UISymSetButtonString(symString, symNum);
            string = XmStringCreate(UIStandardColorName(symNum), UICharSetNormal);
            button = XtVaCreateManagedWidget(symString + 1, xmPushButtonWidgetClass, foreMenu,
                                             XmNuserData, symNum,
                                             XmNforeground, foreground,
                                             XmNlabelString, string,
                                             NULL);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) _UISymbolSetForegroundCBK, text);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK, &changed);
            button = XtVaCreateManagedWidget(symString + 1, xmPushButtonWidgetClass, backMenu,
                                             XmNuserData, symNum,
                                             XmNforeground, foreground,
                                             XmNlabelString, string,
                                             NULL);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) _UISymbolSetBackgroundCBK, text);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK, &changed);
            XmStringFree(string);
        }

        string = XmStringCreate((char *) "Foreground:", UICharSetNormal);
        foreMenu = XtVaCreateManagedWidget(UISymForegroundMenuName + 1, xmRowColumnWidgetClass, mainForm,
                                           XmNtopAttachment, XmATTACH_WIDGET,
                                           XmNtopWidget, text,
                                           XmNrightAttachment, XmATTACH_FORM,
                                           XmNsubMenuId, foreMenu,
                                           XmNlabelString, string,
                                           XmNrowColumnType, XmMENU_OPTION,
                                           XmNtraversalOn, false,
                                           NULL);
        XmStringFree(string);
        string = XmStringCreate((char *) "Background:", UICharSetNormal);
        backMenu = XtVaCreateManagedWidget(UISymBackgroundMenuName + 1, xmRowColumnWidgetClass, mainForm,
                                           XmNtopAttachment, XmATTACH_WIDGET,
                                           XmNtopWidget, foreMenu,
                                           XmNrightAttachment, XmATTACH_FORM,
                                           XmNsubMenuId, backMenu,
                                           XmNlabelString, string,
                                           XmNrowColumnType, XmMENU_OPTION,
                                           XmNtraversalOn, false,
                                           NULL);
        rowCol = XtVaCreateManagedWidget("UISymbolRowCol", xmRowColumnWidgetClass, mainForm,
                                         XmNtopAttachment, XmATTACH_WIDGET,
                                         XmNtopWidget, backMenu,
                                         XmNrightAttachment, XmATTACH_FORM,
                                         XmNbottomAttachment, XmATTACH_FORM,
                                         NULL);
        XtVaGetValues(mainForm, XmNforeground, &foreground, XmNbackground, &background, NULL);
        xgcv.foreground = foreground;
        xgcv.background = background;
        xgcv.fill_style = FillTiled;
        gc = XCreateGC(XtDisplay(UITopLevel()), XtWindow(UITopLevel()), GCForeground | GCBackground | GCFillStyle,
                       &xgcv);

        symMenu = XmCreatePulldownMenu(rowCol, (char *) "UISymShadeMenuPane", NULL, 0);
        depth = DefaultDepth (XtDisplay(UITopLevel()), DefaultScreen(XtDisplay(UITopLevel())));
        for (symNum = 0; (xgcv.tile = UIPattern(symNum, foreground, background)) != (Pixmap) NULL; symNum++) {
            labelPixmap = XCreatePixmap(XtDisplay(UITopLevel()), XtWindow(UITopLevel()), 96, 24, depth);
            XChangeGC(XtDisplay(UITopLevel()), gc, GCTile, &xgcv);
            XFillRectangle(XtDisplay(UITopLevel()), labelPixmap, gc, 0, 0, 96, 24);
            XFreePixmap(XtDisplay(UITopLevel()), xgcv.tile);

            _UISymSetButtonString(symString, symNum);
            button = XtVaCreateManagedWidget(symString + 1, xmPushButtonGadgetClass, symMenu,
                                             XmNuserData, symNum,
                                             XmNlabelType, XmPIXMAP,
                                             XmNlabelPixmap, labelPixmap,
                                             NULL);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) _UISymbolSetStyleCBK, text);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK, &changed);
        }
        string = XmStringCreate((char *) "Shade:", UICharSetNormal);
        symMenu = XtVaCreateWidget(UISymShadeMenuName + 1, xmRowColumnWidgetClass, rowCol,
                                   XmNsubMenuId, symMenu,
                                   XmNlabelString, string,
                                   XmNrowColumnType, XmMENU_OPTION,
                                   XmNtraversalOn, false,
                                   NULL);
        XmStringFree(string);

        xgcv.foreground = background;
        xgcv.fill_style = FillSolid;
        XChangeGC(XtDisplay(UITopLevel()), gc, GCForeground | GCFillStyle, &xgcv);
        symMenu = XmCreatePulldownMenu(rowCol, (char *) "UISymMarkerMenuPane", NULL, 0);
        depth = DefaultDepth (XtDisplay(UITopLevel()), DefaultScreen(XtDisplay(UITopLevel())));
        for (symNum = 0; (markerPixmap = UIMarker(symNum, foreground, background)) != (Pixmap) NULL; symNum++) {
            labelPixmap = XCreatePixmap(XtDisplay(UITopLevel()), XtWindow(UITopLevel()), 96, 24, depth);
            XFillRectangle(XtDisplay(UITopLevel()), labelPixmap, gc, 0, 0, 96, 24);
            XCopyArea(XtDisplay(UITopLevel()), markerPixmap, labelPixmap, gc, 0, 0, 11, 11, 42, 6);
            XFreePixmap(XtDisplay(UITopLevel()), markerPixmap);
            _UISymSetButtonString(symString, symNum);
            button = XtVaCreateManagedWidget(symString + 1, xmPushButtonGadgetClass, symMenu,
                                             XmNuserData, symNum,
                                             XmNlabelType, XmPIXMAP,
                                             XmNlabelPixmap, labelPixmap,
                                             NULL);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) _UISymbolSetStyleCBK, text);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK, &changed);
        }
        string = XmStringCreate((char *) "Marker:", UICharSetNormal);
        symMenu = XtVaCreateWidget(UISymMarkerMenuName + 1, xmRowColumnWidgetClass, rowCol,
                                   XmNsubMenuId, symMenu,
                                   XmNlabelString, string,
                                   XmNrowColumnType, XmMENU_OPTION,
                                   XmNtraversalOn, false,
                                   NULL);
        XmStringFree(string);

        symMenu = XmCreatePulldownMenu(rowCol, (char *) "UISymLineMenuPane", NULL, 0);
        depth = DefaultDepth (XtDisplay(UITopLevel()), DefaultScreen(XtDisplay(UITopLevel())));
        for (symNum = 0; symNum < 12; symNum++) {
            labelPixmap = XCreatePixmap(XtDisplay(UITopLevel()), XtWindow(UITopLevel()), 96, 24, depth);
            xgcv.foreground = background;
            xgcv.fill_style = FillSolid;
            XChangeGC(XtDisplay(UITopLevel()), gc, GCForeground | GCFillStyle, &xgcv);
            XFillRectangle(XtDisplay(UITopLevel()), labelPixmap, gc, 0, 0, 96, 24);
            xgcv.line_width = symNum & 0x03;
            switch (symNum >> 0x02) {
                case 0:
                    xgcv.line_style = LineSolid;
                    break;
                case 1:
                    xgcv.line_style = LineOnOffDash;
                    break;
                case 2:
                    xgcv.line_style = LineDoubleDash;
                    break;
            }
            xgcv.foreground = foreground;
            xgcv.background = UIColor(UIColorStandard, 0);
            XChangeGC(XtDisplay(UITopLevel()), gc, GCForeground | GCBackground | GCLineWidth | GCLineStyle, &xgcv);
            XDrawLine(XtDisplay(UITopLevel()), labelPixmap, gc, 0, 12, 96, 12);
            _UISymSetButtonString(symString, symNum);
            button = XtVaCreateManagedWidget(symString + 1, xmPushButtonGadgetClass, symMenu,
                                             XmNuserData, symNum,
                                             XmNlabelType, XmPIXMAP,
                                             XmNlabelPixmap, labelPixmap,
                                             NULL);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) _UISymbolSetStyleCBK, text);
            XtAddCallback(button, XmNactivateCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK, &changed);
        }
        string = XmStringCreate((char *) "Line:", UICharSetNormal);
        symMenu = XtVaCreateWidget(UISymLineMenuName + 1, xmRowColumnWidgetClass, rowCol,
                                   XmNsubMenuId, symMenu,
                                   XmNlabelString, string,
                                   XmNrowColumnType, XmMENU_OPTION,
                                   XmNtraversalOn, false,
                                   NULL);
        XmStringFree(string);
        XtAddCallback(UIDialogFormGetOkButton(dShell), XmNactivateCallback, (XtCallbackProc) UIAuxSetBooleanTrueCBK,
                      &save);
    }
Ejemplo n.º 19
0
	int32_t run(Filesystem* fs, ConfigSettings* cs)
	{
		// Create main window
		XInitThreads();
		XSetErrorHandler(x11_error_handler);
		m_x11_display = XOpenDisplay(NULL);

		CE_ASSERT(m_x11_display != NULL, "Unable to open X11 display");

		int screen = DefaultScreen(m_x11_display);
		int depth = DefaultDepth(m_x11_display, screen);
		Visual* visual = DefaultVisual(m_x11_display, screen);

		m_x11_parent_window = (m_parent_window_handle == 0) ? RootWindow(m_x11_display, screen) :
			(Window) m_parent_window_handle;

		// Create main window
		XSetWindowAttributes win_attribs;
		win_attribs.background_pixmap = 0;
		win_attribs.border_pixel = 0;
		win_attribs.event_mask = FocusChangeMask
			| StructureNotifyMask 
			| KeyPressMask
			| KeyReleaseMask 
			| ButtonPressMask 
			| ButtonReleaseMask
			| PointerMotionMask;

		m_x11_window = XCreateWindow(m_x11_display,
			m_x11_parent_window,
			0, 0,
			cs->window_width,
			cs->window_height,
			0,
			depth,
			InputOutput,
			visual,
			CWBorderPixel | CWEventMask,
			&win_attribs
		);
		CE_ASSERT(m_x11_window != None, "Unable to create X window");

		// Do we have detectable autorepeat?
		Bool detectable;
		m_x11_detectable_autorepeat = (bool) XkbSetDetectableAutoRepeat(m_x11_display, true, &detectable);

		// Build hidden cursor
		Pixmap bm_no;
		XColor black, dummy;
		Colormap colormap;
		static char no_data[] = { 0, 0, 0, 0, 0, 0, 0, 0 };

		colormap = XDefaultColormap(m_x11_display, screen);
		XAllocNamedColor(m_x11_display, colormap, "black", &black, &dummy);
		bm_no = XCreateBitmapFromData(m_x11_display, m_x11_window, no_data, 8, 8);
		m_x11_hidden_cursor = XCreatePixmapCursor(m_x11_display, bm_no, bm_no, &black, &black, 0, 0);

		m_wm_delete_message = XInternAtom(m_x11_display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(m_x11_display, m_x11_window, &m_wm_delete_message, 1);

		oswindow_set_window(m_x11_display, m_x11_window);
		bgfx::x11SetDisplayWindow(m_x11_display, m_x11_window);
		XMapRaised(m_x11_display, m_x11_window);

		// Get screen configuration
		m_screen_config = XRRGetScreenInfo(m_x11_display, RootWindow(m_x11_display, screen));

		Rotation rr_old_rot;
		const SizeID rr_old_sizeid = XRRConfigCurrentConfiguration(m_screen_config, &rr_old_rot);

		// Start main thread
		MainThreadArgs mta;
		mta.fs = fs;
		mta.cs = cs;

		Thread main_thread;
		main_thread.start(func, &mta);

		while (!s_exit)
		{
			pump_events();
		}

		main_thread.stop();

		// Restore previous screen configuration if changed
		Rotation rr_cur_rot;
		const SizeID rr_cur_sizeid = XRRConfigCurrentConfiguration(m_screen_config, &rr_cur_rot);

		if (rr_cur_rot != rr_old_rot || rr_cur_sizeid != rr_old_sizeid)
		{
			XRRSetScreenConfig(m_x11_display,
				m_screen_config,
				RootWindow(m_x11_display, screen),
				rr_old_sizeid,
				rr_old_rot,
				CurrentTime);
		}
		XRRFreeScreenConfigInfo(m_screen_config);

		XDestroyWindow(m_x11_display, m_x11_window);
		XCloseDisplay(m_x11_display);
		return EXIT_SUCCESS;
	}
Ejemplo n.º 20
0
static BackgroundTexture *parseTexture(RContext * rc, char *text)
{
	BackgroundTexture *texture = NULL;
	WMPropList *texarray;
	WMPropList *val;
	int count;
	char *tmp;
	char *type;

#define GETSTRORGOTO(val, str, i, label) \
    val = WMGetFromPLArray(texarray, i);\
    if (!WMIsPLString(val)) {\
    wwarning("could not parse texture %s", text);\
    goto label;\
    }\
    str = WMGetFromPLString(val)

	texarray = WMCreatePropListFromDescription(text);
	if (!texarray || !WMIsPLArray(texarray)
	    || (count = WMGetPropListItemCount(texarray)) < 2) {

		wwarning("could not parse texture %s", text);
		if (texarray)
			WMReleasePropList(texarray);
		return NULL;
	}

	texture = wmalloc(sizeof(BackgroundTexture));

	GETSTRORGOTO(val, type, 0, error);

	if (strcasecmp(type, "solid") == 0) {
		XColor color;
		Pixmap pixmap;

		texture->solid = 1;

		GETSTRORGOTO(val, tmp, 1, error);

		if (!XParseColor(dpy, DefaultColormap(dpy, scr), tmp, &color)) {
			wwarning("could not parse color %s in texture %s", tmp, text);
			goto error;
		}
		XAllocColor(dpy, DefaultColormap(dpy, scr), &color);

		pixmap = XCreatePixmap(dpy, root, 8, 8, DefaultDepth(dpy, scr));
		XSetForeground(dpy, DefaultGC(dpy, scr), color.pixel);
		XFillRectangle(dpy, pixmap, DefaultGC(dpy, scr), 0, 0, 8, 8);

		texture->pixmap = pixmap;
		texture->color = color;
		texture->width = 8;
		texture->height = 8;
	} else if (strcasecmp(type, "vgradient") == 0
		   || strcasecmp(type, "dgradient") == 0 || strcasecmp(type, "hgradient") == 0) {
		XColor color;
		RColor color1, color2;
		RImage *image;
		Pixmap pixmap;
		RGradientStyle gtype;
		int iwidth, iheight;

		GETSTRORGOTO(val, tmp, 1, error);

		if (!XParseColor(dpy, DefaultColormap(dpy, scr), tmp, &color)) {
			wwarning("could not parse color %s in texture %s", tmp, text);
			goto error;
		}

		color1.red = color.red >> 8;
		color1.green = color.green >> 8;
		color1.blue = color.blue >> 8;

		GETSTRORGOTO(val, tmp, 2, error);

		if (!XParseColor(dpy, DefaultColormap(dpy, scr), tmp, &color)) {
			wwarning("could not parse color %s in texture %s", tmp, text);
			goto error;
		}

		color2.red = color.red >> 8;
		color2.green = color.green >> 8;
		color2.blue = color.blue >> 8;

		switch (type[0]) {
		case 'h':
		case 'H':
			gtype = RHorizontalGradient;
			iwidth = scrWidth;
			iheight = 32;
			break;
		case 'V':
		case 'v':
			gtype = RVerticalGradient;
			iwidth = 32;
			iheight = scrHeight;
			break;
		default:
			gtype = RDiagonalGradient;
			iwidth = scrWidth;
			iheight = scrHeight;
			break;
		}

		image = RRenderGradient(iwidth, iheight, &color1, &color2, gtype);

		if (!image) {
			wwarning("could not render gradient texture:%s", RMessageForError(RErrorCode));
			goto error;
		}

		if (!RConvertImage(rc, image, &pixmap)) {
			wwarning("could not convert texture:%s", RMessageForError(RErrorCode));
			RReleaseImage(image);
			goto error;
		}

		texture->width = image->width;
		texture->height = image->height;
		RReleaseImage(image);

		texture->pixmap = pixmap;
	} else if (strcasecmp(type, "mvgradient") == 0
Ejemplo n.º 21
0
    framebuffer( uint32_t width = 800, uint32_t height = 600 ) : width_(width), height_(height) {
        
        
        {
            // select display and screen
            const char *dpyName = ":0";
            display_ = XOpenDisplay( dpyName );
            scrnum_ = DefaultScreen( display_ );
            if( display_ == 0 ) {
                throw std::runtime_error( "X11 display == 0\n" );
            }
        
        }
        
        
        {
            // create window
            
            Window root;
            root = RootWindow( display_, scrnum_ );
            
            XSetWindowAttributes attr;                   
            attr.background_pixel = 0;
            attr.border_pixel = 0;
            attr.colormap = XCreateColormap( display_, root, DefaultVisual( display_, 0 ), AllocNone );
            attr.event_mask =  StructureNotifyMask | ExposureMask | KeyPressMask | FocusChangeMask;
            unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
            
            window_ = XCreateWindow( display_, root, 0, 0, width, height,
                                      0, DefaultDepth(display_, 0), InputOutput, DefaultVisual(display_, 0), mask, &attr );
            
            if( window_ == 0 )
            {
                
                throw std::runtime_error( "XCreateWindow failed\n" );
            }
        
        }
        
        
        {
            // additional window setup
            XSizeHints sizehints;
            sizehints.width = width_;
            sizehints.height = height_;
            sizehints.flags = USSize;
            XSetNormalHints( display_, window_, &sizehints );
            
            const char *name = "Human Interface";
            // is XSetNormalHints above just plain stupid?
            XSetStandardProperties( display_, window_, name, name, None, (char**)0, 0, &sizehints );   
        }
        
        
        XMapWindow( display_, window_ );
        
        // wait for map notify
        while(true) {
            XEvent e;
            XNextEvent(display_, &e);
            std::cout << "event: " << e.type << "\n";
            if (e.type == MapNotify) {
                break;
            }
        }
        
        
        // done
        
        gc_ = XCreateGC( display_, window_, 0, 0 );
    
        
//         shminfo.
#if 0    
        XImage *xi = XShmCreateImage(display_, DefaultVisual( display_, 0 ), DefaultDepthOfScreen(screen),
                          ZPixmap, NULL, &shminfo,
                          width_, height_);
#endif   
     
        
    }
Ejemplo n.º 22
0
int XDefaultDepth(Display *dpy, int scr)
{
    return(DefaultDepth(dpy, scr));
}
Ejemplo n.º 23
0
		int32_t run(int _argc, char** _argv)
		{
			XInitThreads();
			m_display = XOpenDisplay(0);

			int32_t screen = DefaultScreen(m_display);
			int32_t depth = DefaultDepth(m_display, screen);
			Visual* visual = DefaultVisual(m_display, screen);
			Window root = RootWindow(m_display, screen);

			XSetWindowAttributes windowAttrs;
			memset(&windowAttrs, 0, sizeof(windowAttrs) );
			windowAttrs.background_pixmap = 0;
			windowAttrs.border_pixel = 0;
			windowAttrs.event_mask = 0
					| ButtonPressMask
					| ButtonReleaseMask
					| ExposureMask
					| KeyPressMask
					| KeyReleaseMask
					| PointerMotionMask
					| ResizeRedirectMask
					| StructureNotifyMask
					;

			m_window = XCreateWindow(m_display
									, root
									, 0, 0
									, ENTRY_DEFAULT_WIDTH, ENTRY_DEFAULT_HEIGHT, 0, depth
									, InputOutput
									, visual
									, CWBorderPixel|CWEventMask
									, &windowAttrs
									);

			XMapWindow(m_display, m_window);
			XStoreName(m_display, m_window, "BGFX");

			bgfx::x11SetDisplayWindow(m_display, m_window);

			MainThreadEntry mte;
			mte.m_argc = _argc;
			mte.m_argv = _argv;

			bx::Thread thread;
			thread.init(mte.threadFunc, &mte);

			while (!m_exit)
			{
				if (XPending(m_display) )
				{
					XEvent event;
					XNextEvent(m_display, &event);

					switch (event.type)
					{
						case Expose:
							break;

						case ConfigureNotify:
							break;

						case ButtonPress:
						case ButtonRelease:
							{
								const XButtonEvent& xbutton = event.xbutton;
								MouseButton::Enum mb;
								switch (xbutton.button)
								{
									case Button1: mb = MouseButton::Left;   break;
									case Button2: mb = MouseButton::Middle; break;
									case Button3: mb = MouseButton::Right;  break;
									default:      mb = MouseButton::None;   break;
								}

								if (MouseButton::None != mb)
								{
									m_eventQueue.postMouseEvent(xbutton.x
										, xbutton.y
										, mb
										, event.type == ButtonPress
										);
								}
							}
							break;

						case MotionNotify:
							{
								const XMotionEvent& xmotion = event.xmotion;
								m_eventQueue.postMouseEvent(xmotion.x
										, xmotion.y
										);
							}
							break;

						case KeyPress:
						case KeyRelease:
							{
								XKeyEvent& xkey = event.xkey;
								KeySym keysym = XLookupKeysym(&xkey, 0);
								switch (keysym)
								{
								case XK_Meta_L:    setModifier(Modifier::LeftMeta,   KeyPress == event.type); break;
								case XK_Meta_R:    setModifier(Modifier::RightMeta,  KeyPress == event.type); break;
								case XK_Control_L: setModifier(Modifier::LeftCtrl,   KeyPress == event.type); break;
								case XK_Control_R: setModifier(Modifier::RightCtrl,  KeyPress == event.type); break;
								case XK_Shift_L:   setModifier(Modifier::LeftShift,  KeyPress == event.type); break;
								case XK_Shift_R:   setModifier(Modifier::RightShift, KeyPress == event.type); break;
								case XK_Alt_L:     setModifier(Modifier::LeftAlt,    KeyPress == event.type); break;
								case XK_Alt_R:     setModifier(Modifier::RightAlt,   KeyPress == event.type); break;

								default:
									{
										Key::Enum key = fromXk(keysym);
										if (Key::None != key)
										{
											m_eventQueue.postKeyEvent(key, m_modifiers, KeyPress == event.type);
										}
									}
									break;
								}
							}
							break;

						case ResizeRequest:
							{
								const XResizeRequestEvent& xresize = event.xresizerequest;
								XResizeWindow(m_display, m_window, xresize.width, xresize.height);
							}
							break;
					}
				}
			}

			thread.shutdown();

			XUnmapWindow(m_display, m_window);
			XDestroyWindow(m_display, m_window);

			return EXIT_SUCCESS;
		}
Ejemplo n.º 24
0
//////////
//
// Called at startup one time to declare the initial desktop window as a pseudo-window
// which is
//
//////
	SHwndX* iHwndX_declareDesktopHwnd(void)
	{
		s32			lnWidth, lnHeight;
		WNDCLASSEX	wcx;
		SHwndX*		win;


		//////////
		// Allocate our primary SHwndX buffer if need be
		//////
			if (!gsWindows)			iBuilder_createAndInitialize(&gsWindows, -1);
			if (!gsClasses)			iBuilder_createAndInitialize(&gsClasses, -1);
			if (!gsHdcs)			iBuilder_createAndInitialize(&gsHdcs, -1);


		//////////
		// Connect to X11
		//////
			gsDesktop.display		= XOpenDisplay(NULL);
			gsDesktop.screen		= DefaultScreen(gsDesktop.display);
			gsDesktop.depth			= DefaultDepth(gsDesktop.display, gsDesktop.screen);
			gsDesktop.connection	= ConnectionNumber(gsDesktop.display);
			gsDesktop.windowDesktop	= RootWindow(gsDesktop.display, gsDesktop.screen);


		//////////
		// Register our logical desktop class
		//////
			memset(&wcx, 0, sizeof(wcx));
			wcx.cbSize			= sizeof(wcx);
			wcx.style			= CS_OWNDC;
			wcx._lpfnWndProc	= (uptr)&DefWindowProc;
			wcx.lpszClassName	= (cs8*)&cgcDesktop[0];
			wcx.lpszMenuName	= (cs8*)&cgcDesktop[0];
			RegisterClassEx(&wcx);


		//////////
		// Create our logical desktop window
		//////
			lnWidth			= XDisplayWidth(gsDesktop.display, gsDesktop.screen);
			lnHeight		= XDisplayHeight(gsDesktop.display, gsDesktop.screen);
debug_break;
			ghWndDesktop	= CreateWindowEx(	0, cgcDesktop, cgcDesktop, WS_POPUP,
												0, 0, lnWidth, lnHeight,
												null0, null0, null0, null0);


		//////////
		// Create our default device context
		//////
			win = iHwndX_findWindow_byHwnd(ghWndDesktop);
			if (win)
			{
				// Create the actual hdc
				win->hdcx = iHwndX_createHdc(lnWidth, lnHeight, NULL);

				// Populate with default items
				//XQueryFont(gsDesktop.display, "*");
			}


		//////////
		// Return the logical desktop pointer
		//////
			return(win);
	}
Ejemplo n.º 25
0
void
WindowDevice::WINOPEN(const char *_title, int _xLoc, int _yLoc, int _width, int _height)
{
    // set the WindowDevices title, height, wdth, xLoc and yLoc
    strcpy(title, _title);

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

#endif

    winOpen = 0;
}
Ejemplo n.º 26
0
//////////
//
// Called to physically create the X11 window which will be drawn on the desktop.
//
//////
	s32 iHwndX_initializeXWindow(SXWindow* xwin, s32 width, s32 height, s8* title)
	{
		XSizeHints Hints;


		// Make sure our environment is sane
		if (xwin)
		{
			//////////
			// Allocate a display
			//////
				xwin->display = XOpenDisplay(NULL);
				if (!xwin->display)
					return _X11_NO_DISPLAY;


			//////////
			// Populate our local settings
			//////
				xwin->width		= width;
				xwin->height	= height;
				xwin->drawable	= DefaultScreen(xwin->display);
				xwin->screenptr	= DefaultScreenOfDisplay(xwin->display);
				xwin->visual	= DefaultVisualOfScreen(xwin->screenptr);
				xwin->depth		= DefaultDepth(xwin->display, xwin->drawable);
				xwin->pixelsize	= 4;


			//////////
			// Make sure we have a compatible display
			//////
				if (xwin->depth != 24 && xwin->depth != 32)
					return _X11_UNSUPPORTED;


			//////////
			// Physically create the window on the desktop
			//////
				xwin->window	= XCreateWindow(xwin->display,
												RootWindowOfScreen(xwin->screenptr),
												0, 0, xwin->width, xwin->height,
												0, xwin->depth,
												InputOutput,
												xwin->visual, 0, NULL);

				// Are we valid?
				if (!xwin->window)
					return _X11_NO_WINDOW;

				// Raise it to the top
				XMapRaised(xwin->display, xwin->window);


			//////////
			// Provide hints because we do our own resizing internally
			//////
				Hints.flags			= PSize | PMinSize | PMaxSize;
				Hints.min_width		= Hints.max_width	= Hints.base_width	= width;
				Hints.min_height	= Hints.max_height	= Hints.base_height	= height;
				XSetWMNormalHints(xwin->display, xwin->window, &Hints);


			//////////
			// Set window title and specify those events we would like to receive
			//////
				XStoreName(xwin->display, xwin->window, title);
				XSelectInput(xwin->display, xwin->window, 		ExposureMask
															|	KeyPressMask
															|	KeyReleaseMask
															|	ButtonPressMask
															|	EnterWindowMask
															|	LeaveWindowMask
															|	PointerMotionMask
															|	FocusChangeMask);

			//////////
			// Graphical context
			//////
				xwin->gc = XCreateGC(xwin->display, xwin->window, 0, NULL);


			//////////
			// Primray pixel buffer
			//////
				xwin->screensize	= xwin->height * xwin->width * xwin->pixelsize;
				xwin->virtualscreen	= (SBgra*)malloc(xwin->screensize);
				if (!xwin->virtualscreen)
					return _X11_NO_VIRTUAL_SCREEN;

				// Logical image
				xwin->ximage = XCreateImage(xwin->display, xwin->visual, xwin->depth,
											ZPixmap, 0,
											(s8*)xwin->virtualscreen,
											xwin->width, xwin->height,
											(xwin->pixelsize * 8),
											xwin->width * xwin->pixelsize);

				// Did we get the buffer?
				if (!xwin->ximage)
					return _X11_NO_PIXEL_BUFFER;


			//////////
			// Pixel buffer 2
			//////
				xwin->screensize2		= xwin->height * xwin->width * xwin->pixelsize;
				xwin->virtualscreen2	= (SBgra*)malloc(xwin->screensize2);
				if (!xwin->virtualscreen2)
					return _X11_VIRTALLOC;

				// Logical image
				xwin->ximage2 = XCreateImage(xwin->display, xwin->visual, xwin->depth,
											ZPixmap, 0,
											(s8*)xwin->virtualscreen2,
											xwin->width, xwin->height,
											(xwin->pixelsize * 8),
											xwin->width * xwin->pixelsize);
				// Did we get the buffer?
				if (!xwin->ximage2)
					return _X11_NO_PIXEL_BUFFER;


			//////////
			// We're good
			//////
				return _X11_OK;
		}

		// If we get here, invalid
		return _X11_GENERAL_FAILURE;
	}
Ejemplo n.º 27
0
int main (int argc, char **argv)
{
	
	Visual *vis;
	Colormap cm;
	Display *_display;
	Imlib_Context context;
	Imlib_Image image;
	Pixmap pixmap;
	Imlib_Color_Modifier modifier = NULL;
	_display = XOpenDisplay (NULL);
	int width, height, depth, i, alpha;

	
	char str1[40];
	char str2[40];
	char str3[40];
	char str4[40];
	char str5[40];
	
	int ck0;
	int w, h; 
	w = 0;
	h = 0;
		
			
	for (screen = 0; screen < ScreenCount (_display); screen++)
	{
		display = XOpenDisplay (NULL);

		context = imlib_context_new ();
		imlib_context_push (context);

		imlib_context_set_display (display);
		vis = DefaultVisual (display, screen);
		cm = DefaultColormap (display, screen);

		width = DisplayWidth (display, screen);
		height = DisplayHeight (display, screen);

		depth = DefaultDepth (display, screen);

		pixmap =
			XCreatePixmap (display, RootWindow (display, screen),
							width, height, depth);

		imlib_context_set_visual (vis);
		imlib_context_set_colormap (cm);
		imlib_context_set_drawable (pixmap);
		imlib_context_set_color_range (imlib_create_color_range ());
		
		image = imlib_create_image (width, height);
		imlib_context_set_image (image);
				
		imlib_context_set_color (0, 0, 0, 255);
		imlib_image_fill_rectangle (0, 0, width, height);

		imlib_context_set_dither (1);
		imlib_context_set_blend (1);
		
		alpha = 255;


	for (i = 1; i < argc; i++)
	{
		if (modifier != NULL)
		{
			imlib_apply_color_modifier ();
			imlib_free_color_modifier ();
		}

	modifier = imlib_create_color_modifier ();
	imlib_context_set_color_modifier (modifier);

		if (strcmp (argv[i], "-alpha") == 0)
		{
			if ((++i) >= argc)
			{
				fprintf (stderr, "Missing alpha\n");
				continue;
			}
				if (sscanf (argv[i], "%i", &alpha) == 0)
				{
					fprintf (stderr, "Bad alpha (%s)\n", argv[i]);
					continue;
				}
		}
	else if (strcmp (argv[i], "-solid") == 0)
	{
		Color c;
		
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if (parse_color (argv[i], &c, alpha) == 1)
			{
				fprintf (stderr, "Bad color (%s)\n", argv[i]);
				continue;
			}

		imlib_context_set_color (c.r, c.g, c.b, c.a);
		imlib_image_fill_rectangle (0, 0, width, height);
	}
		else if (strcmp (argv[i], "-clear") == 0)
		{
			imlib_free_color_range ();
			imlib_context_set_color_range (imlib_create_color_range ());
		}
	else if (strcmp (argv[i], "-add") == 0)
	{
		Color c;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if (parse_color (argv[i], &c, alpha) == 1)
			{
				fprintf (stderr, "Bad color (%s)\n", argv[i - 1]);
				continue;
			}

		imlib_context_set_color (c.r, c.g, c.b, c.a);
		imlib_add_color_to_color_range (1);
	}
	else if (strcmp (argv[i], "-addd") == 0)
	{
		Color c;
		int distance;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if ((++i) >= argc)
			{
				fprintf (stderr, "Missing distance\n");
				continue;
			}
				if (parse_color (argv[i - 1], &c, alpha) == 1)
				{
					fprintf (stderr, "Bad color (%s)\n", argv[i - 1]);
					continue;
				}
					if (sscanf (argv[i], "%i", &distance) == 1)
					{
						fprintf (stderr, "Bad distance (%s)\n", argv[i]);
						continue;
					}

				imlib_context_set_color (c.r, c.g, c.b, c.a);
				imlib_add_color_to_color_range (distance);
	}
	else if (strcmp (argv[i], "-gradient") == 0)
	{
		int angle;
		 
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing angle\n");
			continue;
		}
			if (sscanf (argv[i], "%i", &angle) == 1)
			{
				fprintf (stderr, "Bad angle (%s)\n", argv[i]);
				continue;
			}
			
		imlib_image_fill_color_range_rectangle (0, 0, width, height,
												angle);
	}

	 else if (strcmp (argv[i], "-fill") == 0)
	 {
		if ((++i) >= argc)
		{
		  fprintf (stderr, "Missing image\n");
		  continue;
		}
		
		if ( load_Mod_image(Fill, argv[i], width, height, alpha, image, ck0) == 1)
		{
		  fprintf (stderr, "Bad image (%s)\n", argv[i]);
		  continue;
		}
	 }
	else if (strcmp (argv[i], "-dia") == 0)
	{ 
		if((++i) >= argc)
		{
			fprintf(stderr, "missing information to load image\n");
			continue;
		}
			strcpy (str1, argv[i]);
			strcpy (str2, str1);
		
				if ( findX(str1, &w, &h) == 1 )
			{
				fprintf(stderr, " Bad Format < %s >\n", argv[i]);
				continue;
			}
			else if (findX(str2, &w, &h) == 0 && ((++i) >= argc))
			{ 
				fprintf(stderr, "Bad Format: try -dia <size>x<size> <image> \n");
				continue;
			}
			else
			{
				//if format is correct then assign a number for
				//load_Mod_Image to check
				ck0 = -2;
				w = w; // newW
				h = w; //newH;
			}
			
			if( load_Mod_image(Dia, argv[i], w, h, alpha, image, ck0) == 1 )
			{
			fprintf(stderr, "Bad Image or Bad Image Dimensions \n");
			}
	} 
	else if (strcmp (argv[i], "-tile") == 0)
	{
		if ((++i) >= argc)

			{
			fprintf(stderr, "format 0 missing \n");
			continue;
			}
				strcpy (str1, argv[i]);
				strcpy (str2, str1);
				strcpy (str3, str2);
				strcpy (str4, str3);
				strcpy (str5, str4);

				//check for proper format -tile 0 <image>
			if ( findX(str1, &w, &h) == 3 &&  ((++i) >= argc))
			{ 
				continue;
			} //check to see if format is -tile 0 image is there then load img
			else if (findX(str2, &w, &h) == 3)
			{  
				 ck0 = 3; 
				if( load_Mod_image(Tile, argv[i], width, height, alpha, image, ck0) == 1 )
				{
					fprintf(stderr, "Bad Image |%s|\n", argv[i]);
					continue;
				}
			}
				// check for dimentions -tile <dia>x<dia> <image>
			if (findX(str3, &w, &h) == 1)
			{
				fprintf(stderr, "Bad Format\n");
				continue;
			}
			 if (findX(str4, &w, &h) == 0 && ((++i) >= argc))
			{
				fprintf(stderr, "Bad Format: try %s 0 %s \n",argv[i-2], argv[i-1]);
				continue;
			}
			if (findX (str5, &w, &h) == 0 )
			{
				ck0 = 2;
				w = w;
				h = h;
			}
			
			if( load_Mod_image(Tile, argv[i], w, h, alpha, image, ck0) == 1 )
			{
			fprintf(stderr, "Bad Image <%s> \n", argv[i]);
			}

	}

	else if (strcmp (argv[i], "-center") == 0)
	{ 
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing image\n");
			continue;
		}
			if (load_Mod_image (Center, argv[i], width, height, alpha, image, ck0) == 1)
			{ 
				fprintf (stderr, "Bad image (%s)\n", argv[i]);
				continue;
			}
	}
	else if (strcmp (argv[i], "-tint") == 0)
	{
		Color c;
		DATA8 r[256], g[256], b[256], a[256];
		int j;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if (parse_color (argv[i], &c, 255) == 1)
			{
				fprintf (stderr, "Bad color\n");
				continue;
			}

		imlib_get_color_modifier_tables (r, g, b, a);

			for (j = 0; j < 256; j++)
			{
				r[j] = (DATA8) (((double) r[j] / 255.0) * (double) c.r);
				g[j] = (DATA8) (((double) g[j] / 255.0) * (double) c.g);
				b[j] = (DATA8) (((double) b[j] / 255.0) * (double) c.b);
			}

		imlib_set_color_modifier_tables (r, g, b, a);
	}
	else if (strcmp (argv[i], "-blur") == 0)
	{
		int intval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%i", &intval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_image_blur (intval);
	}
	else if (strcmp (argv[i], "-sharpen") == 0)
	{
		int intval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%i", &intval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_image_sharpen (intval);
	}
	else if (strcmp (argv[i], "-contrast") == 0)
	{
		double dblval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%lf", &dblval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_modify_color_modifier_contrast (dblval);
	}
	else if (strcmp (argv[i], "-brightness") == 0)
	{
		double dblval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%lf", &dblval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_modify_color_modifier_brightness (dblval);
	}
	else if (strcmp (argv[i], "-gamma") == 0)
	{
		double dblval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%lf", &dblval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_modify_color_modifier_gamma (dblval);
	}
	else if (strcmp (argv[i], "-flipv") == 0)
	{
		imlib_image_flip_vertical ();
	}
	else if (strcmp (argv[i], "-fliph") == 0)
	{
		imlib_image_flip_horizontal ();
	}
	else if (strcmp (argv[i], "-flipd") == 0)
	{
		imlib_image_flip_diagonal ();
	}
	else if (strcmp (argv[i], "-write") == 0)
	{
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing filename\n");
			continue;
		}
      imlib_save_image (argv[i]);
	}
	else
	{
		usage (argv[0]);
		imlib_free_image ();
		imlib_free_color_range ();

			if (modifier != NULL)
			{
				imlib_context_set_color_modifier (modifier);
				imlib_free_color_modifier ();
				modifier = NULL;
			}
				XFreePixmap (display, pixmap);
				exit (1);
	} // end else
} // end loop off of argc

	if (modifier != NULL)
	{
		imlib_context_set_color_modifier (modifier);
        imlib_apply_color_modifier ();
        imlib_free_color_modifier ();
        modifier = NULL;
	}

		imlib_render_image_on_drawable (0, 0);
		imlib_free_image ();
		imlib_free_color_range ();

		if (setRootAtoms (pixmap) == 0)
			fprintf (stderr, "Couldn't create atoms...\n");

		XKillClient (display, AllTemporary);
		XSetCloseDownMode (display, RetainTemporary);

		XSetWindowBackgroundPixmap (display, RootWindow (display, screen),
									pixmap);

		XClearWindow (display, RootWindow (display, screen));

		XFlush (display);
		XSync (display, False);

		imlib_context_pop ();
		imlib_context_free (context);

	} // end for loop off screen
                  
  return 0;
}
Ejemplo n.º 28
0
/**************************************************************************
  Entry point for GUI specific portion. Called from client_main()
**************************************************************************/
void ui_main(int argc, char *argv[])
{
  int i;
  struct sprite *icon; 

  parse_options(argc, argv);

  /* include later - pain to see the warning at every run */
  XtSetLanguageProc(NULL, NULL, NULL);
  
  toplevel = XtVaAppInitialize(
	       &app_context,               /* Application context */
	       "Freeciv",                  /* application class name */
#ifdef UNUSED
	       cmd_options, XtNumber(cmd_options),
#else
	       NULL, 0,
#endif
	                                   /* command line option list */
	       &argc, argv,                /* command line args */
	       &fallback_resources[1],     /* for missing app-defaults file */
	       XtNallowShellResize, True,
	       NULL);              

  XtGetApplicationResources(toplevel, &appResources, resources,
                            XtNumber(resources), NULL, 0);

/*  XSynchronize(display, 1); 
  XSetErrorHandler(myerr);*/

  if(appResources.version==NULL)  {
    freelog(LOG_FATAL, _("No version number in resources."));
    freelog(LOG_FATAL, _("You probably have an old (circa V1.0)"
			 " Freeciv resource file somewhere."));
    exit(EXIT_FAILURE);
  }

  /* TODO: Use capabilities here instead of version numbers */
  if (0 != strncmp(appResources.version, VERSION_STRING,
		   strlen(appResources.version))) {
    freelog(LOG_FATAL, _("Game version does not match Resource version."));
    freelog(LOG_FATAL, _("Game version: %s - Resource version: %s"), 
	    VERSION_STRING, appResources.version);
    freelog(LOG_FATAL, _("You might have an old Freeciv resourcefile"
			 " in /usr/lib/X11/app-defaults"));
    exit(EXIT_FAILURE);
  }
  
  if(!appResources.gotAppDefFile) {
    freelog(LOG_NORMAL, _("Using fallback resources - which is OK"));
  }

  display = XtDisplay(toplevel);
  screen_number=XScreenNumberOfScreen(XtScreen(toplevel));
  display_depth=DefaultDepth(display, screen_number);
  root_window=DefaultRootWindow(display);

  display_color_type=get_visual(); 
  
  if(display_color_type!=COLOR_DISPLAY) {
    freelog(LOG_FATAL, _("Only color displays are supported for now..."));
    /*    exit(EXIT_FAILURE); */
  }

  {
    XGCValues values;
    char **missing_charset_list_return;
    int missing_charset_count_return;
    char *def_string_return;
    char *city_names_font, *city_productions_font_name;

    values.graphics_exposures = False;
    civ_gc = XCreateGC(display, root_window, GCGraphicsExposures, &values);

    city_names_font = mystrdup("-*-*-*-*-*-*-14-*");

    city_productions_font_name = mystrdup("-*-*-*-*-*-*-14-*");

    main_font_set = XCreateFontSet(display, city_names_font,
	&missing_charset_list_return,
	&missing_charset_count_return,
	&def_string_return);
    if (!main_font_set) {
      freelog(LOG_FATAL, _("Unable to open fontset: %s"),
	      city_names_font);
      freelog(LOG_FATAL,
	      _("Doing 'xset fp rehash' may temporarily solve a problem."));
      exit(EXIT_FAILURE);
    }
    for (i = 0; i < missing_charset_count_return; i++) {
      freelog(LOG_ERROR, _("Font for charset %s is lacking"),
	      missing_charset_list_return[i]);
    }
    values.foreground = get_color(tileset, COLOR_MAPVIEW_CITYTEXT)->color.pixel;
    values.background = get_color(tileset, COLOR_MAPVIEW_UNKNOWN)->color.pixel;
    font_gc= XCreateGC(display, root_window, 
		       GCForeground|GCBackground|GCGraphicsExposures, 
		       &values);

    prod_font_set = XCreateFontSet(display, city_productions_font_name,
	&missing_charset_list_return,
	&missing_charset_count_return,
	&def_string_return);
    if (!prod_font_set) {
      freelog(LOG_FATAL, _("Unable to open fontset: %s"),
	      city_productions_font_name);
      freelog(LOG_FATAL,
	      _("Doing 'xset fp rehash' may temporarily solve a problem."));
      exit(EXIT_FAILURE);
    }
    for (i = 0; i < missing_charset_count_return; i++) {
      freelog(LOG_ERROR, _("Font for charset %s is lacking"),
	      missing_charset_list_return[i]);
    }
    values.foreground = get_color(tileset, COLOR_MAPVIEW_CITYTEXT)->color.pixel;
    values.background = get_color(tileset, COLOR_MAPVIEW_UNKNOWN)->color.pixel;
    prod_font_gc= XCreateGC(display, root_window,
			    GCForeground|GCBackground|GCGraphicsExposures,
			    &values);

    values.line_width = BORDER_WIDTH;
    values.line_style = LineOnOffDash;
    values.cap_style = CapNotLast;
    values.join_style = JoinMiter;
    values.fill_style = FillSolid;
    border_line_gc = XCreateGC(display, root_window,
			       GCGraphicsExposures|GCLineWidth|GCLineStyle
			       |GCCapStyle|GCJoinStyle|GCFillStyle, &values);

    values.foreground = 0;
    values.background = 0;
    fill_bg_gc= XCreateGC(display, root_window, 
			  GCForeground|GCBackground|GCGraphicsExposures,
			  &values);

    values.fill_style=FillStippled;
    fill_tile_gc= XCreateGC(display, root_window, 
    			    GCForeground|GCBackground|GCFillStyle|GCGraphicsExposures,
			    &values);
  }

  {
    char d1[]={0x03,0x0c,0x03,0x0c};
    char d2[]={0x08,0x02,0x08,0x02};
    gray50 = XCreateBitmapFromData(display, root_window, d1, 4, 4);
    gray25 = XCreateBitmapFromData(display, root_window, d2, 4, 4);
  }
  
  /* 135 below is rough value (could be more intelligent) --dwp */
  num_units_below = 135 / tileset_full_tile_width(tileset);
  num_units_below = MIN(num_units_below,MAX_NUM_UNITS_BELOW);
  num_units_below = MAX(num_units_below,1);
  
  /* do setup_widgets before loading the rest of graphics to ensure that
     setup_widgets() has enough colors available:  (on 256-colour systems)
  */
  setup_widgets();
  tileset_init(tileset);
  tileset_load_tiles(tileset);
  load_intro_gfx();
  load_cursors();

  /* FIXME: what about the mask? */
  icon = get_icon_sprite(tileset, ICON_FREECIV);
  XtVaSetValues(toplevel, XtNiconPixmap, icon->pixmap, NULL);

  XtSetKeyboardFocus(bottom_form, inputline_text);
  XtSetKeyboardFocus(below_menu_form, map_canvas);

  InitializeActions(app_context);

  /* Do this outside setup_widgets() so after tiles are loaded */
  fill_econ_label_pixmaps();
		
  XtAddCallback(map_horizontal_scrollbar, XtNjumpProc, 
		scrollbar_jump_callback, NULL);
  XtAddCallback(map_vertical_scrollbar, XtNjumpProc, 
		scrollbar_jump_callback, NULL);
  XtAddCallback(map_horizontal_scrollbar, XtNscrollProc, 
		scrollbar_scroll_callback, NULL);
  XtAddCallback(map_vertical_scrollbar, XtNscrollProc, 
		scrollbar_scroll_callback, NULL);
  XtAddCallback(turn_done_button, XtNcallback, end_turn_callback, NULL);

  XtAppAddWorkProc(app_context, toplevel_work_proc, NULL);

  XtRealizeWidget(toplevel);

  x_interval_id = XtAppAddTimeOut(app_context, TIMER_INTERVAL,
				  timer_callback, NULL);

  init_mapcanvas_and_overview();

  fill_unit_below_pixmaps();

  set_indicator_icons(client_research_sprite(),
		      client_warming_sprite(),
		      client_cooling_sprite(),
		      client_government_sprite());

  wm_delete_window = XInternAtom(XtDisplay(toplevel), "WM_DELETE_WINDOW", 0);
  XSetWMProtocols(display, XtWindow(toplevel), &wm_delete_window, 1);
  XtOverrideTranslations(toplevel,
    XtParseTranslationTable ("<Message>WM_PROTOCOLS: msg-quit-freeciv()"));

  XtSetSensitive(toplevel, FALSE);

  XtAppMainLoop(app_context);
}
Ejemplo n.º 29
0
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, screen_id));
	XftDraw *draw = XftDrawCreate(display, canvas, DefaultVisual(display, screen_id), DefaultColormap(display, screen_id));

	// 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 line_width  = 0;

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

		line = alloca(length + 10);
		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);
	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 = (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);
}
Ejemplo n.º 30
0
Archivo: status.c Proyecto: awaw/status
int
main(int argc, char *argv[])
{
	XEvent e;
	Atom type;
	XClassHint *h;
	XSetWindowAttributes wa;
	unsigned int desktop;
	struct pollfd pfd[1];
	int nfds;
	char *fontstr = FONT;
	int running = 1;

	d = XOpenDisplay(NULL);
	if (d == NULL) {
		fprintf(stderr, "Cannot open display\n");
		exit(1);
	}

	s = DefaultScreen(d);

	wa.override_redirect = 1;
	wa.background_pixmap = ParentRelative;
	wa.event_mask = ExposureMask | ButtonReleaseMask | ButtonPressMask;

	w = XCreateWindow(d, RootWindow(d, s), 0, BARPOS, BARWIDTH, BARHEIGHT, 0,
	    DefaultDepth(d, s), CopyFromParent, DefaultVisual(d, s),
	    CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);

	h = XAllocClassHint();
	h->res_name  = "status";
	h->res_class = "status";
	XSetClassHint(d, w, h);
	XFree(h);

	XStoreName(d, w, "status");

	type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", False);
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", False),
	    XInternAtom(d, "ATOM", False), 32, PropModeReplace, (unsigned char *)&type, 1);

	type = XInternAtom(d, "_NET_WM_STATE_ABOVE", False);
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", False),
	    XInternAtom(d, "ATOM", False), 32, PropModeReplace, (unsigned char *)&type, 1);

	type = XInternAtom(d, "_NET_WM_STATE_STICKY", False);
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", False),
	    XInternAtom(d, "ATOM", False), 32, PropModeAppend, (unsigned char *)&type, 1); 

	desktop = 0xffffffff;
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_DESKTOP", False),
	    XInternAtom(d, "CARDINAL", False), 32, PropModeReplace, (unsigned char *)&desktop, 1);

	xftd = XftDrawCreate(d, w, DefaultVisual(d, s), DefaultColormap(d, s));

	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "white",  &white);
	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "black",  &black);
	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "red",  &red);
	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "green",  &green);

	xftfont = XftFontOpenXlfd(d, s, fontstr);
	if (!xftfont)
		xftfont = XftFontOpenName(d, s, fontstr);
	if (!xftfont)
		exit(1);

	XSelectInput(d, w, ExposureMask | ButtonPressMask | ButtonReleaseMask | Button1MotionMask);
	XSelectInput(d, RootWindow(d, s), PropertyChangeMask);

	XMapWindow(d, w);
	XFlush(d);

	pfd[0].fd = ConnectionNumber(d);
	pfd[0].events = POLLIN;

	while (running) {
		nfds = poll(pfd, 1, 1000);
		if (nfds == -1 || (pfd[0].revents & (POLLERR|POLLHUP|POLLNVAL)))
			break;
		if (nfds == 0) {
			redraw();
			XFlush(d);
			continue;
		}

		while (XPending(d)) {
			XNextEvent(d, &e);
			if (e.type == PropertyNotify &&
			    e.xproperty.window == RootWindow(d, s) &&
			    e.xproperty.atom == XInternAtom(d, "_NET_CURRENT_DESKTOP", True)) {
				redraw();
			}
			if (e.type == Expose) {
				XftDrawRect(xftd, &black, 0, 0, BARWIDTH, BARHEIGHT);
				redraw();
			}
			if (e.type == ButtonPress) {
				/*running = 0;
				break;*/
				redraw();
			}
		}
	}

	XftColorFree(d, DefaultVisual(d, s), DefaultColormap(d, s), &white);
	XftColorFree(d, DefaultVisual(d, s), DefaultColormap(d, s), &black);
	XftFontClose(d, xftfont);
	XftDrawDestroy(xftd);
	XDestroyWindow(d, w);
	XCloseDisplay(d);
	return 0;
}