bool AppFrontend::Process() { if(!IsRunning()) return false; #if CE_FRONTEND_USEXLIB #if CE_FRONTEND_USEXCB xcb_generic_event_t *xcbEvent; xcb_window_t xcbWindow; while((xcbEvent = xcb_poll_for_event((xcb_connection_t *)m_xcbConnection))) { Event event; event.base.timeMS = GetRunTimeMS(); event.base.canvas = 0; switch(xcbEvent->response_type & ~0x80) { case XCB_CLIENT_MESSAGE: if((*(xcb_client_message_event_t*)xcbEvent).data.data32[0] == m_wmDeleteMessage) return Stop(); break; case XCB_DESTROY_NOTIFY: case XCB_UNMAP_NOTIFY: return Stop(true); case XCB_KEY_PRESS: { xcb_button_press_event_t *cast = (xcb_button_press_event_t *)xcbEvent; event.type = event::KeyDown; xcbWindow = cast->event; if(m_canvasMap.count(xcbWindow)) event.base.canvas = m_canvasMap[xcbWindow]; event.key.scanCode = NativeScanCodeToScanCode(cast->detail); event.key.keyCode = ScanCodeToKeyCode(event.key.scanCode); event.key.state = cast->state; OnEvent(event); break; } case XCB_KEY_RELEASE: { xcb_key_release_event_t *cast = (xcb_key_release_event_t *)xcbEvent; event.type = event::KeyUp; xcbWindow = cast->event; if(m_canvasMap.count(xcbWindow)) event.base.canvas = m_canvasMap[xcbWindow]; event.key.scanCode = NativeScanCodeToScanCode(cast->detail); event.key.keyCode = ScanCodeToKeyCode(event.key.scanCode); event.key.state = cast->state; OnEvent(event); break; } case XCB_BUTTON_PRESS: { xcb_button_release_event_t *cast = (xcb_button_release_event_t *)xcbEvent; event.type = event::MouseButtonDown; xcbWindow = cast->event; if(m_canvasMap.count(xcbWindow)) event.base.canvas = m_canvasMap[xcbWindow]; switch(cast->detail) { case 1: event.mouseButton.button = event::MouseButtonLeft; break; case 2: event.mouseButton.button = event::MouseButtonMiddle; break; case 3: event.mouseButton.button = event::MouseButtonRight; break; default: event.mouseButton.button = event::Unknown; } event.mouseButton.state = cast->state; event.mouseButton.x = cast->event_x; event.mouseButton.y = cast->event_y; OnEvent(event); break; } case XCB_BUTTON_RELEASE: { xcb_button_release_event_t *cast = (xcb_button_release_event_t *)xcbEvent; event.type = event::MouseButtonUp; xcbWindow = cast->event; if(m_canvasMap.count(xcbWindow)) event.base.canvas = m_canvasMap[xcbWindow]; switch(cast->detail) { case 1: event.mouseButton.button = event::MouseButtonLeft; break; case 2: event.mouseButton.button = event::MouseButtonMiddle; break; case 3: event.mouseButton.button = event::MouseButtonRight; break; default: event.mouseButton.button = event::Unknown; } event.mouseButton.state = cast->state; event.mouseButton.x = cast->event_x; event.mouseButton.y = cast->event_y; OnEvent(event); break; } case XCB_MOTION_NOTIFY: { xcb_motion_notify_event_t *cast = (xcb_motion_notify_event_t *)xcbEvent; event.type = event::MouseMotion; xcbWindow = cast->event; if(m_canvasMap.count(xcbWindow)) event.base.canvas = m_canvasMap[xcbWindow]; event.mouseMotion.x = cast->event_x; event.mouseMotion.y = cast->event_y; OnEvent(event); break; } case XCB_CONFIGURE_NOTIFY: { xcb_configure_notify_event_t *cast = (xcb_configure_notify_event_t *)xcbEvent; xcbWindow = cast->event; if(m_canvasMap.count(xcbWindow)) event.base.canvas = m_canvasMap[xcbWindow]; if(cast->width != event.base.canvas->GetWidth() || cast->height != event.base.canvas->GetHeight()) { event.base.canvas->UpdateViewport(cast->width, cast->height); event.type = event::WindowResize; event.windowResize.width = cast->width; event.windowResize.height = cast->height; OnEvent(event); } break; } default: break; } free(xcbEvent); } #else while(XPending((Display *)m_xDisplay)) { XEvent xEvent; XNextEvent((Display *)m_xDisplay, &xEvent); Window xWindow = xEvent.xany.window; Event event; event.base.timeMS = GetRunTimeMS(); event.base.canvas = 0; if(m_canvasMap.count(xWindow)) event.base.canvas = m_canvasMap[xWindow]; switch(xEvent.type) { case ClientMessage: if(xEvent.xclient.data.l[0] == m_wmDeleteMessage) return Stop(); break; case DestroyNotify: case UnmapNotify: return Stop(true); case KeyPress: event.type = event::KeyDown; event.key.scanCode = NativeScanCodeToScanCode(xEvent.xkey.keycode); event.key.keyCode = ScanCodeToKeyCode(event.key.scanCode); event.key.state = xEvent.xkey.state; OnEvent(event); break; case KeyRelease: event.type = event::KeyUp; event.key.scanCode = NativeScanCodeToScanCode(xEvent.xkey.keycode); event.key.keyCode = ScanCodeToKeyCode(event.key.scanCode); event.key.state = xEvent.xkey.state; OnEvent(event); break;; case ButtonPress: event.mouseButton.type = event::MouseButtonDown; switch(xEvent.xbutton.button) { case 1: event.mouseButton.button = event::MouseButtonLeft; break; case 2: event.mouseButton.button = event::MouseButtonMiddle; break; case 3: event.mouseButton.button = event::MouseButtonRight; break; default: event.mouseButton.button = event::Unknown; } event.mouseButton.state = xEvent.xbutton.state; event.mouseButton.x = xEvent.xbutton.x; event.mouseButton.y = xEvent.xbutton.y; OnEvent(event); break; case ButtonRelease: event.mouseButton.type = event::MouseButtonUp; switch(xEvent.xbutton.button) { case 1: event.mouseButton.button = event::MouseButtonLeft; break; case 2: event.mouseButton.button = event::MouseButtonMiddle; break; case 3: event.mouseButton.button = event::MouseButtonRight; break; default: event.mouseButton.button = event::Unknown; } event.mouseButton.state = xEvent.xbutton.state; event.mouseButton.x = xEvent.xbutton.x; event.mouseButton.y = xEvent.xbutton.y; OnEvent(event); break; case MotionNotify: event.type = event::MouseMotion; event.mouseMotion.x = xEvent.xmotion.x; event.mouseMotion.y = xEvent.xmotion.y; OnEvent(event); break; case ConfigureNotify: if(xEvent.xconfigure.width != event.base.canvas->GetWidth() || xEvent.xconfigure.height != event.base.canvas->GetHeight()) { event.base.canvas->UpdateViewport(xEvent.xconfigure.width, xEvent.xconfigure.height); event.type = event::WindowResize; event.windowResize.width = xEvent.xconfigure.width; event.windowResize.height = xEvent.xconfigure.height; OnEvent(event); } break; } } #endif #endif #if CE_FRONTEND_USEWIN MSG wMsg; while(PeekMessage(&wMsg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&wMsg); DispatchMessage(&wMsg); } #endif #if CE_FRONTEND_USEXLIB map<int, Canvas *>::iterator it; #endif #if CE_FRONTEND_USEWIN map<void *, Canvas *>::iterator it; #endif for(it = m_canvasMap.begin(); it != m_canvasMap.end(); it++) it->second->Render(); return App::Process(); }
bool QEventDispatcherX11::processEvents(QEventLoop::ProcessEventsFlags flags) { Q_D(QEventDispatcherX11); d->interrupt = false; QApplication::sendPostedEvents(); ulong marker = XNextRequest(X11->display); int nevents = 0; do { while (!d->interrupt) { XEvent event; if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) { // process a pending user input event event = d->queuedUserInputEvents.takeFirst(); } else if (XEventsQueued(X11->display, QueuedAlready)) { // process events from the X server XNextEvent(X11->display, &event); if (flags & QEventLoop::ExcludeUserInputEvents) { // queue user input events switch (event.type) { case ButtonPress: case ButtonRelease: case MotionNotify: case XKeyPress: case XKeyRelease: case EnterNotify: case LeaveNotify: d->queuedUserInputEvents.append(event); continue; case ClientMessage: // only keep the wm_take_focus and // _qt_scrolldone protocols, queue all other // client messages if (event.xclient.format == 32) { if (event.xclient.message_type == ATOM(WM_PROTOCOLS) && (Atom) event.xclient.data.l[0] == ATOM(WM_TAKE_FOCUS)) { break; } else if (event.xclient.message_type == ATOM(_QT_SCROLL_DONE)) { break; } } d->queuedUserInputEvents.append(event); continue; default: break; } } } else { // no event to process break; } // send through event filter if (filterEvent(&event)) continue; nevents++; if (qApp->x11ProcessEvent(&event) == 1) return true; if (event.xany.serial >= marker) { if (XEventsQueued(X11->display, QueuedAfterFlush)) flags &= ~QEventLoop::WaitForMoreEvents; goto out; } } } while (!d->interrupt && XEventsQueued(X11->display, QueuedAfterFlush)); out: if (!d->interrupt) { const uint exclude_all = QEventLoop::ExcludeSocketNotifiers | QEventLoop::X11ExcludeTimers | QEventLoop::WaitForMoreEvents; if (nevents > 0 && ((uint)flags & exclude_all) == exclude_all) { QApplication::sendPostedEvents(); return nevents > 0; } // return true if we handled events, false otherwise return QEventDispatcherUNIX::processEvents(flags) || (nevents > 0); } return nevents > 0; }
/* This function handles XEvents that might be in the queue. It generates GstEvent that will be sent upstream in the pipeline to handle interactivity and navigation. It will also listen for configure events on the window to trigger caps renegotiation so on the fly software scaling can work. */ static void gst_pvrvideosink_handle_xevents (GstPVRVideoSink * pvrvideosink) { XEvent e; gboolean exposed = FALSE; gboolean configured = FALSE; g_mutex_lock (pvrvideosink->flow_lock); g_mutex_lock (pvrvideosink->dcontext->x_lock); /* Handle Expose */ while (XCheckWindowEvent (pvrvideosink->dcontext->x_display, pvrvideosink->xwindow->window, ExposureMask | StructureNotifyMask, &e)) { switch (e.type) { case Expose: exposed = TRUE; break; case ConfigureNotify: g_mutex_unlock (pvrvideosink->dcontext->x_lock); gst_pvrvideosink_xwindow_update_geometry (pvrvideosink); g_mutex_lock (pvrvideosink->dcontext->x_lock); configured = TRUE; break; default: break; } } if (exposed || configured) { g_mutex_unlock (pvrvideosink->dcontext->x_lock); g_mutex_unlock (pvrvideosink->flow_lock); gst_pvrvideosink_expose (GST_VIDEO_OVERLAY (pvrvideosink)); g_mutex_lock (pvrvideosink->flow_lock); g_mutex_lock (pvrvideosink->dcontext->x_lock); } /* Handle Display events */ while (XPending (pvrvideosink->dcontext->x_display)) { XNextEvent (pvrvideosink->dcontext->x_display, &e); switch (e.type) { case ClientMessage:{ Atom wm_delete; wm_delete = XInternAtom (pvrvideosink->dcontext->x_display, "WM_DELETE_WINDOW", True); if (wm_delete != None && wm_delete == (Atom) e.xclient.data.l[0]) { /* Handle window deletion by posting an error on the bus */ GST_ELEMENT_ERROR (pvrvideosink, RESOURCE, NOT_FOUND, ("Output window was closed"), (NULL)); g_mutex_unlock (pvrvideosink->dcontext->x_lock); gst_pvrvideosink_xwindow_destroy (pvrvideosink, pvrvideosink->xwindow); pvrvideosink->xwindow = NULL; g_mutex_lock (pvrvideosink->dcontext->x_lock); } break; } default: break; } } g_mutex_unlock (pvrvideosink->dcontext->x_lock); g_mutex_unlock (pvrvideosink->flow_lock); }
int main(int argc, const char **argv) { int i = 0; FILE *input = NULL; /* Try to connect to X server */ if (!(dpy=XOpenDisplay(0x0))) return 1; /* Initialize globals */ scr = DefaultScreen(dpy); root = RootWindow(dpy,scr); sw = DisplayWidth(dpy,scr); sh = DisplayHeight(dpy,scr); /* parse command line arguments */ for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == 'h') { printf(HELP); exit(0); } else if (argv[i][1] == 'i') mode = INTERACTIVE; else if (argv[i][1] == 's') mode = STDIN; else if (argv[i][1] == 'c' && argc > i+1) { // interpret the content of the `-c' argument command((char *)argv[(++i)]); if (mode == UNSET) mode = COMMAND; } } else { /* file input; try to open the file */ printf("in = ",argv[i]); input = fopen(argv[i],"r"); if (input) mode = INPUTFILE; } } /* if input was only -c parameters, done */ if (mode == COMMAND) exit(0); /* if no input file was opened, use stdin */ if (!input) input = stdin; /* iterate over given list of commands */ if (mode == UNSET || mode == STDIN || mode == INPUTFILE) { char line[MAXLINE+1]; while (running && (fgets(line,MAXLINE,input)) != NULL) command(line); XCloseDisplay(dpy); if (mode == 3) fclose(input); return 0; } /* no args -> interactive mode: */ /* search for config file */ char *dir = getenv("PWD"); chdir(getenv("XDG_CONFIG_HOME")); chdir("iocane"); FILE *rcfile = fopen("config","r"); if (!rcfile) { chdir(getenv("HOME")); rcfile = fopen(".iocanerc","r"); } if (!rcfile) rcfile = fopen("/usr/share/iocane/iocanerc","r"); if (dir) chdir(dir); /* go back to current directory */ /* if unable to find a config file, quit */ if (!rcfile) { fprintf(stderr,"IOCANE: no iocanerc file found.\n"); XCloseDisplay(dpy); return 0; } /* parse config file */ KeySym keysym; char *line = (char *) calloc(MAXLINE+MAXSYMLEN+2,sizeof(char)); char *command_string; char keystring[MAXSYMLEN]; keycount = 0; while (fgets(line,MAXLINE+MAXSYMLEN+2,rcfile) != NULL) { if (line[0] == '#' || line[0] == '\n') continue; /* split each line at space, parse into keysym,command_string */ strncpy(keystring,line,MAXSYMLEN); *strchr(keystring,' ') = '\0'; if ( (keysym=XStringToKeysym(keystring)) == NoSymbol ) continue; command_string = (char *) calloc(strlen(line) - strlen(keystring), sizeof(char)); strcpy(command_string,strchr(line,' ')+1); /* check, if it's the toggle command */ if (command_string[0] == 't') { /* if so, set the special toggle key */ grab_ungrab_key = XKeysymToKeycode(dpy,keysym); } else { /* otherwise (normal key) add keysymbol and command to keys */ keys = realloc(keys, (keycount+1) * sizeof(Key)); keys[keycount].key = XKeysymToKeycode(dpy,keysym); keys[keycount].command = command_string; keycount++; } } /* done parsing; clean up */ free(line); fclose(rcfile); /* actually grab the keys */ grab_keys(); /* loop for interactive mode * Wait for event (blocks) of a grabbed key. If the key is registered in * the `keys' list, then the associated command is executed. */ XEvent ev; XKeyEvent *e; while (running && !XNextEvent(dpy,&ev)) if (ev.type == KeyPress) { e = &ev.xkey; if (e->keycode == grab_ungrab_key) { toggle_interactive_mode(); } else { for (i = 0; i < keycount; i++) if (e->keycode == keys[i].key && keys[i].command) command(keys[i].command); /* execute associated command */ } } /* program done; cleanup */ for (i = 0; i < keycount; i++) free(keys[i].command); free(keys); XCloseDisplay(dpy); /* close connection to X server and release resources */ return 0; }
/* * main */ int main(int argc, char *argv[]) { struct tm *gTime, *gmt; struct stat fi; XEvent event; Pixmap NewPixmap, NewShapeMask; XpmAttributes Attributes; Colormap cmap; int n, s, m, dt1, dt2, dt3, len; int Year, Month, Day; int Hours, Mins, Secs; int i, j, Width, Height, yoff, fd, Flag; long CurrentLocalTime; double UT, hour24(), jd(), CurrentJD, OldFileUT, FileUT; char command[1040], ImageName[256]; int havePixmap= 0; /* * Parse any command line arguments. */ ParseCMDLine(argc, argv); /* * Figure out what the name of the image xpm file should be... */ len = strlen(ImageURL); for (j = 0, i=0; i<len; ++i){ if (ImageURL[i] == '/') j = i; } strcpy(ImageName, ImageURL+j+1); sprintf(XpmFileName, "%s/.wmGrabImage/%s.xpm", getenv("HOME"), ImageName); sprintf(ImageFileName, "%s/.wmGrabImage/%s", getenv("HOME"), ImageName); openXwindow(argc, argv, wmGrabImage_master, wmGrabImage_mask_bits, wmGrabImage_mask_width, wmGrabImage_mask_height); cmap = DefaultColormap(display, DefaultScreen(display)); /* * Loop until we die */ n = 32000; s = 32000; m = 32000; dt1 = 32000; dt2 = 32000; dt3 = 32000; DblClkDelay = 32000; UpToDate = 0; FileUT = -999.0; Flag = 1; NewShapeMask = 0; Attributes.nalloc_pixels = 0; while(1) { /* * Keep track of # of seconds */ if (m > 100){ m = 0; ++dt1; ++dt2; ++dt3; } else { /* * Increment counter */ ++m; } /* * Double Click Delays * Keep track of click events. If Delay too long, set GotFirstClick's to False. */ if (DblClkDelay > 15) { DblClkDelay = 0; GotFirstClick1 = 0; GotDoubleClick1 = 0; GotFirstClick2 = 0; GotDoubleClick2 = 0; GotFirstClick3 = 0; GotDoubleClick3 = 0; } else { ++DblClkDelay; } /* * Process any pending X events. */ while(XPending(display)){ XNextEvent(display, &event); switch(event.type){ case Expose: RedrawWindow(); break; case ButtonPress: pressEvent(&event.xbutton); break; case ButtonRelease: break; } } /* * Draw window. */ if (ForceUpdate||Flag){ /* * Compute Current Julian Date */ CurrentLocalTime = time(CurrentTime); gTime = gmtime(&CurrentLocalTime); Year = gTime->tm_year+1900; Month = gTime->tm_mon+1; Day = gTime->tm_mday; Hours = gTime->tm_hour; Mins = gTime->tm_min; Secs = gTime->tm_sec; UT = (double)Hours + (double)Mins/60.0 + (double)Secs/3600.0; CurrentJD = jd(Year, Month, Day, UT); /* * Clear window. */ copyXPMArea(5, 69, 54, 54, 5, 5); if (havePixmap) { /* * free up the colors, if we alloc'd some before */ if (Attributes.nalloc_pixels > 0) XFreeColors(display, cmap, Attributes.alloc_pixels, Attributes.nalloc_pixels, 0); /* * Free last pixmap -- we dont need it anymore... * A ShapeMask is returned if the Pixmap had the color None used. * We could probably change Transparent to None to make use of this, but for now, * lets just ignore it... */ if ( NewShapeMask != 0 ) XFreePixmap(display, NewShapeMask); XFreePixmap(display, NewPixmap); XpmFreeAttributes(&Attributes); havePixmap= 0; } /* * Grab new pixmap. Accept a reasonable color match. */ Attributes.valuemask = XpmExactColors | XpmCloseness | XpmReturnAllocPixels; Attributes.exactColors = 0; Attributes.closeness = 40000; if (XpmReadFileToPixmap(display, Root, XpmFileName, &NewPixmap, &NewShapeMask, &Attributes) >= 0){ Height = Attributes.height; Width = Attributes.width; yoff = (CenterImage) ? (54 - Height)/2 : 0; XCopyArea(display, NewPixmap, wmgen.pixmap, NormalGC, 0, 0, Width, Height, 5, 5+yoff); Flag = 0; ForceUpdate = 0; havePixmap= 1; } /* * Make changes visible */ RedrawWindow(); } /* * Check xpm file status */ if (dt2 > 1){ dt2 = 0; if ( (fd = open(XpmFileName, O_RDONLY)) >= 0 ) { fstat(fd, &fi); close(fd); gmt = gmtime(&fi.st_mtime); OldFileUT = FileUT; FileUT = (double)gmt->tm_hour + (double)gmt->tm_min/60.0 + (double)gmt->tm_sec/3600.0; if (FileUT != OldFileUT) ForceUpdate = 1; } } /* * Check every 5 min if the values are not up to date... */ if (ForceUpdate2||(dt3 > UpdateDELAY)){ dt3 = 0; /* * Execute Perl script to grab the Latest METAR Report */ if (ConvertGeometry != NULL) sprintf(command, "GrabImage %s %s &", ImageURL, ConvertGeometry); else sprintf(command, "GrabImage %s &", ImageURL); system(command); ForceUpdate = 1; ForceUpdate2 = 0; } /* * Wait for next update */ usleep(DELAY); } }
int main(int argc, char **argv) { XEvent event; int sx=0; int sy=0; const geometryStruct *geom; int bwidth=96; int bhite=24; int spacing=bwidth+10; int vspacing=bhite+10; int xspace=10; int cols[5]; int state; int holdsy; LFSTK_fontButtonClass *fontbutton; int c=0; int option_index=0; const char *shortOpts="h?w:"; option longOptions[]= { {"window",1,0,'w'}, {"help",0,0,'h'}, {0, 0, 0, 0} }; while(1) { option_index=0; c=getopt_long_only(argc,argv,shortOpts,longOptions,&option_index); if (c==-1) break; switch (c) { case 'h': case '?': printf("-?,-h,--help\t\tPrint this help\n"); printf("-w,--window\t\tSet transient for window\n"); exit(0); case 'w': parentWindow=atoi(optarg); break; } } cols[0]=10; for(int j=1;j<5;j++) cols[j]=cols[j-1]+bwidth+xspace; wc=new LFSTK_windowClass(sx,sy,800,600,"LFS Tool Kit Prefs",false); wc->LFSTK_setDecorated(true); geom=wc->LFSTK_getWindowGeom(); fc=new LFSTK_fileDialogClass(wc,"Select Window Tile","/",false); guibuttons[EXIT]=new LFSTK_buttonClass(wc,"Exit",10,geom->h-32,64,24,SouthWestGravity); guibuttons[EXIT]->LFSTK_setCallBack(NULL,callback,(void*)EXIT); guibuttons[APPLY]=new LFSTK_buttonClass(wc,"Apply",geom->w-74,geom->h-32,64,24,SouthEastGravity); guibuttons[APPLY]->LFSTK_setCallBack(NULL,callback,(void*)APPLY); guibuttons[PRINT]=new LFSTK_buttonClass(wc,"Test",(geom->w/2)-(64/2),geom->h-32,64,24,SouthGravity); guibuttons[PRINT]->LFSTK_setCallBack(NULL,callback,(void*)PRINT); //buttons label sy=10; for(int j=LNORMBUTTONS;j<=LFONTCOLOUR;j++) { labels[j]=new LFSTK_labelClass(wc,labelnames[j],cols[j],sy,bwidth,24,NorthWestGravity); labels[j]->LFSTK_setLabelOriention(LEFT); } //buttons sy+=vspacing; holdsy=sy; state=NORMALCOLOUR; for(int j=NORMAL;j<=INACTIVE;j++) { normalbuttons[j]=new LFSTK_buttonClass(wc,buttonnames[j],cols[0],sy,bwidth,24,NorthWestGravity); normalbuttons[j]->LFSTK_setActive(false); normalbuttons[j]->LFSTK_setColourName(INACTIVECOLOUR,wc->globalLib->LFSTK_getGlobalString(state,TYPEBUTTON)); normalbuttons[j]->LFSTK_setFontColourName(INACTIVECOLOUR,wc->globalLib->LFSTK_getGlobalString(state,TYPEFONTCOLOUR)); state++; sy+=vspacing; } //button back col state=NORMALCOLOUR; sy=holdsy; for(int j=ENORMAL;j<=EINACTIVE;j++) { normaledits[j]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(state,TYPEBUTTON),cols[1],sy,bwidth,24,NorthWestGravity); state++; sy+=vspacing; } //button font col state=NORMALCOLOUR; sy=holdsy; for(int j=EFONTNORMAL;j<=EFONTINACTIVE;j++) { normaledits[j]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(state,TYPEFONTCOLOUR),cols[2],sy,bwidth,24,NorthWestGravity); state++; sy+=vspacing; } fontbutton=new LFSTK_fontButtonClass(wc,"Select Font",cols[0],sy,bwidth,24,NorthWestGravity); fontbutton->LFSTK_setCallBack(NULL,fontCB,USERDATA(100)); fontbutton->LFSTK_setLabelIsFont(false); normaledits[EFONTSTRING]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(NORMALCOLOUR,TYPEFONT),cols[1],sy,cols[3]-cols[1]-10,24,NorthWestGravity); sy+=vspacing; //menu items labels state=0; for(int j=LMENUBUTTONS;j<=LMENUFONTCOLOUR;j++) { labels[j]=new LFSTK_labelClass(wc,labelnames[j],cols[state],sy,bwidth,24,NorthWestGravity); state++; labels[j]->LFSTK_setLabelOriention(LEFT); } //menu items sy+=vspacing; holdsy=sy; state=NORMALCOLOUR; for(int j=MENUNORMAL;j<=MENUINACTIVE;j++) { normalbuttons[j]=new LFSTK_buttonClass(wc,buttonnames[j],cols[0],sy,bwidth,24,NorthWestGravity); normalbuttons[j]->LFSTK_setActive(false); normalbuttons[j]->LFSTK_setColourName(INACTIVECOLOUR,wc->globalLib->LFSTK_getGlobalString(state,TYPEBUTTON)); normalbuttons[j]->LFSTK_setFontColourName(INACTIVECOLOUR,wc->globalLib->LFSTK_getGlobalString(state,TYPEMENUITEMFONTCOLOUR)); state++; sy+=vspacing; } //menu back col state=NORMALCOLOUR; sy=holdsy; for(int j=EMENUNORMAL;j<=EMENUINACTIVE;j++) { normaledits[j]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(state,TYPEMENUITEM),cols[1],sy,bwidth,24,NorthWestGravity); state++; sy+=vspacing; } //menu font col state=NORMALCOLOUR; sy=holdsy; for(int j=EMENUFONTNORMAL;j<=EMENUFONTINACTIVE;j++) { normaledits[j]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(state,TYPEMENUITEMFONTCOLOUR),cols[2],sy,bwidth,24,NorthWestGravity); state++; sy+=vspacing; } fontbutton=new LFSTK_fontButtonClass(wc,"Select Font",cols[0],sy,bwidth,24,NorthWestGravity); fontbutton->LFSTK_setCallBack(NULL,fontCB,USERDATA(200)); fontbutton->LFSTK_setLabelIsFont(false); normaledits[EMENUFONTSTRING]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(NORMALCOLOUR,TYPEMENUITEMFONT),cols[1],sy,cols[3]-cols[1]-10,24,NorthWestGravity); sy+=vspacing; //window label and colour labels[LWINDOWCOLOUR]=new LFSTK_labelClass(wc,labelnames[LWINDOWCOLOUR],cols[0],sy,bwidth,24,NorthWestGravity); labels[LWINDOWCOLOUR]->LFSTK_setLabelOriention(LEFT); normaledits[EWINDOWCOLOUR]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(NORMALCOLOUR,TYPEWINDOW),cols[1],sy,bwidth,24,NorthWestGravity); //auto font colour autocolour=new LFSTK_toggleButtonClass(wc,"Auto Colour",cols[2],sy,bwidth,24,NorthWestGravity); autocolour->LFSTK_setCallBack(NULL,callback,(void*)PRINT); autocolour->LFSTK_setValue(wc->autoLabelColour); sy+=vspacing; //theme parts //use theme usetheme=new LFSTK_toggleButtonClass(wc,"Use Theme",cols[0],sy,bwidth,24,NorthWestGravity); usetheme->LFSTK_setCallBack(NULL,callback,(void*)PRINT); usetheme->LFSTK_setValue(wc->globalLib->LFSTK_getUseTheme()); sy+=vspacing; getFileButton=new LFSTK_buttonClass(wc,labelnames[FWTILENAME],cols[0],sy,bwidth,24,NorthWestGravity); getFileButton->LFSTK_setCallBack(NULL,selectfile,USERDATA(EWINDOWTILE)); normaledits[EWINDOWTILE]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(-1,TYPEWINDOWTILE),cols[1],sy,cols[3]-cols[1]-10,24,NorthWestGravity); sy+=vspacing; getFileButton=new LFSTK_buttonClass(wc,labelnames[FBTILENAME],cols[0],sy,bwidth,24,NorthWestGravity); getFileButton->LFSTK_setCallBack(NULL,selectfile,USERDATA(EBUTTONTILE)); normaledits[EBUTTONTILE]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(-1,TYPEBUTTONTILE),cols[1],sy,cols[3]-cols[1]-10,24,NorthWestGravity); sy+=vspacing; getFileButton=new LFSTK_buttonClass(wc,labelnames[FMITEMNAME],cols[0],sy,bwidth,24,NorthWestGravity); getFileButton->LFSTK_setCallBack(NULL,selectfile,USERDATA(EMENUITEMTILE)); normaledits[EMENUITEMTILE]=new LFSTK_lineEditClass(wc,wc->globalLib->LFSTK_getGlobalString(-1,TYPEMENUITEMTILE),cols[1],sy,cols[3]-cols[1]-10,24,NorthWestGravity); sy+=vspacing; labels[LSPACER]=new LFSTK_labelClass(wc,labelnames[LSPACER],0,sy,cols[3],8,NorthWestGravity); sy+=16; printf("Current Settings:\n\n"); callback(NULL,(void*)PRINT); printf("\n\n"); sy+=(vspacing); wc->LFSTK_resizeWindow(cols[3],sy); wc->LFSTK_showWindow(true); wc->LFSTK_setKeepAbove(true); if(parentWindow!=-1) wc->LFSTK_setTransientFor(parentWindow); mainloop=true; while(mainloop==true) { XNextEvent(wc->display,&event); mappedListener *ml=wc->LFSTK_getMappedListener(event.xany.window); if(ml!=NULL) ml->function(ml->gadget,&event,ml->type); switch(event.type) { break; case Expose: wc->LFSTK_setActive(true); wc->LFSTK_clearWindow(); break; case ConfigureNotify: wc->LFSTK_resizeWindow(event.xconfigurerequest.width,event.xconfigurerequest.height,false); break; case ClientMessage: case SelectionNotify: if (event.xclient.message_type == XInternAtom(wc->display, "WM_PROTOCOLS", 1) && (Atom)event.xclient.data.l[0] == XInternAtom(wc->display, "WM_DELETE_WINDOW", 1)) mainloop=false; if(wc->acceptDnd==true) { wc->LFSTK_handleDnD(&event); } default: break; } } delete wc; return(0); }
static void HandleEvents( void ) { XEvent event; qboolean dowarp = qfalse, was_focused = focus; int mwx = x11display.win_width / 2; int mwy = x11display.win_height / 2; char *p; int key = 0; int time = 0; assert( x11display.dpy && x11display.win ); #ifdef WSW_EVDEV if( mouse_active && m_evdev_num ) { evdev_read(); } else #endif if( mouse_active && !dgamouse ) { int root_x, root_y, win_x, win_y; unsigned int mask; Window root, child; if( XQueryPointer( x11display.dpy, x11display.win, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ) ) { mx += ( (int)win_x - mwx ); my += ( (int)win_y - mwy ); mwx = win_x; mwy = win_y; if( mx || my ) dowarp = qtrue; if( ignore_one ) { mx = my = 0; ignore_one = qfalse; } } } while( XPending( x11display.dpy ) ) { XNextEvent( x11display.dpy, &event ); switch( event.type ) { case KeyPress: time = Sys_XTimeToSysTime(event.xkey.time); p = XLateKey( &event.xkey, &key ); if( key ) Key_Event( key, qtrue, time ); while ( p && *p ) { qwchar wc = Q_GrabWCharFromUtf8String( (const char **)&p ); Key_CharEvent( key, wc ); } break; case KeyRelease: if( repeated_press( &event ) ) break; // don't send release events when repeating time = Sys_XTimeToSysTime(event.xkey.time); XLateKey( &event.xkey, &key ); Key_Event( key, event.type == KeyPress, time ); break; case MotionNotify: #ifdef WSW_EVDEV if( mouse_active && dgamouse && !m_evdev_num ) #else if( mouse_active && dgamouse ) #endif { mx += event.xmotion.x_root; my += event.xmotion.y_root; if( ignore_one ) { mx = my = 0; ignore_one = qfalse; } } break; case ButtonPress: if( ( cls.key_dest == key_console ) && !in_grabinconsole->integer ) break; #ifdef WSW_EVDEV if( m_evdev_num ) break; #endif time = Sys_XTimeToSysTime(event.xkey.time); if( event.xbutton.button == 1 ) Key_MouseEvent( K_MOUSE1, 1, time ); else if( event.xbutton.button == 2 ) Key_MouseEvent( K_MOUSE3, 1, time ); else if( event.xbutton.button == 3 ) Key_MouseEvent( K_MOUSE2, 1, time ); else if( event.xbutton.button == 4 ) Key_Event( K_MWHEELUP, 1, time ); else if( event.xbutton.button == 5 ) Key_Event( K_MWHEELDOWN, 1, time ); else if( event.xbutton.button >= 6 && event.xbutton.button <= 10 ) Key_MouseEvent( K_MOUSE4+event.xbutton.button-6, 1, time ); break; case ButtonRelease: if( ( cls.key_dest == key_console ) && !in_grabinconsole->integer ) break; #ifdef WSW_EVDEV if( m_evdev_num ) break; #endif time = Sys_XTimeToSysTime(event.xkey.time); if( event.xbutton.button == 1 ) Key_MouseEvent( K_MOUSE1, 0, time ); else if( event.xbutton.button == 2 ) Key_MouseEvent( K_MOUSE3, 0, time ); else if( event.xbutton.button == 3 ) Key_MouseEvent( K_MOUSE2, 0, time ); else if( event.xbutton.button == 4 ) Key_Event( K_MWHEELUP, 0, time ); else if( event.xbutton.button == 5 ) Key_Event( K_MWHEELDOWN, 0, time ); else if( event.xbutton.button >= 6 && event.xbutton.button <= 10 ) Key_MouseEvent( K_MOUSE4+event.xbutton.button-6, 0, time ); break; case FocusIn: if( x11display.ic ) XSetICFocus(x11display.ic); if( !focus ) { focus = qtrue; } break; case FocusOut: if( x11display.ic ) XUnsetICFocus(x11display.ic); if( focus ) { Key_ClearStates(); focus = qfalse; } break; case ClientMessage: if( event.xclient.data.l[0] == x11display.wmDeleteWindow ) Cbuf_ExecuteText( EXEC_NOW, "quit" ); break; case MapNotify: mapped = qtrue; if( x11display.modeset ) { if ( x11display.dpy && x11display.win ) { XSetInputFocus( x11display.dpy, x11display.win, RevertToPointerRoot, CurrentTime ); x11display.modeset = qfalse; } } if( input_active ) { uninstall_grabs(); install_grabs(); } break; case ConfigureNotify: VID_AppActivate( qtrue, qfalse ); break; case PropertyNotify: if( event.xproperty.window == x11display.win ) { if ( event.xproperty.atom == x11display.wmState ) { qboolean was_minimized = minimized; _X11_CheckWMSTATE(); if( minimized != was_minimized ) { // FIXME: find a better place for this?.. CL_SoundModule_Activate( !minimized ); } } } break; } } if( dowarp ) { XWarpPointer( x11display.dpy, None, x11display.win, 0, 0, 0, 0, x11display.win_width/2, x11display.win_height/2 ); } // set fullscreen or windowed mode upon focus in/out events if: // a) lost focus in fullscreen -> windowed // b) received focus -> fullscreen if a) if( ( focus != was_focused ) ) { if( x11display.features.wmStateFullscreen ) { if( !focus && Cvar_Value( "vid_fullscreen" ) ) { go_fullscreen_on_focus = qtrue; Cbuf_ExecuteText( EXEC_APPEND, "vid_fullscreen 0\n" ); } else if( focus && go_fullscreen_on_focus ) { go_fullscreen_on_focus = qfalse; Cbuf_ExecuteText( EXEC_APPEND, "vid_fullscreen 1\n" ); } } } }
/* * Function for selecting all interesting events on a given * (tree of) window(s). */ static void selectEvents (Window window, Bool substructureOnly) { Window root; /* root window of the window */ Window parent; /* parent of the window */ Window* children; /* children of the window */ unsigned nofChildren = 0; /* number of children */ unsigned i; /* loop counter */ XWindowAttributes attribs; /* attributes of the window */ if( xautolock_ignoreWindow( window )) return; /* * Start by querying the server about the root and parent windows. */ if (!XQueryTree (queue.display, window, &root, &parent, &children, &nofChildren)) { return; } if (nofChildren) (void) XFree ((char*) children); /* * Build the appropriate event mask. The basic idea is that we don't * want to interfere with the normal event propagation mechanism if * we don't have to. * * On the root window, we need to ask for both substructureNotify * and KeyPress events. On all other windows, we always need * substructureNotify, but only need Keypress if some other client * also asked for them, or if they are not being propagated up the * window tree. */ #if 0 if (substructureOnly) { (void) XSelectInput (queue.display, window, SubstructureNotifyMask); } else { if (parent == None) /* the *real* rootwindow */ { attribs.all_event_masks = attribs.do_not_propagate_mask = KeyPressMask; } else if (!XGetWindowAttributes (queue.display, window, &attribs)) #else { if (!XGetWindowAttributes (queue.display, window, &attribs)) #endif { return; } #if 0 (void) XSelectInput (queue.display, window, SubstructureNotifyMask | ( ( attribs.all_event_masks | attribs.do_not_propagate_mask) & KeyPressMask)); #else { int mask = SubstructureNotifyMask | attribs.your_event_mask; if( !substructureOnly ) { mask |= ( ( attribs.all_event_masks | attribs.do_not_propagate_mask) & KeyPressMask ); } (void) XSelectInput (queue.display, window, mask ); } #endif } /* * Now ask for the list of children again, since it might have changed * in between the last time and us selecting SubstructureNotifyMask. * * There is a (very small) chance that we might process a subtree twice: * child windows that have been created after our XSelectinput() has * been processed but before we get to the XQueryTree() bit will be * in this situation. This is harmless. It could be avoided by using * XGrabServer(), but that'd be an impolite thing to do, and since it * isn't required... */ if (!XQueryTree (queue.display, window, &root, &parent, &children, &nofChildren)) { return; } /* * Now do the same thing for all children. */ for (i = 0; i < nofChildren; ++i) { selectEvents (children[i], substructureOnly); } if (nofChildren) (void) XFree ((char*) children); } #if 0 /* * Function for processing any events that have come in since * last time. It is crucial that this function does not block * in case nothing interesting happened. */ void processEvents (void) { while (XPending (queue.display)) { XEvent event; if (XCheckMaskEvent (queue.display, SubstructureNotifyMask, &event)) { if (event.type == CreateNotify) { addToQueue (event.xcreatewindow.window); } } else { (void) XNextEvent (queue.display, &event); } /* * Reset the triggers if and only if the event is a * KeyPress event *and* was not generated by XSendEvent(). */ if ( event.type == KeyPress && !event.xany.send_event) { resetTriggers (); } } /* * Check the window queue for entries that are older than * CREATION_DELAY seconds. */ processQueue ((time_t) CREATION_DELAY); } #else void xautolock_processEvent( XEvent* event ) { if (event->type == CreateNotify) { addToQueue (event->xcreatewindow.window); } /* * Reset the triggers if and only if the event is a * KeyPress event *and* was not generated by XSendEvent(). */ if ( event->type == KeyPress && !event->xany.send_event) { xautolock_resetTriggers (); } } void xautolock_processQueue() { /* * Check the window queue for entries that are older than * CREATION_DELAY seconds. */ processQueue ((time_t) CREATION_DELAY); }
int main(int argc, char **argv) { int num_queued; time_t start_time; double t; long num_frames, fast_skip = 200, fast_rewind = 200; unsigned int width, height; XEvent xevent; const char *prgname = argv[0]; const char *classname = "XLndmovie"; char *pixel_file_name = NULL; FILE *pixel_file; unsigned char *buffer = NULL, *huff = NULL; XImage *shm_image; XShmSegmentInfo shminfo; int shm_major, shm_minor; Bool shm_pixmaps; int ShmCompletionType; int shmtransfer_completed; int i, count, step_key = 0; char xkey[32]; KeySym keysym; XComposeStatus compose; int oc; extern int optind; extern char *optarg; init_signal_handling(); display = xwin_init(NULL, prgname, classname, argc, argv, &screen_no, &width, &height); fixed_font = XLoadQueryFont(display, "fixed"); mit_shm = XShmQueryVersion(display, &shm_major, &shm_minor, &shm_pixmaps); mit_shm = XShmQueryExtension(display); if (mit_shm == True) { /* printf("Shared memory extension used (found V %d.%d)\n", shm_major, shm_minor); */ ShmCompletionType = XShmGetEventBase(display) + ShmCompletion; } /* else printf("Standard Xlib used, no shared memory\n"); */ while ((oc = getopt(argc, argv, "c:f:r:h")) != -1) { switch (oc) { case 'c': cell_boxsize = strtol(optarg, NULL, 10); break; case 'f': fast_skip = strtol(optarg, NULL, 10); if (fast_skip < 1) fast_skip = 200; break; case 'r': fast_rewind = strtol(optarg, NULL, 10); if (fast_rewind < 1) fast_rewind = 200; break; default: fprintf(stderr, "Unknown option \'-%c\' -- ignored\n", oc); break; } } if (optind < argc) pixel_file_name = argv[optind++]; else { fprintf(stderr, "No pixel file specified -- exit\n"); exit (EXIT_FAILURE); } pixel_file = fopen(pixel_file_name, "rb"); if (pixel_file == NULL) { fprintf(stderr, "Failed to open pixel file \"%s\" -- exit\n", pixel_file_name); exit (EXIT_FAILURE); } read_pixheader(pixel_file); if ((cell_boxsize <= 0) || ((width / world_width) < cell_boxsize)) cell_boxsize = width / world_width; if ((height / world_height) < cell_boxsize) cell_boxsize = height / world_height; if (cell_boxsize <= 0) cell_boxsize = 1; if ((height / world_height) < cell_boxsize) cell_boxsize = height / world_height; window_width = world_width * cell_boxsize; pixmap_height = world_height * cell_boxsize; if (fixed_font) window_height = pixmap_height + fixed_font->ascent + fixed_font->descent + 5; else window_height = pixmap_height; buffer = (unsigned char *) malloc(world_width * world_height * sizeof(char)); if (buffer == NULL) { fprintf(stderr, "Failed to allocate internal buffer\n"); exit (EXIT_FAILURE); } huff = (unsigned char *) malloc(world_width * world_height * sizeof(char)); if (buffer == NULL) { fprintf(stderr, "Failed to allocate internal buffer\n"); free(buffer); exit (EXIT_FAILURE); } window = create_window(MOVER | FULLER | CLOSER | RTARROW | LFARROW | UPARROW | DNARROW, window_width, window_height, redraw_pixworld, close_pixwindow, 100, 100, window_width, window_height); XSelectInput(display, window, WH_EVENTMASK | WH_SELECTMASK); map_window(window); if (create_lndgcs(lnd_gc, lndx_gc, background_gc, &text_gc)) { fprintf(stderr, "Failed to create necessary GCs (insufficient colors?)\n"); free(buffer); free(huff); exit (EXIT_FAILURE); } if (mit_shm) { shm_image = XShmCreateImage(display, DefaultVisual(display, screen_no), DefaultDepth(display, screen_no), ZPixmap, NULL, &shminfo, window_width, pixmap_height); /* printf("XImage Structure:\n"); printf("width = %d, height = %d, depth = %d\n", shm_image->width, shm_image->height, shm_image->depth); printf("format: "); switch (shm_image->format) { case XYBitmap: printf("XYBitmap\n"); break; case XYPixmap: printf("XYPixmap\n"); break; case ZPixmap: printf("ZPixmap\n"); break; default: printf("UNKNOWN (%d)\n", shm_image->format); break; } printf("%d bytes per line, %d bits per pixel\n", shm_image->bytes_per_line, shm_image->bits_per_pixel); switch (shm_image->byte_order) { case MSBFirst: printf("byte order: MSBFirst\n"); break; case LSBFirst: printf("byte order: LSBFirst\n"); break; default: printf("byte order UNKNOWN (%d)\n", shm_image->byte_order); break; } switch (shm_image->bitmap_bit_order) { case MSBFirst: printf("bitmap bit order: MSBFirst\n"); break; case LSBFirst: printf("bitmap bit order: LSBFirst\n"); break; default: printf("bitmap bit order UNKNOWN (%d)\n", shm_image->bitmap_bit_order); break; } */ shminfo.shmid = shmget(IPC_PRIVATE, shm_image->bytes_per_line * shm_image->height, IPC_CREAT | 0777); if (shminfo.shmid == -1) { fprintf(stderr, "Failed to get shared memory segment, falling back to standard Xlib\n"); mit_shm = 0; } else { shminfo.shmaddr = shmat(shminfo.shmid, 0, 0); shm_image->data = shminfo.shmaddr; shminfo.readOnly = False; if (XShmAttach(display, &shminfo)) ; /* printf("Shared mem successfully attached to server\n"); */ else { mit_shm = 0; XDestroyImage(shm_image); shmdt(shminfo.shmaddr); shmctl(shminfo.shmid, IPC_RMID, 0); printf("Shared memory released\n"); } } } if (!mit_shm) { paint_pixmap = XCreatePixmap(display, window, window_width, pixmap_height, DefaultDepth(display, screen_no)); XFillRectangle(display, paint_pixmap, background_gc[15], 0, 0, window_width, pixmap_height); } redraw_pixmap = XCreatePixmap(display, window, window_width, pixmap_height, DefaultDepth(display, screen_no)); XFillRectangle(display, redraw_pixmap, background_gc[15], 0, 0, window_width, pixmap_height); /* for (i = 0; i < 6; i++) { XPutPixel(shm_image, 0, 0, lnd_pixel[i]); printf("lnd_pixel[%d]=%08lx -> data=%02x\n", i, lnd_pixel[i], shm_image->data[0]); XPutPixel(shm_image, 0, 0, lndx_pixel[i]); printf("lndx_pixel[%d]=%08lx -> data=%02x\n", i, lndx_pixel[i], shm_image->data[0]); } XPutPixel(shm_image, 0, 0, back_pixel); printf("back_pixel=%08lx -> data=%02x\n", back_pixel, shm_image->data[0]); */ do { XNextEvent(display, &xevent); num_queued = XEventsQueued(display, QueuedAfterFlush); process_xevent(&xevent); } while (!((xevent.type == Expose) && (xevent.xexpose.window == window))); shmtransfer_completed = 1; start_time = time(NULL); num_frames = 0; while (!game_over) { if(feof(pixel_file) || ferror(pixel_file)) { if (resume_fpos != -1) { mode = SINGLE_STEP; /* printf("switched to single step due to feof / ferror\n"); */ step_key = 0; /* printf("rewinding to resume pos %ld\n", resume_fpos); fseek(pixel_file, resume_fpos, SEEK_SET); */ } else { fprintf(stderr, "Encountered EOF without finding any entry point -- quitting\n"); game_over = 1; } } num_queued = XEventsQueued(display, QueuedAfterFlush); while ((num_queued) || ((mode == SINGLE_STEP) && !step_key)) { XNextEvent(display, &xevent); num_queued = XEventsQueued(display, QueuedAfterFlush); /* printf("received event: %s, window: %d\n", event_name[xevent.type], (int) xevent.xany.window); */ if (process_xevent(&xevent)) continue; if (xevent.type == ShmCompletionType) { /* printf("shm transfer completed\n"); */ shmtransfer_completed = 1; } if (xevent.type == KeyPress) { count = XLookupString(&(xevent.xkey), xkey, 32, &keysym, &compose); if (count) { switch(xkey[0]) { case 'f': /* printf("fast forward\n"); */ /* printf("rewind position: %ld\n", resume_fpos); */ mode = FAST_FORWARD; break; case 'r': /* printf("fast rewind\n"); */ /* printf("rewind position: %ld\n", resume_fpos); */ mode = FAST_REWIND; break; case 'b': /* printf("backward play\n"); */ /* printf("rewind position: %ld\n", resume_fpos); */ mode = BACKWARD_PLAY; rewind_generation(pixel_file); break; case 's': /* printf("single step\n"); */ mode = SINGLE_STEP; step_key = 0; break; case 'n': /* printf("normal play\n"); */ /* printf("rewind position: %ld\n", resume_fpos); */ mode = NORMAL_PLAY; break; case 'q': case 'Q': /* printf("game over, bye bye\n"); */ mode = NORMAL_PLAY; step_key = 1; game_over = 1; break; default: step_key = 1; break; } } } } if ((mode == NORMAL_PLAY) || (mode == BACKWARD_PLAY) || ((mode == SINGLE_STEP) && step_key) || ((mode == FAST_FORWARD) && ((generation % fast_skip) == (fast_skip - 1))) || ((mode == FAST_REWIND) && ((generation % fast_rewind) == 1))) { if (mit_shm && shmtransfer_completed) { if (shm_draw_generation(pixel_file, shm_image, buffer, huff)) { mode = SINGLE_STEP; /* printf("switched to single step after shm_draw_generation\n"); */ step_key = 0; } else { if (window != BadValue) XShmPutImage(display, window, background_gc[15], shm_image, 0, 0, 0, window_height - pixmap_height, window_width, pixmap_height, True); if (redraw_pixmap != BadValue) XShmPutImage(display, redraw_pixmap, background_gc[15], shm_image, 0, 0, 0, 0, window_width, pixmap_height, True); shmtransfer_completed = 0; num_frames++; } } else { if (draw_generation(pixel_file, paint_pixmap, buffer, huff)) { mode = SINGLE_STEP; /* printf("switched to single step after draw_generation\n"); */ step_key = 0; } else { if (window != BadValue) XCopyArea(display, paint_pixmap, window, background_gc[15], 0, 0, window_width, pixmap_height, 0, window_height - pixmap_height); if (redraw_pixmap != BadValue) XCopyArea(display, paint_pixmap, redraw_pixmap, background_gc[15], 0, 0, window_width, pixmap_height, 0, 0); num_frames++; } } redraw_text(); if (mode == FAST_REWIND) { if (rewind_generation(pixel_file)) { mode = SINGLE_STEP; /* printf("switched to single step after rewind_generation\n"); */ step_key = 0; } } step_key = 0; } switch (mode) { case BACKWARD_PLAY: if (rewind_generation(pixel_file)) { mode = SINGLE_STEP; /* printf("switched to single step after rewind_generation\n"); */ step_key = 0; } /* fall through */ case FAST_REWIND: if (rewind_generation(pixel_file)) { mode = SINGLE_STEP; /* printf("switched to single step after rewind_generation\n"); */ step_key = 0; } redraw_text(); break; case FAST_FORWARD: if (skip_frame(pixel_file)) { mode = SINGLE_STEP; /* printf("switched to single step after skip_frame\n"); */ step_key = 0; } redraw_text(); break; } } t = difftime(time(NULL), start_time); /* printf("%ld frames in %f seconds (%f frames/sec)\n", num_frames, t, num_frames / t); */ if (mit_shm) { XShmDetach(display, &shminfo); XDestroyImage(shm_image); shmdt(shminfo.shmaddr); shmctl(shminfo.shmid, IPC_RMID, 0); printf("Shared memory released\n"); } free_lndgcs(); if (window != BadValue) remove_window(window); if (redraw_pixmap != BadValue) XFreePixmap(display, redraw_pixmap); if (paint_pixmap != BadValue) XFreePixmap(display, paint_pixmap); free(buffer); free(huff); return (EXIT_SUCCESS); }
static int watch (Display *dpy) { char *v = 0; Window window = RootWindow (dpy, 0); XWindowAttributes xgwa; XEvent event; PROP32 *last = 0; if (v) free (v); XGetWindowAttributes (dpy, window, &xgwa); XSelectInput (dpy, window, xgwa.your_event_mask | PropertyChangeMask); while (1) { XNextEvent (dpy, &event); if (event.xany.type == PropertyNotify && event.xproperty.state == PropertyNewValue && event.xproperty.atom == XA_SCREENSAVER_STATUS) { Atom type; int format; unsigned long nitems, bytesafter; unsigned char *dataP = 0; if (XGetWindowProperty (dpy, RootWindow (dpy, 0), /* always screen #0 */ XA_SCREENSAVER_STATUS, 0, 999, False, XA_INTEGER, &type, &format, &nitems, &bytesafter, &dataP) == Success && type && dataP) { time_t tt; char *s; Bool changed = False; Bool running = False; PROP32 *data = (PROP32 *) dataP; if (type != XA_INTEGER || nitems < 3) { STATUS_LOSE: if (last) XFree (last); if (data) XFree (data); fprintf (stderr, "%s: bad status format on root window.\n", progname); return -1; } tt = (time_t) data[1]; if (tt <= (time_t) 666000000L) /* early 1991 */ goto STATUS_LOSE; s = ctime(&tt); if (s[strlen(s)-1] == '\n') s[strlen(s)-1] = 0; if (!last || data[0] != last[0]) { /* State changed. */ if (data[0] == XA_BLANK) printf ("BLANK %s\n", s); else if (data[0] == XA_LOCK) printf ("LOCK %s\n", s); else if (data[0] == 0) printf ("UNBLANK %s\n", s); else goto STATUS_LOSE; } if (!last) changed = True; else { int i; for (i = 2; i < nitems; i++) { if (data[i] != last[i]) changed = True; if (data[i]) running = True; } } if (running && changed) { int i; fprintf (stdout, "RUN"); for (i = 2; i < nitems; i++) fprintf (stdout, " %d", (int) data[i]); fprintf (stdout, "\n"); } fflush (stdout); if (last) XFree (last); last = data; } else { if (last) XFree (last); if (dataP) XFree (dataP); fprintf (stderr, "%s: no saver status on root window.\n", progname); return -1; } } } }
/* * Attempt to read bytes from the mouse and interpret them. * Returns -1 on error, 0 if either no bytes were read or not enough * was read for a complete state, or 1 if the new state was read. * When a new state is read, the current buttons and x and y deltas * are returned. This routine does not block. */ static int X11_Read(MWCOORD *dx, MWCOORD *dy, MWCOORD *dz, int *bp) { static int noevent_count = 0; XEvent ev; int events = 0; long mask = /* x11_event_mask | */ #ifdef USE_EXPOSURE ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ExposureMask; #else ButtonPressMask | ButtonReleaseMask | PointerMotionMask; #endif while (XCheckMaskEvent(x11_dpy, mask, &ev)) { if (ev.type == MotionNotify) { if (ev.xmotion.window == x11_win) { int button = 0; *dx = ev.xmotion.x; *dy = ev.xmotion.y; *dz = 0; if (ev.xmotion.state & Button1Mask) button |= MWBUTTON_L; if (ev.xmotion.state & Button2Mask) button |= MWBUTTON_M; if (ev.xmotion.state & Button3Mask) button |= MWBUTTON_R; *bp = button; events++; } } else if (ev.type == ButtonPress) { if (ev.xbutton.window == x11_win) { int button = 0; /* Get pressed button */ if(ev.xbutton.button == 1) button = MWBUTTON_L; else if(ev.xbutton.button == 2) button = MWBUTTON_M; else if(ev.xbutton.button == 3) button = MWBUTTON_R; /* Get any other buttons that might be already held */ if (ev.xbutton.state & Button1Mask) button |= MWBUTTON_L; if (ev.xbutton.state & Button2Mask) button |= MWBUTTON_M; if (ev.xbutton.state & Button3Mask) button |= MWBUTTON_R; /* printf("!Pressing button: 0x%x, state: 0x%x, button: 0x%x\n", button,ev.xbutton.state, ev.xbutton.button);*/ *bp = button; *dx = ev.xbutton.x; *dy = ev.xbutton.y; *dz = 0; events++; } } else if (ev.type == ButtonRelease) { if (ev.xbutton.window == x11_win) { int button = 0; int released = 0; /* Get released button */ if(ev.xbutton.button == 1) released = MWBUTTON_L; else if(ev.xbutton.button == 2) released = MWBUTTON_M; else if(ev.xbutton.button == 3) released = MWBUTTON_R; /* Get any other buttons that might be already held */ if (ev.xbutton.state & Button1Mask) button |= MWBUTTON_L; if (ev.xbutton.state & Button2Mask) button |= MWBUTTON_M; if (ev.xbutton.state & Button3Mask) button |= MWBUTTON_R; /* We need to remove the released button from the button mask*/ button &= ~released; *bp = button; *dx = ev.xbutton.x; *dy = ev.xbutton.y; *dz = 0; events++; } } else { x11_handle_event(&ev); } } if (events == 0) { /* after a bunch of consecutive noevent calls here (meaning select() says there's something to read but nothing is returned......), force an event read (which will most likely terminate the connection) */ if (++noevent_count >= 50) { while(XNextEvent(x11_dpy, &ev)) { /* if we return, then we got an event...put it back so we can properly process it next time through */ XPutBackEvent(x11_dpy, &ev); } noevent_count = 0; } return 0; } noevent_count = 0; return 2; /* absolute position returned*/ }
int main(void) { Display *xdisplay; XkbEvent xevent; int opcode, xkbEventBase, xkbErrorBase, major, minor; int currentLayout = 0; time_t timestamp; char datetime[DATETIME_BUFFER + 1]; int status; snd_mixer_t *amixer; snd_mixer_elem_t *amixer_elem; snd_mixer_selem_id_t *amixer_selem; long int volume, volumeMin, volumeMax, volumePercent; struct udev *udev; struct udev_monitor *udev_monitor; struct udev_device *udev_device; int udev_fd; int ps_current = 0, ps_total = 0; openlog(NULL, LOG_CONS|LOG_PERROR|LOG_PID, LOG_DAEMON); if (!(xdisplay = XOpenDisplay(NULL))) { syslog(LOG_ERR, "Can't open display: %s!\n", strerror(errno)); return EXIT_FAILURE; } if (!XkbQueryExtension(xdisplay, &opcode, &xkbEventBase, &xkbErrorBase, &major, &minor)) { syslog(LOG_ERR, "X doesn't support a compatible Xkb!\n"); return EXIT_FAILURE; } if (!XkbSelectEvents(xdisplay, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) { syslog(LOG_ERR, "Could not set Xkb event mask!\n"); return EXIT_FAILURE; } if ((status = snd_mixer_open(&amixer, 0)) < 0 || (status = snd_mixer_selem_register(amixer, NULL, NULL)) < 0 || (status = snd_mixer_attach(amixer, "default")) < 0) { syslog(LOG_ERR, "Alsa failed: %s!\n", snd_strerror(status)); return EXIT_FAILURE; } if ((status = snd_mixer_load(amixer)) || (status = snd_mixer_selem_id_malloc(&amixer_selem)) < 0) { syslog(LOG_ERR, "Alsa failed: %s!\n", snd_strerror(status)); return EXIT_FAILURE; } snd_mixer_selem_id_set_index(amixer_selem, 0); snd_mixer_selem_id_set_name(amixer_selem, "Master"); amixer_elem = snd_mixer_find_selem(amixer, amixer_selem); snd_mixer_selem_get_playback_volume_range(amixer_elem, &volumeMin, &volumeMax); if (amixer_elem == NULL) { syslog(LOG_ERR, "Mixer simple element handle not found!\n"); return EXIT_FAILURE; } udev = udev_new(); if (udev == NULL) { syslog(LOG_ERR, "Can't create udev object!\n"); return EXIT_FAILURE; } udev_monitor = udev_monitor_new_from_netlink(udev, "udev"); if (udev_monitor == NULL) { syslog(LOG_ERR, "Can't create udev monitor!\n"); return EXIT_SUCCESS; } if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "power_supply", NULL) < 0) { syslog(LOG_ERR, "Could't watch power_supply events!\n"); return EXIT_FAILURE; } if (udev_monitor_enable_receiving(udev_monitor) < 0) { syslog(LOG_ERR, "Could't bind udev monitor event!\n"); return EXIT_FAILURE; } udev_fd = udev_monitor_get_fd(udev_monitor); while(1) { time(×tamp); strftime(datetime, DATETIME_BUFFER, DATETIME_FORMAT, localtime(×tamp)); while(XPending(xdisplay)) { XNextEvent(xdisplay, &xevent.core); if (xevent.type == xkbEventBase && xevent.any.xkb_type == XkbStateNotify) { currentLayout = xevent.state.group; } } if ((status = snd_mixer_handle_events(amixer)) < 0) { syslog(LOG_ERR, "Alsa failed: %s!\n", snd_strerror(status)); return EXIT_FAILURE; } if ((status = snd_mixer_selem_get_playback_volume(amixer_elem, SND_MIXER_SCHN_MONO, &volume)) < 0) { syslog(LOG_ERR, "Alsa failed: %s!\n", snd_strerror(status)); return EXIT_FAILURE; } volumePercent = (volume * 100) / volumeMax; fd_set fds; int ret; struct timeval tv = {.tv_sec = 0, .tv_usec = 0}; FD_ZERO(&fds); FD_SET(udev_fd, &fds); ret = select(udev_fd + 1, &fds, NULL, NULL, &tv); if (ret > 0 && FD_ISSET(udev_fd, &fds)) { udev_device = udev_monitor_receive_device(udev_monitor); if (udev_device == NULL) { syslog(LOG_ERR, "Can't get udev device!\n"); return EXIT_SUCCESS; } printf("Name: %s\n", udev_device_get_sysname(udev_device)); printf("Node: %s\n", udev_device_get_devnode(udev_device)); printf("Subsystem: %s\n", udev_device_get_subsystem(udev_device)); printf("Devtype: %s\n", udev_device_get_devtype(udev_device)); printf("Action: %s\n", udev_device_get_action(udev_device)); /*ps_current = atoi(udev_device_get_property_value(udev_device, "POWER_SUPPLY_CHARGE_NOW"));*/ /*ps_total = atoi(udev_device_get_property_value(udev_device, "POWER_SUPPLY_CHARGE_FULL"));*/ printf("%s\n", udev_device_get_sysattr_value(udev_device, "energy_now")); printf("%s\n", udev_device_get_sysattr_value(udev_device, "energy_full")); udev_device_unref(udev_device); } printf("%s %s\t%s %li\t%s %i\t%s %s\n", GLYPH_KEYBOARD, layouts[currentLayout], GLYPH_VOLUME, volumePercent, GLYPH_BATTERY, ps_current, GLYPH_CLOCK, datetime ); usleep(SLEEP_MSECONDS * 1000); } snd_mixer_selem_id_free(amixer_selem); snd_mixer_close(amixer); XCloseDisplay(xdisplay); closelog(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { EGLDisplay sEGLDisplay; EGLContext sEGLContext; EGLSurface sEGLSurface; /* EGL Configuration */ EGLint aEGLAttributes[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; EGLint aEGLContextAttributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLConfig aEGLConfigs[1]; EGLint cEGLConfigs; #ifdef _WIN32 MSG sMessage; #else XSetWindowAttributes win_attrs; int attrs[64], idx = 0, num_config = 0; int major, minor; Colormap colormap; XVisualInfo *pVisual; XEvent e; #endif GLint iLocPosition = 0; GLint iLocColour, iLocTexCoord, iLocNormal, iLocMVP; GLint iLocXangle, iLocYangle, iLocZangle; GLint iLocAspect, iLocLightPos, iLocSampler, iLocSampler2; GLuint uiProgram, uiFragShader, uiVertShader; GLenum myTex, myTex2; int bDone = 0; const unsigned int uiWidth = 640; const unsigned int uiHeight = 480; int iXangle = 0, iYangle = 0, iZangle = 0; float aTBNmatrix1[9], aTBNmatrix2[9]; float aLightPos[] = { 0.0f, 0.0f, -1.0f }; // Light is nearest camera. unsigned char *myPixels = calloc(1, 128*128*4); // Holds texture data. unsigned char *myPixels2 = calloc(1, 128*128*4); // Holds texture data. float aRotate[16], aModelView[16], aPerspective[16], aMVP[16]; int i; /* EGL Init */ #ifdef _WIN32 hDisplay = EGL_DEFAULT_DISPLAY; #else hDisplay = XOpenDisplay(NULL); if (!hDisplay) { printf("Could not open display\n"); exit(-1); } #endif sEGLDisplay = EGL_CHECK(eglGetDisplay(hDisplay)); EGL_CHECK(eglInitialize(sEGLDisplay, NULL, NULL)); EGL_CHECK(eglChooseConfig(sEGLDisplay, aEGLAttributes, aEGLConfigs, 1, &cEGLConfigs)); if (cEGLConfigs == 0) { printf("No EGL configurations were returned.\n"); exit(-1); } #ifdef _WIN32 hWindow = create_window(uiWidth, uiHeight); #else hWindow = create_window("OpenGL ES 2.0 Example on a Linux Desktop", uiWidth, uiHeight, hDisplay, sEGLDisplay, aEGLConfigs[0], &colormap, &pVisual); #endif sEGLSurface = EGL_CHECK(eglCreateWindowSurface(sEGLDisplay, aEGLConfigs[0], (EGLNativeWindowType)hWindow, NULL)); if (sEGLSurface == EGL_NO_SURFACE) { printf("Failed to create EGL surface.\n"); exit(-1); } sEGLContext = EGL_CHECK(eglCreateContext(sEGLDisplay, aEGLConfigs[0], EGL_NO_CONTEXT, aEGLContextAttributes)); if (sEGLContext == EGL_NO_CONTEXT) { printf("Failed to create EGL context.\n"); exit(-1); } EGL_CHECK(eglMakeCurrent(sEGLDisplay, sEGLSurface, sEGLSurface, sEGLContext)); /* Shader Initialisation */ process_shader(&uiVertShader, "shader.vert", GL_VERTEX_SHADER); process_shader(&uiFragShader, "shader.frag", GL_FRAGMENT_SHADER); /* Create uiProgram (ready to attach shaders) */ uiProgram = GL_CHECK(glCreateProgram()); /* Attach shaders and link uiProgram */ GL_CHECK(glAttachShader(uiProgram, uiVertShader)); GL_CHECK(glAttachShader(uiProgram, uiFragShader)); GL_CHECK(glLinkProgram(uiProgram)); /* Get attribute locations of non-fixed attributes like colour and texture coordinates. */ iLocPosition = GL_CHECK(glGetAttribLocation(uiProgram, "av4position")); iLocColour = GL_CHECK(glGetAttribLocation(uiProgram, "av3colour")); #ifdef DEBUG printf("iLocPosition = %i\n", iLocPosition); printf("iLocColour = %i\n", iLocColour); #endif /* Get uniform locations */ iLocMVP = GL_CHECK(glGetUniformLocation(uiProgram, "mvp")); #ifdef DEBUG printf("iLocMVP = %i\n", iLocMVP); #endif GL_CHECK(glUseProgram(uiProgram)); /* Enable attributes for position, colour and texture coordinates etc. */ GL_CHECK(glEnableVertexAttribArray(iLocPosition)); GL_CHECK(glEnableVertexAttribArray(iLocColour)); /* Populate attributes for position, colour and texture coordinates etc. */ GL_CHECK(glVertexAttribPointer(iLocPosition, 3, GL_FLOAT, GL_FALSE, 0, aVertices)); GL_CHECK(glVertexAttribPointer(iLocColour, 3, GL_FLOAT, GL_FALSE, 0, aColours)); GL_CHECK(glEnable(GL_CULL_FACE)); GL_CHECK(glEnable(GL_DEPTH_TEST)); #ifndef _WIN32 XSelectInput(hDisplay, hWindow, KeyPressMask | ExposureMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | VisibilityChangeMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask); #endif /* Enter event loop */ while (!bDone) { #ifdef _WIN32 if(PeekMessage(&sMessage, NULL, 0, 0, PM_REMOVE)) { if(sMessage.message == WM_QUIT) { bDone = 1; } else { TranslateMessage(&sMessage); DispatchMessage(&sMessage); } } #else while (XPending(hDisplay) > 0) { XNextEvent(hDisplay, &e); if (e.type == ButtonPress) { bDone = 1; } } #endif /* * Do some rotation with Euler angles. It is not a fixed axis as * quaterions would be, but the effect is cool. */ rotate_matrix(iXangle, 1.0, 0.0, 0.0, aModelView); rotate_matrix(iYangle, 0.0, 1.0, 0.0, aRotate); multiply_matrix(aRotate, aModelView, aModelView); rotate_matrix(iZangle, 0.0, 1.0, 0.0, aRotate); multiply_matrix(aRotate, aModelView, aModelView); /* Pull the camera back from the cube */ aModelView[14] -= 2.5; perspective_matrix(45.0, (double)uiWidth/(double)uiHeight, 0.01, 100.0, aPerspective); multiply_matrix(aPerspective, aModelView, aMVP); GL_CHECK(glUniformMatrix4fv(iLocMVP, 1, GL_FALSE, aMVP)); iXangle += 3; iYangle += 2; iZangle += 1; if(iXangle >= 360) iXangle -= 360; if(iXangle < 0) iXangle += 360; if(iYangle >= 360) iYangle -= 360; if(iYangle < 0) iYangle += 360; if(iZangle >= 360) iZangle -= 360; if(iZangle < 0) iZangle += 360; GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)); GL_CHECK(glDrawArrays(GL_TRIANGLES, 0, 36)); if (!eglSwapBuffers(sEGLDisplay, sEGLSurface)) { printf("Failed to swap buffers.\n"); } #ifdef _WIN32 Sleep(20); #else usleep(20000); #endif } /* Cleanup shaders */ GL_CHECK(glUseProgram(0)); GL_CHECK(glDeleteShader(uiVertShader)); GL_CHECK(glDeleteShader(uiFragShader)); GL_CHECK(glDeleteProgram(uiProgram)); /* EGL clean up */ EGL_CHECK(eglMakeCurrent(sEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); EGL_CHECK(eglDestroySurface(sEGLDisplay, sEGLSurface)); EGL_CHECK(eglDestroyContext(sEGLDisplay, sEGLContext)); EGL_CHECK(eglTerminate(sEGLDisplay)); #ifndef _WIN32 /* X windows clean up */ XDestroyWindow(hDisplay, hWindow); XFreeColormap(hDisplay, colormap); XFree(pVisual); XCloseDisplay(hDisplay); #endif return 0; }
void MainLoop() override { bool fullscreen = SConfig::GetInstance().m_LocalCoreStartupParameter.bFullscreen; if (fullscreen) { X11Utils::ToggleFullscreen(dpy, win); #if defined(HAVE_XRANDR) && HAVE_XRANDR XRRConfig->ToggleDisplayMode(True); #endif } // The actual loop while (running) { XEvent event; KeySym key; for (int num_events = XPending(dpy); num_events > 0; num_events--) { XNextEvent(dpy, &event); switch (event.type) { case KeyPress: key = XLookupKeysym((XKeyEvent*)&event, 0); if (key == XK_Escape) { if (Core::GetState() == Core::CORE_RUN) { if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XUndefineCursor(dpy, win); Core::SetState(Core::CORE_PAUSE); } else { if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XDefineCursor(dpy, win, blankCursor); Core::SetState(Core::CORE_RUN); } } else if ((key == XK_Return) && (event.xkey.state & Mod1Mask)) { fullscreen = !fullscreen; X11Utils::ToggleFullscreen(dpy, win); #if defined(HAVE_XRANDR) && HAVE_XRANDR XRRConfig->ToggleDisplayMode(fullscreen); #endif } else if (key >= XK_F1 && key <= XK_F8) { int slot_number = key - XK_F1 + 1; if (event.xkey.state & ShiftMask) State::Save(slot_number); else State::Load(slot_number); } else if (key == XK_F9) Core::SaveScreenShot(); else if (key == XK_F11) State::LoadLastSaved(); else if (key == XK_F12) { if (event.xkey.state & ShiftMask) State::UndoLoadState(); else State::UndoSaveState(); } break; case FocusIn: rendererHasFocus = true; if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor && Core::GetState() != Core::CORE_PAUSE) XDefineCursor(dpy, win, blankCursor); break; case FocusOut: rendererHasFocus = false; if (SConfig::GetInstance().m_LocalCoreStartupParameter.bHideCursor) XUndefineCursor(dpy, win); break; case ClientMessage: if ((unsigned long) event.xclient.data.l[0] == XInternAtom(dpy, "WM_DELETE_WINDOW", False)) running = false; break; } } if (!fullscreen) { Window winDummy; unsigned int borderDummy, depthDummy; XGetGeometry(dpy, win, &winDummy, &SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowXPos, &SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowYPos, (unsigned int *)&SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowWidth, (unsigned int *)&SConfig::GetInstance().m_LocalCoreStartupParameter.iRenderWindowHeight, &borderDummy, &depthDummy); } usleep(100000); } }
void SampleMain() { SfwOpenWindow("Gainput: Gesture sample"); gainput::TrackingAllocator allocator(gainput::GetDefaultAllocator()); gainput::InputManager manager(true, allocator); const gainput::DeviceId keyboardId = manager.CreateDevice<gainput::InputDeviceKeyboard>(); const gainput::DeviceId mouseId = manager.CreateDevice<gainput::InputDeviceMouse>(); gainput::InputDeviceTouch* touchDevice = manager.CreateAndGetDevice<gainput::InputDeviceTouch>(); GAINPUT_ASSERT(touchDevice); gainput::DeviceId touchId = touchDevice->GetDeviceId(); #if defined(GAINPUT_PLATFORM_LINUX) || defined(GAINPUT_PLATFORM_WIN) manager.SetDisplaySize(SfwGetWidth(), SfwGetHeight()); #endif SfwSetInputManager(&manager); gainput::InputMap map(manager, "testmap", allocator); map.MapBool(ButtonConfirm, mouseId, gainput::MouseButtonLeft); gainput::DoubleClickGesture* dcg = manager.CreateAndGetDevice<gainput::DoubleClickGesture>(); GAINPUT_ASSERT(dcg); dcg->Initialize(mouseId, gainput::MouseButtonLeft, mouseId, gainput::MouseAxisX, 0.01f, mouseId, gainput::MouseAxisY, 0.01f, 500); map.MapBool(ButtonConfirmDouble, dcg->GetDeviceId(), gainput::DoubleClickTriggered); gainput::SimultaneouslyDownGesture* sdg = manager.CreateAndGetDevice<gainput::SimultaneouslyDownGesture>(); GAINPUT_ASSERT(sdg); sdg->AddButton(mouseId, gainput::MouseButtonLeft); sdg->AddButton(keyboardId, gainput::KeyShiftL); map.MapBool(ButtonConfirmExtra, sdg->GetDeviceId(), gainput::SimultaneouslyDownTriggered); MultiTouchEmulator* mte = manager.CreateAndGetDevice<MultiTouchEmulator>(); mte->Initialize(sdg->GetDeviceId(), gainput::SimultaneouslyDownTriggered, mouseId, gainput::MouseAxisX, mouseId, gainput::MouseAxisY, mouseId, gainput::MouseButtonLeft, mouseId, gainput::MouseAxisX, mouseId, gainput::MouseAxisY); if (!touchDevice->IsAvailable() || touchDevice->GetVariant() == gainput::InputDevice::DV_NULL) { touchId = mte->GetDeviceId(); } gainput::HoldGesture* hg = manager.CreateAndGetDevice<gainput::HoldGesture>(); GAINPUT_ASSERT(hg); hg->Initialize(touchId, gainput::Touch0Down, touchId, gainput::Touch0X, 0.1f, touchId, gainput::Touch0Y, 0.1f, true, 800); map.MapBool(ButtonHoldGesture, hg->GetDeviceId(), gainput::HoldTriggered); gainput::TapGesture* tg = manager.CreateAndGetDevice<gainput::TapGesture>(); GAINPUT_ASSERT(tg); tg->Initialize(touchId, gainput::Touch0Down, 500); map.MapBool(ButtonTapGesture, tg->GetDeviceId(), gainput::TapTriggered); gainput::PinchGesture* pg = manager.CreateAndGetDevice<gainput::PinchGesture>(); GAINPUT_ASSERT(pg); pg->Initialize(touchId, gainput::Touch0Down, touchId, gainput::Touch0X, touchId, gainput::Touch0Y, touchId, gainput::Touch1Down, touchId, gainput::Touch1X, touchId, gainput::Touch1Y); map.MapBool(ButtonPinching, pg->GetDeviceId(), gainput::PinchTriggered); map.MapFloat(ButtonPinchScale, pg->GetDeviceId(), gainput::PinchScale); gainput::RotateGesture* rg = manager.CreateAndGetDevice<gainput::RotateGesture>(); GAINPUT_ASSERT(rg); rg->Initialize(touchId, gainput::Touch0Down, touchId, gainput::Touch0X, touchId, gainput::Touch0Y, touchId, gainput::Touch1Down, touchId, gainput::Touch1X, touchId, gainput::Touch1Y); map.MapBool(ButtonRotating, rg->GetDeviceId(), gainput::RotateTriggered); map.MapFloat(ButtonRotateAngle, rg->GetDeviceId(), gainput::RotateAngle); bool doExit = false; while (!SfwIsDone() && !doExit) { manager.Update(); #if defined(GAINPUT_PLATFORM_LINUX) XEvent event; while (XPending(SfwGetXDisplay())) { XNextEvent(SfwGetXDisplay(), &event); manager.HandleEvent(event); if (event.type == DestroyNotify || event.type == ClientMessage) { doExit = true; } } #elif defined(GAINPUT_PLATFORM_WIN) MSG msg; while (PeekMessage(&msg, SfwGetHWnd(), 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); manager.HandleMessage(msg); } #endif SfwUpdate(); if (map.GetBoolWasDown(ButtonConfirm)) { SFW_LOG("Confirmed!\n"); SFW_LOG("Memory: %u allocs, %u deallocs, %u used bytes\n", static_cast<unsigned>(allocator.GetAllocateCount()), static_cast<unsigned>(allocator.GetDeallocateCount()), static_cast<unsigned>(allocator.GetAllocatedMemory())); } if (map.GetBoolWasDown(ButtonConfirmDouble)) { SFW_LOG("Confirmed doubly!\n"); } if (map.GetBoolWasDown(ButtonConfirmExtra)) { SFW_LOG("Confirmed alternatively!\n"); } if (map.GetBool(ButtonHoldGesture)) { SFW_LOG("Hold triggered!\n"); } if (map.GetBoolWasDown(ButtonTapGesture)) { SFW_LOG("Tapped!\n"); } if (map.GetBool(ButtonPinching)) { SFW_LOG("Pinching: %f\n", map.GetFloat(ButtonPinchScale)); } if (map.GetBool(ButtonRotating)) { SFW_LOG("Rotation angle: %f\n", map.GetFloat(ButtonRotateAngle)); } } SfwCloseWindow(); }
int crt0_inkey(void) { if (sizeChanged) { sizeChanged=0; return KB_SIZE;} for(;;) { XEvent report; XNextEvent(display,&report); switch(report.type) { case KeyPress: { char c; KeySym keysym; c=0; XLookupString(&report.xkey,&c,1,&keysym,NULL); if(c!=0 && c<127 ) return c; switch(keysym) { case XK_Left: return KB_LEFT; case XK_Down: return KB_DOWN; case XK_Up: return KB_UP ; case XK_Right:return KB_RIGHT; case XK_Home: return KB_HOME; case XK_Tab: return KB_TAB; case XK_F1: return KB_F1; case XK_F2: return KB_F2; case XK_F3: return KB_F3; case XK_F4: return KB_F4; case XK_F5: return KB_F5; case XK_F6: return KB_F6; case XK_F7: return KB_F7; case XK_F8: return KB_F8; case XK_F9: return KB_F9; case XK_F10: return KB_F10; case XK_F11: return KB_ESC; case XK_Delete: /* return KB_DC; */ case XK_F12: case XK_BackSpace: return KB_BACKSP; case XK_Insert: return KB_IC; case XK_Next: return KB_PAGED; case XK_Prior: return KB_PAGEU; case XK_Begin: return KB_HOME; case XK_End: return KB_END; default: break; } } break; case Expose: if (xw_expose !=NULL) (*xw_expose)(report.xexpose.x, report.xexpose.y,report.xexpose.width,report.xexpose.height); break; case ButtonPress: mouse_info.x=report.xbutton.x; mouse_info.y=report.xbutton.y; mouse_info.col=mouse_info.x/xw_fn_w+1; mouse_info.row=mouse_info.y/xw_fn_h+1; mouse_info.but1=mouse_info.but2=mouse_info.but3=0; mouse_info.but4=mouse_info.but5=0; if(report.xbutton.button==Button1) mouse_info.but1= 1; if(report.xbutton.button==Button2) mouse_info.but2= 1; if(report.xbutton.button==Button3) mouse_info.but3= 1; if(report.xbutton.button==Button4) mouse_info.but4= 1; if(report.xbutton.button==Button5) mouse_info.but5= 1; return KB_MOUSE; case ButtonRelease: mouse_info.x=report.xbutton.x; mouse_info.y=report.xbutton.y; mouse_info.col=mouse_info.x/xw_fn_w+1; mouse_info.row=mouse_info.y/xw_fn_h+1; mouse_info.but1=mouse_info.but2=mouse_info.but3=0; mouse_info.but4=mouse_info.but5=0; if(report.xbutton.button==Button1) mouse_info.but1= 2; if(report.xbutton.button==Button2) mouse_info.but2= 2; if(report.xbutton.button==Button3) mouse_info.but3= 2; if(report.xbutton.button==Button4) mouse_info.but4= 2; if(report.xbutton.button==Button5) mouse_info.but5= 2; return KB_MOUSE; case ConfigureNotify: bgi_maxx=report.xconfigure.width-1; bgi_maxy=report.xconfigure.height-1; if (xw_expose !=NULL) (*xw_expose)(0,0,bgi_maxx,bgi_maxy); return KB_SIZE; } } }
void wmifs_routine(int argc, char **argv) { rckeys wmifs_keys[] = { { "left", &left_action }, { "middle", &middle_action }, { "right", &right_action }, { NULL, NULL } }; int i, j; XEvent Event; int but_stat = -1; int stat_online; int stat_current; int first_time = 1; unsigned int curtime; unsigned int nexttime; struct timeval tv, tv2; long ipacket, opacket, istat, ostat; char temp[BUFFER_SIZE]; char *p; for (i = 0; i < MAX_STAT_DEVICES; i++) { stat_devices[i].name[0] = 0; for (j = 0; j < 48; j++) { stat_devices[i].his[j][0] = 0; stat_devices[i].his[j][1] = 0; } } stat_online = checknetdevs(); stat_current = 0; if (active_interface) { int isauto = !strcmp(active_interface, "auto"); for (i = 0; i < stat_online; i++) { if ((isauto && stillonline(stat_devices[i].name)) || !strcmp(stat_devices[i].name, active_interface)) { stat_current = i; break; } } } #ifdef LEFT_ACTION left_action = strdup(LEFT_ACTION); #endif #ifdef MIDDLE_ACTION middle_action = strdup(MIDDLE_ACTION); #endif #ifdef RIGHT_ACTION right_action = strdup(RIGHT_ACTION); #endif /* Scan throught the .rc files */ parse_rcfile(CONF"/wmifsrc", wmifs_keys); p = getenv("HOME"); if (p == NULL || *p == 0) { fprintf(stderr, "Unknown $HOME directory, please check your environment\n"); return; } strncpy(temp, p, BUFFER_SIZE - 10); strcat(temp, "/.wmifsrc"); parse_rcfile(temp, wmifs_keys); parse_rcfile(CONF"/wmifsrc.fixed", wmifs_keys); /* set user-defined colors */ if (color[0] != 0) { Window Root; XColor col; XWindowAttributes attributes; int screen; Pixel pixel; #define NUMSYMBOLS 4 XpmColorSymbol user_color[NUMSYMBOLS] = { {NULL, "#2081B2CAAEBA", 0}, /* + */ {NULL, "#28A23CF338E3", 0}, /* O */ {NULL, "#000049244103", 0}, /* @ */ {NULL, "#18618A288617", 0}, /* # */ }; /* code based on GetColor() from wmgeneral.c */ /* we need a temporary display to parse the color */ display = XOpenDisplay(NULL); screen = DefaultScreen(display); Root = RootWindow(display, screen); XGetWindowAttributes(display, Root, &attributes); col.pixel = 0; if (!XParseColor(display, attributes.colormap, color, &col)) { fprintf(stderr, "wmtime: can't parse %s.\n", color); goto draw_window; } else if (!XAllocColor(display, attributes.colormap, &col)) { fprintf(stderr, "wmtime: can't allocate %s.\n", color); goto draw_window; } pixel = col.pixel; /* replace colors from wmtime-master.xpm */ user_color[0].pixel = pixel; user_color[1].pixel = scale_pixel(pixel, .3); user_color[2].pixel = scale_pixel(pixel, .4); user_color[3].pixel = scale_pixel(pixel, .8); wmgen.attributes.valuemask |= XpmColorSymbols; wmgen.attributes.numsymbols = NUMSYMBOLS; wmgen.attributes.colorsymbols = user_color; XCloseDisplay(display); } draw_window: openXwindow(argc, argv, wmifs_master_xpm, (char*)wmifs_mask_bits, wmifs_mask_width, wmifs_mask_height); /* > Button */ AddMouseRegion(0, 5, 5, 35, 15); AddMouseRegion(1, 5, 20, 58, 58); gettimeofday(&tv2, NULL); nexttime = ScrollSpeed; DrawActiveIFS(stat_devices[stat_current].name); while (1) { struct timespec ts; gettimeofday(&tv, NULL); curtime = (tv.tv_sec - tv2.tv_sec) * 1000 + (tv.tv_usec - tv2.tv_usec) / 1000; waitpid(0, NULL, WNOHANG); for (i = 0; i < stat_online; i++) { get_statistics(stat_devices[i].name, &ipacket, &opacket, &istat, &ostat); if (first_time) { first_time = 0; } else { stat_devices[i].his[53][0] += istat - stat_devices[i].istatlast; stat_devices[i].his[53][1] += ostat - stat_devices[i].ostatlast; } if (i == stat_current) { if (!stillonline(stat_devices[i].name)) SetErrLED(LED_NET_POWER); else SetOnLED(LED_NET_POWER); if (stat_devices[i].istatlast == istat) SetOffLED(LED_NET_RX); else SetOnLED(LED_NET_RX); if (stat_devices[i].ostatlast == ostat) SetOffLED(LED_NET_TX); else SetOnLED(LED_NET_TX); } stat_devices[i].istatlast = istat; stat_devices[i].ostatlast = ostat; } RedrawWindow(); if (curtime >= nexttime) { nexttime = curtime + ScrollSpeed; DrawStats(&stat_devices[stat_current].his[0][0], 54, 40, 5, 58); for (i = 0; i < stat_online; i++) { if (stillonline(stat_devices[i].name)) { for (j = 1; j < 54; j++) { stat_devices[i].his[j-1][0] = stat_devices[i].his[j][0]; stat_devices[i].his[j-1][1] = stat_devices[i].his[j][1]; } stat_devices[i].his[53][0] = 0; stat_devices[i].his[53][1] = 0; } } RedrawWindow(); } while (XPending(display)) { XNextEvent(display, &Event); switch (Event.type) { case Expose: RedrawWindow(); break; case DestroyNotify: XCloseDisplay(display); exit(0); break; case ButtonPress: but_stat = CheckMouseRegion(Event.xbutton.x, Event.xbutton.y); break; case ButtonRelease: i = CheckMouseRegion(Event.xbutton.x, Event.xbutton.y); if (but_stat == i && but_stat >= 0) { switch (but_stat) { case 0: /* re-read the table */ strcpy(temp, stat_devices[stat_current].name); stat_online = checknetdevs(); stat_current = 0; for (i = 0; i < stat_online; i++) { if (!strcmp(temp, stat_devices[i].name)) stat_current = i; } stat_current++; if (stat_current == stat_online) stat_current = 0; DrawActiveIFS(stat_devices[stat_current].name); DrawStats(&stat_devices[stat_current].his[0][0], 54, 40, 5, 58); break; case 1: switch (Event.xbutton.button) { case 1: if (left_action) execCommand(left_action); break; case 2: if (middle_action) execCommand(middle_action); break; case 3: if (right_action) execCommand(right_action); break; } break; } } but_stat = -1; RedrawWindow(); break; } } ts.tv_sec = 0; ts.tv_nsec = SampleInt * 1000000; nanosleep(&ts, NULL); } }
/*ARGSUSED*/ extern int main(int argc, char *argv[]) { XEvent ev; struct sigaction sa; int dpy_fd, max_fd; argv0 = argv[0]; mode = wm_initialising; setlocale(LC_ALL, ""); /* Open a connection to the X server. */ dpy = XOpenDisplay(NULL); if (dpy == 0) panic("can't open display."); parseResources(); /* Set up an error handler. */ XSetErrorHandler(errorHandler); /* Set up signal handlers. */ signal(SIGTERM, Terminate); signal(SIGINT, Terminate); signal(SIGHUP, Terminate); /* Ignore SIGCHLD. */ sa.sa_handler = SIG_IGN; #ifdef SA_NOCLDWAIT sa.sa_flags = SA_NOCLDWAIT; #else sa.sa_flags = 0; #endif sigemptyset(&sa.sa_mask); sigaction(SIGCHLD, &sa, 0); /* Internalize useful atoms. */ wm_state = XInternAtom(dpy, "WM_STATE", False); wm_change_state = XInternAtom(dpy, "WM_CHANGE_STATE", False); wm_protocols = XInternAtom(dpy, "WM_PROTOCOLS", False); wm_delete = XInternAtom(dpy, "WM_DELETE_WINDOW", False); wm_take_focus = XInternAtom(dpy, "WM_TAKE_FOCUS", False); wm_colormaps = XInternAtom(dpy, "WM_COLORMAP_WINDOWS", False); compound_text = XInternAtom(dpy, "COMPOUND_TEXT", False); _mozilla_url = XInternAtom(dpy, "_MOZILLA_URL", False); motif_wm_hints = XInternAtom(dpy, "_MOTIF_WM_HINTS", False); ewmh_init(); /* * Get fonts for our titlebar and our popup window. We try to * get Lucida, but if we can't we make do with fixed because everyone * has that. */ { /* FIXME: do these need to be freed? */ char **missing; char *def; int missing_count; font_set = XCreateFontSet(dpy, font_name, &missing, &missing_count, &def); if (font_set == NULL) font_set = XCreateFontSet(dpy, "fixed", &missing, &missing_count, &def); if (font_set == NULL) panic("unable to create font set for title font"); if (missing_count > 0) fprintf(stderr,"%s: warning: missing %d charset" "%s for title font\n", argv0, missing_count, (missing_count == 1)?"":"s"); font_set_ext = XExtentsOfFontSet(font_set); popup_font_set = XCreateFontSet(dpy, popup_font_name, &missing, &missing_count, &def); if (popup_font_set == NULL) popup_font_set = XCreateFontSet(dpy, "fixed", &missing, &missing_count, &def); if (popup_font_set == NULL) panic("unable to create font set for popup font"); if (missing_count > 0) fprintf(stderr,"%s: warning: missing %d charset" "%s for popup font\n", argv0, missing_count, (missing_count == 1)?"":"s"); popup_font_set_ext = XExtentsOfFontSet(popup_font_set); } initScreens(); ewmh_init_screens(); session_init(argc, argv); /* See if the server has the Shape Window extension. */ shape = serverSupportsShapes(); /* * Initialisation is finished, but we start off not interacting with the * user. */ mode = wm_idle; /* * The main event loop. */ dpy_fd = ConnectionNumber(dpy); max_fd = dpy_fd + 1; if (ice_fd > dpy_fd) max_fd = ice_fd + 1; for (;;) { fd_set readfds; FD_ZERO(&readfds); FD_SET(dpy_fd, &readfds); if (ice_fd > 0) FD_SET(ice_fd, &readfds); if (select(max_fd, &readfds, NULL, NULL, NULL) > -1) { if (FD_ISSET(dpy_fd, &readfds)) { while (XPending(dpy)) { XNextEvent(dpy, &ev); dispatch(&ev); } } if (ice_fd > 0 && FD_ISSET(ice_fd, &readfds)) { session_process(); } } } }
static int select_region(Display *dpy, Window root, Region *region) { XEvent ev; GC sel_gc; XGCValues sel_gv; int done = 0, btn_pressed = 0; int x = 0, y = 0; unsigned int width = 0, height = 0; int start_x = 0, start_y = 0; Cursor cursor; cursor = XCreateFontCursor(dpy, XC_crosshair); XGrabPointer( dpy, root, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, cursor, CurrentTime ); sel_gv.function = GXinvert; sel_gv.subwindow_mode = IncludeInferiors; sel_gv.line_width = 1; sel_gc = XCreateGC(dpy, root, GCFunction | GCSubwindowMode | GCLineWidth, &sel_gv); for (;;) { XNextEvent(dpy, &ev); switch (ev.type) { case ButtonPress: btn_pressed = 1; x = start_x = ev.xbutton.x_root; y = start_y = ev.xbutton.y_root; width = height = 0; break; case MotionNotify: /* Draw only if button is pressed */ if (btn_pressed) { /* Re-draw last Rectangle to clear it */ XDrawRectangle(dpy, root, sel_gc, x, y, width, height); x = ev.xbutton.x_root; y = ev.xbutton.y_root; if (x > start_x) { width = x - start_x; x = start_x; } else { width = start_x - x; } if (y > start_y) { height = y - start_y; y = start_y; } else { height = start_y - y; } /* Draw Rectangle */ XDrawRectangle(dpy, root, sel_gc, x, y, width, height); XFlush(dpy); } break; case ButtonRelease: done = 1; break; default: break; } if (done) break; } /* Re-draw last Rectangle to clear it */ XDrawRectangle(dpy, root, sel_gc, x, y, width, height); XFlush(dpy); XUngrabPointer(dpy, CurrentTime); XFreeCursor(dpy, cursor); XFreeGC(dpy, sel_gc); XSync(dpy, 1); Region rr; /* root region */ Region sr; /* selected region */ if (False == XGetGeometry(dpy, root, &rr.root, &rr.x, &rr.y, &rr.w, &rr.h, &rr.b, &rr.d)) { error("failed to get root window geometry\n"); return EXIT_FAILURE; } sr.x = x; sr.y = y; sr.w = width; sr.h = height; /* calculate right and bottom offset */ sr.X = rr.w - sr.x - sr.w; sr.Y = rr.h - sr.y - sr.h; /* those doesn't really make sense but should be set */ sr.b = rr.b; sr.d = rr.d; *region = sr; return EXIT_SUCCESS; }
int main(int argc, char **argv) { XEvent event; KeySym key; done = False; /* default to fullscreen */ GLWin.fs = false; if (!createGLWindow("NeHe's Texture Mapping Tutorial", 640, 480, 24, GLWin.fs)) { done = True; } /* wait for events*/ while (!done) { /* handle the events in the queue */ while (XPending(GLWin.dpy) > 0) { XNextEvent(GLWin.dpy, &event); switch (event.type) { case Expose: if (event.xexpose.count != 0) break; drawGLScene(); break; case ConfigureNotify: /* call resizeGLScene only if our window-size changed */ if ((event.xconfigure.width != GLWin.width) || (event.xconfigure.height != GLWin.height)) { GLWin.width = event.xconfigure.width; GLWin.height = event.xconfigure.height; printf("Resize event\n"); resizeGLScene(event.xconfigure.width, event.xconfigure.height); } break; /* exit in case of a mouse button press */ case ButtonPress: done = True; break; case KeyPress: key = XLookupKeysym(&event.xkey, 0); keyPressed(key); break; case ClientMessage: if (*XGetAtomName(GLWin.dpy, event.xclient.message_type) == *"WM_PROTOCOLS") { printf("Exiting sanely...\n"); done = True; } break; default: break; } } drawGLScene(); } killGLWindow(); return 0; }
static int display(struct vidisp_st *st, const char *title, const struct vidframe *frame) { struct vidframe frame_rgb; int err = 0; if (!st->disp) return ENODEV; /* * check for window delete - without blocking */ while (XPending(st->disp)) { XEvent e; XNextEvent(st->disp, &e); if (e.type == ClientMessage) { if ((Atom) e.xclient.data.l[0] == st->XwinDeleted) { info("x11: window deleted\n"); /* * we have to bail as all of the display * pointers are bad. */ close_window(st); return ENODEV; } } } if (!vidsz_cmp(&st->size, &frame->size)) { char capt[256]; if (st->size.w && st->size.h) { info("x11: reset: %u x %u ---> %u x %u\n", st->size.w, st->size.h, frame->size.w, frame->size.h); } if (st->internal && !st->win) err = create_window(st, &frame->size); err |= x11_reset(st, &frame->size); if (err) return err; if (title) { re_snprintf(capt, sizeof(capt), "%s - %u x %u", title, frame->size.w, frame->size.h); } else { re_snprintf(capt, sizeof(capt), "%u x %u", frame->size.w, frame->size.h); } XStoreName(st->disp, st->win, capt); } /* Convert from YUV420P to RGB */ vidframe_init_buf(&frame_rgb, st->pixfmt, &frame->size, (uint8_t *)st->shm.shmaddr); vidconv(&frame_rgb, frame, 0); /* draw */ if (st->xshmat) XShmPutImage(st->disp, st->win, st->gc, st->image, 0, 0, 0, 0, st->size.w, st->size.h, false); else XPutImage(st->disp, st->win, st->gc, st->image, 0, 0, 0, 0, st->size.w, st->size.h); XSync(st->disp, false); return err; }
void handleTooSmall(XInfo &xinfo, XEvent event) { int x = 0; XEvent event2; unsigned long lastRepaint = 0; int inside = 0; XFillRectangle(xinfo.display, xinfo.window, xinfo.gc[0], 0, 0, 800, 600); std::string text_pause("--Pause--"); XDrawImageString( xinfo.display, xinfo.window, xinfo.gc[1], xinfo.current_w/2, xinfo.current_h/2, text_pause.c_str(), text_pause.length() ); std::string text_resume("The window is too small, please resize the window"); XDrawImageString( xinfo.display, xinfo.window, xinfo.gc[1], xinfo.current_w/2, xinfo.current_h/2 + 20, text_resume.c_str(), text_resume.length() ); while (x == 0) { // stay looping untill window size exceed 800*600 // print to the screen notify user the game window is too small if (XPending(xinfo.display) > 0) { XNextEvent( xinfo.display, &event2 ); switch( event2.type ) { case ConfigureNotify: { XConfigureEvent xce = event2.xconfigure; fprintf(stderr, "Handling resize w=%d h=%d\n", xce.width, xce.height); xinfo.current_w = xce.width; xinfo.current_h = xce.height; if (xce.width >= 800 && xce.height >= 600) { printf("w > 800 and h > 600 resuming the game!!\n"); x = 1; } else { XFillRectangle(xinfo.display, xinfo.window, xinfo.gc[0], 0, 0, 800, 600); std::string text_pause("--Pause--"); XDrawImageString( xinfo.display, xinfo.window, xinfo.gc[1], xinfo.current_w/2, xinfo.current_h/2, text_pause.c_str(), text_pause.length() ); std::string text_resume("The window is too small"); XDrawImageString( xinfo.display, xinfo.window, xinfo.gc[1], xinfo.current_w/2-30, xinfo.current_h/2 + 20, text_resume.c_str(), text_resume.length() ); text_resume="Please resize to continue"; XDrawImageString( xinfo.display, xinfo.window, xinfo.gc[1], xinfo.current_w/2-35, xinfo.current_h/2 + 40, text_resume.c_str(), text_resume.length() ); } break; } case KeyPress: { KeySym key; char text[BufferSize]; int i = XLookupString((XKeyEvent *)&event2,text,BufferSize,&key,NULL); if ( i == 1) { if (text[0] == 'q') { error("Terminating normally."); } } break; } } // switch }// if xpending } // while } // end handleTooSmall
int main(int argc, char **argv) { opt_data opts; optproc(argc, argv, &opts); if(audio_init(&opts) < 0) exit(1); int x = 0, y = 0, w, h; if(opts.w < 0 && opts.h < 0) opts.w = opts.h = 512; else if(opts.w < 0) opts.w = opts.h; else if(opts.h < 0) opts.h = opts.w; w = opts.w; h = opts.h; XEvent event; dpy = XOpenDisplay( NULL ); if(dpy == NULL) { printf("Error: couldn't open display %s\n", getenv("DISPLAY")); exit(EXIT_FAILURE); } int glx_major, glx_minor; if(!glXQueryVersion(dpy, &glx_major, &glx_minor)) { printf("GLX extension missing!\n"); XCloseDisplay(dpy); exit(EXIT_FAILURE); } printf("GLX version %i.%i\n", glx_major, glx_minor); int glxErrBase, glxEventBase; glXQueryExtension(dpy, &glxErrBase, &glxEventBase); printf("GLX: errorBase = %i, eventBase = %i\n", glxErrBase, glxEventBase); Window xwin, root; int numReturned; GLXFBConfig *fbConfigs; fbConfigs = glXChooseFBConfig( dpy, DefaultScreen(dpy), fbattrib, &numReturned ); if(fbConfigs == NULL) { //TODO: handle this? printf("No suitable fbconfigs!\n"); exit(EXIT_FAILURE); } XVisualInfo *vinfo = glXGetVisualFromFBConfig( dpy, fbConfigs[0] ); root = DefaultRootWindow(dpy); /* window attributes */ XSetWindowAttributes attrs; attrs.background_pixel = 0; attrs.border_pixel = 0; attrs.colormap = XCreateColormap(dpy, root, vinfo->visual, AllocNone); //attrs.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask; attrs.event_mask = StructureNotifyMask | KeyPressMask; unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; xwin = XCreateWindow(dpy, root, x, y, w, h, 0, vinfo->depth, InputOutput, vinfo->visual, mask, &attrs); XFree(vinfo); // Set hints and properties: { XSizeHints sizehints; sizehints.x = x; sizehints.y = y; sizehints.width = w; sizehints.height = h; sizehints.flags = USSize | USPosition; XSetNormalHints(dpy, xwin, &sizehints); XSetStandardProperties(dpy, xwin, "Julia-vis", "Julia-vis", None, (char **)NULL, 0, &sizehints); } /* Create a GLX context for OpenGL rendering */ GLXContext context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, NULL, True ); #if 0 GLXContext context = 0; glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" ); if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_ARB_create_context") || !glXCreateContextAttribsARB) { printf("glXCreateContextAttribsARB() not found ... using old-style GLX context\n"); context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, 0, True); } else { const int context_attribs[] = { GLX_RENDER_TYPE, GLX_RGBA_TYPE, GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 1, None }; context = glXCreateContextAttribsARB(dpy, fbConfigs[0], NULL, True, context_attribs); } if(context == NULL) { printf("Failed to create context!\n"); return EXIT_FAILURE; } #endif glxWin = glXCreateWindow(dpy, fbConfigs[0], xwin, NULL ); XMapWindow(dpy, xwin); XIfEvent(dpy, &event, WaitForNotify, (XPointer) xwin); glXMakeContextCurrent(dpy, glxWin, glxWin, context); init_gl(&opts, w, h); if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_MESA_swap_control")) { PFNGLXSWAPINTERVALMESAPROC swap_interval = glXGetProcAddressARB("glXSwapIntervalMESA"); swap_interval(1); opts.draw_rate = 600; } if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_INTEL_swap_event")) { glXSelectEvent(dpy, glxWin, GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK); have_intel_swap_event = GL_TRUE; } int debug_maxsrc = 0, debug_pal = 0, show_mandel = 0, show_fps_hist = 0; if(have_intel_swap_event) render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist); while(1) { if(!have_intel_swap_event) render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist); //int clear_key = 1; while (XPending(dpy) > 0) { XNextEvent(dpy, &event); if(event.type == glxEventBase + GLX_BufferSwapComplete) { render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist); continue; } switch (event.type) { case Expose: /* we'll redraw below */ break; /*case ConfigureNotify: window_w = event.xconfigure.width; window_h = event.xconfigure.height; if (surface_type == EGL_WINDOW_BIT) reshape(window_w, window_h); break;*/ case KeyPress: { //clear_key = 0; //char buffer[10]; int code; code = XLookupKeysym(&event.xkey, 0); if (code == XK_F1) { debug_maxsrc = !debug_maxsrc; } else if (code == XK_F2) { debug_pal = !debug_pal; } else if (code == XK_F3) { show_mandel = !show_mandel; } else if (code == XK_F4) { show_fps_hist = !show_fps_hist; } else { code = XLookupKeysym(&event.xkey, 1); if(code == XK_Escape) { goto glx_main_loop_quit; } } } break; default: //printf("Bar %i!\n", event.type); break; } } } glx_main_loop_quit: audio_shutdown(); XDestroyWindow(dpy, xwin); XCloseDisplay(dpy); return 0; }
static void HandleEvents(void) { int b; int key; XEvent event; qboolean dowarp = qfalse; char *p; int dx, dy; int t = 0; // default to 0 in case we don't set if (!dpy) return; while (XPending(dpy)) { XNextEvent(dpy, &event); switch (event.type) { case KeyPress: t = Sys_XTimeToSysTime(event.xkey.time); p = XLateKey(&event.xkey, &key); if (key) { Sys_QueEvent( t, SE_KEY, key, qtrue, 0, NULL ); } if (p) { while (*p) { Sys_QueEvent( t, SE_CHAR, *p++, 0, 0, NULL ); } } break; case KeyRelease: t = Sys_XTimeToSysTime(event.xkey.time); // bk001206 - handle key repeat w/o XAutRepatOn/Off // also: not done if console/menu is active. // From Ryan's Fakk2. // see game/q_shared.h, KEYCATCH_* . 0 == in 3d game. if (cls.keyCatchers == 0) { // FIXME: KEYCATCH_NONE if (repeated_press(&event) == qtrue) continue; } // if XLateKey(&event.xkey, &key); Sys_QueEvent( t, SE_KEY, key, qfalse, 0, NULL ); break; case MotionNotify: t = Sys_XTimeToSysTime(event.xkey.time); if (mouse_active) { #ifdef HAVE_XF86DGA if (in_dgamouse->value) { mx += event.xmotion.x_root; my += event.xmotion.y_root; if (t - mouseResetTime > MOUSE_RESET_DELAY ) { Sys_QueEvent( t, SE_MOUSE, mx, my, 0, NULL ); } mx = my = 0; } else #endif /* HAVE_XF86DGA */ { // If it's a center motion, we've just returned from our warp if (event.xmotion.x == glConfig.vidWidth/2 && event.xmotion.y == glConfig.vidHeight/2) { mwx = glConfig.vidWidth/2; mwy = glConfig.vidHeight/2; if (t - mouseResetTime > MOUSE_RESET_DELAY ) { Sys_QueEvent( t, SE_MOUSE, mx, my, 0, NULL ); } mx = my = 0; break; } dx = ((int)event.xmotion.x - mwx); dy = ((int)event.xmotion.y - mwy); mx += dx; my += dy; mwx = event.xmotion.x; mwy = event.xmotion.y; dowarp = qtrue; } } break; case ButtonPress: t = Sys_XTimeToSysTime(event.xkey.time); if (event.xbutton.button == 4) { Sys_QueEvent( t, SE_KEY, K_MWHEELUP, qtrue, 0, NULL ); } else if (event.xbutton.button == 5) { Sys_QueEvent( t, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL ); } else { // NOTE TTimo there seems to be a weird mapping for K_MOUSE1 K_MOUSE2 K_MOUSE3 .. b=-1; if (event.xbutton.button == 1) { b = 0; // K_MOUSE1 } else if (event.xbutton.button == 2) { b = 2; // K_MOUSE3 } else if (event.xbutton.button == 3) { b = 1; // K_MOUSE2 } else if (event.xbutton.button == 6) { b = 3; // K_MOUSE4 } else if (event.xbutton.button == 7) { b = 4; // K_MOUSE5 }; Sys_QueEvent( t, SE_KEY, K_MOUSE1 + b, qtrue, 0, NULL ); } break; case ButtonRelease: t = Sys_XTimeToSysTime(event.xkey.time); if (event.xbutton.button == 4) { Sys_QueEvent( t, SE_KEY, K_MWHEELUP, qfalse, 0, NULL ); } else if (event.xbutton.button == 5) { Sys_QueEvent( t, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL ); } else { b=-1; if (event.xbutton.button == 1) { b = 0; } else if (event.xbutton.button == 2) { b = 2; } else if (event.xbutton.button == 3) { b = 1; } else if (event.xbutton.button == 6) { b = 3; // K_MOUSE4 } else if (event.xbutton.button == 7) { b = 4; // K_MOUSE5 }; Sys_QueEvent( t, SE_KEY, K_MOUSE1 + b, qfalse, 0, NULL ); } break; case CreateNotify : win_x = event.xcreatewindow.x; win_y = event.xcreatewindow.y; break; case ConfigureNotify : win_x = event.xconfigure.x; win_y = event.xconfigure.y; break; } } if (dowarp) { XWarpPointer(dpy,None,win,0,0,0,0, (glConfig.vidWidth/2),(glConfig.vidHeight/2)); } }
// // I_GetClipboardText // // by Denis Lukianov - 20 Mar 2006 // Cross-platform clipboard functionality // std::string I_GetClipboardText (void) { #ifdef X11 std::string ret; Display *dis = XOpenDisplay(NULL); int screen = DefaultScreen(dis); if(!dis) { Printf(PRINT_HIGH, "I_GetClipboardText: XOpenDisplay failed"); return ""; } XLockDisplay(dis); Window WindowEvents = XCreateSimpleWindow(dis, RootWindow(dis, screen), 0, 0, 1, 1, 0, BlackPixel(dis, screen), BlackPixel(dis, screen)); if(XGetSelectionOwner(dis, XA_PRIMARY) != None) { if(!XConvertSelection(dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, WindowEvents, CurrentTime)) { XDestroyWindow(dis, WindowEvents); XUnlockDisplay(dis); XCloseDisplay(dis); Printf(PRINT_HIGH, "I_GetClipboardText: XConvertSelection failed"); return ""; } XFlush (dis); // Wait for the reply for(;;) { XEvent e; XNextEvent(dis, &e); if(e.type == SelectionNotify) break; } Atom type; int format, result; u_long len, bytes_left, temp; u_char *data; result = XGetWindowProperty(dis, WindowEvents, XA_PRIMARY, 0, 0, False, AnyPropertyType, &type, &format, &len, &bytes_left, &data); if(result != Success) { XDestroyWindow(dis, WindowEvents); XUnlockDisplay(dis); XCloseDisplay(dis); Printf(PRINT_HIGH, "I_GetClipboardText: XGetWindowProperty failed(1)"); return ""; } if(!bytes_left) { XDestroyWindow(dis, WindowEvents); Printf(PRINT_HIGH, "I_GetClipboardText: Len was: %d", len); XUnlockDisplay(dis); XCloseDisplay(dis); return ""; } result = XGetWindowProperty(dis, WindowEvents, XA_PRIMARY, 0, bytes_left, False, AnyPropertyType, &type, &format, &len, &temp, &data); if(result != Success) { XDestroyWindow(dis, WindowEvents); XUnlockDisplay(dis); XCloseDisplay(dis); Printf(PRINT_HIGH, "I_GetClipboardText: XGetWindowProperty failed(2)"); return ""; } ret = std::string((const char *)data, len); XFree(data); } XDestroyWindow(dis, WindowEvents); XUnlockDisplay(dis); XCloseDisplay(dis); return ret; #endif #ifdef WIN32 std::string ret; if(!IsClipboardFormatAvailable(CF_TEXT)) return ""; if(!OpenClipboard(NULL)) return ""; HANDLE hClipboardData = GetClipboardData(CF_TEXT); if(!hClipboardData) { CloseClipboard(); return ""; } const char *cData = reinterpret_cast<const char *>(GlobalLock(hClipboardData)); u_int uiSize = static_cast<u_int>(GlobalSize(hClipboardData)); if(cData && uiSize) { for(size_t i = 0; i < uiSize; i++) { if(!cData[i]) { uiSize = i; break; } } ret = std::string(cData, uiSize); } GlobalUnlock(hClipboardData); CloseClipboard(); return ret; #endif #ifdef OSX ScrapRef scrap; Size size; int err = GetCurrentScrap(&scrap); if(err) { Printf(PRINT_HIGH, "GetCurrentScrap error: %d", err); return ""; } err = GetScrapFlavorSize(scrap, FOUR_CHAR_CODE('TEXT'), &size); if(err) { Printf(PRINT_HIGH, "GetScrapFlavorSize error: %d", err); return ""; } char *data = new char[size+1]; err = GetScrapFlavorData(scrap, FOUR_CHAR_CODE('TEXT'), &size, data); data[size] = 0; if(err) { Printf(PRINT_HIGH, "GetScrapFlavorData error: %d", err); delete[] data; } std::string ret(data); delete[] data; return ret; #endif return ""; }
void CL_DisplayWindow_OpenGL::keep_alive() { XEvent event, next_event; CL_Rect *rect; for (int i=XPending(disp); i>0; i--) { XNextEvent(disp, &event); switch(event.type) { //Resize or Move case ConfigureNotify: #ifdef DEBUG CL_Log::log("debug", "ConfigureNotify Event received"); #endif set_size(event.xconfigure.width,event.xconfigure.height); break; case ClientMessage: #ifdef DEBUG CL_Log::log("debug", "Received ClientMessage, sending close signal"); #endif sig_window_close(); break; case Expose: // Repaint notification // Could be more efficient if we checked ahead for other // repaint notifications #ifdef DEBUG CL_Log::log("debug", "Expose Event received"); #endif rect = new CL_Rect(event.xexpose.x, event.xexpose.y, event.xexpose.x + event.xexpose.width, event.xexpose.y + event.xexpose.height); sig_paint(*rect); delete rect; break; case FocusIn: #ifdef DEBUG CL_Log::log("debug", "Focus In"); #endif focus = true; sig_got_focus(); break; case FocusOut: #ifdef DEBUG CL_Log::log("debug", "Focus Out"); #endif focus = false; sig_lost_focus(); break; case KeyRelease: if( XEventsQueued( disp, QueuedAfterReading ) ) { XPeekEvent( disp, &next_event ); if( next_event.type == KeyPress && next_event.xkey.window == event.xkey.window && next_event.xkey.keycode == event.xkey.keycode && next_event.xkey.time == event.xkey.time ) { // Do not report anything for this event break; } } case KeyPress: case KeymapNotify: case ButtonPress: case ButtonRelease: case MotionNotify: sig_xevent(event); break; case PropertyNotify: #ifdef DEBUG // This looks to be mostly useless // I'm getting a lot of WM messages that aren't really useful. // --MSR, April 5, 2003 /* if(event.xproperty.state == PropertyNewValue) { CL_Log::log("debug", "%1 has a new value", XGetAtomName(disp, event.xproperty.atom)); } */ #endif break; #ifdef DEBUG case EnterNotify: case LeaveNotify: CL_Log::log("debug", "The mouse has left or entered the window"); break; // default: // CL_Log::log("debug", "Unhandled event type: %1", event.type); #endif default: sig_unknown_xevent(event); break; } } }
void glutMainLoop() { char buffer[10]; int r; // code; char pressed = 0; int i; XAllowEvents(dpy, AsyncBoth, CurrentTime); while (gRunning) { int op = 0; while (XPending(dpy) > 0) { XEvent event; XNextEvent(dpy, &event); switch (event.type) { case ClientMessage: if (event.xclient.data.l[0] == wmDeleteMessage) // quit! gRunning = 0; break; case Expose: op = 1; break; // Update event! Should do draw here. case ConfigureNotify: if (gReshape) gReshape(event.xconfigure.width, event.xconfigure.height); else { glViewport(0, 0, event.xconfigure.width, event.xconfigure.height); } animate = 1; break; case KeyPress: case KeyRelease: r = XLookupString(&event.xkey, buffer, sizeof(buffer), NULL, NULL); if (event.type == KeyPress) { if (gKey) gKey(buffer[0], 0, 0); gKeymap[(int)buffer[0]] = 1;} else { if (gKeyUp) gKeyUp(buffer[0], 0, 0); gKeymap[(int)buffer[0]] = 0;} break; case ButtonPress: gButtonPressed[event.xbutton.button] = 1; if (gMouseFunc != NULL) gMouseFunc(GLUT_LEFT_BUTTON, GLUT_DOWN, event.xbutton.x, event.xbutton.y); break; case ButtonRelease: gButtonPressed[event.xbutton.button] = 0; if (gMouseFunc != NULL) gMouseFunc(GLUT_LEFT_BUTTON, GLUT_UP, event.xbutton.x, event.xbutton.y); break; case MotionNotify: pressed = 0; for (i = 0; i < 5; i++) if (gButtonPressed[i]) pressed = 1; if (pressed && gMouseDragged) gMouseDragged(event.xbutton.x, event.xbutton.y); else if (gMouseMoved) gMouseMoved(event.xbutton.x, event.xbutton.y); break; default: break; } } if (animate) { animate = 0; if (gDisplay) gDisplay(); else printf("No display function!\n"); op = 0; } else if (gIdle) gIdle(); checktimers(); } glXMakeCurrent(dpy, None, NULL); glXDestroyContext(dpy, ctx); XDestroyWindow(dpy, win); XCloseDisplay(dpy); }
int main(int argc,char *argv[]) { int i; unsigned int borderwidth ; char *display_name = NULL; char *wname = "wmload"; XGCValues gcv; unsigned long gcm; XEvent Event; XTextProperty name; XClassHint classHint; Pixmap pixmask; Atom _XA_WM_DELETE_WINDOW = None; Geometry = ""; mywmhints.initial_state = NormalState; /* Parse command line options */ ProgName = argv[0]; for(i=1;i<argc;i++) { char *arg= argv[i]; if (arg[0] == '-') { switch(arg[1]) { case 'u': if(++i >=argc) usage(); sscanf(argv[i], "%d", &updatespeed); continue; case 'e': if(++i >=argc) usage(); strcpy(&Execute[0], argv[i]); strcat(&Execute[0], " &"); continue; case 's': ONLYSHAPE=1; continue; case 'p': if(++i >=argc) usage(); Geometry = argv[i]; continue; case 'i': mywmhints.initial_state = IconicState; continue; case 'w': mywmhints.initial_state = WithdrawnState; continue; case 'l': if(++i >=argc) usage(); LedColor = argv[i]; continue; case 'v': fprintf(stdout, "\nwmload version: %i.%i.%i\n", major_VER, minor_VER, patch_VER); if(argc == 2) exit(0); continue; default: usage(); } } else { fprintf(stderr, "\nInvalid argument: %s\n", arg); usage(); } } /* Open the display */ if (!(dpy = XOpenDisplay(display_name))) { fprintf(stderr,"wmload: can't open display %s\n", XDisplayName(display_name)); exit (1); } screen= DefaultScreen(dpy); Root = RootWindow(dpy, screen); d_depth = DefaultDepth(dpy, screen); x_fd = XConnectionNumber(dpy); _XA_WM_DELETE_WINDOW = XInternAtom (dpy, "WM_DELETE_WINDOW", False); /* Convert XPM Data to XImage */ GetXPM(); /* Create a window to hold the banner */ mysizehints.flags= USSize|USPosition; mysizehints.x = 0; mysizehints.y = 0; back_pix = GetColor("white"); fore_pix = GetColor("black"); XWMGeometry(dpy, screen, Geometry, NULL, (borderwidth =1), &mysizehints, &mysizehints.x,&mysizehints.y,&mysizehints.width,&mysizehints.height, &i); mysizehints.width = wmload.attributes.width; mysizehints.height= wmload.attributes.height; win = XCreateSimpleWindow(dpy,Root,mysizehints.x,mysizehints.y, mysizehints.width,mysizehints.height, borderwidth,fore_pix,back_pix); iconwin = XCreateSimpleWindow(dpy,win,mysizehints.x,mysizehints.y, mysizehints.width,mysizehints.height, borderwidth,fore_pix,back_pix); /* activate hints */ XSetWMNormalHints(dpy, win, &mysizehints); classHint.res_name = "wmload"; classHint.res_class = "WMLoad"; XSetClassHint(dpy, win, &classHint); XSelectInput(dpy,win,MW_EVENTS); XSelectInput(dpy,iconwin,MW_EVENTS); XSetCommand(dpy,win,argv,argc); if (XStringListToTextProperty(&wname, 1, &name) ==0) { fprintf(stderr, "wmload: can't allocate window name\n"); exit(-1); } XSetWMName(dpy, win, &name); /* Create a GC for drawing */ gcm = GCForeground|GCBackground|GCGraphicsExposures; gcv.foreground = fore_pix; gcv.background = back_pix; gcv.graphics_exposures = FALSE; NormalGC = XCreateGC(dpy, Root, gcm, &gcv); if (ONLYSHAPE) { /* try to make shaped window here */ pixmask = XCreateBitmapFromData(dpy, win, (char *)mask2_bits, mask2_width, mask2_height); XShapeCombineMask(dpy, win, ShapeBounding, 0, 0, pixmask, ShapeSet); XShapeCombineMask(dpy, iconwin, ShapeBounding, 0, 0, pixmask, ShapeSet); } mywmhints.icon_window = iconwin; mywmhints.icon_x = mysizehints.x; mywmhints.icon_y = mysizehints.y; mywmhints.window_group = win; mywmhints.flags = StateHint | IconWindowHint | IconPositionHint | WindowGroupHint; XSetWMHints(dpy, win, &mywmhints); XSetWMProtocols (dpy, win, &_XA_WM_DELETE_WINDOW, 1); XMapWindow(dpy,win); InitLoad(); InsertLoad(); RedrawWindow(&visible); while(1) { if (actualtime != time(0)) { actualtime = time(0); if(actualtime % updatespeed == 0) InsertLoad(); RedrawWindow(&visible); } /* read a packet */ while (XPending(dpy)) { XNextEvent(dpy,&Event); switch(Event.type) { case Expose: if(Event.xexpose.count == 0 ) RedrawWindow(&visible); break; case ButtonPress: ExecuteExternal(); break; case ClientMessage: if ((Event.xclient.format != 32) || ((Atom)Event.xclient.data.l[0] != _XA_WM_DELETE_WINDOW)) break; case DestroyNotify: XFreeGC(dpy, NormalGC); XDestroyWindow(dpy, iconwin); XDestroyWindow(dpy, win); XCloseDisplay(dpy); exit(0); break ; default: break; } } XFlush(dpy); #ifdef SYSV poll((struct poll *) 0, (size_t) 0, 50); #else { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 50000000L; /* 5/100 sec */ nanosleep(&ts, NULL); } #endif } return 0; }
main() { Display *dpy = XOpenDisplay(NULL); assert(dpy); Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 200, 100, 0, 0, 0); XSelectInput(dpy, w, StructureNotifyMask); XMapWindow(dpy, w); XSelectionRequestEvent *req; XEvent e, respond; for(;;) { XNextEvent(dpy, &e); if (e.type == MapNotify) break; } XFlush(dpy); // Atom a1, a2, a3, type; XSelectInput(dpy, w, StructureNotifyMask+ExposureMask); int format, result; unsigned long len, bytes_left, dummy; unsigned char *data; Window Sown; for (int ii = 0; ii < 50; ii++) { XSetSelectionOwner (dpy, XA_PRIMARY, w, CurrentTime); XFlush (dpy); XNextEvent (dpy, &e); if (e.type == SelectionRequest) // // Somebody wants our data // { req=&(e.xselectionrequest); printf ("Selection Request from Mr %i I am %i\n", (int)e.xselection.requestor, (int)w); printf ("prop:%i tar:%i sel:%i\n", req->property, req->target, req->selection); if (req->target == XA_STRING) { XChangeProperty (dpy, req->requestor, req->property, XA_STRING, 8, PropModeReplace, (unsigned char*) "It Works", 8); respond.xselection.property=req->property; } else // Strings only please { printf ("No String %i\n", (int)req->target); respond.xselection.property= None; } respond.xselection.type= SelectionNotify; respond.xselection.display= req->display; respond.xselection.requestor= req->requestor; respond.xselection.selection=req->selection; respond.xselection.target= req->target; respond.xselection.time = req->time; XSendEvent (dpy, req->requestor,0,0,&respond); XFlush (dpy); } } }
int main(int argc, char *argv[]) { Display *display = XOpenDisplay(NULL); printf("dddd\n"); if (display == NULL) { printf("Unable to open display\n"); return 1; } font_info = XLoadQueryFont(display, font_name); if (!font_info) { fprintf(stderr, "XLoadQueryFont: failed loading font '%s'\n", font_name); } XClassHint class_hint; XSizeHints *size_hints; size_hints = XAllocSizeHints(); XWMHints *wm_hints; wm_hints = XAllocWMHints(); int black_color = BlackPixel(display, DefaultScreen(display)); int white_color = WhitePixel(display, DefaultScreen(display)); Window window = XCreateSimpleWindow( display , DefaultRootWindow(display) , 0 , 0 , 400 , 300 , black_color , 35 , white_color ); XStoreName(display, window, WIN_TITLE); gc = XCreateGC(display, window, 0, &values); XSetFont(display, gc, font_info->fid); XSetForeground(display, gc, black_color); class_hint.res_name = WIN_NAME; class_hint.res_class = WIN_CLASS; XSetClassHint(display, window, &class_hint); size_hints->flags = PPosition | PSize | PMinSize; size_hints->min_width = 400; size_hints->min_height = 300; XSetWMNormalHints(display, window, size_hints); XSelectInput(display, window, ExposureMask); XMapWindow(display, window); XFlush(display); while(1) { static char *text = "Hello, Ryan"; static int txt_length; static int font_height; static int txt_x_pos,txt_y_pos; XNextEvent(display, &report); switch ( report.type ) { case Expose: if ( report.xexpose.count != 0 ) break; txt_length = XTextWidth(font_info, text, strlen(text)); XDrawString(display, window, gc, 100, 100, "hello ryan", strlen("hello ryan")); break; } } return 0; }