bool wxApp::Initialize(int& argC, wxChar **argV) { #if defined(__WXDEBUG__) && !wxUSE_NANOX // install the X error handler gs_pfnXErrorHandler = XSetErrorHandler( wxXErrorHandler ); #endif // __WXDEBUG__ wxString displayName; bool syncDisplay = false; int argCOrig = argC; for ( int i = 0; i < argCOrig; i++ ) { if (wxStrcmp( argV[i], _T("-display") ) == 0) { if (i < (argCOrig - 1)) { argV[i++] = NULL; displayName = argV[i]; argV[i] = NULL; argC -= 2; } } else if (wxStrcmp( argV[i], _T("-geometry") ) == 0) { if (i < (argCOrig - 1)) { argV[i++] = NULL; int w, h; if (wxSscanf(argV[i], _T("%dx%d"), &w, &h) != 2) { wxLogError( _("Invalid geometry specification '%s'"), wxString(argV[i]).c_str() ); } else { g_initialSize = wxSize(w, h); } argV[i] = NULL; argC -= 2; } } else if (wxStrcmp( argV[i], _T("-sync") ) == 0) { syncDisplay = true; argV[i] = NULL; argC--; } else if (wxStrcmp( argV[i], _T("-iconic") ) == 0) { g_showIconic = true; argV[i] = NULL; argC--; } } if ( argC != argCOrig ) { // remove the arguments we consumed for ( int i = 0; i < argC; i++ ) { while ( !argV[i] ) { memmove(argV + i, argV + i + 1, (argCOrig - i)*sizeof(wxChar *)); } } } // open and set up the X11 display if ( !wxSetDisplay(displayName) ) { wxLogError(_("wxWidgets could not open display. Exiting.")); return false; } Display *dpy = wxGlobalDisplay(); if (syncDisplay) XSynchronize(dpy, True); XSelectInput(dpy, XDefaultRootWindow(dpy), PropertyChangeMask); wxSetDetectableAutoRepeat( true ); if ( !wxAppBase::Initialize(argC, argV) ) return false; #if wxUSE_UNICODE // Glib's type system required by Pango g_type_init(); #endif #if wxUSE_INTL wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding()); #endif wxWidgetHashTable = new wxWindowHash; wxClientWidgetHashTable = new wxWindowHash; return true; }
void * winClipboardProc(void *pvNotUsed) { Atom atomClipboard, atomClipboardManager; int iReturn; HWND hwnd = NULL; int iConnectionNumber = 0; #ifdef HAS_DEVWINDOWS int fdMessageQueue = 0; #else struct timeval tvTimeout; #endif fd_set fdsRead; int iMaxDescriptor; Display *pDisplay = NULL; Window iWindow = None; int iRetries; Bool fUseUnicode; char szDisplay[512]; int iSelectError; pthread_cleanup_push(&winClipboardThreadExit, NULL); winDebug ("winClipboardProc - Hello\n"); /* Do we use Unicode clipboard? */ fUseUnicode = g_fUnicodeClipboard; /* Save the Unicode support flag in a global */ g_fUseUnicode = fUseUnicode; /* Create Windows messaging window */ hwnd = winClipboardCreateMessagingWindow (); /* Save copy of HWND in screen privates */ g_hwndClipboard = hwnd; /* Set error handler */ XSetErrorHandler(winClipboardErrorHandler); g_winClipboardProcThread = pthread_self(); g_winClipboardOldIOErrorHandler = XSetIOErrorHandler(winClipboardIOErrorHandler); /* Set jump point for Error exits */ iReturn = setjmp(g_jmpEntry); /* Check if we should continue operations */ if (iReturn != WIN_JMP_ERROR_IO && iReturn != WIN_JMP_OKAY) { /* setjmp returned an unknown value, exit */ ErrorF("winClipboardProc - setjmp returned: %d exiting\n", iReturn); goto thread_errorexit; } else if (iReturn == WIN_JMP_ERROR_IO) { /* TODO: Cleanup the Win32 window and free any allocated memory */ ErrorF("winClipboardProc - setjmp returned for IO Error Handler.\n"); } /* Use our generated cookie for authentication */ winSetAuthorization(); /* Initialize retry count */ iRetries = 0; /* Setup the display connection string x */ /* * NOTE: Always connect to screen 0 since we require that screen * numbers start at 0 and increase without gaps. We only need * to connect to one screen on the display to get events * for all screens on the display. That is why there is only * one clipboard client thread. */ winGetDisplayName(szDisplay,0); /* Print the display connection string */ winDebug ("winClipboardProc - DISPLAY=%s\n", szDisplay); /* Open the X display */ do { pDisplay = XOpenDisplay(szDisplay); if (pDisplay == NULL) { ErrorF("winClipboardProc - Could not open display, " "try: %d, sleeping: %d\n", iRetries + 1, WIN_CONNECT_DELAY); ++iRetries; sleep(WIN_CONNECT_DELAY); continue; } else break; } while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES); /* Make sure that the display opened */ if (pDisplay == NULL) { ErrorF("winClipboardProc - Failed opening the display, giving up\n"); goto thread_errorexit; } /* Save the display in the screen privates */ g_pClipboardDisplay = pDisplay; winDebug ("winClipboardProc - XOpenDisplay () returned and " "successfully opened the display.\n"); /* Get our connection number */ iConnectionNumber = ConnectionNumber(pDisplay); winDebug("Clipboard is using socket %d\n",iConnectionNumber); #ifdef HAS_DEVWINDOWS /* Open a file descriptor for the windows message queue */ fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, _O_RDONLY); if (fdMessageQueue == -1) { ErrorF("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME); goto thread_errorexit; } /* Find max of our file descriptors */ iMaxDescriptor = max(fdMessageQueue, iConnectionNumber) + 1; #else iMaxDescriptor = iConnectionNumber + 1; #endif /* Create atoms */ atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False); atomClipboardManager = XInternAtom(pDisplay, "CLIPBOARD_MANAGER", False); XInternAtom (pDisplay, WIN_LOCAL_PROPERTY, False); XInternAtom (pDisplay, "UTF8_STRING", False); XInternAtom (pDisplay, "COMPOUND_TEXT", False); XInternAtom (pDisplay, "TARGETS", False); /* Create a messaging window */ iWindow = XCreateSimpleWindow(pDisplay, DefaultRootWindow(pDisplay), 1, 1, 500, 500, 0, BlackPixel(pDisplay, 0), BlackPixel(pDisplay, 0)); if (iWindow == 0) { ErrorF("winClipboardProc - Could not create an X window.\n"); goto thread_errorexit; } XStoreName(pDisplay, iWindow, "xwinclip"); /* Select event types to watch */ if (XSelectInput(pDisplay, iWindow, PropertyChangeMask) == BadWindow) ErrorF("winClipboardProc - XSelectInput generated BadWindow " "on messaging window\n"); /* Save the window in the screen privates */ g_iClipboardWindow = iWindow; /* Assert ownership of selections if Win32 clipboard is owned */ if (NULL != GetClipboardOwner()) { if (g_fClipboardPrimary) { /* PRIMARY */ winDebug("winClipboardProc - asserted ownership.\n"); iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY, iWindow, CurrentTime); if (iReturn == BadAtom || iReturn == BadWindow /*|| XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow*/) { ErrorF ("winClipboardProc - Could not set PRIMARY owner\n"); goto thread_errorexit; } } /* CLIPBOARD */ iReturn = XSetSelectionOwner(pDisplay, atomClipboard, iWindow, CurrentTime); if (iReturn == BadAtom || iReturn == BadWindow /*|| XGetSelectionOwner (pDisplay, atomClipboard) != iWindow*/) { ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n"); goto thread_errorexit; } } /* Pre-flush X events */ /* * NOTE: Apparently you'll freeze if you don't do this, * because there may be events in local data structures * already. */ //winClipboardFlushXEvents(hwnd, iWindow, pDisplay, fUseUnicode); /* Pre-flush Windows messages */ winDebug ("Start flushing \n"); if (!winClipboardFlushWindowsMessageQueue(hwnd)) { ErrorF ("winClipboardFlushWindowsMessageQueue - returned 0\n"); goto thread_errorexit; } winDebug ("winClipboardProc - Started\n"); /* Signal that the clipboard client has started */ g_fClipboardStarted = TRUE; /* Loop for X events */ while (1) { /* Setup the file descriptor set */ /* * NOTE: You have to do this before every call to select * because select modifies the mask to indicate * which descriptors are ready. */ FD_ZERO(&fdsRead); FD_SET(iConnectionNumber, &fdsRead); #ifdef HAS_DEVWINDOWS FD_SET(fdMessageQueue, &fdsRead); #else tvTimeout.tv_sec = 0; tvTimeout.tv_usec = 100; #endif /* Wait for a Windows event or an X event */ iReturn = select(iMaxDescriptor, /* Highest fds number */ &fdsRead, /* Read mask */ NULL, /* No write mask */ NULL, /* No exception mask */ #ifdef HAS_DEVWINDOWS NULL /* No timeout */ #else &tvTimeout /* Set timeout */ #endif ); #ifndef HAS_WINSOCK iSelectError = errno; #else iSelectError = WSAGetLastError(); #endif if (iReturn < 0) { #ifndef HAS_WINSOCK if (iSelectError == EINTR) #else if (iSelectError == WSAEINTR) #endif continue; ErrorF("winClipboardProc - Call to select () failed: %d. " "Bailing.\n", iReturn); break; } /* Branch on which descriptor became active */ // if (FD_ISSET (iConnectionNumber, &fdsRead)) // { Also do it when no read since winClipboardFlushXEvents // is sending the output. /* Process X events */ /* Exit when we see that server is shutting down */ iReturn = winClipboardFlushXEvents(hwnd, iWindow, pDisplay, fUseUnicode, FALSE); if (WIN_XEVENTS_SHUTDOWN == iReturn) { ErrorF("winClipboardProc - winClipboardFlushXEvents " "trapped shutdown event, exiting main loop.\n"); break; } // } #ifdef HAS_DEVWINDOWS /* Check for Windows event ready */ if (FD_ISSET(fdMessageQueue, &fdsRead)) #else if (1) #endif { /* Process Windows messages */ if (!winClipboardFlushWindowsMessageQueue(hwnd)) { ErrorF("winClipboardProc - " "winClipboardFlushWindowsMessageQueue trapped " "WM_QUIT message, exiting main loop.\n"); break; } } } /* Close our X window */ if (pDisplay && iWindow) { iReturn = XDestroyWindow(pDisplay, iWindow); if (iReturn == BadWindow) ErrorF("winClipboardProc - XDestroyWindow returned BadWindow.\n"); #ifdef WINDBG else winDebug("winClipboardProc - XDestroyWindow succeeded.\n"); #endif } #ifdef HAS_DEVWINDOWS /* Close our Win32 message handle */ if (fdMessageQueue) close(fdMessageQueue); #endif #if 0 /* * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26. The * XSync and XSelectInput calls did not help. */ /* Discard any remaining events */ XSync(pDisplay, TRUE); /* Select event types to watch */ XSelectInput(pDisplay, DefaultRootWindow(pDisplay), None); /* Close our X display */ if (pDisplay) { XCloseDisplay(pDisplay); } #endif goto commonexit; thread_errorexit: if (g_pClipboardDisplay && g_iClipboardWindow) { iReturn = XDestroyWindow (g_pClipboardDisplay, g_iClipboardWindow); if (iReturn == BadWindow) ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n"); #ifdef WINDBG else winDebug ("winClipboardProc - XDestroyWindow succeeded.\n"); #endif } winDebug ("Clipboard thread died.\n"); commonexit: g_iClipboardWindow = None; g_pClipboardDisplay = NULL; g_fClipboardLaunched = FALSE; g_fClipboardStarted = FALSE; pthread_cleanup_pop(0); return NULL; }
/* * Vytvoøit a namapovat top-level okno, vytvoøit dal¹í zdroje (napø. GC) */ static void create_resources(int argc, char *argv[]) { XWMHints *wm_hints; /* Doporuèení pro window manager */ XSizeHints *size_hints; /* Doporuèená velikost okna */ XClassHint *class_hint; /* Jméno a tøída pro resource manager */ XTextProperty window_name, icon_name; /* Jména pro window manager */ XGCValues gc_values; /* Hodnoty pro nastavení GC */ char *str_window_name = (char *)"Hello Window"; /* Titulek okna */ char *str_icon_name = (char *)"Hello Icon"; /* Titulek ikony */ XColor exact_bg, screen_bg; /* Barva pozadí pro GC */ /* Vytvoøit top-level okno */ topwin_x = topwin_y = 0; /* Okno umístí window manager */ topwin_w = screen_width / 2; topwin_h = screen_height / 2; topwin_b = 0; topwin = XCreateSimpleWindow(display, root, topwin_x, topwin_y, topwin_w, topwin_h, topwin_b, black, white); debug("Created top-level window ID %#lx\n", topwin); /* Vytvoøit ikonu pro top-level okno */ topwin_icon = XCreateBitmapFromData(display, topwin, Xlib_icon_bits, Xlib_icon_width, Xlib_icon_height); debug("Created icon %#lx for top-level window\n", topwin_icon); /* Nastavit properties pro window manager */ if(!(size_hints = XAllocSizeHints()) || !(wm_hints = XAllocWMHints()) || !(class_hint = XAllocClassHint())) { fprintf(stderr, "Cannot allocate memory\n"); exit(1); } /* Poloha a velikost se bere ze skuteèných hodnot okna v oka¾iku * namapování. PPosition | PSize øíká, ¾e hodnoty nastavil program (a * window manager je mù¾e mìnit podle potøeby). USSize | USPosition by * znamenalo, ¾e hodnoty zadal u¾ivatel (napø. na pøíkazové øádce) a * window manager by je nemìl mìnit. */ size_hints->flags = PPosition | PSize | PMinSize; /* Window manager by nemìl okno nikdy zmen¹it na ménì ne¾ * min_width x min_height pixelù. */ size_hints->min_width = 200; size_hints->min_height = 100; wm_hints->initial_state = NormalState;/* Na zaèátku má být zobrazeno normální okno (ne ikona) */ wm_hints->input = True; /* Aplikace potøebuje vstup z klávesnice */ wm_hints->icon_pixmap = topwin_icon; wm_hints->flags = StateHint | InputHint | IconPixmapHint; /* Ulo¾ení jména okna a ikony */ if(!XStringListToTextProperty(&str_window_name, 1, &window_name) || !XStringListToTextProperty(&str_icon_name, 1, &icon_name)) { fprintf(stderr, "XStringListToTextProperty() for failed\n"); exit(1); } /* Jméno programu a tøídy pro hledání v resource databázi */ class_hint->res_name = progname; class_hint->res_class = (char *) "HelloWorld"; /* Nastavit v¹echny properties */ XSetWMProperties(display, topwin, &window_name, &icon_name, argv, argc, size_hints, wm_hints, class_hint); /* Vybrat události pro top-level okno */ XSelectInput(display, topwin, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask); /* Vytvoøit GC */ if(!XAllocNamedColor(display, cmap, "RGBi:0.5/0.5/0.5", &exact_bg, &screen_bg)) { fprintf(stderr, "Cannot allocate color\n"); exit(1); } gc_values.background = screen_bg.pixel; gc_values.foreground = black; my_gc = XCreateGC(display, topwin, GCBackground | GCForeground, &gc_values); XCopyGC(display, def_gc, GCFont, my_gc); /* default font */ /* Namapovat top-level okno */ XMapWindow(display, topwin); }
feh_menu *feh_menu_new(void) { feh_menu *m; XSetWindowAttributes attr; feh_menu_list *l; static Imlib_Image bg = NULL; static Imlib_Border border; m = (feh_menu *) emalloc(sizeof(feh_menu)); attr.backing_store = NotUseful; attr.override_redirect = True; attr.colormap = cm; attr.border_pixel = 0; attr.background_pixmap = None; attr.save_under = False; attr.do_not_propagate_mask = True; m->win = XCreateWindow( disp, root, 1, 1, 1, 1, 0, depth, InputOutput, vis, CWOverrideRedirect | CWSaveUnder | CWBackingStore | CWColormap | CWBackPixmap | CWBorderPixel | CWDontPropagate, &attr); XSelectInput(disp, m->win, ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | ButtonMotionMask); m->name = NULL; m->fehwin = NULL; m->pmap = 0; m->x = 0; m->y = 0; m->w = 0; m->h = 0; m->visible = 0; m->items = NULL; m->next = NULL; m->prev = NULL; m->updates = NULL; m->needs_redraw = 1; m->func_free = NULL; m->data = NULL; m->calc = 0; m->bg = NULL; l = emalloc(sizeof(feh_menu_list)); l->menu = m; l->next = menus; menus = l; if (!bg) { feh_load_image_char(&bg, opt.menu_bg); if (bg) { border.left = border.right = border.top = border.bottom = 4; imlib_context_set_image(bg); imlib_image_set_border(&border); } } if (bg) m->bg = gib_imlib_clone_image(bg); return(m); }
int main( int argc , char *argv[] ){ Display *display; Window window; Window pen_window[5]; Window color_window[5]; GC gc; char title[] = "Paint"; char icon_title[] = "Paint"; unsigned long background; unsigned long foreground; int button_size=40; char *colors[]={ "rgb:00/00/00", "rgb:ff/00/00", "rgb:00/ff/00", "rgb:00/00/ff", "rgb:ff/ff/00", }; int current_pen=2; unsigned long current_color=0; int x0,y0,x1,y1; int i; display = XOpenDisplay(NULL); background = WhitePixel(display,0); foreground = BlackPixel(display,0); window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0,500,400, 0,0,background); XSetStandardProperties(display,window,title,icon_title, None,argv,argc,NULL); /* GC を生成し、各種設定を行う */ gc = XCreateGC(display,window,0,0); XSetBackground(display,gc,background); XSetForeground(display,gc,current_color); XSetLineAttributes(display,gc,current_pen, LineSolid,CapRound,JoinMiter); /* メインウィンドウのイベントマスクを設定 */ XSelectInput(display,window, ExposureMask | ButtonPressMask | ButtonMotionMask); /* ペンサイズ・色選択ウィンドウを作成 */ for ( i=0 ; i<sizeof(pen_window)/sizeof(pen_window[0]) ; i++ ){ pen_window[i] = XCreateSimpleWindow(display,window, 10,(button_size+10)*i+30, button_size,button_size, 1,mycolor(display,"rgb:aa/aa/aa"), mycolor(display,"rgb:ee/ee/ee")); color_window[i] = XCreateSimpleWindow(display,window, 500-10-button_size,(button_size+10)*i+30, button_size,button_size, 1,mycolor(display,"rgb:aa/aa/aa"), mycolor(display,colors[i])); XSelectInput(display,pen_window[i], ButtonPressMask | EnterWindowMask | LeaveWindowMask ); XSelectInput(display,color_window[i], ButtonPressMask | EnterWindowMask | LeaveWindowMask ); } /* 全てのウィンドウをマップ */ XMapWindow(display,window); XMapSubwindows(display,window); while (1){ XEvent event; XNextEvent(display,&event); switch ( event.type ){ case Expose: /* 再描画 */ for ( i=0 ; i<sizeof(pen_window)/sizeof(pen_window[0]) ; i++ ){ int pen_size = i*3+2; /* ペンサイズウィンドウを再描画 */ XSetForeground(display,gc,foreground); XFillArc(display,pen_window[i],gc, button_size/2-pen_size/2,button_size/2-pen_size/2, pen_size,pen_size,0,360*64); } break; case EnterNotify: /* ウィンドウにポインタが入った */ XSetWindowBorder(display,event.xany.window, mycolor(display,"black")); break; case LeaveNotify: /* ウィンドウからポインタが出た */ XSetWindowBorder(display,event.xany.window, mycolor(display,"rgb:aa/aa/aa")); break; case MotionNotify: /* ボタンを押しながらマウスが動いた */ x1 = event.xbutton.x; y1 = event.xbutton.y; XDrawLine(display,window,gc,x0,y0,x1,y1); x0 = x1; y0 = y1; break; case ButtonPress: /* ボタンが押された */ /* キャンバス上で押された? */ if ( event.xany.window == window ){ x0 = event.xbutton.x; y0 = event.xbutton.y; XDrawLine(display,window,gc,x0,y0,x0,y0); break; } /* ペンサイズ/色選択ウィンドウ上で押された? */ for ( i=0 ; i<sizeof(pen_window)/sizeof(pen_window[0]) ; i++ ){ /* ペンサイズを変更 */ if ( event.xany.window == pen_window[i] ){ current_pen = i*3+2; XSetLineAttributes(display,gc,current_pen, LineSolid,CapRound,JoinMiter); break; } /* 色を変更 */ if ( event.xany.window == color_window[i] ){ current_color = mycolor(display,colors[i]); XSetForeground(display,gc,current_color); break; } } break; } } }
int XVWindow::init(Display* dp, Window rootWindow, int x, int y, int windowWidth, int windowHeight, int imageWidth, int imageHeight) { // local variables needed for creation of window and initialization of XV extension unsigned int i; unsigned int ver, rel, req, ev, err, adapt; XSetWindowAttributes xswattributes; XWindowAttributes xwattributes; XVisualInfo xvinfo; XvAdaptorInfo *xvainfo; unsigned int candidateXVPort=0; unsigned int busyPorts=0; _display=dp; _rootWindow=rootWindow; _state.origLayer=0; // initialize atoms WM_DELETE_WINDOW = XInternAtom(_display, "WM_DELETE_WINDOW", False); XA_WIN_PROTOCOLS = XInternAtom(_display, "_WIN_PROTOCOLS", False); XA_NET_SUPPORTED = XInternAtom(_display, "_NET_SUPPORTED", False); XA_NET_WM_STATE = XInternAtom(_display, "_NET_WM_STATE", False); XA_NET_WM_STATE_FULLSCREEN = XInternAtom(_display, "_NET_WM_STATE_FULLSCREEN", False); XA_NET_WM_STATE_ABOVE = XInternAtom(_display, "_NET_WM_STATE_ABOVE", False); XA_NET_WM_STATE_STAYS_ON_TOP = XInternAtom(_display, "_NET_WM_STATE_STAYS_ON_TOP", False); XA_NET_WM_STATE_BELOW = XInternAtom(_display, "_NET_WM_STATE_BELOW", False); XGetWindowAttributes(_display, _rootWindow, &xwattributes); XMatchVisualInfo(_display, DefaultScreen(_display), xwattributes.depth, TrueColor, &xvinfo); // define window properties and create the window xswattributes.colormap = XCreateColormap(_display, _rootWindow, xvinfo.visual, AllocNone); xswattributes.event_mask = StructureNotifyMask | ExposureMask; xswattributes.background_pixel = 0; xswattributes.border_pixel = 0; _XVWindow = XCreateWindow(_display, _rootWindow, x, y, windowWidth, windowHeight, 0, xvinfo.depth, InputOutput, xvinfo.visual, CWBackPixel|CWBorderPixel|CWColormap|CWEventMask, &xswattributes); // define inputs events XSelectInput(_display, _XVWindow, StructureNotifyMask | KeyPressMask | ButtonPressMask); setSizeHints(DEFAULT_X,DEFAULT_Y, imageWidth, imageHeight, windowWidth, windowHeight); // map the window XMapWindow(_display, _XVWindow); XSetWMProtocols(_display, _XVWindow, &WM_DELETE_WINDOW,1); // check if SHM XV window is possible if (Success != XvQueryExtension(_display, &ver, &rel, &req, &ev, &err)) { LOG_DEBUG("[x11] XQueryExtension failed"); return 0; } if (!XShmQueryExtension(_display)) { LOG_DEBUG("[x11] XQueryShmExtension failed"); return 0; } if (Success != XvQueryAdaptors(_display, _rootWindow, &adapt, &xvainfo)) { LOG_DEBUG("[x11] XQueryAdaptor failed"); XFree(xvainfo); return 0; } // look for a usable XV port for (i = 0; i < adapt && _XVPort == 0; i++) { if ((xvainfo[i].type & XvInputMask) && (xvainfo[i].type & XvImageMask)) { for (candidateXVPort = xvainfo[i].base_id; candidateXVPort < xvainfo[i].base_id + xvainfo[i].num_ports; ++candidateXVPort) if (!XvGrabPort(_display, candidateXVPort, CurrentTime)) { _XVPort = candidateXVPort; break; } else { LOG_DEBUG("[x11] Could not grab port: " + String::fromNumber(candidateXVPort)); ++busyPorts; } } } XvFreeAdaptorInfo(xvainfo); if (!_XVPort) { if (busyPorts) { LOG_WARN("[x11] Could not find free Xvideo port - maybe another process is already using it."); } else { LOG_WARN("[x11] It seems there is no Xvideo support for your video card available."); } return 0; } else { LOG_WARN("[x11] Use XVideo port: " + String::fromNumber(_XVPort)); } _gc = XCreateGC(_display, _XVWindow, 0, 0); // create the shared memory portion _XVImage = XvShmCreateImage(_display, _XVPort, GUID_I420_PLANAR, 0, imageWidth, imageHeight, &_XShmInfo); _XShmInfo.shmid = shmget(IPC_PRIVATE, _XVImage->data_size, IPC_CREAT | 0777); _XShmInfo.shmaddr = (char *) shmat(_XShmInfo.shmid, 0, 0); _XVImage->data = _XShmInfo.shmaddr; _XShmInfo.readOnly = False; if (!XShmAttach(_display, &_XShmInfo)) { LOG_WARN("[x11] XShmAttach failed"); return 0; } else { _isInitialized = true; } // detect the window manager type _wmType=getWMType(); return 1; }
void InitX( void ) { int i; char *pSkinPixelData; char *pSkinPixelCur; char *pBadgeSkinImageData; int status; unsigned long black,white; socklen_t len; struct sockaddr_in peer; char ipstr[256]; int port; // Get peername for stdin FD len = sizeof(peer); if ( getpeername( 0, &peer, &len) == -1 ) { printf( "Couldn't get peername!\n" ); exit(-1); } // deal with both IPv4 and IPv6: #if DEBUG_PRINT_HELPER printf( "Peer IP Address: %s\n", inet_ntoa(peer.sin_addr) ); printf( "Peer Port: %d\n", ntohs(peer.sin_port) ); #endif /* if (addr.ss_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *)&addr; port = ntohs(s->sin_port); inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr); } else { // AF_INET6 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr; port = ntohs(s->sin6_port); inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr); } */ char szDisplayHost[512]; sprintf( szDisplayHost, "%s:0", inet_ntoa(peer.sin_addr) ); g_badgeDisplay = XOpenDisplay( szDisplayHost ); if ( g_badgeDisplay == NULL ) { printf( "Couldn't open X11 display (%s)!\n", szDisplayHost ); exit(-1); } g_screen = DefaultScreen( g_badgeDisplay ); black = BlackPixel( g_badgeDisplay, g_screen ); white = WhitePixel( g_badgeDisplay, g_screen ); g_badgeWindow = XCreateSimpleWindow( g_badgeDisplay, RootWindow( g_badgeDisplay, g_screen ),0,0, g_badgeskinwidth, g_badgeskinheight, 1, black, black); XSetStandardProperties( g_badgeDisplay, g_badgeWindow, "Badger Service", "Badger",None,NULL,0,NULL); XSelectInput( g_badgeDisplay, g_badgeWindow, ExposureMask|ButtonPressMask|KeyPressMask|KeyReleaseMask ); g_GC = DefaultGC( g_badgeDisplay, g_screen );// XCreateGC( g_badgeDisplay, g_badgeWindow, 0, 0 ); /* XSetBackground( g_badgeDisplay, g_GC, white ); XSetForeground( g_badgeDisplay, g_GC, black); */ //XClearWindow( g_badgeDisplay, g_badgeWindow ); //XMapRaised( g_badgeDisplay, g_badgeWindow ); XMapWindow( g_badgeDisplay, g_badgeWindow ); // Get image data pSkinPixelData = malloc( g_badgeskinwidth*g_badgeskinheight * 4 ); i = (g_badgeskinwidth * g_badgeskinheight); pSkinPixelCur = pSkinPixelData; pBadgeSkinImageData = g_badgeskinimage; while ( i-- > 0 ) { char temp; HEADER_PIXEL( pBadgeSkinImageData, pSkinPixelCur ) temp = pSkinPixelCur[0]; pSkinPixelCur[0] = pSkinPixelCur[2]; pSkinPixelCur[2] = temp; pSkinPixelCur[3] = 0; pSkinPixelCur += 4; } g_pBadgeSkinImage = XCreateImage( g_badgeDisplay, XDefaultVisual( g_badgeDisplay, g_screen ), XDefaultDepth( g_badgeDisplay, g_screen ), ZPixmap, 0, pSkinPixelData, g_badgeskinwidth, g_badgeskinheight, 32, 0 ); if ( !g_pBadgeSkinImage ) { printf( "Failed to XCreateImage from pixel data!\n" ); exit(1); } }
void xtbin::xtbin_realize() { Arg args[2]; int n; Widget top_widget; Widget embedded; XSetWindowAttributes attr; unsigned long mask; attr.bit_gravity = NorthWestGravity; attr.event_mask = ButtonMotionMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | ExposureMask | KeyPressMask | KeyReleaseMask | LeaveWindowMask | PointerMotionMask | StructureNotifyMask | VisibilityChangeMask | FocusChangeMask; attr.colormap = xxlib_rgb_get_cmap(mXlibRgbHandle); attr.background_pixel = xxlib_rgb_xpixel_from_rgb(mXlibRgbHandle, 0xFFC0C0C0); attr.border_pixel = xxlib_rgb_xpixel_from_rgb(mXlibRgbHandle, 0xFF646464); #ifdef DEBUG printf("attr.background_pixel = %lx, attr.border_pixel = %lx, parent_window = %x\n", (long)attr.background_pixel, (long)attr.border_pixel, (int)parent_window); #endif /* DEBUG */ mask = CWBitGravity | CWEventMask | CWBorderPixel | CWBackPixel; if (attr.colormap) mask |= CWColormap; window = XCreateWindow(xtdisplay, parent_window, x, y, width, height, 0, xxlib_rgb_get_depth(mXlibRgbHandle), InputOutput, xxlib_rgb_get_visual(mXlibRgbHandle), mask, &attr); XSetWindowBackgroundPixmap(xtdisplay, window, None); XSelectInput(xtdisplay, window, ExposureMask); XMapWindow(xtdisplay, window); XFlush(xtdisplay); top_widget = XtAppCreateShell("drawingArea", "Wrapper", applicationShellWidgetClass, xtdisplay, NULL, 0); xtwidget = top_widget; n = 0; XtSetArg(args[n], XtNheight, height); n++; XtSetArg(args[n], XtNwidth, width); n++; XtSetValues(top_widget, args, n); embedded = XtVaCreateWidget("form", compositeWidgetClass, top_widget, NULL); n = 0; XtSetArg(args[n], XtNheight, height); n++; XtSetArg(args[n], XtNwidth, width); n++; XtSetValues(embedded, args, n); oldwindow = top_widget->core.window; top_widget->core.window = window; XtRegisterDrawable(xtdisplay, window, top_widget); XtRealizeWidget(embedded); XtRealizeWidget(top_widget); XtManageChild(embedded); /* Now fill out the xtbin info */ xtwindow = XtWindow(embedded); /* Suppress background refresh flashing */ XSetWindowBackgroundPixmap(xtdisplay, XtWindow(top_widget), None); XSetWindowBackgroundPixmap(xtdisplay, XtWindow(embedded), None); /* Listen to all Xt events */ XSelectInput(xtdisplay, XtWindow(top_widget), 0x0fffff); XSelectInput(xtdisplay, XtWindow(embedded), 0x0fffff); sync(); }
/* * Vstupní bod programu */ int main(int argc, char *argv[]) { XWMHints *wm_hints; /* Doporuèení pro window manager */ XClassHint *class_hints; /* Jméno tøídy pro resource management */ XTextProperty window_name, icon_name; /* Jména zobrazovaná window managerem */ XSizeHints *size_hints; /* Doporuèená velikost okna */ char *str_window_name = (char *) "Hello World"; char *str_icon_name = (char *) "Hello Icon"; XEvent event; /* Pro zpracování pøijatých událostí */ static Bool window_too_small = False; /* Inicializace */ progname = argv[0]; /* Pøipojení k X serveru */ if(!(display = XOpenDisplay(display_name))) { fprintf(stderr, "%s: cannot connect to X server %s\n", progname, XDisplayName(display_name)); exit(-1); } printf("Connected to X server %s\n", XDisplayName(display_name)); screen_num = DefaultScreen(display); printf("Default screen number is %d\n", screen_num); screen_ptr = DefaultScreenOfDisplay(display); display_width = DisplayWidth(display, screen_num); display_height = DisplayHeight(display, screen_num); printf("Display is %u x %u pixels\n", display_width, display_height); /* Vytvoøení okna */ x = y = 0; /* Okno umístí window manager */ width = display_width/2; height = display_height/2; win = XCreateSimpleWindow(display, RootWindow(display, screen_num), x, y, width, height, border_width, BlackPixel(display, screen_num), WhitePixel(display, screen_num)); printf("Created window with ID %#lx\n", win); /* Pixmapa ikony */ icon_pixmap = XCreateBitmapFromData(display, win, hello_icon_bits, hello_icon_width, hello_icon_height); printf("Created pixmap with ID %#lx\n", icon_pixmap); /* Nastavení properties pro window manager */ if(!(size_hints = XAllocSizeHints())) { fprintf(stderr, "Cannot allocate memory\n"); exit(-1); } if(!(wm_hints = XAllocWMHints())) { fprintf(stderr, "Cannot allocate memory\n"); exit(-1); } if(!(class_hints = XAllocClassHint())) { fprintf(stderr, "Cannot allocate memory\n"); exit(-1); } /* Poloha a velikost se bere ze skuteèných hodnot okna v oka¾iku * namapování. PPosition | PSize øíká, ¾e hodnoty nastavil program (a * window manager je mù¾e mìnit podle potøeby). USSize | USPosition by * znamenalo, ¾e hodnoty zadal u¾ivatel (napø. na pøíkazové øádce) a * window manager by je nemìl mìnit. */ size_hints->flags = PPosition | PSize | PMinSize; /* Window manager by nemìl okno nikdy zmen¹it na ménì ne¾ * min_width x min_height pixelù. */ size_hints->min_width = 300; size_hints->min_height = 200; /* Ulo¾ení jména okna a ikony */ if(!XStringListToTextProperty(&str_window_name, 1, &window_name)) { fprintf(stderr, "XStringListToTextProperty() for window_name" " failed\n"); exit(-1); } if(!XStringListToTextProperty(&str_icon_name, 1, &icon_name)) { fprintf(stderr, "XStringListToTextProperty() for icon_name" " failed\n"); exit(-1); } wm_hints->initial_state = NormalState;/* Na zaèátku má být zobrazeno normální okno (ne ikona) */ wm_hints->input = True; /* Aplikace potøebuje vstup z klávesnice */ wm_hints->icon_pixmap = icon_pixmap; wm_hints->flags = StateHint | InputHint | IconPixmapHint; /* Jméno programu a tøídy pro hledání v resource databázi */ class_hints->res_name = progname; class_hints->res_class = (char *) "HelloWorld"; XSetWMProperties(display, win, &window_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints); /* Výbìr typù událostí ke zpracování */ XSelectInput(display, win, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask); /* Nahrát font */ load_font(&font_info); /* Vytvoøit graphics context pro kreslení */ getGC(win, &gc, font_info); /* Namapovat okno na obrazovku (zobrazit) */ XMapWindow(display, win); /* Smyèka pro pøíjem a zpracování událostí */ while(1) { XNextEvent(display, &event); /* Èeká na pøíchod dal¹í události */ switch(event.type) { /* Zpracování události */ case Expose: printf("Drawing (serial=%lu send=%d count=%d x=%d y=%d " "w=%d h=%d)\n", event.xexpose.serial, event.xexpose.send_event, event.xexpose.count, event.xexpose.x, event.xexpose.y, event.xexpose.width, event.xexpose.height); if(event.xexpose.count == 0) { if(window_too_small) { /* Pøíli¹ zmen¹ené okno */ printf("Drawing small\n"); draw_too_small(win, gc, font_info); } else { /* Nakreslit obsah okna */ printf("Drawing normal (w=%d h=%d)\n", width, height); draw_text(win, gc, font_info, width, height); draw_graphics(win, gc, width, height); } } break; case ConfigureNotify: /* Kdybychom nevolali XClearWindow(), tak pøi rychlé zmìnì * velikosti okna my¹í postupnì window manager mìní velikost * okna, co¾ má za následek smazání pøedchozího obsahu okna a * vygenerování událostí ConfigureNotify a Expose. Jen¾e * jestli¾e program nestihne pøekreslit okno pøed dal¹í * zmìnou velikosti okna, tak X server jednou sma¾e okno, pak * program nìkolikrát pøeète ConfigureNotify a Expose a * nìkolikrát nakreslí obsah okna pro rùzné velikosti * zji¹tìné z ConfigureNotify. Takto se pøekryje nìkolik rùznì * velkých kreseb a obsah okna je ¹patný. */ if(width != event.xconfigure.width || height != event.xconfigure.height) XClearWindow(display, win); width = event.xconfigure.width; height = event.xconfigure.height; window_too_small = (int) width < size_hints->min_width+10 || (int) height < size_hints->min_height+10; printf("ConfigureNotify (serial=%lu send=%d w=%d h=%d)\n", event.xconfigure.serial, event.xconfigure.send_event, event.xconfigure.width, event.xconfigure.height); break; case ButtonPress: case KeyPress: /* Libovolná klávesa nebo tlaèítko my¹i ukonèí program */ /* Následující dvì volání nejsou nezbytná, XCloseDisplay() * uklidí v¹echny server resources alokované tímto klientem */ XUnloadFont(display, font_info->fid); XFreeGC(display, gc); /* Odpojení od X serveru */ XCloseDisplay(display); return 0; break; default: /* Sem se dostanou události vybrané maskou StructureNotifyMask * kromì ConfigureNotify. */ break; } } /* Sem se program nikdy nedostane */ return 0; }
bool wxTopLevelWindowX11::Create(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { // init our fields Init(); m_windowStyle = style; m_parent = parent; SetName(name); m_windowId = id == wxID_ANY ? NewControlId() : id; if (parent) parent->AddChild(this); wxTopLevelWindows.Append(this); Display *xdisplay = wxGlobalDisplay(); int xscreen = DefaultScreen( xdisplay ); Visual *xvisual = DefaultVisual( xdisplay, xscreen ); Window xparent = RootWindow( xdisplay, xscreen ); Colormap cm = DefaultColormap( xdisplay, xscreen ); if (GetExtraStyle() & wxTOPLEVEL_EX_DIALOG) m_backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE); else m_backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE); m_backgroundColour.CalcPixel( (WXColormap) cm ); m_hasBgCol = true; m_x = pos.x; if (m_x < -1) m_x = 10; m_y = pos.y; if (m_y < 0) m_y = 10; m_width = size.x; if (m_width < 0) m_width = 500; m_height = size.y; if (m_height < 0) m_height = 380; #if !wxUSE_NANOX XSetWindowAttributes xattributes; long xattributes_mask = CWBorderPixel | CWBackPixel; xattributes.background_pixel = m_backgroundColour.GetPixel(); xattributes.border_pixel = BlackPixel( xdisplay, xscreen ); if (HasFlag( wxNO_BORDER )) { xattributes_mask |= CWOverrideRedirect; xattributes.override_redirect = True; } if (!HasFlag( wxFULL_REPAINT_ON_RESIZE )) { xattributes_mask |= CWBitGravity; xattributes.bit_gravity = NorthWestGravity; } xattributes_mask |= CWEventMask; xattributes.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask | PropertyChangeMask; Window xwindow = XCreateWindow( xdisplay, xparent, m_x, m_y, m_width, m_height, 0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes ); #else long backColor, foreColor; backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue()); foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue()); Window xwindow = XCreateWindowWithColor( xdisplay, xparent, m_x, m_y, m_width, m_height, 0, 0, InputOutput, xvisual, backColor, foreColor); #endif m_mainWindow = (WXWindow) xwindow; m_clientWindow = (WXWindow) xwindow; wxAddWindowToTable( xwindow, (wxWindow*) this ); #if wxUSE_NANOX XSelectInput( xdisplay, xwindow, GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask | PropertyChangeMask ); #endif // Set background to None which will prevent X11 from clearing the // background completely. XSetWindowBackgroundPixmap( xdisplay, xwindow, None ); #if !wxUSE_NANOX if (HasFlag( wxSTAY_ON_TOP )) { Window xroot = RootWindow( xdisplay, xscreen ); XSetTransientForHint( xdisplay, xwindow, xroot ); } else { if (GetExtraStyle() & wxTOPLEVEL_EX_DIALOG) { if (GetParent() && GetParent()->X11GetMainWindow()) { Window xparentwindow = (Window) GetParent()->X11GetMainWindow(); XSetTransientForHint( xdisplay, xwindow, xparentwindow ); } } } XSizeHints size_hints; size_hints.flags = PSize | PPosition | PWinGravity; size_hints.x = m_x; size_hints.y = m_y; size_hints.width = m_width; size_hints.height = m_height; size_hints.win_gravity = NorthWestGravity; XSetWMNormalHints( xdisplay, xwindow, &size_hints); XWMHints wm_hints; wm_hints.flags = InputHint | StateHint; if (GetParent()) { wm_hints.flags |= WindowGroupHint; wm_hints.window_group = (Window) GetParent()->X11GetMainWindow(); } wm_hints.input = True; wm_hints.initial_state = NormalState; XSetWMHints( xdisplay, xwindow, &wm_hints); Atom wm_protocols[2]; wm_protocols[0] = XInternAtom( xdisplay, "WM_DELETE_WINDOW", False ); wm_protocols[1] = XInternAtom( xdisplay, "WM_TAKE_FOCUS", False ); XSetWMProtocols( xdisplay, xwindow, wm_protocols, 2); #endif wxSetWMDecorations( xwindow, style); SetTitle(title); return true; }
/** * Request the video to avoid the conflicts **/ WId VideoWidget::request( struct vout_window_t *p_wnd, unsigned int *pi_width, unsigned int *pi_height, bool b_keep_size ) { if( stable ) { msg_Dbg( p_intf, "embedded video already in use" ); return 0; } assert( !p_window ); if( b_keep_size ) { *pi_width = size().width(); *pi_height = size().height(); } /* The owner of the video window needs a stable handle (WinId). Reparenting * in Qt4-X11 changes the WinId of the widget, so we need to create another * dummy widget that stays within the reparentable widget. */ stable = new QWidget(); QPalette plt = palette(); plt.setColor( QPalette::Window, Qt::black ); stable->setPalette( plt ); stable->setAutoFillBackground(true); /* Force the widget to be native so that it gets a winId() */ stable->setAttribute( Qt::WA_NativeWindow, true ); /* Indicates that the widget wants to draw directly onto the screen. Widgets with this attribute set do not participate in composition management */ /* This is currently disabled on X11 as it does not seem to improve * performance, but causes the video widget to be transparent... */ #if !defined (Q_WS_X11) && !defined (Q_WS_QPA) stable->setAttribute( Qt::WA_PaintOnScreen, true ); #endif layout->addWidget( stable ); #ifdef Q_WS_X11 /* HACK: Only one X11 client can subscribe to mouse button press events. * VLC currently handles those in the video display. * Force Qt4 to unsubscribe from mouse press and release events. */ Display *dpy = QX11Info::display(); Window w = stable->winId(); XWindowAttributes attr; XGetWindowAttributes( dpy, w, &attr ); attr.your_event_mask &= ~(ButtonPressMask|ButtonReleaseMask); attr.your_event_mask &= ~PointerMotionMask; XSelectInput( dpy, w, attr.your_event_mask ); # ifdef HAVE_XI int n; XIEventMask *xi_masks = XIGetSelectedEvents( dpy, w, &n ); if( xi_masks != NULL ) { for( int i = 0; i < n; i++ ) if( xi_masks[i].mask_len >= 1 ) { xi_masks[i].mask[0] &= ~XI_ButtonPressMask; xi_masks[i].mask[0] &= ~XI_ButtonReleaseMask; xi_masks[i].mask[0] &= ~XI_MotionMask; } XISelectEvents( dpy, w, xi_masks, n ); XFree( xi_masks ); } # endif #endif sync(); p_window = p_wnd; return stable->winId(); }
int main(int argc, char **argv) { XGCValues values; XEvent report; int x0=0, y0=0, width=300, height=200, border=3; char *fontname = "6x13"; XFontStruct *dsp_font; Window menu; char *str1 = " Print out the PostScript file? ", *str0 = "Generate a PostScript file (OUTPUT.ps)?"; int m_width, m_height, flag=yes; /* open display */ if ((dsply = XOpenDisplay(NULL)) == NULL) { printf("Can't open display NULL\n"); exit(-1); } scrn = DefaultScreen(dsply); /* access font */ Gdraws_load_font(&dsp_font, fontname); values.background = WhitePixel(dsply, scrn); values.foreground = BlackPixel(dsply, scrn); gc = XCreateGC(dsply, RootWindow(dsply, scrn), (GCForeground | GCBackground), &values); PSGlobalInit(); /* must initiate before using G/PS functions */ PSCreateContext(gc, "gc", psNormalWidth, psButtCap, psMiterJoin, psWhite, psBlack); XSetFont(dsply, gc, dsp_font->fid); gc1 = XCreateGC(dsply, RootWindow(dsply, scrn), (GCForeground | GCBackground), &values); PSCreateContext(gc1, "gc1", psNormalWidth, psButtCap, psMiterJoin, psWhite, psBlack); XSetFont(dsply, gc1, dsp_font->fid); if (!(viewport = (viewPoints *)malloc(sizeof(viewPoints)))) { fprintf(stderr,"Ran out of memory (malloc) trying to create a viewport.\n"); exit(-1); } viewport->titleWindow = XCreateSimpleWindow(dsply, RootWindow(dsply,scrn), x0, y0, width+6, height+32+height/4, border, BlackPixel(dsply, scrn), WhitePixel(dsply, scrn)); viewport->viewWindow = XCreateSimpleWindow(dsply, viewport->titleWindow, x0, y0+20, width, height, border, BlackPixel(dsply, scrn), WhitePixel(dsply, scrn)); strcpy(viewport->title, "what is a test title?"); m_width = width; m_height = height/4; menu = XCreateSimpleWindow(dsply, viewport->titleWindow, x0, y0+20+height+6, m_width, m_height, border, BlackPixel(dsply,scrn), WhitePixel(dsply,scrn)); XSelectInput(dsply, viewport->viewWindow, KeyPressMask|ButtonPressMask|ExposureMask); XSelectInput(dsply, viewport->titleWindow, KeyPressMask|ExposureMask); XSelectInput(dsply, menu, KeyPressMask|ButtonPressMask|ExposureMask); XMapWindow(dsply, viewport->viewWindow); XMapWindow(dsply, viewport->titleWindow); XFlush(dsply); while (yes) { XNextEvent(dsply, &report); switch (report.type) { case Expose: if (report.xexpose.window==viewport->titleWindow) { if (GDrawImageString(gc, viewport->titleWindow, 20, 15, viewport->title, strlen(viewport->title),X) == psError) printf("screen draw image string failed.\n"); if (Gdraws_data(X) == psError) printf("screen Gdraws_data failed.\n"); } if (report.xexpose.window==viewport->viewWindow) { if (Gdraws_data(X) == psError) printf("screen Gdraws_data failed.\n"); } else if (report.xexpose.window==menu) { if (flag) Gdraws_draw_menu(menu, str0, m_width, m_height); else Gdraws_draw_menu(menu, str1, m_width, m_height); } break; case ButtonPress: if (report.xbutton.window==viewport->viewWindow) { XMapWindow(dsply, menu); XFlush(dsply); } else if (report.xbutton.window==menu && flag) { XUnmapWindow(dsply, menu); if (Gdraws_pressed_yes(m_width, m_height, report.xbutton.x, report.xbutton.y)) { flag=no; XMapWindow(dsply, menu); PSInit(viewport->viewWindow, viewport->titleWindow); if (Gdraws_data(PS) != psError) PSCreateFile(3,viewport->viewWindow, viewport->titleWindow,viewport->title); else printf("PS Gdraws_data failed.\n"); } } else if (report.xbutton.window==menu && !flag) { XUnmapWindow(dsply, menu); if (Gdraws_pressed_yes(m_width, m_height, report.xbutton.x, report.xbutton.y)) system("print OUTPUT.ps"); flag = yes; } break; case KeyPress: if (report.xkey.window==viewport->viewWindow || report.xkey.window==viewport->titleWindow) { XFreeGC(dsply, gc); XFreeGC(dsply, gc1); XCloseDisplay(dsply); PSClose(); exit(1); } else if (report.xkey.window==menu) XUnmapWindow(dsply, menu); default: break; } } return 0; }
void init_display() { int surface_type_id, result, i, value, scrn, num_fbconfigs; GLXFBConfig *fbconfigs; XVisualInfo *visInfo; XSetWindowAttributes attributes; Window root; int attrib_pbuffer[6] = {GLX_PBUFFER_WIDTH, 0, GLX_PBUFFER_HEIGHT, 0, GLX_PRESERVED_CONTENTS, 0}; width = horizontal_size; height = vertical_size; if(chroma_format != CHROMA420) error("we only support 4:2:0 chroma formats\n"); display = XOpenDisplay(NULL); root = XDefaultRootWindow(display); scrn = XDefaultScreen(display); if(!GetPortId(display, &portNum, &surface_type_id)) error("couldn't find a suitable port\n"); #ifdef USE_DLOPEN if(!ResolveFunctions(DLFILENAME)) error("couldn't resolve necessary functions\n"); #endif result = XvMCCreateContext(display, portNum, surface_type_id, coded_picture_width, coded_picture_height, XVMC_DIRECT, &context); if(result != Success) error("couldn't create XvMCContext\n"); for(i = 0; i < numsurfaces; i++) { result = XvMCCreateSurface(display, &context, &surfaces[i]); if(result != Success) { if(i < 4) { XvMCDestroyContext(display, &context); error("couldn't create enough XvMCSurfaces\n"); } else { numsurfaces = i; printf("could only allocate %i surfaces\n", numsurfaces); } } surface_info[i].reference = 0; surface_info[i].sequence_number = 0; } slices = slices * mb_width; XvMCCreateBlocks(display, &context, slices * 6, &blocks); XvMCCreateMacroBlocks(display, &context, slices, ¯o_blocks); fbconfigs = glXChooseFBConfig(display, scrn, attr_fbconfig, &num_fbconfigs); gl_fbconfig = *fbconfigs; /* find the first one with no depth buffer */ for(i = 0; i < num_fbconfigs; i++) { glXGetFBConfigAttrib(display, fbconfigs[i], GLX_DEPTH_SIZE, &value); if(value == 0) { gl_fbconfig = fbconfigs[i]; break; } } PrintVisual(); visInfo = glXGetVisualFromFBConfig(display, gl_fbconfig); attrib_pbuffer[1] = width; attrib_pbuffer[3] = bob ? (height/2) : height; gl_pbuffer = glXCreatePbuffer(display, gl_fbconfig, attrib_pbuffer); gl_context = glXCreateNewContext(display, gl_fbconfig, GLX_RGBA_TYPE, NULL, 1); attributes.colormap = XCreateColormap(display, root, visInfo->visual, AllocNone); window = XCreateWindow(display, root, 0, 0, width, height, 0, visInfo->depth, InputOutput, visInfo->visual, CWColormap, &attributes); gl_window = glXCreateWindow(display, gl_fbconfig, window, NULL); XSelectInput(display, window, KeyPressMask | StructureNotifyMask | Button1MotionMask | ButtonPressMask); XMapWindow(display, window); glXMakeContextCurrent(display, gl_window, gl_pbuffer, gl_context); glDrawBuffer(GL_BACK); glReadBuffer(GL_FRONT_LEFT); tex_w = 1 << PowerOfTwo(width); tex_h = 1 << PowerOfTwo(bob ? (height/2) : height); printf("%i x %i texture\n", tex_w, tex_h); glClearColor (0.0, 0.0, 0.0, 0.0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glShadeModel(GL_FLAT); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, 1.0, -1.0, 1.0, 2, 18.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -8); #ifdef USE_NV_FENCE glGenFencesNV(1, &nvFence); glSetFenceNV(&nvFence, GL_ALL_COMPLETED_NV); #endif XSync(display, 0); uiclp = uiclip+512; for (i= -512; i<512; i++) uiclp[i] = (i<-128) ? 0 : ((i>127) ? 255 : i+128); iclp = iclip+512; for (i= -512; i<512; i++) iclp[i] = (i<-128) ? -128 : ((i>127) ? 127 : i); niclp = niclip+512; for (i= -512; i<512; i++) niclp[i] = (i<-256) ? -256 : ((i>255) ? 255 : i); }
int two_choice(char *choice1, char *choice2, char *string, char *key, int x, int y, Window w, char *title) { Window base, c1, c2, wm; XEvent ev; int not_done = 1; int value = 0; int l1 = strlen(choice1) * DCURX; int l2 = strlen(choice2) * DCURX; int lm = strlen(string) * DCURX; int tot = lm, xm, x1, x2; if (lm < (l1 + l2 + 4 * DCURX)) tot = (l1 + l2 + 4 * DCURX); tot = tot + 6 * DCURX; xm = (tot - lm) / 2; x1 = (tot - l1 - l2 - 4 * DCURX) / 2; x2 = x1 + l1 + 4 * DCURX; base = make_plain_window(w, x, y, tot, 5 * DCURY, 4); make_icon((char *)alert_bits, alert_width, alert_height, base); c1 = make_window(base, x1, 3 * DCURY, l1 + DCURX, DCURY + 4, 1); c2 = make_window(base, x2, 3 * DCURY, l2 + DCURX, DCURY + 4, 1); XSelectInput(display, c1, BUT_MASK); XSelectInput(display, c2, BUT_MASK); wm = make_window(base, xm, DCURY / 2, lm + 2, DCURY, 0); ping(); if (w == RootWindow(display, screen)) { if (title == NULL) { set_window_title(base, "!!!!"); } else { set_window_title(base, title); } } while (not_done) { XNextEvent(display, &ev); switch (ev.type) { case Expose: case MapNotify: do_expose(ev); expose_choice(choice1, choice2, string, c1, c2, wm, ev.xexpose.window); break; case ButtonPress: if (ev.xbutton.window == c1) { value = (int)key[0]; not_done = 0; } if (ev.xbutton.window == c2) { value = (int)key[1]; not_done = 0; } break; case KeyPress: value = get_key_press(&ev); not_done = 0; break; case EnterNotify: if (ev.xcrossing.window == c1 || ev.xcrossing.window == c2) XSetWindowBorderWidth(display, ev.xcrossing.window, 2); XFlush(display); break; case LeaveNotify: if (ev.xcrossing.window == c1 || ev.xcrossing.window == c2) XSetWindowBorderWidth(display, ev.xcrossing.window, 1); XFlush(display); break; } } waitasec(2 * ClickTime); XFlush(display); XSelectInput(display, c1, EV_MASK); XSelectInput(display, c2, EV_MASK); XFlush(display); XDestroySubwindows(display, base); XDestroyWindow(display, base); return (value); }
Rect get_window_frame_size() { #ifdef WIN32 RECT border_rect; border_rect.left = 200; border_rect.right = 200 + 200; border_rect.top = 200; border_rect.bottom = 200 + 200; AdjustWindowRectEx(&border_rect, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX, FALSE, 0); Rect border_size(border_rect.left - 200, border_rect.top - 200, border_rect.right - 400, border_rect.bottom - 400); #else Display *d; Window w; d=XOpenDisplay(NULL); if(d==NULL) { throw Exception("Cannot open display"); } int s=DefaultScreen(d); const int win_xpos = 128; const int win_ypos = 128; const int win_width = 128; const int win_height = 128; w=XCreateSimpleWindow(d, RootWindow(d, s), win_xpos, win_ypos, win_width, win_height, 0, BlackPixel(d, s), WhitePixel(d, s)); XSelectInput(d, w, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask | PropertyChangeMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | KeymapStateMask | FocusChangeMask); // setup size hints: XSizeHints size_hints; memset(&size_hints, 0, sizeof(XSizeHints)); size_hints.x = win_xpos; size_hints.y = win_ypos; size_hints.width = win_width; size_hints.height = win_height; size_hints.base_width = win_width; size_hints.base_height = win_height; size_hints.min_width = size_hints.width; size_hints.min_height = size_hints.height; size_hints.max_width = size_hints.width; size_hints.max_height = size_hints.height; size_hints.flags = PSize|PBaseSize; size_hints.flags |= PMinSize | PMaxSize | PPosition; // These flags are important XSetWMNormalHints(d, w, &size_hints); XMapWindow(d, w); // Wait for mapped XEvent event; do { XMaskEvent(d, StructureNotifyMask, &event); }while ( (event.type != MapNotify) || (event.xmap.event != w) ); int xpos; int ypos; unsigned int width; unsigned int height; Window *children_ptr; unsigned int num_child; Window temp_window; XWindowAttributes attr; XGetWindowAttributes(d, w, &attr); xpos = attr.x; ypos = attr.y; width = attr.width; height = attr.height; // Search all parent windows .... there MUST be an easier may Window current_window = w; while(true) { children_ptr = NULL; XQueryTree(d, current_window, &temp_window, ¤t_window, &children_ptr, &num_child); if (children_ptr) XFree(children_ptr); if (!current_window) break; XGetWindowAttributes(d, current_window, &attr); xpos += attr.x; ypos += attr.y; } XDestroyWindow(d, w); XCloseDisplay(d); xpos -= win_xpos; ypos -= win_ypos; Rect border_size = Rect(-xpos, -ypos, 0, 0); #endif return border_size; }
static void adjustwin (int bnum, void (*drawscreen) (void)) { /* The window button was pressed. Let the user click on the two * * diagonally opposed corners, and zoom in on this area. */ XEvent report; int corner, xold, yold, x[2], y[2]; corner = 0; xold = -1; yold = -1; /* Don't need to init yold, but stops compiler warning. */ while (corner<2) { XNextEvent (display, &report); switch (report.type) { case Expose: #ifdef VERBOSE printf("Got an expose event.\n"); printf("Count is: %d.\n",report.xexpose.count); printf("Window ID is: %d.\n",report.xexpose.window); #endif if (report.xexpose.count != 0) break; if (report.xexpose.window == menu) drawmenu(); else if (report.xexpose.window == toplevel) { drawscreen(); xold = -1; /* No rubber band on screen */ } else if (report.xexpose.window == textarea) draw_message(); break; case ConfigureNotify: top_width = report.xconfigure.width; top_height = report.xconfigure.height; update_transform(); #ifdef VERBOSE printf("Got a ConfigureNotify.\n"); printf("New width: %d New height: %d.\n",top_width,top_height); #endif break; case ButtonPress: #ifdef VERBOSE printf("Got a buttonpress.\n"); printf("Window ID is: %d.\n",report.xbutton.window); printf("Location (%d, %d).\n", report.xbutton.x, report.xbutton.y); #endif if (report.xbutton.window != toplevel) break; x[corner] = report.xbutton.x; y[corner] = report.xbutton.y; if (corner == 0) { XSelectInput (display, toplevel, ExposureMask | StructureNotifyMask | ButtonPressMask | PointerMotionMask); } else { update_win(x,y,drawscreen); } corner++; break; case MotionNotify: #ifdef VERBOSE printf("Got a MotionNotify Event.\n"); printf("x: %d y: %d\n",report.xmotion.x,report.xmotion.y); #endif if (xold >= 0) { /* xold set -ve before we draw first box */ XDrawRectangle(display,toplevel,gcxor,min(x[0],xold), min(y[0],yold),abs(x[0]-xold),abs(y[0]-yold)); } /* Don't allow user to window under menu region */ xold = min(report.xmotion.x,top_width-1-MWIDTH); yold = report.xmotion.y; XDrawRectangle(display,toplevel,gcxor,min(x[0],xold), min(y[0],yold),abs(x[0]-xold),abs(y[0]-yold)); break; } } XSelectInput (display, toplevel, ExposureMask | StructureNotifyMask | ButtonPressMask); }
ObPrompt* prompt_new(const gchar *msg, const gchar *title, const ObPromptAnswer *answers, gint n_answers, gint default_result, gint cancel_result, ObPromptCallback func, ObPromptCleanup cleanup, gpointer data) { ObPrompt *self; XSetWindowAttributes attrib; gint i; attrib.override_redirect = FALSE; self = g_slice_new0(ObPrompt); self->ref = 1; self->func = func; self->cleanup = cleanup; self->data = data; self->default_result = default_result; self->cancel_result = cancel_result; self->super.type = OB_WINDOW_CLASS_PROMPT; self->super.window = XCreateWindow(obt_display, obt_root(ob_screen), 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, CWOverrideRedirect, &attrib); self->ic = obt_keyboard_context_new(self->super.window, self->super.window); /* make it a dialog type window */ OBT_PROP_SET32(self->super.window, NET_WM_WINDOW_TYPE, ATOM, OBT_PROP_ATOM(NET_WM_WINDOW_TYPE_DIALOG)); /* set the window's title */ if (title) OBT_PROP_SETS(self->super.window, NET_WM_NAME, utf8, title); /* listen for key presses on the window */ self->event_mask = KeyPressMask; /* set up the text message widow */ self->msg.text = g_strdup(msg); self->msg.window = XCreateWindow(obt_display, self->super.window, 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, 0, NULL); XMapWindow(obt_display, self->msg.window); /* set up the buttons from the answers */ self->n_buttons = n_answers; if (!self->n_buttons) self->n_buttons = 1; self->button = g_new0(ObPromptElement, self->n_buttons); if (n_answers == 0) { g_assert(self->n_buttons == 1); /* should be set to this above.. */ self->button[0].text = g_strdup(_("OK")); } else { g_assert(self->n_buttons > 0); for (i = 0; i < self->n_buttons; ++i) { self->button[i].text = g_strdup(answers[i].text); self->button[i].result = answers[i].result; } } for (i = 0; i < self->n_buttons; ++i) { self->button[i].window = XCreateWindow(obt_display, self->super.window, 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, 0, NULL); XMapWindow(obt_display, self->button[i].window); window_add(&self->button[i].window, PROMPT_AS_WINDOW(self)); /* listen for button presses on the buttons */ XSelectInput(obt_display, self->button[i].window, ButtonPressMask | ButtonReleaseMask | ButtonMotionMask); } prompt_list = g_list_prepend(prompt_list, self); return self; }
static void build_menu (void) { /* Sets up all the menu buttons on the right hand side of the window. */ XSetWindowAttributes menu_attributes; unsigned long valuemask; int i, xcen, x1, y1, bwid, bheight, space; menu = XCreateSimpleWindow(display,toplevel, top_width-MWIDTH, 0, MWIDTH-4, display_height, 2, colors[BLACK], colors[LIGHTGREY]); menu_attributes.event_mask = ExposureMask; /* Ignore button presses on the menu background. */ menu_attributes.do_not_propagate_mask = ButtonPressMask; /* Keep menu on top right */ menu_attributes.win_gravity = NorthEastGravity; valuemask = CWWinGravity | CWEventMask | CWDontPropagate; XChangeWindowAttributes(display, menu, valuemask, &menu_attributes); XMapWindow (display, menu); /* Now do the arrow buttons */ bwid = 28; space = 3; y1 = 10; xcen = 51; x1 = xcen - bwid/2; mapbut (0, x1, y1, bwid, bwid); setpoly (0, bwid/2, bwid/2, bwid/3, -PI/2.); /* Up */ y1 += bwid + space; x1 = xcen - 3*bwid/2 - space; mapbut (1, x1, y1, bwid, bwid); setpoly (1, bwid/2, bwid/2, bwid/3, PI); /* Left */ x1 = xcen + bwid/2 + space; mapbut (2, x1, y1, bwid, bwid); setpoly (2, bwid/2, bwid/2, bwid/3, 0); /* Right */ y1 += bwid + space; x1 = xcen - bwid/2; mapbut (3, x1, y1, bwid, bwid); setpoly (3, bwid/2, bwid/2, bwid/3, +PI/2.); /* Down */ for (i=0;i<4;i++) { button[i].fcn = translate; button[i].width = bwid; button[i].height = bwid; } /* Rectangular buttons */ y1 += bwid + space + 6; space = 8; bwid = 90; bheight = 26; x1 = xcen - bwid/2; for (i=4;i<NBUTTONS;i++) { mapbut(i, x1, y1, bwid, bheight); y1 += bheight + space; button[i].istext = 1; button[i].ispoly = 0; button[i].width = bwid; button[i].height = bheight; } strcpy (button[4].text,"Zoom In"); strcpy (button[5].text,"Zoom Out"); strcpy (button[6].text,"Window"); strcpy (button[7].text,"Toggle Nets"); strcpy (button[8].text,"Toggle RR"); strcpy (button[9].text,"PostScript"); strcpy (button[10].text,"Proceed"); strcpy (button[11].text,"Exit"); button[4].fcn = zoom; button[5].fcn = zoom; button[6].fcn = adjustwin; button[7].fcn = toggle_nets; button[8].fcn = toggle_rr; button[9].fcn = postscript; button[10].fcn = proceed; button[11].fcn = quit; for (i=0;i<NBUTTONS;i++) { XSelectInput (display, button[i].win, ButtonPressMask); button[i].ispressed = 1; } }
void openXwindow(int argc, char *argv[], char *pixmap_bytes[], char *pixmask_bits, int pixmask_width, int pixmask_height) { unsigned int borderwidth = 1; XClassHint classHint; char *display_name = NULL; char *wname = argv[0]; XTextProperty name; XGCValues gcv; unsigned long gcm; int i, dummy = 0; for (i=1; argv[i]; i++) { if (!strcmp(argv[i], "-display")) display_name = argv[i+1]; } if (!(display = XOpenDisplay(display_name))) { fprintf(stderr, "%s: can't open display %s\n", wname, XDisplayName(display_name)); exit(1); } screen = DefaultScreen(display); Root = RootWindow(display, screen); d_depth = DefaultDepth(display, screen); x_fd = XConnectionNumber(display); /* Convert XPM to XImage */ GetXPM(&wmgen, pixmap_bytes); /* Create a window to hold the stuff */ mysizehints.flags = USSize | USPosition; mysizehints.x = 0; mysizehints.y = 0; back_pix = GetColor("white"); fore_pix = GetColor("black"); XWMGeometry(display, screen, Geometry, NULL, borderwidth, &mysizehints, &mysizehints.x, &mysizehints.y,&mysizehints.width,&mysizehints.height, &dummy); mysizehints.width = 64; mysizehints.height = 64; win = XCreateSimpleWindow(display, Root, mysizehints.x, mysizehints.y, mysizehints.width, mysizehints.height, borderwidth, fore_pix, back_pix); iconwin = XCreateSimpleWindow(display, win, mysizehints.x, mysizehints.y, mysizehints.width, mysizehints.height, borderwidth, fore_pix, back_pix); /* Activate hints */ XSetWMNormalHints(display, win, &mysizehints); classHint.res_name = wname; classHint.res_class = wname; XSetClassHint(display, win, &classHint); XSelectInput(display, win, ButtonPressMask | ExposureMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask); XSelectInput(display, iconwin, ButtonPressMask | ExposureMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask); if (XStringListToTextProperty(&wname, 1, &name) == 0) { fprintf(stderr, "%s: can't allocate window name\n", wname); exit(1); } XSetWMName(display, win, &name); /* Create GC for drawing */ gcm = GCForeground | GCBackground | GCGraphicsExposures; gcv.foreground = fore_pix; gcv.background = back_pix; gcv.graphics_exposures = 0; NormalGC = XCreateGC(display, Root, gcm, &gcv); /* ONLYSHAPE ON */ pixmask = XCreateBitmapFromData(display, win, pixmask_bits, pixmask_width, pixmask_height); XShapeCombineMask(display, win, ShapeBounding, 0, 0, pixmask, ShapeSet); XShapeCombineMask(display, iconwin, ShapeBounding, 0, 0, pixmask, ShapeSet); /* ONLYSHAPE OFF */ mywmhints.initial_state = WithdrawnState; 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(display, win, &mywmhints); XSetCommand(display, win, argv, argc); XMapWindow(display, win); }
void init_graphics (char *window_name) { /* Open the toplevel window, get the colors, 2 graphics * * contexts, load a font, and set up the toplevel window * * Calls build_menu to set up the menu. */ char *display_name = NULL; int x, y; /* window position */ unsigned int border_width = 2; /* ignored by OpenWindows */ XTextProperty windowName; /* X Windows' names for my colours. */ char *cnames[NUM_COLOR] = {"white", "black", "grey55", "grey75", "blue", "green", "yellow", "cyan", "red", "RGBi:0.0/0.5/0.0" }; XColor exact_def; Colormap cmap; int i; unsigned long valuemask = 0; /* ignore XGCvalues and use defaults */ XGCValues values; XEvent event; disp_type = SCREEN; /* Graphics go to screen, not ps */ for (i=0;i<=MAX_FONT_SIZE;i++) font_is_loaded[i] = 0; /* No fonts loaded yet. */ /* connect to X server */ /* connect to X server */ if ( (display=XOpenDisplay(display_name)) == NULL ) { fprintf( stderr, "Cannot connect to X server %s\n", XDisplayName(display_name)); exit( -1 ); } /* get screen size from display structure macro */ screen_num = DefaultScreen(display); display_width = DisplayWidth(display, screen_num); display_height = DisplayHeight(display, screen_num); x = y = 0; top_width = 2*display_width/3; top_height = 4*display_height/5; cmap = DefaultColormap(display, screen_num); private_cmap = None; for (i=0;i<NUM_COLOR;i++) { if (!XParseColor(display,cmap,cnames[i],&exact_def)) { fprintf(stderr, "Color name %s not in database", cnames[i]); exit(-1); } if (!XAllocColor(display, cmap, &exact_def)) { fprintf(stderr, "Couldn't allocate color %s.\n",cnames[i]); if (private_cmap == None) { fprintf(stderr, "Will try to allocate a private colourmap.\n"); fprintf(stderr, "Colours will only display correctly when your " "cursor is in the graphics window.\n" "Exit other colour applications and rerun this " "program if you don't like that.\n\n"); private_cmap = XCopyColormapAndFree (display, cmap); cmap = private_cmap; if (!XAllocColor (display, cmap, &exact_def)) { fprintf (stderr, "Couldn't allocate color %s as private.\n", cnames[i]); exit (1); } } else { fprintf (stderr, "Couldn't allocate color %s as private.\n", cnames[i]); exit (1); } } colors[i] = exact_def.pixel; } toplevel = XCreateSimpleWindow(display,RootWindow(display,screen_num), x, y, top_width, top_height, border_width, colors[BLACK], colors[WHITE]); if (private_cmap != None) XSetWindowColormap (display, toplevel, private_cmap); /* hints stuff deleted. */ XSelectInput (display, toplevel, ExposureMask | StructureNotifyMask | ButtonPressMask); /* Create default Graphics Contexts. valuemask = 0 -> use defaults. */ gc = XCreateGC(display, toplevel, valuemask, &values); gc_menus = XCreateGC(display, toplevel, valuemask, &values); /* Create XOR graphics context for Rubber Banding */ values.function = GXxor; values.foreground = colors[BLACK]; gcxor = XCreateGC(display, toplevel, (GCFunction | GCForeground), &values); /* specify font for menus. */ load_font(menu_font_size); font_is_loaded[menu_font_size] = 1; XSetFont(display, gc_menus, font_info[menu_font_size]->fid); /* Set drawing defaults for user-drawable area. Use whatever the * * initial values of the current stuff was set to. */ force_setfontsize(currentfontsize); force_setcolor (currentcolor); force_setlinestyle (currentlinestyle); force_setlinewidth (currentlinewidth); XStringListToTextProperty(&window_name, 1, &windowName); XSetWMName (display, toplevel, &windowName); /* XSetWMIconName (display, toplevel, &windowName); */ /* set line attributes */ /* XSetLineAttributes(display, gc, line_width, line_style, cap_style, join_style); */ /* set dashes */ /* XSetDashes(display, gc, dash_offset, dash_list, list_length); */ XMapWindow (display, toplevel); build_textarea(); build_menu(); /* The following is completely unnecessary if the user is using the * * interactive (event_loop) graphics. It waits for the first Expose * * event before returning so that I can tell the window manager has got * * the top-level window up and running. Thus the user can start drawing * * into this window immediately, and there's no danger of the window not * * being ready and output being lost. */ XPeekIfEvent (display, &event, test_if_exposed, NULL); }
void GetEvent(void){ XEvent x_event; int b; XNextEvent(x_disp, &x_event); switch(x_event.type){ case KeyPress: keyq[keyq_head].key = XLateKey(&x_event.xkey); keyq[keyq_head].down = true; keyq_head =(keyq_head + 1) & 63; break; case KeyRelease: /* * This is a hack in order to avoid disabling key repeat, which * would cause a lot of problems when changing to other windows * or when the program crashes. * * Whenever a key release event occurs, we check to see if the * next event in the queue is a press event of the same key * with the same time stamp. If it is, we simply discard this * and the next event. */ if( XPending( x_disp) > 0){ XEvent tmp_event; XPeekEvent( x_disp, &tmp_event); if( tmp_event.type == KeyPress && tmp_event.xkey.keycode == x_event.xkey.keycode && tmp_event.xkey.time == x_event.xkey.time){ XNextEvent( x_disp, &tmp_event); break; } } keyq[keyq_head].key = XLateKey(&x_event.xkey); keyq[keyq_head].down = false; keyq_head =(keyq_head + 1) & 63; break; case MotionNotify: if( _windowed_mouse->value){ int xoffset =((int)x_event.xmotion.x -(int)(window_width / 2)); int yoffset =((int)x_event.xmotion.y -(int)(window_height / 2)); if( xoffset != 0 || yoffset != 0){ mx += xoffset; my += yoffset; /* move the mouse to the window center again */ XSelectInput( x_disp, x_win, STD_EVENT_MASK & ~PointerMotionMask); XWarpPointer( x_disp, None, x_win, 0, 0, 0, 0, (window_width / 2),(window_height / 2)); XSelectInput( x_disp, x_win, STD_EVENT_MASK); } } else { mx =((int)x_event.xmotion.x -(int)p_mouse_x); my =((int)x_event.xmotion.y -(int)p_mouse_y); p_mouse_x = x_event.xmotion.x; p_mouse_y = x_event.xmotion.y; } break; case ButtonPress: b = -1; if( x_event.xbutton.button == 1){ b = 0; } else if( x_event.xbutton.button == 2){ b = 2; } else if( x_event.xbutton.button == 3){ b = 1; } if( b >= 0){ mouse_buttonstate |= 1 << b; } break; case ButtonRelease: b = -1; if( x_event.xbutton.button == 1){ b = 0; } else if( x_event.xbutton.button == 2){ b = 2; } else if( x_event.xbutton.button == 3){ b = 1; } if( b >= 0){ mouse_buttonstate &= ~(1 << b); } break; case ConfigureNotify: config_notify_width = x_event.xconfigure.width; config_notify_height = x_event.xconfigure.height; if( xil_keepaspect->value && !force_resize){ double aspect =(double)vid.width / vid.height; if( config_notify_height > config_notify_width / aspect){ force_resize = 1; XResizeWindow( x_disp, x_win, config_notify_width, (int)(config_notify_width / aspect)); } else if( config_notify_width > config_notify_height * aspect){ force_resize = 1; XResizeWindow( x_disp, x_win, (int)(config_notify_height * aspect), config_notify_height); } } else { force_resize = 0; } if( !force_resize){ window_width = config_notify_width; window_height = config_notify_height; newt_initialize_next = 1; } break; case MapNotify: if( _windowed_mouse->value){ XGrabPointer( x_disp, x_win, True, 0, GrabModeAsync, GrabModeAsync, x_win, None, CurrentTime); } break; case UnmapNotify: if( _windowed_mouse->value){ XUngrabPointer( x_disp, CurrentTime); } break; case VisibilityNotify: puts("visibility"); newt_initialize_next = 1; break; default: ; } if( old_windowed_mouse != _windowed_mouse->value){ old_windowed_mouse = _windowed_mouse->value; if( !_windowed_mouse->value){ /* ungrab the pointer */ XUngrabPointer( x_disp, CurrentTime); } else { /* grab the pointer */ XGrabPointer( x_disp, x_win, True, 0, GrabModeAsync, GrabModeAsync, x_win, None, CurrentTime); } } }
struct menu * menu_filter(struct screen_ctx *sc, struct menu_q *menuq, const char *prompt, const char *initial, int flags, void (*match)(struct menu_q *, struct menu_q *, char *), void (*print)(struct menu *, int)) { struct menu_ctx mc; struct menu_q resultq; struct menu *mi = NULL; XEvent e; Window focuswin; int focusrevert, xsave, ysave, xcur, ycur; TAILQ_INIT(&resultq); xu_ptr_getpos(sc->rootwin, &xsave, &ysave); (void)memset(&mc, 0, sizeof(mc)); mc.sc = sc; mc.flags = flags; mc.match = match; mc.print = print; mc.entry = mc.prev = -1; mc.geom.x = xsave; mc.geom.y = ysave; if (mc.flags & CWM_MENU_LIST) mc.list = 1; (void)strlcpy(mc.promptstr, prompt, sizeof(mc.promptstr)); if (initial != NULL) (void)strlcpy(mc.searchstr, initial, sizeof(mc.searchstr)); else mc.searchstr[0] = '\0'; mc.win = XCreateSimpleWindow(X_Dpy, sc->rootwin, 0, 0, 1, 1, Conf.bwidth, sc->xftcolor[CWM_COLOR_MENU_FG].pixel, sc->xftcolor[CWM_COLOR_MENU_BG].pixel); mc.xftdraw = XftDrawCreate(X_Dpy, mc.win, sc->visual, sc->colormap); XSelectInput(X_Dpy, mc.win, MENUMASK); XMapRaised(X_Dpy, mc.win); if (XGrabPointer(X_Dpy, mc.win, False, MENUGRABMASK, GrabModeAsync, GrabModeAsync, None, Conf.cursor[CF_QUESTION], CurrentTime) != GrabSuccess) { XftDrawDestroy(mc.xftdraw); XDestroyWindow(X_Dpy, mc.win); } XGetInputFocus(X_Dpy, &focuswin, &focusrevert); XSetInputFocus(X_Dpy, mc.win, RevertToPointerRoot, CurrentTime); /* make sure keybindings don't remove keys from the menu stream */ XGrabKeyboard(X_Dpy, mc.win, True, GrabModeAsync, GrabModeAsync, CurrentTime); for (;;) { mc.changed = 0; XWindowEvent(X_Dpy, mc.win, MENUMASK, &e); switch (e.type) { case KeyPress: if ((mi = menu_handle_key(&e, &mc, menuq, &resultq)) != NULL) goto out; /* FALLTHROUGH */ case Expose: menu_draw(&mc, menuq, &resultq); break; case MotionNotify: menu_handle_move(&mc, &resultq, e.xbutton.x, e.xbutton.y); break; case ButtonRelease: if ((mi = menu_handle_release(&mc, &resultq, e.xbutton.x, e.xbutton.y)) != NULL) goto out; break; default: break; } } out: if ((mc.flags & CWM_MENU_DUMMY) == 0 && mi->dummy) { /* no mouse based match */ free(mi); mi = NULL; } XftDrawDestroy(mc.xftdraw); XDestroyWindow(X_Dpy, mc.win); XSetInputFocus(X_Dpy, focuswin, focusrevert, CurrentTime); /* restore if user didn't move */ xu_ptr_getpos(sc->rootwin, &xcur, &ycur); if (xcur == mc.geom.x && ycur == mc.geom.y) xu_ptr_setpos(sc->rootwin, xsave, ysave); XUngrabPointer(X_Dpy, CurrentTime); XUngrabKeyboard(X_Dpy, CurrentTime); return(mi); }
void emX11WindowPort::PreConstruct() { XSetWindowAttributes xswa; XWMHints xwmh; XClassHint xch; XSizeHints xsh; XGCValues xgcv; long eventMask,extraEventMask; double vrx,vry,vrw,vrh,d; int border; bool haveBorder; if ((GetWindowFlags()&emWindow::WF_FULLSCREEN)!=0) { Screen.LeaveFullscreenModes(&GetWindow()); Screen.GetVisibleRect(&vrx,&vry,&vrw,&vrh); MinPaneW=1; MinPaneH=1; PaneX=(int)(vrx+0.5); PaneY=(int)(vry+0.5); PaneW=(int)(vrw+0.5); PaneH=(int)(vrh+0.5); BorderL=0; BorderT=0; BorderR=0; BorderB=0; haveBorder=false; Focused=true; } else if ((GetWindowFlags()&(emWindow::WF_POPUP|emWindow::WF_UNDECORATED))!=0) { Screen.GetVisibleRect(&vrx,&vry,&vrw,&vrh); MinPaneW=1; MinPaneH=1; PaneX=(int)(vrx+vrw*emGetDblRandom(0.22,0.28)+0.5); PaneY=(int)(vry+vrh*emGetDblRandom(0.22,0.28)+0.5); PaneW=(int)(vrw*0.5+0.5); PaneH=(int)(vrh*0.5+0.5); BorderL=0; BorderT=0; BorderR=0; BorderB=0; haveBorder=false; Focused=true; } else { Screen.LeaveFullscreenModes(&GetWindow()); Screen.GetVisibleRect(&vrx,&vry,&vrw,&vrh); MinPaneW=32; MinPaneH=32; if (!Owner && (GetWindowFlags()&emWindow::WF_MODAL)==0) { d=emMin(vrw,vrh)*0.08; PaneX=(int)(vrx+d*emGetDblRandom(0.5,1.5)+0.5); PaneY=(int)(vry+d*emGetDblRandom(0.8,1.2)+0.5); PaneW=(int)(vrw-d*2.0+0.5); PaneH=(int)(vrh-d*2.0+0.5); } else { PaneX=(int)(vrx+vrw*emGetDblRandom(0.22,0.28)+0.5); PaneY=(int)(vry+vrh*emGetDblRandom(0.22,0.28)+0.5); PaneW=(int)(vrw*0.5+0.5); PaneH=(int)(vrh*0.5+0.5); } // Some window managers seem to expect that we would expect this: BorderL=3; BorderT=18; BorderR=3; BorderB=3; haveBorder=true; if ((GetWindowFlags()&emWindow::WF_MODAL)!=0) Focused=true; else Focused=false; } ClipX1=PaneX; ClipY1=PaneY; ClipX2=PaneX+PaneW; ClipY2=PaneY+PaneH; PosForced=false; PosPending=false; SizeForced=false; SizePending=false; InvalidRects.Set(PaneX,PaneY,PaneX+PaneW,PaneY+PaneH); Title.Empty(); TitlePending=true; IconPending=true; Cursor=-1; CursorPending=true; PostConstructed=false; Mapped=false; InputStateClock=0; LastButtonPress=EM_KEY_NONE; RepeatKey=EM_KEY_NONE; memset(&ComposeStatus,0,sizeof(ComposeStatus)); memset(&xsh,0,sizeof(xsh)); xsh.flags =PMinSize; xsh.min_width =MinPaneW; xsh.min_height=MinPaneH; eventMask= ExposureMask|ButtonPressMask|ButtonReleaseMask|PointerMotionMask| KeyPressMask|KeyReleaseMask|StructureNotifyMask|SubstructureNotifyMask| VisibilityChangeMask|FocusChangeMask ; memset(&xswa,0,sizeof(xswa)); xswa.bit_gravity=ForgetGravity; xswa.colormap=Screen.Colmap; xswa.event_mask=eventMask; if (haveBorder) { xswa.override_redirect=False; border=1; } else { xswa.override_redirect=True; border=0; } XMutex.Lock(); Win=XCreateWindow( Disp, Screen.RootWin, PaneX-BorderL, PaneY-BorderT, PaneW, PaneH, border, Screen.VisuDepth, InputOutput, Screen.Visu, CWBitGravity|CWColormap|CWEventMask|CWOverrideRedirect, &xswa ); XMutex.Unlock(); Screen.WCThread->AddWindow(Win); if (Owner) { XMutex.Lock(); XSetTransientForHint(Disp,Win,Owner->Win); XMutex.Unlock(); } if (Screen.InputMethod) { XMutex.Lock(); InputContext=XCreateIC( Screen.InputMethod, XNInputStyle,XIMPreeditNothing|XIMStatusNothing, XNClientWindow,Win, (char*)NULL ); XMutex.Unlock(); if (InputContext==NULL) { emFatalError("Failed to create X input context."); } } else { InputContext=NULL; } if (InputContext) { XMutex.Lock(); XGetICValues(InputContext,XNFilterEvents,&extraEventMask,(char*)NULL); XMutex.Unlock(); eventMask|=extraEventMask; } XMutex.Lock(); XSelectInput(Disp,Win,eventMask); XMutex.Unlock(); memset(&xwmh,0,sizeof(xwmh)); xwmh.flags=(InputHint|StateHint); xwmh.input=True; xwmh.initial_state=NormalState; memset(&xch,0,sizeof(xch)); xch.res_name =(char*)GetWMResName().Get(); xch.res_class=(char*)"EagleMode"; XMutex.Lock(); XmbSetWMProperties(Disp,Win,Title.Get(),NULL,NULL,0,&xsh,&xwmh,&xch); XMutex.Unlock(); XMutex.Lock(); XChangeProperty( Disp, Win, Screen.WM_PROTOCOLS, XA_ATOM, 32, PropModeReplace, (const unsigned char*)&Screen.WM_DELETE_WINDOW, 1 ); XMutex.Unlock(); memset(&xgcv,0,sizeof(xgcv)); XMutex.Lock(); Gc=XCreateGC(Disp,Win,0,&xgcv); XMutex.Unlock(); SetViewFocused(Focused); SetViewGeometry(PaneX,PaneY,PaneW,PaneH,Screen.PixelTallness); WakeUp(); }
int main (int argc, char * argv[]) { char expr[50]; double xmax,ymax; int x,y; int tab[400] = {0}; int choix; /*partie pour l'evaluation de la fonction*/ printf("-------------------------------\n"); printf("1°) lignes \n"); printf("2°) points \n"); printf("-------------------------------\n"); scanf("%d",&choix); getc(stdin); printf("Veuillez rentrer les tailles max de votre fenetre xmax,ymax \n"); scanf("%lf %lf",&xmax,&ymax); getc(stdin); printf("Veuillez rentrer l'expression desire\n"); fgets(expr,49,stdin); calcul(expr,xmax,ymax,tab); dpy = XOpenDisplay(0); if(!dpy) { printf("souci à l'ouverture de la fenetre \n"); exit(EXIT_FAILURE); } ecran = DefaultScreen(dpy); root = DefaultRootWindow(dpy); /* ------- Recup. couleur de l'avant plan et arriere plan ------------ */ bpx = BlackPixel(dpy,ecran); wpx = WhitePixel(dpy,ecran); /* ------- Creation de la fenetre: Epaiss 6 pixels, L 400 H 400 ------ */ win = XCreateSimpleWindow(dpy,root,0,0,400,400,6,wpx,bpx); XStoreName(dpy,win,"TP 7: Graphisme 3D sous X-Windows"); /* ------- Definition des evenements qui les concernent -------------- */ XSelectInput(dpy,win,ButtonPressMask | ButtonReleaseMask | Button1MotionMask | KeyPressMask | ExposureMask ); /*---------------------------------------------------------------------*/ XMapWindow(dpy,win); /* ------- Creation des contextes standards -------------------------- */ gcv.foreground = wpx; /* Contexte standard */ gcv.background = bpx; gcv.line_width = 1; gcv.function = GXcopy; gcmask = GCForeground | GCBackground | GCLineWidth | GCFunction; gcontext = XCreateGC(dpy,win,gcmask,&gcv); /* ------------------------------------------------------------------- */ while(!sortie) { XNextEvent(dpy,&ev); switch(ev.type) { case Expose : affich(expr,tab,choix); break; case KeyPress : sortie = 1; break; } } XCloseDisplay(dpy); return(EXIT_SUCCESS); }
int main () { Display *display; Window win; Atom _request, _extents, _type, _normal, _desktop, _state; Atom _state_fs, _state_mh, _state_mv; int x=10,y=10,h=100,w=400; display = XOpenDisplay(NULL); if (display == NULL) { fprintf(stderr, "couldn't connect to X server :0\n"); return 0; } _type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); _normal = XInternAtom(display, "_NET_WM_WINDOW_TYPE_NORMAL", False); _desktop = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DESKTOP", False); _request = XInternAtom(display, "_NET_REQUEST_FRAME_EXTENTS", False); _extents = XInternAtom(display, "_NET_FRAME_EXTENTS", False); _state = XInternAtom(display, "_NET_WM_STATE", False); _state_fs = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False); _state_mh = XInternAtom(display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); _state_mv = XInternAtom(display, "_NET_WM_STATE_MAXIMIZED_VERT", False); win = XCreateWindow(display, RootWindow(display, 0), x, y, w, h, 10, CopyFromParent, CopyFromParent, CopyFromParent, 0, NULL); XSelectInput(display, win, PropertyChangeMask); printf("requesting for type normal\n"); XChangeProperty(display, win, _type, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_normal, 1); request(display, _request, _extents, win); reply(display, _extents); printf("requesting for type normal+fullscreen\n"); XChangeProperty(display, win, _type, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_normal, 1); XChangeProperty(display, win, _state, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_state_fs, 1); request(display, _request, _extents, win); reply(display, _extents); printf("requesting for type normal+maxv\n"); XChangeProperty(display, win, _type, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_normal, 1); XChangeProperty(display, win, _state, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_state_mv, 1); request(display, _request, _extents, win); reply(display, _extents); printf("requesting for type normal+maxh\n"); XChangeProperty(display, win, _type, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_normal, 1); XChangeProperty(display, win, _state, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_state_mh, 1); request(display, _request, _extents, win); reply(display, _extents); printf("requesting for type desktop\n"); XChangeProperty(display, win, _type, XA_ATOM, 32, PropModeReplace, (unsigned char*)&_desktop, 1); request(display, _request, _extents, win); reply(display, _extents); return 1; }
// Wait until a X11 top level has been mapped, courtesy of xtoolwait. static Window waitForTopLevelMapped(Display *display, unsigned count, int timeOutMS, QString * errorMessage) { unsigned mappingsCount = count; Atom xa_wm_state; XEvent event; // Discard all pending events currentX11Function = "XSync"; XSync(display, True); // Listen for top level creation currentX11Function = "XSelectInput"; XSelectInput(display, DefaultRootWindow(display), SubstructureNotifyMask); /* We assume that the window manager provides the WM_STATE property on top-level * windows, as required by ICCCM 2.0. * If the window manager has not yet completed its initialisation, the WM_STATE atom * might not exist, in which case we create it. */ #ifdef XA_WM_STATE /* probably in X11R7 */ xa_wm_state = XA_WM_STATE; #else xa_wm_state = XInternAtom(display, "WM_STATE", False); #endif QTime elapsedTime; elapsedTime.start(); while (mappingsCount) { if (elapsedTime.elapsed() > timeOutMS) { *errorMessage = QString::fromLatin1("X11: Timed out waiting for toplevel %1ms").arg(timeOutMS); return 0; } currentX11Function = "XNextEvent"; unsigned errorCount = x11ErrorCount; XNextEvent(display, &event); if (x11ErrorCount > errorCount) { *errorMessage = QString::fromLatin1("X11: Error in XNextEvent"); return 0; } switch (event.type) { case CreateNotify: // Window created, listen for its mapping now if (!event.xcreatewindow.send_event && !event.xcreatewindow.override_redirect) XSelectInput(display, event.xcreatewindow.window, PropertyChangeMask); break; case PropertyNotify: // Watch for map if (!event.xproperty.send_event && event.xproperty.atom == xa_wm_state) { bool mapped; if (isMapped(display, xa_wm_state, event.xproperty.window, &mapped)) { if (mapped && --mappingsCount == 0) return event.xproperty.window; // Past splash screen, listen for next window to be created XSelectInput(display, DefaultRootWindow(display), SubstructureNotifyMask); } else { // Some temporary window disappeared. Listen for next creation XSelectInput(display, DefaultRootWindow(display), SubstructureNotifyMask); } // Main app window opened? } break; default: break; } } *errorMessage = QString::fromLatin1("X11: Timed out waiting for toplevel %1ms").arg(timeOutMS); return 0; }
/* * Class: jogamp_nativewindow_x11_X11Lib * Method: CreateWindow * Signature: (JJIIIIZZ)J */ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateWindow (JNIEnv *env, jclass unused, jlong parent, jlong display, jint screen_index, jint visualID, jint width, jint height, jboolean input, jboolean visible) { Display * dpy = (Display *)(intptr_t)display; int scrn_idx = (int)screen_index; Window root = RootWindow(dpy, scrn_idx); Window windowParent = (Window) parent; Window window = 0; XVisualInfo visualTemplate; XVisualInfo *pVisualQuery = NULL; Visual *visual = NULL; int depth; XSetWindowAttributes xswa; unsigned long attrMask; int n; Screen* scrn; if(NULL==dpy) { NativewindowCommon_FatalError(env, "invalid display connection.."); return 0; } if(visualID<0) { NativewindowCommon_throwNewRuntimeException(env, "invalid VisualID .."); return 0; } NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); scrn = ScreenOfDisplay(dpy, scrn_idx); if(0==windowParent) { windowParent = root; } // try given VisualID on screen memset(&visualTemplate, 0, sizeof(XVisualInfo)); visualTemplate.screen = scrn_idx; visualTemplate.visualid = (VisualID)visualID; pVisualQuery = XGetVisualInfo(dpy, VisualIDMask|VisualScreenMask, &visualTemplate,&n); if(pVisualQuery!=NULL) { visual = pVisualQuery->visual; depth = pVisualQuery->depth; visualID = (jint)pVisualQuery->visualid; XFree(pVisualQuery); pVisualQuery=NULL; } DBG_PRINT( "X11: [CreateWindow] trying given (dpy %p, screen %d, visualID: %d, parent %p) found: %p\n", dpy, scrn_idx, (int)visualID, windowParent, visual); if (visual==NULL) { // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); NativewindowCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!"); return 0; } if(pVisualQuery!=NULL) { XFree(pVisualQuery); pVisualQuery=NULL; } attrMask = ( CWBackingStore | CWBackingPlanes | CWBackingPixel | CWBackPixmap | CWBorderPixel | CWColormap | CWOverrideRedirect ) ; memset(&xswa, 0, sizeof(xswa)); xswa.override_redirect = False; // use the window manager, always xswa.border_pixel = 0; xswa.background_pixmap = None; xswa.backing_store=NotUseful; /* NotUseful, WhenMapped, Always */ xswa.backing_planes=0; /* planes to be preserved if possible */ xswa.backing_pixel=0; /* value to use in restoring planes */ if( input ) { xswa.event_mask = X11_MOUSE_EVENT_MASK; xswa.event_mask |= KeyPressMask | KeyReleaseMask ; } if( visible ) { xswa.event_mask |= FocusChangeMask | SubstructureNotifyMask | StructureNotifyMask | ExposureMask ; } xswa.colormap = XCreateColormap(dpy, windowParent, visual, AllocNone); window = XCreateWindow(dpy, windowParent, 0, 0, // only a hint, WM most likely will override width, height, 0, // border width depth, InputOutput, visual, attrMask, &xswa); if(0==window) { NativewindowCommon_throwNewRuntimeException(env, "could not create Window, bail out!"); return 0; } NativewindowX11_setNormalWindowEWMH(dpy, window); NativewindowX11_setDecorations(dpy, window, False); if( visible ) { XEvent event; XMapWindow(dpy, window); } XSync(dpy, False); if( !input ) { XSelectInput(dpy, window, 0); // no events } // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); DBG_PRINT( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); return (jlong) window; }
HSClient* manage_client(Window win) { if (is_herbstluft_window(g_display, win)) { // ignore our own window return NULL; } if (get_client_from_window(win)) { return NULL; } // init client HSClient* client = create_client(); client->pid = window_pid(g_display, win); HSMonitor* m = get_current_monitor(); // set to window properties client->window = win; client_update_title(client); unsigned int border, depth; Window root_win; int x, y; unsigned int w, h; XGetGeometry(g_display, win, &root_win, &x, &y, &w, &h, &border, &depth); // treat wanted coordinates as floating coords client->float_size.x = x; client->float_size.y = y; client->float_size.width = w; client->float_size.height = h; // apply rules HSClientChanges changes; client_changes_init(&changes, client); rules_apply(client, &changes); if (changes.tag_name) { client->tag = find_tag(changes.tag_name->str); } if (!changes.manage) { client_changes_free_members(&changes); client_destroy(client); // map it... just to be sure XMapWindow(g_display, win); return NULL; } // actually manage it g_hash_table_insert(g_clients, &(client->window), client); client->window_str = g_string_sized_new(10); g_string_printf(client->window_str, "0x%lx", win); hsobject_link(g_client_object, &client->object, client->window_str->str); // insert to layout if (!client->tag) { client->tag = m->tag; } // get events from window XSelectInput(g_display, win, CLIENT_EVENT_MASK); // insert window to the stack client->slice = slice_create_client(client); stack_insert_slice(client->tag->stack, client->slice); // insert window to the tag frame_insert_window(lookup_frame(client->tag->frame, changes.tree_index->str), win); client_update_wm_hints(client); if (changes.focus) { // give focus to window if wanted // TODO: make this faster! // WARNING: this solution needs O(C + exp(D)) time where W is the count // of clients on this tag and D is the depth of the binary layout tree frame_focus_window(client->tag->frame, win); } HSAttribute attributes[] = { ATTRIBUTE_STRING( "winid", client->window_str, ATTR_READ_ONLY), ATTRIBUTE_STRING( "title", client->title, ATTR_READ_ONLY), ATTRIBUTE_BOOL( "fullscreen", client->fullscreen, client_attr_fullscreen), ATTRIBUTE_BOOL( "pseudotile", client->pseudotile, client_attr_pseudotile), ATTRIBUTE_BOOL( "ewmhrequests", client->ewmhrequests, ATTR_ACCEPT_ALL), ATTRIBUTE_BOOL( "ewmhnotify", client->ewmhnotify, ATTR_ACCEPT_ALL), ATTRIBUTE_BOOL( "sizehints", client->sizehints, ATTR_ACCEPT_ALL), ATTRIBUTE_BOOL( "urgent", client->urgent, client_attr_urgent), ATTRIBUTE_LAST, }; hsobject_set_attributes(&client->object, attributes); ewmh_window_update_tag(client->window, client->tag); tag_set_flags_dirty(); client_set_fullscreen(client, changes.fullscreen); ewmh_update_window_state(client); // add client after setting the correct tag for the new client // this ensures a panel can read the tag property correctly at this point ewmh_add_client(client->window); HSMonitor* monitor = find_monitor_with_tag(client->tag); if (monitor) { if (monitor != get_current_monitor() && changes.focus && changes.switchtag) { monitor_set_tag(get_current_monitor(), client->tag); } // TODO: monitor_apply_layout() maybe is called twice here if it // already is called by monitor_set_tag() monitor_apply_layout(monitor); } else { if (changes.focus && changes.switchtag) { monitor_set_tag(get_current_monitor(), client->tag); } } client_changes_free_members(&changes); grab_client_buttons(client, false); return client; }
static int create_window(void *win_display, int x, int y, int width, int height) { Display *x11_display = (Display *)win_display; int screen = DefaultScreen(x11_display); Window root, win; root = RootWindow(x11_display, screen); printf("Create window0 for thread0\n"); drawable_thread0 = (void *)XCreateSimpleWindow(x11_display, root, x, y, width, height, 0, 0, WhitePixel(x11_display, 0)); win = (Window)drawable_thread0; if (drawable_thread0) { XSizeHints sizehints; sizehints.width = width; sizehints.height = height; sizehints.flags = USSize; XSetNormalHints(x11_display, win, &sizehints); XSetStandardProperties(x11_display, win, "Thread 0", "Thread 0", None, (char **)NULL, 0, &sizehints); XMapWindow(x11_display, win); } context_thread0 = XCreateGC(x11_display, win, 0, 0); XSelectInput(x11_display, win, KeyPressMask | StructureNotifyMask); XSync(x11_display, False); if (put_pixmap) { window_thread0 = (Window)drawable_thread0; drawable_thread0 = (void *)create_pixmap(x11_display, width, height); } if (multi_thread == 0) return 0; printf("Create window1 for thread1\n"); drawable_thread1 = (void *)XCreateSimpleWindow(x11_display, root, width, 0, width, height, 0, 0, WhitePixel(x11_display, 0)); win = (Window)drawable_thread1; if (drawable_thread1) { XSizeHints sizehints; sizehints.width = width; sizehints.height = height; sizehints.flags = USSize; XSetNormalHints(x11_display, win, &sizehints); XSetStandardProperties(x11_display, win, "Thread 1", "Thread 1", None, (char **)NULL, 0, &sizehints); XMapWindow(x11_display, win); } if (put_pixmap) { window_thread1 = (Window)drawable_thread1; drawable_thread1 = (void *)create_pixmap(x11_display, width, height); } context_thread1 = XCreateGC(x11_display, win, 0, 0); XSelectInput(x11_display, win, KeyPressMask | StructureNotifyMask); XSync(x11_display, False); return 0; }
void TestMap() { XSizeHints *hints; XWindowAttributes attr; Window w; /* Create the window. */ w = XCreateSimpleWindow(display, rootWindow, 100, 100, 200, 100, 0, 0, 0); XSelectInput(display, w, StructureNotifyMask | PropertyNotify); /* Map the window and wait for it. */ XMapWindow(display, w); Assert(AwaitEvent(MapNotify)); /* Unmap the window and wait for it. */ XUnmapWindow(display, w); Assert(AwaitEvent(UnmapNotify)); /* Map the window and wait for it (again). */ XMapWindow(display, w); Assert(AwaitEvent(MapNotify)); /* Minimize and wait. */ Minimize(w); Assert(AwaitEvent(UnmapNotify)); /* Restore and wait. */ Unminimize(w); Assert(AwaitEvent(MapNotify)); /* Maximize and wait. */ Maximize(w, 1, 1); Assert(AwaitEvent(ConfigureNotify)); /* Unmaximize and wait. */ Unmaximize(w, 0, 1); Assert(AwaitEvent(ConfigureNotify)); /* Unmaximize and wait. */ Unmaximize(w, 1, 0); Assert(AwaitEvent(ConfigureNotify)); /* Change the size hints. */ hints = XAllocSizeHints(); hints->flags = PMinSize; hints->min_width = 300; hints->min_height = 200; XSetWMNormalHints(display, w, hints); XFree(hints); XSync(display, False); sleep(1); IgnoreEvents(); XGetWindowAttributes(display, w, &attr); Assert(attr.width == 300); Assert(attr.height == 200); /* Shade and wait. */ Shade(w); Assert(AwaitEvent(UnmapNotify)); /* Maximize and wait. */ Maximize(w, 0, 1); Assert(AwaitEvent(MapNotify)); /* Shade and wait. */ Shade(w); Assert(AwaitEvent(UnmapNotify)); /* Unshade and wait. */ Unshade(w); Assert(AwaitEvent(MapNotify)); /* Destroy the window. */ XDestroyWindow(display, w); }