示例#1
0
void
render_init(void)
{
	font = XftFontOpen(display, screen,
	    XFT_FAMILY, XftTypeString, FONT_NAME,
	    XFT_SIZE, XftTypeInteger, FONT_SIZE,
	    NULL);
	if (!XftColorAllocName(display, XDefaultVisual(display, screen),
		DefaultColormap(display, screen), TouchCross, &cross)) {
		fprintf(stderr, "Cannot get color");
		exit(2);
	}
	if (!XftColorAllocName(display, XDefaultVisual(display, screen),
		DefaultColormap(display, screen), PromptText, &promptColor)) {
		fprintf(stderr, "Cannot get color");
		exit(2);
	}
	if (!XftColorAllocName(display, XDefaultVisual(display, screen),
		DefaultColormap(display, screen), Background, &bg)) {
		fprintf(stderr, "Cannot get bg color");
		exit(2);
	}
	if (!XftColorAllocName(display, XDefaultVisual(display, screen),
		DefaultColormap(display, screen), Error, &errorColor)) {
		fprintf(stderr, "Cannot get color");
		exit(2);
	}
	draw = XftDrawCreate(display, win, DefaultVisual(display, screen),
	    DefaultColormap(display, screen));
}
示例#2
0
int
createWin(XDataStr *data)
{
    u_long attributeMask;
    XSetWindowAttributes attribute;
    Window w;
    Display *display = data->display;
    int screen = DefaultScreen(display);
    XGCValues gc_val;
    Screen *s;

    attribute.background_pixel = WhitePixel(display, screen);
    attribute.border_pixel = WhitePixel(display, screen);
    attribute.bit_gravity = NorthWestGravity;
    attribute.event_mask = ButtonPressMask|ButtonReleaseMask|KeyPressMask|
        ExposureMask;

    attributeMask =
        CWBorderPixel |
        CWBackPixel |
        CWEventMask |
        CWBitGravity;
    s = ScreenOfDisplay(data->display, screen);

    w = XCreateWindow(display, RootWindow(display, screen), 0, 0,
            DisplayWidth(display, screen)/2, 150,
            0, DefaultDepth(display, screen), InputOutput,
            DefaultVisual(display, screen), attributeMask, &attribute);

    data->font = XftFontOpen(display, screen,
            XFT_FAMILY, XftTypeString, "mono",
            XFT_SIZE, XftTypeInteger, 16,
            NULL);
    if (!XftColorAllocName(display, XDefaultVisual(display, screen),
                DefaultColormap(display, screen), "red4", &data->color)) {
        fprintf(stderr, "cannot get color");
        return -1;
    }
    if (!XftColorAllocName(display, XDefaultVisual(display, screen),
                DefaultColormap(display, screen), "linen", &data->bg)) {
        fprintf(stderr, "cannot get bg color");
        return -1;
    }
    data->draw = XftDrawCreate(display, w, DefaultVisual(display, screen),
            DefaultColormap(display, screen));
    gc_val.foreground = BlackPixel(display, screen);
    gc_val.background = WhitePixel(display, screen);
    data->gc = XCreateGC (display, w, GCForeground|GCBackground,
            &gc_val);

    data->win = w;
    return 0;
}
示例#3
0
文件: terma.c 项目: halhen/terma
void
x_init_window()
{
    uint32_t mask     = CWBackPixel | CWEventMask;
    XSetWindowAttributes values;

    values.background_pixel = config.background;
    values.event_mask       = KeyPressMask |
                              ExposureMask |
                              StructureNotifyMask;

    size_t width  = X.glyph_width  * config.cols;
    size_t height = X.glyph_height * config.rows;

    Window parent = XRootWindow(X.dpy, X.screen);

    X.window = XCreateWindow(X.dpy,
                             parent,
                             0, 0,             /* x, y */
                             width, height,
                             0,                /* border width */
                             XDefaultDepth(X.dpy, X.screen),
                             InputOutput,
                             XDefaultVisual(X.dpy, X.screen),
                             mask, &values);
}
示例#4
0
struct vl_screen*
vl_screen_create(Display *display, int screen)
{
   struct vl_xsp_screen *xsp_screen;
   struct sw_winsys *winsys;

   assert(display);

   xsp_screen = CALLOC_STRUCT(vl_xsp_screen);
   if (!xsp_screen)
      return NULL;

   winsys = xlib_create_sw_winsys(display);
   if (!winsys) {
      FREE(xsp_screen);
      return NULL;
   }

   xsp_screen->base.pscreen = softpipe_create_screen(winsys);
   if (!xsp_screen->base.pscreen) {
      winsys->destroy(winsys);
      FREE(xsp_screen);
      return NULL;
   }

   xsp_screen->display = display;
   xsp_screen->screen = screen;
   xsp_screen->xdraw.visual = XDefaultVisual(display, screen);

   return &xsp_screen->base;
}
int main(void) {

  Display               * display;
  XImage                * ximage;
  Window                window;
  XEvent                an_event;
  GC                    gc;
  Visual                * visual;
  XGCValues             values;
  int                   m, n, screen, dplanes;
  int                   width, height, ret = 1;

  width = MAXIMOX;
  height = MAXIMOY;
  
  if ((display = XOpenDisplay(NULL)) == NULL) ret = 0;
  else {  
    screen = DefaultScreen(display);
    dplanes = DisplayPlanes(display,screen);   
    visual = XDefaultVisual(display,screen);
  
    if (!(window=XCreateSimpleWindow(display,RootWindow(display,screen),0,0,width,height,1,BlackPixel(display,screen),WhitePixel(display,screen)))) ret = 0;
    else {
      XSelectInput(display, window, EventMask);
      gc = XCreateGC(display, window, 0, &values);
  
      XMapWindow(display,window);
      XSync(display,False);

      ximage = XCreateImage(display,visual,dplanes,ZPixmap,0,malloc(width*height*sizeof(int)),width,height,8,0);
   
      /*Imagens*/
      Image retinha = Line(260,0,0,240, getColor(255,0,0));
      Image retinha2 = Line(10,0,11,240, getColor(0,255,0));
      Image retinha3 = Line(0,0,260,240, getColor(0,0,255));
      Image retangulozinho = Rectangle(200,200, getColor(255,255,0));

      /*Desenhar*/
      Draw(ximage,retangulozinho,150,100);
      Draw(ximage,retinha,100,100);
      Draw(ximage,retinha2,100,100);
      Draw(ximage,retinha3,100,100);

      /*Free memory*/
      Dispose(retangulozinho);
      Dispose(retinha);
      Dispose(retinha2);
      Dispose(retinha3);

      XPutImage(display,window,gc,ximage,0,0,0,0,width,height);
      
      sleep(50);

      }
    }
  return 0;
}
示例#6
0
static  xrandrt_t *xrandrt_init(const char *display_name)
{
    xrandrt_t *xr;
    int        fd;
    Display   *disp;

    disp = XOpenDisplay(display_name);


    if ((xr = malloc(sizeof(*xr))) == NULL) {
        if (disp != NULL)
            XCloseDisplay(disp);
    }
    else {
        fd = XConnectionNumber(disp);

        memset(xr, 0, sizeof(*xr));
        xr->disp  = disp;
        xr->chan  = g_io_channel_unix_new(fd);
        xr->evsrc = g_io_add_watch(xr->chan, G_IO_IN|G_IO_HUP|G_IO_ERR,
                                   xevent_cb,xr);
        
        printf("videoep: xrandr initialized\n");

        {
            Window root;
            Visual *vis;
            int sno;
            unsigned long wp;
            unsigned long bp;
            Window win;
            int depth;
            XSetWindowAttributes attr;
            unsigned long mask;

            root = XDefaultRootWindow(disp);
            sno = XDefaultScreen(disp);
            vis = XDefaultVisual(disp, sno);
            depth = XDefaultDepth(disp, sno);
            bp  = XBlackPixel(disp, sno);
            wp  = XWhitePixel(disp, sno);

            mask = CWBackPixel | CWBorderPixel | CWEventMask;
            attr.background_pixel = wp;
            attr.border_pixel = bp;
            attr.event_mask = ButtonPressMask | FocusChangeMask;

            win = XCreateWindow(disp, root, 50,50, 400,300, 1, depth,
                                InputOutput, vis, mask, &attr);
            XMapWindow(disp,win);            
            XFlush(disp);
        }
    }

    return xr;
}
示例#7
0
static void 
resize_display(struct dispinfo *d, int new_width, int new_height)
{
    int total_squares;
    uint h;
    char *cp;

    /* round down to even multiple of square size */
    new_width = RoundDown(new_width, d->pixel_xmult);
    new_height = RoundDown(new_height, d->pixel_ymult);

    if (new_width <= 0 || new_height <= 0)
	return;

    total_squares = (new_width * new_height) / PixelSize(d);
    d->bytes_vp = d->alloc_unit;

    /* compute how many bytes of memory one square on the display should 
     * represent, so you have the smallest granularity without the window size
     * exceeding the initial height.
     */
    while (total_squares < DivideRoundedUp(d->arena_size, d->bytes_vp))
	d->bytes_vp *= 2;
    
    h = DivideRoundedUp(d->arena_size, d->bytes_vp) * PixelSize(d);
    new_height = DivideRoundedUp(h, new_width);
    new_height = RoundUp(new_height, d->pixel_ymult);

    cp = strchr(d->title, '=');
    if (cp)
	sprintf(cp, "= %d bytes)", d->bytes_vp);

    if (!(d->memory_pixel = DXReAllocate((Pointer)d->memory_pixel, 
					 new_width * new_height))) {
	xerror = 1;
	return;
    }
	
    d->win_width = new_width;
    d->win_height = new_height;
    memset (d->memory_pixel, color_free, d->win_width * d->win_height);

    /* don't let X free our pixel buffer while destroying old image */
    d->memory_image->data = NULL;
    XDestroyImage(d->memory_image);

    d->memory_image = XCreateImage(d->disp,
			     XDefaultVisual(d->disp, XDefaultScreen(d->disp)),
			     8, ZPixmap, 0, (char *) d->memory_pixel,
			     d->win_width, d->win_height, 8, 0);

    XResizeWindow(d->disp, d->wind, d->win_width, d->win_height);
    XStoreName(d->disp, d->wind, d->title);

}
示例#8
0
文件: nenu.c 项目: mytchel/nenu
void setup() {
	XSetWindowAttributes attributes;
	XWindowAttributes window_attributes;
	Visual *vis;
	Colormap cmap;
	int ignore;
	
	display = XOpenDisplay(NULL);
	screen = DefaultScreen(display);
	vis = XDefaultVisual(display, screen);
	cmap = DefaultColormap(display, screen);

	if (XGetGeometry(display, RootWindow(display, screen), &root,
	        &ignore, &ignore,
	        &max_width, &max_height, &ignore, &ignore) == False)
	        die("Failed to get root Geometry!");

	if (!XftColorAllocName(display, vis, cmap, fg_name, &fg))
		die("Failed to allocate foreground color");
	if (!XftColorAllocName(display, vis, cmap, bg_name, &bg))
		die("Failed to allocate background color");

	/* Setup and map window */
	attributes.border_pixel = fg.pixel;
	attributes.background_pixel = bg.pixel;
	attributes.override_redirect = True;
	attributes.event_mask = 
	     ExposureMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask;

	win = XCreateWindow(display, root,
	     0, 0, 1, 1, BORDER_WIDTH,
	     DefaultDepth(display, 0),
	     CopyFromParent, CopyFromParent,
	     CWBackPixel|CWOverrideRedirect|CWEventMask|CWBorderPixel,
	     &attributes);

	xim = XOpenIM(display, NULL, NULL, NULL);
	xic = XCreateIC(xim, XNInputStyle, 
	    XIMPreeditNothing | XIMStatusNothing,
	    XNClientWindow, win, XNFocusWindow, win, NULL);

	gc = XCreateGC(display, win, 0, 0);

	buf = XCreatePixmap(display, win, 1, 1, 
	                    DefaultDepth(display, screen));
	    
	draw = XftDrawCreate(display, buf, vis, cmap);

	load_font(font_str);
}
示例#9
0
文件: cg2dBoi.c 项目: hugonomura/CG2
int DumpX(bufferdevice * dev, palette * pal) {
  	Display 			  * display;
  	XImage                * ximage;
  	Window                window;
  	XEvent                an_event;
  	GC                    gc;
  	Visual                * visual;
  	XGCValues             values;
  	int                   m, n, screen, dplanes;
  	int                   width, height, ret = 1;
  	ColorValues           * cor;
  
  	width = dev->MaxX;
  	height = dev->MaxY; 

  	if ((display = XOpenDisplay(NULL)) == NULL)
		ret = 0;
  	else {  
    	screen = DefaultScreen(display);
    	dplanes = DisplayPlanes(display,screen);   
    	visual = XDefaultVisual(display,screen);
  
    	if (!(window=XCreateSimpleWindow(display,RootWindow(display,screen),0,0,width,height,1,BlackPixel(display,screen),WhitePixel(display,screen))))
			ret = 0;
    	else {
      		XSelectInput(display, window, EventMask);
      		gc = XCreateGC(display, window, 0, &values);
      		XMapWindow(display,window);
      		XSync(display,False);
  			ximage = XCreateImage(display,visual,dplanes,ZPixmap,0,malloc(width*height*sizeof(int)),width,height,8,0);

      		for(m=0;m<height;m++) {
        		for(n=0;n<width;n++) {
          			cor = GetColor(dev->buffer[m*width+n],pal);
          			ximage -> data[(m*4)*width+n*4] = (char) round((cor->blue)*255);
          			ximage -> data[(m*4)*width+n*4+1] = (char) round((cor->green)*255);
          			ximage -> data[(m*4)*width+n*4+2] = (char) round((cor->red)*255);
          			ximage -> data[(m*4)*width+n*4+3] = (char) 0;
          		}
        	}

      		XPutImage(display,window,gc,ximage,0,0,0,0,width,height);

      		sleep(30);
      	}
	}
 
  	return ret;
}
示例#10
0
engine::engine(uint w, uint h) :
    width(w),
    height(h),
    curTime(std::chrono::system_clock::now())
{
    // создали нативное X11 окно
    
    XSetWindowAttributes attr; 
    data.display = XOpenDisplay(NULL);
    if(!data.display) 
       throw std::runtime_error("can't open X11 display");
    data.root   = XDefaultRootWindow(data.display);
    data.screen = XDefaultScreen(data.display);
    data.visual = XDefaultVisual(data.display, data.screen);
    data.window = XCreateSimpleWindow(data.display,data.root,0,0,width, height,0,0,0);
    
    // Настраиваем окно, обрабатываемые события, декорация и пр

    std::memset(&attr,0,sizeof(attr));
    attr.event_mask = StructureNotifyMask|ButtonPressMask|ButtonReleaseMask|Button1MotionMask|KeyPressMask;
    attr.background_pixel   = 0xFFFF0000;
    XWithdrawWindow(data.display,data.window, data.screen);  
    XChangeWindowAttributes(data.display,data.window,CWBackPixel|CWOverrideRedirect|CWSaveUnder|CWEventMask|CWBorderPixel, &attr);
    XMapWindow(data.display,data.window);
    XFlush(data.display); // немного паранойи

    // получаем GL контекст с помощью GLX
    
    int glx_attr[] = 
    {
        GLX_DOUBLEBUFFER,
        GLX_USE_GL,      True,
        GLX_RGBA,        True,
        GLX_BUFFER_SIZE, 32,
        GLX_DEPTH_SIZE,  24,
        None
    };
    auto visual = glXChooseVisual(data.display, data.screen, glx_attr);
    if(!visual)
       throw std::runtime_error("[GLX] unable to find visual");
    data.context = glXCreateContext(data.display, visual, NULL, True);
    if(!data.context)
       throw std::runtime_error("[GLX] unable to create window context");
    glXMakeCurrent(data.display, data.window, data.context);

    // задаем GL вьюпорт во все окно

    glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height));
}
示例#11
0
struct pipe_screen*
vl_screen_create(Display *display, int screen)
{
   struct xsp_pipe_winsys *xsp_winsys;

   assert(display);

   xsp_winsys = CALLOC_STRUCT(xsp_pipe_winsys);
   if (!xsp_winsys)
      return NULL;

   xsp_winsys->base.buffer_create = xsp_buffer_create;
   xsp_winsys->base.user_buffer_create = xsp_user_buffer_create;
   xsp_winsys->base.buffer_map = xsp_buffer_map;
   xsp_winsys->base.buffer_unmap = xsp_buffer_unmap;
   xsp_winsys->base.buffer_destroy = xsp_buffer_destroy;
   xsp_winsys->base.surface_buffer_create = xsp_surface_buffer_create;
   xsp_winsys->base.fence_reference = xsp_fence_reference;
   xsp_winsys->base.fence_signalled = xsp_fence_signalled;
   xsp_winsys->base.fence_finish = xsp_fence_finish;
   xsp_winsys->base.flush_frontbuffer = xsp_flush_frontbuffer;
   xsp_winsys->base.get_name = xsp_get_name;
   xsp_winsys->base.destroy = xsp_destroy;
   xsp_winsys->display = display;
   xsp_winsys->screen = screen;
   xsp_winsys->fbimage = XCreateImage
   (
      display,
      XDefaultVisual(display, screen),
      XDefaultDepth(display, screen),
      ZPixmap,
      0,
      NULL,
      0, /* Don't know the width and height until flush_frontbuffer */
      0,
      32,
      0
   );

   if (!xsp_winsys->fbimage) {
      FREE(xsp_winsys);
      return NULL;
   }

   XInitImage(xsp_winsys->fbimage);

   return softpipe_create_screen(&xsp_winsys->base);
}
		WindowLinux::WindowLinux(const std::string &windowTitle, const AE::OS::WindowDesc &windowDesc)
			: Window(windowTitle, windowDesc)
		{
		    AE::OS::WindowManagerLinux *myWindowManager = static_cast<AE::OS::WindowManagerLinux *>(AE::OS::WindowManager::getInstance());
			::Display *x11display = myWindowManager->_getX11Display();

		    mScreenID = XDefaultScreen(x11display);

            XSetWindowAttributes attributes;
            Visual *visual = XDefaultVisual(x11display, mScreenID);

            attributes.background_pixel		= XWhitePixel(x11display, mScreenID);
            attributes.border_pixel			= XBlackPixel(x11display, mScreenID);
//            attributes.override_redirect	= True;
            attributes.override_redirect	= False;
            attributes.event_mask			= ButtonPressMask        |
                                              ButtonReleaseMask      |
                                              PointerMotionMask      |
                                              StructureNotifyMask    |
                                              SubstructureNotifyMask |
                                              ResizeRedirectMask     |
                                              KeyPressMask           |
                                              KeyReleaseMask         |
                                              ExposureMask           |
                                              EnterWindowMask        |
                                              LeaveWindowMask        |
//                                              VisibilityChangeMask   |
                                              FocusChangeMask;


		    mWindow = XCreateWindow(x11display,
                                    RootWindow(x11display, mScreenID),
                                    windowDesc.position.x, windowDesc.position.y,
                                    windowDesc.dimensions.x, windowDesc.dimensions.y,
                                    1, /* border width */
                                    CopyFromParent, /* color depth */
                                    InputOutput, /* window class */
                                    visual,
                                    CWBackPixel | CWBorderPixel | CWEventMask | CWOverrideRedirect /* enabled attributes */,
                                    &attributes);

            XStoreName(x11display, mWindow, windowTitle.c_str());

            // Override of the 'x' button (the closing one)
            Atom wmDeleteMessage = XInternAtom(x11display, "WM_DELETE_WINDOW", false);
            XSetWMProtocols(x11display, mWindow, &wmDeleteMessage, 1);
		}
示例#13
0
文件: CXWindow.cpp 项目: jdc2172/clop
///////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////
CXWindow::CXWindow(int SizeX, int SizeY)
{
 display = XOpenDisplay(0);
 FATAL(!display);
 win = XCreateSimpleWindow(display,
                           DefaultRootWindow(display),
                           0,
                           0,
                           SizeX,
                           SizeY,
                           0, // Border width
                           0,
                           0);
 {
  XGCValues gcv;
  gcv.graphics_exposures = False;
  gc = XCreateGC(display, win, GCGraphicsExposures, &gcv);
 }
 screen = XDefaultScreen(display);
 pvis = XDefaultVisual(display, screen);
 map = XDefaultColormap(display,DefaultScreen(display));
 XColor exact;
 XAllocNamedColor(display, map, "white", &White, &exact);
 XAllocNamedColor(display, map, "black", &Black, &exact);
 XAllocNamedColor(display, map, "grey41", &DimGrey, &exact);
 XAllocNamedColor(display, map, "grey82", &LightGrey, &exact);

 if (pvis->red_mask && pvis->green_mask && pvis->blue_mask)
 {
  RMult = MultValue(pvis->red_mask);
  RMax = MaxValue(pvis->red_mask);
  GMult = MultValue(pvis->green_mask);
  GMax = MaxValue(pvis->green_mask);
  BMult = MultValue(pvis->blue_mask);
  BMax = MaxValue(pvis->blue_mask);
 }
 else 
  RMult = RMax = GMult = GMax = BMult = BMax = 0;

 wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0);
 XSetWMProtocols(display, win, &wm_delete_window, 1);

 XMapRaised(display, win);
}
int DisplayWindow(int width,int height, int positionX,int positionY){
  int ret =1;
  WindowProperties.width=width;
  WindowProperties.height=height;

  if ((WindowProperties.display = XOpenDisplay(NULL)) == NULL) ret = 0;
  else {  
    WindowProperties.screen = DefaultScreen(WindowProperties.display);
    WindowProperties.dplanes = DisplayPlanes(WindowProperties.display,WindowProperties.screen);   
    WindowProperties.visual = XDefaultVisual(WindowProperties.display,WindowProperties.screen);
    if (!(WindowProperties.window=XCreateSimpleWindow(WindowProperties.display,RootWindow(WindowProperties.display,WindowProperties.screen),positionX,positionY,width,height,1,BlackPixel(WindowProperties.display,WindowProperties.screen),WhitePixel(WindowProperties.display,WindowProperties.screen)))) ret = 0;
    else{
      XSelectInput(WindowProperties.display, WindowProperties.window, EventMask);
      WindowProperties.gc = XCreateGC(WindowProperties.display, WindowProperties.window, 0, &WindowProperties.values);
      XMapWindow(WindowProperties.display,WindowProperties.window);
      XSync(WindowProperties.display,False);
      WindowProperties.ximage = XCreateImage(WindowProperties.display,WindowProperties.visual,WindowProperties.dplanes,ZPixmap,0,malloc(width*height*sizeof(int)),width,height,8,0);
    }
    return ret;
  }
}
示例#15
0
void pxBuffer::blit(pxSurfaceNative s, int dstLeft, int dstTop, 
                    int dstWidth, int dstHeight,
                    int srcLeft, int srcTop)
{
  XImage* image = ::XCreateImage(s->display,
                                 XDefaultVisual(s->display,
                                                XDefaultScreen(s->display)),
                                 24,ZPixmap, 0, (char*)base(),
                                 width(), height(), 32, stride());
  
  if (image)
  {
    ::XPutImage(s->display, s->drawable, s->gc, image, srcLeft, srcTop,
                dstLeft, dstTop, dstWidth, dstHeight);

    // If we don't NULL this out XDestroyImage will damage
    // the heap by trying to free it internally
    image->data = NULL;
    XDestroyImage(image);
  }
}
示例#16
0
文件: lcd_hal.c 项目: Laxa/quals-2016
void InitX( void )
{
	int i;
	char *pSkinPixelData;
	char *pSkinPixelCur;
	char *pBadgeSkinImageData;
	int status;
	unsigned long black,white;
	socklen_t len;
	struct sockaddr_in peer;
	char ipstr[256];
	int port;

	// Get peername for stdin FD
	len = sizeof(peer);
	if ( getpeername( 0, &peer, &len) == -1 )
	{
		printf( "Couldn't get peername!\n" );
		exit(-1);
	}

	// deal with both IPv4 and IPv6:
#if DEBUG_PRINT_HELPER
	printf( "Peer IP Address: %s\n", inet_ntoa(peer.sin_addr) );
	printf( "Peer Port: %d\n", ntohs(peer.sin_port) );
#endif

	/*
	if (addr.ss_family == AF_INET) 
	{
	    struct sockaddr_in *s = (struct sockaddr_in *)&addr;
	    port = ntohs(s->sin_port);
	    inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
	} 
	else 
	{ // AF_INET6
	    struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
	    port = ntohs(s->sin6_port);
	    inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
	}
	*/

	char szDisplayHost[512];
	sprintf( szDisplayHost, "%s:0", inet_ntoa(peer.sin_addr) );

        g_badgeDisplay = XOpenDisplay( szDisplayHost );
	
	if ( g_badgeDisplay == NULL )
	{
		printf( "Couldn't open X11 display (%s)!\n", szDisplayHost  );
		exit(-1);
	}
	
        g_screen = DefaultScreen( g_badgeDisplay );
 
        black = BlackPixel( g_badgeDisplay, g_screen );
        white = WhitePixel( g_badgeDisplay, g_screen );

        g_badgeWindow = XCreateSimpleWindow( g_badgeDisplay, RootWindow( g_badgeDisplay, g_screen ),0,0, g_badgeskinwidth, g_badgeskinheight, 1, black, black);
        
	XSetStandardProperties( g_badgeDisplay, g_badgeWindow, "Badger Service", "Badger",None,NULL,0,NULL);

        XSelectInput( g_badgeDisplay, g_badgeWindow, ExposureMask|ButtonPressMask|KeyPressMask|KeyReleaseMask );
        
	g_GC = DefaultGC( g_badgeDisplay, g_screen );// XCreateGC( g_badgeDisplay, g_badgeWindow, 0, 0 );
	/*
        XSetBackground( g_badgeDisplay, g_GC, white );
        XSetForeground( g_badgeDisplay, g_GC, black);
	*/

        //XClearWindow( g_badgeDisplay, g_badgeWindow );
        //XMapRaised( g_badgeDisplay, g_badgeWindow );
	XMapWindow( g_badgeDisplay, g_badgeWindow );

	// Get image data
	pSkinPixelData = malloc( g_badgeskinwidth*g_badgeskinheight * 4 );

	i = (g_badgeskinwidth * g_badgeskinheight);

	pSkinPixelCur = pSkinPixelData;
	pBadgeSkinImageData = g_badgeskinimage;
	while ( i-- > 0 )
	{
		char temp;
		HEADER_PIXEL( pBadgeSkinImageData, pSkinPixelCur )
		temp = pSkinPixelCur[0];
		pSkinPixelCur[0] = pSkinPixelCur[2];
		pSkinPixelCur[2] = temp;

		pSkinPixelCur[3] = 0;
		pSkinPixelCur += 4;
	}

	g_pBadgeSkinImage = XCreateImage( g_badgeDisplay, XDefaultVisual( g_badgeDisplay, g_screen ), XDefaultDepth( g_badgeDisplay, g_screen ), ZPixmap, 0, pSkinPixelData, g_badgeskinwidth, g_badgeskinheight, 32, 0 );

	if ( !g_pBadgeSkinImage )
	{
		printf( "Failed to XCreateImage from pixel data!\n" );
		exit(1);
	}
	
}
示例#17
0
文件: Main.c 项目: juddy/edcde
/*++++++++++++++++++++++++++++++++++++++*/
int 
main(
        int argc,
        char **argv )
{
    int             n;
    Arg             args[MAX_ARGS];
    XEvent          event;
    XPropertyEvent *pEvent=(XPropertyEvent *)&event;
    long            mwmFunc;
    Boolean         useMaskRtn, useIconFileCacheRtn;    
    char           *dirs = NULL;
    char           *string;
	Visual         *visual;

#ifdef USERHELP
malloc_check(1);
malloc_trace(0);
#endif

    XtSetLanguageProc(NULL, NULL, NULL);
    _DtEnvControl(DT_ENV_SET); 
    

    /* Initialize the toolkit and open the display */
    style.shell = 
        XtInitialize(argv[0], XMCLASS, option_list, 1, (int *)&argc, argv);

#ifdef __osf__
    _XmColorObjCreate(style.shell, NULL, NULL);
#endif

    /* Allow all WS manipulation functions except resize and maximize */
    mwmFunc = MWM_FUNC_ALL ^ (MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE); 

    n = 0;
    XtSetArg(args[n], XmNmwmFunctions, mwmFunc); n++;
    XtSetArg(args[n], XmNuseAsyncGeometry, True); n++;
    XtSetValues(style.shell, args, n);

    /* initialize global style data */

    style.display    = XtDisplay(style.shell);
    style.screen     = DefaultScreenOfDisplay(style.display);
    style.screenNum  = DefaultScreen(style.display);
    style.colormap   = DefaultColormap(style.display, style.screenNum);
    style.root       = DefaultRootWindow(style.display);
    style.execName   = argv[0];
    style.errDialog  = NULL;
    style.tmpXmStr   = NULL;
    style.home = (char *) XtMalloc(strlen((char *) getenv("HOME")) + 1);
    strcpy(style.home, (char *) getenv("HOME"));
    style.colorDialog = NULL;
    style.backdropDialog = NULL;
    style.fontDialog = NULL;
    style.kbdDialog = NULL;
    style.mouseDialog = NULL;
    style.audioDialog = NULL;
    style.screenDialog = NULL;
    style.startupDialog = NULL;
    style.dtwmDialog = NULL;
    style.i18nDialog = NULL;
	visual = XDefaultVisual(style.display,style.screenNum);
	style.visualClass = visual->class;
    
    if (progName = DtStrrchr(argv[0], '/')) progName++;
    else progName = argv[0];

    /* Get the lock established to ensure only one dtstyle process
     * is running per screen .. first malloc enough space*/

    if (_DtGetLock (style.display, STYLE_LOCK) == 0)
    {
        _DtSimpleError (progName, DtError, NULL, "%s",
	     ((char *)GETMESSAGE(2, 5, "Style Manager is already running, second attempt aborted.")));
        exit(1);
    }

    InitDtstyleProtocol();
    SetWindowProperties();

    /* Register error handlers */
    XSetErrorHandler(ErrorHandler);
    XSetIOErrorHandler(IOErrorHandler);
    XtAppSetErrorHandler(XtWidgetToApplicationContext(style.shell),
                         ToolkitErrorHandler);
    XtAddEventHandler(style.shell, StructureNotifyMask, 0,
                         (XtEventHandler)MwmReparentNotify, NULL);

    /* set up resolution dependent layout variables */
    switch (_DtGetDisplayResolution(style.display, style.screenNum))
    {
        case LOW_RES_DISPLAY:
            style.horizontalSpacing = 
            style.verticalSpacing = 3;
            break;
            
        case MED_RES_DISPLAY:
            style.horizontalSpacing = 
            style.verticalSpacing = 5;
            break;
            
        case HIGH_RES_DISPLAY:
            style.horizontalSpacing = 
            style.verticalSpacing = 8;
            break;
    }
    
    GetApplicationResources();
    
    XmeGetIconControlInfo(style.screen, &useMaskRtn,
			  &style.useMultiColorIcons, &useIconFileCacheRtn);
    
    
    /* add the directory $HOME/.dt/backdrops */
    
    string = (char *)XtMalloc(strlen(style.home) + strlen("/.dt/backdrops:") + 1);
    sprintf(string, "%s/.dt/backdrops:", style.home);

    dirs = (char *)XtCalloc(1, strlen("/etc/dt/backdrops:/usr/dt/backdrops") + 
			    (style.xrdb.backdropDir == NULL ? 2 :
			    strlen(style.xrdb.backdropDir)) + 
			    strlen(string) + 2);
  

    strcpy(dirs, string);
    if (style.xrdb.backdropDir) 
      {
	strcat(dirs, style.xrdb.backdropDir);
	strcat(dirs, ":"); 
      }
    strcat(dirs, "/etc/dt/backdrops:/usr/dt/backdrops");

    _DtWsmSetBackdropSearchPath(style.screen, dirs, style.useMultiColorIcons);

    if (string != NULL)
      XtFree((char *)string);
    
    if (dirs != NULL)
      XtFree((char *)dirs); 
    
    

    style.count = 0;
    /* if this is started from save session we need to set up the BMS
       first, otherwise do it after making the window. (for user perception
       for how long it takes for the dtstyle to come up) */
    if(style.xrdb.session != NULL) {
      DtInitialize (style.display, style.shell, progName, progName);
      /*Restore a session or build and display the main Window.*/
      if(!restoreSession(style.shell,style.xrdb.session))
	init_mainWindow(style.shell);
    }
    else {
      init_mainWindow(style.shell);
      DtInitialize (style.display, style.shell, progName, progName);
      InitializeAtoms();
      CheckMonitor(style.shell);
      GetDefaultPal(style.shell);
    }
    
    signal(SIGINT,(void (*)())activateCB_exitBtn); 
    signal(SIGTERM,(void (*)())activateCB_exitBtn); 

    /* to avoid defunct screen saver processes */    
    signal(SIGCHLD, (void (*)())WaitChildDeath);

    /* backdrop dialog  needs to know when the workspace changes to recolor 
       the bitmap displayed in the dialog */
    ListenForWorkspaceChange();

    /* if using COLOR builtin, style.workProcs is True */

    if ((XmeUseColorObj() != FALSE) && style.workProcs)

        XtAppAddWorkProc(XtWidgetToApplicationContext(style.shell), 
                        NewCreateD, style.shell);

    XtAppMainLoop(XtWidgetToApplicationContext(style.shell));

    return 0;
}
示例#18
0
文件: ogl.c 项目: tcbabu/kglib
int  kgInitglWindow(void* Gtmp) {
#if 0	
    int snglBuf[] ={GLX_RGBA,GLX_RED_SIZE,1,GLX_GREEN_SIZE,1,
	            GLX_BLUE_SIZE,1,GLX_DEPTH_SIZE,12,None};
    int dblBuf[] ={GLX_RGBA,GLX_RED_SIZE,1,GLX_GREEN_SIZE,1,
	            GLX_BLUE_SIZE,1,GLX_DEPTH_SIZE,12,GLX_DOUBLEBUFFER,None};
#endif
    DIG *G;
    int snglBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, None};
    int dblBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None};
    XVisualInfo *vInfoMain;
    GLXContext *cMain;
    Window wMain,*sWin;
    int nvis,dummy;
    XVisualInfo  sampleVis;
    Display *xDisplay;
    int xScreen;
    DIALOG *D;
    kgWC *wc;
    G = (DIG *)Gtmp;
    D = (DIALOG *)G->D;
    wc = WC(D);
    xDisplay = wc->Dsp;
#if 1
    if(!glXQueryExtension(xDisplay, &dummy, &dummy)) {
      printf("X server has no OpenGL GLX extension\n");
      return 0;
    }
#endif
    xScreen = DefaultScreen(xDisplay);
    kgSubWindow(Gtmp);
    sWin = (Window *)G->glWindow;
    wMain = *sWin;
#if 0
    sampleVis.screen = xScreen;
    sampleVis.depth = DisplayPlanes(xDisplay,DefaultScreen(xDisplay));
    sampleVis.visual = XDefaultVisual(xDisplay,DefaultScreen(xDisplay));
    sampleVis.visualid = XVisualIDFromVisual(
         XDefaultVisual(xDisplay,DefaultScreen(xDisplay)));
    vInfoMain =  XGetVisualInfo(xDisplay,
       VisualIDMask|VisualScreenMask|VisualDepthMask,&sampleVis, &nvis);
#else
    vInfoMain =  glXChooseVisual(xDisplay,xScreen,dblBuf);
    if(vInfoMain == NULL) {
      vInfoMain =  glXChooseVisual(xDisplay,xScreen,snglBuf);
      if(vInfoMain == NULL) {
	      printf("No RGB Visual with Depth Buffer\n");
	      return GL_FALSE;
      }
      else { 
        G->glDouble=0;
	printf("RGB Visual with Depth Buffer(single)\n");
      }
	
    }
    else {
      G->glDouble=1;
      printf("RGB Visual with Depth Buffer(double)\n");
    }
    if(vInfoMain->class != TrueColor) {
	    printf("TrueColor visual required for this program\n");
	    exit(1);
    }
#endif
    cMain = (GLXContext *)malloc(sizeof(GLXContext));
    *cMain = glXCreateContext(xDisplay, vInfoMain, None,
			       GL_TRUE);
    if (!(*cMain)) {
	fprintf(stderr, "Can't create a context!\n");
	return GL_FALSE;
    }
    G->cMain = (void *) cMain;

    if (!glXMakeCurrent(xDisplay, wMain, *cMain)) {
	printf( "Can't make window current drawable!\n");
	return GL_FALSE;
    }
    XMapWindow(xDisplay, wMain);
    glViewport(0,0,(G->x2-G->x1+1),(G->y2-G->y1+1));

    return GL_TRUE;
}
示例#19
0
int main(int argc, char ** argv) {
  FILE                  * fp;
  struct Image          * frame;
  Display               * display;
  XImage                * ximage;
  Window                window;
  XEvent                an_event;
  GC                    gc;
  Visual                * visual;
  XGCValues             values;
  int                   m, n, FOREGROUNDP = 0, BACKGROUNDP = 1, screen, dplanes;
  int                   IMAGE_HEIGHT, IMAGE_WIDTH;
  
  IMAGE_WIDTH = (int) atoi(argv[2]);
  IMAGE_HEIGHT = (int) atoi(argv[3]);

  if ((fp=fopen(argv[1],"rb"))==NULL) exit(1);
  frame = (struct Image *) malloc(IMAGE_WIDTH*IMAGE_HEIGHT*sizeof(struct Image));
  if (!frame) exit(1);

  if ((display = XOpenDisplay(NULL)) == NULL) {
     printf("Incapaz de conectar ao display...\n");
     exit(1);
     }
    
  screen = DefaultScreen(display);
  dplanes = DisplayPlanes(display,screen);   
  visual = XDefaultVisual(display,screen);
     
  FOREGROUNDP=BlackPixel(display,screen);
  BACKGROUNDP=WhitePixel(display,screen);
  
  if (!(window=XCreateSimpleWindow(display,RootWindow(display,screen),0,0,IMAGE_WIDTH,IMAGE_HEIGHT,1,FOREGROUNDP,BACKGROUNDP))) {
     printf("Não foi possível criar a janela...\n");
     exit(1);
     }

  XSelectInput(display, window, EventMask);
  gc = XCreateGC(display, window, 0, &values);
  
  XMapWindow(display,window);
  XSync(display,False);
  
  ximage = XCreateImage(display, visual, dplanes, ZPixmap, 0, malloc(IMAGE_WIDTH*IMAGE_HEIGHT*sizeof(int32_t)), IMAGE_WIDTH, IMAGE_HEIGHT, 8, 0);

  while (1) {
    if (fread(frame,IMAGE_WIDTH*IMAGE_HEIGHT*sizeof(struct Image),1,fp)<=0) break;
    for(m=0;m<IMAGE_HEIGHT;m++) {
      for(n=0;n<IMAGE_WIDTH;n++) {
        ximage -> data[(m*4)*IMAGE_WIDTH+n*4]   = (uint8_t) frame[m*IMAGE_WIDTH+n].blue;
        ximage -> data[(m*4)*IMAGE_WIDTH+n*4+1] = (uint8_t) frame[m*IMAGE_WIDTH+n].green;
        ximage -> data[(m*4)*IMAGE_WIDTH+n*4+2] = (uint8_t) frame[m*IMAGE_WIDTH+n].red;
        ximage -> data[(m*4)*IMAGE_WIDTH+n*4+3] = (uint8_t) 0;
        }
      }
    XPutImage(display, window, gc, ximage, 0, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
    XFlush(display);
    usleep(50000);  // 50 ms por frame -> aproximadamente 20 quadros por segundo
    } 

  sleep(5);
  fclose(fp);
  
  return 0;
  }
示例#20
0
文件: main.c 项目: ytsarko/nuklear
/* ===============================================================
 *
 *                          DEMO
 *
 * ===============================================================*/
int
main(void)
{
    long dt;
    long started;
    int running = 1;
    XWindow xw;
    struct nk_context *ctx;

    /* X11 */
    memset(&xw, 0, sizeof xw);
    xw.dpy = XOpenDisplay(NULL);
    if (!xw.dpy) die("Could not open a display; perhaps $DISPLAY is not set?");

    xw.root = DefaultRootWindow(xw.dpy);
    xw.screen = XDefaultScreen(xw.dpy);
    xw.vis = XDefaultVisual(xw.dpy, xw.screen);
    xw.cmap = XCreateColormap(xw.dpy,xw.root,xw.vis,AllocNone);
    xw.swa.colormap = xw.cmap;
    xw.swa.event_mask =
        ExposureMask | KeyPressMask | KeyReleaseMask |
        ButtonPress | ButtonReleaseMask| ButtonMotionMask |
        Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
        PointerMotionMask | KeymapStateMask;
    xw.win = XCreateWindow(xw.dpy, xw.root, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
        XDefaultDepth(xw.dpy, xw.screen), InputOutput,
        xw.vis, CWEventMask | CWColormap, &xw.swa);
    XStoreName(xw.dpy, xw.win, "X11");
    XMapWindow(xw.dpy, xw.win);
    XGetWindowAttributes(xw.dpy, xw.win, &xw.attr);
    xw.width = (unsigned int)xw.attr.width;
    xw.height = (unsigned int)xw.attr.height;

    /* GUI */
    xw.font = nk_xfont_create(xw.dpy, "fixed");
    ctx = nk_xlib_init(xw.font, xw.dpy, xw.screen, xw.win, xw.width, xw.height);

    /* style.c */
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/

    while (running)
    {
        /* Input */
        XEvent evt;
        started = timestamp();
        nk_input_begin(ctx);
        while (XCheckWindowEvent(xw.dpy, xw.win, xw.swa.event_mask, &evt)){
            if (XFilterEvent(&evt, xw.win)) continue;
            nk_xlib_handle_event(xw.dpy, xw.screen, xw.win, &evt);
        }
        nk_input_end(ctx);

        /* GUI */
        {struct nk_panel layout;
        if (nk_begin(ctx, &layout, "Demo", nk_rect(50, 50, 200, 200),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
            NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
        {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;

            nk_layout_row_static(ctx, 30, 80, 1);
            if (nk_button_label(ctx, "button"))
                fprintf(stdout, "button pressed\n");
            nk_layout_row_dynamic(ctx, 30, 2);
            if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
            nk_layout_row_dynamic(ctx, 25, 1);
            nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);
        }
        nk_end(ctx);}
        if (nk_window_is_closed(ctx, "Demo")) break;

        /* -------------- EXAMPLES ---------------- */
        /*calculator(ctx);*/
        /*overview(ctx);*/
        /*node_editor(ctx);*/
        /* ----------------------------------------- */

        /* Draw */
        XClearWindow(xw.dpy, xw.win);
        nk_xlib_render(xw.win, nk_rgb(30,30,30));
        XFlush(xw.dpy);

        /* Timing */
        dt = timestamp() - started;
        if (dt < DTIME)
            sleep_for(DTIME - dt);
    }

    nk_xfont_del(xw.dpy, xw.font);
    nk_xlib_shutdown();
    XUnmapWindow(xw.dpy, xw.win);
    XFreeColormap(xw.dpy, xw.cmap);
    XDestroyWindow(xw.dpy, xw.win);
    XCloseDisplay(xw.dpy);
    return 0;
}
示例#21
0
int main(int argc, char ** argv) {
  FILE                  * fp;
  Display               * display;
  XImage                * ximage;
  Window                window;
  GC                    gc;
  Visual                * visual;
  XGCValues             values;
  int                   m, n, FOREGROUNDP = 0, BACKGROUNDP = 1, screen, dplanes;

  int                   IMAGE_HEIGHT, IMAGE_WIDTH;
	float *tdc;

  fp = fopen(argv[1],"rb");

	// recupera a tdc do arquivo
	fread(&IMAGE_WIDTH, sizeof(int), 1, fp);
	fread(&IMAGE_HEIGHT, sizeof(int), 1, fp);

	tdc = malloc(sizeof(float) * 3 * IMAGE_WIDTH * IMAGE_HEIGHT);
	fread(tdc, sizeof(float), 3 * IMAGE_WIDTH * IMAGE_HEIGHT, fp);
  fclose(fp);

	// aplica a itdc 
	Image *itdc = malloc(sizeof(Image) * IMAGE_WIDTH * IMAGE_HEIGHT);
	frame_itdc(&itdc, IMAGE_WIDTH, IMAGE_HEIGHT, &tdc);

  if ((display = XOpenDisplay(NULL)) == NULL) {
     printf("Incapaz de conectar ao display...\n");
     exit(1);
  }
    
	/* ---------------- funcoes do XDisplay ---------------- */
  screen = DefaultScreen(display);
  dplanes = DisplayPlanes(display,screen);   
  visual = XDefaultVisual(display,screen);
     
  FOREGROUNDP=BlackPixel(display,screen);
  BACKGROUNDP=WhitePixel(display,screen);
  
  if (!(window=XCreateSimpleWindow(display,RootWindow(display,screen),0,0,IMAGE_WIDTH,IMAGE_HEIGHT,1,FOREGROUNDP,BACKGROUNDP))) {
     printf("Não foi possível criar a janela...\n");
     exit(1);
     }

  XSelectInput(display, window, EventMask);
  gc = XCreateGC(display, window, 0, &values);
  
  XMapWindow(display,window);
  XSync(display,False);
  
  ximage = XCreateImage(display, visual, dplanes, ZPixmap, 0, malloc(IMAGE_WIDTH*IMAGE_HEIGHT*sizeof(int)), IMAGE_WIDTH, IMAGE_HEIGHT, 8, 0);
	/* ------------------------------------------------ */

	// Carrega os valores da itdc para exibir 
  for(m=0;m<IMAGE_HEIGHT;m++) {
    for(n=0;n<IMAGE_WIDTH;n++) {
      ximage -> data[(m*4)*IMAGE_WIDTH+n*4] = itdc[m*IMAGE_WIDTH+n].blue;
      ximage -> data[(m*4)*IMAGE_WIDTH+n*4+1] = itdc[m*IMAGE_WIDTH+n].green;
      ximage -> data[(m*4)*IMAGE_WIDTH+n*4+2] = itdc[m*IMAGE_WIDTH+n].red;
      ximage -> data[(m*4)*IMAGE_WIDTH+n*4+3] = 0;
      }
    }

  XPutImage(display, window, gc, ximage, 0, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);

  sleep(10);
  
	free(tdc);
	free(itdc);

  return 0;
}
示例#22
0
/* ===============================================================
 *
 *                          DEMO
 *
 * ===============================================================*/
int
main(void)
{
    long dt;
    long started;
    int running = 1;
    int status;
    XWindow xw;
    struct rawfb_context *rawfb;
    void *fb = NULL;
    unsigned char tex_scratch[512 * 512];

    /* X11 */
    memset(&xw, 0, sizeof xw);
    xw.dpy = XOpenDisplay(NULL);
    if (!xw.dpy) die("Could not open a display; perhaps $DISPLAY is not set?");

    xw.root = DefaultRootWindow(xw.dpy);
    xw.screen = XDefaultScreen(xw.dpy);
    xw.vis = XDefaultVisual(xw.dpy, xw.screen);
    xw.cmap = XCreateColormap(xw.dpy,xw.root,xw.vis,AllocNone);
    xw.swa.colormap = xw.cmap;
    xw.swa.event_mask =
        ExposureMask | KeyPressMask | KeyReleaseMask |
        ButtonPress | ButtonReleaseMask| ButtonMotionMask |
        Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
        PointerMotionMask | KeymapStateMask | EnterWindowMask | LeaveWindowMask;
    xw.win = XCreateWindow(xw.dpy, xw.root, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
        XDefaultDepth(xw.dpy, xw.screen), InputOutput,
        xw.vis, CWEventMask | CWColormap, &xw.swa);

    XStoreName(xw.dpy, xw.win, "X11");
    XMapWindow(xw.dpy, xw.win);
    XGetWindowAttributes(xw.dpy, xw.win, &xw.attr);
    xw.width = (unsigned int)xw.attr.width;
    xw.height = (unsigned int)xw.attr.height;

    /* Framebuffer emulator */
    status = nk_xlib_init(xw.dpy, xw.vis, xw.screen, xw.win, xw.width, xw.height, &fb);
    if (!status || !fb)
        return 0;

    /* GUI */
    rawfb = nk_rawfb_init(fb, tex_scratch, xw.width, xw.height, xw.width * 4);
    if (!rawfb) running = 0;

    #ifdef INCLUDE_STYLE
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/
    #endif

    while (running) {
        /* Input */
        XEvent evt;
        started = timestamp();
        nk_input_begin(&rawfb->ctx);
        while (XCheckWindowEvent(xw.dpy, xw.win, xw.swa.event_mask, &evt)) {
            if (XFilterEvent(&evt, xw.win)) continue;
            nk_xlib_handle_event(xw.dpy, xw.screen, xw.win, &evt, rawfb);
        }
        nk_input_end(&rawfb->ctx);

        /* GUI */
        if (nk_begin(&rawfb->ctx, "Demo", nk_rect(50, 50, 200, 200),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|
            NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE)) {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;

            nk_layout_row_static(&rawfb->ctx, 30, 80, 1);
            if (nk_button_label(&rawfb->ctx, "button"))
                fprintf(stdout, "button pressed\n");
            nk_layout_row_dynamic(&rawfb->ctx, 30, 2);
            if (nk_option_label(&rawfb->ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(&rawfb->ctx, "hard", op == HARD)) op = HARD;
            nk_layout_row_dynamic(&rawfb->ctx, 25, 1);
            nk_property_int(&rawfb->ctx, "Compression:", 0, &property, 100, 10, 1);
        }
        nk_end(&rawfb->ctx);
        if (nk_window_is_closed(&rawfb->ctx, "Demo")) break;

        /* -------------- EXAMPLES ---------------- */
        #ifdef INCLUDE_CALCULATOR
          calculator(ctx);
        #endif
        #ifdef INCLUDE_OVERVIEW
          overview(ctx);
        #endif
        #ifdef INCLUDE_NODE_EDITOR
          node_editor(ctx);
        #endif
        /* ----------------------------------------- */

        /* Draw framebuffer */
        nk_rawfb_render(rawfb, nk_rgb(30,30,30), 1);

        /* Emulate framebuffer */
        XClearWindow(xw.dpy, xw.win);
        nk_xlib_render(xw.win);
        XFlush(xw.dpy);

        /* Timing */
        dt = timestamp() - started;
        if (dt < DTIME)
            sleep_for(DTIME - dt);
    }

    nk_rawfb_shutdown(rawfb);
    nk_xlib_shutdown();
    XUnmapWindow(xw.dpy, xw.win);
    XFreeColormap(xw.dpy, xw.cmap);
    XDestroyWindow(xw.dpy, xw.win);
    XCloseDisplay(xw.dpy);
    return 0;
}
示例#23
0
static Error
init_memory_visual (struct dispinfo *d)
{
    int		x, y;
    int		w, h;
    int		border;
    XSizeHints	hint;
    Colormap	colors;
    XColor	shade;
    XColor	exact;
    XGCValues	val;
    long	flags;


    if ((d->disp = open_memory_visual_display ()) == (Display *) NULL)
	return ERROR;
    
    d->fd = ConnectionNumber(d->disp);

    x 	   = 0;	     	/* default to opening window in upper left */
    y 	   = 0;
    w 	   = d->win_width;
    h	   = d->win_height;
    border = BORDER;

    hint.x		= x;
    hint.y		= y;
    hint.width		= w;
    hint.height		= h;
    hint.min_width	= w;
    hint.min_height	= h;
    hint.max_width	= w;
    hint.max_height	= h;
    hint.flags		= PPosition | PSize | USPosition | USSize;

    d->wind = XCreateSimpleWindow (d->disp, DefaultRootWindow (d->disp),
			        x, y, w, h, border,
				WhitePixel (d->disp, DefaultScreen (d->disp)),
				BlackPixel (d->disp, DefaultScreen (d->disp)));

    XSetStandardProperties (d->disp, d->wind, d->title, d->title, None, NULL, 
			    0, &hint);

    XSelectInput(d->disp, d->wind, 
		 ExposureMask | 
		 StructureNotifyMask |
		 ButtonPressMask |
		 ButtonReleaseMask);

    /*
     * Now get the pixel values for the colormaps and create the GCs
     */

    val.background = BlackPixel (d->disp, DefaultScreen (d->disp));
    flags = GCForeground | GCBackground;
    colors = DefaultColormap (d->disp, DefaultScreen (d->disp));

    d->gc = XCreateGC (d->disp, d->wind, flags, &val);

    XAllocNamedColor (d->disp, colors, COLOR_ALLOC, &shade, &exact);
    color_alloc = (ubyte) shade.pixel;
    XAllocNamedColor (d->disp, colors, COLOR_SMALLOC, &shade, &exact);
    color_smallalloc = (ubyte) shade.pixel;
    XAllocNamedColor (d->disp, colors, COLOR_FREE, &shade, &exact);
    color_free = (ubyte) shade.pixel;
    XAllocNamedColor (d->disp, colors, COLOR_TRACE, &shade, &exact);
    color_trace = (ubyte) shade.pixel;
    XAllocNamedColor (d->disp, colors, COLOR_EXTRA, &shade, &exact);
    color_extra = (ubyte) shade.pixel;


    d->memory_pixel = (ubyte *) DXAllocate(w * h);
    memset (d->memory_pixel, color_free, w * h);

    d->memory_image = XCreateImage (d->disp,
			   XDefaultVisual (d->disp, XDefaultScreen (d->disp)),
			   8, ZPixmap, 0, (char *) d->memory_pixel, 
			   w, h, 8, 0);
    
    XSetErrorHandler(error_handler);

    /* refresh image once */
    d->refresh = 1;
    if (!handler_script(d->fd, d))
	goto error;

    /* arrange for it to appear, and appear on top */
    XMapRaised(d->disp, d->wind);
    XFlush(d->disp);

    /* register with executive to get X events */
    DXRegisterInputHandlerWithCheckProc(
	(Handler)handler_script, (Checker)XChecker, d->fd, (Pointer)d);

    if (xerror) goto error;
    return OK;

  error:
    xerror = 0;
    return ERROR;
}
示例#24
0
文件: Menu.C 项目: bbidulock/wmx
Menu::Menu(WindowManager *manager, XEvent *e)
    : m_items(0), m_nItems(0), m_nHidden(0),
      m_hasSubmenus(False),
      m_windowManager(manager),
      m_event(e)
{
    if (!m_initialised)
    {
	XGCValues *values;
	XSetWindowAttributes *attr;

        m_menuGC = (GC *) malloc(m_windowManager->screensTotal() * sizeof(GC));
        m_window = (Window *) malloc(m_windowManager->screensTotal() *
				     sizeof(Window));
#ifdef CONFIG_USE_XFT
	char *fi = strdup(CONFIG_MENU_FONT);
	char *ffi = fi, *tokstr = fi;
	while ((fi = strtok(tokstr, ","))) {
		
	    fprintf(stderr, "fi = \"%s\"\n", fi);
	    tokstr = 0;
	    
	    FcPattern *pattern = FcPatternCreate();
	    FcPatternAddString(pattern, FC_FAMILY, (FcChar8 *)fi);
	    FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);

#ifndef FC_WEIGHT_REGULAR
#define FC_WEIGHT_REGULAR FC_WEIGHT_MEDIUM
#endif
	    FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_REGULAR);
	    FcPatternAddInteger(pattern, FC_PIXEL_SIZE, CONFIG_MENU_FONT_SIZE);
	    FcConfigSubstitute(FcConfigGetCurrent(), pattern, FcMatchPattern);

	    FcResult result = FcResultMatch;
	    FcPattern *match = FcFontMatch(FcConfigGetCurrent(), pattern, &result);
	    FcPatternDestroy(pattern);

	    if (!match || result != FcResultMatch) {
		if (match) FcPatternDestroy(match);
		continue;
	    }

	    m_font = XftFontOpenPattern(display(), match);
	    if (m_font) break;
	    FcPatternDestroy(match);
	}
	free(ffi);
	if (!m_font) {
	    m_windowManager->fatal("couldn't load menu Xft font");
	}
	m_xftColour = (XftColor *) malloc(m_windowManager->screensTotal() *
					  sizeof(XftColor));
	m_xftDraw = (XftDraw **) malloc(m_windowManager->screensTotal() *
					sizeof(XftDraw *));
#else
	m_font = (XFontStruct **) malloc(m_windowManager->screensTotal() *
					 sizeof(XFontStruct *));
#endif
	values = (XGCValues *) malloc(m_windowManager->screensTotal() *
				      sizeof(XGCValues));
	attr = (XSetWindowAttributes *) malloc(m_windowManager->screensTotal() *
				      sizeof(XSetWindowAttributes));
	
        for (int i = 0; i < m_windowManager->screensTotal(); i++)
	{
	    m_foreground = m_windowManager->allocateColour
	      (i, CONFIG_MENU_FOREGROUND, "menu foreground");
	    m_background = m_windowManager->allocateColour
	      (i, CONFIG_MENU_BACKGROUND, "menu background");
	    m_border = m_windowManager->allocateColour
	      (i, CONFIG_MENU_BORDERS, "menu border");

#ifndef CONFIG_USE_XFT
	    char **ml;
	    int mc;
	    char *ds;
	    
	    m_fontset = XCreateFontSet(display(), CONFIG_NICE_MENU_FONT,
				       &ml, &mc, &ds);
	    if (!m_fontset)
	      m_fontset = XCreateFontSet(display(), CONFIG_NASTY_FONT,
					 &ml, &mc, &ds);
	    if (m_fontset) {
		XFontStruct **fs_list;
		XFontsOfFontSet(m_fontset, &fs_list, &ml);
		m_font[i] = fs_list[0];
	    } else {
		m_font[i] = NULL;
	    }
#define XDrawString(t,u,v,w,x,y,z) XmbDrawString(t,u,m_fontset,v,w,x,y,z)
	    if (!m_font[i]) m_windowManager->fatal("couldn't load menu font\n");
#endif
	    
	    values[i].background = m_background;
	    values[i].foreground = m_foreground ^ m_background;
	    values[i].function = GXxor;
	    values[i].line_width = 0;
	    values[i].subwindow_mode = IncludeInferiors;
#ifndef CONFIG_USE_XFT
	    values[i].font = m_font[i]->fid;
#endif
	    m_menuGC[i] = XCreateGC
	      (display(), m_windowManager->mroot(i),
	       GCForeground | GCBackground | GCFunction |
	       GCLineWidth | GCSubwindowMode, &values[i]);

#ifndef CONFIG_USE_XFT
	    XChangeGC(display(), Border::drawGC(m_windowManager, i),
		      GCFont, &values[i]);
#endif

	    m_window[i] = XCreateSimpleWindow
	      (display(), m_windowManager->mroot(i), 0, 0, 1, 1, 1,
	       m_border, m_background);

	    
#if ( CONFIG_USE_PIXMAPS != False ) && ( CONFIG_USE_PIXMAP_MENUS != False )
	    attr[i].background_pixmap = Border::backgroundPixmap(manager);
#endif
	    attr[i].save_under =
	      (DoesSaveUnders(ScreenOfDisplay(display(), i)) ?
	     True : False);

#if ( CONFIG_USE_PIXMAPS != False ) && ( CONFIG_USE_PIXMAP_MENUS != False )
	    XChangeWindowAttributes
	      (display(), m_window[i], CWBackPixmap, &attr[i]);
#endif
	    XChangeWindowAttributes
	      (display(), m_window[i], CWSaveUnder, &attr[i]);

#ifdef CONFIG_USE_XFT
	    XftColorAllocName
		(display(),
		 XDefaultVisual(display(), i),
		 XDefaultColormap(display(), i),
		 CONFIG_MENU_FOREGROUND,
		 &m_xftColour[i]);

	    m_xftDraw[i] = XftDrawCreate(display(), m_window[i],
					 XDefaultVisual(display(), i),
					 XDefaultColormap(display(), i));
#endif
	}
	m_initialised = True;
    }
}
示例#25
0
static BOOL CreateDeviceColormap(Display *display, int screen,
	int minplanes, int maxplanes)
{
	int i, j;
	unsigned long *pixels, planes[32];

	/* pass 1: allocate colors from default colormap
	 * pass 2: create colormap & allocate colors from new colormap
	 */
	DeviceColormapSize = (XDefaultVisual(display, screen))->map_entries;
	for (i = 0; i < 2; i++)
	{
		/* pass 1: get default colormap
		 * pass 2: create custom colormap
		 */
		if (i == 0)
		{
			DeviceColormap = XDefaultColormap(display, screen);
		}
		else
		{
			DeviceColormap = XCreateColormap(display,
				XRootWindow(display, screen),
				XDefaultVisual(display, screen),
				AllocNone);
		}
		/* pass 1: save default colormap colors for pass 2
		 * pass 2: initialize with default colormap colors to minimize
		 *	   techni-color(tm) effect
		 */
		if (i == 0)
		{
			DeviceColormapValues = (XColor *)
				WinMalloc(DeviceColormapSize * sizeof(XColor));
			for (j = 0; j < DeviceColormapSize; j++)
			{
				DeviceColormapValues[j].pixel = j;
			}
			XQueryColors(display, DeviceColormap,
				DeviceColormapValues,
				DeviceColormapSize);
		}
		else
		{
			pixels = (unsigned long *) WinMalloc(DeviceColormapSize *
				sizeof(unsigned long));
			XAllocColorCells(display, DeviceColormap, True,
				planes, 0, pixels, DeviceColormapSize);
			XStoreColors(display, DeviceColormap,
				DeviceColormapValues,
				DeviceColormapSize);
			XFreeColors(display, DeviceColormap, pixels,
				DeviceColormapSize, 0L);
		}
		/* allocate as many color planes as possible */
		if ((minplanes < 1) || (maxplanes < 1))
			break;
		for (j = maxplanes; j >= minplanes; j--)
		{
			if (!XAllocColorCells(display, DeviceColormap, True,
				pixel_masks, j, &pixel0, 1))
			{
				continue;
			}
			pixel_numplanes = j;
			pixel_mask0 = ~0;
			for (pixel_mask = 0, j = 0; j < pixel_numplanes; j++)
			{
				pixel_mask |= pixel_masks[j];
				pixel_mask0 = min(pixel_mask0, pixel_masks[j]);
			}
			break;
		}
		if (j >= minplanes)
			break;
	}
	if (i == 2)
	{
		ERRSTR((LF_WARNING, 
			"%s: Unable to alloc %d to %d planes.\n",
			"CreateDeviceColormap",
			minplanes, maxplanes));
		return (FALSE);
	}

	/* success */
	return (TRUE);

}
示例#26
0
文件: mpng.c 项目: mcgrew/lxvt
long
PngReadFileToPixmap (Display* display, Window window, GC gc, char* filename, Pixmap* pixmap, long* w, long* h)
{
    int red_mask, green_mask, blue_mask;
    int red_shift, green_shift, blue_shift;
    int start_shift, msb_flag;
    unsigned int start_mask, udat;
    XWindowAttributes win_attr;
    FILE* ifile;
  long display_depth;
      png_byte            sig[8];
  png_infop info_ptr;
  png_structp png_ptr;
      png_uint_32 png_width;
    png_uint_32 png_height;
    int png_depth;
    int png_color_type;
png_uint_32 png_row_bytes;
  png_uint_32 png_channels;
    long rwidth;
    long rheight;
    long components;
    unsigned char* buf;
    png_byte** png_row_ptrs;
    long vwidth;
    long vheight;
    long stretched;
    XImage* image;
    Visual* visual;
    Pixmap pix;
    int i;
    char* data1;
    unsigned char r,g,b;
    long ptr = 0;
    long ptr2 = 0;
    long j;

    red_mask = green_mask = blue_mask = 0;
    red_shift = green_shift = blue_shift = 0;

    ifile = fopen(filename,"r");
    if (ifile == NULL){
      return -1;
    }
    display_depth = XDefaultDepth(display,XDefaultScreen(display));

    fread(sig, 1, 8, ifile);
    if (png_sig_cmp(sig, 0, 8)){
      fclose(ifile);
      return -1;
    }
    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,
      (png_error_ptr)png_cexcept_error, (png_error_ptr)NULL);
    if (png_ptr == NULL){
      fclose(ifile);
      return -1;
    } 
    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL){
      png_destroy_read_struct(&png_ptr, NULL, NULL);
      fclose(ifile);
      return -1;
    }

    png_init_io(png_ptr, ifile);
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);
    png_get_IHDR(png_ptr, info_ptr, &png_width, &png_height, &png_depth,
            &png_color_type, NULL, NULL, NULL);
    if (png_depth == 16){
      png_set_strip_16(png_ptr);
    }
    png_row_bytes = png_get_rowbytes(png_ptr, info_ptr);
    png_channels = png_get_channels(png_ptr, info_ptr);

    if (png_depth < 8){
      if (png_color_type == PNG_COLOR_TYPE_GRAY ){
        png_set_expand_gray_1_2_4_to_8(png_ptr);
        png_row_bytes = png_width;
      }else{
        png_set_expand(png_ptr);
        png_row_bytes = png_width;
        png_row_bytes = png_width * 3;
        png_channels = 3;
      }
    }
    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)){
      png_set_expand(png_ptr);
      png_row_bytes = png_width;
    }
    if (png_color_type == PNG_COLOR_TYPE_GRAY ||
        png_color_type == PNG_COLOR_TYPE_GRAY_ALPHA){
      png_set_gray_to_rgb(png_ptr);
      png_row_bytes = png_width;
    }

    if (png_color_type == PNG_COLOR_TYPE_PALETTE){
      png_set_palette_to_rgb(png_ptr);
      png_row_bytes = png_width * 3;
      png_channels = 3;
    }

    rwidth = png_width;
    rheight = png_height;
    components = png_channels;

    /* possible integer overflow? */
    assert ((int) png_row_bytes > 0);
    assert ((int) png_height > 0);
    assert (((int)png_row_bytes) * ((int)png_height) * sizeof(png_byte) > 0);
    buf = rxvt_malloc(png_row_bytes * png_height * sizeof(png_byte));
    if (buf == NULL){
      rxvt_msg (DBG_ERROR, DBG_IMAGES, "png read error: out of memory..\n");
      png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
      fclose(ifile);
      return -1;
    }
    /* possible integer overflow? */
    assert ((int) png_height > 0);
    assert (sizeof(png_bytep) * ((int)png_height) > 0);
    png_row_ptrs = rxvt_malloc (sizeof(png_bytep)*png_height);
    if (png_row_ptrs == NULL){
      rxvt_msg (DBG_ERROR, DBG_IMAGES, "png read error: out of memory..\n");
      png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
      fclose(ifile);
      return -1;
    }

    for(i = 0; i < (int)png_height; i++){
      png_row_ptrs[i] = (png_byte*)(buf + i * png_row_bytes);
    }
    png_read_image(png_ptr, png_row_ptrs);
    png_read_end(png_ptr,NULL);
    rxvt_free(png_row_ptrs);

    vwidth = *w;
    vheight = *h;
    stretched =0;
    if (*w == 0 || *h == 0){
      *w = rwidth;
      *h = rheight;
    }else{
      if ((long)((double)rwidth * vheight/vwidth) < rheight){
        *w = (long)((double)vheight * rwidth/rheight);
      }else{
        *h = (long)((double)vwidth * rheight/rwidth);
      }
      stretched = 1;
    }
    vwidth = *w;
    vheight = *h;



    image = 0;
    visual = XDefaultVisual(display,XDefaultScreen(display));
    if (display_depth >16){
      image = XCreateImage(display,visual, display_depth,
                           ZPixmap,0,0,vwidth,vheight,32,0);
    }else
    if (display_depth >8){
      image = XCreateImage(display,visual, display_depth,
                           ZPixmap,0,0,vwidth,vheight,16,0);
    }else{
      image = XCreateImage(display,visual, display_depth,
                           ZPixmap,0,0,vwidth,vheight,8,0);
    }

    msb_flag = (ImageByteOrder(display) == MSBFirst)?1:0;

    if (XGetWindowAttributes(display,
                     RootWindow(display, DefaultScreen(display)),
                     &win_attr) == 0) {
        fclose(ifile);
                 return -1;
    }

    if ((win_attr.depth == 24) || (win_attr.depth == 16)) {
      unsigned int n;
      if (win_attr.depth == 24) {
        start_shift = 24;
        start_mask = 0x80000000;
      }else{
        start_shift = 8;
        start_mask = 0x8000;
      }
      red_mask = win_attr.visual->red_mask;
      red_shift = start_shift;
      n = start_mask;
      while (!(n & red_mask)) {
        n >>= 1;
        red_shift--;
      }
      green_mask = win_attr.visual->green_mask;
      green_shift = start_shift;
      n = start_mask;
      while (!(n & green_mask)) {
        n >>= 1;
        green_shift--;
      }
      blue_mask = win_attr.visual->blue_mask;
      blue_shift = start_shift;
      n = start_mask;
      while (!(n & blue_mask)) {
        n >>= 1;
        blue_shift--;
      }
    }
示例#27
0
文件: xlib.c 项目: Tarek-Samy/zahnrad
int
main(int argc, char *argv[])
{
    long dt;
    long started;
    XWindow xw;
    struct demo_gui gui;

    /* Platform */
    UNUSED(argc); UNUSED(argv);
    memset(&xw, 0, sizeof xw);
    xw.dpy = XOpenDisplay(NULL);
    xw.root = DefaultRootWindow(xw.dpy);
    xw.screen = XDefaultScreen(xw.dpy);
    xw.vis = XDefaultVisual(xw.dpy, xw.screen);
    xw.cmap = XCreateColormap(xw.dpy,xw.root,xw.vis,AllocNone);
    xw.swa.colormap = xw.cmap;
    xw.swa.event_mask =
        ExposureMask | KeyPressMask | KeyReleaseMask |
        ButtonPress | ButtonReleaseMask| ButtonMotionMask |
        Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
        PointerMotionMask;
    xw.win = XCreateWindow(xw.dpy, xw.root, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
        XDefaultDepth(xw.dpy, xw.screen), InputOutput,
        xw.vis, CWEventMask | CWColormap, &xw.swa);
    XStoreName(xw.dpy, xw.win, "X11");
    XMapWindow(xw.dpy, xw.win);
    XGetWindowAttributes(xw.dpy, xw.win, &xw.attr);
    xw.width = (unsigned int)xw.attr.width;
    xw.height = (unsigned int)xw.attr.height;
    xw.surf = surface_create(xw.dpy, xw.screen, xw.win, xw.width, xw.height);
    xw.font = font_create(xw.dpy, "fixed");

    /* GUI */
    memset(&gui, 0, sizeof gui);
    zr_command_queue_init_fixed(&gui.queue, calloc(MAX_MEMORY, 1), MAX_MEMORY);
    gui.font.userdata = zr_handle_ptr(xw.font);
    gui.font.height = (zr_float)xw.font->height;
    gui.font.width = font_get_text_width;
    init_demo(&gui);

    while (gui.running) {
        /* Input */
        XEvent evt;
        started = timestamp();
        zr_input_begin(&gui.input);
        while (XCheckWindowEvent(xw.dpy, xw.win, xw.swa.event_mask, &evt)) {
            if (evt.type == KeyPress)
                key(&xw, &gui.input, &evt, zr_true);
            else if (evt.type == KeyRelease) key(&xw, &gui.input, &evt, zr_false);
            else if (evt.type == ButtonPress) btn(&gui.input, &evt, zr_true);
            else if (evt.type == ButtonRelease) btn(&gui.input, &evt, zr_false);
            else if (evt.type == MotionNotify) motion(&gui.input, &evt);
            else if (evt.type == Expose || evt.type == ConfigureNotify)
                resize(&xw, xw.surf);
        }
        zr_input_end(&gui.input);

        /* GUI */
        run_demo(&gui);

        /* Draw */
        XClearWindow(xw.dpy, xw.win);
        surface_clear(xw.surf, 0x00646464);
        draw(xw.surf, &gui.queue);
        surface_blit(xw.win, xw.surf, xw.width, xw.height);
        XFlush(xw.dpy);

        /* Timing */
        dt = timestamp() - started;
        if (dt < DTIME)
            sleep_for(DTIME - dt);
    }

    free(zr_buffer_memory(&gui.queue.buffer));
    font_del(xw.dpy, xw.font);
    surface_del(xw.surf);
    XUnmapWindow(xw.dpy, xw.win);
    XFreeColormap(xw.dpy, xw.cmap);
    XDestroyWindow(xw.dpy, xw.win);
    XCloseDisplay(xw.dpy);
    return 0;
}
示例#28
0
文件: button.cpp 项目: ALLPix/SoXt
int
main(int argc, char ** argv)
{

  setbuf(stdout, NULL);
  setbuf(stderr, NULL);
  
  Display * display = XOpenDisplay(NULL);
  assert(display != NULL);
  XSynchronize(display, True);

  XtAppContext context = XtCreateApplicationContext();

  Widget appshell = XtVaAppInitialize(&context, "SoXtTest", NULL, 0, &argc, argv, NULL, NULL);
  fprintf(stderr, "appshell: %p\n", appshell);

#if WANT_VISUALID
  int i, numvisuals;
  unsigned int wanted = WANT_VISUALID;
  XVisualInfo templ;
  XVisualInfo * visuals = XGetVisualInfo(display, VisualNoMask, &templ, &numvisuals);
  for ( i = 0; i < numvisuals; i++ ) {
    if ( visuals[i].visualid == wanted ) goto selected;
  }
  assert(0 && "no visual selected");
selected:

  Visual * visual = visuals[i].visual;
  int visualid = visuals[i].visualid;
  int depth = visuals[i].depth;
  Colormap colormap = 0;

  fprintf(stderr, "visualid: %d, depth: %d, class: %s\n", visualid, depth, visuals[i].c_class == DirectColor ? "DirectColor" : "Other");

  int numcmaps;
  XStandardColormap * stdcolormaps = NULL;
  if ( XmuLookupStandardColormap(display, visuals[i].screen, visuals[i].visualid, visuals[i].depth,
                                 XA_RGB_DEFAULT_MAP, False, True) &&
       XGetRGBColormaps(display, RootWindow(display, visuals[i].screen),
                        &stdcolormaps, &numcmaps, XA_RGB_DEFAULT_MAP) ) {
    for ( int j = 0; j < numcmaps; j++ ) {
      if (stdcolormaps[j].visualid == visuals[i].visualid) {
        colormap = stdcolormaps[j].colormap;
        goto cont;
      }
    }
    colormap = XCreateColormap(display, RootWindow(display, visuals[i].screen), visuals[i].visual, AllocNone);
    fprintf(stderr, "standard RGB colormaps did not work with visual - created own (%ld)", colormap);
  } else {
    assert(0);
  }

cont:
  fprintf(stderr, "colormap: %ld\n", colormap);
#else
  Visual * visual = NULL;
  int depth = 0;
  Colormap colormap = 0;

  int snum = XDefaultScreen(display);
  visual = XDefaultVisual(display, snum);
  depth = XDefaultDepth(display, snum);
  colormap = XDefaultColormap(display, snum);

  fprintf(stderr, "visual: %p, depth: %d\n", visual, depth);
  fprintf(stderr, "colormap: %ld\n", colormap);
#endif

  XtVaSetValues(appshell,
    XmNwidth, 100,
    XmNheight, 100,
    XmNvisual, visual,
    XmNcolormap, colormap,
    XmNdepth, depth,
    NULL);

  Widget form = XtVaCreateManagedWidget(
    "form", xmFormWidgetClass,
    appshell,
    NULL);

  Widget button = XtVaCreateManagedWidget(
    "button", xmPushButtonWidgetClass,
    form,
    XmNtopAttachment, XmATTACH_FORM,
    XmNleftAttachment, XmATTACH_FORM,
    XmNbottomAttachment, XmATTACH_FORM,
    XmNrightAttachment, XmATTACH_FORM,
    NULL);

  Pixmap pixmap = createPixmapFromXpm(button, home_xpm);
  XtVaSetValues(button,
    XmNlabelType, XmPIXMAP,
    XmNlabelPixmap, pixmap,
    XmNlabelInsensitivePixmap, pixmap,
    XmNselectPixmap, pixmap,
    XmNselectInsensitivePixmap, pixmap,
    NULL);

  Widget list[] = { appshell, form, button, NULL };
  XtSetWMColormapWindows(appshell, list, 3);

  XtRealizeWidget(appshell);
  XtAppMainLoop(context);
}
示例#29
0
int
ga_xwin_init(const char *displayname, gaImage *gaimg) {
	int ignore = 0;
	//
	bzero(&__xshminfo, sizeof(__xshminfo));
	// open display
	if((display = XOpenDisplay(displayname)) == NULL) {
		ga_error("cannot open display \"%s\"\n", displayname ? displayname : "DEFAULT");
		return -1;
	}
	// check MIT extension
	if(XQueryExtension(display, "MIT-SHM", &ignore, &ignore, &ignore) ) {
		int major, minor;
		Bool pixmaps;
		if(XShmQueryVersion(display, &major, &minor, &pixmaps) == True) {
			ga_error("XShm extention version %d.%d %s shared pixmaps\n",
					major, minor, (pixmaps==True) ? "with" : "without");
		} else {
			ga_error("XShm extension not supported.\n");
			goto xcap_init_error;
		}
	}
	// get default screen
	screenNumber = XDefaultScreen(display);
	if((screen = XScreenOfDisplay(display, screenNumber)) == NULL) {
		ga_error("cannot obtain screen #%d\n", screenNumber);
		goto xcap_init_error;
	}
	//
	width = XDisplayWidth(display, screenNumber);
	height = XDisplayHeight(display, screenNumber);
	depth = XDisplayPlanes(display, screenNumber);
	ga_error("X-Window-init: dimension: %dx%dx%d @ %d/%d\n",
			width, height, depth,
			screenNumber, XScreenCount(display));
	//
	if((image = XShmCreateImage(display,
			XDefaultVisual(display, screenNumber),
			depth, ZPixmap, NULL, &__xshminfo,
			width, height)) == NULL) {
		ga_error("XShmCreateImage failed.\n");
		goto xcap_init_error;
	}
	//
	if((__xshminfo.shmid = shmget(IPC_PRIVATE,
				image->bytes_per_line*image->height,
				IPC_CREAT | 0777)) < 0) {
		perror("shmget");
		goto xcap_init_error;
	}
	//
	__xshminfo.shmaddr = image->data = (char*) shmat(__xshminfo.shmid, 0, 0);
	__xshminfo.readOnly = False;
	if(XShmAttach(display, &__xshminfo) == 0) {
		ga_error("XShmAttach failed.\n");
		goto xcap_init_error;
	}
	//
	__xshmattached = true;
	rootWindow = XRootWindow(display, screenNumber);
	gaimg->width = image->width;
	gaimg->height = image->height;
	gaimg->bytes_per_line = image->bytes_per_line;
	//
	return 0;
	//
xcap_init_error:
	ga_xwin_deinit();
	return -1;
}