bool OpenGLApp::initAPI(){ screen = DefaultScreen(display); int nModes; XF86VidModeGetAllModeLines(display, screen, &nModes, &dmodes); Array <DispRes> modes; char str[64]; int foundMode = -1; for (int i = 0; i < nModes; i++){ if (dmodes[i]->hdisplay >= 640 && dmodes[i]->vdisplay >= 480){ modes.add(newRes(dmodes[i]->hdisplay, dmodes[i]->vdisplay, i)); if (dmodes[i]->hdisplay == fullscreenWidth && dmodes[i]->vdisplay == fullscreenHeight){ foundMode = i; } } } resolution->clear(); modes.sort(dComp); for (uint i = 0; i < modes.getCount(); i++){ sprintf(str, "%dx%d", modes[i].w, modes[i].h); int index = resolution->addItemUnique(str); if (modes[i].index == foundMode) resolution->selectItem(index); } if (fullscreen){ if (foundMode >= 0 && XF86VidModeSwitchToMode(display, screen, dmodes[foundMode])){ XF86VidModeSetViewPort(display, screen, 0, 0); } else { char str[128]; sprintf(str, "Couldn't set fullscreen at %dx%d.", fullscreenWidth, fullscreenHeight); ErrorMsg(str); fullscreen = false; } } XVisualInfo *vi; while (true){ int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, (colorBits > 24)? 8 : 0, GLX_DEPTH_SIZE, depthBits, GLX_STENCIL_SIZE, stencilBits, GLX_SAMPLE_BUFFERS_ARB, (antiAliasSamples > 0), GLX_SAMPLES_ARB, antiAliasSamples, None, }; vi = glXChooseVisual(display, screen, attribs); if (vi != NULL) break; antiAliasSamples -= 2; if (antiAliasSamples < 0){ char str[256]; sprintf(str, "No Visual matching colorBits=%d, depthBits=%d and stencilBits=%d", colorBits, depthBits, stencilBits); ErrorMsg(str); return false; } } //printf("Selected visual = 0x%x\n",(unsigned int) (vi->visualid)); glContext = glXCreateContext(display, vi, None, True); XSetWindowAttributes attr; attr.colormap = XCreateColormap(display, RootWindow(display, screen), vi->visual, AllocNone); attr.border_pixel = 0; attr.override_redirect = fullscreen; attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; window = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr); if (!fullscreen){ Atom wmDelete; wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", True); XSetWMProtocols(display, window, &wmDelete, 1); char *title = "OpenGL"; XSetStandardProperties(display, window, title, title, None, NULL, 0, NULL); } XMapRaised(display, window); // Create a blank cursor for cursor hiding XColor dummy; char data = 0; Pixmap blank = XCreateBitmapFromData(display, window, &data, 1, 1); blankCursor = XCreatePixmapCursor(display, blank, blank, &dummy, &dummy, 0, 0); XFreePixmap(display, blank); XGrabKeyboard(display, window, True, GrabModeAsync, GrabModeAsync, CurrentTime); glXMakeCurrent(display, window, glContext); initExtensions(display); if (antiAliasSamples > 0){ glEnable(GL_MULTISAMPLE_ARB); } if (fullscreen) captureMouse(!configDialog->isVisible()); renderer = new OpenGLRenderer(window, glContext, display, screen); renderer->setViewport(width, height); antiAlias->selectItem(antiAliasSamples / 2); linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP); defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp); blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA); noDepthTest = renderer->addDepthState(false, false); noDepthWrite = renderer->addDepthState(true, false); cullNone = renderer->addRasterizerState(CULL_NONE); cullBack = renderer->addRasterizerState(CULL_BACK); cullFront = renderer->addRasterizerState(CULL_FRONT); return true; }
void run_app(Window forgein_window) { Display* dpy = XOpenDisplay(NULL); Window window = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1024, 768, 0, // borderwidth 0, // border 0x000000); // background XSelectInput(dpy, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask); // FIXME: No idea why I have to do all this stuff, but it makes the // XReparentWindow() work the first time, otherwise the program has // to be started twice to make a successful capture XUnmapWindow(dpy, forgein_window); set_decorations(dpy, forgein_window, 0); usleep(100000); XReparentWindow(dpy, forgein_window, window, 0, 0); XMapRaised(dpy, window); XMapWindow(dpy, forgein_window); bool quit = false; while(!quit) { XEvent event; XNextEvent (dpy, &event); switch (event.type) { case ButtonPress: std::cout << "ButtonPress" << std::endl; break; case ButtonRelease: std::cout << "ButtonPress" << std::endl; break; case KeyPress: std::cout << "KeyPress" << std::endl; { KeySym sym = XLookupKeysym(&event.xkey,0); switch (sym) { case XK_Escape: quit = true; break; default: XSendEvent(dpy, forgein_window, True, KeyPressMask, &event); break; } } break; case KeyRelease: std::cout << "KeyRelease" << std::endl; // doesn't work with Wine/Gargoyle? XSendEvent(dpy, forgein_window, True, KeyReleaseMask, &event); break; case ConfigureNotify: std::cout << "ConfigureNotify: " << event.xconfigure.width << "x" << event.xconfigure.height << "+" << event.xconfigure.x << "+" << event.xconfigure.y << std::endl; { XWindowAttributes attr; XGetWindowAttributes(dpy, forgein_window, &attr); std::cout << " -- " << attr.x << "+" << attr.y << " " << attr.width << "x" << attr.height << std::endl; XResizeWindow(dpy, forgein_window, attr.width, event.xconfigure.height); XGetWindowAttributes(dpy, forgein_window, &attr); XMoveWindow(dpy, forgein_window, event.xconfigure.width/2 - attr.width/2, event.xconfigure.height/2 - attr.height/2); std::cout << " -- " << attr.x << "+" << attr.y << " " << attr.width << "x" << attr.height << std::endl; } break; default: std::cout << "unhandled message type" << std::endl; break; } } // cleanup XDestroyWindow(dpy, window); XCloseDisplay(dpy); }
static bool gfx_ctx_glx_set_video_mode(void *data, unsigned width, unsigned height, bool fullscreen) { XEvent event; bool true_full = false, windowed_full; int val, x_off = 0, y_off = 0; XVisualInfo *vi = NULL; XSetWindowAttributes swa = {0}; int (*old_handler)(Display*, XErrorEvent*) = NULL; settings_t *settings = config_get_ptr(); gfx_ctx_glx_data_t *glx = (gfx_ctx_glx_data_t*) gfx_ctx_data_get_ptr(); x11_install_sighandlers(); if (!glx) return false; windowed_full = settings->video.windowed_fullscreen; true_full = false; vi = glXGetVisualFromFBConfig(g_x11_dpy, glx->g_fbc); if (!vi) goto error; swa.colormap = g_x11_cmap = XCreateColormap(g_x11_dpy, RootWindow(g_x11_dpy, vi->screen), vi->visual, AllocNone); swa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonReleaseMask | ButtonPressMask; swa.override_redirect = fullscreen ? True : False; if (fullscreen && !windowed_full) { if (x11_enter_fullscreen(g_x11_dpy, width, height, &glx->g_desktop_mode)) { glx->g_should_reset_mode = true; true_full = true; } else RARCH_ERR("[GLX]: Entering true fullscreen failed. Will attempt windowed mode.\n"); } if (settings->video.monitor_index) g_x11_screen = settings->video.monitor_index - 1; #ifdef HAVE_XINERAMA if (fullscreen || g_x11_screen != 0) { unsigned new_width = width; unsigned new_height = height; if (x11_get_xinerama_coord(g_x11_dpy, g_x11_screen, &x_off, &y_off, &new_width, &new_height)) RARCH_LOG("[GLX]: Using Xinerama on screen #%u.\n", g_x11_screen); else RARCH_LOG("[GLX]: Xinerama is not active on screen.\n"); if (fullscreen) { width = new_width; height = new_height; } } #endif RARCH_LOG("[GLX]: X = %d, Y = %d, W = %u, H = %u.\n", x_off, y_off, width, height); g_x11_win = XCreateWindow(g_x11_dpy, RootWindow(g_x11_dpy, vi->screen), x_off, y_off, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | (true_full ? CWOverrideRedirect : 0), &swa); XSetWindowBackground(g_x11_dpy, g_x11_win, 0); glx->g_glx_win = glXCreateWindow(g_x11_dpy, glx->g_fbc, g_x11_win, 0); x11_set_window_attr(g_x11_dpy, g_x11_win); if (fullscreen) x11_show_mouse(g_x11_dpy, g_x11_win, false); if (true_full) { RARCH_LOG("[GLX]: Using true fullscreen.\n"); XMapRaised(g_x11_dpy, g_x11_win); } else if (fullscreen) /* We attempted true fullscreen, but failed. Attempt using windowed fullscreen. */ { XMapRaised(g_x11_dpy, g_x11_win); RARCH_LOG("[GLX]: Using windowed fullscreen.\n"); /* We have to move the window to the screen we want to go fullscreen on first. * x_off and y_off usually get ignored in XCreateWindow(). */ x11_move_window(g_x11_dpy, g_x11_win, x_off, y_off, width, height); x11_windowed_fullscreen(g_x11_dpy, g_x11_win); } else { XMapWindow(g_x11_dpy, g_x11_win); /* If we want to map the window on a different screen, we'll have to do it by force. * Otherwise, we should try to let the window manager sort it out. * x_off and y_off usually get ignored in XCreateWindow(). */ if (g_x11_screen) x11_move_window(g_x11_dpy, g_x11_win, x_off, y_off, width, height); } x11_event_queue_check(&event); if (!glx->g_ctx) { if (glx->g_core_es || glx->g_debug) { int attribs[16]; int *aptr = attribs; if (glx->g_core_es) { *aptr++ = GLX_CONTEXT_MAJOR_VERSION_ARB; *aptr++ = g_major; *aptr++ = GLX_CONTEXT_MINOR_VERSION_ARB; *aptr++ = g_minor; if (glx->g_core_es_core) { /* Technically, we don't have core/compat until 3.2. * Version 3.1 is either compat or not depending on GL_ARB_compatibility. */ *aptr++ = GLX_CONTEXT_PROFILE_MASK_ARB; #ifdef HAVE_OPENGLES2 *aptr++ = GLX_CONTEXT_ES_PROFILE_BIT_EXT; #else *aptr++ = GLX_CONTEXT_CORE_PROFILE_BIT_ARB; #endif } } if (glx->g_debug) { *aptr++ = GLX_CONTEXT_FLAGS_ARB; *aptr++ = GLX_CONTEXT_DEBUG_BIT_ARB; } *aptr = None; glx->g_ctx = glx_create_context_attribs(g_x11_dpy, glx->g_fbc, NULL, True, attribs); if (glx->g_use_hw_ctx) { RARCH_LOG("[GLX]: Creating shared HW context.\n"); glx->g_hw_ctx = glx_create_context_attribs(g_x11_dpy, glx->g_fbc, glx->g_ctx, True, attribs); if (!glx->g_hw_ctx) RARCH_ERR("[GLX]: Failed to create new shared context.\n"); } } else { glx->g_ctx = glXCreateNewContext(g_x11_dpy, glx->g_fbc, GLX_RGBA_TYPE, 0, True); if (glx->g_use_hw_ctx) { glx->g_hw_ctx = glXCreateNewContext(g_x11_dpy, glx->g_fbc, GLX_RGBA_TYPE, glx->g_ctx, True); if (!glx->g_hw_ctx) RARCH_ERR("[GLX]: Failed to create new shared context.\n"); } } if (!glx->g_ctx) { RARCH_ERR("[GLX]: Failed to create new context.\n"); goto error; } } else { video_driver_ctl(RARCH_DISPLAY_CTL_SET_VIDEO_CACHE_CONTEXT_ACK, NULL); RARCH_LOG("[GLX]: Using cached GL context.\n"); } glXMakeContextCurrent(g_x11_dpy, glx->g_glx_win, glx->g_glx_win, glx->g_ctx); XSync(g_x11_dpy, False); x11_install_quit_atom(); glXGetConfig(g_x11_dpy, vi, GLX_DOUBLEBUFFER, &val); glx->g_is_double = val; if (glx->g_is_double) { const char *swap_func = NULL; g_pglSwapIntervalEXT = (void (*)(Display*, GLXDrawable, int))glXGetProcAddress((const GLubyte*)"glXSwapIntervalEXT"); g_pglSwapIntervalSGI = (int (*)(int))glXGetProcAddress((const GLubyte*)"glXSwapIntervalSGI"); g_pglSwapInterval = (int (*)(int))glXGetProcAddress((const GLubyte*)"glXSwapIntervalMESA"); if (g_pglSwapIntervalEXT) swap_func = "glXSwapIntervalEXT"; else if (g_pglSwapInterval) swap_func = "glXSwapIntervalMESA"; else if (g_pglSwapIntervalSGI) swap_func = "glXSwapIntervalSGI"; if (!g_pglSwapInterval && !g_pglSwapIntervalEXT && !g_pglSwapIntervalSGI) RARCH_WARN("[GLX]: Cannot find swap interval call.\n"); else RARCH_LOG("[GLX]: Found swap function: %s.\n", swap_func); } else RARCH_WARN("[GLX]: Context is not double buffered!.\n"); gfx_ctx_glx_swap_interval(data, glx->g_interval); /* This can blow up on some drivers. It's not fatal, so override errors for this call. */ old_handler = XSetErrorHandler(glx_nul_handler); XSetInputFocus(g_x11_dpy, g_x11_win, RevertToNone, CurrentTime); XSync(g_x11_dpy, False); XSetErrorHandler(old_handler); XFree(vi); if (!x11_input_ctx_new(true_full)) goto error; return true; error: if (vi) XFree(vi); ctx_glx_destroy_resources(glx); if (glx) free(glx); g_x11_screen = 0; return false; }
bool Sys_CreateWindow(const char *title, unsigned int w, unsigned int h, bool fs) { XVisualInfo *visual_info; Colormap colormap; XF86VidModeModeInfo **modes; int modeNum, i, best_mode = 0; Atom wm_delete; Window win_dummy; unsigned int border_dummy; g_Window.display = XOpenDisplay(0); g_Window.screen = DefaultScreen(g_Window.display); g_Window.width = w; g_Window.height = h; g_Window.fs = fs; #if DEBUG /* TODO: I think I should just define debug with a ./configure flag. */ _VidModeQueryVersion(); #endif XF86VidModeGetAllModeLines(g_Window.display, g_Window.screen, &modeNum, &modes); g_Window.desktop_mode = *modes[0]; /* What if we don't have a match at all? ** Should I pick the next best mode? */ for (i = 0; i < modeNum; ++i) { if ((modes[i]->hdisplay == g_Window.width) && (modes[i]->vdisplay == g_Window.height)) { best_mode = i; break; } } visual_info = glXChooseVisual(g_Window.display, g_Window.screen, attrListDbl); if (visual_info == NULL) { fprintf(stderr, "Need single-buffered output\n"); return false; } g_Window.double_buffered = true; #if DEBUG printf("Using double-buffered output\n"); _glXQueryVersion(); #endif g_Window.glctx = glXCreateContext(g_Window.display, visual_info, 0, GL_TRUE); g_Window.parent_window = RootWindow(g_Window.display, visual_info->screen); colormap = XCreateColormap( g_Window.display, g_Window.parent_window, visual_info->visual, AllocNone ); g_Window.window_attrs.colormap = colormap; g_Window.window_attrs.border_pixel = 0; g_Window.window_attrs.event_mask = X_MASK; if (g_Window.fs) { XF86VidModeSwitchToMode(g_Window.display, g_Window.screen, modes[best_mode]); XF86VidModeSetViewPort(g_Window.display, g_Window.screen, 0, 0); XFree(modes); g_Window.window_attrs.override_redirect = true; g_Window.window = _XCreateWindow(visual_info, g_Window.width, g_Window.height); } else { /* create a window in window mode */ g_Window.window = _XCreateWindow(visual_info, g_Window.width, g_Window.height); wm_delete = XInternAtom(g_Window.display, "WM_DELETE_WINDOW", true); XSetWMProtocols(g_Window.display, g_Window.window, &wm_delete, 1); XSetStandardProperties(g_Window.display, g_Window.window, title, title, None, NULL, 0, NULL); } /* XWarpPointer(g_Window.display, None, g_Window.window, 0, 0, 0, 0, g_Window.width/2, g_Window.height/2); */ /* don't discard events in the queue */ XSync(g_Window.display, false); /*XDefineCursor(g_Window.display, g_Window.window, CreateNullCursor());*/ XMapRaised(g_Window.display, g_Window.window); XGrabKeyboard(g_Window.display, g_Window.window, true, GrabModeAsync, GrabModeAsync, CurrentTime); if (g_Window.fs) { XGrabPointer(g_Window.display, g_Window.window, true, MOUSE_MASK, GrabModeAsync, GrabModeAsync, g_Window.window, None, CurrentTime); } glXMakeCurrent(g_Window.display, g_Window.window, g_Window.glctx); XGetGeometry(g_Window.display, g_Window.window, &win_dummy, &g_Window.x, &g_Window.y, &g_Window.width, &g_Window.height, &border_dummy, &g_Window.depth); #if DEBUG printf("Resolution %dx%d\n", g_Window.width, g_Window.height); printf("Depth %d\n", g_Window.depth); #endif mouse_active = true; return true; }
/* * Starts a window resize operation */ void RESIZE_EventLoop(ScreenInfo *scr, Window w, MwmWindow *tmp_win, int val1, int val2, int val1_unit, int val2_unit) { Bool finished = False, done = False; int x, y, delta_x, delta_y; Window ResizeWindow; XEvent oevent; if ((w == None) || (tmp_win == NULL)) return; /* Already checked this in functions.c, but its here too incase * there's a resize on initial placement. */ if (tmp_win && !(tmp_win->functions & MWM_FUNC_RESIZE)) { XBell(dpy, scr->screen); return; } /* can't resize icons */ if (tmp_win->flags & ICONIFIED) return; ResizeWindow = tmp_win->frame; if ((val1 != 0) && (val2 != 0)) { dragWidth = val1 * val1_unit / 100; dragHeight = val2 * val2_unit / 100; WIN_ConstrainWindow(scr, tmp_win, &dragWidth, &dragHeight); DEC_ConfigureDecorations(scr, tmp_win, tmp_win->frame_x, tmp_win->frame_y, dragWidth, dragHeight, False); ResizeWindow = None; PAGER_Clear(scr); return; } COLOR_PushRootColorMap(scr); if (menuFromFrameOrWindowOrTitlebar) { /* warp the pointer to the cursor position from before menu appeared */ XWarpPointer(dpy, None, scr->root_win, 0, 0, 0, 0, Stashed_X, Stashed_Y); XFlush(dpy); } if (!MISC_Grab(scr, MOVE_CURS)) { XBell(dpy, scr->screen); return; } if ((!(scr->flags & OpaqueResize)) || ((scr->flags & OpaqueResize) && (!(tmp_win->flags & MAPPED)))) XGrabServer(dpy); pagerOn = False; XGetGeometry(dpy, (Drawable)ResizeWindow, &JunkRoot, &dragx, &dragy, (unsigned int *)&dragWidth, (unsigned int *)&dragHeight, &JunkBW, &JunkDepth); dragx += tmp_win->bw; dragy += tmp_win->bw; origx = dragx; origy = dragy; origWidth = dragWidth; origHeight = dragHeight; ymotion = xmotion = 0; /* pop up a resize dimensions window */ if (Mwm.show_feedback & MWM_FEEDBACK_RESIZE) XMapRaised(dpy, scr->size_win); last_width = 0; last_height = 0; if (Mwm.show_feedback & MWM_FEEDBACK_RESIZE) display_size(scr, tmp_win, origWidth, origHeight, True); /* Get the current position to determine which border to resize */ if ((scr->pressed_win != scr->root_win) && (scr->pressed_win != None)) { if (scr->pressed_win == tmp_win->sides[0]) /* top */ ymotion = 1; if (scr->pressed_win == tmp_win->sides[1]) /* right */ xmotion = -1; if (scr->pressed_win == tmp_win->sides[2]) /* bottom */ ymotion = -1; if (scr->pressed_win == tmp_win->sides[3]) /* left */ xmotion = 1; if (scr->pressed_win == tmp_win->corners[0]) { /* upper-left */ ymotion = 1; xmotion = 1; } if (scr->pressed_win == tmp_win->corners[1]) { /* upper-right */ xmotion = -1; ymotion = 1; } if (scr->pressed_win == tmp_win->corners[2]) { /* lower right */ ymotion = -1; xmotion = 1; } if (scr->pressed_win == tmp_win->corners[3]) { /* lower left */ ymotion = -1; xmotion = -1; } } /* draw the rubber-band window */ if ((!(scr->flags & OpaqueResize)) || ((scr->flags & OpaqueResize) && (!(tmp_win->flags & MAPPED)))) WIN_DrawOutline(scr, scr->root_win, dragx - tmp_win->bw, dragy - tmp_win->bw, dragWidth + 2 * tmp_win->bw, dragHeight + 2 * tmp_win->bw); /* loop to resize */ while (!finished) { XMaskEvent(dpy, ButtonPressMask | ButtonReleaseMask | KeyPressMask | ButtonMotionMask | PointerMotionMask | ExposureMask, &oevent); MISC_StashEventTime(&oevent); if (oevent.type == MotionNotify) /* discard any extra motion events before a release */ while (XCheckMaskEvent(dpy, ButtonMotionMask | ButtonReleaseMask | PointerMotionMask, &oevent)) { MISC_StashEventTime(&oevent); if (oevent.type == ButtonRelease) break; } done = False; /* Handle a limited number of key press events to allow mouseless * operation */ if (oevent.type == KeyPress) MISC_KeyboardShortcut(scr, &oevent, ButtonRelease); switch (oevent.type) { case ButtonPress: XAllowEvents(dpy, ReplayPointer, CurrentTime); case KeyPress: done = True; break; case ButtonRelease: finished = True; done = True; break; case MotionNotify: x = oevent.xmotion.x_root; y = oevent.xmotion.y_root; /* need to move the viewport */ PAN_PanDesktop(scr, scr->edge_scroll_x, scr->edge_scroll_y, &x, &y, &delta_x, &delta_y, False, &oevent); origx -= delta_x; origy -= delta_y; dragx -= delta_x; dragy -= delta_y; resize_window(scr, x, y, tmp_win); done = True; default: break; } if (!done) { if ((!(scr->flags & OpaqueResize)) || ((scr->flags & OpaqueResize) && (!(tmp_win->flags & MAPPED)))) WIN_DrawOutline(scr, scr->root_win, 0, 0, 0, 0); EVENT_Dispatch(&oevent); if ((!(scr->flags & OpaqueResize)) || ((scr->flags & OpaqueResize) && (!(tmp_win->flags & MAPPED)))) WIN_DrawOutline(scr, scr->root_win, dragx - tmp_win->bw, dragy - tmp_win->bw, dragWidth + 2 * tmp_win->bw, dragHeight + 2 * tmp_win->bw); } } /* erase the rubber-band */ if ((!(scr->flags & OpaqueResize)) || ((scr->flags & OpaqueResize) && (!(tmp_win->flags & MAPPED)))) WIN_DrawOutline(scr, scr->root_win, 0, 0, 0, 0); /* pop down the size window */ if (Mwm.show_feedback & MWM_FEEDBACK_RESIZE) XUnmapWindow(dpy, scr->size_win); pagerOn = True; WIN_ConstrainWindow(scr, tmp_win, &dragWidth, &dragHeight); DEC_ConfigureDecorations(scr, tmp_win, dragx - tmp_win->bw, dragy - tmp_win->bw, dragWidth, dragHeight, False); COLOR_PopRootColorMap(scr); ResizeWindow = None; XUngrabServer(dpy); MISC_Ungrab(scr); PAGER_Clear(scr); }
void initgraph(int larg, int haut) { char *window_name[2] = {"Fenetre graphique",NULL}; char *icon_name[2] = {"graph", NULL}; XTextProperty windowName, iconName; unsigned long wattrmask; XSetWindowAttributes wattr; unsigned long gcattrmask; XGCValues gcattr; XEvent report; /* déja initialisée ? */ if (init) { fprintf(stderr, "%s: graphique deja initialise\n", NAME); return; } /* connection au serveur X */ if ((display = XOpenDisplay(NULL)) == NULL) { fprintf(stderr, "%s: impossible de se connecter au serveur X %s\n", NAME, XDisplayName(NULL)); abort(); } screen = DefaultScreen(display); black = BlackPixel(display, screen); white = WhitePixel(display, screen); /* on crée la fenêtre */ window = XCreateSimpleWindow(display, RootWindow(display, screen), 0, 0, larg, haut, BORDER_WIDTH, black, white); wattrmask = CWEventMask | CWSaveUnder | CWBackingStore; wattr.event_mask = ExposureMask; wattr.backing_store = Always; wattr.save_under = True; XChangeWindowAttributes(display, window, wattrmask, &wattr); /* Création de l'icone */ /* XpmCreatePixmapFromData(display, window, icon_xpm, &icon_pixmap, NULL, NULL); */ // icon_pixmap = XCreateBitmapFromData(display, window, icon_bits, // icon_width, icon_height); /* allocation mémoire */ if (!(size_hints = XAllocSizeHints())) { fprintf(stderr, "%s: pb allocation SizeHints\n", NAME); abort(); } if (!(wm_hints = XAllocWMHints())) { fprintf(stderr, "%s: pb allocation WMHints\n", NAME); abort(); } /* la taille minimale demandée */ size_hints->flags = PMinSize | PMaxSize; size_hints->min_width = larg; size_hints->min_height = haut; size_hints->max_width = larg; size_hints->max_height = haut; /* les noms de la fenetre et de l'icone */ if (XStringListToTextProperty(window_name, 1, &windowName) == 0) { fprintf(stderr, "%s: pb allocation windowName\n", NAME); abort(); } if (XStringListToTextProperty(icon_name, 1, &iconName) == 0) { fprintf(stderr, "%s: pb allocation iconName\n", NAME); abort(); } /* quelques conseils pour le WindowManager */ wm_hints->initial_state = NormalState; wm_hints->input = True; // wm_hints->icon_pixmap = icon_pixmap; // wm_hints->flags = StateHint | IconPixmapHint | InputHint; wm_hints->flags = StateHint | InputHint; XSetWMProperties(display, window, &windowName, &iconName, NULL, 0, size_hints, wm_hints, NULL); XFree(windowName.value); XFree(iconName.value); /* les attributs de dessin */ // font = XLoadFont(display, fontname); gcattr.foreground = black; gcattr.background = white; // gcattr.font = font; gcattrmask = GCForeground | GCBackground; // gcattrmask = GCForeground | GCBackground | GCFont; gc = XCreateGC(display, window, gcattrmask, &gcattr); /* affiche la fenêtre */ XMapRaised(display, window); /* il faut attendre un Expose avant de dessiner ... */ XWindowEvent(display, window, ExposureMask, &report); shadow = XCreatePixmap(display, window, larg, haut, DefaultDepth(display, screen)); init = 1; cleargraph(); return; }
// ---------------------------------------------------------------------------------------------- // Switch to fullscreen. // ---------------------------------------------------------------------------------------------- void wsFullScreen( wsTWindow * win ) { int decoration = 0; if ( win->isFullScreen ) { vo_x11_ewmh_fullscreen( _NET_WM_STATE_REMOVE ); // removes fullscreen state if wm supports EWMH if ( ! (vo_fs_type & vo_wm_FULLSCREEN) ) // shouldn't be needed with EWMH fs { win->X=win->OldX; win->Y=win->OldY; win->Width=win->OldWidth; win->Height=win->OldHeight; decoration=win->Decorations; } #ifdef ENABLE_DPMS wsScreenSaverOn( wsDisplay ); #endif win->isFullScreen=False; } else { if ( ! (vo_fs_type & vo_wm_FULLSCREEN) ) // shouldn't be needed with EWMH fs { win->OldX=win->X; win->OldY=win->Y; win->OldWidth=win->Width; win->OldHeight=win->Height; vo_dx = win->X; vo_dy = win->Y; vo_dwidth = win->Width; vo_dheight = win->Height; 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; win->X=wsOrgX; win->Y=wsOrgY; win->Width=wsMaxX; win->Height=wsMaxY; } win->isFullScreen=True; #ifdef ENABLE_DPMS wsScreenSaverOff( wsDisplay ); #endif vo_x11_ewmh_fullscreen( _NET_WM_STATE_ADD ); // adds fullscreen state if wm supports EWMH } if ( ! (vo_fs_type & vo_wm_FULLSCREEN) ) // shouldn't be needed with EWMH fs { vo_x11_decoration( wsDisplay,win->WindowID,decoration ); vo_x11_sizehint( win->X,win->Y,win->Width,win->Height,0 ); vo_x11_setlayer( wsDisplay,win->WindowID,win->isFullScreen ); if ((!(win->isFullScreen)) & vo_ontop) vo_x11_setlayer(wsDisplay, win->WindowID,1); XMoveResizeWindow( wsDisplay,win->WindowID,win->X,win->Y,win->Width,win->Height ); } if ( vo_wm_type == 0 && !(vo_fsmode&16) ) { XWithdrawWindow( wsDisplay,win->WindowID,wsScreen ); } XMapRaised( wsDisplay,win->WindowID ); XRaiseWindow( wsDisplay,win->WindowID ); XFlush( wsDisplay ); }
void setup(void) { int x, y, screen = DefaultScreen(dc->dpy); Window root = RootWindow(dc->dpy, screen); XSetWindowAttributes swa; XIM xim; #ifdef XINERAMA int n; XineramaScreenInfo *info; #endif clip = XInternAtom(dc->dpy, "CLIPBOARD", False); utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False); /* calculate menu geometry */ bh = dc->font.height + 2; lines = MAX(lines, 0); mh = (lines + 1) * bh; #ifdef XINERAMA if((info = XineramaQueryScreens(dc->dpy, &n))) { int a, j, di, i = 0, area = 0; unsigned int du; Window w, pw, dw, *dws; XWindowAttributes wa; XGetInputFocus(dc->dpy, &w, &di); if(w != root && w != PointerRoot && w != None) { /* find top-level window containing current input focus */ do { if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws) XFree(dws); } while(w != root && w != pw); /* find xinerama screen with which the window intersects most */ if(XGetWindowAttributes(dc->dpy, pw, &wa)) for(j = 0; j < n; j++) if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) { area = a; i = j; } } /* no focused window is on screen, so use pointer location instead */ if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du)) for(i = 0; i < n; i++) if(INTERSECT(x, y, 1, 1, info[i])) break; x = info[i].x_org; y = info[i].y_org + (topbar ? 0 : info[i].height - mh); mw = info[i].width; XFree(info); } else #endif { x = 0; y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh; mw = DisplayWidth(dc->dpy, screen); } promptw = (prompt && *prompt) ? textw(dc, prompt) : 0; inputw = MIN(inputw, mw/3); match(); /* create menu window */ swa.override_redirect = True; swa.background_pixel = normcol->BG; swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask; win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0, DefaultDepth(dc->dpy, screen), CopyFromParent, DefaultVisual(dc->dpy, screen), CWOverrideRedirect | CWBackPixel | CWEventMask, &swa); /* open input methods */ xim = XOpenIM(dc->dpy, NULL, NULL, NULL); xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, win, XNFocusWindow, win, NULL); XMapRaised(dc->dpy, win); resizedc(dc, mw, mh); drawmenu(); }
bool CWinSystemX11::SetWindow(int width, int height, bool fullscreen, const std::string &output, int *winstate) { bool changeWindow = false; bool changeSize = false; float mouseX = 0.5; float mouseY = 0.5; if (!m_mainWindow) { CInputManager::GetInstance().SetMouseActive(false); } if (m_mainWindow && ((m_bFullScreen != fullscreen) || m_currentOutput.compare(output) != 0 || m_windowDirty)) { // set mouse to last known position // we can't trust values after an xrr event if (m_bIsInternalXrr && m_MouseX >= 0 && m_MouseY >= 0) { mouseX = (float)m_MouseX/m_nWidth; mouseY = (float)m_MouseY/m_nHeight; } else if (!m_windowDirty) { Window root_return, child_return; int root_x_return, root_y_return; int win_x_return, win_y_return; unsigned int mask_return; bool isInWin = XQueryPointer(m_dpy, m_mainWindow, &root_return, &child_return, &root_x_return, &root_y_return, &win_x_return, &win_y_return, &mask_return); if (isInWin) { mouseX = (float)win_x_return/m_nWidth; mouseY = (float)win_y_return/m_nHeight; } } CInputManager::GetInstance().SetMouseActive(false); OnLostDevice(); DestroyWindow(); m_windowDirty = true; } // create main window if (!m_mainWindow) { EnableSystemScreenSaver(false); Colormap cmap; XSetWindowAttributes swa; XVisualInfo *vi; int x0 = 0; int y0 = 0; XOutput *out = g_xrandr.GetOutput(output); if (!out) out = g_xrandr.GetOutput(m_currentOutput); if (out) { m_nScreen = out->screen; x0 = out->x; y0 = out->y; } vi = GetVisual(); if (!vi) { CLog::Log(LOGERROR, "Failed to find matching visual"); return false; } cmap = XCreateColormap(m_dpy, RootWindow(m_dpy, vi->screen), vi->visual, AllocNone); bool hasWM = HasWindowManager(); int def_vis = (vi->visual == DefaultVisual(m_dpy, vi->screen)); swa.override_redirect = hasWM ? False : True; swa.border_pixel = fullscreen ? 0 : 5; swa.background_pixel = def_vis ? BlackPixel(m_dpy, vi->screen) : 0; swa.colormap = cmap; swa.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | PropertyChangeMask | StructureNotifyMask | KeymapStateMask | EnterWindowMask | LeaveWindowMask | ExposureMask; unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWOverrideRedirect | CWEventMask; m_mainWindow = XCreateWindow(m_dpy, RootWindow(m_dpy, vi->screen), x0, y0, width, height, 0, vi->depth, InputOutput, vi->visual, mask, &swa); swa.override_redirect = False; swa.border_pixel = 0; swa.event_mask = ExposureMask; mask = CWBackPixel | CWBorderPixel | CWColormap | CWOverrideRedirect | CWColormap | CWEventMask; m_glWindow = XCreateWindow(m_dpy, m_mainWindow, 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, mask, &swa); if (fullscreen && hasWM) { Atom fs = XInternAtom(m_dpy, "_NET_WM_STATE_FULLSCREEN", True); XChangeProperty(m_dpy, m_mainWindow, XInternAtom(m_dpy, "_NET_WM_STATE", True), XA_ATOM, 32, PropModeReplace, (unsigned char *) &fs, 1); // disable desktop compositing for KDE, when Kodi is in full-screen mode int one = 1; XChangeProperty(m_dpy, m_mainWindow, XInternAtom(m_dpy, "_KDE_NET_WM_BLOCK_COMPOSITING", True), XA_CARDINAL, 32, PropModeReplace, (unsigned char*) &one, 1); } // define invisible cursor Pixmap bitmapNoData; XColor black; static char noData[] = { 0,0,0,0,0,0,0,0 }; black.red = black.green = black.blue = 0; bitmapNoData = XCreateBitmapFromData(m_dpy, m_mainWindow, noData, 8, 8); m_invisibleCursor = XCreatePixmapCursor(m_dpy, bitmapNoData, bitmapNoData, &black, &black, 0, 0); XFreePixmap(m_dpy, bitmapNoData); XDefineCursor(m_dpy,m_mainWindow, m_invisibleCursor); XFree(vi); //init X11 events CWinEventsX11Imp::Init(m_dpy, m_mainWindow); changeWindow = true; changeSize = true; } if (!CWinEventsX11Imp::HasStructureChanged() && ((width != m_nWidth) || (height != m_nHeight))) { changeSize = true; } if (changeSize || changeWindow) { XResizeWindow(m_dpy, m_mainWindow, width, height); } if ((width != m_nWidth) || (height != m_nHeight) || changeWindow) { XResizeWindow(m_dpy, m_glWindow, width, height); } if (changeWindow) { m_icon = None; { CreateIconPixmap(); XWMHints *wm_hints; XClassHint *class_hints; XTextProperty windowName, iconName; std::string titleString = CCompileInfo::GetAppName(); std::string classString = titleString; char *title = (char*)titleString.c_str(); XStringListToTextProperty(&title, 1, &windowName); XStringListToTextProperty(&title, 1, &iconName); wm_hints = XAllocWMHints(); wm_hints->initial_state = NormalState; wm_hints->icon_pixmap = m_icon; wm_hints->flags = StateHint | IconPixmapHint; class_hints = XAllocClassHint(); class_hints->res_class = (char*)classString.c_str(); class_hints->res_name = (char*)classString.c_str(); XSetWMProperties(m_dpy, m_mainWindow, &windowName, &iconName, NULL, 0, NULL, wm_hints, class_hints); XFree(class_hints); XFree(wm_hints); // register interest in the delete window message Atom wmDeleteMessage = XInternAtom(m_dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(m_dpy, m_mainWindow, &wmDeleteMessage, 1); } // placement of window may follow mouse XWarpPointer(m_dpy, None, m_mainWindow, 0, 0, 0, 0, mouseX*width, mouseY*height); XMapRaised(m_dpy, m_glWindow); XMapRaised(m_dpy, m_mainWindow); // discard events generated by creating the window, i.e. xrr events XSync(m_dpy, TRUE); if (winstate) *winstate = 1; } UpdateCrtc(); return true; }
int main(int argc, char *argv[]) { int i; char *action_string = NULL; char *endptr; /* default values */ dzen.cur_line = 0; dzen.ret_val = 0; dzen.title_win.x = dzen.slave_win.x = 0; dzen.title_win.y = 0; dzen.title_win.width = dzen.slave_win.width = 0; dzen.title_win.alignment = ALIGNCENTER; dzen.slave_win.alignment = ALIGNLEFT; dzen.fnt = FONT; dzen.bg = BGCOLOR; dzen.fg = FGCOLOR; dzen.slave_win.max_lines = 0; dzen.running = True; dzen.xinescreen = 0; dzen.tsupdate = 0; dzen.line_height = 0; /* cmdline args */ for(i = 1; i < argc; i++) if(!strncmp(argv[i], "-l", 3)){ if(++i < argc) { dzen.slave_win.max_lines = atoi(argv[i]); init_input_buffer(); } } else if(!strncmp(argv[i], "-u", 3)){ dzen.tsupdate = True; } else if(!strncmp(argv[i], "-p", 3)) { dzen.ispersistent = True; if (i+1 < argc) { dzen.timeout = strtoul(argv[i+1], &endptr, 10); if(*endptr) dzen.timeout = 0; else i++; } } else if(!strncmp(argv[i], "-ta", 4)) { if(++i < argc) dzen.title_win.alignment = argv[i][0]; } else if(!strncmp(argv[i], "-sa", 4)) { if(++i < argc) dzen.slave_win.alignment = argv[i][0]; } else if(!strncmp(argv[i], "-m", 3)) { dzen.slave_win.ismenu = True; if(i+1 < argc) dzen.slave_win.ishmenu = (argv[i+1][0] == 'h') ? ++i, True : False; } else if(!strncmp(argv[i], "-fn", 4)) { if(++i < argc) dzen.fnt = argv[i]; } else if(!strncmp(argv[i], "-e", 3)) { if(++i < argc) action_string = argv[i]; } else if(!strncmp(argv[i], "-bg", 4)) { if(++i < argc) dzen.bg = argv[i]; } else if(!strncmp(argv[i], "-fg", 4)) { if(++i < argc) dzen.fg = argv[i]; } else if(!strncmp(argv[i], "-x", 3)) { if(++i < argc) dzen.title_win.x = dzen.slave_win.x = atoi(argv[i]); } else if(!strncmp(argv[i], "-y", 3)) { if(++i < argc) dzen.title_win.y = atoi(argv[i]); } else if(!strncmp(argv[i], "-w", 3)) { if(++i < argc) dzen.slave_win.width = atoi(argv[i]); } else if(!strncmp(argv[i], "-h", 3)) { if(++i < argc) dzen.line_height= atoi(argv[i]); } else if(!strncmp(argv[i], "-tw", 4)) { if(++i < argc) dzen.title_win.width = atoi(argv[i]); } #ifdef DZEN_XINERAMA else if(!strncmp(argv[i], "-xs", 4)) { if(++i < argc) dzen.xinescreen = atoi(argv[i]); } #endif else if(!strncmp(argv[i], "-v", 3)) eprint("dzen-"VERSION", (C)opyright 2007 Robert Manea\n"); else eprint("usage: dzen2 [-v] [-p [seconds]] [-m [v|h]] [-ta <l|c|r>] [-sa <l|c|r>]\n" " [-x <pixel>] [-y <pixel>] [-w <pixel>] [-tw <pixel>] [-u] \n" " [-e <string>] [-l <lines>] [-fn <font>] [-bg <color>] [-fg <color>]\n" #ifdef DZEN_XINERAMA " [-xs <screen>]\n" #endif ); if(dzen.tsupdate && !dzen.slave_win.max_lines) dzen.tsupdate = False; if(!dzen.title_win.width) dzen.title_win.width = dzen.slave_win.width; if(!setlocale(LC_ALL, "") || !XSupportsLocale()) puts("dzen: locale not available, expect problems with fonts.\n"); if(action_string) fill_ev_table(action_string); else { if(!dzen.slave_win.max_lines) { char edef[] = "button3=exit:13"; fill_ev_table(edef); } else if(dzen.slave_win.ishmenu) { char edef[] = "enterslave=grabkeys;leaveslave=ungrabkeys;" "button4=scrollup;button5=scrolldown;" "key_Left=scrollup;key_Right=scrolldown;" "button1=menuexec;button3=exit:13;" "key_Escape=ungrabkeys,exit"; fill_ev_table(edef); } else { char edef[] = "entertitle=uncollapse,grabkeys;" "enterslave=grabkeys;leaveslave=collapse,ungrabkeys;" "button1=menuexec;button2=togglestick;button3=exit:13;" "button4=scrollup;button5=scrolldown;" "key_Up=scrollup;key_Down=scrolldown;" "key_Escape=ungrabkeys,exit"; fill_ev_table(edef); } } if((find_event(onexit) != -1) && (setup_signal(SIGTERM, catch_sigterm) == SIG_ERR)) fprintf(stderr, "dzen: error hooking SIGTERM\n"); if((find_event(sigusr1) != -1) && (setup_signal(SIGUSR1, catch_sigusr1) == SIG_ERR)) fprintf(stderr, "dzen: error hooking SIGUSR1\n"); if((find_event(sigusr2) != -1) && (setup_signal(SIGUSR2, catch_sigusr2) == SIG_ERR)) fprintf(stderr, "dzen: error hooking SIGUSR2\n"); if(setup_signal(SIGALRM, catch_alrm) == SIG_ERR) fprintf(stderr, "dzen: error hooking SIGALARM\n"); set_alignment(); if(dzen.slave_win.ishmenu && !dzen.slave_win.max_lines) dzen.slave_win.max_lines = 1; x_create_windows(); if(!dzen.slave_win.ishmenu) x_map_window(dzen.title_win.win); else { XMapRaised(dzen.dpy, dzen.slave_win.win); for(i=0; i < dzen.slave_win.max_lines; i++) XMapWindow(dzen.dpy, dzen.slave_win.line[i]); } do_action(onstart); /* main loop */ event_loop(); do_action(onexit); clean_up(); if(dzen.ret_val) return dzen.ret_val; return EXIT_SUCCESS; }
void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) { last_button_state=0; xmbstring=NULL; event_id=0; x11_window=0; last_click_ms=0; args=OS::get_singleton()->get_cmdline_args(); current_videomode=p_desired; main_loop=NULL; last_timestamp=0; last_mouse_pos_valid=false; last_keyrelease_time=0; if (get_render_thread_mode()==RENDER_SEPARATE_THREAD) { XInitThreads(); } /** XLIB INITIALIZATION **/ x11_display = XOpenDisplay(NULL); char * modifiers = XSetLocaleModifiers ("@im=none"); ERR_FAIL_COND( modifiers == NULL ); xim = XOpenIM (x11_display, NULL, NULL, NULL); if (xim == NULL) { WARN_PRINT("XOpenIM failed"); xim_style=0L; } else { ::XIMStyles *xim_styles=NULL; xim_style=0L; char *imvalret=NULL; imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL); if (imvalret != NULL || xim_styles == NULL) { fprintf (stderr, "Input method doesn't support any styles\n"); } if (xim_styles) { xim_style = 0L; for (int i=0;i<xim_styles->count_styles;i++) { if (xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) { xim_style = xim_styles->supported_styles[i]; break; } } XFree (xim_styles); } XFree( imvalret ); } /* char* windowid = getenv("GODOT_WINDOWID"); if (windowid) { //freopen("/home/punto/stdout", "w", stdout); //reopen("/home/punto/stderr", "w", stderr); x11_window = atol(windowid); XWindowAttributes xwa; XGetWindowAttributes(x11_display,x11_window,&xwa); current_videomode.width = xwa.width; current_videomode.height = xwa.height; }; */ // maybe contextgl wants to be in charge of creating the window //print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height)); #if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED) context_gl = memnew( ContextGL_X11( x11_display, x11_window,current_videomode, false ) ); context_gl->initialize(); rasterizer = memnew( RasterizerGLES2 ); #endif visual_server = memnew( VisualServerRaster(rasterizer) ); if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) { visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD)); } #if 1 // NEW_WM_API // borderless fullscreen window mode if (current_videomode.fullscreen) { // needed for lxde/openbox, possibly others Hints hints; Atom property; hints.flags = 2; hints.decorations = 0; property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True); XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); XMapRaised(x11_display, x11_window); XWindowAttributes xwa; XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa); XMoveResizeWindow(x11_display, x11_window, 0, 0, xwa.width, xwa.height); // code for netwm-compliants XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False); memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.window = x11_window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = 1; xev.xclient.data.l[1] = fullscreen; xev.xclient.data.l[2] = 0; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureNotifyMask, &xev); } // disable resizable window if (!current_videomode.resizable) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = PMinSize | PMaxSize; XWindowAttributes xwa; if (current_videomode.fullscreen) { XGetWindowAttributes(x11_display,DefaultRootWindow(x11_display),&xwa); } else { XGetWindowAttributes(x11_display,x11_window,&xwa); } xsh->min_width = xwa.width; xsh->max_width = xwa.width; xsh->min_height = xwa.height; xsh->max_height = xwa.height; XSetWMNormalHints(x11_display, x11_window, xsh); XFree(xsh); } #else capture_idle = 0; minimized = false; maximized = false; if (current_videomode.fullscreen) { //set_wm_border(false); set_wm_fullscreen(true); } if (!current_videomode.resizable) { int screen = get_current_screen(); Size2i screen_size = get_screen_size(screen); set_window_size(screen_size); set_window_resizable(false); } #endif AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton(); audio_driver_index=p_audio_driver; if (AudioDriverManagerSW::get_driver(p_audio_driver)->init()!=OK) { bool success=false; audio_driver_index=-1; for(int i=0;i<AudioDriverManagerSW::get_driver_count();i++) { if (i==p_audio_driver) continue; AudioDriverManagerSW::get_driver(i)->set_singleton(); if (AudioDriverManagerSW::get_driver(i)->init()==OK) { success=true; print_line("Audio Driver Failed: "+String(AudioDriverManagerSW::get_driver(p_audio_driver)->get_name())); print_line("Using alternate audio driver: "+String(AudioDriverManagerSW::get_driver(i)->get_name())); audio_driver_index=i; break; } } if (!success) { ERR_PRINT("Initializing audio failed."); } } sample_manager = memnew( SampleManagerMallocSW ); audio_server = memnew( AudioServerSW(sample_manager) ); audio_server->init(); spatial_sound_server = memnew( SpatialSoundServerSW ); spatial_sound_server->init(); spatial_sound_2d_server = memnew( SpatialSound2DServerSW ); spatial_sound_2d_server->init(); ERR_FAIL_COND(!visual_server); ERR_FAIL_COND(x11_window==0); XSetWindowAttributes new_attr; new_attr.event_mask=KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask | KeymapStateMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | SubstructureNotifyMask | SubstructureRedirectMask | FocusChangeMask | PropertyChangeMask | ColormapChangeMask | OwnerGrabButtonMask; XChangeWindowAttributes(x11_display, x11_window,CWEventMask,&new_attr); XClassHint* classHint; /* set the titlebar name */ XStoreName(x11_display, x11_window, "Godot"); /* set the name and class hints for the window manager to use */ classHint = XAllocClassHint(); if (classHint) { classHint->res_name = (char *)"Godot"; classHint->res_class = (char *)"Godot"; } XSetClassHint(x11_display, x11_window, classHint); XFree(classHint); wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true); XSetWMProtocols(x11_display, x11_window, &wm_delete, 1); if (xim && xim_style) { xic = XCreateIC (xim,XNInputStyle, xim_style,XNClientWindow,x11_window,XNFocusWindow, x11_window, (char*)NULL); } else { xic=NULL; WARN_PRINT("XCreateIC couldn't create xic"); } XcursorSetTheme(x11_display,"default"); cursor_size = XcursorGetDefaultSize(x11_display); cursor_theme = XcursorGetTheme(x11_display); if (!cursor_theme) { print_line("not found theme"); cursor_theme="default"; } for(int i=0;i<CURSOR_MAX;i++) { cursors[i]=None; img[i]=NULL; } current_cursor=CURSOR_ARROW; if (cursor_theme) { //print_line("cursor theme: "+String(cursor_theme)); for(int i=0;i<CURSOR_MAX;i++) { static const char *cursor_file[]={ "left_ptr", "xterm", "hand2", "cross", "watch", "left_ptr_watch", "fleur", "hand1", "X_cursor", "sb_v_double_arrow", "sb_h_double_arrow", "size_bdiag", "size_fdiag", "hand1", "sb_v_double_arrow", "sb_h_double_arrow", "question_arrow" }; img[i] = XcursorLibraryLoadImage(cursor_file[i],cursor_theme,cursor_size); if (img[i]) { cursors[i]=XcursorImageLoadCursor(x11_display,img[i]); //print_line("found cursor: "+String(cursor_file[i])+" id "+itos(cursors[i])); } else { if (OS::is_stdout_verbose()) print_line("failed cursor: "+String(cursor_file[i])); } } } { Pixmap cursormask; XGCValues xgc; GC gc; XColor col; Cursor cursor; cursormask = XCreatePixmap(x11_display, RootWindow(x11_display,DefaultScreen(x11_display)), 1, 1, 1); xgc.function = GXclear; gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc); XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1); col.pixel = 0; col.red = 0; col.flags = 4; cursor = XCreatePixmapCursor(x11_display, cursormask, cursormask, &col, &col, 0, 0); XFreePixmap(x11_display, cursormask); XFreeGC(x11_display, gc); if (cursor == None) { ERR_PRINT("FAILED CREATING CURSOR"); } null_cursor=cursor; } set_cursor_shape(CURSOR_BUSY); visual_server->init(); // physics_server = memnew( PhysicsServerSW ); physics_server->init(); //physics_2d_server = memnew( Physics2DServerSW ); physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>(); physics_2d_server->init(); input = memnew( InputDefault ); #ifdef JOYDEV_ENABLED joystick = memnew( joystick_linux(input)); #endif _ensure_data_dir(); }
static void x_map_window(Window win) { XMapRaised(dzen.dpy, win); XSync(dzen.dpy, False); }
void DisplayAboutWindow (void) { XMapRaised (dpy, aboutWindow); XMoveWindow (dpy, aboutWindow, (DisplayWidth (dpy, iScreen) - ABOUT_WINDOW_WIDTH) / 2, (DisplayHeight (dpy, iScreen) - ABOUT_WINDOW_HEIGHT) / 2); }
///////////////////////////////////////////////////////// // createMess // ///////////////////////////////////////////////////////// bool gemglxwindow :: create(void) { bool success=true; /* * hmm, this crashes when enabled * when disabled, we don't get textures on two screens */ //~#warning context-sharing disabled bool context_sharing=false; if(!m_context && context_sharing) { /* gemglxwindow::PIMPL::s_shared.count(m_display)>0 */ gemglxwindow::PIMPL*sharedPimpl=&gemglxwindow::PIMPL::s_shared[m_display]; if(!sharedPimpl->glxcontext) { try { int x=0, y=0; unsigned int w=1, h=1; success=sharedPimpl->create(m_display, 2, false, false, x, y, w, h, m_transparent); } catch (GemException&ex) { error("creation of shared glxcontext failed: %s", ex.what()); verbose(0, "continuing at your own risk!"); } if(!sharedPimpl->gemcontext) { try { sharedPimpl->gemcontext = createContext(); } catch (GemException&ex) { sharedPimpl->gemcontext = NULL; error("creation of shared gem::context failed: %s", ex.what()); } } } m_context=sharedPimpl->gemcontext; } else { // no context sharing /* creation of gem::Context is deferred until *after* window creation */ } int modeNum=4; #ifdef HAVE_LIBXXF86VM XF86VidModeModeInfo **modes; #endif char svalue[3]; snprintf(svalue, 3, "%d", m_fsaa); svalue[2]=0; if (m_fsaa!=0) { setenv("__GL_FSAA_MODE", svalue, 1); // this works only for NVIDIA-cards } try { success=m_pimpl->create(m_display, m_buffer, m_fullscreen, m_border, m_xoffset, m_yoffset, m_width, m_height, m_transparent); } catch (GemException&x) { x.report(); success=false; } if(!success) { return false; } /* create a gem::context if we don't already have (a shared) one */ if(!m_context) { try { m_context = createContext(); } catch (GemException&x) { m_context = NULL; error("creation of gem::context failed: %s", x.what()); } } XMapRaised(m_pimpl->dpy, m_pimpl->win); // XMapWindow(m_pimpl->dpy, m_pimpl->win); XEvent report; XIfEvent(m_pimpl->dpy, &report, WaitForNotify, (char*)m_pimpl->win); if (glXIsDirect(m_pimpl->dpy, m_pimpl->glxcontext)) { post("Direct Rendering enabled!"); } cursorMess(m_cursor); titleMess(m_title); return createGemWindow(); }
int main(int argc, char **argv) { char curs[] = {0, 0, 0, 0, 0, 0, 0, 0}; char buf[32], passwd[256], passdisp[256]; int num, screen, width, height, update, sleepmode, term, pid; #ifndef HAVE_BSD_AUTH const char *pws; #endif unsigned int len; Bool running = True; Cursor invisible; Display *dpy; KeySym ksym; Pixmap pmap; Window root, w; XColor black, red, dummy; XEvent ev; XSetWindowAttributes wa; XFontStruct* font; GC gc; XGCValues values; // defaults char* passchar = "*"; char* fontname = "-*-dejavu sans-bold-r-*-*-*-420-100-100-*-*-iso8859-1"; char* username = "******"; int showline = 1; for (int i = 0; i < argc; i++) { if (!strcmp(argv[i], "-c")) { if (i + 1 < argc) passchar = argv[i + 1]; else die("error: no password character given.\n"); } else if (!strcmp(argv[i], "-f")) { if (i + 1 < argc) fontname = argv[i + 1]; else die("error: font not specified.\n"); }else if (!strcmp(argv[i], "-u")) { if (i + 1 < argc) username = argv[i + 1]; else die("error: username not specified.\n"); } else if (!strcmp(argv[i], "-v")) die("sflock-"VERSION", © 2010 Ben Ruijl\n"); else if (!strcmp(argv[i], "-h")) showline = 0; else if (!strcmp(argv[i], "?")) die("usage: sflock [-v] [-c passchars] [-f fontname] [-u username]\n"); } // fill with password characters for (int i = 0; i < sizeof passdisp; i+= strlen(passchar)) for (int j = 0; j < strlen(passchar); j++) passdisp[i + j] = passchar[j]; /* disable tty switching */ if ((term = open("/dev/console", O_RDWR)) == -1) { perror("error opening console"); } if ((ioctl(term, VT_LOCKSWITCH)) == -1) { perror("error locking console"); } /* deamonize */ pid = fork(); if (pid < 0) die("Could not fork sflock."); if (pid > 0) exit(0); // exit parent #ifndef HAVE_BSD_AUTH pws = get_password(username); #else username = getlogin(); #endif if(!(dpy = XOpenDisplay(0))) die("sflock: cannot open dpy\n"); screen = DefaultScreen(dpy); root = RootWindow(dpy, screen); width = DisplayWidth(dpy, screen); height = DisplayHeight(dpy, screen); wa.override_redirect = 1; wa.background_pixel = XBlackPixel(dpy, screen); w = XCreateWindow(dpy, root, 0, 0, width, height, 0, DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa); XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "orange red", &red, &dummy); XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy); pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8); invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0); XDefineCursor(dpy, w, invisible); XMapRaised(dpy, w); font = XLoadQueryFont(dpy, fontname); if (font == 0) { die("error: could not find font. Try using a full description.\n"); } gc = XCreateGC(dpy, w, (unsigned long)0, &values); XSetFont(dpy, gc, font->fid); XSetForeground(dpy, gc, XWhitePixel(dpy, screen)); for(len = 1000; len; len--) { if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess) break; usleep(1000); } if((running = running && (len > 0))) { for(len = 1000; len; len--) { if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess) break; usleep(1000); } running = (len > 0); } len = 0; XSync(dpy, False); update = True; sleepmode = False; /* main event loop */ while(running && !XNextEvent(dpy, &ev)) { if (sleepmode) { DPMSEnable(dpy); DPMSForceLevel(dpy, DPMSModeOff); XFlush(dpy); } if (update) { int x, y, dir, ascent, descent; XCharStruct overall; XClearWindow(dpy, w); XTextExtents (font, passdisp, len, &dir, &ascent, &descent, &overall); x = (width - overall.width) / 2; y = (height + ascent - descent) / 2; XDrawString(dpy,w,gc, (width - XTextWidth(font, username, strlen(username))) / 2, y - ascent - 20, username, strlen(username)); if (showline) XDrawLine(dpy, w, gc, width * 3 / 8 , y - ascent - 10, width * 5 / 8, y - ascent - 10); XDrawString(dpy,w,gc, x, y, passdisp, len); update = False; } if (ev.type == MotionNotify) { sleepmode = False; } if(ev.type == KeyPress) { sleepmode = False; buf[0] = 0; num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0); if(IsKeypadKey(ksym)) { if(ksym == XK_KP_Enter) ksym = XK_Return; else if(ksym >= XK_KP_0 && ksym <= XK_KP_9) ksym = (ksym - XK_KP_0) + XK_0; } if(IsFunctionKey(ksym) || IsKeypadKey(ksym) || IsMiscFunctionKey(ksym) || IsPFKey(ksym) || IsPrivateKeypadKey(ksym)) continue; switch(ksym) { case XK_Return: passwd[len] = 0; #ifdef HAVE_BSD_AUTH running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd); #else running = strcmp(crypt(passwd, pws), pws); #endif if (running != 0) // change background on wrong password XSetWindowBackground(dpy, w, red.pixel); len = 0; break; case XK_Escape: len = 0; if (DPMSCapable(dpy)) { sleepmode = True; } break; case XK_BackSpace: if(len) --len; break; default: if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) { memcpy(passwd + len, buf, num); len += num; } break; } update = True; // show changes } } /* free and unlock */ setreuid(geteuid(), 0); if ((ioctl(term, VT_UNLOCKSWITCH)) == -1) { perror("error unlocking console"); } close(term); setuid(getuid()); // drop rights permanently XUngrabPointer(dpy, CurrentTime); XFreePixmap(dpy, pmap); XFreeFont(dpy, font); XFreeGC(dpy, gc); XDestroyWindow(dpy, w); XCloseDisplay(dpy); return 0; }
void do_map_and_raise(Window window){ XMapRaised(display, window); }
int init_window() { wa.w = 0; wa.glx_context = NULL; wa.vHandle = wa.fHandle = wa.pHandle = 0; wa.cmap = 0; #ifdef SHOW_TEXT wa.font = NULL; #endif wa.dpy = XOpenDisplay(NULL); if (!wa.dpy) return 1; int attrList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 4, GLX_GREEN_SIZE, 4, GLX_BLUE_SIZE, 4, None}; XVisualInfo * vinfo = glXChooseVisual(wa.dpy, DefaultScreen(wa.dpy), attrList); if (!vinfo) { printf("Unable to acquire visual\n"); wa.dpy = NULL; return 1; } XSetWindowAttributes swa; swa.event_mask = ButtonPressMask | KeyPressMask | PointerMotionMask | StructureNotifyMask; swa.colormap = XCreateColormap(wa.dpy, RootWindow(wa.dpy, vinfo->screen), vinfo->visual, AllocNone); wa.cmap = swa.colormap; #ifdef FULLSCREEN swa.override_redirect = 1; #endif wa.w = XCreateWindow(wa.dpy, DefaultRootWindow(wa.dpy), 0, 0, DisplayWidth(wa.dpy, vinfo->screen), DisplayHeight(wa.dpy, vinfo->screen), 0, 0, CopyFromParent, vinfo->visual, #ifdef FULLSCREEN CWColormap | CWEventMask | CWOverrideRedirect, #else CWColormap | CWEventMask, #endif &swa); if (!wa.w) { printf("Unable to create window\n"); return 1; } wa.width = DisplayWidth(wa.dpy, vinfo->screen); wa.height = DisplayHeight(wa.dpy, vinfo->screen); wa.glx_context = glXCreateContext(wa.dpy, vinfo, NULL, True); XFree(vinfo); if (!wa.glx_context) { printf("Unable to create context\n"); return 1; } if (!glXMakeCurrent(wa.dpy, wa.w, wa.glx_context)) { printf("glXMakeCurrent failed\n"); return 1; } wa.vHandle = compileShader(vShader, GL_VERTEX_SHADER); wa.fHandle = compileShader(fShader, GL_FRAGMENT_SHADER); wa.pHandle = createProgram(wa.vHandle, wa.fHandle); if (!wa.vHandle || !wa.fHandle || !wa.pHandle) { printf("Compile failed\n"); return 1; } glUseProgram(wa.pHandle); #ifdef SHOW_TEXT wa.font = XLoadQueryFont(wa.dpy, FONT_USED); if (!wa.font) { printf("Font not found\n"); return 1; } #endif initGL(wa.dpy, wa.w, wa.pHandle #ifdef SHOW_TEXT , wa.font #endif ); XMapRaised(wa.dpy, wa.w); #ifdef FULLSCREEN XGrabKeyboard(wa.dpy, wa.w, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(wa.dpy, wa.w, True, PointerMotionMask, GrabModeAsync, GrabModeAsync, wa.w, None, CurrentTime); #endif return 0; }
void _glfwPlatformShowWindow(_GLFWwindow* window) { XMapRaised(_glfw.x11.display, window->x11.handle); XFlush(_glfw.x11.display); }
/* FIXME: bits is currently unused */ Bool createGLWindow(char* title, int width, int height, int bits, Bool fullscreenflag) { XVisualInfo *vi; Colormap cmap; int dpyWidth, dpyHeight; int i; int glxMajorVersion, glxMinorVersion; int vidModeMajorVersion, vidModeMinorVersion; XF86VidModeModeInfo **modes; int modeNum; int bestMode; Atom wmDelete; Window winDummy; unsigned int borderDummy; GLWin.fs = fullscreenflag; /* set best mode to current */ bestMode = 0; /* get a connection */ GLWin.dpy = XOpenDisplay(0); GLWin.screen = DefaultScreen(GLWin.dpy); XF86VidModeQueryVersion(GLWin.dpy, &vidModeMajorVersion, &vidModeMinorVersion); printf("XF86VidModeExtension-Version %d.%d\n", vidModeMajorVersion, vidModeMinorVersion); XF86VidModeGetAllModeLines(GLWin.dpy, GLWin.screen, &modeNum, &modes); /* save desktop-resolution before switching modes */ GLWin.deskMode = *modes[0]; /* look for mode with requested resolution */ for (i = 0; i < modeNum; i++) { if ((modes[i]->hdisplay == width) && (modes[i]->vdisplay == height)) { bestMode = i; } } /* get an appropriate visual */ vi = glXChooseVisual(GLWin.dpy, GLWin.screen, attrListDbl); if (vi == NULL) { vi = glXChooseVisual(GLWin.dpy, GLWin.screen, attrListSgl); printf("Only Singlebuffered Visual!\n"); } else { printf("Got Doublebuffered Visual!\n"); } glXQueryVersion(GLWin.dpy, &glxMajorVersion, &glxMinorVersion); printf("glX-Version %d.%d\n", glxMajorVersion, glxMinorVersion); /* create a GLX context */ GLWin.ctx = glXCreateContext(GLWin.dpy, vi, 0, GL_TRUE); /* create a color map */ cmap = XCreateColormap(GLWin.dpy, RootWindow(GLWin.dpy, vi->screen), vi->visual, AllocNone); GLWin.attr.colormap = cmap; GLWin.attr.border_pixel = 0; if (GLWin.fs) { XF86VidModeSwitchToMode(GLWin.dpy, GLWin.screen, modes[bestMode]); XF86VidModeSetViewPort(GLWin.dpy, GLWin.screen, 0, 0); dpyWidth = modes[bestMode]->hdisplay; dpyHeight = modes[bestMode]->vdisplay; printf("Resolution %dx%d\n", dpyWidth, dpyHeight); XFree(modes); /* create a fullscreen window */ GLWin.attr.override_redirect = True; GLWin.attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask; GLWin.win = XCreateWindow(GLWin.dpy, RootWindow(GLWin.dpy, vi->screen), 0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &GLWin.attr); XWarpPointer(GLWin.dpy, None, GLWin.win, 0, 0, 0, 0, 0, 0); XMapRaised(GLWin.dpy, GLWin.win); XGrabKeyboard(GLWin.dpy, GLWin.win, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(GLWin.dpy, GLWin.win, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, GLWin.win, None, CurrentTime); } else { /* create a window in window mode*/ GLWin.attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask; GLWin.win = XCreateWindow(GLWin.dpy, RootWindow(GLWin.dpy, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &GLWin.attr); /* only set window title and handle wm_delete_events if in windowed mode */ wmDelete = XInternAtom(GLWin.dpy, "WM_DELETE_WINDOW", True); XSetWMProtocols(GLWin.dpy, GLWin.win, &wmDelete, 1); XSetStandardProperties(GLWin.dpy, GLWin.win, title, title, None, NULL, 0, NULL); XMapRaised(GLWin.dpy, GLWin.win); } /* connect the glx-context to the window */ glXMakeCurrent(GLWin.dpy, GLWin.win, GLWin.ctx); XGetGeometry(GLWin.dpy, GLWin.win, &winDummy, &GLWin.x, &GLWin.y, &GLWin.width, &GLWin.height, &borderDummy, &GLWin.depth); printf("Depth %d\n", GLWin.depth); if (glXIsDirect(GLWin.dpy, GLWin.ctx)) printf("Congrats, you have Direct Rendering!\n"); else printf("Sorry, no Direct Rendering possible!\n"); if (!initGL()) { printf("Could not initialize OpenGL.\nAborting...\n"); return False; } return True; }
/****************************************************************************** MakeMeWindow - Create and setup the window we will need ******************************************************************************/ void MakeMeWindow(void) { XSizeHints hints; XGCValues gcval; unsigned long gcmask; unsigned int dummy1, dummy2; int x, y, ret, count; Window dummyroot, dummychild; int i; if ((count = ItemCountD(&windows))==0 && Transient) ShutMeDown(0); AdjustWindow(); hints.width=win_width; hints.height=win_height; hints.win_gravity=NorthWestGravity; hints.flags=PSize|PWinGravity|PResizeInc; hints.width_inc=0; hints.height_inc=0; if (geometry!= NULL) { ret=XParseGeometry(geometry,&x,&y,&dummy1,&dummy2); if (ret&XValue && ret &YValue) { hints.x=x; if (ret&XNegative) hints.x+=XDisplayWidth(dpy,screen)-win_width; hints.y=y; if (ret&YNegative) hints.y+=XDisplayHeight(dpy,screen)-win_height; hints.flags|=USPosition; } if (ret&XNegative) { if (ret&YNegative) hints.win_gravity=SouthEastGravity; else hints.win_gravity=NorthEastGravity; } else { if (ret&YNegative) hints.win_gravity=SouthWestGravity; else hints.win_gravity=NorthWestGravity; } } if (Transient) { XQueryPointer(dpy,Root,&dummyroot,&dummychild,&hints.x,&hints.y,&x,&y,&dummy1); hints.win_gravity=NorthWestGravity; hints.flags |= USPosition; } win_grav=hints.win_gravity; win_x=hints.x; win_y=hints.y; for (i = 0; i != MAX_COLOUR_SETS; i++) if(d_depth < 2) { back[i] = GetColor("white"); fore[i] = GetColor("black"); } else { back[i] = GetColor(BackColor[i] == NULL ? BackColor[0] : BackColor[i]); fore[i] = GetColor(ForeColor[i] == NULL ? ForeColor[0] : ForeColor[i]); } win=XCreateSimpleWindow(dpy,Root,hints.x,hints.y,hints.width,hints.height,1, fore[0],back[0]); wm_del_win=XInternAtom(dpy,"WM_DELETE_WINDOW",False); XSetWMProtocols(dpy,win,&wm_del_win,1); XSetWMNormalHints(dpy,win,&hints); if (!Transient) { XGrabButton(dpy,1,AnyModifier,win,True,GRAB_EVENTS,GrabModeAsync, GrabModeAsync,None,None); XGrabButton(dpy,2,AnyModifier,win,True,GRAB_EVENTS,GrabModeAsync, GrabModeAsync,None,None); XGrabButton(dpy,3,AnyModifier,win,True,GRAB_EVENTS,GrabModeAsync, GrabModeAsync,None,None); SetMwmHints(MWM_DECOR_ALL|MWM_DECOR_RESIZEH|MWM_DECOR_MAXIMIZE|MWM_DECOR_MINIMIZE, MWM_FUNC_ALL|MWM_FUNC_RESIZE|MWM_FUNC_MAXIMIZE|MWM_FUNC_MINIMIZE, MWM_INPUT_MODELESS); } else { SetMwmHints(0,MWM_FUNC_ALL,MWM_INPUT_MODELESS); } for (i = 0; i != MAX_COLOUR_SETS; i++) { gcval.foreground=fore[i]; gcval.background=back[i]; gcval.font=ButtonFont->fid; gcmask=GCForeground|GCBackground|GCFont; graph[i]=XCreateGC(dpy,Root,gcmask,&gcval); if(d_depth < 2) gcval.foreground=GetShadow(fore[i]); else gcval.foreground=GetShadow(back[i]); gcval.background=back[i]; gcmask=GCForeground|GCBackground; shadow[i]=XCreateGC(dpy,Root,gcmask,&gcval); gcval.foreground=GetHilite(back[i]); gcval.background=back[i]; gcmask=GCForeground|GCBackground; hilite[i]=XCreateGC(dpy,Root,gcmask,&gcval); gcval.foreground=back[i]; gcmask=GCForeground; background[i]=XCreateGC(dpy,Root,gcmask,&gcval); } XSelectInput(dpy,win,(ExposureMask | KeyPressMask)); ChangeWindowName(&Module[1]); if (ItemCountD(&windows) > 0) { XMapRaised(dpy,win); WaitForExpose(); WindowIsUp=1; } else WindowIsUp=2; if (Transient) { if ( XGrabPointer(dpy,win,True,GRAB_EVENTS,GrabModeAsync,GrabModeAsync, None,None,CurrentTime)!=GrabSuccess) ShutMeDown(1); XQueryPointer(dpy,Root,&dummyroot,&dummychild,&hints.x,&hints.y,&x,&y,&dummy1); if (!SomeButtonDown(dummy1)) ShutMeDown(0); } }
bool video::init_window(int xsize, int ysize) { { //enclose local variables before fail label g_sizex = xsize; g_sizey = ysize; // Open the display if (!dpy) { dpy = XOpenDisplay(display_name); if (!dpy) { fprintf(stderr, "Can't open X11 display %s\n", XDisplayName(display_name)); goto fail; } } int theScreen = DefaultScreen(dpy); scrn = ScreenOfDisplay(dpy, theScreen); dispdepth = DefaultDepth(dpy, theScreen); XVisualInfo vinfo; if (!( (dispdepth >= 15 && dispdepth <= 32 && XMatchVisualInfo(dpy, theScreen, dispdepth, TrueColor, &vinfo) ) || XMatchVisualInfo(dpy, theScreen, 24, TrueColor, &vinfo) || XMatchVisualInfo(dpy, theScreen, 32, TrueColor, &vinfo) || XMatchVisualInfo(dpy, theScreen, 16, TrueColor, &vinfo) || XMatchVisualInfo(dpy, theScreen, 15, TrueColor, &vinfo) )) { fprintf(stderr, "Display has no appropriate True Color visual\n"); goto fail; } vis = vinfo.visual; depth = dispdepth = vinfo.depth; mask2bits(vinfo.red_mask, red_mask, red_shift); mask2bits(vinfo.green_mask, green_mask, green_shift); mask2bits(vinfo.blue_mask, blue_mask, blue_shift); rootW = RootWindow(dpy, theScreen); cmap = XCreateColormap(dpy, rootW, vis, AllocNone); XSetWindowAttributes attrs; attrs.backing_store = Always; attrs.colormap = cmap; attrs.event_mask = StructureNotifyMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask; attrs.background_pixel = BlackPixelOfScreen(scrn); attrs.border_pixel = WhitePixelOfScreen(scrn); win = XCreateWindow(dpy, rootW, 0, 0, xsize, ysize, 2, dispdepth, InputOutput, vis, CWBackingStore | CWColormap | CWEventMask | CWBackPixel | CWBorderPixel, &attrs); if(!win) { fprintf(stderr, "Can't create the window\n"); goto fail; } XSizeHints sh; sh.flags = PSize | PMinSize | PMaxSize; sh.width = sh.min_width = sh.max_width = xsize; sh.height = sh.min_height = sh.max_height = ysize; XSetStandardProperties( dpy, win, g_video->title, g_video->title, None, NULL, 0, &sh ); _XA_WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", false); XSetWMProtocols(dpy, win, &_XA_WM_DELETE_WINDOW, 1); gc = XCreateGC(dpy, win, 0L, &xgcv); XMapRaised(dpy, win); XFlush(dpy); #ifdef X_FULLSYNC XSynchronize(dpy, true); #endif XSetErrorHandler(xerr_handler); int imgbytes = xsize*ysize*(dispdepth<=16?2:4); const char *vidstr; #ifndef X_NOSHMEM int major, minor, pixmaps; if(XShmQueryExtension(dpy) && XShmQueryVersion(dpy, &major, &minor, &pixmaps)) { // Shared memory if(NULL!=getenv(NOSHMEM_env_var_name) && 0!=strcmp("0",getenv(NOSHMEM_env_var_name))) { goto generic; } shmseginfo.shmid = shmget(IPC_PRIVATE, imgbytes, IPC_CREAT|0777); if(shmseginfo.shmid < 0) { fprintf(stderr, "Warning: Can't get shared memory: %s\n", strerror(errno)); goto generic; } g_pImg = (unsigned int*)(shmseginfo.shmaddr = (char*)shmat(shmseginfo.shmid, 0, 0)); if(g_pImg == (unsigned int*)-1) { fprintf(stderr, "Warning: Can't attach to shared memory: %s\n", strerror(errno)); shmctl(shmseginfo.shmid, IPC_RMID, NULL); goto generic; } shmseginfo.readOnly = false; if(!XShmAttach(dpy, &shmseginfo) || x_error) { char err[256]; XGetErrorText(dpy, x_error, err, 255); fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error); shmdt(shmseginfo.shmaddr); shmctl(shmseginfo.shmid, IPC_RMID, NULL); goto generic; } already_called_X_ShmAttach = true; #ifndef X_NOSHMPIX if(pixmaps && XShmPixmapFormat(dpy) == ZPixmap) { // Pixmaps vidtype = 2; vidstr = "X11 shared memory pixmap"; pixmap = XShmCreatePixmap(dpy, win, (char*)g_pImg, &shmseginfo, xsize, ysize, dispdepth); XSetWindowBackgroundPixmap(dpy, win, pixmap); } else #endif//!X_NOSHMPIX { // Standard vidtype = 1; vidstr = "X11 shared memory"; ximage = XShmCreateImage(dpy, vis, dispdepth, ZPixmap, 0, &shmseginfo, xsize, ysize); if(!ximage) { fprintf(stderr, "Can't create the shared image\n"); goto fail; } assert(ximage->bytes_per_line == xsize*(dispdepth<=16?2:4)); ximage->data = shmseginfo.shmaddr; } } else #endif { #ifndef X_NOSHMEM generic: #endif vidtype = 0; vidstr = "generic X11"; g_pImg = new unsigned int[imgbytes/sizeof(int)]; ximage = XCreateImage(dpy, vis, dispdepth, ZPixmap, 0, (char*)g_pImg, xsize, ysize, 32, imgbytes/ysize); if(!ximage) { fprintf(stderr, "Can't create the image\n"); goto fail; } } // Note: It may be more efficient to adopt the server's byte order // and swap once per get_color() call instead of once per pixel. const uint32_t probe = 0x03020100; const bool big_endian = (((const char*)(&probe))[0]==0x03); ximage->byte_order = big_endian ? MSBFirst : LSBFirst; printf("Note: using %s with %s visual for %d-bit color depth\n", vidstr, vis==DefaultVisual(dpy, theScreen)?"default":"non-default", dispdepth); running = true; return true; } // end of enclosing local variables fail: terminate(); init_console(); return false; }
int lockScreen(void) { XSetWindowAttributes attr, attr1, attr2; Pixmap shape, pic, lock, shp, bg_pic, bg_shp; int screen_number = 0; long win_mask = CWBackPixel | CWBorderPixel | CWOverrideRedirect; if (is_blocked()) return 0; set_blocked(1); x = 5; y = 35; (dsp) = XOpenDisplay(":0.0"); if ((dsp) == NULL) { write_log("Could not open Display 0:0\n"); return (-1); } dW = XDisplayWidth(dsp, screen_number); dH = XDisplayHeight(dsp, screen_number); root = XRootWindow(dsp, screen_number); /* If a extern XPM background file specified on the command line */ if (background_filename != NULL) { if (XpmReadFileToPixmap (dsp, root, background_filename, &bg_pic, &bg_shp, NULL) != XpmOpenFailed) win_mask = CWBackPixmap | CWBorderPixel | CWOverrideRedirect; } attr.background_pixel = 700; attr.background_pixmap = bg_pic; attr.border_pixel = 100; attr.override_redirect = True; (wnd1) = XCreateWindow(dsp, root, 0, 0, dW, dH, 0, CopyFromParent, CopyFromParent, CopyFromParent, win_mask, &attr); XMapRaised(dsp, wnd1); if (logo_filename != NULL) { XpmReadFileToPixmap(dsp, root, logo_filename, &pic, &shape, NULL); } attr1.background_pixmap = pic; logo = XCreateWindow(dsp, wnd1, dW - 150, 0, 150, 30, 0, CopyFromParent, CopyFromParent, CopyFromParent, CWBackPixmap, &attr1); XMapWindow(dsp, logo); logo2 = XCreateSimpleWindow(dsp, wnd1, 0, 0, dW - 150, 30, 0, 0, 300); XMapWindow(dsp, logo2); if (foreground_filename != NULL) { XpmReadFileToPixmap(dsp, root, foreground_filename, &lock, &shp, NULL); } attr2.background_pixmap = lock; wnd = XCreateWindow(dsp, wnd1, dW / 2 - 150, dH / 2 - 100, 300, 200, 0, CopyFromParent, CopyFromParent, CopyFromParent, CWBackPixmap, &attr2); //wnd = XCreateSimpleWindow(dsp, wnd1, x, y, 200, 200, 1, 0, 400); XMapWindow(dsp, wnd); XGrabPointer(dsp, wnd1, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); XGrabKeyboard(dsp, wnd1, False, GrabModeAsync, GrabModeAsync, CurrentTime); XSelectInput(dsp, wnd1, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ShiftMask | LockMask | ControlMask | Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask); write_log_fmt("locking screen\n"); return (0); }
void* mfb_open(const char* title, int width, int height, unsigned int flags, int scale) { XSetWindowAttributes windowAttributes; XSizeHints sizeHints; XImage* image; Window window; WindowInfo* window_info; if (!setup_display()) { return 0; } //TODO: Handle no title/borderless (void)flags; width *= scale; height *= scale; Window defaultRootWindow = DefaultRootWindow(s_display); windowAttributes.border_pixel = BlackPixel(s_display, s_screen); windowAttributes.background_pixel = BlackPixel(s_display, s_screen); windowAttributes.backing_store = NotUseful; window = XCreateWindow(s_display, defaultRootWindow, (s_screen_width - width) / 2, (s_screen_height - height) / 2, width, height, 0, s_depth, InputOutput, s_visual, CWBackPixel | CWBorderPixel | CWBackingStore, &windowAttributes); if (!window) { printf("Unable to create X11 Window\n"); return 0; } //XSelectInput(s_display, s_window, KeyPressMask | KeyReleaseMask); XStoreName(s_display, window, title); XSelectInput(s_display, window, ButtonPressMask | KeyPressMask | KeyReleaseMask | ButtonReleaseMask); if (!(flags & WINDOW_RESIZE)) { sizeHints.flags = PPosition | PMinSize | PMaxSize; sizeHints.x = 0; sizeHints.y = 0; sizeHints.min_width = width; sizeHints.max_width = width; sizeHints.min_height = height; sizeHints.max_height = height; XSetWMNormalHints(s_display, window, &sizeHints); } XClearWindow(s_display, window); XMapRaised(s_display, window); XFlush(s_display); image = XCreateImage(s_display, CopyFromParent, s_depth, ZPixmap, 0, NULL, width, height, 32, width * 4); if (!image) { XDestroyWindow(s_display, window); printf("Unable to create XImage\n"); return 0; } window_info = (WindowInfo*)malloc(sizeof(WindowInfo)); window_info->key_callback = 0; window_info->rust_data = 0; window_info->window = window; window_info->ximage = image; window_info->scale = scale; window_info->width = width; window_info->height = height; window_info->draw_buffer = malloc(width * height * 4); window_info->update = 1; XSetWMProtocols(s_display, window, &s_wm_delete_window, 1); XSaveContext(s_display, window, s_context, (XPointer) window_info); image->data = (char*)window_info->draw_buffer; s_window_count += 1; return (void*)window_info; }
int MFDisplay_CreateDisplay(int width, int height, int bpp, int rate, bool vsync, bool triplebuffer, bool wide, bool progressive) { MFCALLSTACK; MFZeroMemory(gXKeys, sizeof(gXKeys)); MFZeroMemory(&gXMouse, sizeof(gXMouse)); gXMouse.x = -1; gDisplay.fullscreenWidth = gDisplay.width = width; gDisplay.fullscreenHeight = gDisplay.height = height; gDisplay.refreshRate = 0; gDisplay.colourDepth = 0; /* Use default. Chances are, it's something sane */ gDisplay.windowed = true; gDisplay.wide = false; gDisplay.progressive = true; if(!(xdisplay = XOpenDisplay(NULL))) { MFDebug_Error("Unable to open display"); MFDisplay_DestroyDisplay(); return 1; } screen = DefaultScreen(xdisplay); rootWindow = RootWindow(xdisplay, screen); // build our internal list of available video modes GetModes(&modes, !gDisplay.windowed); while(!FindMode(modes, width, height)) { if(!gDisplay.windowed) { // no fullscreen mode, try windowed mode instead MFDebug_Warn(1, "No suitable modes for fullscreen mode, trying windowed mode"); gDisplay.windowed = true; FreeModes(); GetModes(&modes, false); } else { // default is some sort of custom mode that doesn't appear in the windowed mode list // HACK: we'll add it to the end.. modes[numModes].width = width; modes[numModes].height = height; currentMode = numModes; ++numModes; break; } } DebugMenu_AddItem("Resolution", "Display Options", &resSelect, ChangeResCallback); DebugMenu_AddItem("Apply", "Display Options", &applyDisplayMode, ApplyDisplayModeCallback); // Set full screen mode, if necessary if(!gDisplay.windowed && numModes > 1) { if(!XF86VidModeSwitchToMode(xdisplay, screen, vidModes[currentMode])) { MFDebug_Error("Unable to switch screenmodes, defaulting to windowed mode"); MFDisplay_DestroyDisplay(); return 1; } } XVisualInfo *MFRenderer_GetVisualInfo(); XVisualInfo *visualInfo = MFRenderer_GetVisualInfo(); if(!visualInfo) return 1; if(!(colorMap = XCreateColormap(xdisplay, rootWindow, visualInfo->visual, AllocNone))) { MFDebug_Error("Unable to create colourmap"); XFree(visualInfo); MFDisplay_DestroyDisplay(); return 1; } XSetWindowAttributes windowAttrs; windowAttrs.colormap = colorMap; windowAttrs.cursor = None; windowAttrs.event_mask = StructureNotifyMask; windowAttrs.border_pixel = BlackPixel(xdisplay, screen); windowAttrs.background_pixel = BlackPixel(xdisplay, screen); if(!(window = XCreateWindow(xdisplay, rootWindow, 0, 0, width, height, 0, visualInfo->depth, InputOutput, visualInfo->visual, CWBackPixel | CWBorderPixel | CWCursor | CWColormap | CWEventMask, &windowAttrs))) { MFDebug_Error("Unable to create X Window"); XFree(visualInfo); MFDisplay_DestroyDisplay(); return 1; } // Tell the window manager not to allow our window to be resized. But some window managers can ignore me and do it anyway. Typical X-Windows. if((sizeHints = XAllocSizeHints()) == NULL) { MFDebug_Error("Unable to alloc XSizeHints structure, out of memory?"); XFree(visualInfo); MFDisplay_DestroyDisplay(); return 1; } sizeHints->flags = PSize | PMinSize | PMaxSize; sizeHints->min_width = sizeHints->max_width = sizeHints->base_width = width; sizeHints->min_height = sizeHints->max_height = sizeHints->base_height = height; XSetWMNormalHints(xdisplay, window, sizeHints); // Window title XStoreName(xdisplay, window, gDefaults.display.pWindowTitle); XWMHints *wmHints; if((wmHints = XAllocWMHints()) == NULL) { MFDebug_Error("Unable to alloc XWMHints structure, out of memory?"); XFree(visualInfo); MFDisplay_DestroyDisplay(); return 1; } wmHints->flags = InputHint | StateHint; wmHints->input = true; wmHints->initial_state = NormalState; if(!XSetWMHints(xdisplay, window, wmHints)) { MFDebug_Error("Unable to set WM hints for window"); XFree(visualInfo); MFDisplay_DestroyDisplay(); return 1; } XFree(wmHints); XFree(visualInfo); // Tell the window manager that I want to be notified if the window's closed wm_delete_window = XInternAtom(xdisplay, "WM_DELETE_WINDOW", false); if(!XSetWMProtocols(xdisplay, window, &wm_delete_window, 1)) { MFDebug_Error("Unable to set Window Manager protocols"); MFDisplay_DestroyDisplay(); return 1; } XSelectInput(xdisplay, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | ExposureMask); if(!XMapRaised(xdisplay, window)) { MFDebug_Error("Unable to map new window"); MFDisplay_DestroyDisplay(); return 1; } // Wait for the window to be mapped, etc. The documentation doesn't indicate that this is necessary, but every GLX program I've ever seen does it, so I assume it is. XEvent event; XIfEvent(xdisplay, &event, WaitForNotify, (char *)window); MFRenderer_CreateDisplay(); if(!gDisplay.windowed && numModes > 1) { if(!XF86VidModeSwitchToMode(xdisplay, screen, vidModes[currentMode])) { MFDebug_Error("Unable to set screen mode"); MFDisplay_DestroyDisplay(); return 1; } XGrabPointer(xdisplay, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, None, CurrentTime); XFlush(xdisplay); // A little trick to make sure the entire window is on the screen XWarpPointer(xdisplay, None, window, 0, 0, 0, 0, width - 1, height - 1); XWarpPointer(xdisplay, None, window, 0, 0, 0, 0, 0, 0); XFlush(xdisplay); } return 0; }
void x11_window_create() { if (cfgLoadInt("pvr", "nox11", 0) == 0) { XInitThreads(); // X11 variables Window x11Window = 0; Display* x11Display = 0; long x11Screen = 0; XVisualInfo* x11Visual = 0; Colormap x11Colormap = 0; /* Step 0 - Create a NativeWindowType that we can use it for OpenGL ES output */ Window sRootWindow; XSetWindowAttributes sWA; unsigned int ui32Mask; int i32Depth; // Initializes the display and screen x11Display = XOpenDisplay(NULL); if (!x11Display && !(x11Display = XOpenDisplay(":0"))) { printf("Error: Unable to open X display\n"); return; } x11Screen = XDefaultScreen(x11Display); // Gets the window parameters sRootWindow = RootWindow(x11Display, x11Screen); int depth = CopyFromParent; #if !defined(GLES) // 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(x11Display, &glx_major, &glx_minor) || ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) { printf("Invalid GLX version"); exit(1); } int fbcount; GLXFBConfig* fbc = glXChooseFBConfig(x11Display, x11Screen, visual_attribs, &fbcount); if (!fbc) { printf("Failed to retrieve a framebuffer config\n"); exit(1); } printf("Found %d matching FB configs.\n", fbcount); GLXFBConfig bestFbc = fbc[0]; XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(x11Display, bestFbc); printf("Chosen visual ID = 0x%lx\n", vi->visualid); depth = vi->depth; x11Visual = vi; x11Colormap = XCreateColormap(x11Display, RootWindow(x11Display, x11Screen), vi->visual, AllocNone); #else i32Depth = DefaultDepth(x11Display, x11Screen); x11Visual = new XVisualInfo; XMatchVisualInfo(x11Display, x11Screen, i32Depth, TrueColor, x11Visual); if (!x11Visual) { printf("Error: Unable to acquire visual\n"); return; } x11Colormap = XCreateColormap(x11Display, sRootWindow, x11Visual->visual, AllocNone); #endif sWA.colormap = x11Colormap; // Add to these for handling other events sWA.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask; ui32Mask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap; x11_width = cfgLoadInt("x11", "width", DEFAULT_WINDOW_WIDTH); x11_height = cfgLoadInt("x11", "height", DEFAULT_WINDOW_HEIGHT); x11_fullscreen = (cfgLoadInt("x11", "fullscreen", DEFAULT_FULLSCREEN) > 0); if (x11_width < 0 || x11_height < 0) { x11_width = XDisplayWidth(x11Display, x11Screen); x11_height = XDisplayHeight(x11Display, x11Screen); } // Creates the X11 window x11Window = XCreateWindow(x11Display, RootWindow(x11Display, x11Screen), (ndcid%3)*640, (ndcid/3)*480, x11_width, x11_height, 0, depth, InputOutput, x11Visual->visual, ui32Mask, &sWA); // Capture the close window event wmDeleteMessage = XInternAtom(x11Display, "WM_DELETE_WINDOW", False); XSetWMProtocols(x11Display, x11Window, &wmDeleteMessage, 1); if(x11_fullscreen) { // fullscreen Atom wmState = XInternAtom(x11Display, "_NET_WM_STATE", False); Atom wmFullscreen = XInternAtom(x11Display, "_NET_WM_STATE_FULLSCREEN", False); XChangeProperty(x11Display, x11Window, wmState, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wmFullscreen, 1); XMapRaised(x11Display, x11Window); } else { XMapWindow(x11Display, x11Window); } #if !defined(GLES) #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*); glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB"); verify(glXCreateContextAttribsARB != 0); int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 1, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, None }; x11_glc = glXCreateContextAttribsARB(x11Display, bestFbc, 0, True, context_attribs); XSync(x11Display, False); if (!x11_glc) { die("Failed to create GL3.1 context\n"); } #endif XFlush(x11Display); //(EGLNativeDisplayType)x11Display; x11_disp = (void*)x11Display; x11_win = (void*)x11Window; x11_vis = (void*)x11Visual->visual; } else { printf("Not creating X11 window ..\n"); } }
/*--------------------------------------------------------*/ void open_gwindow_( ) { /* * create new graphics window on first entry.... */ int font,black,white; int scr_width,scr_height; int j; unsigned long valuemask; static int depth; /* number of planes */ static Visual *visual; /*VISUAL TYPE */ static XSizeHints win_position; /*position and size for window manager.*/ /* * initialize display id and screen id.... */ disp_id = XOpenDisplay(0); if (!disp_id) { printf("Display not opened!\n"); exit(-1); } /* * next instruction for debugging only.... */ /* XSynchronize(disp_id, 1); */ screen_id = XDefaultScreenOfDisplay(disp_id); root_win_id = XRootWindowOfScreen(screen_id); black = XBlackPixelOfScreen(screen_id); white = XWhitePixelOfScreen(screen_id); scr_width = XWidthOfScreen(screen_id); scr_height = XHeightOfScreen(screen_id); depth = XDefaultDepthOfScreen(screen_id); visual = XDefaultVisualOfScreen(screen_id); /* * set up backing store.... */ valuemask = CWBitGravity | CWBackingStore | CWBackPixel; setwinattr.bit_gravity = SouthWestGravity; setwinattr.backing_store = Always; setwinattr.background_pixel = white; /* * create the window.... */ win_id = XCreateWindow(disp_id, root_win_id, scr_width - win_width - 15, scr_height - win_height - 35, win_width, win_height, 10, depth, InputOutput, visual, valuemask, &setwinattr); /* WMHints structure */ win_position.x = scr_width - win_width - 15; win_position.y = scr_height - win_height - 35; win_position.width = win_width; win_position.height = win_height; win_position.flags=USPosition|USSize; XSetWMNormalHints(disp_id, win_id, &win_position); XStoreName(disp_id, win_id, WINDNAME); /* * get named color values.... */ color[1] = define_color_("BLUE"); color[2] = define_color_("DEEP SKY BLUE"); color[3] = define_color_("LIGHT SKY BLUE"); color[4] = define_color_("SEA GREEN"); color[5] = define_color_("MEDIUM SEA GREEN"); color[6] = define_color_("GREEN"); color[7] = define_color_("BROWN"); color[8] = define_color_("CHOCOLATE"); color[9] = define_color_("SANDY BROWN"); color[10] = define_color_("RED"); color[11] = define_color_("CORAL"); color[12] = define_color_("ORANGE"); color[13] = define_color_("YELLOW3"); color[14] = define_color_("YELLOW2"); color[15] = define_color_("YELLOW"); color[16] = define_color_("PEACH PUFF"); color[17] = define_color_("PAPAYA WHIP"); color[18] = define_color_("OLD LACE"); color[19] = white; color[20] = black; color[21] = black; /* * create graphics context.... */ xgcvl.background = color[19]; xgcvl.foreground = color[20]; gc_id = XCreateGC(disp_id, win_id, GCForeground | GCBackground, &xgcvl); xgcvl.function = GXinvert; gc_comp_id = XCreateGC(disp_id, win_id, GCFunction, &xgcvl); /* * load the font for text writing.... */ font = XLoadFont(disp_id, FONTNAME); XSetFont(disp_id, gc_id, font); /* Map the window.... */ XSelectInput(disp_id,win_id,ExposureMask|VisibilityChangeMask); XMapRaised(disp_id,win_id); /* * Wait for the window to be raised. Some X servers do not * generate an initial expose event, so also check the visibility * event. */ XMaskEvent(disp_id,ExposureMask|VisibilityChangeMask,&event); XSelectInput(disp_id,win_id,0); XSync(disp_id,1); }
int main(int argc, char **argv) { if(!argv[1])return -1; if(argv[1][0]==0)return -1; if(!loadShaders(argv[1]))return -1; Display *dpy; int screen; Window win; GLXContext ctx; XSetWindowAttributes attr; XVisualInfo *vi; Colormap cmap; Atom wmDelete; dpy = XOpenDisplay(0); screen = DefaultScreen(dpy); #ifdef _DEBUG unsigned int width=512,height=320; Bool bOverride=False; #else unsigned int width,height; width=XDisplayWidth(dpy, screen); height=XDisplayHeight(dpy, screen); Bool bOverride=True; #endif vi = glXChooseVisual(dpy, screen, attrlist); if(!vi){printf("No doublebuffering.\n");return -1;} ctx = glXCreateContext(dpy, vi, 0, GL_TRUE); cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), vi->visual, AllocNone); attr.colormap = cmap; attr.border_pixel = 0; attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask; attr.override_redirect = bOverride; win = XCreateWindow(dpy, RootWindow(dpy, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr); if(bOverride){ XWarpPointer(dpy, None, win, 0, 0, 0, 0, 0, 0); XMapRaised(dpy, win); XGrabKeyboard(dpy, win, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(dpy, win, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, win, None, CurrentTime); }else{ XMapRaised(dpy, win); XSetStandardProperties(dpy, win, "ShaderDemoX", "ShaderDemoX", None, NULL, 0, NULL); } glXMakeCurrent(dpy, win, ctx);// connect the glx-context to the window and get real size Window winDummy; unsigned int borderDummy,x,y,depth; XGetGeometry(dpy, win, &winDummy, &x, &y, &width, &height, &borderDummy, &depth); if (!glXIsDirect(dpy, ctx)){printf("No Direct Rendering\n");return -1;} //setup textures & buffers GLuint texture,fbo[2],rttex[2]; glGenFramebuffers(2, fbo); // Rendering to buffers glGenTextures(2, rttex); // Create named textures to render to glGenTextures(1, &texture); // For keyboard buffer glActiveTexture(GL_TEXTURE0); // Render to texture 0 int i; for(i=0;i<2;i++){ glBindTexture(GL_TEXTURE_2D, rttex[i]); // Bind to the render texture SetTexParams(width,height); // Create it and set params glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, fbo[i]); //Bind to the frame buffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rttex[i], 0); //Attach texture GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) {glBindFramebuffer(GL_FRAMEBUFFER, 0);return -1;}//Bail } glViewport(0,0,width,height);// Set the Viewport glClear(GL_COLOR_BUFFER_BIT); //create the programs bufferA & image GLuint P_A, VS_A, FS_A, P_I, VS_I, FS_I; GLint zBufA, zTexA, zUniA, zBufI, zTexI, zUniI; char *FSscript=(char *)malloc(65536); //max text for scripts sprintf(FSscript,fsh,bufferA); if(!createprogram(VSscript, FSscript, &P_A, &VS_A, &FS_A)){free(FSscript);return -1;} glUseProgram(P_A); zUniA=glGetUniformLocation(P_A,"Zuni");//set uniforms zBufA=glGetUniformLocation(P_A,"Zbuf"); zTexA=glGetUniformLocation(P_A,"Ztex"); sprintf(FSscript,fsh,image); if(!createprogram(VSscript, FSscript, &P_I, &VS_I, &FS_I)){free(FSscript);return -1;} glUseProgram(P_I); zUniI=glGetUniformLocation(P_I,"Zuni"); zBufI=glGetUniformLocation(P_I,"Zbuf"); zTexI=glGetUniformLocation(P_I,"Ztex"); #ifdef ADD_SOUND pthread_t tid; if(sound[0]!=0){ char fssh[]="uniform float Zuni[2];\nvec2 mainSound(in float);\n\ void main(){float t=floor(gl_FragCoord.y)*Zuni[0]+floor(gl_FragCoord.x);\n\ vec2 v1=mainSound(t*2.0/Zuni[1]),v2=mainSound((t*2.0+1.0)/Zuni[1]);\n\ gl_FragColor=clamp(vec4(v1,v2),-1.0,1.0);}\n%s";
JNIEXPORT void JNICALL Java_org_lwjgl_opengl_LinuxDisplay_mapRaised(JNIEnv *env, jclass unused, jlong display, jlong window_ptr) { Display *disp = (Display *)(intptr_t)display; Window window = (Window)window_ptr; XMapRaised(disp, window); }
/* FIXME: bits is currently unused */ GLWindow * createGLWindow(struct display_camera *camera) { GLWindow *x11_gl_window = New( GLWindow ); XVisualInfo *vi; Colormap cmap; int dpyWidth, dpyHeight; int i; int glxMajorVersion, glxMinorVersion; int vidModeMajorVersion, vidModeMinorVersion; XF86VidModeModeInfo **modes; int modeNum; int bestMode; Atom wmDelete; Window winDummy; unsigned int borderDummy; MemSet( x11_gl_window, 0, sizeof( GLWindow ) ); camera->hVidCore->x11_gl_window = x11_gl_window; x11_gl_window->fs = 0;//fullscreenflag; /* set best mode to current */ bestMode = 0; /* get a connection */ x11_gl_window->dpy = XOpenDisplay(0); if( x11_gl_window->dpy ) { x11_gl_window->screen = DefaultScreen(x11_gl_window->dpy); #if 0 x11_gl_window->atom_create = XInternAtom( x11_gl_window->dpy, "UserCreateWindow", 0 ); XF86VidModeQueryVersion(x11_gl_window->dpy, &vidModeMajorVersion, &vidModeMinorVersion); printf("XF86VidModeExtension-Version %d.%d\n", vidModeMajorVersion, vidModeMinorVersion); if( x11_gl_window->fs ) { XF86VidModeGetAllModeLines(x11_gl_window->dpy, x11_gl_window->screen, &modeNum, &modes); /* save desktop-resolution before switching modes */ x11_gl_window->deskMode = *modes[0]; /* look for mode with requested resolution */ for (i = 0; i < modeNum; i++) { if ((modes[i]->hdisplay == camera->w) && (modes[i]->vdisplay == camera->h)) { bestMode = i; } } } #endif /* get an appropriate visual */ vi = glXChooseVisual(x11_gl_window->dpy, x11_gl_window->screen, attrListDbl); if (vi == NULL) { vi = glXChooseVisual(x11_gl_window->dpy, x11_gl_window->screen, attrListSgl); x11_gl_window->doubleBuffered = False; printf("Only Singlebuffered Visual!\n"); } else { x11_gl_window->doubleBuffered = True; printf("Got Doublebuffered Visual!\n"); } glXQueryVersion(x11_gl_window->dpy, &glxMajorVersion, &glxMinorVersion); printf("glX-Version %d.%d\n", glxMajorVersion, glxMinorVersion); /* create a GLX context */ x11_gl_window->ctx = glXCreateContext(x11_gl_window->dpy, vi, 0, GL_TRUE); /* create a color map */ lprintf( "colormap..." ); cmap = XCreateColormap(x11_gl_window->dpy, RootWindow(x11_gl_window->dpy, vi->screen), vi->visual, AllocNone); x11_gl_window->attr.colormap = cmap; x11_gl_window->attr.border_pixel = 0; x11_gl_window->attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask | StructureNotifyMask; if (x11_gl_window->fs) { XF86VidModeSwitchToMode(x11_gl_window->dpy, x11_gl_window->screen, modes[bestMode]); XF86VidModeSetViewPort(x11_gl_window->dpy, x11_gl_window->screen, 0, 0); dpyWidth = modes[bestMode]->hdisplay; dpyHeight = modes[bestMode]->vdisplay; printf("Resolution %dx%d\n", dpyWidth, dpyHeight); XFree(modes); /* create a fullscreen window */ x11_gl_window->attr.override_redirect = True; x11_gl_window->win = XCreateWindow(x11_gl_window->dpy, RootWindow(x11_gl_window->dpy, vi->screen), 0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &x11_gl_window->attr); XWarpPointer(x11_gl_window->dpy, None, x11_gl_window->win, 0, 0, 0, 0, 0, 0); XMapRaised(x11_gl_window->dpy, x11_gl_window->win); XGrabKeyboard(x11_gl_window->dpy, x11_gl_window->win, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(x11_gl_window->dpy, x11_gl_window->win, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, x11_gl_window->win, None, CurrentTime); } else { /* create a window in window mode*/ lprintf( "create window... %d,%d %d", camera->w, camera->h, vi->depth ); x11_gl_window->win = XCreateWindow(x11_gl_window->dpy, RootWindow(x11_gl_window->dpy, vi->screen), 0, 0, camera->w, camera->h, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &x11_gl_window->attr); /* only set window title and handle wm_delete_events if in windowed mode */ wmDelete = XInternAtom(x11_gl_window->dpy, "WM_DELETE_WINDOW", True); XSetWMProtocols(x11_gl_window->dpy, x11_gl_window->win, &wmDelete, 1); XSetStandardProperties(x11_gl_window->dpy, x11_gl_window->win, "No Title", "No Title", None, NULL, 0, NULL); XMapRaised(x11_gl_window->dpy, x11_gl_window->win); } /* connect the glx-context to the window */ SetActiveGLDisplayView( camera, 0 ); //glXMakeCurrent(x11_gl_window->dpy, x11_gl_window->win, x11_gl_window->ctx); XGetGeometry(x11_gl_window->dpy, x11_gl_window->win, &winDummy, &x11_gl_window->x, &x11_gl_window->y, &x11_gl_window->width, &x11_gl_window->height, &borderDummy, &x11_gl_window->depth); printf("Depth %d\n", x11_gl_window->depth); if (glXIsDirect(x11_gl_window->dpy, x11_gl_window->ctx)) printf("Congrats, you have Direct Rendering!\n"); else printf("Sorry, no Direct Rendering possible!\n"); } else { lprintf( "Failed to open display" ); return NULL; } return x11_gl_window; }
void gfx_init_x11() { int f; XSetWindowAttributes attr; XSizeHints hints; Atom WM_DELETE_WINDOW; XGCValues gcValues; display = XOpenDisplay(NULL); screen = DefaultScreen(display); visual = DefaultVisual(display, screen); depth = DefaultDepth(display, screen); create_colormap_lookup_table(); /* hints.flags=PResizeInc|PMinSize|PMaxSize; */ hints.flags = PMinSize; hints.max_width = 2 * emu_window_width; hints.max_height = 2 * emu_window_height; hints.min_width = selected_model->pixel_width; hints.min_height = selected_model->pixel_height; hints.width_inc = 16; hints.height_inc = 16; attr.background_pixel = cmap24[C_gray]; /* TODO customize */ win = XCreateWindow(display, DefaultRootWindow(display), 0, 0, emu_window_width + WINDOW_FRAME, emu_window_height + WINDOW_FRAME, 0, CopyFromParent, CopyFromParent, CopyFromParent, CWBackPixel, &attr); WM_DELETE_WINDOW = XInternAtom(display, "WM_DELETE_WINDOW", False); XSetWMProtocols(display, win, &WM_DELETE_WINDOW, 1); XSetWMNormalHints(display, win, &hints); XSetStandardProperties(display, win, selected_model->title, selected_model->title, None, NULL, 0, NULL); XSelectInput(display, win, ExposureMask | ButtonPressMask | ButtonReleaseMask | PropertyChangeMask | KeyPressMask | KeyReleaseMask | Button1MotionMask | StructureNotifyMask); gc = XCreateGC(display, win, 0, 0); gcBackground = XCreateGC(display, win, 0, 0); gcValues.function = GXor; gcInvers = XCreateGC(display, win, GCFunction, &gcValues); XClearWindow(display, win); for (f = 0; f < ZOOM_MAX; f++) { krtImage[f] = XCreatePixmap(display, win, selected_model->pixel_width * (f + 1), selected_model->pixel_height * (f + 1), depth); } generateFonts(); initialized = 1; /* so jetzt läuft unser Main-Thread weiter */ XMapRaised(display, win); XFlush(display); handle_event(); gfx_exit(); }