Exemplo n.º 1
0
void
setup(void) {
    int x, y, screen;
    XSetWindowAttributes wa;
#ifdef XINERAMA
    int n;
    XineramaScreenInfo *info;
#endif

    screen = DefaultScreen(dc->dpy);
    root = RootWindow(dc->dpy, screen);
    utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);

    normcol[ColBG] = getcolor(dc, normbgcolor);
    normcol[ColFG] = getcolor(dc, normfgcolor);
    selcol[ColBG] = getcolor(dc, selbgcolor);
    selcol[ColFG] = getcolor(dc, selfgcolor);

    /* menu geometry */
    bh = dc->font.height + 2;
    lines = MAX(lines, 0);
    mh = (MAX(MIN(lines + 1, itemcount), 1)) * bh;

    if(height < mh) {
        height = mh;
    }
#ifdef XINERAMA
    if((info = XineramaQueryScreens(dc->dpy, &n))) {
        int i, di;
        unsigned int du;
        Window dw;

        XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du);
        for(i = 0; i < n; i++)
            if((monitor == info[i].screen_number)
                    || (monitor < 0 && INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)))
                break;
        x = info[i].x_org;
        y = info[i].y_org + (topbar ? 0 : info[i].height - height);
        mw = info[i].width;
        XFree(info);
    }
    else
#endif
    {
        x = 0;
        y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - height;
        mw = DisplayWidth(dc->dpy, screen);
    }
    /* menu window */
    wa.override_redirect = True;
    wa.background_pixmap = ParentRelative;
    wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
    win = XCreateWindow(dc->dpy, root, x, y, mw, height, 0,
                        DefaultDepth(dc->dpy, screen), CopyFromParent,
                        DefaultVisual(dc->dpy, screen),
                        CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);

    grabkeyboard();
    resizedc(dc, mw, height);
    inputw = MIN(inputw, mw/3);
    promptw = prompt ? textw(dc, prompt) : 0;
    XMapRaised(dc->dpy, win);
    text[0] = '\0';
    match();
}
Exemplo n.º 2
0
WireFrame *
wireframeCreate (Client *c)
{
    ScreenInfo *screen_info;
    WireFrame *wireframe;
    XSetWindowAttributes attrs;
    XVisualInfo xvisual_info;
    Visual *xvisual;
    int depth;

    g_return_val_if_fail (c != NULL, None);

    TRACE ("entering wireframeCreate");

    screen_info = c->screen_info;
    wireframe = g_new0 (WireFrame, 1);
    wireframe->screen_info = screen_info;
    wireframe->mapped = FALSE;
    wireframe->width = 0;
    wireframe->height = 0;
    wireframe->cr = NULL;
    wireframe->surface = NULL;
    wireframe->alpha = (compositorIsActive (screen_info) ? 0.5 : 1.0);

    if (compositorIsActive (screen_info) &&
            XMatchVisualInfo (myScreenGetXDisplay (screen_info), screen_info->screen,
                              32, TrueColor, &xvisual_info))
    {
        xvisual = xvisual_info.visual;
        depth = xvisual_info.depth;
        wireframe->xcolormap = XCreateColormap (myScreenGetXDisplay (screen_info),
                                                screen_info->xroot,
                                                xvisual, AllocNone);
    }
    else
    {
        xvisual = screen_info->visual;
        depth = screen_info->depth;
        wireframe->xcolormap = screen_info->cmap;
    }

    attrs.override_redirect = True;
    attrs.colormap = wireframe->xcolormap;
    attrs.background_pixel = BlackPixel (myScreenGetXDisplay (screen_info),
                                         screen_info->screen);
    attrs.border_pixel = BlackPixel (myScreenGetXDisplay (screen_info),
                                     screen_info->screen);
    wireframe->xwindow = XCreateWindow (myScreenGetXDisplay (screen_info), screen_info->xroot,
                                        frameExtentX (c), frameExtentY (c),
                                        frameExtentWidth (c), frameExtentHeight (c),
                                        0, depth, InputOutput, xvisual,
                                        CWOverrideRedirect | CWColormap | CWBackPixel | CWBorderPixel,
                                        &attrs);

    if (compositorIsActive (screen_info))
    {
        /* Cairo */
        wireframeInitColor (wireframe);
        wireframe->surface = cairo_xlib_surface_create (myScreenGetXDisplay (screen_info),
                             wireframe->xwindow, xvisual,
                             frameExtentWidth (c), frameExtentHeight (c));
        wireframe->cr = cairo_create (wireframe->surface);
        cairo_set_line_width (wireframe->cr, OUTLINE_WIDTH_CAIRO);
        cairo_set_line_join (wireframe->cr, CAIRO_LINE_JOIN_MITER);
    }

    wireframeUpdate (c, wireframe);

    return (wireframe);
}
Exemplo n.º 3
0
int
X11_CreateWindow(_THIS, SDL_Window * window)
{
    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
    SDL_DisplayData *displaydata =
        (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
    Display *display = data->display;
    int screen = displaydata->screen;
    Visual *visual;
    int depth;
    XSetWindowAttributes xattr;
    Window w;
    XSizeHints *sizehints;
    XWMHints *wmhints;
    XClassHint *classhints;
    Atom _NET_WM_WINDOW_TYPE;
    Atom _NET_WM_WINDOW_TYPE_NORMAL;
    int wmstate_count;
    Atom wmstate_atoms[3];

#if SDL_VIDEO_DRIVER_X11_XINERAMA
/* FIXME
    if ( use_xinerama ) {
        x = xinerama_info.x_org;
        y = xinerama_info.y_org;
    }
*/
#endif
#if SDL_VIDEO_OPENGL_GLX
    if (window->flags & SDL_WINDOW_OPENGL) {
        XVisualInfo *vinfo;

        vinfo = X11_GL_GetVisual(_this, display, screen);
        if (!vinfo) {
            return -1;
        }
        visual = vinfo->visual;
        depth = vinfo->depth;
        XFree(vinfo);
    } else
#endif
#ifdef SDL_VIDEO_DRIVER_PANDORA
    if (window->flags & SDL_WINDOW_OPENGL) {
        XVisualInfo *vinfo;

        vinfo = X11_GLES_GetVisual(_this, display, screen);
        if (!vinfo) {
            return -1;
        }
        visual = vinfo->visual;
        depth = vinfo->depth;
        XFree(vinfo);
    } else
#endif
    {
        visual = displaydata->visual;
        depth = displaydata->depth;
    }

    xattr.override_redirect = False;
    xattr.background_pixel = 0;
    xattr.border_pixel = 0;
    xattr.colormap = XCreateColormap(display, RootWindow(display, screen), visual, AllocNone);

    w = XCreateWindow(display, RootWindow(display, screen),
                      window->x, window->y, window->w, window->h,
                      0, depth, InputOutput, visual,
                      (CWOverrideRedirect | CWBackPixel | CWBorderPixel |
                       CWColormap), &xattr);
    if (!w) {
        SDL_SetError("Couldn't create window");
        return -1;
    }
#if SDL_VIDEO_DRIVER_PANDORA
    /* Create the GLES window surface */
    _this->gles_data->egl_surface =
        _this->gles_data->eglCreateWindowSurface(_this->gles_data->
                                                 egl_display,
                                                 _this->gles_data->egl_config,
                                                 (NativeWindowType) w, NULL);

    if (_this->gles_data->egl_surface == EGL_NO_SURFACE) {
        SDL_SetError("Could not create GLES window surface");
        return -1;
    }
#endif

    sizehints = XAllocSizeHints();
    if (sizehints) {
        if (!(window->flags & SDL_WINDOW_RESIZABLE)) {
            sizehints->min_width = sizehints->max_width = window->w;
            sizehints->min_height = sizehints->max_height = window->h;
            sizehints->flags = PMaxSize | PMinSize;
        }
        sizehints->x = window->x;
        sizehints->y = window->y;
        sizehints->flags |= USPosition;
        XSetWMNormalHints(display, w, sizehints);
        XFree(sizehints);
    }

    if (window->flags & SDL_WINDOW_BORDERLESS) {
        SDL_bool set;
        Atom WM_HINTS;

        /* We haven't modified the window manager hints yet */
        set = SDL_FALSE;

        /* First try to set MWM hints */
        WM_HINTS = XInternAtom(display, "_MOTIF_WM_HINTS", True);
        if (WM_HINTS != None) {
            /* Hints used by Motif compliant window managers */
            struct
            {
                unsigned long flags;
                unsigned long functions;
                unsigned long decorations;
                long input_mode;
                unsigned long status;
            } MWMHints = {
            (1L << 1), 0, 0, 0, 0};

            XChangeProperty(display, w, WM_HINTS, WM_HINTS, 32,
                            PropModeReplace, (unsigned char *) &MWMHints,
                            sizeof(MWMHints) / 4);
            set = SDL_TRUE;
        }
        /* Now try to set KWM hints */
        WM_HINTS = XInternAtom(display, "KWM_WIN_DECORATION", True);
        if (WM_HINTS != None) {
            long KWMHints = 0;

            XChangeProperty(display, w, WM_HINTS, WM_HINTS, 32,
                            PropModeReplace,
                            (unsigned char *) &KWMHints,
                            sizeof(KWMHints) / 4);
            set = SDL_TRUE;
        }
        /* Now try to set GNOME hints */
        WM_HINTS = XInternAtom(display, "_WIN_HINTS", True);
        if (WM_HINTS != None) {
            long GNOMEHints = 0;

            XChangeProperty(display, w, WM_HINTS, WM_HINTS, 32,
                            PropModeReplace,
                            (unsigned char *) &GNOMEHints,
                            sizeof(GNOMEHints) / 4);
            set = SDL_TRUE;
        }
        /* Finally set the transient hints if necessary */
        if (!set) {
            XSetTransientForHint(display, w, RootWindow(display, screen));
        }
    } else {
        SDL_bool set;
        Atom WM_HINTS;

        /* We haven't modified the window manager hints yet */
        set = SDL_FALSE;

        /* First try to unset MWM hints */
        WM_HINTS = XInternAtom(display, "_MOTIF_WM_HINTS", True);
        if (WM_HINTS != None) {
            XDeleteProperty(display, w, WM_HINTS);
            set = SDL_TRUE;
        }
        /* Now try to unset KWM hints */
        WM_HINTS = XInternAtom(display, "KWM_WIN_DECORATION", True);
        if (WM_HINTS != None) {
            XDeleteProperty(display, w, WM_HINTS);
            set = SDL_TRUE;
        }
        /* Now try to unset GNOME hints */
        WM_HINTS = XInternAtom(display, "_WIN_HINTS", True);
        if (WM_HINTS != None) {
            XDeleteProperty(display, w, WM_HINTS);
            set = SDL_TRUE;
        }
        /* Finally unset the transient hints if necessary */
        if (!set) {
            XDeleteProperty(display, w, XA_WM_TRANSIENT_FOR);
        }
    }

    /* Set the input hints so we get keyboard input */
    wmhints = XAllocWMHints();
    if (wmhints) {
        wmhints->input = True;
        wmhints->flags = InputHint;
        XSetWMHints(display, w, wmhints);
        XFree(wmhints);
    }

    /* Set the class hints so we can get an icon (AfterStep) */
    classhints = XAllocClassHint();
    if (classhints != NULL) {
        classhints->res_name = data->classname;
        classhints->res_class = data->classname;
        XSetClassHint(display, w, classhints);
        XFree(classhints);
    }

    /* Set the window manager state */
    wmstate_count = X11_GetWMStateProperty(_this, window, wmstate_atoms);
    if (wmstate_count > 0) {
        XChangeProperty(display, w, data->_NET_WM_STATE, XA_ATOM, 32,
                        PropModeReplace,
                        (unsigned char *)wmstate_atoms, wmstate_count);
    } else {
        XDeleteProperty(display, w, data->_NET_WM_STATE);
    }

    /* Let the window manager know we're a "normal" window */
    _NET_WM_WINDOW_TYPE = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
    _NET_WM_WINDOW_TYPE_NORMAL = XInternAtom(display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
    XChangeProperty(display, w, _NET_WM_WINDOW_TYPE, XA_ATOM, 32,
                    PropModeReplace,
                    (unsigned char *)&_NET_WM_WINDOW_TYPE_NORMAL, 1);

    /* Allow the window to be deleted by the window manager */
    XSetWMProtocols(display, w, &data->WM_DELETE_WINDOW, 1);

    if (SetupWindowData(_this, window, w, SDL_TRUE) < 0) {
        XDestroyWindow(display, w);
        return -1;
    }

#ifdef X_HAVE_UTF8_STRING
    {
        Uint32 fevent = 0;
        pXGetICValues(((SDL_WindowData *) window->driverdata)->ic,
                      XNFilterEvents, &fevent, NULL);
        XSelectInput(display, w,
                     (FocusChangeMask | EnterWindowMask | LeaveWindowMask |
                      ExposureMask | ButtonPressMask | ButtonReleaseMask |
                      PointerMotionMask | KeyPressMask | KeyReleaseMask |
                      PropertyChangeMask | StructureNotifyMask |
                      KeymapStateMask | fevent));
    }
#else
    {
        XSelectInput(display, w,
                     (FocusChangeMask | EnterWindowMask | LeaveWindowMask |
                      ExposureMask | ButtonPressMask | ButtonReleaseMask |
                      PointerMotionMask | KeyPressMask | KeyReleaseMask |
                      PropertyChangeMask | StructureNotifyMask |
                      KeymapStateMask));
    }
#endif

    XFlush(display);

    return 0;
}
Exemplo n.º 4
0
void
setup(void)
{
    XSetWindowAttributes wa;
    XTextProperty str;
    XSizeHints *sizeh;
    XClassHint *ch;
    int i, sh, sw, ls;

    /* init screen */
    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    sw = DisplayWidth(dpy, screen) - 1;
    sh = DisplayHeight(dpy, screen) - 1;
    initfont(font);

    /* init atoms */

    /* init appearance */

    for (i = 0, www = 0; i < nentries; i++) {
        ls = textnw(entries[i]->label,
                    strlen(entries[i]->label));
        if (ls > www)
            www = ls;
    }
    www *= widthscaling;

    if (!ww) {
        if (horizontal) {
            ww = www * nentries;
        } else {
            ww = www;
        }
    }
    if (!wh) {
        if (horizontal) {
            wh = dc.font.height * heightscaling;
        } else {
            wh = nentries * dc.font.height * heightscaling;
        }
    }
    if (!wy)
        wy = (sh - wh) / 2;
    if (wy < 0)
        wy = sh + wy - wh;
    if (!wx)
        wx = (sw - ww) / 2;
    if (wx < 0)
        wx = sw + wx - ww;

    dc.norm[ColBG] = getcolor(normbgcolor);
    dc.norm[ColFG] = getcolor(normfgcolor);
    dc.press[ColBG] = getcolor(pressbgcolor);
    dc.press[ColFG] = getcolor(pressfgcolor);
    dc.high[ColBG] = getcolor(highlightbgcolor);
    dc.high[ColFG] = getcolor(highlightfgcolor);

    dc.drawable = XCreatePixmap(dpy, root, ww, wh, DefaultDepth(dpy, screen));
    dc.gc = XCreateGC(dpy, root, 0, 0);
    if(!dc.font.set)
        XSetFont(dpy, dc.gc, dc.font.xfont->fid);
    for(i = 0; i < nentries; i++)
        entries[i]->pressed = 0;

    wa.override_redirect = !wmborder;
    wa.border_pixel = dc.norm[ColFG];
    wa.background_pixel = dc.norm[ColBG];
    win = XCreateWindow(dpy, root, wx, wy, ww, wh, 0,
                        CopyFromParent, CopyFromParent, CopyFromParent,
                        CWOverrideRedirect | CWBorderPixel | CWBackingPixel, &wa);
    XSelectInput(dpy, win, StructureNotifyMask|KeyReleaseMask|
                 ButtonReleaseMask|ButtonPressMask|
                 ExposureMask|LeaveWindowMask|PointerMotionMask);

    sizeh = XAllocSizeHints();
    sizeh->flags = PMaxSize | PMinSize;
    sizeh->min_width = sizeh->max_width = ww;
    sizeh->min_height = sizeh->max_height = wh;
    XStringListToTextProperty(&name, 1, &str);
    ch = XAllocClassHint();
    ch->res_class = name;
    ch->res_name = name;

    XSetWMProperties(dpy, win, &str, &str, NULL, 0, sizeh, NULL,
                     ch);

    XFree(ch);
    XFree(str.value);
    XFree(sizeh);

    XMapRaised(dpy, win);
    updateentries();
    drawmenu();
}
Exemplo n.º 5
0
void
Create_Window (char *geometry)
{
    short q;
    Visual *vid;
    XSetWindowAttributes xswa;
    XSizeHints sizehint;
    XWMHints wmhints;
    int depth;
    unsigned char wname[256];	/* Window Name */
    unsigned long vmask = CWEventMask | CWBackPixel | CWBackingStore;

    depth = DefaultDepth (display.dpy, display.screen);
    xswa.event_mask = 0;
    xswa.background_pixel = display.bg;
    xswa.backing_store = Always;
    debug_printf ("DefaultVisual id=%d bp-rgb=%d map-entries=%d\n",
		  (int) (*DefaultVisual (display.dpy, display.screen)).visualid,
		  (*DefaultVisual (display.dpy, display.screen)).bits_per_rgb,
		  (*DefaultVisual (display.dpy, display.screen)).map_entries);
    vid = DefaultVisual (display.dpy, display.screen);
    display.cmap
	    = XDefaultColormap (display.dpy, display.screen);
    display.win = XCreateWindow (display.dpy, display.root,
				 winX, winY,
				 display.winW, display.winH, 0, depth,
				 InputOutput,	/* vid , */
				 DefaultVisual (display.dpy, display.screen),
				 /*      PseudoColor,  */
				 vmask, &xswa);

    sizehint.x = winX - 100;
    sizehint.y = winY;
    sizehint.width = display.winW;
    sizehint.height = display.winH;
    sizehint.min_width = display.winW;
    sizehint.min_height = display.winH;
    sizehint.max_width = display.winW;
    sizehint.max_height = display.winH;
    /* GCS FIX:  Be careful about resizing the opening screen */
    /* WCK: Fixed.  We lock it now, and unlock it after the opening screen.
       not gorgeous, but it works for now.  Still need to clean up.*/
#define NO_RESIZABLE_WINDOWS 1
    if (geometry != NULL) {
#if defined (NO_RESIZABLE_WINDOWS)
	sizehint.flags = USPosition | USSize | PMinSize | PMaxSize;
#else
	sizehint.flags = USPosition | USSize | PMinSize;
#endif
    } else {
#if defined (NO_RESIZABLE_WINDOWS)
	sizehint.flags = PPosition | PSize | PMinSize | PMaxSize;
#else
	sizehint.flags = PPosition | PSize | PMinSize;
#endif
    }
    XSetNormalHints (display.dpy, display.win, &sizehint);

    display.protocol_atom = XInternAtom (display.dpy, "WM_PROTOCOLS",
					 False);
    display.kill_atom = XInternAtom (display.dpy, "WM_DELETE_WINDOW",
				     False);

    /* Title */
    sprintf ((char *) wname,
	     _("xlincity, Version %s, "
	     "(Copyright) IJ Peters - copying policy GNU GPL"),
	     VERSION);
    XChangeProperty (display.dpy, display.win,
		     XA_WM_NAME, XA_STRING, 8, PropModeReplace, wname,
		     strlen ((char *) wname));

    /* Window Manager Hints (This is supposed to make input work.) */
    wmhints.flags = InputHint;
    wmhints.input = True;
    XSetWMHints (display.dpy, display.win, &wmhints);

    /* GCS - 2003/08/15 - Cygwin doesn't generate the MapEvent unless
       the mask enabled before XMapWindow is called.  Therefore, 
       XSelectInput needs to be called before XMapWindow */
    XSelectInput (display.dpy, display.win,
		  KeyPressMask | ButtonPressMask | ButtonReleaseMask
		  | ExposureMask | StructureNotifyMask);

    XMapWindow (display.dpy, display.win);
    
    for (q = 0; q < 256; q++)
    {
	display.pixcolour_gc[q] = XCreateGC (display.dpy
					     ,display.win, 0, NULL);
	XSetForeground (display.dpy, display.pixcolour_gc[q], q);
	XSetBackground (display.dpy, display.pixcolour_gc[q],
			display.bg);
	XSetGraphicsExposures (display.dpy, display.pixcolour_gc[q],
			       False);
    }
}
Exemplo n.º 6
0
/*
 * Setup X11 wnd System
 */
void
X11_SetupWindow (GF_VideoOutput * vout)
{
	X11VID ();
	const char *sOpt;

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

	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;

	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 = 20;
		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 = 32;
	Hints->min_height = 32;
	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);
	XFree (Hints);


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

#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)) {
	    /*this is disabled due to flip pb (we cannot reposition backbuffer)*/
	    if (0 && XShmPixmaps && (XShmPixmapFormat(xWindow->display) == ZPixmap)) {
		xWindow->videoaccesstype = VIDEO_XI_SHMPIXMAP;
	    } else {
	      xWindow->videoaccesstype = VIDEO_XI_SHMSTD;
	      GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using X11 Hardware Blit\n"));
	    }
	  }
	}
#endif

	GF_SAFEALLOC(xWindow->back_buffer, X11WrapSurface);
	xWindow->back_buffer->id = -1;


	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);
	}
#ifdef GPAC_HAS_OPENGL
	if (xWindow->is_3D_out) {
	  int attribs[64];
	  int i;

	  i=0;
	  attribs[i++] = GLX_RGBA;
	  attribs[i++] = GLX_RED_SIZE;
	  attribs[i++] = 5;
	  attribs[i++] = GLX_GREEN_SIZE;
	  attribs[i++] = 5;
	  attribs[i++] = GLX_BLUE_SIZE;
	  attribs[i++] = 5;
	  attribs[i++] = GLX_DEPTH_SIZE;
	  attribs[i++] = 16;
	  if (xWindow->gl_cfg.double_buffered) 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"));
	  }
	}
#endif
	xWindow->setup_done = 1;
}
bool GLWindow::Create()
{
    assert ( !IsDestroyed() );
    assert ( IsDisposed() );

    XVisualInfo *vi;
    Colormap cmap;
    int dpyWidth, dpyHeight;
    int i;
    int glxMajorVersion, glxMinorVersion;
    int vidModeMajorVersion, vidModeMinorVersion;
    XF86VidModeModeInfo **modes;
    int modeNum;
    int bestMode;
    Atom wmDelete;
    Window winDummy;
    unsigned int borderDummy;

    /* set best mode to current */
    bestMode = 0;
    /* get a connection */
    hDC = XOpenDisplay(0);
    screen = DefaultScreen(hDC);
    XF86VidModeQueryVersion(hDC, &vidModeMajorVersion, &vidModeMinorVersion);
    printf("XF86VidModeExtension-Version %d.%d\n", vidModeMajorVersion,
        vidModeMinorVersion);
    XF86VidModeGetAllModeLines(hDC, screen, &modeNum, &modes);
    /* save desktop-resolution before switching modes */
    deskMode = *modes[0];
    /* look for mode with requested resolution */
    for (i = 0; i < modeNum; i++)
        if ((modes[i]->hdisplay == Width) && (modes[i]->vdisplay == Height))
            bestMode = i;
    /* get an appropriate visual */
    vi = glXChooseVisual(hDC, screen, attrListDbl);
    if (vi == NULL)
    {
        vi = glXChooseVisual(hDC, screen, attrListSgl);
        printf("Only Singlebuffered Visual!\n");
    }
    else
        printf("Got Doublebuffered Visual!\n");
    glXQueryVersion(hDC, &glxMajorVersion, &glxMinorVersion);
    printf("glX-Version %d.%d\n", glxMajorVersion, glxMinorVersion);
    /* create a GLX context */
    glctx = glXCreateContext(hDC, vi, 0, GL_TRUE);
    /* create a color map */
    cmap = XCreateColormap(hDC, RootWindow(hDC, vi->screen),
        vi->visual, AllocNone);
    attr.colormap = cmap;
    attr.border_pixel = 0;

    if (FL_fullscreen)
    {
        XF86VidModeSwitchToMode(hDC, screen, modes[bestMode]);
        XF86VidModeSetViewPort(hDC, screen, 0, 0);
        dpyWidth = modes[bestMode]->hdisplay;
        dpyHeight = modes[bestMode]->vdisplay;
        printf("Resolution %dx%d\n", dpyWidth, dpyHeight);
        XFree(modes);

        /* create a fullscreen window */
        attr.override_redirect = True;
        attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
            FocusChangeMask | EnterWindowMask | StructureNotifyMask;
        win = XCreateWindow(hDC, RootWindow(hDC, vi->screen),
            0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual,
            CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
            &attr);
        XWarpPointer(hDC, None, win, 0, 0, 0, 0, 0, 0);
        XMapRaised(hDC, win);
        XGrabKeyboard(hDC, win, True, GrabModeAsync,
            GrabModeAsync, CurrentTime);
        XGrabPointer(hDC, win, True, ButtonPressMask,
            GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
    }
    else
    {
        /* create a window in window mode*/
        attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
            PointerMotionMask | FocusChangeMask | StructureNotifyMask;
        win = XCreateWindow(hDC, RootWindow(hDC, vi->screen),
            0, 0, Width, Height, 0, vi->depth, InputOutput, vi->visual,
            CWBorderPixel | CWColormap | CWEventMask, &attr);
        /* only set window title and handle wm_delete_events if in windowed mode */
        wmDelete = XInternAtom(hDC, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(hDC, win, &wmDelete, 1);
        XSetStandardProperties(hDC, win, Title,
            Title, None, NULL, 0, NULL);
        XMapRaised(hDC, win);
    }
    /* connect the glx-context to the window */
    glXMakeCurrent(hDC, win, glctx);
    XGetGeometry(hDC, win, &winDummy, &x, &y,
        &Width, &Height, &borderDummy, &depth);
    printf("Depth %d\n", depth);
    if (glXIsDirect(hDC, glctx))
        printf("Congrats, you have Direct Rendering!\n");
    else
        printf("Sorry, no Direct Rendering possible!\n");

    OnCreate();
    this->Resize(Width, Height);

    return true;
}
Exemplo n.º 8
0
static gboolean
clutter_backend_egl_create_context (ClutterBackend  *backend,
                                    GError         **error)
{
  ClutterBackendEGL *backend_egl;
  ClutterBackendX11 *backend_x11;
  EGLConfig          config;
  EGLint             config_count = 0;
  EGLBoolean         status;
  EGLint             cfg_attribs[] = {
    /* NB: This must be the first attribute, since we may
     * try and fallback to no stencil buffer */
    EGL_STENCIL_SIZE,   8,

    EGL_RED_SIZE,       5,
    EGL_GREEN_SIZE,     6,
    EGL_BLUE_SIZE,      5,

    EGL_BUFFER_SIZE,    EGL_DONT_CARE,

#ifdef HAVE_COGL_GLES2
    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#else /* HAVE_COGL_GLES2 */
    EGL_SURFACE_TYPE,    EGL_WINDOW_BIT,
#endif /* HAVE_COGL_GLES2 */

    EGL_NONE
  };
  EGLDisplay edpy;
  gint retry_cookie = 0;
  XVisualInfo *xvisinfo;
  XSetWindowAttributes attrs;

  backend     = clutter_get_default_backend ();
  backend_egl = CLUTTER_BACKEND_EGL (backend);

  if (backend_egl->egl_context != EGL_NO_CONTEXT)
    return TRUE;

  backend_x11 = CLUTTER_BACKEND_X11 (backend);

  edpy = clutter_eglx_display ();

retry:
  /* Here we can change the attributes depending on the fallback count... */

  /* Some GLES hardware can't support a stencil buffer: */
  if (retry_cookie == 1)
    {
      g_warning ("Trying with stencil buffer disabled...");
      cfg_attribs[1 /* EGL_STENCIL_SIZE */] = 0;
    }

  /* XXX: at this point we only have one fallback */

  status = eglChooseConfig (edpy,
                            cfg_attribs,
                            &config, 1,
                            &config_count);
  if (status != EGL_TRUE || config_count == 0)
    {
      g_warning ("eglChooseConfig failed");
      goto fail;
    }

  if (G_UNLIKELY (backend_egl->egl_context == EGL_NO_CONTEXT))
    {
#ifdef HAVE_COGL_GLES2
      static const EGLint attribs[3]
        = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };

      backend_egl->egl_context = eglCreateContext (edpy,
                                                   config,
                                                   EGL_NO_CONTEXT,
                                                   attribs);
#else
      /* Seems some GLES implementations 1.x do not like attribs... */
      backend_egl->egl_context = eglCreateContext (edpy,
                                                   config,
                                                   EGL_NO_CONTEXT,
                                                   NULL);
#endif
      if (backend_egl->egl_context == EGL_NO_CONTEXT)
        {
          g_warning ("Unable to create a suitable EGL context");
          goto fail;
        }

      backend_egl->egl_config = config;
      CLUTTER_NOTE (GL, "Created EGL Context");
    }

  /* COGL assumes that there is always a GL context selected; in order
   * to make sure that an EGL context exists and is made current, we use
   * a dummy, offscreen override-redirect window to which we can always
   * fall back if no stage is available */

  xvisinfo = clutter_backend_x11_get_visual_info (backend_x11);
  if (xvisinfo == NULL)
    {
      g_critical ("Unable to find suitable GL visual.");
      return FALSE;
    }

  attrs.override_redirect = True;
  attrs.colormap = XCreateColormap (backend_x11->xdpy,
                                    backend_x11->xwin_root,
                                    xvisinfo->visual,
                                    AllocNone);
  attrs.border_pixel = 0;

  backend_egl->dummy_xwin = XCreateWindow (backend_x11->xdpy,
                                           backend_x11->xwin_root,
                                           -100, -100, 1, 1,
                                           0,
                                           xvisinfo->depth,
                                           CopyFromParent,
                                           xvisinfo->visual,
                                           CWOverrideRedirect |
                                           CWColormap |
                                           CWBorderPixel,
                                           &attrs);

  XFree (xvisinfo);

  backend_egl->dummy_surface =
    eglCreateWindowSurface (edpy,
                            backend_egl->egl_config,
                            (NativeWindowType) backend_egl->dummy_xwin,
                            NULL);

  if (backend_egl->dummy_surface == EGL_NO_SURFACE)
    {
      g_critical ("Unable to create an EGL surface");
      return FALSE;
    }

  eglMakeCurrent (edpy,
                  backend_egl->dummy_surface,
                  backend_egl->dummy_surface,
                  backend_egl->egl_context);

  return TRUE;

fail:

  /* NB: We currently only support a single fallback option */
  if (retry_cookie == 0)
    {
      retry_cookie = 1;
      goto retry;
    }

  return FALSE;
}
Exemplo n.º 9
0
int main(int argc, char**argv) {
  char **missing_charset_list;
  int missing_charset_count;
  XGCValues xgcv;
  unsigned long mask;
  Display* dpy;
  int scr;
  gi_window_id_t w, root;
  XSetWindowAttributes set_attr;
  int i;
  XIMStyle *style;
  static char buf[128];
  KeySym keysym = 0;
  Status status;
  XWMHints wm_hints;
  XClassHint class_hints;
  XIMStyle input_style = 0;
  char **font_name_list;
  char *def_string;
  gi_ufont_t **font_struct_list;
  char **font_encoding_list;
  int nb_font;
  int len = 0;
  int no_xim = 0;

  printf ("A -> %c \n", XUtf8Tolower('A'));
  if (!setlocale(LC_ALL, ""))
    puts("locale not supported by C library, locale unchanged");

  if (!XSetLocaleModifiers(""))
    puts("X locale modifiers not supported, using default");
  
  dpy = gi_init();
  if (!dpy) { puts("cannot open display.\n"); exit(-1); }
  scr = DefaultScreen(dpy);
  root = RootWindow(dpy, scr);
  set_attr.event_mask = KeyPressMask|FocusChangeMask;
  set_attr.background_pixel = WhitePixel(dpy, DefaultScreen(dpy));
  set_attr.border_pixel = BlackPixel(dpy, DefaultScreen(dpy));
  w = XCreateWindow(dpy, root, 10,10,200,100,0, 
		    DefaultDepth(dpy, DefaultScreen(dpy)),
		    InputOutput, DefaultVisual(dpy, DefaultScreen(dpy)),
		    CWEventMask | CWBackPixel | CWBorderPixel, &set_attr);
  if (!w) {
    puts("cannot creat window.\n");
    exit(-1);
  }

  class_hints.res_name = "test";
  class_hints.res_class = "Test";
  wm_hints.input = True;
  wm_hints.flags = InputHint;

  XmbSetWMProperties(dpy, w, "test", "test", NULL, 0,
		     NULL, &wm_hints, &class_hints);

  XMapWindow(dpy, w);
  xim_im = XOpenIM(dpy, NULL, "test", "Test");
  if (!xim_im) { 
    puts("cannot Open Input Manager: Try default.\n"); 
    XSetLocaleModifiers("@im=");
    xim_im = XOpenIM(dpy, NULL, "test", "Test");
    if (!xim_im) {
      puts("Failed exiting.\n");
      exit(-1);
    }
  }
  XGetIMValues (xim_im, XNQueryInputStyle, &xim_styles, NULL, NULL);
  for (i = 0, style = xim_styles->supported_styles;
       i < xim_styles->count_styles; i++, style++) {
    if (i == 0 && *style == (XIMStatusNone|XIMPreeditNone)) {
      printf("this is not a XIM server !!!\n");
      no_xim = 1;
    }
    printf("input style : 0x%X\n", *style);
  }

  xim_ic = XCreateIC(xim_im,
		     XNInputStyle, 
		     (XIMPreeditNothing | XIMStatusNothing),
		     XNClientWindow, w,
		     XNFocusWindow, w,
		     NULL);
  if (!xim_ic) {
    puts("cannot create Input Context.\n");
    exit(-1);
  }
  XFree(xim_styles);
  XSetICFocus(xim_ic);

  /***************************************************************
   *  I don't recommend to use a font base name list similar 
   *  to the following one in a real application ;-) 
   *  You should use an iso8859-1 font, plus a single font for 
   *  your language.
   ***************************************************************/
  fontset = XCreateUtf8FontStruct(dpy, 
	  "-*-*-*-*-*-*-*-*-*-*-*-*-iso8858-3," /* not valid */
	  "-*-*-medium-r-*-*-*-*-*-*-*-*-iso8859-1,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-6,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-8,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-ksc5601.1987-0,"
	  "-*-symbol-*-*-*-*-*-*-*-*-*-*-adobe-fontspecific," 
	  "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-2,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-koi8-1,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0208.1983-0,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0212.1990-0,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-big5-0,"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0201.1976-0,"
	  "-*-unifont-*-*-*-*-*-*-*-*-*-*-iso10646-1[0x300 0x400_0x500],"
	  "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"); 

  /* THIS PART IS NOT REQUIERED */
  nb_font = fontset->nb_font;

  while (nb_font > 0) {
    nb_font--;
    if (fontset->fonts[nb_font]) {
      printf("encoding=\"\" fid=%d \n  %s\n", 
      /*     fontset->encodings[nb_font], */
	     fontset->fonts[nb_font]->fid,
	     fontset->font_name_list[nb_font]);
    }
  }
  /* END OF NOT REQUIERED PART*/

  mask = (GCForeground | GCBackground);
  xgcv.foreground = BlackPixel(dpy, DefaultScreen(dpy));
  xgcv.background = WhitePixel(dpy, DefaultScreen(dpy));

  gc = gi_create_gc( w, mask, &xgcv);
  if (!gc) {
    puts("cannot create Graphic Context.\n");
    exit(-1);
  }

  /***************************************************************/
  while (1) {
    int filtered;
    static gi_msg_t xevent;
    static XVaNestedList list1 = 0;
    int r;

    XNextEvent(dpy, &xevent);
    if (xevent.type == KeyPress) {
      XKeyEvent *e = (XKeyEvent*) &xevent;
      printf ("0x%X %d\n", e->state, e->keycode);
    }
    if (xevent.type == DestroyNotify) {
      /* XIM server has crashed */
      no_xim = 1;
      XSetLocaleModifiers("@im=");
      xim_im = XOpenIM(dpy, NULL, "test", "Test");
      if (xim_im) {
	xim_ic = XCreateIC(xim_im,
	                   XNInputStyle, (XIMPreeditNothing | XIMStatusNothing),
			   XNClientWindow, w,
			   XNFocusWindow, w,
			   NULL);
      } else {
	xim_ic = NULL;
      }
      if (!xim_ic) {
	puts("Crash recovery failed. exiting.\n");
	exit(-1);
      }
    }
    if (xevent.type != DestroyNotify) {
      filtered = XFilterEvent(&xevent, 0);
    }
    if (xevent.type == FocusOut && xim_ic) XUnsetICFocus(xim_ic);
    if (xevent.type == FocusIn && xim_ic) XSetICFocus(xim_ic);

    if (xevent.type == KeyPress && !filtered) {
      len = XUtf8LookupString(xim_ic, &xevent.xkey, 
			      buf, 127, &keysym, &status);

      if (len == 1 && buf[0] == '\b') {
	x -= XUtf8TextWidth(fontset, buf, len);
	XUtf8DrawImageString(dpy, w, fontset, gc, 
			     x, y, buf, len);
      } else if (len == 1 && buf[0] == '\r') {
	y += fontset->ascent + fontset->descent;
	x = 0;
	XCloseIM(xim_im);
      } else {
	XUtf8DrawImageString(dpy, w, fontset, gc, x, y, buf, len);
	x += XUtf8TextWidth(fontset, buf, len);
      }

      XUtf8DrawString(dpy, w, fontset, gc, 0, 20, jp_txt, strlen(jp_txt));
      XUtf8DrawString(dpy, w, fontset, gc, 50, 90, rtl_txt, strlen(rtl_txt));
      XUtf8DrawRtlString(dpy, w, fontset, gc, 50, 90, rtl_txt, strlen(rtl_txt));
      buf[len] = 0;
      printf("'%s' %d %x\n", buf, keysym, keysym);
      buf[0] = 0;
    }
    if (filtered) {
      printf("Dead key\n");
    }
  }
  XFreeUtf8FontStruct(dpy, fontset);
  return 0;
}
Exemplo n.º 10
0
int main( int argc, char ** argv)
{
	MouseEvent event, prevevent;
	MouseEvent *pEvent = &event;
	prevevent.type = EVENT_NULL;
	prevevent.value = 0;

	Display	*dpy; /* X server connection */
	Window	win;
	XWindowAttributes winattr;
	int xtest_major_version = 0;
	int xtest_minor_version = 0;
	int dummy;

	SOCKET s, s_accept;
	struct sockaddr_in s_add; //from anyone!
	struct sockaddr s_client;
	socklen_t s_client_size = sizeof( struct sockaddr );
	int port = PORT;
	int recvsize;

	int button, yDelta = 0, yTmp;

	printf("RemotePad Server for X11 version %s\n", kVersionX11);
	printf("Application launched.\n");

    /*
	* Open the display using the $DISPLAY environment variable to locate
	* the X server.  See Section 2.1.
	*/
    if ((dpy = XOpenDisplay(NULL)) == NULL) {
	   printf("%s: can't open DISPLAY: %s\n", argv[0], XDisplayName(NULL));
	   exit(1);
    }

    Bool success = XTestQueryExtension(dpy, &dummy, &dummy,
&xtest_major_version, &xtest_minor_version);
    if(success == False || xtest_major_version < 2 ||
(xtest_major_version <= 2 && xtest_minor_version < 2))
    {
	   printf("XTEST extension not supported\n");
	   exit(1);
    }

	/*
	 * create a small unmapped window on a screen just so xdm can use
	 * it as a handle on which to killclient() us.
	 */
	win = XCreateWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, 0, (XSetWindowAttributes*)0);

	/*
	 * get keyboard mapping to detect modifier keys for each keysym
	 */
	XDisplayKeycodes(dpy, &minKeycode, &maxKeycode);
	int keycodeCount = maxKeycode - minKeycode + 1;
	keyboardMapping = XGetKeyboardMapping(dpy, minKeycode, keycodeCount, &keysymsPerKeycode);

//network stuff
	//configure socket
	if ( ( s = socket( PF_INET, SOCK_STREAM, 0 ) ) == -1 ) 
	{
		perror ( "Failed to create socket :(" ); 
		exit( 2 );

	}

	int yes = 1;
	setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
	memset( &s_add, 0, sizeof( struct sockaddr_in ) );
	s_add.sin_family = AF_INET;
	s_add.sin_port = htons( port );
	s_add.sin_addr.s_addr = INADDR_ANY;

	if ( bind( s, (struct sockaddr * )&s_add, sizeof( struct sockaddr_in ) ) == -1 )
	{
		perror( "Failed to bind socket" );
		exit( 2 );
	}

	if( listen( s , 1 ) )
	{
		perror( "Can't listen!" );
		exit( 2 );
	}

	while( 1 )
	{
		if(!findInterfaceAddresses(s))
			printf("waiting for clients\n");

		struct timeval tv;
		while (1) {
			fd_set fdset;
			FD_ZERO(&fdset);
			FD_SET(s, &fdset);
			tv.tv_sec = 5;
			tv.tv_usec = 0;
			select(s+1, &fdset, NULL, NULL, &tv);
			if (FD_ISSET(s, &fdset))
				break;
			// sending a keep-alive event for an X server
			XGetWindowAttributes(dpy, win, &winattr);
		}

		s_accept = accept( s, &s_client, &s_client_size );

		if ( s_accept == -1 )
		{
			perror( "failed to accept!" );
			return -1;
		} else {
			printf("Connected!\n");
		}

		tv.tv_sec = 5;
		tv.tv_usec = 0;
		setsockopt(s_accept, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv));

		gettimeofday(&tv, NULL);
		MouseEvent versionEvent = {htonl(EVENT_VERSION), htonl(kVersionX11Current), htonl(tv.tv_sec), htonl(tv.tv_usec*1000)};
		send(s_accept, (void *)&versionEvent, sizeof(MouseEvent), 0);

		while( 1 )
		{
			recvsize = recv( s_accept, pEvent, sizeof( MouseEvent ), MSG_WAITALL );
			if ( recvsize == sizeof( MouseEvent ) )//got data
			{
				event.type = ntohl(event.type);
				event.value = ntohl(event.value);
				event.tv_sec = ntohl(event.tv_sec);
				event.tv_nsec = ntohl(event.tv_nsec);

				switch( event.type )
				{

					case EVENT_MOUSE_DELTA_X:
						// following event should be EVENT_MOUSE_DELTA_Y
						break;
					case EVENT_MOUSE_DELTA_Y:
					//	printf( "move: %d, %d!\n", pEvent->move_info.dx, pEvent->move_info.dy );
						if (prevevent.type == EVENT_MOUSE_DELTA_X) {
							XTestFakeRelativeMotionEvent( dpy, prevevent.value, event.value, 0 );
						} else {
							// printf( "stray event EVENT_MOUSE_DELTA_Y\n" );
						}

						break;
					case EVENT_MOUSE_DELTA_W:
						//no x-scrolling :-/
						break;
					case EVENT_MOUSE_DELTA_Z:
						//no x-scrolling :-/
						yDelta += event.value;
						if ( yDelta < 0 )//down
						{
							button = BUTTON_SCROLL_DOWN;
							yTmp = - yDelta;
						}
						else
						{
							button = BUTTON_SCROLL_UP;
							yTmp = yDelta;
						}

						// send as many clicks as necessary (ty synergy for this)
						for( ; yTmp >= SCROLL_AMT; yTmp -= SCROLL_AMT )
						{
							XTestFakeButtonEvent( dpy, button, 1, 0 );
							XTestFakeButtonEvent( dpy, button, 0, 0 );
						}

						//fix yTmp:
						if ( yDelta < 0 )//we were scrolling down
						{
							yDelta = -yTmp;
						}
						else
						{
							yDelta = yTmp;
						}

						break;

					case EVENT_MOUSE_DOWN:
						//printf( "mouse down: %d", pEvent->button_info.button );
						button = ButtonNumber[MouseNumber(event.value) % NButtons];
						XTestFakeButtonEvent( dpy, button, 1, 0 );
						break;

					case EVENT_MOUSE_UP:	
						//printf( "mouse up: %d", pEvent->button_info.button );
						button = ButtonNumber[MouseNumber(event.value) % NButtons];
						XTestFakeButtonEvent( dpy, button, 0, 0 );
						break;

					case EVENT_KEY_UP:	
					case EVENT_KEY_DOWN:
						handleKeyEvent( dpy, pEvent );
						break;

					case EVENT_ASCII:
						simulateKeyWithUnichar(dpy, pEvent);
						break;

					default:
						//printf( "unknown message type: %d\n", event.type );
						break;
				}
				prevevent = event;

				XFlush( dpy );
			
			}
			else if ( recvsize > 0 )
			{
				// printf( "partial recv!\n" );
			}
			else if ( recvsize == 0 )
			{
				//connection terminated
				close( s_accept );
				break; //exit this while loop, wait for another connection
			}
			else if (errno == EAGAIN) {
				// sending a keep-alive event for an X server
				XGetWindowAttributes(dpy, win, &winattr);
			    // sending a keep-alive packet
			    struct timeval tv;
			    gettimeofday(&tv, NULL);
			    MouseEvent event = {htonl(EVENT_NULL), 0, htonl(tv.tv_sec), htonl(tv.tv_usec*1000)};
			    send(s_accept, (void *)&event, sizeof(event), 0);
			}
			else
			{
				perror( "error in recv" );
				shutdown(s_accept, SHUT_RDWR);
				close(s_accept);
				break;
			}
		}

		printf("Disconnected!\n");

	}

	//shouldn't get here!

	return 0;
}
Exemplo n.º 11
0
QXcbWindow::QXcbWindow(QWidget *tlw)
    : QPlatformWindow(tlw)
    , m_context(0)
{
    m_screen = static_cast<QXcbScreen *>(QPlatformScreen::platformScreenForWidget(tlw));

    setConnection(m_screen->connection());

    const quint32 mask = XCB_CW_BACK_PIXMAP | XCB_CW_EVENT_MASK;
    const quint32 values[] = {
        // XCB_CW_BACK_PIXMAP
        XCB_NONE,
        // XCB_CW_EVENT_MASK
        XCB_EVENT_MASK_EXPOSURE
        | XCB_EVENT_MASK_STRUCTURE_NOTIFY
        | XCB_EVENT_MASK_KEY_PRESS
        | XCB_EVENT_MASK_KEY_RELEASE
        | XCB_EVENT_MASK_BUTTON_PRESS
        | XCB_EVENT_MASK_BUTTON_RELEASE
        | XCB_EVENT_MASK_BUTTON_MOTION
        | XCB_EVENT_MASK_ENTER_WINDOW
        | XCB_EVENT_MASK_LEAVE_WINDOW
        | XCB_EVENT_MASK_PROPERTY_CHANGE
        | XCB_EVENT_MASK_FOCUS_CHANGE
    };

#if defined(XCB_USE_GLX) || defined(XCB_USE_EGL)
    if (tlw->platformWindowFormat().windowApi() == QPlatformWindowFormat::OpenGL
        && QApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL)
        || tlw->platformWindowFormat().alpha())
    {
#if defined(XCB_USE_GLX)
        XVisualInfo *visualInfo = qglx_findVisualInfo(DISPLAY_FROM_XCB(m_screen),m_screen->screenNumber(), tlw->platformWindowFormat());
#elif defined(XCB_USE_EGL)
        EGLDisplay eglDisplay = connection()->egl_display();
        EGLConfig eglConfig = q_configFromQPlatformWindowFormat(eglDisplay,tlw->platformWindowFormat(),true);
        VisualID id = QXlibEglIntegration::getCompatibleVisualId(DISPLAY_FROM_XCB(this), eglDisplay, eglConfig);

        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
        visualInfoTemplate.visualid = id;

        XVisualInfo *visualInfo;
        int matchingCount = 0;
        visualInfo = XGetVisualInfo(DISPLAY_FROM_XCB(this), VisualIDMask, &visualInfoTemplate, &matchingCount);
#endif //XCB_USE_GLX
        if (visualInfo) {
            m_depth = visualInfo->depth;
            m_format = (m_depth == 32) ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
            Colormap cmap = XCreateColormap(DISPLAY_FROM_XCB(this), m_screen->root(), visualInfo->visual, AllocNone);

            XSetWindowAttributes a;
            a.background_pixel = WhitePixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
            a.border_pixel = BlackPixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
            a.colormap = cmap;
            m_window = XCreateWindow(DISPLAY_FROM_XCB(this), m_screen->root(), tlw->x(), tlw->y(), tlw->width(), tlw->height(),
                                      0, visualInfo->depth, InputOutput, visualInfo->visual,
                                      CWBackPixel|CWBorderPixel|CWColormap, &a);

            printf("created GL window: %d\n", m_window);
        } else {
            qFatal("no window!");
        }
    } else
#endif //defined(XCB_USE_GLX) || defined(XCB_USE_EGL)
    {
        m_window = xcb_generate_id(xcb_connection());
        m_depth = m_screen->screen()->root_depth;
        m_format = (m_depth == 32) ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;

        Q_XCB_CALL(xcb_create_window(xcb_connection(),
                                     XCB_COPY_FROM_PARENT,            // depth -- same as root
                                     m_window,                        // window id
                                     m_screen->root(),                // parent window id
                                     tlw->x(),
                                     tlw->y(),
                                     tlw->width(),
                                     tlw->height(),
                                     0,                               // border width
                                     XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
                                     m_screen->screen()->root_visual, // visual
                                     0,                               // value mask
                                     0));                             // value list

        printf("created regular window: %d\n", m_window);
    }

    Q_XCB_CALL(xcb_change_window_attributes(xcb_connection(), m_window, mask, values));

    xcb_atom_t properties[4];
    int propertyCount = 0;
    properties[propertyCount++] = atom(QXcbAtom::WM_DELETE_WINDOW);
    properties[propertyCount++] = atom(QXcbAtom::WM_TAKE_FOCUS);
    properties[propertyCount++] = atom(QXcbAtom::_NET_WM_PING);

    if (m_screen->syncRequestSupported())
        properties[propertyCount++] = atom(QXcbAtom::_NET_WM_SYNC_REQUEST);

    if (tlw->windowFlags() & Qt::WindowContextHelpButtonHint)
        properties[propertyCount++] = atom(QXcbAtom::_NET_WM_CONTEXT_HELP);

    Q_XCB_CALL(xcb_change_property(xcb_connection(),
                                   XCB_PROP_MODE_REPLACE,
                                   m_window,
                                   atom(QXcbAtom::WM_PROTOCOLS),
                                   XCB_ATOM_ATOM,
                                   32,
                                   propertyCount,
                                   properties));
    m_syncValue.hi = 0;
    m_syncValue.lo = 0;

    if (m_screen->syncRequestSupported()) {
        m_syncCounter = xcb_generate_id(xcb_connection());
        Q_XCB_CALL(xcb_sync_create_counter(xcb_connection(), m_syncCounter, m_syncValue));

        Q_XCB_CALL(xcb_change_property(xcb_connection(),
                                       XCB_PROP_MODE_REPLACE,
                                       m_window,
                                       atom(QXcbAtom::_NET_WM_SYNC_REQUEST_COUNTER),
                                       XCB_ATOM_CARDINAL,
                                       32,
                                       1,
                                       &m_syncCounter));
    }

    if (isTransient(tlw) && tlw->parentWidget()) {
        // ICCCM 4.1.2.6
        QWidget *p = tlw->parentWidget()->window();
        xcb_window_t parentWindow = p->winId();
        Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
                                       XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32,
                                       1, &parentWindow));

    }

    // set the PID to let the WM kill the application if unresponsive
    long pid = getpid();
    Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
                                   atom(QXcbAtom::_NET_WM_PID), XCB_ATOM_CARDINAL, 32,
                                   1, &pid));
}
Exemplo n.º 12
0
static void About_create_window(void)
{
    const unsigned int		windowWidth = ABOUT_WINDOW_WIDTH,
				buttonWindowHeight = 2*BTN_BORDER
				    + buttonFont->ascent + buttonFont->descent,
				windowHeight = ABOUT_WINDOW_HEIGHT;
    unsigned			textWidth;
    XSetWindowAttributes	sattr;
    unsigned long		mask;


    /*
     * Create the window and initialize window name.
     */
    mask = 0;
    sattr.background_pixel = colors[windowColor].pixel;
    mask |= CWBackPixel;
    sattr.border_pixel = colors[borderColor].pixel;
    mask |= CWBorderPixel;
    if (colormap != 0) {
	sattr.colormap = colormap;
	mask |= CWColormap;
    }
    sattr.backing_store = Always;
    mask |= CWBackingStore;

    aboutWindow
	= XCreateWindow(dpy,
			DefaultRootWindow(dpy),
			0, 0,
			windowWidth, windowHeight,
			2, (int)dispDepth,
			InputOutput, visual,
			mask, &sattr);
    XStoreName(dpy, aboutWindow, "XPilot - information");
    XSetIconName(dpy, aboutWindow, "XPilot/info");
    XSetTransientForHint(dpy, aboutWindow, topWindow);

    textWidth = XTextWidth(buttonFont, "CLOSE", 5);
    about_close_b
	= XCreateSimpleWindow(dpy, aboutWindow,
			      BORDER,
			      (int)(windowHeight - BORDER
				    - buttonWindowHeight - 4),
			      2*BTN_BORDER + textWidth,
			      buttonWindowHeight,
			      0, 0,
			      colors[buttonColor].pixel);

    /*
     * Create 'buttons' in the window.
     */
    textWidth = XTextWidth(buttonFont, "PREV", 4);
    about_prev_b
	= XCreateSimpleWindow(dpy, aboutWindow,
			      (int)(windowWidth / 2
				    - BTN_BORDER - textWidth / 2),
			      (int)(windowHeight
				    - BORDER - buttonWindowHeight - 4),
			      2*BTN_BORDER + textWidth, buttonWindowHeight,
			      0, 0,
			      colors[buttonColor].pixel);

    textWidth = XTextWidth(buttonFont, "NEXT", 4);
    about_next_b
	= XCreateSimpleWindow(dpy, aboutWindow,
			      (int)(windowWidth - BORDER
				    - 2*BTN_BORDER - textWidth),
			      (int)(windowHeight - BORDER
				    - buttonWindowHeight - 4),
			      2*BTN_BORDER + textWidth, buttonWindowHeight,
			      0, 0,
			      colors[buttonColor].pixel);

    XSelectInput(dpy, about_close_b,
		 ExposureMask | ButtonPressMask | ButtonReleaseMask);
    XSelectInput(dpy, about_next_b,
		 ExposureMask | ButtonPressMask | ButtonReleaseMask);
    XSelectInput(dpy, about_prev_b,
		 ExposureMask | ButtonPressMask | ButtonReleaseMask);
    XSelectInput(dpy, aboutWindow, ExposureMask);

    Expose_about_window();

    XMapSubwindows(dpy, aboutWindow);
}
Exemplo n.º 13
0
int wincreat( int x, int y, int width, int height, char *title)
{ 
  XSetWindowAttributes   swa; 
  Colormap               cmap;
  XVisualInfo           *vi;
  int                    dummy;
  GLXContext             glcx;
  XEvent                 event;
  int                    attributes[] = { GLX_RGBA,
                                          GLX_DEPTH_SIZE, 16,
                                          GLX_RED_SIZE, 8,
                                          GLX_GREEN_SIZE, 8,
                                          GLX_BLUE_SIZE, 8,
                                          GLX_ALPHA_SIZE, 8,
                                          GLX_DOUBLEBUFFER,
                                          None }; 

    if( !(dpy = XOpenDisplay( NULL )) )    /* defaults to $DISPLAY */
  {
      fprintf( stderr, "Unable to open display.\n" );
      exit( 1 );

  } else {

    /*printf( "Connected to display... %s (%s).\n", dpy->display_name, dpy->vendor );*/

  }   /* end if( ) */

  if( !glXQueryExtension( dpy, &dummy, &dummy ) )
  {
      fprintf( stderr, "Unable to query GLX extensions.\n" );
      exit( 1 );

  }   /* end if( ) */

  if( !(vi = glXChooseVisual( dpy, DefaultScreen( dpy ), attributes )) )
  {
      fprintf( stderr, "Unable get a visual.\n" );
      exit( 1 );

  }   /* end if( ) */

  if( vi->class != TrueColor )
  {
      fprintf( stderr, "Need TrueColor class.\n" );
      exit( 1 );
  }

  if( !(glcx = glXCreateContext( dpy, vi, None, GL_TRUE )) )
  {
      fprintf( stderr, "Unable create a GL context.\n" );
      exit( 1 );

  }   /* end if( ) */

  cmap = XCreateColormap( dpy, RootWindow( dpy, vi->screen ),
                                     vi->visual, AllocNone );

  swa.colormap                  = cmap;
  swa.border_pixel              = 0;
  swa.event_mask                = ExposureMask
                                | KeyPressMask
                                | StructureNotifyMask;

  glwin = XCreateWindow(        dpy,
                                RootWindow( dpy, vi->screen ),
                                x,
                                y,
                                width,
                                height,
                                0,
                                vi->depth,
                                InputOutput,
                                vi->visual,
                                CWBorderPixel   |
                                CWColormap      |
                                CWEventMask,
                                &swa
                        );

/* Make a clear cursor so it looks like we have none. */
  {
      Pixmap pixmap;
      Cursor cursor;
      XColor color;
      char clear_bits[32];

      memset(clear_bits, 0, sizeof(clear_bits));

      pixmap = XCreatePixmapFromBitmapData(dpy, glwin, clear_bits,
                                           16, 16, 1, 0, 1);
      cursor = XCreatePixmapCursor(dpy, pixmap, pixmap, &color, &color, 8, 8);
      XDefineCursor(dpy, glwin, cursor);

      XFreePixmap(dpy, pixmap);
  }


  XSetStandardProperties( dpy, glwin, title, title, None, NULL, 0, NULL );

  if( !glXMakeCurrent( dpy, glwin, glcx ) )
  {
      fprintf( stderr, "Failed to make the GL context current.\n" );
      exit( 1 );
  }

  XMapWindow( dpy, glwin );
  XIfEvent( dpy, &event, WaitForMapNotify, (char *)glwin );

  return( 1 );

} /* end int APIENTRY pglc_wincreat( ) */
Exemplo n.º 14
0
Arquivo: glxgears.c Projeto: MCL88/psr
/*
 * Create an RGB, double-buffered window.
 * Return the window and context handles.
 */
static void
make_window( Display *dpy, const char *name,
             int x, int y, int width, int height,
             Window *winRet, GLXContext *ctxRet)
{
   int attrib[] = { GLX_RGBA,
		    GLX_RED_SIZE, 1,
		    GLX_GREEN_SIZE, 1,
		    GLX_BLUE_SIZE, 1,
		    GLX_DOUBLEBUFFER,
		    GLX_DEPTH_SIZE, 1,
		    None };
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;
   GLXContext ctx;
   XVisualInfo *visinfo;

   scrnum = DefaultScreen( dpy );
   root = RootWindow( dpy, scrnum );

   visinfo = glXChooseVisual( dpy, scrnum, attrib );
   if (!visinfo) {
      printf("Error: couldn't get an RGB, Double-buffered visual\n");
      exit(1);
   }

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow( dpy, root, 0, 0, width, height,
		        0, visinfo->depth, InputOutput,
		        visinfo->visual, mask, &attr );

   /* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(dpy, win, &sizehints);
      XSetStandardProperties(dpy, win, name, name,
                              None, (char **)NULL, 0, &sizehints);
   }

   ctx = glXCreateContext( dpy, visinfo, NULL, True );
   if (!ctx) {
      printf("Error: glXCreateContext failed\n");
      exit(1);
   }

   XFree(visinfo);

   *winRet = win;
   *ctxRet = ctx;
}
Exemplo n.º 15
0
int main() {
    Display *dpy;
    int attrib[] = { GLX_RGBA,
		     GLX_RED_SIZE, 8,
		     GLX_GREEN_SIZE, 8,
		     GLX_BLUE_SIZE, 8,
		     GLX_DEPTH_SIZE, 24,
		     None };
    int eventbase, errorbase;
    int screen;
    Window root, win;
    XVisualInfo *visinfo;
    XSetWindowAttributes attr;
    GLXContext ctx;

    dpy = XOpenDisplay(NULL);
    
    if(NULL == dpy) {
        fprintf(stderr, "error: unable to open display!\n");
        return EXIT_FAILURE;
    }
    
    if(!glXQueryExtension(dpy, &eventbase, &errorbase)) {
        fprintf(stderr, "GLX is not available!\n");
        return EXIT_FAILURE;
    }
    
    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);

    visinfo = glXChooseVisual(dpy, screen, attrib);

    if(!visinfo) {
	fprintf(stderr, "error: couldn't get an RGBA, double-buffered visual!\n");
	return EXIT_FAILURE;
    }

    attr.background_pixel = 0;
    attr.border_pixel = 0;
    attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
    attr.event_mask = StructureNotifyMask | ExposureMask;

    win = XCreateWindow(dpy, root, /*x*/ 0, /*y*/ 0, 
			/*width*/ 400, /*height*/ 400,
			0, visinfo->depth, InputOutput,
			visinfo->visual, 
			CWBackPixel | CWBorderPixel | CWColormap | CWEventMask,
			&attr);
   
    ctx = glXCreateContext(dpy, visinfo, NULL, True );
    if(!ctx) {
	fprintf(stderr, "error: glXCreateContext failed!\n");
	return EXIT_FAILURE;
    }
    
    XMapWindow(dpy, win);

    glXMakeCurrent(dpy, win, ctx);

    event_loop(dpy);

    return EXIT_SUCCESS;
}
Exemplo n.º 16
0
/*
 * createXworkWindow()
 *
 * Utility to create an X-Window.
 * Borrowed heavily from function by the same name in xcontrol.c
 *
 */
static Window
createXWorkWindow(Display *dpy, CROddp* psa)
{
    Window                  win;
    static  XWMHints        xwmh = {
        (InputHint | StateHint ),/* flags                       */
        True,                   /* input                        */
        NormalState,            /* initial_state                */
        0,                      /* icon pixmap                  */
        0,                      /* icon window                  */
        0, 0,                   /* icon location                */
        0,                      /* icon mask                    */
        0                       /* Window group                 */
    };
    static XClassHint xch = {
        "xgks", /* resource name                */
        "Xgks"  /* class name                   */
    };
    XSizeHints              xsh = { /* Size hints for window manager*/
        (PMinSize),
        0,0,                    /* obsolete ????                */
        DEFAULT_WIDTH,          /* obsolete ????                */
        DEFAULT_HEIGHT,         /* obsolete ????                */
        MIN_WIDTH, MIN_HEIGHT,  /* minimum usefull win dim      */
        0,0,                    /* max dim (not used)           */
        0,0,                    /* not used                     */
        {0,0},                  /* not used                     */
        {0,0},                  /* not used                     */
        0,
        0,                      /* dimensions of window         */
        0
    };
    char                    *geometry=NULL;
    int                     geom_mask = 0;
    XSetWindowAttributes    xswa;   /* Set Window Attribute struct  */
    XTextProperty           window_name, icon_name;
    unsigned long           bw = 0; /* Border width                 */
    XEvent                   event; /* Event received               */
    Atom                    wm_del;

    xsh.x = psa->window_pos_x;
    xsh.y = psa->window_pos_y;
    xsh.width = psa->image_width;
    xsh.height = psa->image_height;
    geom_mask = XValue | YValue | WidthValue | HeightValue;

    /*
     * see if user specified a window position.
     */
    if ((geom_mask & XValue) || (geom_mask & YValue)) {
        xsh.flags |= USPosition;
    }

    /*
     * deal with negative position
     */
    if ((geom_mask & XValue) && (geom_mask & XNegative)) {
        xsh.x = DisplayWidth (dpy, DefaultScreen(dpy)) + xsh.x -
            xsh.width - bw * 2;
    }

    if ((geom_mask & YValue) && (geom_mask & YNegative)) {
        xsh.y = DisplayWidth (dpy, DefaultScreen(dpy)) + xsh.y -
            xsh.height - bw * 2;
    }


    /*
     * see if user specified a dimension, else we use program defaults
     */
    if ((geom_mask & WidthValue) || (geom_mask & HeightValue)) {
        xsh.flags |= USSize;
    }
    else {
        xsh.flags |= PSize;
    }

    /*
     * Ensure that the window's colormap field points to the default
     * colormap,  so that the window manager knows the correct
     * colormap to use for the window.
     */
    xswa.bit_gravity = CenterGravity;
    xswa.backing_store = WhenMapped;
    xswa.background_pixel = WhitePixel(dpy, DefaultScreen(dpy));
    xswa.border_pixel = WhitePixel(dpy, DefaultScreen(dpy)); 

    /*
     * Create the Window with the information in the XSizeHints, the
     * border width, and the border & background pixels.
     */
    win = XCreateWindow(dpy, RootWindow(dpy,DefaultScreen(dpy)),
                        xsh.x, xsh.y, xsh.width, xsh.height,
                        bw,CopyFromParent,InputOutput,CopyFromParent,
                        (CWBitGravity|CWBackingStore|CWBackPixel|CWBorderPixel),&xswa);

    /*
     * Set the standard properties for the window managers.
     */
    window_name.encoding = XA_STRING;
    window_name.format = 8;
    window_name.value = (unsigned char *) psa->window_title;
    window_name.nitems = strlen ((char *)window_name.value);

    icon_name.encoding = XA_STRING;
    icon_name.format = 8;
    icon_name.value = (unsigned char *) psa->icon_title;
    icon_name.nitems = strlen ((char *)icon_name.value);

    XSetWMProperties(dpy,win,&window_name,&icon_name,NULL,0,&xsh,&xwmh,
                     &xch);

    /*
     * Select notification of Expose event that is generated when
     * the window is first mapped (becomes visible) to the screen.
     */
    XSelectInput(dpy, win, ExposureMask);

    /*
     * Map the window to make it visible.
     */
    XMapWindow(dpy, win);

    /*
     *      get expose event as window becomes visible. we can't
     *      draw until after this
     */
    while(1) {
        /* get next event       */
        XNextEvent(dpy, &event);

        /*
         * find the last expose event on the event queue.
         */
        if (event.type == Expose && event.xexpose.count == 0) {

            /*
             * Remove any other pending Expose events from
             * the queue to avoid multiple repaints.
             */
            /*SUPPRESS570*/
            while (XCheckTypedEvent(dpy, Expose, &event));

            break;
        }
    }

    /*
     * Select input for "pause" and destroy of window.
     */
    XSelectInput(dpy,win,
                 (ButtonPressMask|KeyPressMask|StructureNotifyMask));

    /*
     * Request clientMessage events for WM_DELETE_WINDOW.
     */

    wm_del = XInternAtom(dpy,"WM_DELETE_WINDOW",False);
    XSetWMProtocols(dpy,win,&wm_del,1);

    return win;
}
Exemplo n.º 17
0
void wsCreateWindow(wsTWindow *win, int X, int Y, int wX, int hY, int bW, int cV, unsigned char D, char *label)
{
    int depth;

    win->Property = D;

    if (D & wsShowFrame)
        win->Decorations = 1;

    wsHGC = DefaultGC(wsDisplay, wsScreen);

    wsWindowPosition(win, X, Y, wX, hY);

    win->Width     = wX;
    win->Height    = hY;
    win->OldX      = win->X;
    win->OldY      = win->Y;
    win->OldWidth  = win->Width;
    win->OldHeight = win->Height;

    /* Border size for window. */
    win->BorderWidth = bW;
    /* Hide Mouse Cursor */
    win->wsCursor = None;
    win->wsMouseEventType = cV;
    win->wsCursorData[0]  = 0;
    win->wsCursorPixmap   = XCreateBitmapFromData(wsDisplay, wsRootWin, win->wsCursorData, 1, 1);

    if (!(cV & wsShowMouseCursor))
        win->wsCursor = XCreatePixmapCursor(wsDisplay, win->wsCursorPixmap, win->wsCursorPixmap, &win->wsColor, &win->wsColor, 0, 0);

    depth = vo_find_depth_from_visuals(wsDisplay, wsScreen, NULL);

    if (depth < 15) {
        mp_msg(MSGT_GPLAYER, MSGL_FATAL, MSGTR_WS_ColorDepthTooLow);
        mplayer(MPLAYER_EXIT_GUI, EXIT_ERROR, 0);
    }

    XMatchVisualInfo(wsDisplay, wsScreen, depth, TrueColor, &win->VisualInfo);

    /* --- */
    win->AtomLeaderClient = XInternAtom(wsDisplay, "WM_CLIENT_LEADER", False);
    win->AtomDeleteWindow = XInternAtom(wsDisplay, "WM_DELETE_WINDOW", False);
    win->AtomTakeFocus    = XInternAtom(wsDisplay, "WM_TAKE_FOCUS", False);
    win->AtomRolle         = XInternAtom(wsDisplay, "WM_WINDOW_ROLE", False);
    win->AtomWMSizeHint    = XInternAtom(wsDisplay, "WM_SIZE_HINT", False);
    win->AtomWMNormalHint  = XInternAtom(wsDisplay, "WM_NORMAL_HINT", False);
    win->AtomProtocols     = XInternAtom(wsDisplay, "WM_PROTOCOLS", False);
    win->AtomsProtocols[0] = win->AtomDeleteWindow;
    win->AtomsProtocols[1] = win->AtomTakeFocus;
    win->AtomsProtocols[2] = win->AtomRolle;
    /* --- */

    win->WindowAttrib.background_pixel = BlackPixel(wsDisplay, wsScreen);
    win->WindowAttrib.border_pixel     = WhitePixel(wsDisplay, wsScreen);
    win->WindowAttrib.colormap   = XCreateColormap(wsDisplay, wsRootWin, win->VisualInfo.visual, AllocNone);
    win->WindowAttrib.event_mask = StructureNotifyMask | FocusChangeMask |
                                   ExposureMask | PropertyChangeMask |
                                   EnterWindowMask | LeaveWindowMask |
                                   VisibilityChangeMask |
                                   KeyPressMask | KeyReleaseMask;

    if ((cV & wsHandleMouseButton))
        win->WindowAttrib.event_mask |= ButtonPressMask | ButtonReleaseMask;

    if ((cV & wsHandleMouseMove))
        win->WindowAttrib.event_mask |= PointerMotionMask;

    win->WindowAttrib.cursor = win->wsCursor;
    win->WindowAttrib.override_redirect = False;

    if (D & wsOverredirect)
        win->WindowAttrib.override_redirect = True;

    win->WindowMask = CWBackPixel | CWBorderPixel |
                      CWColormap | CWEventMask | CWCursor |
                      CWOverrideRedirect;

    win->WindowID = XCreateWindow(wsDisplay,
                                  (win->Parent != 0 ? win->Parent : wsRootWin),
                                  win->X, win->Y, win->Width, win->Height, win->BorderWidth,
                                  win->VisualInfo.depth,
                                  InputOutput,
                                  win->VisualInfo.visual,
                                  win->WindowMask, &win->WindowAttrib);

    wsClassHint.res_name = "MPlayer";

    wsClassHint.res_class = "MPlayer";
    XSetClassHint(wsDisplay, win->WindowID, &wsClassHint);

    win->SizeHint.flags  = PPosition | PSize | PResizeInc | PWinGravity; // | PBaseSize;
    win->SizeHint.x      = win->X;
    win->SizeHint.y      = win->Y;
    win->SizeHint.width  = win->Width;
    win->SizeHint.height = win->Height;

    if (D & wsMinSize) {
        win->SizeHint.flags     |= PMinSize;
        win->SizeHint.min_width  = win->Width;
        win->SizeHint.min_height = win->Height;
    }

    if (D & wsMaxSize) {
        win->SizeHint.flags     |= PMaxSize;
        win->SizeHint.max_width  = win->Width;
        win->SizeHint.max_height = win->Height;
    }

    win->SizeHint.height_inc  = 1;
    win->SizeHint.width_inc   = 1;
    win->SizeHint.base_width  = win->Width;
    win->SizeHint.base_height = win->Height;
    win->SizeHint.win_gravity = StaticGravity;
    XSetWMNormalHints(wsDisplay, win->WindowID, &win->SizeHint);

    win->WMHints.flags = InputHint | StateHint;
    win->WMHints.input = True;
    win->WMHints.initial_state = NormalState;
    XSetWMHints(wsDisplay, win->WindowID, &win->WMHints);

    wsWindowDecoration(win, win->Decorations);
    XStoreName(wsDisplay, win->WindowID, label);
    XmbSetWMProperties(wsDisplay, win->WindowID, label, label, NULL, 0, NULL, NULL, NULL);

    XSetWMProtocols(wsDisplay, win->WindowID, win->AtomsProtocols, 3);
    XChangeProperty(wsDisplay, win->WindowID,
                    win->AtomLeaderClient,
                    XA_WINDOW, 32, PropModeReplace,
                    (unsigned char *)&LeaderWindow, 1);

    wsTextProperty.value    = label;
    wsTextProperty.encoding = XA_STRING;
    wsTextProperty.format   = 8;
    wsTextProperty.nitems   = strlen(label);
    XSetWMIconName(wsDisplay, win->WindowID, &wsTextProperty);

    win->wGC = XCreateGC(wsDisplay, win->WindowID,
                         GCForeground | GCBackground,
                         &win->wGCV);

    win->Visible = 0;
    win->Focused = 0;
    win->Mapped  = 0;
    win->Rolled  = 0;

    if (D & wsShowWindow)
        XMapWindow(wsDisplay, win->WindowID);

    wsCreateImage(win, win->Width, win->Height);
    /* End of creating -------------------------------------------------------------------------- */

    {
        int i;

        for (i = 0; i < wsWLCount; i++)
            if (wsWindowList[i] == NULL)
                break;

        if (i == wsWLCount) {
            mp_msg(MSGT_GPLAYER, MSGL_FATAL, MSGTR_WS_TooManyOpenWindows);
            mplayer(MPLAYER_EXIT_GUI, EXIT_ERROR, 0);
        }

        wsWindowList[i] = win;
    }

    XFlush(wsDisplay);
    XSync(wsDisplay, False);

    win->ReDraw       = NULL;
    win->ReSize       = NULL;
    win->Idle         = NULL;
    win->MouseHandler = NULL;
    win->KeyHandler   = NULL;
    mp_msg(MSGT_GPLAYER, MSGL_DBG2, "[ws] window is created. ( %s ).\n", label);
}
Exemplo n.º 18
0
/*
 * we'll call this once for each thread, before the threads are created.
 */
static void
create_window(struct winthread *wt, GLXContext shareCtx)
{
   Window win;
   GLXContext ctx;
   int attrib[] = { GLX_RGBA,
		    GLX_RED_SIZE, 1,
		    GLX_GREEN_SIZE, 1,
		    GLX_BLUE_SIZE, 1,
                    GLX_DEPTH_SIZE, 1,
		    GLX_DOUBLEBUFFER,
		    None };
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   XVisualInfo *visinfo;
   int width = 160, height = 160;
   int xpos = (wt->Index % 8) * (width + 10);
   int ypos = (wt->Index / 8) * (width + 20);

   scrnum = DefaultScreen(wt->Dpy);
   root = RootWindow(wt->Dpy, scrnum);

   visinfo = glXChooseVisual(wt->Dpy, scrnum, attrib);
   if (!visinfo) {
      Error("Unable to find RGB, Z, double-buffered visual");
   }

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap(wt->Dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow(wt->Dpy, root, xpos, ypos, width, height,
		        0, visinfo->depth, InputOutput,
		        visinfo->visual, mask, &attr);
   if (!win) {
      Error("Couldn't create window");
   }

   {
      XSizeHints sizehints;
      sizehints.x = xpos;
      sizehints.y = ypos;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(wt->Dpy, win, &sizehints);
      XSetStandardProperties(wt->Dpy, win, "glthreads", "glthreads",
                              None, (char **)NULL, 0, &sizehints);
   }


   ctx = glXCreateContext(wt->Dpy, visinfo, shareCtx, True);
   if (!ctx) {
      Error("Couldn't create GLX context");
   }

   XMapWindow(wt->Dpy, win);
   XSync(wt->Dpy, 0);

   /* save the info for this window/context */
   wt->Win = win;
   wt->Context = ctx;
   wt->Angle = 0.0;
   wt->WinWidth = width;
   wt->WinHeight = height;
   wt->NewSize = GL_TRUE;
}
Exemplo n.º 19
0
/*
 * Create an RGB, double-buffered X window.
 * Return the window and context handles.
 */
static void
make_x_window(Display *x_dpy, EGLDisplay egl_dpy,
              const char *name,
              int x, int y, int width, int height,
              Window *winRet,
              EGLContext *ctxRet,
              EGLSurface *surfRet)
{
   static const EGLint attribs[] = {
      EGL_RED_SIZE, 1,
      EGL_GREEN_SIZE, 1,
      EGL_BLUE_SIZE, 1,
      EGL_DEPTH_SIZE, 1,
      EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
      EGL_NONE
   };
   static const EGLint ctx_attribs[] = {
      EGL_CONTEXT_CLIENT_VERSION, 2,
      EGL_NONE
   };
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;
   XVisualInfo *visInfo, visTemplate;
   int num_visuals;
   EGLContext ctx;
   EGLConfig config;
   EGLint num_configs;
   EGLint vid;

   scrnum = DefaultScreen( x_dpy );
   root = RootWindow( x_dpy, scrnum );

   if (!eglChooseConfig( egl_dpy, attribs, &config, 1, &num_configs)) {
      printf("Error: couldn't get an EGL visual config\n");
      exit(1);
   }

   assert(config);
   assert(num_configs > 0);

   if (!eglGetConfigAttrib(egl_dpy, config, EGL_NATIVE_VISUAL_ID, &vid)) {
      printf("Error: eglGetConfigAttrib() failed\n");
      exit(1);
   }

   /* The X window visual must match the EGL config */
   visTemplate.visualid = vid;
   visInfo = XGetVisualInfo(x_dpy, VisualIDMask, &visTemplate, &num_visuals);
   if (!visInfo) {
      printf("Error: couldn't get X visual\n");
      exit(1);
   }

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap( x_dpy, root, visInfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow( x_dpy, root, 0, 0, width, height,
                        0, visInfo->depth, InputOutput,
                        visInfo->visual, mask, &attr );

   /* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(x_dpy, win, &sizehints);
      XSetStandardProperties(x_dpy, win, name, name,
                              None, (char **)NULL, 0, &sizehints);
   }

#if USE_FULL_GL /* XXX fix this when eglBindAPI() works */
   eglBindAPI(EGL_OPENGL_API);
#else
   eglBindAPI(EGL_OPENGL_ES_API);
#endif

   ctx = eglCreateContext(egl_dpy, config, EGL_NO_CONTEXT, ctx_attribs );
   if (!ctx) {
      printf("Error: eglCreateContext failed\n");
      exit(1);
   }

   /* test eglQueryContext() */
   {
      EGLint val;
      eglQueryContext(egl_dpy, ctx, EGL_CONTEXT_CLIENT_VERSION, &val);
      assert(val == 2);
   }

   *surfRet = eglCreateWindowSurface(egl_dpy, config, win, NULL);
   if (!*surfRet) {
      printf("Error: eglCreateWindowSurface failed\n");
      exit(1);
   }

   /* sanity checks */
   {
      EGLint val;
      eglQuerySurface(egl_dpy, *surfRet, EGL_WIDTH, &val);
      assert(val == width);
      eglQuerySurface(egl_dpy, *surfRet, EGL_HEIGHT, &val);
      assert(val == height);
      assert(eglGetConfigAttrib(egl_dpy, config, EGL_SURFACE_TYPE, &val));
      assert(val & EGL_WINDOW_BIT);
   }

   XFree(visInfo);

   *winRet = win;
   *ctxRet = ctx;
}
Exemplo n.º 20
0
void* platform::getNativeWindow()
{
	Window root;
	XSetWindowAttributes swa;
	XSetWindowAttributes  xattr;
	Atom wm_state;
	XWMHints hints;
	XEvent xev;
	EGLConfig ecfg;
	EGLint num_config;
	Window win;

	Display* x_display = XOpenDisplay(NULL);
	assert(x_display);
 
     /*
      * X11 native display initialization
      */
 
     x_display = XOpenDisplay(NULL);
     if ( x_display == NULL )
     {
         return EGL_FALSE;
     }
 
     root = DefaultRootWindow(x_display);
 
     swa.event_mask  =  ExposureMask | PointerMotionMask | KeyPressMask;
     win = XCreateWindow(
                x_display, root,
                0, 0, 640, 480, 0,
                CopyFromParent, InputOutput,
                CopyFromParent, CWEventMask,
                &swa );
 
     xattr.override_redirect = false;
     XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );
 
     hints.input = true;
     hints.flags = InputHint;
     XSetWMHints(x_display, win, &hints);
 
     // make the window visible on the screen
     XMapWindow (x_display, win);
     XStoreName (x_display, win, "foo");
 
     // get identifiers for the provided atom name strings
     wm_state = XInternAtom (x_display, "_NET_WM_STATE", false);
 
     memset ( &xev, 0, sizeof(xev) );
     xev.type                 = ClientMessage;
     xev.xclient.window       = win;
     xev.xclient.message_type = wm_state;
     xev.xclient.format       = 32;
     xev.xclient.data.l[0]    = 1;
     xev.xclient.data.l[1]    = false;
     XSendEvent (
        x_display,
        DefaultRootWindow ( x_display ),
        false,
        SubstructureNotifyMask,
        &xev );
 
     //(eEGLNativeWindowType) win;
     return (void*) win;

}
static cairo_surface_t *
_cairo_boilerplate_vg_create_surface_glx (const char	*name,
        cairo_content_t	 content,
        double		 width,
        double		 height,
        double		 max_width,
        double		 max_height,
        cairo_boilerplate_mode_t mode,
        int		 id,
        void		**closure)
{
    int rgba_attribs[] = {
        GLX_RGBA,
        GLX_RED_SIZE, 1,
        GLX_GREEN_SIZE, 1,
        GLX_BLUE_SIZE, 1,
        GLX_ALPHA_SIZE, 1,
        GLX_DOUBLEBUFFER,
        None
    };
    int rgb_attribs[] = {
        GLX_RGBA,
        GLX_RED_SIZE, 1,
        GLX_GREEN_SIZE, 1,
        GLX_BLUE_SIZE, 1,
        GLX_DOUBLEBUFFER,
        None
    };
    XVisualInfo *vi;
    Display *dpy;
    Colormap cmap;
    XSetWindowAttributes swa;
    cairo_surface_t *surface;
    cairo_vg_context_t *context;
    vg_closure_glx_t *vgc;

    vgc = malloc (sizeof (vg_closure_glx_t));
    *closure = vgc;

    if (width == 0)
        width = 1;
    if (height == 0)
        height = 1;

    dpy = XOpenDisplay (NULL);
    vgc->dpy = dpy;
    if (vgc->dpy == NULL) {
        fprintf (stderr, "Failed to open display: %s\n", XDisplayName(0));
        free (vgc);
        return NULL;
    }

    if (content == CAIRO_CONTENT_COLOR)
        vi = glXChooseVisual (dpy, DefaultScreen (dpy), rgb_attribs);
    else
        vi = glXChooseVisual (dpy, DefaultScreen (dpy), rgba_attribs);

    if (vi == NULL) {
        fprintf (stderr, "Failed to create RGB, double-buffered visual\n");
        XCloseDisplay (dpy);
        free (vgc);
        return NULL;
    }

    vgc->ctx = glXCreateContext (dpy, vi, NULL, True);
    cmap = XCreateColormap (dpy,
                            RootWindow (dpy, vi->screen),
                            vi->visual,
                            AllocNone);
    swa.colormap = cmap;
    swa.border_pixel = 0;
    vgc->win = XCreateWindow (dpy, RootWindow (dpy, vi->screen),
                              -1, -1, 1, 1, 0,
                              vi->depth,
                              InputOutput,
                              vi->visual,
                              CWBorderPixel | CWColormap, &swa);
    XFreeColormap (dpy, cmap);
    XFree (vi);

    XMapWindow (dpy, vgc->win);

    /* we need an active context to initialise VG */
    glXMakeContextCurrent (dpy, vgc->win, vgc->win, vgc->ctx);

#ifdef USE_AMANITH
    vgInitContextAM (width, height, VG_FALSE, VG_TRUE);
#endif
#ifdef USE_SHIVA
    vgCreateContextSH (width, height);
#endif

    context = cairo_vg_context_create_for_glx (dpy, vgc->ctx);
    vgc->surface = cairo_vg_surface_create (context, content, width, height);
    cairo_vg_context_destroy (context);

    surface = vgc->surface;
    if (cairo_surface_status (surface))
        _cairo_boilerplate_vg_cleanup_glx (vgc);

    return surface;
}
Exemplo n.º 22
0
int main(int argc, char **argv) {


    Display *dpy;
    XVisualInfo *vi;
    Colormap cmap;
    XSetWindowAttributes swa;
    Window win;
    GLXContext cx;
    XEvent event;
    int swap_flag = 1; /* get a connection */ dpy = XOpenDisplay(0); /* get an appropriate visual */
    vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributeListSgl);
    if (vi == NULL) {
        vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributeListDbl);
        swap_flag = 1;
    } /* create a GLX context */ cx = glXCreateContext(dpy, vi, 0, GL_TRUE);
    /* create a color map */ cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), vi->visual, AllocNone);
    /* create a window */
    swa.colormap = cmap;
    swa.border_pixel = 0;
    swa.event_mask = StructureNotifyMask;
    win = XCreateWindow(dpy, RootWindow(dpy, vi->screen), 0, 0, 512, 512, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
    XMapWindow(dpy, win);
    XIfEvent(dpy, &event, WaitForNotify, (char*)win);



    /* connect the context to the window */
    glXMakeCurrent(dpy, win, cx);

    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        printf("glew failed to init\n");
        exit(1);
    }
    printf("glew initialized\n");


    glViewport(0,0,512,512);
    glMatrixMode   ( GL_PROJECTION );  // Select The Projection Matrix
    glLoadIdentity ( );                // Reset The Projection Matrix
    gluPerspective ( 80, 1, 1.0, 5000.0 );

    glMatrixMode   ( GL_MODELVIEW );  // Select The Model View Matrix
    glLoadIdentity ( );    // Reset The Model View Matrix
    /* clear the buffer */
    glClearColor(1,1,0,1);
    GLuint list = glGenLists(1);
    glNewList(list, GL_COMPILE);


    glBegin(GL_TRIANGLES);
    glColor3f(1.0f,0.0f,0.0f);			// Red
    glVertex3f( 0.0f, 1.0f, 0.0f);			// Top Of Triangle (Front)
    glColor3f(0.0f,1.0f,0.0f);			// Green
    glVertex3f(-1.0f,-1.0f, 1.0f);			// Left Of Triangle (Front)
    glColor3f(0.0f,0.0f,1.0f);			// Blue
    glVertex3f( 1.0f,-1.0f, 1.0f);			// Right Of Triangle (Front)

    glColor3f(1.0f,0.0f,0.0f);			// Red
    glVertex3f( 0.0f, 1.0f, 0.0f);			// Top Of Triangle (Right)
    glColor3f(0.0f,0.0f,1.0f);			// Blue
    glVertex3f( 1.0f,-1.0f, 1.0f);			// Left Of Triangle (Right)
    glColor3f(0.0f,1.0f,0.0f);			// Green
    glVertex3f( 1.0f,-1.0f, -1.0f);			// Right Of Triangle (Right)

    glColor3f(1.0f,0.0f,0.0f);			// Red
    glVertex3f( 0.0f, 1.0f, 0.0f);			// Top Of Triangle (Back)
    glColor3f(0.0f,1.0f,0.0f);			// Green
    glVertex3f( 1.0f,-1.0f, -1.0f);			// Left Of Triangle (Back)
    glColor3f(0.0f,0.0f,1.0f);			// Blue
    glVertex3f(-1.0f,-1.0f, -1.0f);			// Right Of Triangle (Back)

    glColor3f(1.0f,0.0f,0.0f);			// Red
    glVertex3f( 0.0f, 1.0f, 0.0f);			// Top Of Triangle (Left)
    glColor3f(0.0f,0.0f,1.0f);			// Blue
    glVertex3f(-1.0f,-1.0f,-1.0f);			// Left Of Triangle (Left)
    glColor3f(0.0f,1.0f,0.0f);			// Green
    glVertex3f(-1.0f,-1.0f, 1.0f);			// Right Of Triangle (Left)
    glEnd();						// Done Drawing The Pyramid
    glEndList();
    int i;
    for(i = 0; i < 100; i++)
    {

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     // Clear The Screen And The Depth Buffer
        glLoadIdentity();                                       // Reset The View
        glTranslatef(-1.5f,0.0f,-16.0f);                         // Move Left And Into The Screen

        glRotatef(0.5,0.0f,1.0f,0.0f);                          // Rotate The Pyramid On It's Y Axis

        glCallList(list);
        glFinish();
        if (swap_flag) glXSwapBuffers(dpy,win);
    }
    /* wait a while */ sleep(2);
}
Exemplo n.º 23
0
static INLINE boolean
st_hardpipe_load(void)
{
   Display *dpy;
   int scrnum;
   Window root;
   int attribSingle[] = {
      GLX_RGBA,
      GLX_RED_SIZE, 1,
      GLX_GREEN_SIZE, 1,
      GLX_BLUE_SIZE, 1,
      None };
   int attribDouble[] = {
      GLX_RGBA,
      GLX_RED_SIZE, 1,
      GLX_GREEN_SIZE, 1,
      GLX_BLUE_SIZE, 1,
      GLX_DOUBLEBUFFER,
      None };
   XVisualInfo *visinfo;
   GLXContext ctx = NULL;
   XSetWindowAttributes attr;
   unsigned long mask;
   int width = 100, height = 100;
   Window win;

   dpy = XOpenDisplay(NULL);
   if (!dpy)
      return FALSE;

   scrnum = 0;
   
   root = RootWindow(dpy, scrnum);

   visinfo = glXChooseVisual(dpy, scrnum, attribSingle);
   if (!visinfo)
      visinfo = glXChooseVisual(dpy, scrnum, attribDouble);
   if (!visinfo)
      return FALSE;
      
   ctx = glXCreateContext( dpy, visinfo, NULL, True );

   if (!ctx)
      return FALSE;

   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask;
   
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
   
   win = XCreateWindow(dpy, root, 0, 0, width, height,
                       0, visinfo->depth, InputOutput,
                       visinfo->visual, mask, &attr);

   if (!glXMakeCurrent(dpy, win, ctx))
      return FALSE;

   pfnGetGalliumScreenMESA = (PFNGETGALLIUMSCREENMESAPROC)glXGetProcAddressARB((const GLubyte *)"glXGetGalliumScreenMESA");
   if(!pfnGetGalliumScreenMESA)
      return FALSE;

   pfnCreateGalliumContextMESA = (PFNCREATEGALLIUMCONTEXTMESAPROC)glXGetProcAddressARB((const GLubyte *)"glXCreateGalliumContextMESA");
   if(!pfnCreateGalliumContextMESA)
      return FALSE;

   glXDestroyContext(dpy, ctx);
   XFree(visinfo);
   XDestroyWindow(dpy, win);
   XCloseDisplay(dpy);

   return TRUE;
}
Exemplo n.º 24
0
static int initEGL(void)
{
	NativeWindowType window = 0;

	printf ("GL init\n");

	EGLint numConfigs;
	EGLint majorVersion;
	EGLint minorVersion;
#if defined(USE_X11)
	enum
	{
	_NET_WM_STATE_REMOVE =0,
	_NET_WM_STATE_ADD = 1,
	_NET_WM_STATE_TOGGLE =2
	};
	
	Window			        sRootWindow;
	XSetWindowAttributes	sWA;
	unsigned int		    ui32Mask;
	int			            i32Depth;
#endif
	
	EGLint *attribList = NULL;
	if (use_fsaa)
	{
		printf( "GLES: Using Full Scene Antialiasing\n" );
		attribList = attrib_list_fsaa;
	}
	else
	{
		attribList = attrib_list;
	}

#if defined(USE_X11)
            // Initializes the display and screen
            x11Display = XOpenDisplay( ":0" );
            if (!x11Display)
            {
                printf("GLES Error: Unable to open X display\n");
                return -1;
            }
            x11Screen = XDefaultScreen( x11Display );

            // Gets the display parameters so we can pass the same parameters to the window to be created.
            sRootWindow	= RootWindow(x11Display, x11Screen);
            i32Depth	= DefaultDepth(x11Display, x11Screen);
            px11Visual	= &x11Visual;
            XMatchVisualInfo( x11Display, x11Screen, i32Depth, TrueColor, px11Visual);
            if (!px11Visual)
            {
                printf("GLES Error: Unable to acquire visual\n");
                return -1;
            }
            // Colormap of the specified visual type for the display.
            x11Colormap = XCreateColormap( x11Display, sRootWindow, px11Visual->visual, AllocNone );
            sWA.colormap = x11Colormap;

            // List of events to be handled by the application. Add to these for handling other events.
            sWA.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask;

            // Display capabilities list.
            ui32Mask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap;

            // Creates the X11 window
            x11Window = XCreateWindow( x11Display, RootWindow(x11Display, x11Screen), 0, 0, iResX, iResY,
                                        0, CopyFromParent, InputOutput, CopyFromParent, ui32Mask, &sWA);

            // Make the window viewable and flush the output buffer.
            XMapWindow(x11Display, x11Window);
            XFlush(x11Display);

            // Make the window fullscreen
            unsigned char fullScreen = 1;
            Atom wmState = XInternAtom(x11Display, "_NET_WM_STATE", False);
            Atom wmFullScreen = XInternAtom(x11Display,"_NET_WM_STATE_FULLSCREEN", False);

            XEvent xev;
            xev.xclient.type		    = ClientMessage;
            xev.xclient.serial		    = 0;
            xev.xclient.send_event      = True;
            xev.xclient.window		    = x11Window;
            xev.xclient.message_type    = wmState;
            xev.xclient.format		    = 32;
            xev.xclient.data.l[0]		= (fullScreen ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE);
            xev.xclient.data.l[1]		= wmFullScreen;
            xev.xclient.data.l[2]		= 0;

            XSendEvent(x11Display, DefaultRootWindow(x11Display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);

            display = eglGetDisplay( (EGLNativeDisplayType)x11Display );
            window = x11Window;
#else
            display = eglGetDisplay( (EGLNativeDisplayType)0 );
#endif

	if( display == EGL_NO_DISPLAY )
	{
		printf( "GLES EGL Error: GL No Display\n" );
		return -1;
	}

	if( !eglInitialize( display, &majorVersion, &minorVersion ) )
	{
		printf( "GLES EGL Error: eglInitialize failed\n" );
		return -1;
	}

	if( !eglChooseConfig( display, attribList, &config, 1, &numConfigs ) )
	{
		printf( "GLES EGL Error: eglChooseConfig failed\n" );
		return -1;
	}

	context = eglCreateContext( display, config, NULL, NULL );
	if( context==0 )
	{
		printf( "GLES EGL Error: eglCreateContext failed\n" );
		return -1;
	}

#ifdef FAKE_WINDOW
	// broken Caanoo libs won't accept NULL window
	window = (NativeWindowType)1;
#endif
	surface = eglCreateWindowSurface( display, config, window, NULL );
	if (!TestEGLError("eglCreateWindowSurface"))
		return -1;

	eglMakeCurrent( display, surface, surface, context );
	if (!TestEGLError("eglMakeCurrent"))
		return -1;

	printf("GLES init ok\n");
	return 0;
}
Exemplo n.º 25
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
									);

			const char *wmDeleteWindowName = "WM_DELETE_WINDOW";
			Atom wmDeleteWindow;
			XInternAtoms(m_display, (char **)&wmDeleteWindowName, 1, False, &wmDeleteWindow);
			XSetWMProtocols(m_display, m_window, &wmDeleteWindow, 1);

			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 ClientMessage:
							if((Atom)event.xclient.data.l[0] == wmDeleteWindow)
							{
								m_eventQueue.postExitEvent();
							}
							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
										, 0
										, mb
										, event.type == ButtonPress
										);
								}
							}
							break;

						case MotionNotify:
							{
								const XMotionEvent& xmotion = event.xmotion;
								m_eventQueue.postMouseEvent(xmotion.x
										, xmotion.y
										, 0
										);
							}
							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;
		}
Exemplo n.º 26
0
      bool LinuxWindowImpl::RunThread() {
        Thread::RunThread();

        // Lock our use of the display connection..
        XLockDisplay(GetDisplay());

        int screenId = DefaultScreen(GetDisplay());

        // Make sure we have glx extensions loaded.
        gladLoadGLX(GetDisplay(), screenId);

        // Make sure we've got a good version of GLX
        int majorGLX, minorGLX = 0;
        glXQueryVersion(GetDisplay(), &majorGLX, &minorGLX);
        if (majorGLX <= 1 && minorGLX < 3) {
          LOG(Log::CRITICAL) << "GLX 1.3 or greater is required.\n";
          return false;
        }
        else {
          LOG(Log::DEFAULT) << "GLX version: " << majorGLX << "." << minorGLX << '\n';
        }

        // Pick a visual info based on the context display settings.
        ::XVisualInfo* vi = GetVisualInfoFromSettings(GetDisplay(), screenId, settings);
        if (!vi) {
          LOG(Log::CRITICAL) << "Couldn't find an XVisualInfo that matches Context Settings!";
          return false;
        }

        // Open the actual window.
        XSetWindowAttributes windowAttribs;
        windowAttribs.border_pixel = BlackPixel(GetDisplay(), screenId);
        windowAttribs.background_pixel = WhitePixel(GetDisplay(), screenId);
        windowAttribs.override_redirect = True;
        windowAttribs.colormap = XCreateColormap(GetDisplay(), RootWindow(GetDisplay(), screenId), vi->visual, AllocNone);
        windowAttribs.event_mask = ExposureMask | FocusChangeMask;
        window = XCreateWindow(GetDisplay(),
                               RootWindow(GetDisplay(), screenId),
                               0, 0,
                               width, height,
                               0,
                               vi->depth,
                               InputOutput,
                               vi->visual,
                               CWBackPixel | CWColormap | CWBorderPixel | CWEventMask,
                               &windowAttribs);

        XClearWindow(GetDisplay(), window);
        XMapRaised(GetDisplay(), window);

        // Finished with the display
        XUnlockDisplay(GetDisplay());

        Wait();

        XLockDisplay(GetDisplay());

        // Have to do this ridiculousness just to capture when the window is closed...
        Atom wmDeleteMessage = XInternAtom(GetDisplay(), "WM_DELETE_WINDOW", False);
        XSetWMProtocols(GetDisplay(), window, &wmDeleteMessage, 1);

        XUnlockDisplay(GetDisplay());

        // Loop through the events dealing with them.
        running = true;
        while (running) {
          xcb_generic_event_t* event = xcb_wait_for_event(GetXCBConnection());
          switch(event->response_type & ~0x80) {
            case XCB_EXPOSE:
              break;

            case XCB_CLIENT_MESSAGE: {
              xcb_client_message_event_t* clientMessage = (xcb_client_message_event_t*)event;
              if (clientMessage->data.data32[0] == wmDeleteMessage)
                running = false;
              break;
            }

            default:
              break;
          }

          free(event);
        }

        XFree(vi);

        XLockDisplay(GetDisplay());
        XFreeColormap(LinuxWindowImpl::GetDisplay(), windowAttribs.colormap);
        XDestroyWindow(LinuxWindowImpl::GetDisplay(), window);
        XUnlockDisplay(GetDisplay());

        return true;
      }
Exemplo n.º 27
0
PuglView*
puglCreate(PuglNativeWindow parent,
           const char*      title,
           int              width,
           int              height,
           bool             resizable,
           bool             addToDesktop)
{
	PuglView*      view = (PuglView*)calloc(1, sizeof(PuglView));
	PuglInternals* impl = (PuglInternals*)calloc(1, sizeof(PuglInternals));
	if (!view || !impl) {
		return NULL;
	}

	view->impl   = impl;
	view->width  = width;
	view->height = height;

	impl->display = XOpenDisplay(0);
	impl->screen  = DefaultScreen(impl->display);

	XVisualInfo* vi = glXChooseVisual(impl->display, impl->screen, attrListDbl);
	if (!vi) {
		vi = glXChooseVisual(impl->display, impl->screen, attrListSgl);
		impl->doubleBuffered = False;
		printf("singlebuffered rendering will be used, no doublebuffering available\n");
	} else {
		impl->doubleBuffered = True;
		printf("doublebuffered rendering available\n");
	}

	int glxMajor, glxMinor;
	glXQueryVersion(impl->display, &glxMajor, &glxMinor);
	printf("GLX-Version %d.%d\n", glxMajor, glxMinor);

	impl->ctx = glXCreateContext(impl->display, vi, 0, GL_TRUE);

	Window xParent = parent
		? (Window)parent
		: RootWindow(impl->display, impl->screen);

	Colormap cmap = XCreateColormap(
		impl->display, xParent, vi->visual, AllocNone);

	XSetWindowAttributes attr;
	memset(&attr, 0, sizeof(XSetWindowAttributes));
	attr.colormap     = cmap;
	attr.border_pixel = 0;

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

	impl->win = XCreateWindow(
		impl->display, xParent,
		0, 0, view->width, view->height, 0, vi->depth, InputOutput, vi->visual,
		CWBorderPixel | CWColormap | CWEventMask, &attr);

	XSizeHints sizeHints;
	memset(&sizeHints, 0, sizeof(sizeHints));
	if (!resizable) {
		sizeHints.flags      = PMinSize|PMaxSize;
		sizeHints.min_width  = width;
		sizeHints.min_height = height;
		sizeHints.max_width  = width;
		sizeHints.max_height = height;
		XSetNormalHints(impl->display, impl->win, &sizeHints);
	}

	if (title) {
		XStoreName(impl->display, impl->win, title);
	}

	if (!parent) {
		Atom wmDelete = XInternAtom(impl->display, "WM_DELETE_WINDOW", True);
		XSetWMProtocols(impl->display, impl->win, &wmDelete, 1);
	}

	if (addToDesktop) {
		XMapRaised(impl->display, impl->win);
	}

	if (glXIsDirect(impl->display, impl->ctx)) {
		printf("DRI enabled\n");
	} else {
		printf("No DRI available\n");
	}

	XFree(vi);

	return view;
}
Exemplo n.º 28
0
static void createTheWindow()
{
	XEvent event;
	int x,y, attr_mask;
	XSizeHints hints;
	XWMHints *startup_state;
	XTextProperty textprop;
	XSetWindowAttributes attr = {0,};
	static char *title = "FTB's little OpenGL example - ARGB extension by WXD";

	Xdisplay = XOpenDisplay(NULL);
	if (!Xdisplay) {
		fatalError("Couldn't connect to X server\n");
	}
	Xscreen = DefaultScreen(Xdisplay);
	Xroot = RootWindow(Xdisplay, Xscreen);

	fbconfigs = glXChooseFBConfig(Xdisplay, Xscreen, VisData, &numfbconfigs);
	fbconfig = 0;
	for(int i = 0; i<numfbconfigs; i++) {
		visual = (XVisualInfo*) glXGetVisualFromFBConfig(Xdisplay, fbconfigs[i]);
		if(!visual)
			continue;

		pict_format = XRenderFindVisualFormat(Xdisplay, visual->visual);
		if(!pict_format)
			continue;

		fbconfig = fbconfigs[i];
		if(pict_format->direct.alphaMask > 0) {
			break;
		}
	}

	if(!fbconfig) {
		fatalError("No matching FB config found");
	}

	describe_fbconfig(fbconfig);

	/* Create a colormap - only needed on some X clients, eg. IRIX */
	cmap = XCreateColormap(Xdisplay, Xroot, visual->visual, AllocNone);

	attr.colormap = cmap;
	attr.background_pixmap = None;
	attr.border_pixmap = None;
	attr.border_pixel = 0;
	attr.event_mask =
		StructureNotifyMask |
		EnterWindowMask |
		LeaveWindowMask |
		ExposureMask |
		ButtonPressMask |
		ButtonReleaseMask |
		OwnerGrabButtonMask |
		KeyPressMask |
		KeyReleaseMask;

	attr_mask = 
		CWBackPixmap|
		CWColormap|
		CWBorderPixel|
		CWEventMask;

	width = DisplayWidth(Xdisplay, DefaultScreen(Xdisplay))/2;
	height = DisplayHeight(Xdisplay, DefaultScreen(Xdisplay))/2;
	x=width/2, y=height/2;

	window_handle = XCreateWindow(	Xdisplay,
					Xroot,
					x, y, width, height,
					0,
					visual->depth,
					InputOutput,
					visual->visual,
					attr_mask, &attr);

	if( !window_handle ) {
		fatalError("Couldn't create the window\n");
	}

#if USE_GLX_CREATE_WINDOW
	int glXattr[] = { None };
	glX_window_handle = glXCreateWindow(Xdisplay, fbconfig, window_handle, glXattr);
	if( !glX_window_handle ) {
		fatalError("Couldn't create the GLX window\n");
	}
#else
	glX_window_handle = window_handle;
#endif

	textprop.value = (unsigned char*)title;
	textprop.encoding = XA_STRING;
	textprop.format = 8;
	textprop.nitems = strlen(title);

	hints.x = x;
	hints.y = y;
	hints.width = width;
	hints.height = height;
	hints.flags = USPosition|USSize;

	startup_state = XAllocWMHints();
	startup_state->initial_state = NormalState;
	startup_state->flags = StateHint;

	XSetWMProperties(Xdisplay, window_handle,&textprop, &textprop,
			NULL, 0,
			&hints,
			startup_state,
			NULL);

	XFree(startup_state);

	XMapWindow(Xdisplay, window_handle);
	XIfEvent(Xdisplay, &event, WaitForMapNotify, (char*)&window_handle);

	if ((del_atom = XInternAtom(Xdisplay, "WM_DELETE_WINDOW", 0)) != None) {
		XSetWMProtocols(Xdisplay, window_handle, &del_atom, 1);
	}
}
Exemplo n.º 29
0
int main () {
    Display   *display;
    Window     win;
    XEvent     report;
    XEvent     msg;
    int        x=10,y=10,h=100,w=100;

    display = XOpenDisplay(NULL);

    if (display == NULL) {
        fprintf(stderr, "couldn't connect to X server :0\n");
        return 0;
    }

    win = XCreateWindow(display, RootWindow(display, 0),
                        x, y, w, h, 0, CopyFromParent, CopyFromParent,
                        CopyFromParent, 0, NULL);

    XSetWindowBackground(display,win,WhitePixel(display,0));

    XSelectInput(display, win, (ExposureMask | StructureNotifyMask |
                                GravityNotify));

    XMapWindow(display, win);
    XFlush(display);

    sleep(1);
    XResizeWindow(display, win, w+5, h+5);
    XMoveWindow(display, win, x, y);

    while (1) {
        XNextEvent(display, &report);

        switch (report.type) {
        case MapNotify:
            printf("map notify\n");
            break;
        case Expose:
            printf("exposed\n");
            break;
        case GravityNotify:
            printf("gravity notify event 0x%x window 0x%x x %d y %d\n",
                   report.xgravity.event, report.xgravity.window,
                   report.xgravity.x, report.xgravity.y);
            break;
        case ConfigureNotify: {
            int se = report.xconfigure.send_event;
            int event = report.xconfigure.event;
            int window = report.xconfigure.window;
            int x = report.xconfigure.x;
            int y = report.xconfigure.y;
            int w = report.xconfigure.width;
            int h = report.xconfigure.height;
            int bw = report.xconfigure.border_width;
            int above = report.xconfigure.above;
            int or = report.xconfigure.override_redirect;
            printf("confignotify send %d ev 0x%x win 0x%x %i,%i-%ix%i bw %i\n"
                   "             above 0x%x ovrd %d\n",
                   se,event,window,x,y,w,h,bw,above,or);
            break;
        }
        }

    }

    return 1;
}
Exemplo n.º 30
0
	int32_t run(Filesystem* fs, ConfigSettings* cs)
	{
		// http://tronche.com/gui/x/xlib/display/XInitThreads.html
		Status xs = XInitThreads();
		CE_ASSERT(xs != 0, "XInitThreads: error");
		CE_UNUSED(xs);

		_x11_display = XOpenDisplay(NULL);
		CE_ASSERT(_x11_display != NULL, "XOpenDisplay: error");

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

		_x11_parent_window = (cs->parent_window == 0) ? RootWindow(_x11_display, screen) :
			(Window) cs->parent_window;

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

		_x11_window = XCreateWindow(_x11_display
			, _x11_parent_window
			, 0
			, 0
			, cs->window_width
			, cs->window_height
			, 0
			, depth
			, InputOutput
			, visual
			, CWBorderPixel | CWEventMask
			, &win_attribs);
		CE_ASSERT(_x11_window != None, "XCreateWindow: error");

		// Do we have detectable autorepeat?
		Bool detectable;
		_x11_detectable_autorepeat = (bool) XkbSetDetectableAutoRepeat(_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(_x11_display, screen);
		XAllocNamedColor(_x11_display, colormap, "black", &black, &dummy);
		bm_no = XCreateBitmapFromData(_x11_display, _x11_window, no_data, 8, 8);
		_x11_hidden_cursor = XCreatePixmapCursor(_x11_display, bm_no, bm_no, &black, &black, 0, 0);

		_wm_delete_message = XInternAtom(_x11_display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(_x11_display, _x11_window, &_wm_delete_message, 1);

		oswindow_set_window(_x11_display, _x11_window);
		bgfx::x11SetDisplayWindow(_x11_display, _x11_window);
		XMapRaised(_x11_display, _x11_window);

		// Save screen configuration
		_screen_config = XRRGetScreenInfo(_x11_display, RootWindow(_x11_display, screen));

		Rotation rr_old_rot;
		const SizeID rr_old_sizeid = XRRConfigCurrentConfiguration(_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
		Rotation rr_rot;
		const SizeID rr_sizeid = XRRConfigCurrentConfiguration(_screen_config, &rr_rot);

		if (rr_rot != rr_old_rot || rr_sizeid != rr_old_sizeid)
		{
			XRRSetScreenConfig(_x11_display
				, _screen_config
				, RootWindow(_x11_display, screen)
				, rr_old_sizeid
				, rr_old_rot
				, CurrentTime);
		}
		XRRFreeScreenConfigInfo(_screen_config);

		XDestroyWindow(_x11_display, _x11_window);
		XCloseDisplay(_x11_display);
		return EXIT_SUCCESS;
	}