int main(void) { int rx = 0, ry = 0, rw = 0, rh = 0; int rect_x = 0, rect_y = 0, rect_w = 0, rect_h = 0; int btn_pressed = 0, done = 0; XEvent ev; Display *disp = XOpenDisplay(NULL); if(!disp) return EXIT_FAILURE; Screen *scr = NULL; scr = ScreenOfDisplay(disp, DefaultScreen(disp)); Window root = 0; root = RootWindow(disp, XScreenNumberOfScreen(scr)); Cursor cursor, cursor2; cursor = XCreateFontCursor(disp, XC_left_ptr); cursor2 = XCreateFontCursor(disp, XC_lr_angle); XGCValues gcval; gcval.foreground = XWhitePixel(disp, 0); gcval.function = GXxor; gcval.background = XBlackPixel(disp, 0); gcval.plane_mask = gcval.background ^ gcval.foreground; gcval.subwindow_mode = IncludeInferiors; GC gc; gc = XCreateGC(disp, root, GCFunction | GCForeground | GCBackground | GCSubwindowMode, &gcval); /* this XGrab* stuff makes XPending true ? */ if ((XGrabPointer (disp, root, False, ButtonMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, root, cursor, CurrentTime) != GrabSuccess)) printf("couldn't grab pointer:"); if ((XGrabKeyboard (disp, root, False, GrabModeAsync, GrabModeAsync, CurrentTime) != GrabSuccess)) printf("couldn't grab keyboard:"); while (!done) { while (!done && XPending(disp)) { XNextEvent(disp, &ev); switch (ev.type) { case MotionNotify: /* this case is purely for drawing rect on screen */ if (btn_pressed) { if (rect_w) { /* re-draw the last rect to clear it */ XDrawRectangle(disp, root, gc, rect_x, rect_y, rect_w, rect_h); } else { /* Change the cursor to show we're selecting a region */ XChangeActivePointerGrab(disp, ButtonMotionMask | ButtonReleaseMask, cursor2, CurrentTime); } rect_x = rx; rect_y = ry; rect_w = ev.xmotion.x - rect_x; rect_h = ev.xmotion.y - rect_y; if (rect_w < 0) { rect_x += rect_w; rect_w = 0 - rect_w; } if (rect_h < 0) { rect_y += rect_h; rect_h = 0 - rect_h; } /* draw rectangle */ XDrawRectangle(disp, root, gc, rect_x, rect_y, rect_w, rect_h); XFlush(disp); } break; case ButtonPress: btn_pressed = 1; rx = ev.xbutton.x; ry = ev.xbutton.y; break; case ButtonRelease: done = 1; break; } } } /* clear the drawn rectangle */ if (rect_w) { XDrawRectangle(disp, root, gc, rect_x, rect_y, rect_w, rect_h); XFlush(disp); } rw = ev.xbutton.x - rx; rh = ev.xbutton.y - ry; /* cursor moves backwards */ if (rw < 0) { rx += rw; rw = 0 - rw; } if (rh < 0) { ry += rh; rh = 0 - rh; } XCloseDisplay(disp); printf("%dx%d+%d+%d\n",rw,rh,rx,ry); return EXIT_SUCCESS; }
void StartWindozeCycle(WWindow *wwin, XEvent *event, Bool next, Bool class_only) { WShortKey binding; WSwitchPanel *swpanel = NULL; WScreen *scr = wScreenForRootWindow(event->xkey.root); KeyCode leftKey = XKeysymToKeycode(dpy, XK_Left); KeyCode rightKey = XKeysymToKeycode(dpy, XK_Right); KeyCode homeKey = XKeysymToKeycode(dpy, XK_Home); KeyCode endKey = XKeysymToKeycode(dpy, XK_End); KeyCode shiftLKey = XKeysymToKeycode(dpy, XK_Shift_L); KeyCode shiftRKey = XKeysymToKeycode(dpy, XK_Shift_R); KeyCode escapeKey = XKeysymToKeycode(dpy, XK_Escape); KeyCode returnKey = XKeysymToKeycode(dpy, XK_Return); Bool esc_cancel = False; Bool somethingElse = False; Bool done = False; Bool hasModifier; int modifiers; WWindow *newFocused; WWindow *oldFocused; XEvent ev; if (!wwin) return; if (next) { if (class_only) binding = wKeyBindings[WKBD_GROUPNEXT]; else binding = wKeyBindings[WKBD_FOCUSNEXT]; } else { if (class_only) binding = wKeyBindings[WKBD_GROUPPREV]; else binding = wKeyBindings[WKBD_FOCUSPREV]; } hasModifier = (binding.modifier != 0); if (hasModifier) XGrabKeyboard(dpy, scr->root_win, False, GrabModeAsync, GrabModeAsync, CurrentTime); scr->flags.doing_alt_tab = 1; swpanel = wInitSwitchPanel(scr, wwin, class_only); oldFocused = wwin; if (swpanel) { if (wwin->flags.mapped && !wPreferences.panel_only_open) newFocused = wSwitchPanelSelectNext(swpanel, !next, True, False); else newFocused = wSwitchPanelSelectFirst(swpanel, False); oldFocused = change_focus_and_raise(newFocused, oldFocused, swpanel, scr, False); } else { if (wwin->frame->workspace == w_global.workspace.current) newFocused = wwin; else newFocused = NULL; } while (hasModifier && !done) { WMMaskEvent(dpy, KeyPressMask | KeyReleaseMask | ExposureMask | PointerMotionMask | ButtonReleaseMask | EnterWindowMask, &ev); /* ignore CapsLock */ modifiers = ev.xkey.state & w_global.shortcut.modifiers_mask; if (!swpanel) break; switch (ev.type) { case KeyPress: if ((wKeyBindings[WKBD_FOCUSNEXT].keycode == ev.xkey.keycode && wKeyBindings[WKBD_FOCUSNEXT].modifier == modifiers) || (wKeyBindings[WKBD_GROUPNEXT].keycode == ev.xkey.keycode && wKeyBindings[WKBD_GROUPNEXT].modifier == modifiers) || ev.xkey.keycode == rightKey) { newFocused = wSwitchPanelSelectNext(swpanel, False, ev.xkey.keycode != rightKey, (!class_only && wKeyBindings[WKBD_GROUPNEXT].keycode == ev.xkey.keycode && wKeyBindings[WKBD_GROUPNEXT].modifier == modifiers)); oldFocused = change_focus_and_raise(newFocused, oldFocused, swpanel, scr, False); } else if ((wKeyBindings[WKBD_FOCUSPREV].keycode == ev.xkey.keycode && wKeyBindings[WKBD_FOCUSPREV].modifier == modifiers) || (wKeyBindings[WKBD_GROUPPREV].keycode == ev.xkey.keycode && wKeyBindings[WKBD_GROUPPREV].modifier == modifiers) || ev.xkey.keycode == leftKey) { newFocused = wSwitchPanelSelectNext(swpanel, True, ev.xkey.keycode != leftKey, (!class_only && wKeyBindings[WKBD_GROUPPREV].keycode == ev.xkey.keycode && wKeyBindings[WKBD_GROUPPREV].modifier == modifiers)); oldFocused = change_focus_and_raise(newFocused, oldFocused, swpanel, scr, False); } else if (ev.xkey.keycode == homeKey || ev.xkey.keycode == endKey) { newFocused = wSwitchPanelSelectFirst(swpanel, ev.xkey.keycode != homeKey); oldFocused = change_focus_and_raise(newFocused, oldFocused, swpanel, scr, False); } else if (ev.xkey.keycode == escapeKey) { /* Focus the first window of the swpanel, despite the 'False' */ newFocused = wSwitchPanelSelectFirst(swpanel, False); oldFocused = change_focus_and_raise(newFocused, oldFocused, swpanel, scr, True); esc_cancel = True; done = True; } else if (ev.xkey.keycode == returnKey) { /* Close the switchpanel without eating the keypress */ done = True; } else if (ev.xkey.keycode != shiftLKey && ev.xkey.keycode != shiftRKey) { somethingElse = True; done = True; } break; case KeyRelease: if (ev.xkey.keycode == shiftLKey || ev.xkey.keycode == shiftRKey) if (wPreferences.strict_windoze_cycle) break; if (ev.xkey.keycode == leftKey || ev.xkey.keycode == rightKey) break; if (ev.xkey.keycode == XK_Return) break; if (ev.xkey.keycode != binding.keycode) done = True; break; case EnterNotify: /* ignore unwanted EnterNotify's */ break; case LeaveNotify: case MotionNotify: case ButtonRelease: { WWindow *tmp; tmp = wSwitchPanelHandleEvent(swpanel, &ev); if (tmp) { newFocused = tmp; oldFocused = change_focus_and_raise(newFocused, oldFocused, swpanel, scr, False); if (ev.type == ButtonRelease) done = True; } } break; default: WMHandleEvent(&ev); break; } } if (hasModifier) XUngrabKeyboard(dpy, CurrentTime); if (swpanel) wSwitchPanelDestroy(swpanel); if (newFocused && !esc_cancel) { wRaiseFrame(newFocused->frame->core); CommitStacking(scr); if (!newFocused->flags.mapped) wMakeWindowVisible(newFocused); wSetFocusTo(scr, newFocused); } scr->flags.doing_alt_tab = 0; if (somethingElse) WMHandleEvent(&ev); }
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; }
bool MWindow::create(const char * title, unsigned int width, unsigned int height, int colorBits, bool fullscreen) { static int dblBuf[] = {GLX_RGBA, GLX_RED_SIZE, 4, GLX_GREEN_SIZE, 4, GLX_BLUE_SIZE, 4, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None}; XVisualInfo * vi; Colormap cmap; XSetWindowAttributes swa; // open display display = XOpenDisplay(NULL); // fullscreen #ifndef __CYGWIN__ int vmMajor, vmMinor; if(XF86VidModeQueryVersion(display, &vmMajor, &vmMinor) && fullscreen) { screen = DefaultScreen(display); int modeNum, screenMode=0; XF86VidModeModeInfo **modes; XF86VidModeGetAllModeLines(display, screen, &modeNum, &modes); if(modeNum > 0) { desktopMode = *modes[0]; for(int i=0; i<modeNum; i++) { if((modes[i]->hdisplay == width) && (modes[i]->vdisplay == height)) screenMode = i; } XF86VidModeSwitchToMode(display, screen, modes[screenMode]); XF86VidModeSetViewPort(display, screen, 0, 0); m_width = modes[screenMode]->hdisplay; m_height = modes[screenMode]->vdisplay; XFree(modes); swa.override_redirect = True; swa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask | ExposureMask | FocusChangeMask | VisibilityChangeMask; rootWindow = RootWindow(display,vi->screen); window = XCreateWindow( display, rootWindow, 0, 0, m_width, m_height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &swa); XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0); XMapRaised(display, window); XGrabKeyboard(display, window, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(display, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, None, CurrentTime); m_fullscreen = true; } else { return false; } } else #endif // window { m_fullscreen = false; vi = glXChooseVisual(display, DefaultScreen(display), dblBuf); context = glXCreateContext(display, vi, None, True); rootWindow = RootWindow(display,vi->screen); cmap = XCreateColormap(display,rootWindow,vi->visual,AllocNone); swa.colormap = cmap; swa.border_pixel = 0; swa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask | ExposureMask | FocusChangeMask | VisibilityChangeMask; m_width = width; m_height = height; window = XCreateWindow( display, rootWindow, 0, 0, m_width, m_height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa); wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", False); XSetWMProtocols(display, window, &wmDelete, 1); XSetStandardProperties(display, window, title, title, None, NULL, 0, NULL); XMapWindow(display, window); } // make current context glXMakeCurrent(display, window, context); // cursor nullCursor = createNULLCursor(display, rootWindow); return true; }
void grabkeyboard(){ XGrabKeyboard(dpy,win,1,GrabModeAsync,GrabModeAsync,CurrentTime); }
int Tk_Grab( Tcl_Interp *interp, /* Used for error reporting. */ Tk_Window tkwin, /* Window on whose behalf the pointer is to be * grabbed. */ int grabGlobal) /* Non-zero means issue a grab to the server * so that no other application gets mouse or * keyboard events. Zero means the grab only * applies within this application. */ { int grabResult, numTries; TkWindow *winPtr = (TkWindow *) tkwin; TkDisplay *dispPtr = winPtr->dispPtr; TkWindow *winPtr2; unsigned int serial; ReleaseButtonGrab(dispPtr); if (dispPtr->eventualGrabWinPtr != NULL) { if ((dispPtr->eventualGrabWinPtr == winPtr) && (grabGlobal == ((dispPtr->grabFlags & GRAB_GLOBAL) != 0))) { return TCL_OK; } if (dispPtr->eventualGrabWinPtr->mainPtr != winPtr->mainPtr) { goto alreadyGrabbed; } Tk_Ungrab((Tk_Window) dispPtr->eventualGrabWinPtr); } Tk_MakeWindowExist(tkwin); if (!grabGlobal) { Window dummy1, dummy2; int dummy3, dummy4, dummy5, dummy6; unsigned int state; /* * Local grab. However, if any mouse buttons are down, turn it into a * global grab temporarily, until the last button goes up. This does * two things: (a) it makes sure that we see the button-up event; and * (b) it allows us to track mouse motion among all of the windows of * this application. */ dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL); XQueryPointer(dispPtr->display, winPtr->window, &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6, &state); if (state & ALL_BUTTONS) { dispPtr->grabFlags |= GRAB_TEMP_GLOBAL; goto setGlobalGrab; } } else { dispPtr->grabFlags |= GRAB_GLOBAL; setGlobalGrab: /* * Tricky point: must ungrab before grabbing. This is needed in case * there is a button auto-grab already in effect. If there is, and the * mouse has moved to a different window, X won't generate enter and * leave events to move the mouse if we grab without ungrabbing. */ XUngrabPointer(dispPtr->display, CurrentTime); serial = NextRequest(dispPtr->display); /* * Another tricky point: there are races with some window managers * that can cause grabs to fail because the window manager hasn't * released its grab quickly enough. To work around this problem, * retry a few times after AlreadyGrabbed errors to give the grab * release enough time to register with the server. */ grabResult = 0; /* Needed only to prevent gcc compiler * warnings. */ for (numTries = 0; numTries < 10; numTries++) { grabResult = XGrabPointer(dispPtr->display, winPtr->window, True, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask |PointerMotionMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); if (grabResult != AlreadyGrabbed) { break; } Tcl_Sleep(100); } if (grabResult != 0) { goto grabError; } grabResult = XGrabKeyboard(dispPtr->display, Tk_WindowId(tkwin), False, GrabModeAsync, GrabModeAsync, CurrentTime); if (grabResult != 0) { XUngrabPointer(dispPtr->display, CurrentTime); goto grabError; } /* * Eat up any grab-related events generated by the server for the * grab. There are several reasons for doing this: * * 1. We have to synthesize the events for local grabs anyway, since * the server doesn't participate in them. * 2. The server doesn't always generate the right events for global * grabs (e.g. it generates events even if the current window is in * the grab tree, which we don't want). * 3. We want all the grab-related events to be processed immediately * (before other events that are already queued); events coming * from the server will be in the wrong place, but events we * synthesize here will go to the front of the queue. */ EatGrabEvents(dispPtr, serial); } /* * Synthesize leave events to move the pointer from its current window up * to the lowest ancestor that it has in common with the grab window. * However, only do this if the pointer is outside the grab window's * subtree but inside the grab window's application. */ if ((dispPtr->serverWinPtr != NULL) && (dispPtr->serverWinPtr->mainPtr == winPtr->mainPtr)) { for (winPtr2 = dispPtr->serverWinPtr; ; winPtr2 = winPtr2->parentPtr) { if (winPtr2 == winPtr) { break; } if (winPtr2 == NULL) { MovePointer2(dispPtr->serverWinPtr, winPtr, NotifyGrab, 1, 0); break; } } } QueueGrabWindowChange(dispPtr, winPtr); return TCL_OK; grabError: if (grabResult == GrabNotViewable) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "grab failed: window not viewable", -1)); Tcl_SetErrorCode(interp, "TK", "GRAB", "UNVIEWABLE", NULL); } else if (grabResult == AlreadyGrabbed) { alreadyGrabbed: Tcl_SetObjResult(interp, Tcl_NewStringObj( "grab failed: another application has grab", -1)); Tcl_SetErrorCode(interp, "TK", "GRAB", "GRABBED", NULL); } else if (grabResult == GrabFrozen) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "grab failed: keyboard or pointer frozen", -1)); Tcl_SetErrorCode(interp, "TK", "GRAB", "FROZEN", NULL); } else if (grabResult == GrabInvalidTime) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "grab failed: invalid time", -1)); Tcl_SetErrorCode(interp, "TK", "GRAB", "BAD_TIME", NULL); } else { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "grab failed for unknown reason (code %d)", grabResult)); Tcl_SetErrorCode(interp, "TK", "GRAB", "UNKNOWN", NULL); } return TCL_ERROR; }
void emX11WindowPort::PostConstruct() { int i,r; if ((GetWindowFlags()&( emWindow::WF_POPUP|emWindow::WF_UNDECORATED|emWindow::WF_FULLSCREEN ))!=0) { XMutex.Lock(); XMapRaised(Disp,Win); XMutex.Unlock(); } else { XMutex.Lock(); XMapWindow(Disp,Win); XMutex.Unlock(); } if (Focused) { if (MakeViewable()) { if ((GetWindowFlags()&emWindow::WF_MODAL)!=0 && Owner) { XMutex.Lock(); XSetInputFocus(Disp,Win,RevertToParent,CurrentTime); XMutex.Unlock(); } else { XMutex.Lock(); XSetInputFocus(Disp,Win,RevertToNone,CurrentTime); XMutex.Unlock(); } } else { Focused=false; SetViewFocused(false); } } if ( (GetWindowFlags()&emWindow::WF_FULLSCREEN)!=0 || ( (GetWindowFlags()&emWindow::WF_POPUP)!=0 && ( !Screen.GrabbingWinPort || (Screen.GrabbingWinPort->GetWindowFlags()&emWindow::WF_FULLSCREEN)==0 ) ) ) { if (MakeViewable()) { for (i=0; ; i++) { XMutex.Lock(); r=XGrabKeyboard( Disp, Win, True, GrabModeSync, GrabModeAsync, CurrentTime ); XMutex.Unlock(); if (r==GrabSuccess) break; if (i>10) emFatalError("XGrabKeyboard failed."); emWarning("XGrabKeyboard failed - trying again..."); emSleepMS(50); } for (i=0; ; i++) { XMutex.Lock(); r=XGrabPointer( Disp, Win, True, ButtonPressMask|ButtonReleaseMask|PointerMotionMask| ButtonMotionMask|EnterWindowMask|LeaveWindowMask, GrabModeSync, GrabModeAsync, (GetWindowFlags()&emWindow::WF_FULLSCREEN)!=0 ? Win : None, None, CurrentTime ); XMutex.Unlock(); if (r==GrabSuccess) break; if (i>10) emFatalError("XGrabPointer failed."); emWarning("XGrabPointer failed - trying again..."); emSleepMS(50); } XMutex.Lock(); XAllowEvents(Disp,SyncPointer,CurrentTime); XMutex.Unlock(); Screen.GrabbingWinPort=this; } } if ((GetWindowFlags()&emWindow::WF_FULLSCREEN)!=0) { FullscreenUpdateTimer=new emTimer(GetScheduler()); AddWakeUpSignal(FullscreenUpdateTimer->GetSignal()); FullscreenUpdateTimer->Start(500,true); } if ((GetWindowFlags()&emWindow::WF_MODAL)!=0) { SetModalState(true); } }
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; int xshift = 0; 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], "-v")) die("sflock-"VERSION", © 2015 Ben Ruijl\n"); else if (!strcmp(argv[i], "-h")) showline = 0; else if (!strcmp(argv[i], "-xshift")) xshift = atoi(argv[i + 1]); else if (!strcmp(argv[i], "?")) die("usage: sflock [-v] [-c passchars] [-f fontname] [-xshift horizontal shift]\n"); } // fill with password characters for (int i = 0; i < sizeof passdisp; i+= strlen(passchar)) for (int j = 0; j < strlen(passchar) && i + j < sizeof passdisp; 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 = getpwuid(geteuid())->pw_name; #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 + xshift, y - ascent - 20, username, strlen(username)); if (showline) XDrawLine(dpy, w, gc, width * 3 / 8 + xshift, y - ascent - 10, width * 5 / 8 + xshift, y - ascent - 10); XDrawString(dpy,w,gc, x + xshift, 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; }
JNIEXPORT jint JNICALL Java_org_lwjgl_opengl_LinuxDisplay_nGrabKeyboard(JNIEnv *env, jclass unused, jlong display_ptr, jlong window_ptr) { Display *disp = (Display *)(intptr_t)display_ptr; Window win = (Window)window_ptr; return XGrabKeyboard(disp, win, False, GrabModeAsync, GrabModeAsync, CurrentTime); }
void menu_draw(Menu menu, int x, int y) { int i, width, height, out; XEvent ev; BarWindow *item[menu.nitem]; BarWindow *frame; int chcklen = 0; if(menu_get_checkstring_needed(menu.item, menu.nitem)) chcklen = textw(conf.selected_layout_symbol) + PAD / 3; width = menu_get_longer_string(menu.item, menu.nitem) + chcklen + textw(">") + PAD * 3; height = menu.nitem * (INFOBARH - SHADH); /* Frame barwin */ screen_get_sel(); if((out = x + width - MAXW) > 0) x -= out; if((out = y + height - MAXH) > 0) y -= out; frame = barwin_create(ROOT, x, y, width + SHADH, height + SHADH * 3, menu.colors.normal.bg, menu.colors.normal.fg, False, False, True); barwin_map(frame); barwin_map_subwin(frame); barwin_refresh_color(frame); for(i = 0; i < menu.nitem; ++i) { item[i] = barwin_create(frame->win, SHADH, (i * (INFOBARH - SHADH) + SHADH), width - SHADH, INFOBARH, menu.colors.normal.bg, menu.colors.normal.fg, True, False, False); barwin_map(item[i]); barwin_refresh_color(item[i]); menu_draw_item_name(&menu, i, item, chcklen); barwin_refresh(item[i]); } /* Select the first item */ menu_focus_item(&menu, 0, item); XGrabKeyboard(dpy, ROOT, True, GrabModeAsync, GrabModeAsync, CurrentTime); while(!menu_manage_event(&ev, &menu, item)); XUngrabKeyboard(dpy, CurrentTime); for(i = 0; i < menu.nitem; ++i) barwin_delete(item[i]); barwin_delete(frame); return; }
/* Function Name: * GetClientWindow * * Description: * Gets the Client's window by asking the user. * * Arguments: * w - a widget. * * Returns: * a clients window, or None. * * Calls: * SetMessage - utils.c * * Global Data: */ Window GetClientWindow(Widget w, int *x, int *y) { int status; Cursor cursor; XEvent event; int buttons = 0; int keys = 0; Display *dpy = XtDisplayOfObject(w); Window target_win = None; Window root_win = RootWindowOfScreen(XtScreenOfObject(w)); XtAppContext context = XtWidgetToApplicationContext(w); char buffer[10]; int len; KeySym keycode; /* >>>>> HACK for batchres */ if (global_winID != None) { /* we submit the winID given by parameter only once! */ /* otherwise there is an infinite loop */ target_win = global_winID; global_winID = None; return(target_win); } /* <<<<< HACK for batchres */ /* Make the target cursor */ cursor = XCreateFontCursor(dpy, XC_crosshair); /* Grab the pointer using target cursor, letting it room all over */ status = XGrabPointer(dpy, /* Display */ root_win, /* grab_window */ False, /* owner_events */ ButtonPressMask | ButtonReleaseMask, GrabModeSync, /* pointer_mode */ GrabModeAsync, /* keyboard_mode */ root_win, /* confine_to */ cursor, /* cursor */ CurrentTime); /* time, when grab took place */ if (status != GrabSuccess) { /* "Can't grab the mouse" */ SetMessage(global_screen_data.info_label, res_labels[5], "Can't grab the mouse"); return(None); } /* if (grab of mouse pointer unsuccessful) */ /* Grab the keyboard, letting it room all over */ status = XGrabKeyboard(dpy, /* Display */ root_win, /* grab_window */ False, /* owner_events */ GrabModeAsync, /* pointer_mode */ GrabModeAsync, /* keyboard_mode */ CurrentTime); /* time, when grab took place */ if (status != GrabSuccess) { /* "Can't grab the keyboard" */ SetMessage(global_screen_data.info_label, res_labels[37], "Can't grab the keyboard"); return(None); } /* if (grab of keyboard unsuccessful) */ /* Let the user select a window... */ while ( (target_win == None) || (buttons != 0) ) { /* printf("targetwin: 0x%x, buttons: %d\n", target_win, buttons); */ /* allow one more event */ XAllowEvents(dpy, SyncPointer, CurrentTime); XtAppNextEvent(context, &event); switch (event.type) { case ButtonPress: /* printf("ButtonWindow 0x%x\n", event.xbutton.window); */ if (event.xbutton.window != root_win) { XtDispatchEvent(&event); break; } if (target_win == None) { target_win = event.xbutton.subwindow; /* window selected */ if (x != NULL) { *x = event.xbutton.x_root; } if (y != NULL) { *y = event.xbutton.y_root; } } buttons++; break; /* ButtonPress */ case ButtonRelease: if (event.xbutton.window != root_win) { XtDispatchEvent(&event); break; } if (buttons > 0) /* There may have been some */ { /* down before we started */ buttons--; } break; /* ButtonRelease */ case KeyPress: /* <Key>ESC aborts, <Key>Return + <Key>Spacebar select */ len = (XLookupString(&(event.xkey), buffer, sizeof(buffer), &keycode, (XComposeStatus*)NULL)); /* printf("keycode: 0x%x\n", keycode); */ switch (keycode) { case XK_Return: case XK_space: case XK_Select: case XK_KP_Space: case XK_KP_Enter: /* printf("Ret, space, Select, ...\n"); */ /* printf("KeyWindow 0x%x\n", event.xkey.window); */ /* if (event.xkey.window != root_win) */ /* { */ /* XtDispatchEvent(&event); */ /* break; */ /* } */ /* printf(" window root \n"); */ if (target_win == None) { /* printf(" subwindow 0x%x\n", event.xkey.subwindow); */ target_win = event.xkey.subwindow; /* window selected */ if (x != NULL) { *x = event.xkey.x_root; } if (y != NULL) { *y = event.xkey.y_root; } } break; /* XK_Return */ case XK_Escape: case XK_Cancel: case XK_Break: XUngrabPointer(dpy, CurrentTime); /* Done with pointer */ XUngrabKeyboard(dpy, CurrentTime); /* Done with keyboard */ return ((Window)None); break; /* XK_Escape */ default: fprintf(stderr, "Unknown key! Press <ESC> to abort, <Return> to select\n"); break; } /* switch (keycode) */ break; /* KeyPress */ default: XtDispatchEvent(&event); break; /* default */ } /* switch (event.type) */ } /* while () */ /* If the XServer supports KeyRelease, we throw it away */ while ((event.type == KeyRelease) || (event.type == KeyPress)) { XtDispatchEvent(&event); } /* while (discard Keyboard-Events) */ XUngrabPointer(dpy, CurrentTime); /* Done with pointer */ XUngrabKeyboard(dpy, CurrentTime); /* Done with keyboard */ /* printf("[GetClientWindow] target_win 0x%x, XmuClientWindow 0x%x\n", */ /* target_win, */ /* XmuClientWindow(dpy, target_win)); */ return (XmuClientWindow(dpy, target_win)); } /* GetClientWindow() */
struct menu * menu_filter(struct screen_ctx *sc, struct menu_q *menuq, char *prompt, char *initial, int dummy, void (*match)(struct menu_q *, struct menu_q *, char *), void (*print)(struct menu *, int)) { struct menu_ctx mc; struct menu_q resultq; struct menu *mi = NULL; XEvent e; Window focuswin; int evmask, focusrevert; int xsave, ysave, xcur, ycur; TAILQ_INIT(&resultq); bzero(&mc, sizeof(mc)); xu_ptr_getpos(sc->rootwin, &mc.x, &mc.y); xsave = mc.x; ysave = mc.y; if (prompt == NULL) { evmask = MENUMASK; mc.promptstr[0] = '\0'; mc.list = 1; } else { evmask = MENUMASK | KEYMASK; /* only accept keys if prompt */ (void)snprintf(mc.promptstr, sizeof(mc.promptstr), "%s%s", prompt, PROMPT_SCHAR); (void)snprintf(mc.dispstr, sizeof(mc.dispstr), "%s%s%s", mc.promptstr, mc.searchstr, PROMPT_ECHAR); mc.width = font_width(sc, mc.dispstr, strlen(mc.dispstr)); mc.hasprompt = 1; } if (initial != NULL) (void)strlcpy(mc.searchstr, initial, sizeof(mc.searchstr)); else mc.searchstr[0] = '\0'; mc.match = match; mc.print = print; mc.entry = mc.prev = -1; XMoveResizeWindow(X_Dpy, sc->menuwin, mc.x, mc.y, mc.width, font_height(sc)); XSelectInput(X_Dpy, sc->menuwin, evmask); XMapRaised(X_Dpy, sc->menuwin); if (xu_ptr_grab(sc->menuwin, MENUGRABMASK, Cursor_question) < 0) { XUnmapWindow(X_Dpy, sc->menuwin); return (NULL); } XGetInputFocus(X_Dpy, &focuswin, &focusrevert); XSetInputFocus(X_Dpy, sc->menuwin, RevertToPointerRoot, CurrentTime); /* make sure keybindings don't remove keys from the menu stream */ XGrabKeyboard(X_Dpy, sc->menuwin, True, GrabModeAsync, GrabModeAsync, CurrentTime); menu_draw(sc, &mc, menuq, &resultq); for (;;) { mc.changed = 0; XWindowEvent(X_Dpy, sc->menuwin, evmask, &e); switch (e.type) { case KeyPress: if ((mi = menu_handle_key(&e, &mc, menuq, &resultq)) != NULL) goto out; /* FALLTHROUGH */ case Expose: menu_draw(sc, &mc, menuq, &resultq); break; case MotionNotify: menu_handle_move(&e, &mc, &resultq, sc); break; case ButtonRelease: if ((mi = menu_handle_release(&e, &mc, sc, &resultq)) != NULL) goto out; break; default: break; } } out: if (dummy == 0 && mi->dummy) { /* no mouse based match */ xfree(mi); mi = NULL; } XSetInputFocus(X_Dpy, focuswin, focusrevert, CurrentTime); /* restore if user didn't move */ xu_ptr_getpos(sc->rootwin, &xcur, &ycur); if (xcur == mc.x && ycur == mc.y) xu_ptr_setpos(sc->rootwin, xsave, ysave); xu_ptr_ungrab(); XUnmapWindow(X_Dpy, sc->menuwin); XUngrabKeyboard(X_Dpy, CurrentTime); return (mi); }
int glx_init( int fullscreen ) { int vi_attr[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 4, GLX_GREEN_SIZE, 4, GLX_BLUE_SIZE, 4, GLX_DEPTH_SIZE, 16, None }; XVisualInfo *vi; Window root_win; XWindowAttributes win_attr; XSetWindowAttributes set_attr; XFontStruct *fixed; XColor black = { 0, 0, 0, 0, 0, 0 }; if( ( dpy = XOpenDisplay( NULL ) ) == NULL ) { fprintf( stderr, "XOpenDisplay failed\n" ); return( 1 ); } if( ( vi = glXChooseVisual( dpy, DefaultScreen( dpy ), vi_attr ) ) == NULL ) { fprintf( stderr, "glXChooseVisual failed\n" ); XCloseDisplay( dpy ); return( 1 ); } root_win = RootWindow( dpy, vi->screen ); XGetWindowAttributes( dpy, root_win, &win_attr ); width = ( fullscreen ) ? win_attr.width : 640; height = ( fullscreen ) ? win_attr.height : 480; set_attr.border_pixel = 0; set_attr.colormap = XCreateColormap( dpy, root_win, vi->visual, AllocNone ); set_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; set_attr.override_redirect = ( ( fullscreen ) ? True : False ); win = XCreateWindow( dpy, root_win, 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &set_attr ); XStoreName( dpy, win, AppTitle ); XMapWindow( dpy, win ); if( fullscreen ) { XGrabKeyboard( dpy, win, True, GrabModeAsync, GrabModeAsync, CurrentTime ); } else { wmDelete = XInternAtom( dpy, "WM_DELETE_WINDOW", True ); XSetWMProtocols( dpy, win, &wmDelete, 1 ); } if( ( ctx = glXCreateContext( dpy, vi, NULL, True ) ) == NULL ) { fprintf( stderr, "glXCreateContext failed\n" ); XDestroyWindow( dpy, win ); XCloseDisplay( dpy ); return( 1 ); } if( glXMakeCurrent( dpy, win, ctx ) == False ) { fprintf( stderr, "glXMakeCurrent failed\n" ); glXDestroyContext( dpy, ctx ); XDestroyWindow( dpy, win ); XCloseDisplay( dpy ); return( 1 ); } font = glGenLists( 256 ); fixed = XLoadQueryFont( dpy, "-misc-fixed-medium-r-*-*-20-*-*-*-*-*-*-*" ); null_cursor = XCreateGlyphCursor( dpy, fixed->fid, fixed->fid, ' ', ' ', &black, &black ); glXUseXFont( fixed->fid, 0, 256, font ); XFreeFont( dpy, fixed ); return( 0 ); }
int microgl_open(int w, int h, int fs) { XEvent event; XSetWindowAttributes wa; // Colormap cmap; win.w = w; win.h = h; // step 1: create the window wa.event_mask=ExposureMask|KeyPressMask|KeyReleaseMask|ButtonPressMask|ButtonReleaseMask; if (!fs) wa.event_mask|= PointerMotionMask | StructureNotifyMask| ExposureMask | FocusChangeMask | VisibilityChangeMask; win.Win=XCreateWindow(Dpy,DefaultRootWindow(Dpy), 0,0,w,h,0,CopyFromParent,InputOutput, CopyFromParent,CWEventMask,&wa); // step 2: fullscreen tweaks if (fs) { int success=0; Atom atom; /* window manager specific, leave out for now atom=XInternAtom(Dpy,"_MOTIF_WM_HINTS",True); if (atom!=None) { struct { unsigned long flags; unsigned long functions; unsigned long decorations; long input_mode; unsigned long status; } MWMHints = { MWM_HINTS_DECORATIONS, 0, 0, 0, 0 }; XChangeProperty( Dpy, win.Win, atom, atom, 32, PropModeReplace, (unsigned char *)&MWMHints, sizeof(MWMHints)/4 ); sucess=1; } atom = XInternAtom( Dpy, "KWM_WIN_DECORATION", True ); if ( atom!= None ) { long KWMHints = KDE_tinyDecoration; XChangeProperty( Dpy, win.Win, atom, atom, 32, PropModeReplace, (unsigned char *)&KWMHints, sizeof(KWMHints)/4 ); success= 1; } */ atom= XInternAtom(Dpy,"_WIN_HINTS",True); if ( atom != None ) { long GNOMEHints = 0; XChangeProperty( Dpy, win.Win, atom, atom, 32, PropModeReplace, (unsigned char *)&GNOMEHints, sizeof(GNOMEHints)/4 ); success = 1; } atom = XInternAtom( Dpy, "_NET_WM_WINDOW_TYPE", True ); if ( atom != None ) { Atom NET_WMHints[2]; NET_WMHints[0] = XInternAtom( Dpy, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True ); NET_WMHints[1] = XInternAtom( Dpy, "_NET_WM_WINDOW_TYPE_NORMAL", True ); XChangeProperty( Dpy, win.Win, atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&NET_WMHints, 2 ); success = 1; } atom=XInternAtom(Dpy,"_NET_WM_STATE",True); if (atom!=None) { Atom NET_WMHints[1]; NET_WMHints[0] = XInternAtom( Dpy, "_NET_WM_STATE_FULLSCREEN",True); XChangeProperty(Dpy,win.Win,atom, XA_ATOM, 32, PropModeReplace, (unsigned char*)&NET_WMHints, 1); success=1; } atom=XInternAtom(Dpy,"_HILDON_NON_COMPOSITED_WINDOW",True); if (atom!=None) { int one=1; XChangeProperty(Dpy,win.Win,atom, XA_INTEGER, 32, PropModeReplace, (unsigned char*)&one, 1); success=1; } // Hildon run in landscape mode by default // this is opposite of other mobiles ! /* atom=XInternAtom(Dpy,"_HILDON_PORTRAIT_MODE_SUPPORT",True); if (atom!=None) { long one=1; XChangeProperty(Dpy,win.Win,atom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&one, 1); } atom=XInternAtom(Dpy,"_HILDON_PORTRAIT_MODE_REQUEST",True); if (atom!=None) { long one=1; XChangeProperty(Dpy,win.Win,atom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&one, 1); } */ if (success) { XSetTransientForHint(Dpy,win.Win,DefaultRootWindow(Dpy)); XUnmapWindow(Dpy,win.Win); XMapWindow(Dpy,win.Win); } { XSetWindowAttributes xattr; xattr.override_redirect=True; XChangeWindowAttributes(Dpy,win.Win,CWOverrideRedirect,&xattr); } } // step 3: glx / egl setup #ifdef USE_GLX { GLint att16[] = { GLX_RGBA, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None }; GLint att24[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; //XXXX Scrn is not initialized!!! win.VI = glXChooseVisual(Dpy, win.Scrn, att16); if (win.VI == NULL) win.VI = glXChooseVisual(Dpy, win.Scrn, att24); if (win.VI == NULL) return 0; // failed to find a visual win.CX = glXCreateContext( Dpy, win.VI, 0, GL_TRUE ); glXMakeCurrent( Dpy, win.Win, win.CX ); } #endif #ifdef USE_EGL { EGLConfig ecfg; EGLint num_config; // EGLint attr[]={EGL_BUFFER_SIZE,16,EGL_RENDERABLE_TYPE,EGL_OPENGL_ES2_BIT, EGL_NONE}; EGLint attr[]={EGL_BUFFER_SIZE,16,EGL_RENDERABLE_TYPE,EGL_OPENGL_ES_BIT, EGL_NONE}; // EGLint ctxattr[]={EGL_CONTEXT_CLIENT_VERSION,2,EGL_NONE}; EGLint ctxattr[]={EGL_CONTEXT_CLIENT_VERSION,1,EGL_NONE}; win.egl_display=eglGetDisplay((EGLNativeDisplayType) Dpy); if ( win.egl_display == EGL_NO_DISPLAY ) { printf("ERROR 1\n"); return 0; } if (!eglInitialize(win.egl_display,NULL,NULL)) { printf("ERROR 2\n"); return 0; } if (!eglChooseConfig(win.egl_display,attr,&ecfg,1,&num_config)) { printf("ERROR 3\n"); return 0; } if (num_config!=1) { printf("ERROR 4\n"); return 0; } win.egl_surface=eglCreateWindowSurface(win.egl_display,ecfg,(void*)win.Win,NULL); if (win.egl_surface==EGL_NO_SURFACE) { printf("ERROR 5\n"); return 0; } win.egl_context=eglCreateContext(win.egl_display, ecfg, EGL_NO_CONTEXT, ctxattr); if (win.egl_context==EGL_NO_CONTEXT) { printf("ERROR 6\n"); return 0; } eglMakeCurrent(win.egl_display,win.egl_surface,win.egl_surface,win.egl_context); } #endif win.WMDeleteWindow = XInternAtom( Dpy, "WM_DELETE_WINDOW", False ); XSetWMProtocols( Dpy, win.Win, &(win.WMDeleteWindow),1); // show the window XMapWindow( Dpy, win.Win ); if (!fs) XIfEvent( Dpy, &event, _microglWaitForMapNotify, (char*)win.Win ); XRaiseWindow( Dpy, win.Win ); // is this needed?? win.KeyboardGrabbed = win.PointerGrabbed = 0; if (fs) { // fullscreen specific stuff XMoveWindow(Dpy,win.Win,0,0); XResizeWindow(Dpy,win.Win,w,h); if (XGrabKeyboard(Dpy, win.Win, True, GrabModeAsync, GrabModeAsync, CurrentTime ) == GrabSuccess) win.KeyboardGrabbed = 1; if (XGrabPointer( Dpy, win.Win, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, win.Win, None, CurrentTime ) == GrabSuccess) win.PointerGrabbed = 1; XWarpPointer(Dpy,None,win.Win,0,0,0,0,0,0); XWarpPointer(Dpy,None,win.Win,0,0,0,0,w/2,h/2); } XStoreName( Dpy, win.Win, SYS_APPNAME); XSetIconName( Dpy, win.Win, SYS_APPNAME); // clear garbage fast? glViewport(0,0,w,h); glClearColor(0,0,0,0); glClear( GL_COLOR_BUFFER_BIT ); microgl_swapbuffers(); return 1; }
main() { Window w2; Display *dpy = XOpenDisplay(NIL); assert(dpy); Screen *scr = DefaultScreenOfDisplay(dpy); // CreateWindow Window w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL); XDestroyWindow(dpy, w); // CreateWindow with arguments XSetWindowAttributes swa; swa.background_pixel = WhitePixelOfScreen(scr); swa.bit_gravity = NorthWestGravity; swa.border_pixel = BlackPixelOfScreen(scr); swa.colormap = DefaultColormapOfScreen(scr); swa.cursor = None; swa.win_gravity = NorthGravity; w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent, CopyFromParent, CopyFromParent, CWBackPixel | CWBitGravity | CWBorderPixel | CWColormap | CWCursor | CWWinGravity, &swa); // CreateWindow with other arguments XDestroyWindow(dpy, w); Pixmap pixmap = XCreatePixmap(dpy, RootWindowOfScreen(scr), 45, 25, DefaultDepthOfScreen(scr)); assert(pixmap); swa.background_pixmap = pixmap; swa.border_pixmap = pixmap; w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent, CopyFromParent, CopyFromParent, CWBackPixmap | CWBorderPixmap, &swa); // ChangeWindowAttributes swa.backing_planes = 0x1; swa.backing_pixel = WhitePixelOfScreen(scr); swa.save_under = True; swa.event_mask = KeyPressMask | KeyReleaseMask; swa.do_not_propagate_mask = ButtonPressMask | Button4MotionMask; swa.override_redirect = False; XChangeWindowAttributes(dpy, w, CWBackingPlanes | CWBackingPixel | CWSaveUnder | CWEventMask | CWDontPropagate | CWOverrideRedirect, &swa); // GetWindowAttributes XWindowAttributes wa; Status success = XGetWindowAttributes(dpy, w, &wa); // DestroyWindow (done) // DestroySubwindows w2 = XCreateWindow(dpy, w, 20, 30, 40, 50, 3, CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL); XDestroySubwindows(dpy, w); // ChangeSaveSet // Display *dpy2 = XOpenDisplay(NIL); // assert(dpy2); // XAddToSaveSet(dpy2, w); // XCloseDisplay(dpy2); // ReparentWindow w2 = XCreateWindow(dpy, RootWindowOfScreen(scr), 20, 30, 40, 50, 3, CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL); XReparentWindow(dpy, w2, w, 10, 5); // MapWindow XMapWindow(dpy, w); // MapSubwindows XMapSubwindows(dpy, w); // UnmapWindow XUnmapWindow(dpy, w); // UnmapSubwindows XMapWindow(dpy, w); XUnmapSubwindows(dpy, w2); XMapSubwindows(dpy, w); // ConfigureWindow Window w3 = XCreateWindow(dpy, w, 10, 50, 100, 10, 2, CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL); XMapWindow(dpy, w3); XWindowChanges wc; wc.x = -5; wc.y = -10; wc.width = 50; wc.height = 40; wc.border_width = 7; wc.sibling = w2; wc.stack_mode = Opposite; XConfigureWindow(dpy, w3, CWX | CWY | CWWidth | CWHeight | CWBorderWidth | CWSibling | CWStackMode, &wc); // CirculateWindow XCirculateSubwindows(dpy, w, RaiseLowest); // GetGeometry Window root; int x, y; unsigned width, height, border_width, depth; XGetGeometry(dpy, w, &root, &x, &y, &width, &height, &border_width, &depth); // QueryTree Window parent; Window *children; unsigned nchildren; success = XQueryTree(dpy, w, &root, &parent, &children, &nchildren); XFree(children); // InternAtom Atom a = XInternAtom(dpy, "WM_PROTOCOLS", True); // GetAtomName char *string = XGetAtomName(dpy, XA_PRIMARY); XFree(string); // ChangeProperty XStoreName(dpy, w, "test window"); // DeleteProperty XDeleteProperty(dpy, w, XA_WM_NAME); // GetProperty // TODO // ListProperties int num_prop; Atom *list = XListProperties(dpy, w, &num_prop); XFree(list); // SetSelectionOwner XSetSelectionOwner(dpy, XA_PRIMARY, w, 12000); XSetSelectionOwner(dpy, XA_SECONDARY, w, CurrentTime); // GetSelectionOwner Window wx = XGetSelectionOwner(dpy, XA_PRIMARY); // ConvertSelection XConvertSelection(dpy, XA_SECONDARY, XA_CURSOR, XA_POINT, w, CurrentTime); // SendEvent // GrabPointer std::cerr << "Grabbing" << std::endl; int res = XGrabPointer(dpy, w, False, Button5MotionMask | PointerMotionHintMask, GrabModeSync, GrabModeAsync, w, None, CurrentTime); XSync(dpy, False); // sleep(5); // UngrabPointer std::cerr << "Ungrabbing" << std::endl; XUngrabPointer(dpy, CurrentTime); // GrabButton XGrabButton(dpy, 3, ShiftMask | ControlMask, w, False, PointerMotionHintMask | Button2MotionMask, GrabModeAsync, GrabModeSync, None, None); XGrabButton(dpy, 2, AnyModifier, w, False, PointerMotionHintMask | Button2MotionMask, GrabModeAsync, GrabModeSync, None, None); // UngrabButton XUngrabButton(dpy, 2, LockMask, w); // ChangeActivePointerGrab XChangeActivePointerGrab(dpy, ButtonPressMask, None, CurrentTime); // GrabKeyboard XGrabKeyboard(dpy, w, True, GrabModeSync, GrabModeSync, 12000); // UngrabKeyboard XUngrabKeyboard(dpy, 13000); // GrabKey XGrabKey(dpy, XKeysymToKeycode(dpy, XK_Tab), ShiftMask | Mod3Mask, w, True, GrabModeSync, GrabModeSync); // UngrabKey XUngrabKey(dpy, AnyKey, AnyModifier, w); // AllowEvents XAllowEvents(dpy, AsyncPointer, 14000); // GrabServer XGrabServer(dpy); // UngrabServer XUngrabServer(dpy); // QueryPointer Window child; int root_x, root_y, win_x, win_y; unsigned mask; Bool bres = XQueryPointer(dpy, w, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask); // GetMotionEvents int nevents; XGetMotionEvents(dpy, w, 15000, 16000, &nevents); // TranslateCoordinates int dest_x, dest_y; XTranslateCoordinates(dpy, w, w2, 10, 20, &dest_x, &dest_y, &child); // WarpPointer XWarpPointer(dpy, w, w2, 0, 0, 100, 100, 20, 30); // SetInputFocus XSetInputFocus(dpy,w, RevertToPointerRoot, 17000); XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, 17000); // GetInputFocus Window focus; int revert_to; XGetInputFocus(dpy, &focus, &revert_to); // QueryKeymap char keys_return[32]; XQueryKeymap(dpy, keys_return); // OpenFont Font fid = XLoadFont(dpy, "cursor"); // CloseFont XUnloadFont(dpy, fid); // QueryFont XFontStruct *fs = XLoadQueryFont(dpy, "cursor"); assert(fs); // QueryTextExtents int direction, font_ascent, font_descent; XCharStruct overall; XQueryTextExtents(dpy, fs -> fid, "toto", 4, &direction, &font_ascent, &font_descent, &overall); XQueryTextExtents(dpy, fs -> fid, "odd__length", 11, &direction, &font_ascent, &font_descent, &overall); XChar2b c2bs; c2bs.byte1 = '$'; c2bs.byte2 = 'B'; XQueryTextExtents16(dpy, fs -> fid, &c2bs, 1, &direction, &font_ascent, &font_descent, &overall); XQueryTextExtents(dpy, fs -> fid, longString, strlen(longString), &direction, &font_ascent, &font_descent, &overall); // ListFonts int actual_count; char **fontList = XListFonts(dpy, "*", 100, &actual_count); XFree((char *)fontList); // ListFontsWithInfo int count; XFontStruct *info; char **names = XListFontsWithInfo(dpy, "*", 100, &count, &info); XFreeFontInfo(names, info, count); // SetFontPath // GetFontPath int npaths; char **charList = XGetFontPath(dpy, &npaths); char **charList2 = new char *[npaths + 1]; memcpy(charList2, charList, npaths * sizeof(char *)); charList2[npaths] = charList2[0]; XSetFontPath(dpy, charList2, npaths + 1); XSetFontPath(dpy, charList, npaths); // Reset to some reasonnable value XFreeFontPath(charList); delete [] charList2; // CreatePixmap Pixmap pix2 = XCreatePixmap(dpy, w, 100, 200, DefaultDepthOfScreen(scr)); // FreePixmap XFreePixmap(dpy, pix2); // CreateGC Pixmap bitmap = XCreateBitmapFromData(dpy, RootWindowOfScreen(scr), "\000\000\001\000\000\001\000\000\001\377\377\377", 3, 4); XGCValues gcv; gcv.function = GXand; gcv.plane_mask = 0x1; gcv.foreground = WhitePixelOfScreen(scr); gcv.background = BlackPixelOfScreen(scr); gcv.line_width = 2; gcv.line_style = LineDoubleDash; gcv.cap_style = CapProjecting; gcv.join_style = JoinRound; gcv.fill_style = FillStippled; gcv.fill_rule = EvenOddRule; gcv.arc_mode = ArcPieSlice; gcv.tile = pixmap; gcv.stipple = bitmap; gcv.ts_x_origin = 3; gcv.ts_y_origin = 4; gcv.font = fs -> fid; gcv.subwindow_mode = ClipByChildren; gcv.graphics_exposures = True; gcv.clip_x_origin = 5; gcv.clip_y_origin = 6; gcv.clip_mask = bitmap; gcv.dash_offset = 1; gcv.dashes = 0xc2; GC gc = XCreateGC(dpy, w, GCFunction | GCPlaneMask | GCForeground | GCBackground | GCLineWidth | GCLineStyle | GCCapStyle | GCJoinStyle | GCFillStyle | GCFillRule | GCTile | GCStipple | GCTileStipXOrigin | GCTileStipYOrigin | GCFont | GCSubwindowMode | GCGraphicsExposures | GCClipXOrigin | GCClipYOrigin | GCClipMask | GCDashOffset | GCDashList | GCArcMode, &gcv); // ChangeGC gcv.function = GXandReverse; // Only a few of these should appear, since the values are cached on the client side by the Xlib. XChangeGC(dpy, gc, GCFunction | GCLineStyle | GCStipple | GCGraphicsExposures | GCDashList, &gcv); // CopyGC GC gc2 = XCreateGC(dpy, w, 0, NIL); XCopyGC(dpy, gc, GCFunction | GCLineStyle | GCStipple | GCGraphicsExposures | GCDashList, gc2); // SetDashes XSetDashes(dpy, gc, 3, "\001\377\001", 3); // SetClipRectangles XRectangle rectangles[] = { { 10, 20, 30, 40 }, { 100, 200, 5, 3 }, { -5, 1, 12, 24 } }; XSetClipRectangles(dpy, gc, 12, 9, rectangles, SIZEOF(rectangles), Unsorted); // FreeGC // done already // ClearArea XClearArea(dpy, w, 30, 10, 10, 100, False); // CopyArea XCopyArea(dpy, w, pixmap, gc, 0, 0, 100, 100, 10, 10); // CopyPlane // This won't work if the Screen doesn't have at least 3 planes XCopyPlane(dpy, pixmap, w, gc, 20, 10, 40, 30, 0, 0, 0x4); // PolyPoint XDrawPoint(dpy, w, gc, 1, 2); XPoint points[] = { { 3, 4 }, { 5, 6 } }; XDrawPoints(dpy, w, gc, points, SIZEOF(points), CoordModeOrigin); // PolyLine XDrawLines(dpy, w, gc, points, SIZEOF(points), CoordModePrevious); // PolySegment XSegment segments[] = { { 7, 8, 9, 10 }, { 11, 12, 13, 14 }, { 15, 16, 17, 18 } }; XDrawSegments(dpy, w, gc, segments, SIZEOF(segments)); // PolyRectangle XDrawRectangles(dpy, w, gc, rectangles, SIZEOF(rectangles)); // PolyArc XArc arcs[] = { { 10, 20, 30, 40, 50, 60 }, { -70, 80, 90, 100, 110, 120 }, { 10, 20, 30, 40, 50, -30 } }; XDrawArcs(dpy, w, gc, arcs, SIZEOF(arcs)); // FillPoly XFillPolygon(dpy, w, gc, points, SIZEOF(points), Convex, CoordModePrevious); // PolyFillRectangle XFillRectangles(dpy, w, gc, rectangles, SIZEOF(rectangles)); // PolyFillArc XFillArcs(dpy, w, gc, arcs, SIZEOF(arcs)); // PutImage // GetImage XImage *image = XGetImage(dpy, w, 10, 20, 40, 30, AllPlanes, ZPixmap); XPutImage(dpy, w, gc, image, 0, 0, 50, 60, 40, 30); XSync(dpy, False); // Make the next request starts at the beginning of a packet // PolyText8 XTextItem textItems[3]; textItems[0].chars = "toto"; textItems[0].nchars = strlen(textItems[0].chars); textItems[0].delta = -3; textItems[0].font = fs->fid; textItems[1].chars = "titi"; textItems[1].nchars = strlen(textItems[1].chars); textItems[1].delta = 3; textItems[1].font = None; textItems[2].chars = "tutu"; textItems[2].nchars = strlen(textItems[2].chars); textItems[2].delta = 0; textItems[2].font = fs->fid; XDrawText(dpy, w, gc, 10, 10, textItems, 3); XTextItem textItems2[3]; textItems2[0].chars = "totox"; textItems2[0].nchars = strlen(textItems2[0].chars); textItems2[0].delta = -3; textItems2[0].font = fs->fid; textItems2[1].chars = "titi"; textItems2[1].nchars = strlen(textItems2[1].chars); textItems2[1].delta = 3; textItems2[1].font = None; textItems2[2].chars = "tutu"; textItems2[2].nchars = strlen(textItems2[2].chars); textItems2[2].delta = 0; textItems2[2].font = fs->fid; XDrawText(dpy, w, gc, 10, 10, textItems2, 3); // PolyText16 XChar2b c2b2[] = { 0, 't', 0, 'x' }; XTextItem16 items16[] = { { &c2bs, 1, -5, None }, { NULL, 0, 0, None }, { c2b2, 2, 0, fs -> fid } }; XDrawText16(dpy, w, gc, 10, 0, items16, SIZEOF(items16)); // ImageText8 XDrawImageString(dpy, w, gc, 10, 10, "toto", 4); // ImageText16 XDrawImageString16(dpy, w, gc, 10, 10, &c2bs, 1); XDrawImageString16(dpy, w, gc, 10, 20, c2b2, 2); // CreateColormap // Don't forget to tell the kids how it was when we had only 8 bits per pixel. Colormap colormap = XCreateColormap(dpy, w, DefaultVisualOfScreen(scr), None); // FreeColormap XFreeColormap(dpy, colormap); colormap = XCreateColormap(dpy, w, DefaultVisualOfScreen(scr), None); // CopyColormapAndFree Colormap colormap2 = XCopyColormapAndFree(dpy, colormap); // InstallColormap XInstallColormap(dpy, colormap2); // UninstallColormap XUninstallColormap(dpy, colormap2); // ListInstalledColormaps int num; Colormap *colormapList = XListInstalledColormaps(dpy, w, &num); // AllocColor XColor screen; screen.red = 0; screen.green = 32767; screen.blue = 65535; screen.flags = DoRed | DoGreen | DoBlue; success = XAllocColor(dpy, colormap, &screen); // AllocNamedColor XColor screen2, exact; success = XAllocNamedColor(dpy, colormap, "Wheat", &screen2, &exact); // AllocColorCells unsigned long plane_masks, pixels; success = XAllocColorCells(dpy, colormap, False, &plane_masks, 1, &pixels, 1); // AllocColorPlanes unsigned long rmask, gmask, bmask; success = XAllocColorPlanes(dpy, colormap, False, &pixels, 1, 0, 0, 0, &rmask, &gmask, &bmask); // FreeColors unsigned long pixels2[2] = { screen.pixel, screen2.pixel }; XFreeColors(dpy, colormap, pixels2, 2, 0); // StoreColors success = XAllocColorCells(dpy, colormap, False, NIL, 0, pixels2, 2); // On many contemporary (that is, year 2000) video cards, you can't allocate read / write cells // I want my requests to be sent, however. if (!success) { XSetErrorHandler(errorHandler); } XColor colors[2]; colors[0] = screen; colors[0].pixel = pixels2[0]; colors[1] = screen2; colors[1].pixel = pixels2[1]; XStoreColors(dpy, colormap, colors, 2); // StoreNamedColor XStoreNamedColor(dpy, colormap, "Wheat", colors[0].pixel, DoBlue); XSync(dpy, False); XSetErrorHandler(NIL); // Restore the default handler // QueryColors screen2.pixel = WhitePixelOfScreen(scr); XQueryColor(dpy, colormap, &screen2); // LookupColor success = XLookupColor(dpy, colormap, "DarkCyan", &exact, &screen); // CreateCursor Cursor cursor = XCreatePixmapCursor(dpy, pixmap, None, &exact, colors, 10, 10); // CreateGlyphCursor Cursor cursor2 = XCreateGlyphCursor(dpy, fs -> fid, fs -> fid, 'X', 0, &exact, colors); // FreeCursor XFreeCursor(dpy, cursor2); // RecolorCursor XRecolorCursor(dpy, cursor, colors, &exact); // QueryBestSize success = XQueryBestSize(dpy, CursorShape, RootWindowOfScreen(scr), 100, 20, &width, &height); // QueryExtension int major_opcode, first_event, first_error; XQueryExtension(dpy, "toto", &major_opcode, &first_event, &first_error); // ListExtensions int nextensions; char **extensionList = XListExtensions(dpy, &nextensions); for(char **p = extensionList; nextensions; nextensions--, p++) std::cout << *p << std::endl; XFree(extensionList); // ChangeKeyboardMapping // GetKeyboardMapping int min_keycodes, max_keycodes; XDisplayKeycodes(dpy, &min_keycodes, &max_keycodes); int keysyms_per_keycode; KeySym *keysyms = XGetKeyboardMapping(dpy, min_keycodes, max_keycodes - min_keycodes + 1, &keysyms_per_keycode); XChangeKeyboardMapping(dpy, min_keycodes, keysyms_per_keycode, keysyms, max_keycodes - min_keycodes + 1); // ChangeKeyboardControl // GetKeyboardControl XKeyboardState keyboardState; XGetKeyboardControl(dpy, &keyboardState); XKeyboardControl keyboardValues; keyboardValues.key_click_percent = keyboardState.key_click_percent; keyboardValues.bell_percent = keyboardState.bell_percent; keyboardValues.bell_pitch = keyboardState.bell_pitch; keyboardValues.bell_duration = keyboardState.bell_duration; keyboardValues.led = 1; keyboardValues.led_mode = LedModeOn; keyboardValues.key = min_keycodes; keyboardValues.auto_repeat_mode = AutoRepeatModeDefault; XChangeKeyboardControl(dpy, KBKeyClickPercent | KBBellPercent | KBBellPitch | KBBellDuration | KBLed | KBLedMode | KBKey | KBAutoRepeatMode, &keyboardValues); // Bell XBell(dpy, 90); // ChangePointerControl // GetPointerControl int accel_numerator, accel_denominator, threshold; XGetPointerControl(dpy, &accel_numerator, &accel_denominator, &threshold); XChangePointerControl(dpy, True, True, accel_numerator, accel_denominator, threshold); // SetScreenSaver // GetScreenSaver int timeout, interval, prefer_blanking, allow_exposures; XGetScreenSaver(dpy, &timeout, &interval, &prefer_blanking, &allow_exposures); XSetScreenSaver(dpy, timeout, interval, prefer_blanking, allow_exposures); // ChangeHosts // ListHosts int nhosts; Bool state; XHostAddress *hostList = XListHosts(dpy, &nhosts, &state); XHostAddress host; host.family = FamilyInternet; host.length = 4; host.address = "\001\002\003\004"; XAddHost(dpy, &host); // SetAccessControl XSetAccessControl(dpy, EnableAccess); // SetCloseDownMode XSetCloseDownMode(dpy, RetainTemporary); // KillClient XKillClient(dpy, AllTemporary); // RotateProperties Atom properties[] = { XInternAtom(dpy, "CUT_BUFFER0", False), XInternAtom(dpy, "CUT_BUFFER1", False), XInternAtom(dpy, "CUT_BUFFER2", False) }; XRotateWindowProperties(dpy, RootWindowOfScreen(scr), properties, SIZEOF(properties), -1); // ForceScreenSaver XForceScreenSaver(dpy, ScreenSaverReset); // SetPointerMapping // GetPointerMapping unsigned char map[64]; int map_length = XGetPointerMapping(dpy, map, 64); XSetPointerMapping(dpy, map, map_length); // SetModifierMapping // GetModifierMapping XModifierKeymap *modmap = XGetModifierMapping(dpy); XSetModifierMapping(dpy, modmap); // NoOperation XNoOp(dpy); for(;;) { XEvent e; XNextEvent(dpy, &e); std::cout << "Got an event of type " << e.type << std::endl; } }
GuiCalibratorX11::GuiCalibratorX11(Calibrator* calibrator0) : calibrator(calibrator0), time_elapsed(0) { // setup strings get_display_texts(&display_texts, calibrator0); display = XOpenDisplay(NULL); if (display == NULL) { throw std::runtime_error("Unable to connect to X server"); } screen_num = DefaultScreen(display); // Load font and get font information structure font_info = XLoadQueryFont(display, "9x15"); if (font_info == NULL) { // fall back to native font font_info = XLoadQueryFont(display, "fixed"); if (font_info == NULL) { XCloseDisplay(display); throw std::runtime_error("Unable to open neither '9x15' nor 'fixed' font"); } } int width = 0, height = 0; int offset_x = 0, offset_y = 0; detect_screen_geometry(&width, &height, &offset_x, &offset_y); set_display_size(width, height); // parse geometry string int ox, oy, gw, gh; if (calibrator->get_parsed_geometry(&ox, &oy, &gw, &gh)) { offset_x = ox; offset_y = oy; set_display_size(gw, gh); } // Register events on the window XSetWindowAttributes attributes; attributes.override_redirect = True; attributes.event_mask = ExposureMask | KeyPressMask | ButtonPressMask; win = XCreateWindow(display, RootWindow(display, screen_num), offset_x, offset_y, display_width, display_height, 0, CopyFromParent, InputOutput, CopyFromParent, CWOverrideRedirect | CWEventMask, &attributes); XMapWindow(display, win); // Listen to events XGrabKeyboard(display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(display, win, False, ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); Colormap colormap = DefaultColormap(display, screen_num); XColor color; for (int i = 0; i != NUM_COLORS; i++) { XParseColor(display, colormap, colors[i], &color); XAllocColor(display, colormap, &color); pixel[i] = color.pixel; } XSetWindowBackground(display, win, pixel[GRAY]); XClearWindow(display, win); gc = XCreateGC(display, win, 0, NULL); XSetFont(display, gc, font_info->fid); // Setup timer for animation #ifdef HAVE_TIMERFD struct itimerspec timer; unsigned int period = time_step * 1000; // microseconds unsigned int sec = period/1000000; unsigned int ns = (period - (sec * 1000000)) * 1000; timer.it_value.tv_sec = sec; timer.it_value.tv_nsec = ns; timer.it_interval = timer.it_value; timer_fd = timerfd_create(CLOCK_MONOTONIC, 0); timerfd_settime(timer_fd, 0, &timer, NULL); #else signal(SIGALRM, sigalarm_handler); struct itimerval timer; timer.it_value.tv_sec = time_step/1000; timer.it_value.tv_usec = (time_step % 1000) * 1000; timer.it_interval = timer.it_value; setitimer(ITIMER_REAL, &timer, NULL); #endif }
int main(int argc, char *argv[]) { // Minimal options char fullscreen = 1; if(argc != 1) { if(strcmp(argv[1], "-h") == 0) { printf("lock. Use -n to not go to leave the desktop visible\n"); return 0; } if(strcmp(argv[1], "-n") == 0) { fullscreen = 0; } } // Open Display Display *display = XOpenDisplay(NULL); XSetCloseDownMode(display, DestroyAll); // Initialize PAM pam_handle_t *pamh; struct pam_conv conv; conv.conv = pam_nocomm; if(pam_start("xscreensaver", (getpwuid(getuid()))->pw_name, &conv, &pamh) != PAM_SUCCESS) { exit(1); } // Create and map window XSetWindowAttributes at; at.override_redirect = 1; at.event_mask = KeyPressMask; Window w = XCreateWindow(display, DefaultRootWindow(display), 0, 0, 100, 100, 1, CopyFromParent, CopyFromParent, CopyFromParent, CWOverrideRedirect | CWEventMask, &at); XWindowAttributes xwa; XGetWindowAttributes(display, DefaultRootWindow(display), &xwa); if(fullscreen == 1) { XMoveResizeWindow(display, w, 0, 0, xwa.width, xwa.height); } else { XMoveResizeWindow(display, w, 0, 0, 1, 1); } XMapWindow(display, w); XRaiseWindow(display, w); XSync(display, False); // Wait for the WM to settle.. sleep(1); // Grab Pointer & Keyboard for(int tries=0; XGrabPointer(display, w, False, ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, w, None, CurrentTime) != GrabSuccess; tries++) { if(tries > 3) { exit(1); } sleep(1); } for(int tries=0; XGrabKeyboard(display, w, False, GrabModeAsync, GrabModeAsync, CurrentTime) != GrabSuccess; tries++) { if(tries > 3) { exit(1); } sleep(1); } XSetWindowBackground(display, w, 0); XClearWindow(display, w); XSync(display, False); // Disable screen if(fullscreen == 1) { DPMSForceLevel(display, DPMSModeOff); } // Read password from keyboard events, // verify, loop where required XEvent xev; char inputBuffer[4]; int passwordBufferLength = 0; while(True) { // Read password passwordBufferLength = 0; while(True) { XNextEvent(display, &xev); if(xev.type != 2 /* KeyPress */) { continue; } KeySym keysym = XLookupKeysym((XKeyEvent *)&xev, 0); if(keysym == XK_BackSpace && passwordBufferLength > 0) { passwordBufferLength--; } else if(keysym == XK_Return) { break; } else if(XLookupString((XKeyEvent *)&xev, inputBuffer, 4, NULL, NULL) == 1) { int len = strlen(inputBuffer); if(passwordBufferLength + len < sizeof(passwordBuffer)) { memcpy(passwordBuffer + passwordBufferLength, inputBuffer, len); passwordBufferLength += len; } } } passwordBuffer[passwordBufferLength] = 0; // Verify password pam_set_item(pamh, PAM_AUTHTOK, passwordBuffer); if(pam_authenticate(pamh, PAM_SILENT) == PAM_SUCCESS) { break; } } // Clean up pam_end(pamh, 0); XUnmapWindow(display, w); XUngrabServer(display); XFlush(display); return 0; }
int main(int argc, char **argv){ XEvent ev; KeySym ks; char cbuf[10], rbuf[128]; /* shadow appears to suggest 127 a good value here */ int clen, rlen=0; long goodwill= INITIALGOODWILL, timeout= 0; XSetWindowAttributes attrib; Cursor cursor; Pixmap csr_source,csr_mask; XColor csr_fg, csr_bg, dummy, black; int ret, screen, blank = 0, fork_after = 0; #ifdef SHADOW_PWD struct spwd *sp; #endif struct timeval tv; int tvt, gs; int opt, index, cmdlen = 0; char cmdstr[CMDMAXLEN] = {0}; #if 0 while (argc > 1) { if ((strcmp(argv[1], "-b") == 0)) { blank = 1; argc--; argv++; } else if ((strcmp(argv[1], "-f") == 0)) { fork_after = 1; argc--; argv++; } else { fprintf(stderr,"xtrlock (version %s); usage: xtrlock [-b] [-f]\n", program_version); exit(1); } } #endif while ((opt = getopt (argc, argv, "bc:f")) != -1) { switch (opt) { case 'b': blank = 1; break; case 'c': strncpy(cmdstr, optarg, CMDMAXLEN - 1); cmdlen = strlen(cmdstr); break; case 'f': fork_after = 1; break; default: fprintf(stderr,"xtrlock (version %s mod); usage: xtrlock [-b] [-c command] [-f]\n", program_version); exit(1); } } /* Make sure not to consume the next input option */ if (cmdstr[0] == '-') { fprintf (stderr, "Option -c requires an argument.\n"); exit(1); } if (cmdstr[0]) { for (index = optind; index < argc; index++) { cmdlen += strlen(argv[index]) + 1; if (cmdlen < CMDMAXLEN) { strcat(cmdstr, " "); strcat(cmdstr, argv[index]); } else { fprintf (stderr, "Command too large. Ignoring.\n"); cmdlen = 0; break; } } } if (cmdlen) fprintf(stdout, "cmd: [%s]\n", cmdstr); errno=0; pw= getpwuid(getuid()); if (!pw) { perror("password entry for uid not found"); exit(1); } #ifdef SHADOW_PWD sp = getspnam(pw->pw_name); if (sp) pw->pw_passwd = sp->sp_pwdp; endspent(); #endif /* logically, if we need to do the following then the same applies to being installed setgid shadow. we do this first, because of a bug in linux. --jdamery */ if (setgid(getgid())) { perror("setgid"); exit(1); } /* we can be installed setuid root to support shadow passwords, and we don't need root privileges any longer. --marekm */ if (setuid(getuid())) { perror("setuid"); exit(1); } if (strlen(pw->pw_passwd) < 13) { fputs("password entry has no pwd\n",stderr); exit(1); } display= XOpenDisplay(0); if (display==NULL) { fprintf(stderr,"xtrlock (version %s): cannot open display\n", program_version); exit(1); } attrib.override_redirect= True; if (blank) { screen = DefaultScreen(display); attrib.background_pixel = BlackPixel(display, screen); window= XCreateWindow(display,DefaultRootWindow(display), 0,0,DisplayWidth(display, screen),DisplayHeight(display, screen), 0,DefaultDepth(display, screen), CopyFromParent, DefaultVisual(display, screen), CWOverrideRedirect|CWBackPixel,&attrib); XAllocNamedColor(display, DefaultColormap(display, screen), "black", &black, &dummy); } else { window= XCreateWindow(display,DefaultRootWindow(display), 0,0,1,1,0,CopyFromParent,InputOnly,CopyFromParent, CWOverrideRedirect,&attrib); } XSelectInput(display,window,KeyPressMask|KeyReleaseMask); csr_source= XCreateBitmapFromData(display,window,lock_bits,lock_width,lock_height); csr_mask= XCreateBitmapFromData(display,window,mask_bits,mask_width,mask_height); ret = XAllocNamedColor(display, DefaultColormap(display, DefaultScreen(display)), "steelblue3", &dummy, &csr_bg); if (ret==0) XAllocNamedColor(display, DefaultColormap(display, DefaultScreen(display)), "black", &dummy, &csr_bg); ret = XAllocNamedColor(display, DefaultColormap(display,DefaultScreen(display)), "grey25", &dummy, &csr_fg); if (ret==0) XAllocNamedColor(display, DefaultColormap(display, DefaultScreen(display)), "white", &dummy, &csr_bg); cursor= XCreatePixmapCursor(display,csr_source,csr_mask,&csr_fg,&csr_bg, lock_x_hot,lock_y_hot); XMapWindow(display,window); /*Sometimes the WM doesn't ungrab the keyboard quickly enough if *launching xtrlock from a keystroke shortcut, meaning xtrlock fails *to start We deal with this by waiting (up to 100 times) for 10,000 *microsecs and trying to grab each time. If we still fail *(i.e. after 1s in total), then give up, and emit an error */ gs=0; /*gs==grab successful*/ for (tvt=0 ; tvt<100; tvt++) { ret = XGrabKeyboard(display,window,False,GrabModeAsync,GrabModeAsync, CurrentTime); if (ret == GrabSuccess) { gs=1; break; } /*grab failed; wait .01s*/ tv.tv_sec=0; tv.tv_usec=10000; select(1,NULL,NULL,NULL,&tv); } if (gs==0){ fprintf(stderr,"xtrlock (version %s): cannot grab keyboard\n", program_version); exit(1); } if (XGrabPointer(display,window,False,(KeyPressMask|KeyReleaseMask)&0, GrabModeAsync,GrabModeAsync,None, cursor,CurrentTime)!=GrabSuccess) { XUngrabKeyboard(display,CurrentTime); fprintf(stderr,"xtrlock (version %s): cannot grab pointer\n", program_version); exit(1); } if (fork_after) { pid_t pid = fork(); if (pid < 0) { fprintf(stderr,"xtrlock (version %s): cannot fork: %s\n", program_version, strerror(errno)); exit(1); } else if (pid > 0) { exit(0); } } for (;;) { XNextEvent(display,&ev); switch (ev.type) { case KeyPress: if (ev.xkey.time < timeout) { XBell(display,0); break; } clen= XLookupString(&ev.xkey,cbuf,9,&ks,0); switch (ks) { case XK_Escape: case XK_Clear: rlen=0; break; case XK_Delete: case XK_BackSpace: if (rlen>0) rlen--; break; case XK_Linefeed: case XK_Return: if (rlen==0) break; rbuf[rlen]=0; if (passwordok(rbuf)) goto loop_x; XBell(display,0); rlen= 0; if (timeout) { goodwill+= ev.xkey.time - timeout; if (goodwill > MAXGOODWILL) { goodwill= MAXGOODWILL; } } timeout= -goodwill*GOODWILLPORTION; goodwill+= timeout; timeout+= ev.xkey.time + TIMEOUTPERATTEMPT; break; default: if (clen != 1) break; /* allow space for the trailing \0 */ if (rlen < (sizeof(rbuf) - 1)){ rbuf[rlen]=cbuf[0]; rlen++; } break; } break; default: break; } } loop_x: if (cmdlen) execl("/bin/sh", "sh", "-c", cmdstr, (char *) 0); exit(0); }
int TkPointerEvent( register XEvent *eventPtr, /* Pointer to the event. */ TkWindow *winPtr) /* Tk's information for window where event was * reported. */ { register TkWindow *winPtr2; TkDisplay *dispPtr = winPtr->dispPtr; unsigned int serial; int outsideGrabTree = 0; int ancestorOfGrab = 0; int appGrabbed = 0; /* Non-zero means event is being reported to * an application that is affected by the * grab. */ /* * Collect information about the grab (if any). */ switch (TkGrabState(winPtr)) { case TK_GRAB_IN_TREE: appGrabbed = 1; break; case TK_GRAB_ANCESTOR: appGrabbed = 1; outsideGrabTree = 1; ancestorOfGrab = 1; break; case TK_GRAB_EXCLUDED: appGrabbed = 1; outsideGrabTree = 1; break; } if ((eventPtr->type == EnterNotify) || (eventPtr->type == LeaveNotify)) { /* * Keep track of what window the mouse is *really* over. Any events * that we generate have a special send_event value, which is detected * below and used to ignore the event for purposes of setting * serverWinPtr. */ if (eventPtr->xcrossing.send_event != GENERATED_GRAB_EVENT_MAGIC) { if ((eventPtr->type == LeaveNotify) && (winPtr->flags & TK_TOP_HIERARCHY)) { dispPtr->serverWinPtr = NULL; } else { dispPtr->serverWinPtr = winPtr; } } /* * When a grab is active, X continues to report enter and leave events * for windows outside the tree of the grab window: * 1. Detect these events and ignore them except for windows above the * grab window. * 2. Allow Enter and Leave events to pass through the windows above * the grab window, but never let them end up with the pointer *in* * one of those windows. */ if (dispPtr->grabWinPtr != NULL) { if (outsideGrabTree && appGrabbed) { if (!ancestorOfGrab) { return 0; } switch (eventPtr->xcrossing.detail) { case NotifyInferior: return 0; case NotifyAncestor: eventPtr->xcrossing.detail = NotifyVirtual; break; case NotifyNonlinear: eventPtr->xcrossing.detail = NotifyNonlinearVirtual; break; } } /* * Make buttons have the same grab-like behavior inside a grab as * they do outside a grab: do this by ignoring enter and leave * events except for the window in which the button was pressed. */ if ((dispPtr->buttonWinPtr != NULL) && (winPtr != dispPtr->buttonWinPtr)) { return 0; } } return 1; } if (!appGrabbed) { return 1; } if (eventPtr->type == MotionNotify) { /* * When grabs are active, X reports motion events relative to the * window under the pointer. Instead, it should report the events * relative to the window the button went down in, if there is a * button down. Otherwise, if the pointer window is outside the * subtree of the grab window, the events should be reported relative * to the grab window. Otherwise, the event should be reported to the * pointer window. */ winPtr2 = winPtr; if (dispPtr->buttonWinPtr != NULL) { winPtr2 = dispPtr->buttonWinPtr; } else if (outsideGrabTree || (dispPtr->serverWinPtr == NULL)) { winPtr2 = dispPtr->grabWinPtr; } if (winPtr2 != winPtr) { TkChangeEventWindow(eventPtr, winPtr2); Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD); return 0; } return 1; } /* * Process ButtonPress and ButtonRelease events: * 1. Keep track of whether a button is down and what window it went down * in. * 2. If the first button goes down outside the grab tree, pretend it went * down in the grab window. Note: it's important to redirect events to * the grab window like this in order to make things like menus work, * where button presses outside the grabbed menu need to be seen. An * application can always ignore the events if they occur outside its * window. * 3. If a button press or release occurs outside the window where the * first button was pressed, retarget the event so it's reported to the * window where the first button was pressed. * 4. If the last button is released in a window different than where the * first button was pressed, generate Enter/Leave events to move the * mouse from the button window to its current window. * 5. If the grab is set at a time when a button is already down, or if * the window where the button was pressed was deleted, then * dispPtr->buttonWinPtr will stay NULL. Just forget about the * auto-grab for the button press; events will go to whatever window * contains the pointer. If this window isn't in the grab tree then * redirect events to the grab window. * 6. When a button is pressed during a local grab, the X server sets a * grab of its own, since it doesn't even know about our local grab. * This causes enter and leave events no longer to be generated in the * same way as for global grabs. To eliminate this problem, set a * temporary global grab when the first button goes down and release it * when the last button comes up. */ if ((eventPtr->type == ButtonPress) || (eventPtr->type == ButtonRelease)) { winPtr2 = dispPtr->buttonWinPtr; if (winPtr2 == NULL) { if (outsideGrabTree) { winPtr2 = dispPtr->grabWinPtr; /* Note 5. */ } else { winPtr2 = winPtr; /* Note 5. */ } } if (eventPtr->type == ButtonPress) { if (!(eventPtr->xbutton.state & ALL_BUTTONS)) { if (outsideGrabTree) { TkChangeEventWindow(eventPtr, dispPtr->grabWinPtr); Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD); return 0; /* Note 2. */ } if (!(dispPtr->grabFlags & GRAB_GLOBAL)) { /* Note 6. */ serial = NextRequest(dispPtr->display); if (XGrabPointer(dispPtr->display, dispPtr->grabWinPtr->window, True, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == 0) { EatGrabEvents(dispPtr, serial); if (XGrabKeyboard(dispPtr->display, winPtr->window, False, GrabModeAsync, GrabModeAsync, CurrentTime) == 0) { dispPtr->grabFlags |= GRAB_TEMP_GLOBAL; } else { XUngrabPointer(dispPtr->display, CurrentTime); } } } dispPtr->buttonWinPtr = winPtr; return 1; } } else { if ((eventPtr->xbutton.state & ALL_BUTTONS) == buttonStates[eventPtr->xbutton.button - Button1]) { ReleaseButtonGrab(dispPtr); /* Note 4. */ } } if (winPtr2 != winPtr) { TkChangeEventWindow(eventPtr, winPtr2); Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD); return 0; /* Note 3. */ } } return 1; }
void GLWindow::initWindow(const char* sWindowName,int* visualProperties) { /* Get a handle to the root window: */ root=RootWindow(display,screen); /* Query for GLX extension: */ int errorBase,eventBase; if(!glXQueryExtension(display,&errorBase,&eventBase)) Misc::throwStdErr("GLWindow: GLX extension not supported"); /* Find a suitable, OpenGL-capable visual: */ static int defaultVisualProperties[]={GLX_RGBA,GLX_DEPTH_SIZE,16,GLX_DOUBLEBUFFER,None}; XVisualInfo* visInfo=glXChooseVisual(display,screen,visualProperties!=0?visualProperties:defaultVisualProperties); if(visInfo==0) Misc::throwStdErr("GLWindow: No suitable visual found"); /* Create an OpenGL context: */ context=glXCreateContext(display,visInfo,0,GL_TRUE); if(context==0) Misc::throwStdErr("GLWindow: Unable to create GL context"); /* Create an X colormap (visual might not be default): */ colorMap=XCreateColormap(display,root,visInfo->visual,AllocNone); /* Create an X window with the selected visual: */ XSetWindowAttributes swa; swa.colormap=colorMap; swa.border_pixel=0; if(fullscreen) // Create a fullscreen window { windowPos.origin[0]=0; windowPos.origin[1]=0; windowPos.size[0]=DisplayWidth(display,screen); windowPos.size[1]=DisplayHeight(display,screen); swa.override_redirect=True; } else swa.override_redirect=False; swa.event_mask=PointerMotionMask|EnterWindowMask|LeaveWindowMask|ButtonPressMask|ButtonReleaseMask|KeyPressMask|KeyReleaseMask|ExposureMask|StructureNotifyMask; unsigned long attributeMask=CWBorderPixel|CWColormap|CWOverrideRedirect|CWEventMask; window=XCreateWindow(display,root, windowPos.origin[0],windowPos.origin[1],windowPos.size[0],windowPos.size[1], 0,visInfo->depth,InputOutput,visInfo->visual,attributeMask,&swa); XSetStandardProperties(display,window,sWindowName,sWindowName,None,0,0,0); /* Delete the visual information structure: */ XFree(visInfo); /* Initiate window manager communication: */ wmProtocolsAtom=XInternAtom(display,"WM_PROTOCOLS",False); wmDeleteWindowAtom=XInternAtom(display,"WM_DELETE_WINDOW",False); XSetWMProtocols(display,window,&wmDeleteWindowAtom,1); /* Display the window on the screen: */ XMapWindow(display,window); if(fullscreen) { /* Grab pointer and keyboard: */ XGrabPointer(display,window,True,0,GrabModeAsync,GrabModeAsync,None,None,CurrentTime); XGrabKeyboard(display,window,True,GrabModeAsync,GrabModeAsync,CurrentTime); } /* Gobble up the initial rush of X events regarding window creation: */ #if 0 XEvent event; while(XCheckWindowEvent(display,window,StructureNotifyMask,&event)) { switch(event.type) { case ConfigureNotify: /* Retrieve the final window size: */ windowWidth=event.xconfigure.width; windowHeight=event.xconfigure.height; break; } } #else while(true) { /* Look at the next event: */ XEvent event; XPeekEvent(display,&event); if(event.type==Expose) break; // Leave this event for the caller to process /* Process the next event: */ XNextEvent(display,&event); switch(event.type) { case ConfigureNotify: /* Retrieve the final window position and size: */ windowPos.origin[0]=event.xconfigure.x; windowPos.origin[1]=event.xconfigure.y; windowPos.size[0]=event.xconfigure.width; windowPos.size[1]=event.xconfigure.height; break; } } #endif }
void KillWindow::start() { static Cursor kill_cursor = 0; if (!kill_cursor) kill_cursor = XCreateFontCursor(qt_xdisplay(), XC_pirate); if (XGrabPointer(qt_xdisplay(), qt_xrootwin(), False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask, GrabModeAsync, GrabModeAsync, None, kill_cursor, CurrentTime) == GrabSuccess) { XGrabKeyboard(qt_xdisplay(), qt_xrootwin(), False, GrabModeAsync, GrabModeAsync, CurrentTime); XEvent ev; int return_pressed = 0; int escape_pressed = 0; int button_released = 0; grabXServer(); while (!return_pressed && !escape_pressed && !button_released) { XMaskEvent(qt_xdisplay(), KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask, &ev); if (ev.type == KeyPress) { int kc = XKeycodeToKeysym(qt_xdisplay(), ev.xkey.keycode, 0); int mx = 0; int my = 0; return_pressed = (kc == XK_Return) || (kc == XK_space); escape_pressed = (kc == XK_Escape); if (kc == XK_Left) mx = -10; if (kc == XK_Right) mx = 10; if (kc == XK_Up) my = -10; if (kc == XK_Down) my = 10; if (ev.xkey.state & ControlMask) { mx /= 10; my /= 10; } QCursor::setPos(QCursor::pos()+QPoint(mx, my)); } if (ev.type == ButtonRelease) { button_released = (ev.xbutton.button == Button1); if ( ev.xbutton.button == Button3 ) { escape_pressed = TRUE; break; } if( ev.xbutton.button == Button1 || ev.xbutton.button == Button2 ) workspace->killWindowId(ev.xbutton.subwindow); } continue; } if (return_pressed) { Window root, child; int dummy1, dummy2, dummy3, dummy4; unsigned int dummy5; if( XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child, &dummy1, &dummy2, &dummy3, &dummy4, &dummy5 ) == true && child != None ) workspace->killWindowId( child ); } ungrabXServer(); XUngrabKeyboard(qt_xdisplay(), CurrentTime); XUngrabPointer(qt_xdisplay(), CurrentTime); } }
void AnalyzeKeyEvent(int pad, keyEvent &evt) { KeySym key = (KeySym)evt.key; int index = get_keyboard_key(pad, key); switch (evt.evt) { case KeyPress: // Shift F12 is not yet use by pcsx2. So keep it to grab/ungrab input // I found it very handy vs the automatic fullscreen detection // 1/ Does not need to detect full-screen // 2/ Can use a debugger in full-screen // 3/ Can grab input in window without the need of a pixelated full-screen if (key == XK_Shift_R || key == XK_Shift_L) s_Shift = true; if (key == XK_F12 && s_Shift) { if(!s_grab_input) { s_grab_input = true; XGrabPointer(GSdsp, GSwin, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, GSwin, None, CurrentTime); XGrabKeyboard(GSdsp, GSwin, True, GrabModeAsync, GrabModeAsync, CurrentTime); } else { s_grab_input = false; XUngrabPointer(GSdsp, CurrentTime); XUngrabKeyboard(GSdsp, CurrentTime); } } // Analog controls. if (IsAnalogKey(index)) { switch (index) { case PAD_R_LEFT: case PAD_R_UP: case PAD_L_LEFT: case PAD_L_UP: key_status->press(pad, index, -MAX_ANALOG_VALUE); break; case PAD_R_RIGHT: case PAD_R_DOWN: case PAD_L_RIGHT: case PAD_L_DOWN: key_status->press(pad, index, MAX_ANALOG_VALUE); break; } } else if (index != -1) key_status->press(pad, index); //PAD_LOG("Key pressed:%d\n", index); event.evt = KEYPRESS; event.key = key; break; case KeyRelease: if (key == XK_Shift_R || key == XK_Shift_L) s_Shift = false; if (index != -1) key_status->release(pad, index); event.evt = KEYRELEASE; event.key = key; break; case FocusIn: XAutoRepeatOff(GSdsp); break; case FocusOut: XAutoRepeatOn(GSdsp); break; case ButtonPress: if (index != -1) key_status->press(pad, index); break; case ButtonRelease: if (index != -1) key_status->release(pad, index); break; case MotionNotify: // FIXME: How to handle when the mouse does not move, no event generated!!! // 1/ small move == no move. Cons : can not do small movement // 2/ use a watchdog timer thread // 3/ ??? idea welcome ;) if (conf->options & ((PADOPTION_MOUSE_L|PADOPTION_MOUSE_R) << 16 * pad )) { unsigned int pad_x; unsigned int pad_y; // Note when both PADOPTION_MOUSE_R and PADOPTION_MOUSE_L are set, take only the right one if (conf->options & (PADOPTION_MOUSE_R << 16 * pad)) { pad_x = PAD_R_RIGHT; pad_y = PAD_R_UP; } else { pad_x = PAD_L_RIGHT; pad_y = PAD_L_UP; } unsigned x = evt.key & 0xFFFF; unsigned int value = (s_previous_mouse_x > x) ? s_previous_mouse_x - x : x - s_previous_mouse_x; value *= conf->sensibility; if (x == 0) key_status->press(pad, pad_x, -MAX_ANALOG_VALUE); else if (x == 0xFFFF) key_status->press(pad, pad_x, MAX_ANALOG_VALUE); else if (x < (s_previous_mouse_x -2)) key_status->press(pad, pad_x, -value); else if (x > (s_previous_mouse_x +2)) key_status->press(pad, pad_x, value); else key_status->release(pad, pad_x); unsigned y = evt.key >> 16; value = (s_previous_mouse_y > y) ? s_previous_mouse_y - y : y - s_previous_mouse_y; value *= conf->sensibility; if (y == 0) key_status->press(pad, pad_y, -MAX_ANALOG_VALUE); else if (y == 0xFFFF) key_status->press(pad, pad_y, MAX_ANALOG_VALUE); else if (y < (s_previous_mouse_y -2)) key_status->press(pad, pad_y, -value); else if (y > (s_previous_mouse_y +2)) key_status->press(pad, pad_y, value); else key_status->release(pad, pad_y); s_previous_mouse_x = x; s_previous_mouse_y = y; } break; }
/* * Enters the game mode */ int FGAPIENTRY glutEnterGameMode( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutEnterGameMode" ); if( fgStructure.GameMode ) fgAddToWindowDestroyList( fgStructure.GameMode ); else fghRememberState( ); if( ! fghChangeDisplayMode( GL_FALSE ) ) { fgWarning( "failed to change screen settings" ); return 0; } fgStructure.GameMode = fgCreateWindow( NULL, "FREEGLUT", 0, 0, fgState.GameModeSize.X, fgState.GameModeSize.Y, GL_TRUE, GL_FALSE ); fgStructure.GameMode->State.Width = fgState.GameModeSize.X; fgStructure.GameMode->State.Height = fgState.GameModeSize.Y; fgStructure.GameMode->State.NeedToResize = GL_TRUE; fgStructure.GameMode->State.IsGameMode = GL_TRUE; #if TARGET_HOST_UNIX_X11 /* * Sync needed to avoid a real race, the Xserver must have really created * the window before we can grab the pointer into it: */ XSync( fgDisplay.Display, False ); /* * Grab the pointer to confine it into the window after the calls to * XWrapPointer() which ensure that the pointer really enters the window. * * We also need to wait here until XGrabPointer() returns GrabSuccess, * otherwise the new window is not viewable yet and if the next function * (XSetInputFocus) is called with a not yet viewable window, it will exit * the application which we have to aviod, so wait until it's viewable: */ while( GrabSuccess != XGrabPointer( fgDisplay.Display, fgStructure.GameMode->Window.Handle, TRUE, ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, fgStructure.GameMode->Window.Handle, None, CurrentTime) ) usleep( 100 ); /* * Change input focus to the new window. This will exit the application * if the new window is not viewable yet, see the XGrabPointer loop above. */ XSetInputFocus( fgDisplay.Display, fgStructure.GameMode->Window.Handle, RevertToNone, CurrentTime ); /* Move the Pointer to the middle of the fullscreen window */ XWarpPointer( fgDisplay.Display, None, fgDisplay.RootWindow, 0, 0, 0, 0, fgState.GameModeSize.X/2, fgState.GameModeSize.Y/2 ); # ifdef X_XF86VidModeSetViewPort if( fgDisplay.DisplayModeValid ) { int x, y; Window child; /* Change to viewport to the window topleft edge: */ if( !XF86VidModeSetViewPort( fgDisplay.Display, fgDisplay.Screen, 0, 0 ) ) fgWarning( "XF86VidModeSetViewPort failed" ); /* * Final window repositioning: It could be avoided using an undecorated * window using override_redirect, but this * would possily require * more changes and investigation. */ /* Get the current postion of the drawable area on screen */ XTranslateCoordinates( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle, fgDisplay.RootWindow, 0, 0, &x, &y, &child ); /* Move the decorataions out of the topleft corner of the display */ XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle, -x, -y); } #endif /* Grab the keyboard, too */ XGrabKeyboard( fgDisplay.Display, fgStructure.GameMode->Window.Handle, FALSE, GrabModeAsync, GrabModeAsync, CurrentTime ); #endif return fgStructure.GameMode->ID; }
struct menu * menu_filter(struct screen_ctx *sc, struct menu_q *menuq, const char *prompt, const char *initial, int flags, void (*match)(struct menu_q *, struct menu_q *, char *), void (*print)(struct menu *, int)) { struct menu_ctx mc; struct menu_q resultq; struct menu *mi = NULL; XEvent e; Window focuswin; int focusrevert, xsave, ysave, xcur, ycur; TAILQ_INIT(&resultq); xu_ptr_getpos(sc->rootwin, &xsave, &ysave); (void)memset(&mc, 0, sizeof(mc)); mc.sc = sc; mc.flags = flags; mc.match = match; mc.print = print; mc.entry = mc.prev = -1; mc.geom.x = xsave; mc.geom.y = ysave; if (mc.flags & CWM_MENU_LIST) mc.list = 1; (void)strlcpy(mc.promptstr, prompt, sizeof(mc.promptstr)); if (initial != NULL) (void)strlcpy(mc.searchstr, initial, sizeof(mc.searchstr)); else mc.searchstr[0] = '\0'; mc.win = XCreateSimpleWindow(X_Dpy, sc->rootwin, 0, 0, 1, 1, Conf.bwidth, sc->xftcolor[CWM_COLOR_MENU_FG].pixel, sc->xftcolor[CWM_COLOR_MENU_BG].pixel); mc.xftdraw = XftDrawCreate(X_Dpy, mc.win, sc->visual, sc->colormap); XSelectInput(X_Dpy, mc.win, MENUMASK); XMapRaised(X_Dpy, mc.win); if (XGrabPointer(X_Dpy, mc.win, False, MENUGRABMASK, GrabModeAsync, GrabModeAsync, None, Conf.cursor[CF_QUESTION], CurrentTime) != GrabSuccess) { XftDrawDestroy(mc.xftdraw); XDestroyWindow(X_Dpy, mc.win); } XGetInputFocus(X_Dpy, &focuswin, &focusrevert); XSetInputFocus(X_Dpy, mc.win, RevertToPointerRoot, CurrentTime); /* make sure keybindings don't remove keys from the menu stream */ XGrabKeyboard(X_Dpy, mc.win, True, GrabModeAsync, GrabModeAsync, CurrentTime); for (;;) { mc.changed = 0; XWindowEvent(X_Dpy, mc.win, MENUMASK, &e); switch (e.type) { case KeyPress: if ((mi = menu_handle_key(&e, &mc, menuq, &resultq)) != NULL) goto out; /* FALLTHROUGH */ case Expose: menu_draw(&mc, menuq, &resultq); break; case MotionNotify: menu_handle_move(&mc, &resultq, e.xbutton.x, e.xbutton.y); break; case ButtonRelease: if ((mi = menu_handle_release(&mc, &resultq, e.xbutton.x, e.xbutton.y)) != NULL) goto out; break; default: break; } } out: if ((mc.flags & CWM_MENU_DUMMY) == 0 && mi->dummy) { /* no mouse based match */ free(mi); mi = NULL; } XftDrawDestroy(mc.xftdraw); XDestroyWindow(X_Dpy, mc.win); XSetInputFocus(X_Dpy, focuswin, focusrevert, CurrentTime); /* restore if user didn't move */ xu_ptr_getpos(sc->rootwin, &xcur, &ycur); if (xcur == mc.geom.x && ycur == mc.geom.y) xu_ptr_setpos(sc->rootwin, xsave, ysave); XUngrabPointer(X_Dpy, CurrentTime); XUngrabKeyboard(X_Dpy, CurrentTime); return(mi); }
static void draw_it (LoginWidget w) { #ifdef XPM int i,in_frame_x,in_login_y,in_pass_y,in_width,in_height; int gr_line_x, gr_line_y, gr_line_w; #endif /* XPM */ EraseCursor (w); #ifdef XPM if( (w->login.outframewidth) < 1 ) w->login.outframewidth = 1; for(i=1;i<=(w->login.outframewidth);i++) { XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, i-1,i-1,w->core.width-i,i-1); XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, i-1,i-1,i-1,w->core.height-i); XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, w->core.width-i,i-1,w->core.width-i,w->core.height-i); XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, i-1,w->core.height-i,w->core.width-i,w->core.height-i); } /* make separator line */ gr_line_x = w->login.outframewidth + w->login.logoPadding; gr_line_y = GREET_Y(w) + GREET_Y_INC(w); gr_line_w = w->core.width - 2*(w->login.outframewidth) - (w->login.logoWidth + 3*(w->login.logoPadding)); for(i=1;i<=(w->login.sepwidth);i++) { XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, gr_line_x, gr_line_y + i-1, gr_line_x+gr_line_w, gr_line_y + i-1); XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, gr_line_x, gr_line_y + 2*(w->login.inframeswidth) -i, gr_line_x+gr_line_w, gr_line_y + 2*(w->login.inframeswidth) -i); } in_frame_x = LOGIN_TEXT_X(w) - w->login.inframeswidth - 3; in_login_y = LOGIN_Y(w) - w->login.inframeswidth - 1 - TEXT_Y_INC(w); in_pass_y = PASS_Y(w) - w->login.inframeswidth - 1 - TEXT_Y_INC(w); in_width = LOGIN_W(w) - PROMPT_W(w) - (w->login.logoWidth + 2*(w->login.logoPadding)); in_height = LOGIN_H(w) + w->login.inframeswidth + 2; for(i=1;i<=(w->login.inframeswidth);i++) { /* Make top/left sides */ XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, in_frame_x + i-1, in_login_y + i-1, in_frame_x + in_width-i, in_login_y + i-1); XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, in_frame_x + i-1, in_login_y + i-1, in_frame_x + i-1, in_login_y + in_height-i); XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, in_frame_x + in_width-i, in_login_y + i-1, in_frame_x + in_width-i, in_login_y + in_height-i); XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, in_frame_x + i-1, in_login_y + in_height-i, in_frame_x + in_width-i, in_login_y + in_height-i); /* Make bottom/right sides */ XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, in_frame_x + i-1, in_pass_y + i-1, in_frame_x + in_width-i, in_pass_y + i-1); XDrawLine(XtDisplay (w), XtWindow (w), w->login.shdGC, in_frame_x + i-1, in_pass_y + i-1, in_frame_x + i-1, in_pass_y + in_height-i); XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, in_frame_x + in_width-i, in_pass_y + i-1, in_frame_x + in_width-i, in_pass_y + in_height-i); XDrawLine(XtDisplay (w), XtWindow (w), w->login.hiGC, in_frame_x + i-1, in_pass_y + in_height-i, in_frame_x + in_width-i, in_pass_y + in_height-i); } #endif /* XPM */ if (GREETING(w)[0]) XDrawString (XtDisplay (w), XtWindow (w), w->login.greetGC, #ifndef XPM GREET_X(w), GREET_Y(w), #else GREET_X(w) - ((w->login.logoWidth/2) + w->login.logoPadding), GREET_Y(w), #endif /* XPM */ GREETING(w), strlen (GREETING(w))); XDrawString (XtDisplay (w), XtWindow (w), w->login.promptGC, LOGIN_X(w), LOGIN_Y(w), w->login.namePrompt, strlen (w->login.namePrompt)); XDrawString (XtDisplay (w), XtWindow (w), w->login.promptGC, PASS_X(w), PASS_Y(w), w->login.passwdPrompt, strlen (w->login.passwdPrompt)); RedrawFail (w); DrawName (w, 0); XorCursor (w); /* * The GrabKeyboard here is needed only because of * a bug in the R3 server -- the keyboard is grabbed on * the root window, and the server won't dispatch events * to the focus window unless the focus window is a ancestor * of the grab window. Bug in server already found and fixed, * compatibility until at least R4. */ if (XGrabKeyboard (XtDisplay (w), XtWindow (w), False, GrabModeAsync, GrabModeAsync, CurrentTime) != GrabSuccess) { XSetInputFocus (XtDisplay (w), XtWindow (w), RevertToPointerRoot, CurrentTime); } }
JNIEXPORT void JNICALL Java_com_turbovnc_vncviewer_Viewport_grabKeyboard (JNIEnv *env, jobject obj, jboolean on, jboolean pointer) { JAWT awt; JAWT_DrawingSurface *ds = NULL; JAWT_DrawingSurfaceInfo *dsi = NULL; JAWT_X11DrawingSurfaceInfo *x11dsi = NULL; int ret; awt.version = JAWT_VERSION_1_3; if (!handle) { if ((handle = dlopen("libjawt.so", RTLD_LAZY)) == NULL) _throw(dlerror()); if ((__JAWT_GetAWT = (__JAWT_GetAWT_type)dlsym(handle, "JAWT_GetAWT")) == NULL) _throw(dlerror()); } if (__JAWT_GetAWT(env, &awt) == JNI_FALSE) _throw("Could not initialize AWT native interface"); if ((ds = awt.GetDrawingSurface(env, obj)) == NULL) _throw("Could not get drawing surface"); if ((ds->Lock(ds) & JAWT_LOCK_ERROR) != 0) _throw("Could not lock surface"); if ((dsi = ds->GetDrawingSurfaceInfo(ds)) == NULL) _throw("Could not get drawing surface info"); if ((x11dsi = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo) == NULL) _throw("Could not get X11 drawing surface info"); XSync(x11dsi->display, False); if (on) { int count = 5; while ((ret = XGrabKeyboard(x11dsi->display, x11dsi->drawable, True, GrabModeAsync, GrabModeAsync, CurrentTime)) != GrabSuccess) { switch (ret) { case AlreadyGrabbed: _throw("Could not grab keyboard: already grabbed by another application"); case GrabInvalidTime: _throw("Could not grab keyboard: invalid time"); case GrabNotViewable: /* The window should theoretically be viewable by now, but in practice, sometimes a race condition occurs with Swing. It is unclear why, since everything should be happening in the EDT. */ if (count == 0) _throw("Could not grab keyboard: window not viewable"); usleep(100000); count--; continue; case GrabFrozen: _throw("Could not grab keyboard: keyboard frozen by another application"); } } if (pointer) { ret = XGrabPointer(x11dsi->display, x11dsi->drawable, True, ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); switch (ret) { case AlreadyGrabbed: _throw("Could not grab pointer: already grabbed by another application"); case GrabInvalidTime: _throw("Could not grab pointer: invalid time"); case GrabNotViewable: _throw("Could not grab pointer: window not viewable"); case GrabFrozen: _throw("Could not grab pointer: pointer frozen by another application"); } } printf("TurboVNC Helper: Grabbed keyboard%s for window 0x%.8lx\n", pointer? " & pointer" : "", x11dsi->drawable); } else { XUngrabKeyboard(x11dsi->display, CurrentTime); if (pointer) XUngrabPointer(x11dsi->display, CurrentTime); printf("TurboVNC Helper: Ungrabbed keyboard%s\n", pointer ? " & pointer" : ""); } XSync(x11dsi->display, False); bailout: if (ds) { if (dsi) ds->FreeDrawingSurfaceInfo(dsi); ds->Unlock(ds); awt.FreeDrawingSurface(ds); } }
void KSMServer::performLegacySessionSave() { kdDebug( 1218 ) << "Saving legacy session apps" << endl; // Setup error handler legacyWindows.clear(); windowMapPtr = &legacyWindows; XErrorHandler oldHandler = XSetErrorHandler(winsErrorHandler); // Compute set of leader windows that need legacy session management // and determine which style (WM_COMMAND or WM_SAVE_YOURSELF) KWinModule module; if( wm_save_yourself == (Atom)None ) { Atom atoms[ 3 ]; const char* const names[] = { "WM_SAVE_YOURSELF", "WM_PROTOCOLS", "WM_CLIENT_LEADER" }; XInternAtoms( tqt_xdisplay(), const_cast< char** >( names ), 3, False, atoms ); wm_save_yourself = atoms[ 0 ]; wm_protocols = atoms[ 1 ]; wm_client_leader = atoms[ 2 ]; } for ( TQValueList<WId>::ConstIterator it = module.windows().begin(); it != module.windows().end(); ++it) { WId leader = windowWmClientLeader( *it ); if (!legacyWindows.contains(leader) && windowSessionId( *it, leader ).isEmpty()) { SMType wtype = SM_WMCOMMAND; int nprotocols = 0; Atom *protocols = 0; if( XGetWMProtocols(tqt_xdisplay(), leader, &protocols, &nprotocols)) { for (int i=0; i<nprotocols; i++) if (protocols[i] == wm_save_yourself) { wtype = SM_WMSAVEYOURSELF; break; } XFree((void*) protocols); } SMData data; data.type = wtype; XClassHint classHint; if( XGetClassHint( tqt_xdisplay(), leader, &classHint ) ) { data.wmclass1 = classHint.res_name; data.wmclass2 = classHint.res_class; XFree( classHint.res_name ); XFree( classHint.res_class ); } legacyWindows.insert(leader, data); } } // Open fresh display for sending WM_SAVE_YOURSELF XSync(tqt_xdisplay(), False); Display *newdisplay = XOpenDisplay(DisplayString(tqt_xdisplay())); if (!newdisplay) { windowMapPtr = NULL; XSetErrorHandler(oldHandler); return; } WId root = DefaultRootWindow(newdisplay); XGrabKeyboard(newdisplay, root, False, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(newdisplay, root, False, Button1Mask|Button2Mask|Button3Mask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); // Send WM_SAVE_YOURSELF messages XEvent ev; int awaiting_replies = 0; for (WindowMap::Iterator it = legacyWindows.begin(); it != legacyWindows.end(); ++it) { if ( (*it).type == SM_WMSAVEYOURSELF ) { WId w = it.key(); awaiting_replies += 1; memset(&ev, 0, sizeof(ev)); ev.xclient.type = ClientMessage; ev.xclient.window = w; ev.xclient.message_type = wm_protocols; ev.xclient.format = 32; ev.xclient.data.l[0] = wm_save_yourself; ev.xclient.data.l[1] = GET_QT_X_TIME(); XSelectInput(newdisplay, w, PropertyChangeMask|StructureNotifyMask); XSendEvent(newdisplay, w, False, 0, &ev); } } // Wait for change in WM_COMMAND with timeout XFlush(newdisplay); TQTime start = TQTime::currentTime(); while (awaiting_replies > 0) { if (XPending(newdisplay)) { /* Process pending event */ XNextEvent(newdisplay, &ev); if ( ( ev.xany.type == UnmapNotify ) || ( ev.xany.type == PropertyNotify && ev.xproperty.atom == XA_WM_COMMAND ) ) { WindowMap::Iterator it = legacyWindows.find( ev.xany.window ); if ( it != legacyWindows.end() && (*it).type != SM_WMCOMMAND ) { awaiting_replies -= 1; if ( (*it).type != SM_ERROR ) (*it).type = SM_WMCOMMAND; } } } else { /* Check timeout */ int msecs = start.elapsed(); if (msecs >= WM_SAVE_YOURSELF_TIMEOUT) break; /* Wait for more events */ fd_set fds; FD_ZERO(&fds); int fd = ConnectionNumber(newdisplay); FD_SET(fd, &fds); struct timeval tmwait; tmwait.tv_sec = (WM_SAVE_YOURSELF_TIMEOUT - msecs) / 1000; tmwait.tv_usec = ((WM_SAVE_YOURSELF_TIMEOUT - msecs) % 1000) * 1000; ::select(fd+1, &fds, NULL, &fds, &tmwait); } } // Terminate work in new display XAllowEvents(newdisplay, ReplayPointer, CurrentTime); XAllowEvents(newdisplay, ReplayKeyboard, CurrentTime); XSync(newdisplay, False); XCloseDisplay(newdisplay); // Restore old error handler XSync(tqt_xdisplay(), False); XSetErrorHandler(oldHandler); for (WindowMap::Iterator it = legacyWindows.begin(); it != legacyWindows.end(); ++it) { if ( (*it).type != SM_ERROR) { WId w = it.key(); (*it).wmCommand = windowWmCommand(w); (*it).wmClientMachine = windowWmClientMachine(w); } } kdDebug( 1218 ) << "Done saving " << legacyWindows.count() << " legacy session apps" << endl; }
void createWindow(int setWidth, int setHeight) { width = setWidth; height = setHeight; XVisualInfo *vi; Colormap cmap; int i, dpyWidth, dpyHeight; int glxMajor, glxMinor, vmMajor, vmMinor; XF86VidModeModeInfo **modes; int modeNum, bestMode; Atom wmDelete; // set best mode to current bestMode = 0; // get a connection display = XOpenDisplay(0); screen = DefaultScreen(display); XF86VidModeQueryVersion(display, &vmMajor, &vmMinor); cout << "XF86 VideoMode extension version " << vmMajor << "." << vmMinor << endl; XF86VidModeGetAllModeLines(display, screen, &modeNum, &modes); // save desktop-resolution before switching modes GLWin.deskMode = *modes[0]; desktopMode = *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(display, screen, attrListDbl); if (vi == NULL) { vi = glXChooseVisual(display, screen, attrListSgl); doubleBuffered = False; cout << "singlebuffered rendering will be used, no doublebuffering available" << endl; } else { doubleBuffered = True; cout << "doublebuffered rendering available" << endl; } glXQueryVersion(display, &glxMajor, &glxMinor); cout << "GLX-Version " << glxMajor << "." << glxMinor << endl; // create a GLX context glxContext = glXCreateContext(display, vi, 0, GL_TRUE); // create a color map cmap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone); winAttr.colormap = cmap; winAttr.border_pixel = 0; if (fullscreen) { // switch to fullscreen XF86VidModeSwitchToMode(display, screen, modes[bestMode]); XF86VidModeSetViewPort(display, screen, 0, 0); dpyWidth = modes[bestMode]->hdisplay; dpyHeight = modes[bestMode]->vdisplay; cout << "resolution " << dpyWidth << "x" << dpyHeight << endl; XFree(modes); // set window attributes winAttr.override_redirect = True; winAttr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask; window = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &winAttr); XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0); XMapRaised(display, window); XGrabKeyboard(display, window, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(display, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, None, CurrentTime); } else { // create a window in window mode winAttr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask | ButtonReleaseMask | PointerMotionMask; window = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &winAttr); // only set window title and handle wm_delete_events if in windowed mode wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", True); XSetWMProtocols(display, window, &wmDelete, 1); XSetStandardProperties(display, window, title.c_str(), title.c_str(), None, NULL, 0, NULL); XMapRaised(display, window); } // connect the glx-context to the window glXMakeCurrent(display, window, glxContext); if (glXIsDirect(display, glxContext)) cout << "DRI enabled" << endl; else cout << "no DRI available" << endl; }
void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor) { static int originalmouseparms_num; static int originalmouseparms_denom; static int originalmouseparms_threshold; static qboolean restore_spi; #if !defined(__APPLE__) && !defined(SUNOS) qboolean usedgamouse; #endif if (!vidx11_display || !win) return; if (relative) fullscreengrab = true; if (!mouse_avail) fullscreengrab = relative = hidecursor = false; #if !defined(__APPLE__) && !defined(SUNOS) usedgamouse = relative && vid_dgamouse.integer; if (!vid_x11_dgasupported) usedgamouse = false; if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse)) VID_SetMouse(false, false, false); // ungrab first! #endif if (vid_usingmousegrab != fullscreengrab) { vid_usingmousegrab = fullscreengrab; cl_ignoremousemoves = 2; if (fullscreengrab) { XGrabPointer(vidx11_display, win, True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime); if (vid_grabkeyboard.integer || vid_isoverrideredirect) XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime); } else { XUngrabPointer(vidx11_display, CurrentTime); XUngrabKeyboard(vidx11_display, CurrentTime); } } if (relative) { if (!vid_usingmouse) { XWindowAttributes attribs_1; XSetWindowAttributes attribs_2; XGetWindowAttributes(vidx11_display, win, &attribs_1); attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK; XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2); #if !defined(__APPLE__) && !defined(SUNOS) vid_usingdgamouse = usedgamouse; if (usedgamouse) { XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse); XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0); } else #endif XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2); // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only) #if !defined(__APPLE__) && !defined(SUNOS) if (!COM_CheckParm ("-noforcemparms") && !usedgamouse) #else if (!COM_CheckParm ("-noforcemparms")) #endif { XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold); XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment restore_spi = true; } else restore_spi = false; cl_ignoremousemoves = 2; vid_usingmouse = true; } } else { if (vid_usingmouse) { #if !defined(__APPLE__) && !defined(SUNOS) if (vid_usingdgamouse) XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0); vid_usingdgamouse = false; #endif cl_ignoremousemoves = 2; if (restore_spi) XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold); restore_spi = false; vid_usingmouse = false; } } if (vid_usinghidecursor != hidecursor) { vid_usinghidecursor = hidecursor; if (hidecursor) XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win)); else XUndefineCursor(vidx11_display, win); } }
void Keyboard::grab() const { Window w = DefaultRootWindow(data->display); XGrabKeyboard(data->display, w, True, GrabModeAsync, GrabModeAsync, CurrentTime); }