void createGLContext() { printf("Creating OpenGL Context..."); display = XOpenDisplay(NULL); if (!display) { MSG("Fatal: Failed to open X display"); exit(1); } // Get a matching FB config static int visual_attribs[] = { GLX_X_RENDERABLE , True, GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR, GLX_RED_SIZE , 8, GLX_GREEN_SIZE , 8, GLX_BLUE_SIZE , 8, GLX_ALPHA_SIZE , 8, GLX_DEPTH_SIZE , 24, GLX_STENCIL_SIZE , 8, GLX_DOUBLEBUFFER , True, //GLX_SAMPLE_BUFFERS , 1, //GLX_SAMPLES , 4, None }; int glx_major, glx_minor; // FBConfigs were added in GLX version 1.3. if (!glXQueryVersion(display, &glx_major, &glx_minor) || ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) { MSG("Fatal: Invalid GLX version"); exit(1); } MSG("Getting matching framebuffer configs"); int fbcount; GLXFBConfig *fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount); if (!fbc) { MSG("Fatal: Failed to retrieve a framebuffer config"); exit(1); } MSG("Found %d matching FB configs.", fbcount); // Pick the FB config/visual with the most samples per pixel MSG("Getting XVisualInfos"); int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; int i; for (i = 0; i < fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[i]); if (vi) { int samp_buf, samples; glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLES , &samples); //Commented to reduce output //MSG("Matching fbconfig %d, visual ID 0x%2x:" // "SAMPLE_BUFFERS = %d, SAMPLES = %d", // i, vi -> visualid, samp_buf, samples); if (best_fbc < 0 || samp_buf && samples > best_num_samp) { best_fbc = i, best_num_samp = samples; } if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp) { worst_fbc = i, worst_num_samp = samples; } } XFree(vi); } GLXFBConfig bestFbc = fbc[best_fbc]; // Be sure to free the FBConfig list allocated by glXChooseFBConfig() XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc); MSG("Chosen visual ID = 0x%x", vi->visualid); MSG("Creating colormap"); XSetWindowAttributes swa; swa.colormap = cmap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone); swa.background_pixmap = None ; swa.border_pixel = 0; swa.event_mask = StructureNotifyMask; MSG("Creating window"); win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa); if (!win) { MSG("Fatal: Failed to create window."); exit(1); } // Done with the visual info data XFree(vi); XStoreName(display, win, "Window"); MSG("Mapping window"); XMapWindow(display, win); // Get the default screen's GLX extension list const char *glxExts = glXQueryExtensionsString(display, DefaultScreen(display)); // NOTE: It is not necessary to create or make current to a context before // calling glXGetProcAddressARB glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddressARB((const GLubyte *) "glXCreateContextAttribsARB"); // Install an X error handler so the application won't exit if GL <VERSION> // context allocation fails. // // Note this error handler is global. All display connections in all threads // of a process use the same error handler, so be sure to guard against other // threads issuing X commands while this code is running. ctxErrorOccurred = false; int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&ctxErrorHandler); // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. if (!isExtensionSupported(glxExts, "GLX_ARB_create_context") || !glXCreateContextAttribsARB) { MSG("glXCreateContextAttribsARB() not found" "... using old-style GLX context"); ctx = glXCreateNewContext(display, bestFbc, GLX_RGBA_TYPE, 0, True); } // If it does, try to get a GL <VERSION> context! // GL_<>_VERSION defined at top of file else { int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, GL_VER_MAJOR, GLX_CONTEXT_MINOR_VERSION_ARB, GL_VER_MINOR, GLX_CONTEXT_FLAGS_ARB , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; MSG("Creating context"); ctx = glXCreateContextAttribsARB(display, bestFbc, 0, True, context_attribs); // Sync to ensure any errors generated are processed. XSync(display, False); if (!ctxErrorOccurred && ctx) { MSG("Created GL %d.%d context", GL_VER_MAJOR, GL_VER_MINOR); } else { MSG("Fatal: Failed to create GL %d.%d context", GL_VER_MAJOR, GL_VER_MINOR); // Remove this exit to fall back to 2.1 context. exit(1); // Couldn't create GL <VERSION> context. Fall back to old-style 2.x context. // When a context version below <VERSION> is requested, implementations will // return the newest context version compatible with OpenGL versions less // than version <VERSION>. // GLX_CONTEXT_MAJOR_VERSION_ARB = 1 context_attribs[1] = 1; // GLX_CONTEXT_MINOR_VERSION_ARB = 0 context_attribs[3] = 0; ctxErrorOccurred = false; ctx = glXCreateContextAttribsARB(display, bestFbc, 0, True, context_attribs); } } // Sync to ensure any errors generated are processed. XSync(display, False); // Restore the original error handler XSetErrorHandler(oldHandler); if (ctxErrorOccurred || !ctx) { MSG("Fatal: Failed to create an OpenGL context"); exit(1); } // Verifying that context is a direct context if (! glXIsDirect(display, ctx)) { MSG("Indirect GLX rendering context obtained"); } else { MSG("Direct GLX rendering context obtained"); } MSG("Making context current"); glXMakeCurrent(display, win, ctx); MSG("Getting OpenGL Version information..."); MSG("GL Version = %s", glGetString(GL_VERSION)); MSG("GL Vendor = %s", glGetString(GL_VENDOR)); MSG("GL Renderer = %s", glGetString(GL_RENDERER)); MSG("GL Shader = %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); }
//========================================= // XF86ConfigFile: call XF86 loader... //----------------------------------------- void XF86ConfigFile::CallXF86Loader (str file) { int dpy = GetDisplay(); str scr ; sprintf(scr,":%d",dpy); str log ; sprintf(log,"/var/log/XFree86.%d.log",dpy); str lock ; sprintf(lock,"/tmp/.X%d-lock",dpy); MsgDetect *parse = NULL; Display *disp = NULL; int spid = 0; int count = 0; int vmd = 0; unlink(log); string proc = qx( XFree86,STDOUT,5,"%s %s %s %s %s",XW_LOG,BLANK,CONFIG,file,scr ); disp = XOpenDisplay (scr); if (disp) { vmd = DisplayPlanes (disp, DefaultScreen(disp)); XCloseDisplay (disp); } spid = atoi(proc.c_str()); kill(spid,15); while(1) { ifstream handle(lock); if (! handle) { break; } handle.close(); sleep(1); count++; if (count >= 3) { unlink(lock); kill(spid,9); break; } } sleep(2); parse = PLogGetData(log); unlink(log); if (parse != NULL) { for (int i=0;i<parse[0].cards;i++) { ParseData plog; plog.id = parse[i].id; plog.clock = parse[i].clkstr; plog.ddc = parse[i].ddc; plog.dtype = parse[i].displaytype; plog.primary = parse[i].primary; plog.chipset = parse[i].chipset; plog.hsmax = parse[i].hsync_max; plog.vsmax = parse[i].vsync_max; plog.dacspeed = parse[i].dacspeed; plog.videoram = parse[i].memory; plog.modecount = parse[i].vesacount; plog.dpix = parse[i].dpix; plog.dpiy = parse[i].dpiy; plog.bus = bus[i]; plog.slot = slot[i]; plog.func = func[i]; plog.vmdepth = vmd; for (int n=0;n<parse[i].vesacount;n++) { XMode mode; mode.x = parse[i].vmodes[n].x; mode.y = parse[i].vmodes[n].y; mode.hsync = parse[i].vmodes[n].hsync; mode.vsync = parse[i].vmodes[n].vsync; plog.modes[n] = mode; } GetBusFormat( parse[i].primary, &plog.pbus,&plog.pslot,&plog.pfunc ); if ((plog.pbus == 0) && (plog.pslot == 0) && (plog.pfunc == 0)) { plog.pbus = bus[0]; plog.pslot = slot[0]; plog.pfunc = func[0]; } Push(plog); } } }
int main (int argc, char* argv[]) { /* Determine number of iterations. */ if (2 != argc) { printf("usage: %s <num-iterations>\n", argv[0]); exit(1); } int numIterations = atoi(argv[1]); int returnCode = 0; Display* xDisplay = NULL; Window xWindow = 0; Picture xPictureWindow = 0; Pixmap xPixmapMain = 0; Picture xPictureMain = 0; Pixmap xPixmapOverlay = 0; Picture xPictureOverlay = 0; Pixmap xPixmapMask = 0; Picture xPictureMask = 0; GC gcMask = 0; /* Access X display. */ if (NULL == (xDisplay = XOpenDisplay(NULL))) { printf("XOpenDisplay(NULL) failed\n"); returnCode = 1; goto error; } /* Access info about the screen. */ Screen* xScreen = XDefaultScreenOfDisplay(xDisplay); GC gc = XDefaultGCOfScreen(xScreen); Colormap xColormap = XDefaultColormapOfScreen(xScreen); /* Create main X window */ xWindow = XCreateSimpleWindow( xDisplay, RootWindow(xDisplay, 0), 0, 0, IMAGE_WIDTH*2, IMAGE_HEIGHT*2, 0, BlackPixel(xDisplay, 0), BlackPixel(xDisplay, 0)); if (0 == xWindow) { printf("XCreateSimpleWindow failed\n"); returnCode = 1; goto error; } XMapWindow(xDisplay, xWindow); XSync(xDisplay, False); /* Get the attributes associated with the main window. */ XWindowAttributes xWindowAttr; if (!XGetWindowAttributes(xDisplay, xWindow, &xWindowAttr)) { printf("XGetWindowAttributes failed\n"); returnCode = 1; goto error; } /* Find the X render picture format associated with the visual */ /* for the main window */ XRenderPictFormat* xRenderPictFormatWindow = XRenderFindVisualFormat(xDisplay, xWindowAttr.visual); if (NULL == xRenderPictFormatWindow) { printf("XRenderFindVisualFormat failed\n"); returnCode = 1; goto error; } /* Find the X render picture format associated with 8 bit alpha. */ XRenderPictFormat xRenderPictFormatTemplate; xRenderPictFormatTemplate.depth = 8; xRenderPictFormatTemplate.type = PictTypeDirect; xRenderPictFormatTemplate.direct.alphaMask = 0x0FF; unsigned long xRenderPictFormatTemplateMask = PictFormatDepth | PictFormatType | PictFormatAlphaMask; XRenderPictFormat* xRenderPictFormatMask = XRenderFindFormat( xDisplay, xRenderPictFormatTemplateMask, &xRenderPictFormatTemplate, 0); if (NULL == xRenderPictFormatMask) { printf("XRenderFindFormat failed\n"); returnCode = 1; goto error; } /* Create X render picture associated with the screen. */ /* Having the same visual format as the window. */ xPictureWindow = XRenderCreatePicture( xDisplay, xWindow, xRenderPictFormatWindow, 0, NULL); if (0 == xPictureWindow) { printf("XRenderCreatePicture (window) failed\n"); returnCode = 1; goto error; } /* Create backing pixmap for the main window. */ xPixmapMain = XCreatePixmap( xDisplay, xWindow, xWindowAttr.width, xWindowAttr.height, xWindowAttr.depth); if (0 == xPixmapMain) { printf("XCreatePixmap (main) failed\n"); returnCode = 1; goto error; } /* Create X render picture associated with the backing pixmap. */ /* Having the same visual format as the window. */ xPictureMain = XRenderCreatePicture( xDisplay, xPixmapMain, xRenderPictFormatWindow, 0, NULL); if (0 == xPictureMain) { printf("XRenderCreatePicture (main) failed\n"); returnCode = 1; goto error; } /* Draw concentric rectangles of different gray. */ unsigned i; for (i = 0; i < 256; ++i) { float fGray = i / 255.0; /* Find the color gray. */ XcmsColor xColorGray; xColorGray.spec.RGBi.red = fGray; xColorGray.spec.RGBi.green = fGray; xColorGray.spec.RGBi.blue = fGray; xColorGray.format = XcmsRGBiFormat; if (0 == XcmsAllocColor( xDisplay, xColormap, &xColorGray, XcmsRGBFormat)) { printf("XcmsAllocColor failed\n"); returnCode = 1; goto error; } /* Change the drawing color for the main window. */ XSetForeground(xDisplay, gc, xColorGray.pixel); XDrawRectangle( xDisplay, xPixmapMain, gc, i, i, (IMAGE_WIDTH - i) * 2 - 1, (IMAGE_HEIGHT - i) * 2 - 1); } XRenderComposite( xDisplay, PictOpSrc, xPictureMain, /* src */ 0, /* mask */ xPictureWindow, /* dst */ 0, 0, /* src (x,y) */ 0, 0, /* mask (x,y) */ 0, 0, /* dst (x,y) */ xWindowAttr.width, xWindowAttr.height); XSync(xDisplay, False); /* Create pixmap for the overlay content. */ xPixmapOverlay = XCreatePixmap( xDisplay, xWindow, IMAGE_WIDTH, IMAGE_HEIGHT, xWindowAttr.depth); if (0 == xPixmapOverlay) { printf("XCreatePixmap (overlay) failed\n"); returnCode = 1; goto error; } /* Create X render picture assocaited with the overlay pixmap. */ /* Having the same visual format as the window. */ xPictureOverlay = XRenderCreatePicture( xDisplay, xPixmapOverlay, xRenderPictFormatWindow, 0, NULL); if (0 == xPictureOverlay) { printf("XRenderCreatePicture (overlay) failed\n"); returnCode = 1; goto error; } /* Fill the overlay with black to be used for overlay color. */ XSetForeground(xDisplay, gc, XBlackPixelOfScreen(xScreen)); XFillRectangle( xDisplay, xPixmapOverlay, gc, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); /* Create pixmap for the mask content. */ xPixmapMask = XCreatePixmap( xDisplay, xWindow, IMAGE_WIDTH, IMAGE_HEIGHT, 8); if (0 == xPixmapMask) { printf("XCreatePixmap (mask) failed\n"); returnCode = 1; goto error; } /* Create X render picture assocaited with the mask pixmap. */ xPictureMask = XRenderCreatePicture( xDisplay, xPixmapMask, xRenderPictFormatMask, 0, NULL); if (0 == xPictureMask) { printf("XRenderCreatePicture (mask) failed\n"); returnCode = 1; goto error; } /* Create a GC to go with mask */ gcMask = XCreateGC(xDisplay, xPixmapMask, 0, NULL); XSetForeground(xDisplay, gcMask, 0x00000000); XFillRectangle( xDisplay, xPixmapMask, gcMask, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); XSetForeground(xDisplay, gcMask, 0x40404040); XDrawRectangle( xDisplay, xPixmapMask, gcMask, 0, 0, IMAGE_WIDTH-1, IMAGE_HEIGHT-1); XFillArc( xDisplay, xPixmapMask, gcMask, 100, 100, 100, 100, 0, /* start angle-degrees * 64 */ 360 * 64); /* extent angle-degrees * 64 */ Bool bIncX = True; Bool bIncY = True; Bool bNextRow = False; int x = 0; int y = 0; struct timeval timeStart; gettimeofday(&timeStart, NULL); int iter; for (iter = 0; iter < numIterations; ++iter) { XRenderComposite( xDisplay, PictOpSrc, xPictureMain, /* src */ 0, /* mask */ xPictureWindow, /* dst */ x, y, /* src (x,y) */ 0, 0, /* mask (x,y) */ x, /* dst x */ y, /* dst y */ IMAGE_WIDTH, IMAGE_HEIGHT); if (bNextRow) { if (bIncY) { if ((y += 10) >= IMAGE_HEIGHT) { y = IMAGE_HEIGHT - 1; bIncY = False; } } else { if ((y -= 10) < 0) { y = 0; bIncY = True; } } bNextRow = False; } else { if (bIncX) { if (++x >= IMAGE_WIDTH) { x = IMAGE_WIDTH - 1; bIncX = False; bNextRow = True; } } else { if (--x < 0) { x = 0; bIncX = True; bNextRow = True; } } } XRenderComposite( xDisplay, PictOpOver, xPictureOverlay,/* src */ xPictureMask, /* mask */ xPictureWindow, /* dst */ 0, 0, /* src (x,y) */ 0, 0, /* mask (x,y) */ x, /* dst x */ y, /* dst y */ IMAGE_WIDTH, IMAGE_HEIGHT); } XSync(xDisplay, False); struct timeval timeEnd; gettimeofday(&timeEnd, NULL); double elapsedSec = getElapsedMicroseconds(&timeStart, &timeEnd) / 1000000L; double fps = numIterations / elapsedSec; printf("average update rate = %.1lf FPS\n", fps); error: if (0 != gcMask) { XFreeGC(xDisplay, gcMask); gcMask = 0; } if (0 != xPictureMask) { XRenderFreePicture(xDisplay, xPictureMask); xPictureMask = 0; } if (0 != xPixmapMask) { XFreePixmap(xDisplay, xPixmapMask); xPixmapMask = 0; } if (0 != xPictureOverlay) { XRenderFreePicture(xDisplay, xPictureOverlay); xPictureOverlay = 0; } if (0 != xPixmapOverlay) { XFreePixmap(xDisplay, xPixmapOverlay); xPixmapOverlay = 0; } if (0 != xPictureMain) { XRenderFreePicture(xDisplay, xPictureMain); xPictureMain = 0; } if (0 != xPixmapMain) { XFreePixmap(xDisplay, xPixmapMain); xPixmapMain = 0; } if (0 != xPictureWindow) { XRenderFreePicture(xDisplay, xPictureWindow); xPictureWindow = 0; } if (0 != xWindow) { XDestroyWindow(xDisplay, xWindow); xWindow = 0; } if (NULL != xDisplay) { XCloseDisplay(xDisplay); xDisplay = NULL; } return returnCode; }
int main(void) { Display *dpy; int i, j, fd; unsigned int attachments[] = { DRI2BufferBackLeft, DRI2BufferFrontLeft, }; XRRScreenResources *res; dpy = XOpenDisplay(NULL); if (dpy == NULL) return 77; if (!XRRQueryVersion(dpy, &i, &j)) return 77; fd = dri2_open(dpy); if (fd < 0) return 1; res = _XRRGetScreenResourcesCurrent(dpy, DefaultRootWindow(dpy)); if (res == NULL) return 1; printf("noutput=%d, ncrtc=%d\n", res->noutput, res->ncrtc); for (i = 0; i < res->ncrtc; i++) XRRSetCrtcConfig(dpy, res, res->crtcs[i], CurrentTime, 0, 0, None, RR_Rotate_0, NULL, 0); XSync(dpy, True); for (i = 0; i < res->noutput; i++) { XRROutputInfo *output; XRRModeInfo *mode; output = XRRGetOutputInfo(dpy, res, res->outputs[i]); if (output == NULL) continue; mode = NULL; if (res->nmode) mode = lookup_mode(res, output->modes[0]); for (j = 0; mode && j < output->ncrtc; j++) { printf("[%d, %d] -- OUTPUT:%ld, CRTC:%ld\n", i, j, (long)res->outputs[i], (long)output->crtcs[j]); XRRSetCrtcConfig(dpy, res, output->crtcs[j], CurrentTime, 0, 0, output->modes[0], RR_Rotate_0, &res->outputs[i], 1); XSync(dpy, True); run(dpy, mode->width, mode->height, attachments, 1, "fullscreen"); run(dpy, mode->width, mode->height, attachments, 2, "fullscreen (with front)"); run(dpy, mode->width/2, mode->height/2, attachments, 1, "windowed"); run(dpy, mode->width/2, mode->height/2, attachments, 2, "windowed (with front)"); XRRSetCrtcConfig(dpy, res, output->crtcs[j], CurrentTime, 0, 0, None, RR_Rotate_0, NULL, 0); XSync(dpy, True); } XRRFreeOutputInfo(output); } return 0; }
/// // WinCreate() // // This function initialized the native X11 display and window for EGL // EGLBoolean WinCreate(ESContext *esContext, const char *title) { Window root; XSetWindowAttributes swa; XSetWindowAttributes xattr; Atom wm_state; XWMHints hints; XEvent xev; Window win; /* * 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, esContext->width, esContext->height, 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, title); // 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 ); esContext->hWnd = (EGLNativeWindowType) win; return EGL_TRUE; }
int main(int argc, char** argv) { int attrib[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_DOUBLEBUFFER, True, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, None }; PlatformContext context; context.MainDisplay = XOpenDisplay(NULL); int screenIndex = DefaultScreen(context.MainDisplay); Window root = RootWindow(context.MainDisplay, screenIndex); int fbcount; PFNGLXCHOOSEFBCONFIGPROC glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress((GLubyte*)"glXChooseFBConfig"); GLXFBConfig *fbc = glXChooseFBConfig(context.MainDisplay, screenIndex, attrib, &fbcount); if (!fbc) pezFatal("Failed to retrieve a framebuffer config\n"); PFNGLXGETVISUALFROMFBCONFIGPROC glXGetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) glXGetProcAddress((GLubyte*)"glXGetVisualFromFBConfig"); if (!glXGetVisualFromFBConfig) pezFatal("Failed to get a GLX function pointer\n"); PFNGLXGETFBCONFIGATTRIBPROC glXGetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) glXGetProcAddress((GLubyte*)"glXGetFBConfigAttrib"); if (!glXGetFBConfigAttrib) pezFatal("Failed to get a GLX function pointer\n"); if (PezGetConfig().Multisampling) { int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; for ( int i = 0; i < fbcount; i++ ) { XVisualInfo *vi = glXGetVisualFromFBConfig( context.MainDisplay, fbc[i] ); if (!vi) { continue; } int samp_buf, samples; glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf ); glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLES , &samples ); //printf( " Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d," // " SAMPLES = %d\n", // i, (unsigned int) vi->visualid, samp_buf, samples ); if ( best_fbc < 0 || (samp_buf && samples > best_num_samp) ) best_fbc = i, best_num_samp = samples; if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp ) worst_fbc = i, worst_num_samp = samples; XFree( vi ); } fbc[0] = fbc[ best_fbc ]; } XVisualInfo *visinfo = glXGetVisualFromFBConfig(context.MainDisplay, fbc[0]); if (!visinfo) pezFatal("Error: couldn't create OpenGL window with this pixel format.\n"); XSetWindowAttributes attr; attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap(context.MainDisplay, root, visinfo->visual, AllocNone); attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask; context.MainWindow = XCreateWindow( context.MainDisplay, root, 0, 0, PezGetConfig().Width, PezGetConfig().Height, 0, visinfo->depth, InputOutput, visinfo->visual, CWBackPixel | /*CWBorderPixel |*/ CWColormap | CWEventMask, &attr ); int borderless = 1; if (borderless) { Atom mwmHintsProperty = XInternAtom(context.MainDisplay, "_MOTIF_WM_HINTS", 0); MwmHints hints = {0}; hints.flags = MWM_HINTS_DECORATIONS; hints.decorations = 0; XChangeProperty(context.MainDisplay, context.MainWindow, mwmHintsProperty, mwmHintsProperty, 32, PropModeReplace, (unsigned char *)&hints, PROP_MWM_HINTS_ELEMENTS); } XMapWindow(context.MainDisplay, context.MainWindow); int centerWindow = 1; if (centerWindow) { Screen* pScreen = XScreenOfDisplay(context.MainDisplay, screenIndex); int left = XWidthOfScreen(pScreen)/2 - PezGetConfig().Width/2; int top = XHeightOfScreen(pScreen)/2 - PezGetConfig().Height/2; XMoveWindow(context.MainDisplay, context.MainWindow, left, top); } GLXContext glcontext = 0; if (PEZ_FORWARD_COMPATIBLE_GL) { PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribs = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((GLubyte*)"glXCreateContextAttribsARB"); if (!glXCreateContextAttribs) { pezFatal("Your platform does not support OpenGL 4.0.\n" "Try changing PEZ_FORWARD_COMPATIBLE_GL to 0.\n"); } int attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 4, GLX_CONTEXT_MINOR_VERSION_ARB, 0, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; glcontext = glXCreateContextAttribs(context.MainDisplay, fbc[0], NULL, True, attribs); } else { glcontext = glXCreateContext(context.MainDisplay, visinfo, NULL, True); } glXMakeCurrent(context.MainDisplay, context.MainWindow, glcontext); PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress((GLubyte*)"glXSwapIntervalSGI"); if (glXSwapIntervalSGI) { glXSwapIntervalSGI(PezGetConfig().VerticalSync ? 1 : 0); } /* GLenum err = glewInit(); if (GLEW_OK != err) pezFatal("GLEW Error: %s\n", glewGetErrorString(err)); // Work around some GLEW issues: #define glewGetProcAddress(name) (*glXGetProcAddressARB)(name) glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)glewGetProcAddress((const GLubyte*)"glPatchParameteri"); glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)glewGetProcAddress((const GLubyte*)"glBindVertexArray"); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)glewGetProcAddress((const GLubyte*)"glDeleteVertexArrays"); glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)glewGetProcAddress((const GLubyte*)"glGenVertexArrays"); glIsVertexArray = (PFNGLISVERTEXARRAYPROC)glewGetProcAddress((const GLubyte*)"glIsVertexArray"); */ // Reset OpenGL error state: glGetError(); // Lop off the trailing .c bstring name = bfromcstr(PezGetConfig().Title); bstring shaderPrefix = bmidstr(name, 0, blength(name) - 1); pezSwInit(bdata(shaderPrefix)); bdestroy(shaderPrefix); // Set up the Shader Wrangler pezSwAddPath("./", ".glsl"); pezSwAddPath("../", ".glsl"); char qualifiedPath[128]; strcpy(qualifiedPath, pezResourcePath()); strcat(qualifiedPath, "/"); pezSwAddPath(qualifiedPath, ".glsl"); pezSwAddDirective("*", "#version 420"); // Perform user-specified intialization pezPrintString("OpenGL Version: %s\n", glGetString(GL_VERSION)); PezInitialize(); bstring windowTitle = bmidstr(name, 5, blength(name) - 7); XStoreName(context.MainDisplay, context.MainWindow, bdata(windowTitle)); bdestroy(windowTitle); bdestroy(name); // ------------------- // Start the Game Loop // ------------------- unsigned int previousTime = GetMicroseconds(); int done = 0; while (!done) { if (glGetError() != GL_NO_ERROR) pezFatal("OpenGL error.\n"); if (XPending(context.MainDisplay)) { XEvent event; XNextEvent(context.MainDisplay, &event); switch (event.type) { case Expose: //redraw(display, event.xany.window); break; case ConfigureNotify: //resize(event.xconfigure.width, event.xconfigure.height); break; #ifdef PEZ_MOUSE_HANDLER case ButtonPress: PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_DOWN); break; case ButtonRelease: PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_UP); break; case MotionNotify: PezHandleMouse(event.xmotion.x, event.xmotion.y, PEZ_MOVE); break; #endif case KeyRelease: case KeyPress: { XComposeStatus composeStatus; char asciiCode[32]; KeySym keySym; int len; len = XLookupString(&event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus); switch (asciiCode[0]) { case 'x': case 'X': case 'q': case 'Q': case 0x1b: done = 1; break; } } } } unsigned int currentTime = GetMicroseconds(); unsigned int deltaTime = currentTime - previousTime; previousTime = currentTime; PezUpdate((float) deltaTime / 1000000.0f); PezRender(0); glXSwapBuffers(context.MainDisplay, context.MainWindow); } pezSwShutdown(); return 0; }
bool CWindowUnix::Init(int width, int height, int bpp, axelynx::WindowMode wm, int samples) { XVisualInfo *vi; Colormap cmap; XSetWindowAttributes swa; int dummy; width_ = width; height_ = height; /*** (1) open a connection to the X server ***/ dpy_ = XOpenDisplay(NULL); if (dpy_ == NULL) fatalError("could not open display"); int nelements; GLXFBConfig *fbc = glXChooseFBConfig(dpy_, DefaultScreen(dpy_), 0, &nelements); /*** (2) make sure OpenGL's GLX extension supported ***/ if(!glXQueryExtension(dpy_, &dummy, &dummy)) fatalError("X server has no OpenGL GLX extension"); /*** (3) find an appropriate visual ***/ /* find an OpenGL-capable RGB visual with depth buffer */ vi = glXChooseVisual(dpy_, DefaultScreen(dpy_), dblBuf); if (vi == NULL) { vi = glXChooseVisual(dpy_, DefaultScreen(dpy_), snglBuf); if (vi == NULL) fatalError("no RGB visual with depth buffer"); doubleBuffer_ = GL_FALSE; } //if(vi->class != TrueColor) // fatalError("TrueColor visual required for this program"); /*** (4) create an OpenGL rendering context ***/ /* create an OpenGL rendering context */ // cx_ = glXCreateContext(dpy_, vi, /* no shared dlists */ None, /* direct rendering if possible */ GL_TRUE); /*** (5) create an X window with the selected visual ***/ /* create an X colormap since probably not using default visual */ cmap = XCreateColormap(dpy_, RootWindow(dpy_, vi->screen), vi->visual, AllocNone); swa.colormap = cmap; swa.border_pixel = 0; swa.event_mask = KeyPressMask | ExposureMask | ButtonPressMask | StructureNotifyMask | FocusChangeMask; win_ = XCreateWindow(dpy_, RootWindow(dpy_, vi->screen), 0, 0, width_, height_, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa); XSetStandardProperties(dpy_, win_, "main", "main", None, 0, 0, NULL); PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); int attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 3, 0}; cx_ = glXCreateContextAttribsARB(dpy_, *fbc, 0, true, attribs); //glXMakeCurrent (dpy, win, ctx); /*** (6) bind the rendering context to the window ***/ glXMakeCurrent(dpy_, win_, cx_); /*** (7) request the X window to be displayed on the screen ***/ XMapWindow(dpy_, win_); /*** (8) configure the OpenGL context for rendering ***/ glEnable(GL_DEPTH_TEST); /* enable depth buffering */ glDepthFunc(GL_LESS); /* pedantic, GL_LESS is the default */ glClearDepth(1.0); /* pedantic, 1.0 is the default */ /* frame buffer clears should be to black */ glClearColor(0.0, 0.0, 0.0, 0.0); /* set up projection transform */ /* establish initial viewport */ /* pedantic, full window size is default viewport */ isFullscreen_ = false; Resize(width,height,wm); fprintf(stderr, "succers: %d\n", width); return true; }
void wsXInit( void* mDisplay ) { int eventbase; int errorbase; if(mDisplay){ wsDisplay=mDisplay; } else { char * DisplayName = ":0.0"; if ( getenv( "DISPLAY" ) ) DisplayName=getenv( "DISPLAY" ); wsDisplay=XOpenDisplay( DisplayName ); if ( !wsDisplay ) { mp_msg( MSGT_GPLAYER,MSGL_FATAL,MSGTR_WS_CouldNotOpenDisplay ); exit( 0 ); } } /* enable DND atoms */ wsXDNDInitialize(); { /* on remote display XShm will be disabled - LGB */ char *dispname=DisplayString(wsDisplay); int localdisp=1; if (dispname&&*dispname!=':') { localdisp=0; wsUseXShm=0; } mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"[ws] display name: %s => %s display.\n",dispname,localdisp?"local":"REMOTE"); if (!localdisp) mp_msg( MSGT_GPLAYER,MSGL_V,MSGTR_WS_RemoteDisplay ); } if ( !XShmQueryExtension( wsDisplay ) ) { mp_msg( MSGT_GPLAYER,MSGL_ERR,MSGTR_WS_NoXshm ); wsUseXShm=0; } #ifdef HAVE_XSHAPE if ( !XShapeQueryExtension( wsDisplay,&eventbase,&errorbase ) ) { mp_msg( MSGT_GPLAYER,MSGL_ERR,MSGTR_WS_NoXshape ); wsUseXShape=0; } #else wsUseXShape=0; #endif XSynchronize( wsDisplay,True ); wsScreen=DefaultScreen( wsDisplay ); wsRootWin=RootWindow( wsDisplay,wsScreen ); #ifdef HAVE_XF86VM { int clock; XF86VidModeModeLine modeline; XF86VidModeGetModeLine( wsDisplay,wsScreen,&clock ,&modeline ); wsMaxX=modeline.hdisplay; wsMaxY=modeline.vdisplay; } #endif { wsOrgX = wsOrgY = 0; if ( !wsMaxX ) wsMaxX=DisplayWidth( wsDisplay,wsScreen ); if ( !wsMaxY ) wsMaxY=DisplayHeight( wsDisplay,wsScreen ); } vo_screenwidth = wsMaxX; vo_screenheight = wsMaxY; xinerama_x = wsOrgX; xinerama_y = wsOrgY; update_xinerama_info(); wsMaxX = vo_screenwidth; wsMaxY = vo_screenheight; wsOrgX = xinerama_x; wsOrgY = xinerama_y; wsGetDepthOnScreen(); #ifdef DEBUG { int minor,major,shp; mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] Screen depth: %d\n",wsDepthOnScreen ); mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] size: %dx%d\n",wsMaxX,wsMaxY ); #ifdef HAVE_XINERAMA mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] origin: +%d+%d\n",wsOrgX,wsOrgY ); #endif mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] red mask: 0x%x\n",wsRedMask ); mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] green mask: 0x%x\n",wsGreenMask ); mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] blue mask: 0x%x\n",wsBlueMask ); if ( wsUseXShm ) { XShmQueryVersion( wsDisplay,&major,&minor,&shp ); mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] XShm version is %d.%d\n",major,minor ); } #ifdef HAVE_XSHAPE if ( wsUseXShape ) { XShapeQueryVersion( wsDisplay,&major,&minor ); mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[ws] XShape version is %d.%d\n",major,minor ); } #endif } #endif wsOutMask=wsGetOutMask(); mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"[ws] Initialized converter: " ); sws_rgb2rgb_init(get_sws_cpuflags()); switch ( wsOutMask ) { case wsRGB32: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to rgb32\n" ); wsConvFunc=rgb32torgb32; break; case wsBGR32: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to bgr32\n" ); wsConvFunc=rgb32tobgr32; break; case wsRGB24: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to rgb24\n" ); wsConvFunc=rgb32to24; break; case wsBGR24: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to bgr24\n" ); wsConvFunc=rgb32tobgr24; break; case wsRGB16: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to rgb16\n" ); wsConvFunc=rgb32to16; break; case wsBGR16: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to bgr16\n" ); wsConvFunc=rgb32tobgr16; break; case wsRGB15: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to rgb15\n" ); wsConvFunc=rgb32to15; break; case wsBGR15: mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"rgb32 to bgr15\n" ); wsConvFunc=rgb32tobgr15; break; } XSetErrorHandler( wsErrorHandler ); }
static SDL_VideoDevice * X11_CreateDevice(int devindex) { SDL_VideoDevice *device; SDL_VideoData *data; const char *display = NULL; /* Use the DISPLAY environment variable */ if (!SDL_X11_LoadSymbols()) { return NULL; } /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (!device) { SDL_OutOfMemory(); return NULL; } data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); if (!data) { SDL_OutOfMemory(); SDL_free(device); return NULL; } device->driverdata = data; #if SDL_VIDEO_DRIVER_PANDORA device->gles_data = (struct SDL_PrivateGLESData *) SDL_calloc(1, sizeof(SDL_PrivateGLESData)); if (!device->gles_data) { SDL_OutOfMemory(); return NULL; } #endif /* FIXME: Do we need this? if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) || (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) { local_X11 = 1; } else { local_X11 = 0; } */ data->display = XOpenDisplay(display); #if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC) /* On Tru64 if linking without -lX11, it fails and you get following message. * Xlib: connection to ":0.0" refused by server * Xlib: XDM authorization key matches an existing client! * * It succeeds if retrying 1 second later * or if running xhost +localhost on shell. */ if (data->display == NULL) { SDL_Delay(1000); data->display = XOpenDisplay(display); } #endif if (data->display == NULL) { SDL_free(device); SDL_SetError("Couldn't open X11 display"); return NULL; } #ifdef X11_DEBUG XSynchronize(data->display, True); #endif /* Set the function pointers */ device->VideoInit = X11_VideoInit; device->VideoQuit = X11_VideoQuit; device->GetDisplayModes = X11_GetDisplayModes; device->SetDisplayMode = X11_SetDisplayMode; device->SetDisplayGammaRamp = X11_SetDisplayGammaRamp; device->GetDisplayGammaRamp = X11_GetDisplayGammaRamp; device->SuspendScreenSaver = X11_SuspendScreenSaver; device->PumpEvents = X11_PumpEvents; device->CreateWindow = X11_CreateWindow; device->CreateWindowFrom = X11_CreateWindowFrom; device->SetWindowTitle = X11_SetWindowTitle; device->SetWindowIcon = X11_SetWindowIcon; device->SetWindowPosition = X11_SetWindowPosition; device->SetWindowSize = X11_SetWindowSize; device->ShowWindow = X11_ShowWindow; device->HideWindow = X11_HideWindow; device->RaiseWindow = X11_RaiseWindow; device->MaximizeWindow = X11_MaximizeWindow; device->MinimizeWindow = X11_MinimizeWindow; device->RestoreWindow = X11_RestoreWindow; device->SetWindowGrab = X11_SetWindowGrab; device->DestroyWindow = X11_DestroyWindow; device->GetWindowWMInfo = X11_GetWindowWMInfo; #ifdef SDL_VIDEO_OPENGL_GLX device->GL_LoadLibrary = X11_GL_LoadLibrary; device->GL_GetProcAddress = X11_GL_GetProcAddress; device->GL_UnloadLibrary = X11_GL_UnloadLibrary; device->GL_CreateContext = X11_GL_CreateContext; device->GL_MakeCurrent = X11_GL_MakeCurrent; device->GL_SetSwapInterval = X11_GL_SetSwapInterval; device->GL_GetSwapInterval = X11_GL_GetSwapInterval; device->GL_SwapWindow = X11_GL_SwapWindow; device->GL_DeleteContext = X11_GL_DeleteContext; #endif #if SDL_VIDEO_DRIVER_PANDORA device->GL_LoadLibrary = X11_GLES_LoadLibrary; device->GL_GetProcAddress = X11_GLES_GetProcAddress; device->GL_UnloadLibrary = X11_GLES_UnloadLibrary; device->GL_CreateContext = X11_GLES_CreateContext; device->GL_MakeCurrent = X11_GLES_MakeCurrent; device->GL_SetSwapInterval = X11_GLES_SetSwapInterval; device->GL_GetSwapInterval = X11_GLES_GetSwapInterval; device->GL_SwapWindow = X11_GLES_SwapWindow; device->GL_DeleteContext = X11_GLES_DeleteContext; #endif device->SetClipboardText = X11_SetClipboardText; device->GetClipboardText = X11_GetClipboardText; device->HasClipboardText = X11_HasClipboardText; device->free = X11_DeleteDevice; return device; }
int main (int argc, char **argv) { XEvent event; XSizeHints xsh; XSetWindowAttributes xswa; XVisualInfo *vinfo; glitz_drawable_format_t templ; glitz_drawable_format_t *dformat; unsigned long mask = 0; unsigned int width, height, window_width, window_height; int i; program_name = argv[0]; for (i = 1; i < argc; i++) { if (!strcasecmp ("-image", argv[i])) output_type = IMAGE_TYPE; #ifdef CAIRO_HAS_XLIB_SURFACE else if (!strcasecmp ("-xrender", argv[i])) { output_type = XRENDER_TYPE; } #endif else if (!strcasecmp ("-glx", argv[i])) { output_type = GLX_TYPE; } else if (!strcasecmp ("-noaa", argv[i])) { aa = 0; } else if (!strcasecmp ("-swaa", argv[i])) { aa = 1; } else if (!strcasecmp ("-hwaa", argv[i])) { aa = 3; } else { test_type = get_test_type (argv[i]); } } if (!test_type) { usage(); exit(1); } if (output_type != GLX_TYPE && test_type >= OPENGL_TYPE) { printf ("Sorry, this test only works with OpenGL!\n"); usage(); exit(1); } window_width = width = WINDOW_WIDTH; window_height = height = WINDOW_HEIGHT; if (aa == 3) templ.samples = 4; else templ.samples = 1; templ.depth_size = 16; if (test_type == CUBE_TYPE) mask |= GLITZ_FORMAT_DEPTH_SIZE_MASK; mask |= GLITZ_FORMAT_SAMPLES_MASK; if ((dpy = XOpenDisplay (NULL)) == NULL) { fprintf(stderr, "%s: can't open display: %s\n", argv[0], XDisplayName (NULL)); exit(1); } if (output_type != GLX_TYPE) { xsh.flags = PSize; xsh.width = width; xsh.height = height; xsh.x = 0; xsh.y = 0; win = XCreateWindow (dpy, RootWindow (dpy, DefaultScreen (dpy)), xsh.x, xsh.y, xsh.width, xsh.height, 0, CopyFromParent, CopyFromParent, CopyFromParent, 0, &xswa); XSetStandardProperties (dpy, win, PACKAGE, PACKAGE, None, argv, argc, &xsh); XSetWMHints (dpy, win, &xwmh); XSelectInput (dpy, win, StructureNotifyMask); } else { xsh.flags = PSize; xsh.width = width; xsh.height = height; xsh.x = 0; xsh.y = 0; mask = 0; templ.doublebuffer = 1; mask |= GLITZ_FORMAT_DOUBLEBUFFER_MASK; dformat = glitz_glx_find_window_format (dpy, DefaultScreen (dpy), mask, &templ, 0); vinfo = glitz_glx_get_visual_info_from_format (dpy, DefaultScreen (dpy), dformat); xswa.colormap = XCreateColormap (dpy, RootWindow (dpy, DefaultScreen (dpy)), vinfo->visual, AllocNone); win = XCreateWindow (dpy, RootWindow (dpy, DefaultScreen (dpy)), xsh.x, xsh.y, xsh.width, xsh.height, 0, vinfo->depth, CopyFromParent, vinfo->visual, CWColormap, &xswa); XSetStandardProperties (dpy, win, PACKAGE, PACKAGE, None, argv, argc, &xsh); XSetWMHints (dpy, win, &xwmh); XSelectInput (dpy, win, StructureNotifyMask); } switch (output_type) { case XRENDER_TYPE: resize_pixmap (width, height); break; case IMAGE_TYPE: resize_image (width, height); break; case GLX_TYPE: drawable = glitz_glx_create_drawable_for_window (dpy, 0, dformat, win, width, height); if (!drawable) { printf ("failed to create glitz drawable\n"); exit (1); } break; } if (aa == 3 && dformat->samples < 2) { fprintf (stderr, "hardware multi-sampling not available\n"); exit (1); } if (drawable) { surface = resize_glitz_drawable (drawable, dformat, width, height); } cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); setup (test_type); XMapWindow (dpy, win); for (;;) { if (XPending (dpy)) { XNextEvent (dpy, &event); if (event.type == ConfigureNotify) { width = event.xconfigure.width; height = event.xconfigure.height; switch (output_type) { #ifdef CAIRO_HAS_XLIB_SURFACE case XRENDER_TYPE: resize_pixmap (width, height); cairo_destroy (cr); cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); break; #endif case IMAGE_TYPE: resize_image (width, height); cairo_destroy (cr); cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); break; case GLX_TYPE: cairo_surface_destroy (surface); surface = resize_glitz_drawable (drawable, dformat, width, height); cairo_destroy (cr); cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); break; } } } else { render (test_type, output_type == GLX_TYPE); switch (output_type) { #ifdef CAIRO_HAS_XLIB_SURFACE case XRENDER_TYPE: XSetWindowBackgroundPixmap (dpy, win, pixmap); XClearWindow (dpy, win); break; #endif case IMAGE_TYPE: { GC gc; XImage *xim; pixmap = XCreatePixmap (dpy, DefaultRootWindow (dpy), width, height, DefaultDepth (dpy, DefaultScreen (dpy))); xim = XCreateImage(dpy, DefaultVisual (dpy, DefaultScreen (dpy)), DefaultDepth(dpy, DefaultScreen (dpy)), ZPixmap, 0, (char *) image, width, height, 32, 0); gc = XCreateGC (dpy, pixmap, 0, NULL); XPutImage (dpy, pixmap, gc, xim, 0, 0, 0, 0, width, height); XFreeGC (dpy, gc); xim->data = NULL; XDestroyImage (xim); XSetWindowBackgroundPixmap (dpy, win, pixmap); XClearWindow (dpy, win); XFreePixmap (dpy, pixmap); } break; } XSync (dpy, 0); } } exit (1); }
int _glfwPlatformInit(void) { #if !defined(X_HAVE_UTF8_STRING) // HACK: If the current locale is C, apply the environment's locale // This is done because the C locale breaks wide character input if (strcmp(setlocale(LC_CTYPE, NULL), "C") == 0) setlocale(LC_CTYPE, ""); #endif XInitThreads(); _glfw.x11.display = XOpenDisplay(NULL); if (!_glfw.x11.display) { const char* display = getenv("DISPLAY"); if (display) { _glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to open display %s", display); } else { _glfwInputError(GLFW_PLATFORM_ERROR, "X11: The DISPLAY environment variable is missing"); } return GL_FALSE; } _glfw.x11.screen = DefaultScreen(_glfw.x11.display); _glfw.x11.root = RootWindow(_glfw.x11.display, _glfw.x11.screen); _glfw.x11.context = XUniqueContext(); if (!initExtensions()) return GL_FALSE; _glfw.x11.cursor = createNULLCursor(); if (XSupportsLocale()) { XSetLocaleModifiers(""); _glfw.x11.im = XOpenIM(_glfw.x11.display, 0, NULL, NULL); if (_glfw.x11.im) { if (!hasUsableInputMethodStyle()) { XCloseIM(_glfw.x11.im); _glfw.x11.im = NULL; } } } if (!_glfwInitContextAPI()) return GL_FALSE; if (!_glfwInitJoysticks()) return GL_FALSE; _glfwInitTimer(); return GL_TRUE; }
/* * Do all the X / GLX setup stuff. */ static int Setup(int width, int height) { #if defined(GLX_SGIX_fbconfig) && defined(GLX_SGIX_pbuffer) XVisualInfo *visInfo; GLXContext glCtx; /* Open the X display */ gDpy = XOpenDisplay(NULL); if (!gDpy) { printf("Error: couldn't open default X display.\n"); return 0; } /* Get default screen */ gScreen = DefaultScreen(gDpy); /* Test that pbuffers are available */ if (!QueryPbuffers(gDpy, gScreen)) { printf("Error: pbuffers not available on this screen\n"); XCloseDisplay(gDpy); return 0; } /* Create Pbuffer */ gPBuffer = MakePbuffer( gDpy, gScreen, width, height ); if (gPBuffer==None) { printf("Error: couldn't create pbuffer\n"); XCloseDisplay(gDpy); return 0; } /* Get corresponding XVisualInfo */ visInfo = glXGetVisualFromFBConfigSGIX(gDpy, gFBconfig); if (!visInfo) { printf("Error: can't get XVisualInfo from FBconfig\n"); XCloseDisplay(gDpy); return 0; } /* Create GLX context */ glCtx = glXCreateContext(gDpy, visInfo, NULL, True); if (!glCtx) { /* try indirect */ glCtx = glXCreateContext(gDpy, visInfo, NULL, False); if (!glCtx) { printf("Error: Couldn't create GLXContext\n"); XFree(visInfo); XCloseDisplay(gDpy); return 0; } else { printf("Warning: using indirect GLXContext\n"); } } /* Bind context to pbuffer */ if (!glXMakeCurrent(gDpy, gPBuffer, glCtx)) { printf("Error: glXMakeCurrent failed\n"); XFree(visInfo); XCloseDisplay(gDpy); return 0; } return 1; /* Success!! */ #else printf("Error: GLX_SGIX_fbconfig and/or GLX_SGIX_pbuffer extensions not" " available at compile-time.\n"); return 0; #endif }
/* **************************************************************** * Programa principal * **************************************************************** */ void main (int argc, const char *argv[]) { Display *dp; Window win; int screen; ulong fg, bg; GC gc; XEvent ev; Font font; KeySym key; char text[80]; int doneflag, len, opt, exitval; /* * Inicializa opções. */ exitval = 0; /* * Analisa as opções de execução. */ while ((opt = getopt (argc, argv, "G:f:MH")) != EOF) { switch (opt) { case 'M': exit (0); case 'H': help (0); break; case 'f': fontname = (char *)optarg; break; case 'G': get_geometry (optarg); break; default: putc ('\n', stderr); help (2); } /* end switch (opt) */ } /* while ((opt = getopt (...))) */ /* * Conecta-se ao servidor. */ if ((dp = XOpenDisplay (NULL)) == (Display *)NULL) msg ("$Não consegui conectar-me ao servidor"); screen = DefaultScreen (dp); bg = WhitePixel (dp, screen); fg = BlackPixel (dp, screen); win = XCreateSimpleWindow ( dp, DefaultRootWindow (dp), x, y, dx, dy, 2, fg, bg /* cores: frente e fundo */ ); gc = DefaultGC (dp, screen); if (fontname != NOSTR) { if (font = XLoadFont (dp, fontname)) XSetFont (dp, gc, font); } XSelectInput (dp, win, ButtonPressMask|KeyPressMask|ExposureMask); XMapRaised (dp, win); for (doneflag = 0; doneflag == 0; /* sem incremento */) { XNextEvent (dp, &ev); switch (ev.type) { case Expose: break; case ButtonPress: sprintf ( text, #if (0) /****************************************************/ "(%d, %d), (%d, %d)", ev.xbutton.x_root, ev.xbutton.y_root, #endif /****************************************************/ "(%d, %d)", ev.xbutton.x, ev.xbutton.y ); XDrawImageString ( dp, win, gc, ev.xbutton.x, ev.xbutton.y, text, strlen (text) ); break; case KeyPress: len = XLookupString (&ev.xkey, text, 10, &key, 0); if (len == 1 && text[0] == 'q') doneflag++; break; } } XDestroyWindow (dp, win); XCloseDisplay (dp); exit (0); } /* end main */
void screen(int width, int height) { int a,r; if ((display=XOpenDisplay(NULL)) == NULL) { fprintf(stderr,"Could not connect to X server; not using X.\n"); exit(1); } scr_ptr = DefaultScreenOfDisplay(display); screen_num = DefaultScreen(display); for(a=0; a<32; a++) { r=XAllocNamedColor(display,DefaultColormap(display,screen_num),\ colornames[a],&screen_color,&exact_color); if(r==0) { fprintf(stderr,"Could not allocate color '%s'.\n",colornames[a]); exit(1); } colors[a]=screen_color.pixel; if(a==0) cursorbg=screen_color; if(a==1) cursorfg=screen_color; } totalw=width*mag; totalh=height*mag; fontwidth=0; fontheight=0; font=XLoadFont(display,fontname); if(font==BadName) { fprintf(stderr,"Font %s not found, trying \"fixed\".\n",fontname); font=XLoadFont(display,"fixed"); if(font==BadName) { fprintf(stderr,"Fixed font not found. Giving up.\n"); exit(1); } } fontinfo=XQueryFont(display,font); fontwidth=XTextWidth(fontinfo,"Z",1); fontheight=fontinfo->ascent+fontinfo->descent; if(statusline) { totalh+=fontheight+2; } main_pixmap=XCreatePixmap(display,DefaultRootWindow(display),\ totalw,totalh,DefaultDepth(display,screen_num)); main_win = XCreateSimpleWindow(display,DefaultRootWindow(display), \ 0,0,totalw,totalh,1,colors[1],colors[0]); the_GC = XCreateGC(display,main_win,0,0); XSetForeground(display,the_GC,0); XSetFont(display,the_GC,font); XStoreName(display,main_win,"xmaze"); XMapWindow(display,main_win); XSelectInput(display, main_win, ButtonReleaseMask|ButtonPressMask|ExposureMask|VisibilityChangeMask); XSetGraphicsExposures(display,the_GC,True); XSetForeground(display,the_GC,colors[bg]); XSetBackground(display,the_GC,colors[bg]); XFillRectangle(display,main_pixmap,the_GC,0,0,totalw,totalh); XFillRectangle(display,main_win,the_GC,0,0,totalw,totalh); XSetForeground(display,the_GC,colors[fg]); // cursor = XCreateFontCursor(display,XC_crosshair); // XDefineCursor(display,main_win,cursor); // // This is why X11 turns off a many budding programmers: // Make the cursor a simple red box: // cursorsource=XCreatePixmap(display,DefaultRootWindow(display),\ mag,mag,1); cursormask=XCreatePixmap(display,DefaultRootWindow(display),\ mag,mag,1); XAllocNamedColor(display,DefaultColormap(display,screen_num),\ colornames[1],&screen_color,&exact_color); cursorbg=screen_color; XAllocNamedColor(display,DefaultColormap(display,screen_num),\ colornames[0],&screen_color,&exact_color); cursorbg=screen_color; gc_mask = GCForeground; xgcv.foreground = 0; gcbg=XCreateGC(display,cursorsource,gc_mask,&xgcv); gc_mask = GCForeground; xgcv.foreground = 1; gcfg=XCreateGC(display,cursorsource,gc_mask,&xgcv); XFillRectangle(display,cursormask,gcfg,0,0,mag,mag); XFillRectangle(display,cursorsource,gcfg,0,0,mag,mag); cursor=XCreatePixmapCursor(display,cursorsource,cursormask,&cursorfg,&cursorbg,mag/2,mag/2); XDefineCursor(display,main_win,cursor); // See how simple that was? wmDeleteMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); XSetWMProtocols(display, main_win, &wmDeleteMessage, 1); expose(); }
/* * Creates the config file and tells i3 to reload. * */ static void finish() { printf("creating \"%s\"...\n", config_path); if (!(dpy = XOpenDisplay(NULL))) errx(1, "Could not connect to X11"); FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r"); if (kc_config == NULL) err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes"); FILE *ks_config = fopen(config_path, "w"); if (ks_config == NULL) err(1, "Could not open output config file \"%s\"", config_path); free(config_path); char *line = NULL; size_t len = 0; #ifndef USE_FGETLN ssize_t read; #endif bool head_of_file = true; /* write a header about auto-generation to the output file */ fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config); fputs("# It will not be overwritten, so edit it as you like.\n", ks_config); fputs("#\n", ks_config); fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config); fputs("# this file and re-run i3-config-wizard(1).\n", ks_config); fputs("#\n", ks_config); #ifdef USE_FGETLN char *buf = NULL; while ((buf = fgetln(kc_config, &len)) != NULL) { /* fgetln does not return null-terminated strings */ FREE(line); sasprintf(&line, "%.*s", len, buf); #else size_t linecap = 0; while ((read = getline(&line, &linecap, kc_config)) != -1) { len = strlen(line); #endif /* skip the warning block at the beginning of the input file */ if (head_of_file && strncmp("# WARNING", line, strlen("# WARNING")) == 0) continue; head_of_file = false; /* Skip leading whitespace */ char *walk = line; while (isspace(*walk) && walk < (line + len)) { /* Pre-output the skipped whitespaces to keep proper indentation */ fputc(*walk, ks_config); walk++; } /* Set the modifier the user chose */ if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) { if (modifier == MOD_Mod1) fputs("set $mod Mod1\n", ks_config); else fputs("set $mod Mod4\n", ks_config); continue; } /* Check for 'bindcode'. If it’s not a bindcode line, we * just copy it to the output file */ if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) { fputs(walk, ks_config); continue; } char *result = rewrite_binding(walk); fputs(result, ks_config); free(result); } /* sync to do our best in order to have the file really stored on disk */ fflush(ks_config); fsync(fileno(ks_config)); #ifndef USE_FGETLN free(line); #endif fclose(kc_config); fclose(ks_config); /* tell i3 to reload the config file */ int sockfd = ipc_connect(socket_path); ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload"); close(sockfd); exit(0); } int main(int argc, char *argv[]) { config_path = resolve_tilde("~/.i3/config"); socket_path = getenv("I3SOCK"); char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1"; char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1"; int o, option_index = 0; static struct option long_options[] = { {"socket", required_argument, 0, 's'}, {"version", no_argument, 0, 'v'}, {"limit", required_argument, 0, 'l'}, {"prompt", required_argument, 0, 'P'}, {"prefix", required_argument, 0, 'p'}, {"font", required_argument, 0, 'f'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; char *options_string = "s:vh"; while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) { switch (o) { case 's': FREE(socket_path); socket_path = strdup(optarg); break; case 'v': printf("i3-config-wizard " I3_VERSION "\n"); return 0; case 'h': printf("i3-config-wizard " I3_VERSION "\n"); printf("i3-config-wizard [-s <socket>] [-v]\n"); return 0; } } /* Check if the destination config file does not exist but the path is * writable. If not, exit now, this program is not useful in that case. */ struct stat stbuf; if (stat(config_path, &stbuf) == 0) { printf("The config file \"%s\" already exists. Exiting.\n", config_path); return 0; } /* Create ~/.i3 if it does not yet exist */ char *config_dir = resolve_tilde("~/.i3"); if (stat(config_dir, &stbuf) != 0) if (mkdir(config_dir, 0755) == -1) err(1, "mkdir(%s) failed", config_dir); free(config_dir); int fd; if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) { printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno)); return 0; } close(fd); unlink(config_path); if (socket_path == NULL) socket_path = root_atom_contents("I3_SOCKET_PATH"); if (socket_path == NULL) socket_path = "/tmp/i3-ipc.sock"; int screens; if ((conn = xcb_connect(NULL, &screens)) == NULL || xcb_connection_has_error(conn)) errx(1, "Cannot open display\n"); keysyms = xcb_key_symbols_alloc(conn); xcb_get_modifier_mapping_cookie_t modmap_cookie; modmap_cookie = xcb_get_modifier_mapping(conn); symbols = xcb_key_symbols_alloc(conn); /* Place requests for the atoms we need as soon as possible */ #define xmacro(atom) \ xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom); #include "atoms.xmacro" #undef xmacro root_screen = xcb_aux_get_screen(conn, screens); root = root_screen->root; if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL))) errx(EXIT_FAILURE, "Could not get modifier mapping\n"); xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply); font = load_font(pattern, true); bold_font = load_font(patternbold, true); /* Open an input window */ win = xcb_generate_id(conn); xcb_create_window( conn, XCB_COPY_FROM_PARENT, win, /* the window id */ root, /* parent == root */ 490, 297, 300, 205, /* dimensions */ 0, /* X11 border = 0, we draw our own */ XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */ XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK, (uint32_t[]){ 0, /* back pixel: black */ XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS }); /* Map the window (make it visible) */ xcb_map_window(conn, win); /* Setup NetWM atoms */ #define xmacro(name) \ do { \ xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \ if (!reply) \ errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \ \ A_ ## name = reply->atom; \ free(reply); \ } while (0); #include "atoms.xmacro" #undef xmacro /* Set dock mode */ xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win, A__NET_WM_WINDOW_TYPE, A_ATOM, 32, 1, (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG); /* Set window title */ xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3: first configuration"), "i3: first configuration"); /* Create pixmap */ pixmap = xcb_generate_id(conn); pixmap_gc = xcb_generate_id(conn); xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500); xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0); /* Grab the keyboard to get all input */ xcb_flush(conn); /* Try (repeatedly, if necessary) to grab the keyboard. We might not * get the keyboard at the first attempt because of the keybinding * still being active when started via a wm’s keybinding. */ xcb_grab_keyboard_cookie_t cookie; xcb_grab_keyboard_reply_t *reply = NULL; int count = 0; while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) { cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC); reply = xcb_grab_keyboard_reply(conn, cookie, NULL); usleep(1000); } if (reply->status != XCB_GRAB_STATUS_SUCCESS) { fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status); exit(-1); } xcb_flush(conn); xcb_generic_event_t *event; while ((event = xcb_wait_for_event(conn)) != NULL) { if (event->response_type == 0) { fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence); continue; } /* Strip off the highest bit (set if the event is generated) */ int type = (event->response_type & 0x7F); switch (type) { case XCB_KEY_PRESS: handle_key_press(NULL, conn, (xcb_key_press_event_t*)event); break; /* TODO: handle mappingnotify */ case XCB_BUTTON_PRESS: handle_button_press((xcb_button_press_event_t*)event); break; case XCB_EXPOSE: handle_expose(); break; } free(event); } return 0; }
int main(int argc, char* argv[]) { Display* display; Window win; char *display_name = getenv("DISPLAY"); GC gc, rev_gc; Atom wmDelete; struct CEventDescriptor event = { .Type = EVENT_NULL }; InitGUIServer(); ClearScreen(); while (!ProcessGUIServer(&event)) ; display = XOpenDisplay(display_name); if (display == NULL) { fprintf(stderr, "%s: cannot connect to X server '%s'\n", argv[0], display_name); exit(1); } win = create_simple_window(display, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0); wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", True); XSetWMProtocols(display, win, &wmDelete, 1); gc = create_gc(display, win, 0); rev_gc = create_gc(display, win, 1); XSelectInput(display, win, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask); { int done = 0; XEvent an_event; while (!done) { XNextEvent(display, &an_event); switch (an_event.type) { case Expose: handle_expose(display, gc, rev_gc, (XExposeEvent*)&an_event.xexpose); break; case ButtonPress: handle_button_down(display, gc, rev_gc, (XButtonEvent*)&an_event.xbutton); break; case KeyPress: done = handle_key_down(display, gc, rev_gc, (XKeyEvent*)&an_event.xkey); break; case ClientMessage: done = True; break; default: break; } } } XFreeGC(display, gc); XFreeGC(display, rev_gc); XCloseDisplay(display); return 0; }
int EGLX11Display::createEGLDisplay(int width, int height, bool fullscreen) { Window root; XSetWindowAttributes swa; XSetWindowAttributes xattr; Atom wm_state, a_fullscreen; XWMHints hints; XEvent xev; EGLConfig ecfg; EGLint num_config; w_width = width; w_height = height; w_fullscreen = fullscreen; /* * X11 native display initialization */ DebugLog::Instance()->MESSAGE(3, "Connecting to X server\n"); x_display = XOpenDisplay(NULL); if ( x_display == NULL ) { DebugLog::Instance()->MESSAGE(1, "Error: Unable to connect to X Server\n"); return -1; } DebugLog::Instance()->MESSAGE(3, "Querying X root window\n"); root = DefaultRootWindow(x_display); DebugLog::Instance()->MESSAGE(3, "Creating X11 window\n"); swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask; win = XCreateWindow( x_display, root, 0, 0, width, height, 0, CopyFromParent, InputOutput, CopyFromParent, CWEventMask, &swa ); DebugLog::Instance()->MESSAGE(3, "Updating window attributes\n"); xattr.override_redirect = false; XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr ); DebugLog::Instance()->MESSAGE(3, "Setting Window manager hints\n"); hints.input = true; hints.flags = InputHint; XSetWMHints(x_display, win, &hints); // make the window visible on the screen DebugLog::Instance()->MESSAGE(3, "Making window visible\n"); XMapWindow (x_display, win); XStoreName (x_display, win, "EGLX11Display"); // get identifiers for the provided atom name strings wm_state = XInternAtom (x_display, "_NET_WM_STATE", false); a_fullscreen = false; if (w_fullscreen == true) a_fullscreen = XInternAtom (x_display, "_NET_WM_STATE_FULLSCREEN", w_fullscreen); DebugLog::Instance()->MESSAGE(3, "Updating window event masks\n"); 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] = a_fullscreen; XSendEvent ( x_display, DefaultRootWindow ( x_display ), false, SubstructureNotifyMask, &xev ); DebugLog::Instance()->MESSAGE(2, "X11 native display init done!\n"); /* * Now that the native window is up, we shall initialize EGL */ DebugLog::Instance()->MESSAGE(3, "EGL: eglGetDisplay()\n"); egl_display = eglGetDisplay( (EGLNativeDisplayType) x_display ); GLWrapper::Instance()->flushEGLErrors(); if ( egl_display == EGL_NO_DISPLAY ) { DebugLog::Instance()->MESSAGE(1, "EGL: eglGetDisplay() failed!\n"); return -1; } DebugLog::Instance()->MESSAGE(3, "EGL: eglInitialize()\n"); if ( !eglInitialize( egl_display, NULL, NULL ) ) { GLWrapper::Instance()->flushEGLErrors(); DebugLog::Instance()->MESSAGE(1, "EGL: eglInitialize() failed!\n"); return -1; } GLWrapper::Instance()->flushEGLErrors(); DebugLog::Instance()->MESSAGE(3, "EGL: eglChooseConfig()\n"); if ( !eglChooseConfig( egl_display, attr, &ecfg, 1, &num_config ) ) { GLWrapper::Instance()->flushEGLErrors(); DebugLog::Instance()->MESSAGE(1, "EGL: eglChooseConfig() failed!\n"); return -1; } GLWrapper::Instance()->flushEGLErrors(); DebugLog::Instance()->MESSAGE(3, "EGL: EGL configs available?\n"); if ( num_config == 0 ) { DebugLog::Instance()->MESSAGE(1, "EGL: eglGetDisplay() no configs found!\n"); return -1; } DebugLog::Instance()->MESSAGE(3, "EGL: eglCreateWindowSurface()\n"); egl_surface = eglCreateWindowSurface ( egl_display, ecfg, win, NULL ); GLWrapper::Instance()->flushEGLErrors(); if ( egl_surface == EGL_NO_SURFACE ) { DebugLog::Instance()->MESSAGE(5, "EGL: eglCreateWindowSurface() failed!\n"); return -1; } DebugLog::Instance()->MESSAGE(3, "EGL: eglCreateContext()\n"); egl_context = eglCreateContext ( egl_display, ecfg, EGL_NO_CONTEXT, ctxattr ); GLWrapper::Instance()->flushEGLErrors(); if ( egl_context == EGL_NO_CONTEXT ) { DebugLog::Instance()->MESSAGE(1, "EGL: eglCreateContext() failed!\n"); return -1; } DebugLog::Instance()->MESSAGE(3, "EGL: eglMakeCurrent()\n"); eglMakeCurrent( egl_display, egl_surface, egl_surface, egl_context ); GLWrapper::Instance()->flushEGLErrors(); GLWrapper::Instance()->flushGLErrors(); DebugLog::Instance()->MESSAGE(2, "EGL initialization completed!\n"); return 0; }
void X11_MainLoop() { bool fullscreen = SConfig::GetInstance().m_LocalCoreStartupParameter.bFullscreen; while (!Core::IsRunning()) updateMainFrameEvent.Wait(); Display *dpy = XOpenDisplay(0); Window win = (Window)Core::GetWindowHandle(); XSelectInput(dpy, win, KeyPressMask | FocusChangeMask); if (SConfig::GetInstance().m_LocalCoreStartupParameter.bDisableScreenSaver) X11Utils::InhibitScreensaver(dpy, win, true); #if defined(HAVE_XRANDR) && HAVE_XRANDR X11Utils::XRRConfiguration *XRRConfig = new X11Utils::XRRConfiguration(dpy, win); #endif Cursor blankCursor = None; if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) { // make a blank cursor Pixmap Blank; XColor DummyColor; char ZeroData[1] = {0}; Blank = XCreateBitmapFromData (dpy, win, ZeroData, 1, 1); blankCursor = XCreatePixmapCursor(dpy, Blank, Blank, &DummyColor, &DummyColor, 0, 0); XFreePixmap (dpy, Blank); XDefineCursor(dpy, win, blankCursor); } if (fullscreen) { X11Utils::EWMH_Fullscreen(dpy, _NET_WM_STATE_TOGGLE); #if defined(HAVE_XRANDR) && HAVE_XRANDR XRRConfig->ToggleDisplayMode(True); #endif } // The actual loop while (running) { XEvent event; KeySym key; for (int num_events = XPending(dpy); num_events > 0; num_events--) { XNextEvent(dpy, &event); switch (event.type) { case KeyPress: key = XLookupKeysym((XKeyEvent*)&event, 0); if (key == XK_Escape) { if (Core::GetState() == Core::CORE_RUN) { if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XUndefineCursor(dpy, win); Core::SetState(Core::CORE_PAUSE); } else { if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XDefineCursor(dpy, win, blankCursor); Core::SetState(Core::CORE_RUN); } } else if ((key == XK_Return) && (event.xkey.state & Mod1Mask)) { fullscreen = !fullscreen; X11Utils::EWMH_Fullscreen(dpy, _NET_WM_STATE_TOGGLE); #if defined(HAVE_XRANDR) && HAVE_XRANDR XRRConfig->ToggleDisplayMode(fullscreen); #endif } else if (key >= XK_F1 && key <= XK_F8) { int slot_number = key - XK_F1 + 1; if (event.xkey.state & ShiftMask) State::Save(slot_number); else State::Load(slot_number); } else if (key == XK_F9) Core::SaveScreenShot(); else if (key == XK_F11) State::LoadLastSaved(); else if (key == XK_F12) { if (event.xkey.state & ShiftMask) State::UndoLoadState(); else State::UndoSaveState(); } break; case FocusIn: rendererHasFocus = true; if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor && Core::GetState() != Core::CORE_PAUSE) XDefineCursor(dpy, win, blankCursor); break; case FocusOut: rendererHasFocus = false; if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XUndefineCursor(dpy, win); break; } } if (!fullscreen) { Window winDummy; unsigned int borderDummy, depthDummy; XGetGeometry(dpy, win, &winDummy, &SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowXPos, &SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowYPos, (unsigned int *)&SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowWidth, (unsigned int *)&SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowHeight, &borderDummy, &depthDummy); } usleep(100000); } #if defined(HAVE_XRANDR) && HAVE_XRANDR delete XRRConfig; #endif if (SConfig::GetInstance().m_LocalCoreStartupParameter.bDisableScreenSaver) X11Utils::InhibitScreensaver(dpy, win, false); if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XFreeCursor(dpy, blankCursor); XCloseDisplay(dpy); Core::Stop(); }
// only used internally void makeNativeWindow() { #ifdef __FOR_XORG__ __x_display = XOpenDisplay(NULL); // open the standard display (the primary screen) if (__x_display == NULL) { printf("cannot connect to X server\n"); } Window root = DefaultRootWindow(__x_display); // get the root window (usually the whole screen) XSetWindowAttributes swa; swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask | KeyReleaseMask; __display_width=640; __display_height=480; // xorg hard coded for now int s = DefaultScreen(__x_display); __win = XCreateSimpleWindow(__x_display, root, 10, 10, __display_width, __display_height, 1, BlackPixel(__x_display, s), WhitePixel(__x_display, s)); XSelectInput(__x_display, __win, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); XSetWindowAttributes xattr; Atom atom; int one = 1; xattr.override_redirect = False; XChangeWindowAttributes(__x_display, __win, CWOverrideRedirect, &xattr); /* atom = XInternAtom(__x_display, "_NET_WM_STATE_FULLSCREEN", True); XChangeProperty(__x_display, win, XInternAtom(__x_display, "_NET_WM_STATE", True), XA_ATOM, 32, PropModeReplace, (unsigned char *)&atom, 1); */ XWMHints hints; hints.input = True; hints.flags = InputHint; XSetWMHints(__x_display, __win, &hints); XMapWindow(__x_display, __win); // make the window visible on the screen XStoreName(__x_display, __win, "GLES2.0 framework"); // give the window a name // NB - RPi needs to use EGL_DEFAULT_DISPLAY that some X configs dont seem to like __egl_display = eglGetDisplay((EGLNativeDisplayType) __x_display); if (__egl_display == EGL_NO_DISPLAY) { printf("Got no EGL display.\n"); } __eventWin = __win; Cursor invisibleCursor; Pixmap bitmapNoData; XColor black; static char noData[] = { 0,0,0,0,0,0,0,0 }; black.red = black.green = black.blue = 0; bitmapNoData = XCreateBitmapFromData(__x_display, __win, noData, 8, 8); invisibleCursor = XCreatePixmapCursor(__x_display, bitmapNoData, bitmapNoData, &black, &black, 0, 0); XDefineCursor(__x_display,__win, invisibleCursor); XFreeCursor(__x_display, invisibleCursor); #endif //__FOR_XORG__ #ifdef __FOR_RPi__ bcm_host_init(); int32_t success = 0; // create an EGL window surface, passing context width/height success = graphics_get_display_size(0 /* LCD */ , &__display_width, &__display_height); if (success < 0) { printf("unable to get display size\n"); //return EGL_FALSE; } __x_display = XOpenDisplay(NULL); // open the standard display (the primary screen) if (__x_display == NULL) { printf("cannot connect to X server\n"); } Window root = DefaultRootWindow(__x_display); // get the root window (usually the whole screen) XSetWindowAttributes swa; swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask | KeyReleaseMask; int s = DefaultScreen(__x_display); __eventWin = XCreateSimpleWindow(__x_display, root, 0, 0, __display_width, __display_height, 1, BlackPixel(__x_display, s), WhitePixel(__x_display, s)); XSelectInput(__x_display, __eventWin, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); XSetWindowAttributes xattr; Atom atom; int one = 1; xattr.override_redirect = False; XChangeWindowAttributes(__x_display, __eventWin, CWOverrideRedirect, &xattr); XWMHints hints; hints.input = True; hints.flags = InputHint; XSetWMHints(__x_display, __eventWin, &hints); XMapWindow(__x_display, __eventWin); // make the window visible on the screen XStoreName(__x_display, __eventWin, "Event trap"); // give the window a name // we have to be full screen to capture all mouse events // TODO consider using warp mouse to report relative motions // instead of absolute... XFlush(__x_display); // you have to flush or bcm seems to prevent window coming up? Atom wmState = XInternAtom(__x_display, "_NET_WM_STATE", False); Atom fullScreen = XInternAtom(__x_display, "_NET_WM_STATE_FULLSCREEN", False); XEvent xev; xev.xclient.type = ClientMessage; xev.xclient.serial = 0; xev.xclient.send_event = True; xev.xclient.window = __eventWin; xev.xclient.message_type = wmState; xev.xclient.format = 32; xev.xclient.data.l[0] = 1; //_NET_WM_STATE_ADD xev.xclient.data.l[1] = fullScreen; xev.xclient.data.l[2] = 0; XSendEvent(__x_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(__x_display); // you have to flush or bcm seems to prevent window coming up? static EGL_DISPMANX_WINDOW_T nativewindow; DISPMANX_ELEMENT_HANDLE_T dispman_element; DISPMANX_DISPLAY_HANDLE_T dispman_display; DISPMANX_UPDATE_HANDLE_T dispman_update; VC_RECT_T dst_rect; VC_RECT_T src_rect; // printf("display size %i,%i\n",__display_width,__display_height); dst_rect.x = 0; dst_rect.y = 0; dst_rect.width = __display_width; dst_rect.height = __display_height; src_rect.x = 0; src_rect.y = 0; src_rect.width = __display_width << 16; src_rect.height = __display_height << 16; dispman_display = vc_dispmanx_display_open(0 /* LCD */ ); dispman_update = vc_dispmanx_update_start(0); //VC_DISPMANX_ALPHA_T alpha = { DISPMANX_FLAGS_ALPHA_FROM_SOURCE | DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS,255,0 }; VC_DISPMANX_ALPHA_T alpha = { DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS,255,0 }; dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display, 0 /*layer */ , &dst_rect, 0 /*src */ , &src_rect, DISPMANX_PROTECTION_NONE, &alpha /*alpha */ , 0 /*clamp */ , 0 /*transform */ ); nativewindow.element = dispman_element; nativewindow.width = __display_width; nativewindow.height = __display_height; vc_dispmanx_update_submit_sync(dispman_update); __win = &nativewindow; __egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); #endif //__FOR_RPi__ #ifdef __FOR_RPi_noX__ bcm_host_init(); int32_t success = 0; success = graphics_get_display_size(0 /* LCD */ , &__display_width, &__display_height); if (success < 0) { printf("unable to get display size\n"); //return EGL_FALSE; } static EGL_DISPMANX_WINDOW_T nativewindow; DISPMANX_ELEMENT_HANDLE_T dispman_element; DISPMANX_DISPLAY_HANDLE_T dispman_display; DISPMANX_UPDATE_HANDLE_T dispman_update; VC_RECT_T dst_rect; VC_RECT_T src_rect; dst_rect.x = 0; dst_rect.y = 0; dst_rect.width = __display_width; dst_rect.height = __display_height; src_rect.x = 0; src_rect.y = 0; src_rect.width = __display_width << 16; src_rect.height = __display_height << 16; dispman_display = vc_dispmanx_display_open(0 /* LCD */ ); dispman_update = vc_dispmanx_update_start(0); VC_DISPMANX_ALPHA_T alpha = { DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS,255,0 }; dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display, 0 /*layer */ , &dst_rect, 0 /*src */ , &src_rect, DISPMANX_PROTECTION_NONE, &alpha /*alpha */ , 0 /*clamp */ , 0 /*transform */ ); nativewindow.element = dispman_element; nativewindow.width = __display_width; nativewindow.height = __display_height; vc_dispmanx_update_submit_sync(dispman_update); __win = &nativewindow; __egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (__egl_display == EGL_NO_DISPLAY) { printf("Got no EGL display.\n"); } #endif //__FOR_RPi_noX__ }
///Сохранение и уменьшение скринота в массив - сохранение изображения //1)Снятие скриншота с сохранением указателя //2)Уменьшение изображения по указателю //3)Сохранение изображение void get_screen (string filenom) { Display *disp; Window root; XWindowAttributes watts; XImage *image; cairo_surface_t *surface; unsigned int width; unsigned int height; int stride; /*Глобальная перменная - замер времени выполнения участков кода*/ disp = XOpenDisplay(NULL); root = DefaultRootWindow(disp); //Взять скрин с окна с именем в заголовке "FCEUX 2.2.1" root = windowWithName(disp, root,"FCEUX 2.2.1"); XGetWindowAttributes(disp, root, &watts); width = watts.width; height = watts.height; image = XGetImage(disp, root, watts.x, watts.y, width, height, AllPlanes,ZPixmap); stride = cairo_format_stride_for_width(CAIRO_FORMAT_RGB24, width); unsigned char *datapng = (unsigned char *) malloc (stride * height); int red_shift= get_shift(image->red_mask); int green_shift= get_shift(image->green_mask); int blue_shift= get_shift(image->blue_mask); //Массив с пикселями изображения //map< int ,map <int , map < int, unsigned char > > > in; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { unsigned long pixel = XGetPixel(image, x, y); unsigned char red = (image->red_mask & pixel) >> red_shift; unsigned char green = (image->green_mask & pixel) >> green_shift; unsigned char blue = (image->blue_mask & pixel) >> blue_shift; /* in[y][x][0]=blue; in[y][x][1]=green; in[y][x][2]=red; */ //Буффер записи в файл datapng[y * stride + x * 4 + 0]=blue; datapng[y * stride + x * 4 + 1]=green; datapng[y * stride + x * 4 + 2]=red; in[y][x][0]=red; in[y][x][1]=green; in[y][x][2]=blue; } } const float tx = float(width) / nwidth; const float ty = float(height) / nheight; const int components = 3; const int bytes_per_row = width * components; const int components2 = components; const int bytes_per_row2=width * components; int a, b, c, d, index; unsigned char Ca, Cb, Cc; unsigned char C[5]; unsigned char d0, d2, d3, a0, a1, a2, a3; for (int i = 0; i < nheight; ++i) { for (int j = 0; j < nwidth; ++j) { const int x = int(tx * j); const int y = int(ty * i); const float dx = tx * j - x; const float dy = ty * i - y; index = y * bytes_per_row + x * components; a = y * bytes_per_row + (x + 1) * components; b = (y + 1) * bytes_per_row + x * components; c = (y + 1) * bytes_per_row + (x + 1) * components; for (int k = 0; k < 3; ++k) { for (int jj = 0; jj <= 3; ++jj) { //Беруться пиксели из входящего изображения d0 = in[(y - 1 + jj)][(x - 1)][k] - in[(y - 1 + jj)][x][k]; d2 = in[(y - 1 + jj)][(x + 1)][k] - in[(y - 1 + jj)][x][k]; d3 = in[(y - 1 + jj)][(x + 2)][k] - in[(y - 1 + jj)][x][k]; a0 = in[(y - 1 + jj)][x][k]; //Вычисляются параметры a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3; a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2; a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3; C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx; d0 = C[0] - C[1]; d2 = C[2] - C[1]; d3 = C[3] - C[1]; a0 = C[1]; a1 = -1.0 / 3 * d0 + d2 -1.0 / 6 * d3; a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2; a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3; Cc = a0 + a1 * dy + a2 * dy * dy + a3* dy * dy * dy; //Буффер записи в файл // datapng[i * stride + j * 4 + k]=Cc; //Запись в массив изображения pixels_image[i][j][k]=(int)Cc; } } } } //Сохранение изображения string filename; filename="output/"+filenom+".png"; const char* filename2=filename.c_str(); surface = cairo_image_surface_create_for_data( datapng, CAIRO_FORMAT_RGB24, width, height, stride); cairo_surface_write_to_png( surface, filename2 ); cairo_surface_destroy(surface); free(datapng); }
//Algoritmo T9 di predizione del testo basato su liste void gestionet9 (struttura *str,int tasto) { //fase inizializzazione str->tp.numparoletrovate=0; int i=0; for (i=0; i<N;i++) { str->tp.vetparole[i].frequenza=0; bzero(str->tp.vetparole[i].parola,30); } gtk_list_clear_items ((GtkList *) str->tp.gtklist,0,N); //aggiornamento str->tp.luncodicet9=str->tp.luncodicet9+1; sprintf(str->tp.codicet9,"%s%d",str->tp.codicet9,tasto); //printf("\nTasti premuti: %s\tlunghezza:%d\n",str->tp.codicet9,str->tp.luncodicet9); char query[200]; bzero (query,200); //se freq0 globale, se 1 pers sprintf (query, " select parola dist,frequenza from personale where codice like \'%s%%\' union select parola dist,frequenza from globale where codice like \'%s%%\' order by 2 desc, 1 asc limit 0,5;",str->tp.codicet9,str->tp.codicet9); //GtkWidget *list_item; GList *dlist=NULL; gchar *s; s = (gchar*)malloc(sizeof(gchar)); sprintf(s,""); printf("\n%s\n",query); int retval = sqlite3_prepare_v2(str->tp.db,query,-1,&str->tp.stmt,0); if(retval) { printf("\nerrore database\n"); return; } // Read the number of rows fetched int cols = sqlite3_column_count(str->tp.stmt); while(1) { // fetch a row's status retval = sqlite3_step(str->tp.stmt); if(retval == SQLITE_DONE) break; else if(retval == SQLITE_ROW) { // SQLITE_ROW means fetched a row str->tp.numparoletrovate=str->tp.numparoletrovate+1; printf ("\n"); // sqlite3_column_text returns a const void* , typecast it to const char* for(int col=0 ; col<cols;col++) { const char *val = (const char*)sqlite3_column_text(str->tp.stmt,col); //printf("%s = %s\t",sqlite3_column_name(str->tp.stmt,col),val); if (col==0) { printf ("%s",val); sprintf(str->tp.vetparole[str->tp.numparoletrovate-1].parola,"%s",val); str->tp.list_item=gtk_list_item_new_with_label(val); dlist=g_list_append(dlist, str->tp.list_item); gtk_widget_show(str->tp.list_item); gtk_object_set_data(GTK_OBJECT(str->tp.list_item), list_item_data_key,s); } else { printf ("\tfr=%s",val); str->tp.vetparole[str->tp.numparoletrovate-1].frequenza=atoi(val); } } } else { // Some error encountered printf("errori query\n"); return; } } str->tp.indice=0; Display *display = XOpenDisplay(0); if(str->tp.numparoletrovate> 0) { gtk_list_append_items((GtkList*)(str->tp.gtklist), dlist); } gdk_window_process_all_updates (); XCloseDisplay(display); printf ("\n"); }
static void x11_init(void) { memset(keys, 0, KEYMAX); memset(mouse, 0, 3); display = XOpenDisplay(0); screen = DefaultScreen(display); xvis = glXChooseVisual(display, screen, xAttrList); if(!xvis) { printf("glXChooseVisual() failed.\n"); exit(1); } glx_context = glXCreateContext(display, xvis, 0, GL_TRUE); memset(&xwin_attr, 0, sizeof(XSetWindowAttributes)); xwin_attr.colormap = XCreateColormap(display, RootWindow(display, xvis->screen), xvis->visual, AllocNone); xwin_attr.event_mask = ExposureMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | KeyPressMask | KeyReleaseMask; x11_window(); static char buf[] = { 0,0,0,0,0,0,0,0 }; XColor black = { .red=0, .green=0, .blue=0 }; Pixmap bitmap = XCreateBitmapFromData(display, window, buf, 2, 2); cursor_none = XCreatePixmapCursor(display, bitmap, bitmap, &black, &black, 0, 0); int event, error; if (!XQueryExtension(display, "XInputExtension", &opcode, &event, &error)) { printf("X Input extension not available.\n"); return; } #ifdef ASD /* Which version of XI2? We support 2.0 */ int major = 2, minor = 0; if (XIQueryVersion(display, &major, &minor) == BadRequest) { printf("XI2 not available. Server supports %d.%d\n", major, minor); return; } XIEventMask eventmask; unsigned char mask[3] = { 0,0,0 }; /* the actual mask */ eventmask.deviceid = XIAllDevices; eventmask.mask_len = sizeof(mask); /* always in bytes */ eventmask.mask = mask; /* now set the mask */ // XISetMask(mask, XI_ButtonPress); // XISetMask(mask, XI_ButtonRelease); XISetMask(mask, XI_RawMotion); // XISetMask(mask, XI_KeyPress); // mask = mask | KeyReleaseMask | KeyPressMask; /* select on the window */ Window root = DefaultRootWindow(display); XISelectEvents(display, root, &eventmask, 1); // XSetDeviceMode(display, mouse, Relative); #endif } void print_rawmotion(XIRawEvent *event) { int i; double *raw_valuator = event->raw_values, *valuator = event->valuators.values; for (i = 0; i < event->valuators.mask_len * 8; i++) { if (XIMaskIsSet(event->valuators.mask, i)) { switch(i) { case 0: mickey_x += *valuator; break; case 1: mickey_y += *valuator; break; default: break; } valuator++; raw_valuator++; } } }
int main(int argc, char *argv[]) { Display *x_dpy; Window win1, win2; EGLSurface egl_surf1, egl_surf2; EGLContext egl_ctx; EGLDisplay egl_dpy; char *dpyName = NULL; GLboolean printInfo = GL_FALSE; EGLint egl_major, egl_minor; int i; const char *s; static struct { char *name; GLenum value; enum {GetString, GetInteger} type; } info_items[] = { {"GL_RENDERER", GL_RENDERER, GetString}, {"GL_VERSION", GL_VERSION, GetString}, {"GL_VENDOR", GL_VENDOR, GetString}, {"GL_EXTENSIONS", GL_EXTENSIONS, GetString}, {"GL_MAX_PALETTE_MATRICES_OES", GL_MAX_PALETTE_MATRICES_OES, GetInteger}, {"GL_MAX_VERTEX_UNITS_OES", GL_MAX_VERTEX_UNITS_OES, GetInteger}, }; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-display") == 0) { dpyName = argv[i+1]; i++; } else if (strcmp(argv[i], "-info") == 0) { printInfo = GL_TRUE; } else { usage(); return -1; } } x_dpy = XOpenDisplay(dpyName); if (!x_dpy) { printf("Error: couldn't open display %s\n", dpyName ? dpyName : getenv("DISPLAY")); return -1; } egl_dpy = eglGetDisplay(x_dpy); if (!egl_dpy) { printf("Error: eglGetDisplay() failed\n"); return -1; } if (!eglInitialize(egl_dpy, &egl_major, &egl_minor)) { printf("Error: eglInitialize() failed\n"); return -1; } s = eglQueryString(egl_dpy, EGL_VERSION); printf("EGL_VERSION = %s\n", s); s = eglQueryString(egl_dpy, EGL_VENDOR); printf("EGL_VENDOR = %s\n", s); s = eglQueryString(egl_dpy, EGL_EXTENSIONS); printf("EGL_EXTENSIONS = %s\n", s); s = eglQueryString(egl_dpy, EGL_CLIENT_APIS); printf("EGL_CLIENT_APIS = %s\n", s); make_x_window(x_dpy, egl_dpy, "xegl_two_win #1", 0, 0, WinWidth[0], WinHeight[0], &win1, &egl_ctx, &egl_surf1); make_x_window(x_dpy, egl_dpy, "xegl_two_win #2", WinWidth[0] + 50, 0, WinWidth[1], WinHeight[1], &win2, NULL, &egl_surf2); XMapWindow(x_dpy, win1); XMapWindow(x_dpy, win2); if (!eglMakeCurrent(egl_dpy, egl_surf1, egl_surf1, egl_ctx)) { printf("Error: eglMakeCurrent() failed\n"); return -1; } if (printInfo) { for (i = 0; i < sizeof(info_items)/sizeof(info_items[0]); i++) { switch (info_items[i].type) { case GetString: printf("%s = %s\n", info_items[i].name, (char *)glGetString(info_items[i].value)); break; case GetInteger: { GLint rv = -1; glGetIntegerv(info_items[i].value, &rv); printf("%s = %d\n", info_items[i].name, rv); break; } } } }; init(); event_loop(x_dpy, win1, win2, egl_dpy, egl_surf1, egl_surf2, egl_ctx); eglDestroyContext(egl_dpy, egl_ctx); eglDestroySurface(egl_dpy, egl_surf1); eglDestroySurface(egl_dpy, egl_surf2); eglTerminate(egl_dpy); XDestroyWindow(x_dpy, win1); XDestroyWindow(x_dpy, win2); XCloseDisplay(x_dpy); return 0; }
int main(int argc, char **argv) { const char *pws; Display *dpy; int screen; int result; while((result = getopt(argc,argv,"vo:")) != -1) { switch(result) { case 'v': die("slock-%s, © 2006-2012 Anselm R Garbe\n", VERSION); case 'o': opacity = atof(optarg); printf("%f\n", opacity); break; case '?': usage(); break; } } if ((argc - optind) > 0) usage(); #ifdef __linux__ dontkillme(); #endif if(!getpwuid(getuid())) die("slock: no passwd entry for you\n"); pws = getpw(); if(!(dpy = XOpenDisplay(0))) die("slock: cannot open display\n"); /* Get the number of screens in display "dpy" and blank them all. */ nscreens = ScreenCount(dpy); locks = malloc(sizeof(Lock *) * nscreens); if(locks == NULL) die("slock: malloc: %s\n", strerror(errno)); int nlocks = 0; for(screen = 0; screen < nscreens; screen++) { if ( (locks[screen] = lockscreen(dpy, screen)) != NULL) { nlocks++; } } XSync(dpy, False); /* Did we actually manage to lock something? */ if (nlocks == 0) { // nothing to protect free(locks); XCloseDisplay(dpy); return 1; } /* Everything is now blank. Now wait for the correct password. */ readpw(dpy, pws); /* Password ok, unlock everything and quit. */ for(screen = 0; screen < nscreens; screen++) unlockscreen(dpy, locks[screen]); free(locks); XCloseDisplay(dpy); return 0; }
/* * * Procedure: * main - start of module * */ int main(int argc, char **argv) { char *display_name = NULL; char *tline; FlocaleInit(LC_CTYPE, "", "", "MvwmIdent"); module = ParseModuleArgs(argc,argv,0); /* no alias */ if (module == NULL) { fprintf( stderr, "MvwmIdent Version %s should only be executed" " by mvwm!\n", VERSION); exit(1); } #ifdef HAVE_SIGACTION { struct sigaction sigact; sigemptyset(&sigact.sa_mask); sigaddset(&sigact.sa_mask, SIGPIPE); sigaddset(&sigact.sa_mask, SIGTERM); sigaddset(&sigact.sa_mask, SIGQUIT); sigaddset(&sigact.sa_mask, SIGINT); sigaddset(&sigact.sa_mask, SIGHUP); # ifdef SA_INTERRUPT sigact.sa_flags = SA_INTERRUPT; # else sigact.sa_flags = 0; # endif sigact.sa_handler = TerminateHandler; sigaction(SIGPIPE, &sigact, NULL); sigaction(SIGTERM, &sigact, NULL); sigaction(SIGQUIT, &sigact, NULL); sigaction(SIGINT, &sigact, NULL); sigaction(SIGHUP, &sigact, NULL); } #else /* We don't have sigaction(), so fall back to less robust methods. */ #ifdef USE_BSD_SIGNALS mvwmSetSignalMask( sigmask(SIGPIPE) | sigmask(SIGTERM) | sigmask(SIGQUIT) | sigmask(SIGINT) | sigmask(SIGHUP) ); #endif signal(SIGPIPE, TerminateHandler); signal(SIGTERM, TerminateHandler); signal(SIGQUIT, TerminateHandler); signal(SIGINT, TerminateHandler); signal(SIGHUP, TerminateHandler); #ifdef HAVE_SIGINTERRUPT siginterrupt(SIGPIPE, 1); siginterrupt(SIGTERM, 1); siginterrupt(SIGQUIT, 1); siginterrupt(SIGINT, 1); siginterrupt(SIGHUP, 1); #endif #endif fd[0] = module->to_mvwm; fd[1] = module->from_mvwm; /* Open the Display */ if (!(dpy = XOpenDisplay(display_name))) { fprintf(stderr,"%s: can't open display %s", module->name, XDisplayName(display_name)); exit (1); } x_fd = XConnectionNumber(dpy); screen= DefaultScreen(dpy); Root = RootWindow(dpy, screen); XSetErrorHandler(ErrorHandler); flib_init_graphics(dpy); FlocaleAllocateWinString(&FwinString); SetMessageMask(fd, M_CONFIGURE_WINDOW | M_WINDOW_NAME | M_ICON_NAME | M_RES_CLASS | M_RES_NAME | M_END_WINDOWLIST | M_CONFIG_INFO | M_END_CONFIG_INFO | M_SENDCONFIG); SetMessageMask(fd, MX_PROPERTY_CHANGE); /* scan config file for set-up parameters */ /* Colors and fonts */ InitGetConfigLine(fd,CatString3("*",module->name,0)); GetConfigLine(fd,&tline); while (tline != (char *)0) { if (strlen(tline) <= 1) { continue; } if (strncasecmp(tline, CatString3("*",module->name,0), module->namelen+1) == 0) { tline += (module->namelen +1); if (strncasecmp(tline, "Font", 4) == 0) { CopyStringWithQuotes(&font_string, &tline[4]); } else if (strncasecmp(tline, "Fore", 4) == 0) { CopyString(&ForeColor, &tline[4]); colorset = -1; } else if (strncasecmp(tline, "Back", 4) == 0) { CopyString(&BackColor, &tline[4]); colorset = -1; } else if (strncasecmp(tline, "Colorset", 8) == 0) { sscanf(&tline[8], "%d", &colorset); AllocColorset(colorset); } else if (strncasecmp(tline, "MinimalLayer", 12) == 0) { char *layer_str = PeekToken(&tline[12], NULL); if (layer_str == NULL) { minimal_layer = default_layer; } else if (sscanf( layer_str, "%d", &minimal_layer) != 1) { if (strncasecmp( layer_str, "none", 4) == 0) { minimal_layer = -1; } else { minimal_layer = default_layer; } } } } else if (strncasecmp(tline, "Colorset", 8) == 0) { LoadColorset(&tline[8]); } GetConfigLine(fd, &tline); } if(module->window == 0) { mvwmlib_get_target_window( dpy, screen, module->name, &(module->window), True); } fd_width = GetFdWidth(); /* Create a list of all windows */ /* Request a list of all windows, * wait for ConfigureWindow packets */ SendText(fd, "Send_WindowList", 0); /* tell mvwm we're running */ SendFinishedStartupNotification(fd); if (module->window == Root) { exit(0); } Loop(fd); return 0; }
static gboolean skype_connect() { Window root; Atom skype_inst; Atom type_ret; int format_ret; unsigned long nitems_ret; unsigned long bytes_after_ret; unsigned char *prop; int status; x11_error_code = 0; XSetErrorHandler(x11_error_handler); skype_debug_info("skype_x11", "Set the XErrorHandler\n"); #ifdef USE_XVFB_SERVER if (!getenv("SKYPEDISPLAY")) setenv("SKYPEDISPLAY", ":25", 0); #endif if (getenv("SKYPEDISPLAY")) disp = XOpenDisplay(getenv("SKYPEDISPLAY")); else disp = XOpenDisplay(getenv("DISPLAY")); if (disp == NULL) { skype_debug_info("skype_x11", "Couldn't open display\n"); return FALSE; } skype_debug_info("skype_x11", "Opened display\n"); message_start = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE_BEGIN", False ); message_continue = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE", False ); root = DefaultRootWindow( disp ); win = XCreateSimpleWindow( disp, root, 0, 0, 1, 1, 0, BlackPixel( disp, DefaultScreen( disp ) ), BlackPixel( disp, DefaultScreen( disp ) )); XFlush(disp); if (win == -1) { XCloseDisplay(disp); skype_debug_info("skype_x11", "Could not create X11 messaging window\n"); return FALSE; } skype_debug_info("skype_x11", "Created X11 messaging window\n"); skype_inst = XInternAtom(disp, "_SKYPE_INSTANCE", True); if (skype_inst == None) { XDestroyWindow(disp, win); XCloseDisplay(disp); win = (Window)-1; skype_win = (Window)-1; skype_debug_info("skype_x11", "Could not create skype Atom\n"); return FALSE; } skype_debug_info("skype_x11", "Created skype Atom\n"); status = XGetWindowProperty(disp, root, skype_inst, 0, 1, False, XA_WINDOW, &type_ret, &format_ret, &nitems_ret, &bytes_after_ret, &prop); if(status != Success || format_ret != 32 || nitems_ret < 1) { XDestroyWindow(disp, win); XCloseDisplay(disp); win = (Window)-1; XFree(prop); skype_win = (Window)-1; skype_debug_info("skype", "Skype instance not found\n"); return FALSE; } skype_debug_info("skype_x11", "Skype instance found\n"); skype_win = * (const unsigned long *) prop & 0xffffffff; XFree(prop); run_loop = TRUE; skype_debug_info("skype_x11", "Charging lasers...\n"); receiving_thread = g_thread_create((GThreadFunc)receive_message_loop, NULL, FALSE, NULL); return TRUE; }
bool WaylandX11WindowSystem::createNativeContext() { bool result = true; Window rootWindow = 0; XSetWindowAttributes windowAttributes; unsigned int windowMask = 0; int colorDepth = 0; int widthCorrected = 0; int heightCorrected = 0; LOG_DEBUG("WaylandX11WindowSystem", "createNativeContext IN"); m_x11Window = 0; m_x11Display = NULL; m_x11Screen = 0; m_x11Visual = NULL; m_x11Display = XOpenDisplay(0); if (!m_x11Display) { printf("Error: Unable to open X display\n"); return false; } m_x11Screen = XDefaultScreen(m_x11Display); // Get the root window parameters rootWindow = RootWindow(m_x11Display, m_x11Screen); colorDepth = 32; // TODO: DefaultDepth(m_x11Display, m_x11Screen); // Alloc memory for the visual info m_x11Visual = (XVisualInfo*)malloc(sizeof(XVisualInfo)); // Try to find a visual which is matching the needed parameters if (!XMatchVisualInfo(m_x11Display, m_x11Screen, colorDepth, TrueColor, m_x11Visual)) { printf("Error: Unable to acquire visual\n"); //destroyX11Context(); return false; } // Create the rendercontext color map m_x11Colormap = XCreateColormap( m_x11Display, rootWindow, m_x11Visual->visual, AllocNone); windowAttributes.colormap = m_x11Colormap; // Add to these for handling other events windowAttributes.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | Button1MotionMask | PointerMotionMask | FocusChangeMask; windowAttributes.backing_store = Always; // Set the window mask attributes windowMask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap | CWBackingStore; // get the corrected window dimensions widthCorrected = m_width < XDisplayWidth(m_x11Display, m_x11Screen) ? m_width : XDisplayWidth( m_x11Display, m_x11Screen); heightCorrected = m_height < XDisplayHeight(m_x11Display, m_x11Screen) ? m_height : XDisplayHeight( m_x11Display, m_x11Screen); // Creates the X11 window m_x11Window = XCreateWindow( m_x11Display, RootWindow(m_x11Display, m_x11Screen), 0, 0, widthCorrected, heightCorrected, 0, m_x11Visual->depth, InputOutput, m_x11Visual->visual, windowMask, &windowAttributes); // map the window XMapWindow(m_x11Display, m_x11Window); XFlush(m_x11Display); LOG_DEBUG("WaylandX11WindowSystem", "createNativeContext OUT"); return result; }
void X11_Init (void) { int attributes[] = { GLX_RGBA, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DOUBLEBUFFER, None }; Colormap color_map; XSetWindowAttributes attr; XEvent event; char* p; XInitThreads (); X11_display = XOpenDisplay (0); if (!X11_display) { const char* displayName = getenv ("DISPLAY"); errx (EXIT_FAILURE, "Failed to open X11_display %s", displayName ? displayName : ":0"); } XSynchronize (X11_display, True); if (!glXQueryExtension (X11_display, 0, 0)) errx (EXIT_FAILURE, "No GLX extension present"); if (!(X11_visual = glXChooseVisual (X11_display, DefaultScreen (X11_display), attributes))) errx (EXIT_FAILURE, "glXChooseVisual failed"); if (!(X11_glxContext = glXCreateContext (X11_display, X11_visual, 0, GL_TRUE))) errx (EXIT_FAILURE, "Failed creating OpenGL context"); color_map = XCreateColormap (X11_display, RootWindow (X11_display, X11_visual->screen), X11_visual->visual, AllocNone); attr.colormap = color_map; attr.border_pixel = 0; attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | ExposureMask | FocusChangeMask; X11_window = XCreateWindow (X11_display, RootWindow (X11_display, X11_visual->screen), 0, 0, X11_window_width, X11_window_height, 0, X11_visual->depth, InputOutput, X11_visual->visual, CWBorderPixel | CWColormap | CWEventMask, &attr); XMapRaised (X11_display, X11_window); if ((p = XSetLocaleModifiers ("")) && *p) X11_xim = XOpenIM (X11_display, 0, 0, 0); if (!X11_xim && (p = XSetLocaleModifiers ("@im=none")) && *p) X11_xim = XOpenIM (X11_display, 0, 0, 0); if (!X11_xim) errx (EXIT_FAILURE, "Failed to open X Input Method"); X11_xic = XCreateIC (X11_xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, X11_window, XNFocusWindow, X11_window, NULL); if (!X11_xic) errx (EXIT_FAILURE, "Failed to create X Input Context"); while (!x11_gotMapNotify) { XEvent event; XNextEvent (X11_display, &event); x11_ProcessEvent (&event); } if (!glXMakeCurrent (X11_display, X11_window, X11_glxContext)) errx (EXIT_FAILURE, "glXMakeCurrent returned false"); glewInit (); X11_xa_wm_delete_window = XInternAtom (X11_display, "WM_DELETE_WINDOW", False); XSynchronize (X11_display, False); }
/*ARGSUSED*/ int main(int argc, char *argv[]) { XEvent ev; XGCValues gv; XSetWindowAttributes attr; (void) argc; argv0 = argv[0]; /* Open a connection to the X server. */ dpy = XOpenDisplay(""); if (dpy == 0) Panic("can't open display."); get_resources(); /* Find the screen's dimensions. */ display_width = DisplayWidth(dpy, DefaultScreen(dpy)); display_height = DisplayHeight(dpy, DefaultScreen(dpy)); /* Set up an error handler. */ XSetErrorHandler(ErrorHandler); /* Get the pixel values of the only two colours we use. */ black = BlackPixel(dpy, DefaultScreen(dpy)); white = WhitePixel(dpy, DefaultScreen(dpy)); /* Get font. */ font = XLoadQueryFont(dpy, font_name); if (font == 0) font = XLoadQueryFont(dpy, "fixed"); if (font == 0) Panic("can't find a font."); /* Get a cursor. */ initCursor(); /* Create the window. */ root = DefaultRootWindow(dpy); attr.override_redirect = True; attr.background_pixel = white; attr.border_pixel = black; attr.cursor = mouse_cursor; attr.event_mask = ExposureMask | VisibilityChangeMask | ButtonMotionMask | PointerMotionHintMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask | EnterWindowMask | LeaveWindowMask; window = XCreateWindow(dpy, root, 0, 0, display_width, 1.2 * (font->ascent + font->descent), 0, CopyFromParent, InputOutput, CopyFromParent, CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWCursor | CWEventMask, &attr); /* Create GC. */ gv.foreground = black; gv.background = white; gv.font = font->fid; gc = XCreateGC(dpy, window, GCForeground | GCBackground | GCFont, &gv); /* Create the menu items. */ readMenu(); /* Bring up the window. */ XMapRaised(dpy, window); /* Make sure all our communication to the server got through. */ XSync(dpy, False); /* The main event loop. */ for (;;) { getEvent(&ev); dispatch(&ev); } }
int main(int argc, char *argv[]) { /* Declare variables */ Window win; /* Window */ /* set up option table. I can't figure out a better way than this to * do it while sticking to pure ANSI C. The option and specifier * members have a type of volatile char *, so they need to be allocated * by strdup or malloc, you can't set them to a string constant at * declare time, this is note pure ANSI C apparently, although it does * work with gcc */ /* loop option entry */ opt_tab[0].option = xcstrdup("-loops"); opt_tab[0].specifier = xcstrdup(".loops"); opt_tab[0].argKind = XrmoptionSepArg; opt_tab[0].value = (XPointer) NULL; /* display option entry */ opt_tab[1].option = xcstrdup("-display"); opt_tab[1].specifier = xcstrdup(".display"); opt_tab[1].argKind = XrmoptionSepArg; opt_tab[1].value = (XPointer) NULL; /* selection option entry */ opt_tab[2].option = xcstrdup("-selection"); opt_tab[2].specifier = xcstrdup(".selection"); opt_tab[2].argKind = XrmoptionSepArg; opt_tab[2].value = (XPointer) NULL; /* filter option entry */ opt_tab[3].option = xcstrdup("-filter"); opt_tab[3].specifier = xcstrdup(".filter"); opt_tab[3].argKind = XrmoptionNoArg; opt_tab[3].value = (XPointer) xcstrdup(ST); /* in option entry */ opt_tab[4].option = xcstrdup("-in"); opt_tab[4].specifier = xcstrdup(".direction"); opt_tab[4].argKind = XrmoptionNoArg; opt_tab[4].value = (XPointer) xcstrdup("I"); /* out option entry */ opt_tab[5].option = xcstrdup("-out"); opt_tab[5].specifier = xcstrdup(".direction"); opt_tab[5].argKind = XrmoptionNoArg; opt_tab[5].value = (XPointer) xcstrdup("O"); /* version option entry */ opt_tab[6].option = xcstrdup("-version"); opt_tab[6].specifier = xcstrdup(".print"); opt_tab[6].argKind = XrmoptionNoArg; opt_tab[6].value = (XPointer) xcstrdup("V"); /* help option entry */ opt_tab[7].option = xcstrdup("-help"); opt_tab[7].specifier = xcstrdup(".print"); opt_tab[7].argKind = XrmoptionNoArg; opt_tab[7].value = (XPointer) xcstrdup("H"); /* silent option entry */ opt_tab[8].option = xcstrdup("-silent"); opt_tab[8].specifier = xcstrdup(".olevel"); opt_tab[8].argKind = XrmoptionNoArg; opt_tab[8].value = (XPointer) xcstrdup("S"); /* quiet option entry */ opt_tab[9].option = xcstrdup("-quiet"); opt_tab[9].specifier = xcstrdup(".olevel"); opt_tab[9].argKind = XrmoptionNoArg; opt_tab[9].value = (XPointer) xcstrdup("Q"); /* verbose option entry */ opt_tab[10].option = xcstrdup("-verbose"); opt_tab[10].specifier = xcstrdup(".olevel"); opt_tab[10].argKind = XrmoptionNoArg; opt_tab[10].value = (XPointer) xcstrdup("V"); /* parse command line options */ doOptMain(argc, argv); /* Connect to the X server. */ if ((dpy = XOpenDisplay(sdisp))) { /* successful */ if (fverb == OVERBOSE) fprintf(stderr, "Connected to X server.\n"); } else { /* couldn't connect to X server. Print error and exit */ errxdisplay(sdisp); } /* parse selection command line option */ doOptSel(); /* Create a window to trap events */ win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, 0, 0); /* get events about property changes */ XSelectInput(dpy, win, PropertyChangeMask); if (fdiri) doIn(win, argv[0]); else doOut(win); /* Disconnect from the X server */ XCloseDisplay(dpy); /* exit */ return (EXIT_SUCCESS); }