void xDrawLegendBox (Display *dpy, Window win, int x, int y, int width, int height, float bclip, float wclip, char *units, char *legendfont, char *labelfont, char *title, char *titlefont, char *axescolor, char *titlecolor, char *gridcolor, int style) /***************************************************************************** draw a labeled axes box ****************************************************************************** Input: dpy display pointer win window x x coordinate of upper left corner of box y y coordinate of upper left corner of box width width of box height height of box units label for legend legendfont name of font to use for legend labels labelfont name of font to use for axes labels title axes box title titlefont name of font to use for title axescolor name of color to use for axes titlecolor name of color to use for title gridcolor name of color to use for grid int style NORMAL (axis 1 on bottom, axis 2 on left) SEISMIC (axis 1 on left, axis 2 on top) ****************************************************************************** Notes: xDrawLegendBox will determine the numbered tic incremenet and first numbered tic automatically, if the specified increment is zero. Pad values must be specified in the same units as the corresponding axes values. These pads are useful when the contents of the axes box requires more space than implied by the axes values. For example, the first and last seismic wiggle traces plotted inside an axes box will typically extend beyond the axes values corresponding to the first and last traces. However, all tics will lie within the limits specified in the axes values (x1beg, x1end, x2beg, x2end). ****************************************************************************** Author: Dave Hale, Colorado School of Mines, 01/27/90 Author: Berend Scheffers , TNO Delft, 06/11/92 *****************************************************************************/ { GC gca,gct,gcg; XGCValues *values=NULL; XColor scolor,ecolor; XFontStruct *fa,*ft; XWindowAttributes wa; Colormap cmap; int labelca,labelcd,labelch,labelcw,titleca,titlecd,titlech,titlecw, xa,ya,tw,ticsize,ticb,numb,lstr,scr; float dnum=EPS,amin,amax,base,anum,azero; char str[256]; /* get screen */ scr = DefaultScreen(dpy); /* create graphics contexts */ gca = XCreateGC(dpy,win,0,values); gct = XCreateGC(dpy,win,0,values); gcg = XCreateGC(dpy,win,0,values); /* get and set fonts and determine character dimensions */ fa = XLoadQueryFont(dpy,legendfont); if (fa==NULL) fa = XLoadQueryFont(dpy,"fixed"); if (fa==NULL) { fprintf(stderr,"Cannot load/query legendfont=%s\n",legendfont); exit(-1); } XSetFont(dpy,gca,fa->fid); labelca = fa->max_bounds.ascent; labelcd = fa->max_bounds.descent; labelch = fa->max_bounds.ascent+fa->max_bounds.descent; labelcw = fa->max_bounds.lbearing+fa->max_bounds.rbearing; ft = XLoadQueryFont(dpy,titlefont); if (ft==NULL) ft = XLoadQueryFont(dpy,"fixed"); if (ft==NULL) { fprintf(stderr,"Cannot load/query titlefont=%s\n",titlefont); exit(-1); } XSetFont(dpy,gct,ft->fid); titleca = ft->max_bounds.ascent; titlecd = ft->max_bounds.descent; titlech = ft->max_bounds.ascent+ft->max_bounds.descent; titlecw = ft->max_bounds.lbearing+ft->max_bounds.rbearing; /* determine window's current colormap */ XGetWindowAttributes(dpy,win,&wa); cmap = wa.colormap; /* get and set colors */ if (XAllocNamedColor(dpy,cmap,axescolor,&scolor,&ecolor)) XSetForeground(dpy,gca,ecolor.pixel); else XSetForeground(dpy,gca,1L); if (XAllocNamedColor(dpy,cmap,titlecolor,&scolor,&ecolor)) XSetForeground(dpy,gct,ecolor.pixel); else XSetForeground(dpy,gct,1L); if (XAllocNamedColor(dpy,cmap,gridcolor,&scolor,&ecolor)) XSetForeground(dpy,gcg,ecolor.pixel); else XSetForeground(dpy,gcg,1L); /* determine tic size */ ticsize = labelcw; /* draw vertical axis */ amin = wclip; amax = bclip; /* trap for cases when bclip=wclip */ if ((bclip - wclip)!=0) dnum = (bclip-wclip)/4; base = y; ticb = -ticsize; numb = ticb-ticsize/4; azero = 0.0001*(amax-amin); xa = x+1.25*width; ya = y; for (anum=amax; anum>=amin; anum-=dnum) { if (anum<amin) continue; XDrawLine(dpy,win,gca,x,ya,x+width,ya); XDrawLine(dpy,win,gca,x+width,ya,xa,ya); sprintf(str,"%1.4g",anum); lstr = strlen(str); tw = XTextWidth(fa,str,lstr); XDrawString(dpy,win,gca,xa+width/4,ya+labelca/2,str,lstr); ya += height/4; } xa = x+width/8; ya = y+height+labelch; sprintf(str,units); lstr = strlen(str); tw = XTextWidth(fa,str,lstr); XDrawString(dpy,win,gca,xa,ya,str,lstr); /* draw axes box */ XDrawRectangle(dpy,win,gca,x,y,width,height); /* free resources before returning */ XFreeGC(dpy,gca); XFreeGC(dpy,gct); XFreeGC(dpy,gcg); }
Widget XtNativePopupMenu::traverseBuild( Widget parent, MenuRecord * menu, int indent) { assert(indent < 24); int i; #if SOXT_POPUPMENU_DEBUG char pre[24]; for (i = 0; i < indent; i++) pre[i] = ' '; pre[i] = '\0'; #endif // SOXT_POPUPMENU_DEBUG int j = 0; MenuRecord * sub; ItemRecord * item; do { sub = (MenuRecord *) NULL; item = (ItemRecord *) NULL; const int numMenus = this->menus->getLength(); for (i = 0; i < numMenus; i++) { sub = (MenuRecord *) (*this->menus)[i]; if ((sub->pos == j) && (sub->parent == menu)) { #if SOXT_POPUPMENU_DEBUG fprintf(stderr, "%s%s {\n", pre, sub->name); #endif // SOXT_POPUPMENU_DEBUG Display * dpy = SoXt::getDisplay(); const int screen = DefaultScreen(dpy); Visual * visual = DefaultVisual(dpy, screen); Colormap colormap = DefaultColormap(dpy, screen); int depth = DefaultDepth(dpy, screen); Arg args[10]; int argc = 0; XtSetArg(args[argc], XmNvisual, visual); argc++; XtSetArg(args[argc], XmNdepth, depth); argc++; XtSetArg(args[argc], XmNcolormap, colormap); argc++; Widget submenu = XmCreatePulldownMenu(parent, sub->name, args, argc); sub->menu = XtVaCreateManagedWidget(sub->name, xmCascadeButtonGadgetClass, parent, XmNsubMenuId, submenu, XtVaTypedArg, XmNlabelString, XmRString, sub->title, strlen(sub->title) + 1, NULL); this->traverseBuild(submenu, sub, indent + 2); #if SOXT_POPUPMENU_DEBUG fprintf(stderr, "%s}\n", pre); #endif // SOXT_POPUPMENU_DEBUG break; } else { sub = (MenuRecord *) NULL; } } if (sub == NULL) { const int numItems = this->items->getLength(); for (i = 0; i < numItems; i++) { item = (ItemRecord *) (*this->items)[i]; if ((item->pos == j) && (item->parent == menu)) { #if SOXT_POPUPMENU_DEBUG fprintf(stderr, "%s%s\n", pre, item->name); #endif // SOXT_POPUPMENU_DEBUG if (item->flags & ITEM_SEPARATOR) { item->item = XtVaCreateManagedWidget(item->title, xmSeparatorGadgetClass, parent, NULL); } else { item->item = XtVaCreateManagedWidget(item->title, xmToggleButtonGadgetClass, parent, XmNsensitive, (item->flags & ITEM_ENABLED) ? True : False, XtVaTypedArg, XmNlabelString, XmRString, item->title, strlen(item->title)+1, NULL); XtAddCallback(item->item, XmNvalueChangedCallback, XtNativePopupMenu::itemSelectionCallback, this); XmToggleButtonSetState(item->item, (item->flags & ITEM_MARKED) ? True : False, False); } break; } else { item = (ItemRecord *) NULL; } } } j++; } while ((sub != NULL) || (item != NULL)); return parent; } // traverseBuild()
void CWinSystemX11::UpdateResolutions() { CWinSystemBase::UpdateResolutions(); int numScreens = XScreenCount(m_dpy); g_xrandr.SetNumScreens(numScreens); bool switchOnOff = CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOSCREEN_BLANKDISPLAYS); m_userOutput = CSettings::GetInstance().GetString(CSettings::SETTING_VIDEOSCREEN_MONITOR); if (m_userOutput.compare("Default") == 0) switchOnOff = false; if(g_xrandr.Query(true, !switchOnOff)) { XOutput *out = NULL; if (m_userOutput.compare("Default") != 0) { out = g_xrandr.GetOutput(m_userOutput); if (out) { XMode mode = g_xrandr.GetCurrentMode(m_userOutput); if (!mode.isCurrent && !switchOnOff) { out = NULL; } } } if (!out) { m_userOutput = g_xrandr.GetModes()[0].name; out = g_xrandr.GetOutput(m_userOutput); } if (switchOnOff) { // switch on output g_xrandr.TurnOnOutput(m_userOutput); // switch off other outputs std::vector<XOutput> outputs = g_xrandr.GetModes(); for (size_t i=0; i<outputs.size(); i++) { if (StringUtils::EqualsNoCase(outputs[i].name, m_userOutput)) continue; g_xrandr.TurnOffOutput(outputs[i].name); } } XMode mode = g_xrandr.GetCurrentMode(m_userOutput); if (mode.id.empty()) mode = g_xrandr.GetPreferredMode(m_userOutput); m_bIsRotated = out->isRotated; if (!m_bIsRotated) UpdateDesktopResolution(CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP), 0, mode.w, mode.h, mode.hz); else UpdateDesktopResolution(CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP), 0, mode.h, mode.w, mode.hz); CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strId = mode.id; CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strOutput = m_userOutput; } else { m_userOutput = "No Output"; m_nScreen = DefaultScreen(m_dpy); int w = DisplayWidth(m_dpy, m_nScreen); int h = DisplayHeight(m_dpy, m_nScreen); UpdateDesktopResolution(CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP), 0, w, h, 0.0); } // erase previous stored modes CDisplaySettings::GetInstance().ClearCustomResolutions(); CLog::Log(LOGINFO, "Available videomodes (xrandr):"); XOutput *out = g_xrandr.GetOutput(m_userOutput); if (out != NULL) { std::vector<XMode>::iterator modeiter; CLog::Log(LOGINFO, "Output '%s' has %" PRIdS" modes", out->name.c_str(), out->modes.size()); for (modeiter = out->modes.begin() ; modeiter!=out->modes.end() ; modeiter++) { XMode mode = *modeiter; CLog::Log(LOGINFO, "ID:%s Name:%s Refresh:%f Width:%d Height:%d", mode.id.c_str(), mode.name.c_str(), mode.hz, mode.w, mode.h); RESOLUTION_INFO res; res.iScreen = 0; // not used by X11 res.dwFlags = 0; res.iWidth = mode.w; res.iHeight = mode.h; res.iScreenWidth = mode.w; res.iScreenHeight = mode.h; if (mode.IsInterlaced()) res.dwFlags |= D3DPRESENTFLAG_INTERLACED; if (!m_bIsRotated) { res.iWidth = mode.w; res.iHeight = mode.h; } else { res.iWidth = mode.h; res.iHeight = mode.w; } if (mode.h>0 && mode.w>0 && out->hmm>0 && out->wmm>0) res.fPixelRatio = ((float)out->wmm/(float)mode.w) / (((float)out->hmm/(float)mode.h)); else res.fPixelRatio = 1.0f; CLog::Log(LOGINFO, "Pixel Ratio: %f", res.fPixelRatio); res.strMode = StringUtils::Format("%s: %s @ %.2fHz", out->name.c_str(), mode.name.c_str(), mode.hz); res.strOutput = out->name; res.strId = mode.id; res.iSubtitles = (int)(0.965*mode.h); res.fRefreshRate = mode.hz; res.bFullScreen = true; g_graphicsContext.ResetOverscan(res); CDisplaySettings::GetInstance().AddResolutionInfo(res); } } CDisplaySettings::GetInstance().ApplyCalibrations(); }
static Lock * lockscreen(Display *dpy, int screen) { #if !TRANSPARENT char curs[] = {0, 0, 0, 0, 0, 0, 0, 0}; #endif unsigned int len; Lock *lock; #if !TRANSPARENT XColor color, dummy; #endif XSetWindowAttributes wa; #if !TRANSPARENT Cursor invisible; #endif #if TRANSPARENT XVisualInfo vi; #endif if(dpy == NULL || screen < 0) return NULL; lock = malloc(sizeof(Lock)); if(lock == NULL) return NULL; lock->screen = screen; lock->root = RootWindow(dpy, lock->screen); #if TRANSPARENT XMatchVisualInfo(dpy, DefaultScreen(dpy), 32, TrueColor, &vi); wa.colormap = XCreateColormap(dpy, DefaultRootWindow(dpy), vi.visual, AllocNone); #endif /* init */ wa.override_redirect = 1; #if !TRANSPARENT wa.background_pixel = BlackPixel(dpy, lock->screen); #else wa.border_pixel = 0; wa.background_pixel = 0xaa000000; #endif lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen), #if !TRANSPARENT 0, DefaultDepth(dpy, lock->screen), CopyFromParent, DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa); #else 0, vi.depth, CopyFromParent, vi.visual, CWOverrideRedirect | CWBackPixel | CWColormap | CWBorderPixel, &wa); #endif Atom name_atom = XA_WM_NAME; XTextProperty name_prop = { "slock", name_atom, 8, 5 }; XSetWMName(dpy, lock->win, &name_prop); // Atom name_ewmh_atom = XInternAtom(dpy, "_NET_WM_NAME", False); // XTextProperty name_ewmh_prop = { "slock", name_ewmh_atom, 8, 5 }; // XSetTextProperty(dpy, lock->win, &name_ewmh_prop, name_ewmh_atom); // XSetWMName(dpy, lock->win, &name_ewmh_prop); XClassHint *hint = XAllocClassHint(); if (hint) { hint->res_name = "slock"; hint->res_class = "slock"; XSetClassHint(dpy, lock->win, hint); XFree(hint); } #if !TRANSPARENT XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), COLOR2, &color, &dummy); lock->colors[1] = color.pixel; XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), COLOR1, &color, &dummy); lock->colors[0] = color.pixel; lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8); invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0); XDefineCursor(dpy, lock->win, invisible); #endif XMapRaised(dpy, lock->win); for(len = 1000; len; len--) { if(XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, #if !TRANSPARENT GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess) #else GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess) #endif break; usleep(1000); } if(running && (len > 0)) { for(len = 1000; len; len--) { if(XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess) break; usleep(1000); } } running &= (len > 0); if(!running) { unlockscreen(dpy, lock); lock = NULL; } else XSelectInput(dpy, lock->root, SubstructureNotifyMask); usboff(); return lock; }
main (int argc, char *argv[]) #endif { XEvent ev; fd_set fd; int xfd; dd = XOpenDisplay (NULL); if (!dd) return 0; scr_screen = DefaultScreen (dd); scr_depth = DefaultDepth (dd, scr_screen); scr_height = DisplayHeight (dd, scr_screen); scr_width = DisplayWidth (dd, scr_screen); root_win = RootWindow (dd, scr_screen); /* helps us catch windows closing/opening */ XSelectInput (dd, root_win, PropertyChangeMask); XSetErrorHandler ((XErrorHandler) handle_error); XInternAtoms (dd, atom_names, ATOM_COUNT, False, atoms); gui_init (); bzero (&tb, sizeof (struct taskbar)); tb.win = gui_create_taskbar (); xfd = ConnectionNumber (dd); gui_sync (); while (1) { FD_ZERO (&fd); FD_SET (xfd, &fd); select (xfd + 1, &fd, 0, 0, 0); while (XPending (dd)) { XNextEvent (dd, &ev); switch (ev.type) { case ButtonPress: handle_press (ev.xbutton.x, ev.xbutton.y, ev.xbutton.button); break; case DestroyNotify: del_task (ev.xdestroywindow.window); /* fall through */ case Expose: gui_draw_taskbar (); break; case PropertyNotify: handle_propertynotify (ev.xproperty.window, ev.xproperty.atom); break; case FocusIn: handle_focusin (ev.xfocus.window); break; /*default: printf ("unknown evt type: %d\n", ev.type);*/ } } } /*XCloseDisplay (dd); return 0;*/ }
static Window createWindow(Window parent, Visual *visual, gulong mask, XSetWindowAttributes *attrib) { return XCreateWindow(t_display, parent, 0, 0, 1, 1, 0, (visual ? 32 : DefaultDepth(t_display, DefaultScreen(t_display))), InputOutput, (visual ? visual : DefaultVisual(t_display, DefaultScreen(t_display))), mask, attrib); }
void winopen(void) { XWMHints *hints; xdpy = XOpenDisplay(nil); if (!xdpy) winerror(&gapp, "could not open display."); XA_TARGETS = XInternAtom(xdpy, "TARGETS", False); XA_TIMESTAMP = XInternAtom(xdpy, "TIMESTAMP", False); XA_UTF8_STRING = XInternAtom(xdpy, "UTF8_STRING", False); xscr = DefaultScreen(xdpy); ximage_init(xdpy, xscr, DefaultVisual(xdpy, xscr)); xcarrow = XCreateFontCursor(xdpy, XC_left_ptr); xchand = XCreateFontCursor(xdpy, XC_hand2); xcwait = XCreateFontCursor(xdpy, XC_watch); xbgcolor.red = 0x7000; xbgcolor.green = 0x7000; xbgcolor.blue = 0x7000; xshcolor.red = 0x4000; xshcolor.green = 0x4000; xshcolor.blue = 0x4000; XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xbgcolor); XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xshcolor); xwin = XCreateWindow(xdpy, DefaultRootWindow(xdpy), 10, 10, 200, 100, 1, ximage_get_depth(), InputOutput, ximage_get_visual(), 0, nil); XSetWindowColormap(xdpy, xwin, ximage_get_colormap()); XSelectInput(xdpy, xwin, StructureNotifyMask | ExposureMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask); mapped = 0; xgc = XCreateGC(xdpy, xwin, 0, nil); XDefineCursor(xdpy, xwin, xcarrow); hints = XAllocWMHints(); if (hints) { hints->flags = IconPixmapHint; hints->icon_pixmap = XCreateBitmapFromData(xdpy, xwin, gs_l_xbm_bits, gs_l_xbm_width, gs_l_xbm_height); if (hints->icon_pixmap) { XSetWMHints(xdpy, xwin, hints); } XFree(hints); } }
int main(int argc, char* argv[]) { int number_of_stars = 200; int iterations = 1000; prec time_unit = gdt; if(argc == 3) { number_of_stars = atoi(argv[1]); iterations = atoi(argv[2]); } struct star* star_array = malloc(sizeof(struct star) * number_of_stars); generate_init_values(number_of_stars, star_array); #ifdef ANIMATE XPoint* points = malloc(sizeof(XPoint)*number_of_stars); Display* disp; Window window, rootwin; int screen; disp = XOpenDisplay(NULL); screen = DefaultScreen(disp); rootwin = RootWindow(disp,screen); window = XCreateSimpleWindow(disp,rootwin, 0,0,X_SIZE,Y_SIZE,1,0,0); GC gc = XCreateGC(disp, window, 0, 0); XSetForeground(disp, gc, WhitePixel(disp, screen)); XSetBackground(disp, gc, BlackPixel(disp, screen)); XMapWindow(disp,window); XClearWindow(disp,window); copyToXBuffer(star_array, points, number_of_stars); XDrawPoints(disp, window, gc, points, number_of_stars, 0); XFlush(disp); #endif clock_t start = clock(); for(int i = 0; i < iterations; i++) { #ifndef ANIMATE resetForces(number_of_stars, star_array); updateForces(number_of_stars, number_of_stars - 1, star_array); for(int j = 0; j < number_of_stars; ++j){ update_position(&star_array[j], time_unit); } #endif #ifdef ANIMATE resetForces(number_of_stars, star_array); updateForces(number_of_stars, number_of_stars - 1, star_array); for(int j = 0; j < number_of_stars; ++j){ update_position(&star_array[j], time_unit); copyToXBuffer(star_array, points,number_of_stars ); XDrawPoints(disp, window, gc, points, number_of_stars, CoordModeOrigin); } XClearWindow(disp,window); #endif } clock_t stop = clock(); float diff = (float)(stop - start)/CLOCKS_PER_SEC; printf("Total: %lf seconds\n",diff); printf("Bodies: %d\n",number_of_stars); printf("Iterations: %d\n", iterations); #ifdef ANIMATE free(points); XCloseDisplay(disp); #endif free(star_array); return 0; }
bool GLWindow::CreateContextGL(int major, int minor) { if (!NativeDisplay) return false; // Get visual information int attrListDbl[] = { // GLX_X_RENDERABLE: If True is specified, then only frame buffer configurations that have associated X // visuals (and can be used to render to Windows and/or GLX pixmaps) will be considered. The default value is GLX_DONT_CARE. GLX_X_RENDERABLE , True, GLX_RED_SIZE , 8, GLX_GREEN_SIZE , 8, GLX_BLUE_SIZE , 8, GLX_DEPTH_SIZE , 24, GLX_DOUBLEBUFFER , True, None }; // Attribute are very sensible to the various implementation (intel, nvidia, amd) // Nvidia and Intel doesn't support previous attributes for opengl2.0 int attrListDbl_2_0[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DEPTH_SIZE, 24, None }; // Only keep for older card but NVIDIA and AMD both drop the support of those cards if (major <= 2) { XVisualInfo *vi = glXChooseVisual(NativeDisplay, DefaultScreen(NativeDisplay), attrListDbl_2_0); if (vi == NULL) return NULL; glxContext = glXCreateContext(NativeDisplay, vi, NULL, GL_TRUE); XFree(vi); if (!glxContext) return false; glXMakeCurrent(NativeDisplay, NativeWindow, glxContext); return true; } PFNGLXCHOOSEFBCONFIGPROC glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)GetProcAddress("glXChooseFBConfig"); int fbcount = 0; GLXFBConfig *fbc = glXChooseFBConfig(NativeDisplay, DefaultScreen(NativeDisplay), attrListDbl, &fbcount); if (!fbc || fbcount < 1) { ZZLog::Error_Log("GLX: failed to find a framebuffer"); return false; } PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)GetProcAddress("glXCreateContextAttribsARB"); if (!glXCreateContextAttribsARB) return false; // Create a context int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, major, GLX_CONTEXT_MINOR_VERSION_ARB, minor, // Keep compatibility for old cruft GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB | GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // FIXME : Request a debug context to ease opengl development #if (defined(ZEROGS_DEVBUILD) || defined(_DEBUG)) && defined(OGL4_LOG) GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB, #endif None }; glxContext = glXCreateContextAttribsARB(NativeDisplay, fbc[0], 0, true, context_attribs); if (!glxContext) { ZZLog::Error_Log("GLX: failed to create an opengl context"); return false; } XSync( NativeDisplay, false); if (!glXMakeCurrent(NativeDisplay, NativeWindow, glxContext)) { ZZLog::Error_Log("GLX: failed to attach the opengl context"); return false; } return true; }
int main(int argc, char**argv) { char **missing_charset_list; int missing_charset_count; XGCValues xgcv; unsigned long mask; Display* dpy; int scr; Window w, root; XSetWindowAttributes set_attr; int i; XIMStyle *style; static char buf[128]; KeySym keysym = 0; Status status; XWMHints wm_hints; XClassHint class_hints; XIMStyle input_style = 0; char **font_name_list; char *def_string; XFontStruct **font_struct_list; char **font_encoding_list; int nb_font; int len = 0; int no_xim = 0; printf ("A -> %c \n", XUtf8Tolower('A')); if (!setlocale(LC_ALL, "")) puts("locale not supported by C library, locale unchanged"); if (!XSetLocaleModifiers("")) puts("X locale modifiers not supported, using default"); dpy = XOpenDisplay(0); if (!dpy) { puts("cannot open display.\n"); exit(-1); } scr = DefaultScreen(dpy); root = RootWindow(dpy, scr); set_attr.event_mask = KeyPressMask|FocusChangeMask; set_attr.background_pixel = WhitePixel(dpy, DefaultScreen(dpy)); set_attr.border_pixel = BlackPixel(dpy, DefaultScreen(dpy)); w = XCreateWindow(dpy, root, 10,10,200,100,0, DefaultDepth(dpy, DefaultScreen(dpy)), InputOutput, DefaultVisual(dpy, DefaultScreen(dpy)), CWEventMask | CWBackPixel | CWBorderPixel, &set_attr); if (!w) { puts("cannot creat window.\n"); exit(-1); } class_hints.res_name = "test"; class_hints.res_class = "Test"; wm_hints.input = True; wm_hints.flags = InputHint; XmbSetWMProperties(dpy, w, "test", "test", NULL, 0, NULL, &wm_hints, &class_hints); XMapWindow(dpy, w); xim_im = XOpenIM(dpy, NULL, "test", "Test"); if (!xim_im) { puts("cannot Open Input Manager: Try default.\n"); XSetLocaleModifiers("@im="); xim_im = XOpenIM(dpy, NULL, "test", "Test"); if (!xim_im) { puts("Failed exiting.\n"); exit(-1); } } XGetIMValues (xim_im, XNQueryInputStyle, &xim_styles, NULL, NULL); for (i = 0, style = xim_styles->supported_styles; i < xim_styles->count_styles; i++, style++) { if (i == 0 && *style == (XIMStatusNone|XIMPreeditNone)) { printf("this is not a XIM server !!!\n"); no_xim = 1; } printf("input style : 0x%X\n", *style); } xim_ic = XCreateIC(xim_im, XNInputStyle, (XIMPreeditNothing | XIMStatusNothing), XNClientWindow, w, XNFocusWindow, w, NULL); if (!xim_ic) { puts("cannot create Input Context.\n"); exit(-1);} XFree(xim_styles); XSetICFocus(xim_ic); /***************************************************************/ /** I don't recommand to use a font base name list similar * to the following one in a real application ;-) * You should use an iso8859-1 font, plus a single font for * your language. */ /***************************************************************/ fontset = XCreateUtf8FontStruct(dpy, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8858-3," /* not valid */ "-*-*-medium-r-*-*-*-*-*-*-*-*-iso8859-1," "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-6," "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-8," "-*-*-*-*-*-*-*-*-*-*-*-*-ksc5601.1987-0," "-*-symbol-*-*-*-*-*-*-*-*-*-*-adobe-fontspecific," "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-2," "-*-*-*-*-*-*-*-*-*-*-*-*-koi8-1," "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0208.1983-0," "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0212.1990-0," "-*-*-*-*-*-*-*-*-*-*-*-*-big5-0," "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0201.1976-0," "-*-unifont-*-*-*-*-*-*-*-*-*-*-iso10646-1[0x300 0x400_0x500]," "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"); /* THIS PART IS NOT REQUIERED */ nb_font = fontset->nb_font; while (nb_font > 0) { nb_font--; if (fontset->fonts[nb_font]) { printf("encoding=\"\" fid=%d \n %s\n", // fontset->encodings[nb_font], fontset->fonts[nb_font]->fid, fontset->font_name_list[nb_font]); } } /* END OF NOT REQUIERED PART*/ mask = (GCForeground | GCBackground); xgcv.foreground = BlackPixel(dpy, DefaultScreen(dpy)); xgcv.background = WhitePixel(dpy, DefaultScreen(dpy)); gc = XCreateGC(dpy, w, mask, &xgcv); if (!gc) { puts("cannot create Graphic Context.\n"); exit(-1);} /***************************************************************/ while (1) { int filtered; static XEvent xevent; static XVaNestedList list1 = 0; int r; XNextEvent(dpy, &xevent); if (xevent.type == KeyPress) { XKeyEvent *e = (XKeyEvent*) &xevent; printf ("0x%X %d\n", e->state, e->keycode); } if (xevent.type == DestroyNotify) { /* XIM server has crashed */ no_xim = 1; XSetLocaleModifiers("@im="); xim_im = XOpenIM(dpy, NULL, "test", "Test"); if (xim_im) { xim_ic = XCreateIC(xim_im, XNInputStyle, (XIMPreeditNothing | XIMStatusNothing), XNClientWindow, w, XNFocusWindow, w, NULL); } else { xim_ic = NULL; } if (!xim_ic) { puts("Crash recovery failed. exiting.\n"); exit(-1); } } if (xevent.type != DestroyNotify) { filtered = XFilterEvent(&xevent, 0); } if (xevent.type == FocusOut && xim_ic) XUnsetICFocus(xim_ic); if (xevent.type == FocusIn && xim_ic) XSetICFocus(xim_ic); if (xevent.type == KeyPress && !filtered) { len = XUtf8LookupString(xim_ic, &xevent.xkey, buf, 127, &keysym, &status); if (len == 1 && buf[0] == '\b') { x -= XUtf8TextWidth(fontset, buf, len); XUtf8DrawImageString(dpy, w, fontset, gc, x, y, buf, len); } else if (len == 1 && buf[0] == '\r') { y += fontset->ascent + fontset->descent; x = 0; XCloseIM(xim_im); } else { XUtf8DrawImageString(dpy, w, fontset, gc, x, y, buf, len); x += XUtf8TextWidth(fontset, buf, len); } XUtf8DrawString(dpy, w, fontset, gc, 0, 20, jp_txt, strlen(jp_txt)); XUtf8DrawString(dpy, w, fontset, gc, 50, 90, rtl_txt, strlen(rtl_txt)); XUtf8DrawRtlString(dpy, w, fontset, gc, 50, 90, rtl_txt, strlen(rtl_txt)); buf[len] = 0; printf("'%s' %d %x\n", buf, keysym, keysym); buf[0] = 0; } if (filtered) { printf("Dead key\n"); } } XFreeUtf8FontStruct(dpy, fontset); return 0; }
BOOL DRI2FallbackPRESENTPixmap(PRESENTpriv *present_priv, struct DRI2priv *dri2_priv, int fd, int width, int height, int stride, int depth, int bpp, PRESENTPixmapPriv **present_pixmap_priv) { Window root = RootWindow(dri2_priv->dpy, DefaultScreen(dri2_priv->dpy)); Pixmap pixmap; EGLImageKHR image; GLuint texture_read, texture_write, fbo_read, fbo_write; EGLint attribs[] = { EGL_WIDTH, 0, EGL_HEIGHT, 0, EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_ARGB8888, EGL_DMA_BUF_PLANE0_FD_EXT, 0, EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, 0, EGL_NONE }; EGLenum current_api = 0; int status; pthread_mutex_lock(&present_priv->mutex_present); pixmap = XCreatePixmap(dri2_priv->dpy, root, width, height, 24); if (!pixmap) goto fail; attribs[1] = width; attribs[3] = height; attribs[7] = fd; attribs[11] = stride; current_api = eglQueryAPI(); eglBindAPI(EGL_OPENGL_API); /* We bind the dma-buf to a EGLImage, then to a texture, and then to a fbo. * Note that we can delete the EGLImage, but we shouldn't delete the texture, * else the fbo is invalid */ image = dri2_priv->eglCreateImageKHR_func(dri2_priv->display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attribs); if (image == EGL_NO_IMAGE_KHR) goto fail; close(fd); if(eglMakeCurrent(dri2_priv->display, EGL_NO_SURFACE, EGL_NO_SURFACE, dri2_priv->context)) { glGenTextures(1, &texture_read); glBindTexture(GL_TEXTURE_2D, texture_read); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); dri2_priv->glEGLImageTargetTexture2DOES_func(GL_TEXTURE_2D, image); glGenFramebuffers(1, &fbo_read); glBindFramebuffer(GL_FRAMEBUFFER, fbo_read); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_read, 0); status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) goto fail; glBindTexture(GL_TEXTURE_2D, 0); dri2_priv->eglDestroyImageKHR_func(dri2_priv->display, image); /* We bind a newly created pixmap (to which we want to copy the content) * to an EGLImage, then to a texture, then to a fbo. */ image = dri2_priv->eglCreateImageKHR_func(dri2_priv->display, dri2_priv->context, EGL_NATIVE_PIXMAP_KHR, (void *)pixmap, NULL); if (image == EGL_NO_IMAGE_KHR) goto fail; glGenTextures(1, &texture_write); glBindTexture(GL_TEXTURE_2D, texture_write); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); dri2_priv->glEGLImageTargetTexture2DOES_func(GL_TEXTURE_2D, image); glGenFramebuffers(1, &fbo_write); glBindFramebuffer(GL_FRAMEBUFFER, fbo_write); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_write, 0); status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) goto fail; glBindTexture(GL_TEXTURE_2D, 0); dri2_priv->eglDestroyImageKHR_func(dri2_priv->display, image); } else { ERR("eglMakeCurrent failed with 0x%0X\n", eglGetError()); } eglMakeCurrent(dri2_priv->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); *present_pixmap_priv = (PRESENTPixmapPriv *) calloc(1, sizeof(PRESENTPixmapPriv)); if (!*present_pixmap_priv) { goto fail; } (*present_pixmap_priv)->released = TRUE; (*present_pixmap_priv)->pixmap = pixmap; (*present_pixmap_priv)->present_priv = present_priv; (*present_pixmap_priv)->next = present_priv->first_present_priv; (*present_pixmap_priv)->width = width; (*present_pixmap_priv)->height = height; (*present_pixmap_priv)->depth = depth; (*present_pixmap_priv)->dri2_info.is_dri2 = TRUE; (*present_pixmap_priv)->dri2_info.dri2_priv = dri2_priv; (*present_pixmap_priv)->dri2_info.fbo_read = fbo_read; (*present_pixmap_priv)->dri2_info.fbo_write = fbo_write; (*present_pixmap_priv)->dri2_info.texture_read = texture_read; (*present_pixmap_priv)->dri2_info.texture_write = texture_write; present_priv->last_serial_given++; (*present_pixmap_priv)->serial = present_priv->last_serial_given; present_priv->first_present_priv = *present_pixmap_priv; eglBindAPI(current_api); pthread_mutex_unlock(&present_priv->mutex_present); return TRUE; fail: eglMakeCurrent(dri2_priv->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglBindAPI(current_api); pthread_mutex_unlock(&present_priv->mutex_present); return FALSE; }
//-------------------------------------------------------------------------------------------------// void GLXWindow::create(const String& name, uint width, uint height, bool fullScreen, const NameValuePairList *miscParams) { Display *xDisplay = mGLSupport->getXDisplay(); String title = name; uint samples = 0; short frequency = 0; bool vsync = false; bool hidden = false; unsigned int vsyncInterval = 1; int gamma = 0; ::GLXContext glxContext = 0; ::GLXDrawable glxDrawable = 0; Window externalWindow = 0; Window parentWindow = DefaultRootWindow(xDisplay); int left = DisplayWidth(xDisplay, DefaultScreen(xDisplay))/2 - width/2; int top = DisplayHeight(xDisplay, DefaultScreen(xDisplay))/2 - height/2; mIsFullScreen = fullScreen; if(miscParams) { NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); // NB: Do not try to implement the externalGLContext option. // // Accepting a non-current context would expose us to the // risk of segfaults when we made it current. Since the // application programmers would be responsible for these // segfaults, they are better discovering them in their code. if ((opt = miscParams->find("currentGLContext")) != end && StringConverter::parseBool(opt->second)) { if (! glXGetCurrentContext()) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "GLXWindow::create"); } glxContext = glXGetCurrentContext(); glxDrawable = glXGetCurrentDrawable(); } // Note: Some platforms support AA inside ordinary windows if((opt = miscParams->find("FSAA")) != end) samples = StringConverter::parseUnsignedInt(opt->second); if((opt = miscParams->find("displayFrequency")) != end) frequency = (short)StringConverter::parseInt(opt->second); if((opt = miscParams->find("vsync")) != end) vsync = StringConverter::parseBool(opt->second); if((opt = miscParams->find("hidden")) != end) hidden = StringConverter::parseBool(opt->second); if((opt = miscParams->find("vsyncInterval")) != end) vsyncInterval = StringConverter::parseUnsignedInt(opt->second); if ((opt = miscParams->find("gamma")) != end) gamma = StringConverter::parseBool(opt->second); if((opt = miscParams->find("left")) != end) left = StringConverter::parseInt(opt->second); if((opt = miscParams->find("top")) != end) top = StringConverter::parseInt(opt->second); if((opt = miscParams->find("title")) != end) title = opt->second; if ((opt = miscParams->find("externalGLControl")) != end) mIsExternalGLControl = StringConverter::parseBool(opt->second); if((opt = miscParams->find("parentWindowHandle")) != end) { vector<String>::type tokens = StringUtil::split(opt->second, " :"); if (tokens.size() == 3) { // deprecated display:screen:xid format parentWindow = StringConverter::parseUnsignedLong(tokens[2]); } else { // xid format parentWindow = StringConverter::parseUnsignedLong(tokens[0]); } } else if((opt = miscParams->find("externalWindowHandle")) != end) { vector<String>::type tokens = StringUtil::split(opt->second, " :"); LogManager::getSingleton().logMessage( "GLXWindow::create: The externalWindowHandle parameter is deprecated.\n" "Use the parentWindowHandle or currentGLContext parameter instead."); if (tokens.size() == 3) { // Old display:screen:xid format // The old GLX code always created a "parent" window in this case: parentWindow = StringConverter::parseUnsignedLong(tokens[2]); } else if (tokens.size() == 4) { // Old display:screen:xid:visualinfo format externalWindow = StringConverter::parseUnsignedLong(tokens[2]); } else { // xid format externalWindow = StringConverter::parseUnsignedLong(tokens[0]); } } } // Ignore fatal XErrorEvents during parameter validation: oldXErrorHandler = XSetErrorHandler(safeXErrorHandler); // Validate parentWindowHandle if (parentWindow != DefaultRootWindow(xDisplay)) { XWindowAttributes windowAttrib; if (! XGetWindowAttributes(xDisplay, parentWindow, &windowAttrib) || windowAttrib.root != DefaultRootWindow(xDisplay)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid parentWindowHandle (wrong server or screen)", "GLXWindow::create"); } } // Validate externalWindowHandle if (externalWindow != 0) { XWindowAttributes windowAttrib; if (! XGetWindowAttributes(xDisplay, externalWindow, &windowAttrib) || windowAttrib.root != DefaultRootWindow(xDisplay)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid externalWindowHandle (wrong server or screen)", "GLXWindow::create"); } glxDrawable = externalWindow; } // Derive fbConfig ::GLXFBConfig fbConfig = 0; if (glxDrawable) { fbConfig = mGLSupport->getFBConfigFromDrawable (glxDrawable, &width, &height); } if (! fbConfig && glxContext) { fbConfig = mGLSupport->getFBConfigFromContext (glxContext); } mIsExternal = (glxDrawable != 0); XSetErrorHandler(oldXErrorHandler); if (! fbConfig) { int minAttribs[] = { GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_RED_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_GREEN_SIZE, 1, None }; int maxAttribs[] = { GLX_SAMPLES, samples, GLX_DOUBLEBUFFER, 1, GLX_STENCIL_SIZE, INT_MAX, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, 1, None }; fbConfig = mGLSupport->selectFBConfig(minAttribs, maxAttribs); if (gamma != 0) { mGLSupport->getFBConfigAttrib(fbConfig, GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &gamma); } mHwGamma = (gamma != 0); } if (! fbConfig) { // This should never happen. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a GLXFBConfig","GLXWindow::create"); } mIsTopLevel = (! mIsExternal && parentWindow == DefaultRootWindow(xDisplay)); if (! mIsTopLevel) { mIsFullScreen = false; left = top = 0; } if (mIsFullScreen) { mGLSupport->switchMode (width, height, frequency); } if (! mIsExternal) { XSetWindowAttributes attr; ulong mask; XVisualInfo *visualInfo = mGLSupport->getVisualFromFBConfig (fbConfig); attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap(xDisplay, DefaultRootWindow(xDisplay), visualInfo->visual, AllocNone); attr.event_mask = StructureNotifyMask | VisibilityChangeMask | FocusChangeMask; mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; if(mIsFullScreen && mGLSupport->mAtomFullScreen == None) { LogManager::getSingleton().logMessage("GLXWindow::switchFullScreen: Your WM has no fullscreen support"); // A second best approach for outdated window managers attr.backing_store = NotUseful; attr.save_under = False; attr.override_redirect = True; mask |= CWSaveUnder | CWBackingStore | CWOverrideRedirect; left = top = 0; } // Create window on server mWindow = XCreateWindow(xDisplay, parentWindow, left, top, width, height, 0, visualInfo->depth, InputOutput, visualInfo->visual, mask, &attr); XFree(visualInfo); if(!mWindow) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to create an X Window", "GLXWindow::create"); } if (mIsTopLevel) { XWMHints *wmHints; XSizeHints *sizeHints; if ((wmHints = XAllocWMHints()) != NULL) { wmHints->initial_state = NormalState; wmHints->input = True; wmHints->flags = StateHint | InputHint; int depth = DisplayPlanes(xDisplay, DefaultScreen(xDisplay)); // Check if we can give it an icon if(depth == 24 || depth == 32) { if(mGLSupport->loadIcon("GLX_icon.png", &wmHints->icon_pixmap, &wmHints->icon_mask)) { wmHints->flags |= IconPixmapHint | IconMaskHint; } } } // Is this really necessary ? Which broken WM might need it? if ((sizeHints = XAllocSizeHints()) != NULL) { sizeHints->flags = USPosition; } XTextProperty titleprop; char *lst = (char*)title.c_str(); XStringListToTextProperty((char **)&lst, 1, &titleprop); XSetWMProperties(xDisplay, mWindow, &titleprop, NULL, NULL, 0, sizeHints, wmHints, NULL); XFree(titleprop.value); XFree(wmHints); XFree(sizeHints); XSetWMProtocols(xDisplay, mWindow, &mGLSupport->mAtomDeleteWindow, 1); XWindowAttributes windowAttrib; XGetWindowAttributes(xDisplay, mWindow, &windowAttrib); left = windowAttrib.x; top = windowAttrib.y; width = windowAttrib.width; height = windowAttrib.height; } glxDrawable = mWindow; // setHidden takes care of mapping or unmapping the window // and also calls setFullScreen if appropriate. setHidden(hidden); XFlush(xDisplay); WindowEventUtilities::_addRenderWindow(this); } mContext = new GLXContext(mGLSupport, fbConfig, glxDrawable, glxContext); // apply vsync settings. call setVSyncInterval first to avoid // setting vsync more than once. setVSyncInterval(vsyncInterval); setVSyncEnabled(vsync); int fbConfigID; mGLSupport->getFBConfigAttrib(fbConfig, GLX_FBCONFIG_ID, &fbConfigID); LogManager::getSingleton().logMessage("GLXWindow::create used FBConfigID = " + StringConverter::toString(fbConfigID)); mName = name; mWidth = width; mHeight = height; mLeft = left; mTop = top; mActive = true; mClosed = false; }
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow, X11Display &rDisplay, bool dragDrop, bool playOnDrop, X11Window *pParentWindow, GenericWindow::WindowType_t type ): OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ), m_dragDrop( dragDrop ), m_pDropTarget( NULL ), m_type ( type ) { XSetWindowAttributes attr; unsigned long valuemask; std::string name_type; if( type == GenericWindow::FullscreenWindow ) { m_wnd_parent = DefaultRootWindow( XDISPLAY ); int i_screen = DefaultScreen( XDISPLAY ); attr.event_mask = ExposureMask | StructureNotifyMask; attr.background_pixel = BlackPixel( XDISPLAY, i_screen ); attr.backing_store = Always; valuemask = CWBackingStore | CWBackPixel | CWEventMask; if( NET_WM_STATE_FULLSCREEN == None ) { attr.override_redirect = True; valuemask = valuemask | CWOverrideRedirect; } name_type = "Fullscreen"; } else if( type == GenericWindow::VoutWindow ) { m_wnd_parent = pParentWindow->m_wnd; int i_screen = DefaultScreen( XDISPLAY ); attr.event_mask = ExposureMask | StructureNotifyMask; attr.backing_store = Always; attr.background_pixel = BlackPixel( XDISPLAY, i_screen ); valuemask = CWBackingStore | CWBackPixel | CWEventMask; name_type = "VoutWindow"; } else if( type == GenericWindow::FscWindow ) { m_wnd_parent = DefaultRootWindow( XDISPLAY ); attr.event_mask = ExposureMask | StructureNotifyMask; valuemask = CWEventMask; name_type = "FscWindow"; } else { m_wnd_parent = DefaultRootWindow( XDISPLAY ); attr.event_mask = ExposureMask | StructureNotifyMask; valuemask = CWEventMask; name_type = "TopWindow"; } // Create the window m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 10, 10, 0, 0, InputOutput, CopyFromParent, valuemask, &attr ); // wait for X server to process the previous commands XSync( XDISPLAY, false ); // Set the colormap for 8bpp mode if( XPIXELSIZE == 1 ) { XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() ); } // Select events received by the window long event_mask; if( type == GenericWindow::VoutWindow ) { event_mask = ExposureMask|KeyPressMask| LeaveWindowMask|FocusChangeMask; } else { event_mask = ExposureMask|KeyPressMask| PointerMotionMask|ButtonPressMask|ButtonReleaseMask| LeaveWindowMask|FocusChangeMask; } XSelectInput( XDISPLAY, m_wnd, event_mask ); // Store a pointer on the generic window in a map X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() ); pFactory->m_windowMap[m_wnd] = &rWindow; // Changing decorations struct { unsigned long flags; unsigned long functions; unsigned long decorations; signed long input_mode; unsigned long status; } motifWmHints; Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False ); motifWmHints.flags = 2; // MWM_HINTS_DECORATIONS; motifWmHints.decorations = 0; XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32, PropModeReplace, (unsigned char *)&motifWmHints, sizeof( motifWmHints ) / sizeof( uint32_t ) ); // Drag & drop if( m_dragDrop ) { // Create a Dnd object for this window m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd, playOnDrop, &rWindow ); // Register the window as a drop target Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False ); char xdndVersion = 4; XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&xdndVersion, 1 ); // Store a pointer to be used in X11Loop pFactory->m_dndMap[m_wnd] = m_pDropTarget; } // Change the window title std::string name_window = "VLC (" + name_type + ")"; XStoreName( XDISPLAY, m_wnd, name_window.c_str() ); // Set the WM_TRANSIENT_FOR property if( type == GenericWindow::FscWindow ) { // Associate the fsc window to the fullscreen window VoutManager* pVoutManager = VoutManager::instance( getIntf() ); GenericWindow* pWin = pVoutManager->getVoutMainWindow(); Window wnd = (Window) pWin->getOSHandle(); XSetTransientForHint( XDISPLAY, m_wnd, wnd ); } else { // Associate the regular top-level window to the offscren main window XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() ); } // initialize Class Hint XClassHint classhint; classhint.res_name = (char*) "vlc"; classhint.res_class = (char*) "Vlc"; XSetClassHint( XDISPLAY, m_wnd, &classhint ); // copies WM_HINTS from the main window XWMHints *wm = XGetWMHints( XDISPLAY, m_rDisplay.getMainWindow() ); if( wm ) { XSetWMHints( XDISPLAY, m_wnd, wm ); XFree( wm ); } // initialize WM_CLIENT_MACHINE char* hostname = NULL; long host_name_max = sysconf( _SC_HOST_NAME_MAX ); if( host_name_max <= 0 ) host_name_max = _POSIX_HOST_NAME_MAX; hostname = new (std::nothrow) char[host_name_max]; if( hostname && gethostname( hostname, host_name_max ) == 0 ) { hostname[host_name_max - 1] = '\0'; XTextProperty textprop; textprop.value = (unsigned char *) hostname; textprop.encoding = XA_STRING; textprop.format = 8; textprop.nitems = strlen( hostname ); XSetWMClientMachine( XDISPLAY, m_wnd, &textprop); } delete[] hostname; // initialize EWMH pid pid_t pid = getpid(); assert( NET_WM_PID != None ); XChangeProperty( XDISPLAY, m_wnd, NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1 ); if( NET_WM_WINDOW_TYPE != None ) { if( type == GenericWindow::FullscreenWindow ) { // Some Window Managers like Gnome3 limit fullscreen to the // subarea outside the task bar if no window type is provided. // For those WMs, setting type window to normal ensures a clean // 100% fullscreen XChangeProperty( XDISPLAY, m_wnd, NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, (unsigned char *)&NET_WM_WINDOW_TYPE_NORMAL, 1 ); } } }
const QRect XfitMan::availableGeometry(int screen) const { QDesktopWidget *d = QApplication::desktop(); if (screen < 0 || screen >= d->screenCount()) screen = d->primaryScreen(); QRect available = d->screenGeometry(screen); // Iterate over all the client windows and subtract from the available // area the space they reserved on the edges (struts). // Note: _NET_WORKAREA is not reliable as it exposes only one // rectangular area spanning all screens. Display *display = QX11Info::display(); int x11Screen = d->isVirtualDesktop() ? DefaultScreen(display) : screen; Atom ret; int format, status; uchar* data = 0; ulong nitems, after; status = XGetWindowProperty(display, QX11Info::appRootWindow(x11Screen), atom("_NET_CLIENT_LIST"), 0L, ~0L, False, XA_WINDOW, &ret, &format, &nitems, &after, &data); if (status == Success && ret == XA_WINDOW && format == 32 && nitems) { const QRect desktopGeometry = d->rect(); Window* xids = (Window*) data; for (quint32 i = 0; i < nitems; ++i) { ulong nitems2; uchar* data2 = 0; status = XGetWindowProperty(display, xids[i], atom("_NET_WM_STRUT_PARTIAL"), 0, 12, False, XA_CARDINAL, &ret, &format, &nitems2, &after, &data2); if (status == Success && ret == XA_CARDINAL && format == 32 && nitems2 == 12) { ulong* struts = (ulong*) data2; QRect left(desktopGeometry.x(), desktopGeometry.y() + struts[4], struts[0], struts[5] - struts[4]); if (available.intersects(left)) available.setX(left.width()); QRect right(desktopGeometry.x() + desktopGeometry.width() - struts[1], desktopGeometry.y() + struts[6], struts[1], struts[7] - struts[6]); if (available.intersects(right)) available.setWidth(right.x() - available.x()); QRect top(desktopGeometry.x() + struts[8], desktopGeometry.y(), struts[9] - struts[8], struts[2]); if (available.intersects(top)) available.setY(top.height()); QRect bottom(desktopGeometry.x() + struts[10], desktopGeometry.y() + desktopGeometry.height() - struts[3], struts[11] - struts[10], struts[3]); if (available.intersects(bottom)) available.setHeight(bottom.y() - available.y()); } if (data2) XFree(data2); } } if (data) XFree(data); return available; }
int main(int argc, char **argv){ Display *dpy; Window w, quit, clearButton, drawButton; Window root; struct timespec wait; int screen; unsigned long black, white; GC gc; XEvent e; float t; int isDraw; int pointNum; int i; XPoint usrPoints[20]; XPoint bufPoints[20]; XPoint selectedPoints[20]; //*************************************init**** dpy = XOpenDisplay(""); root = DefaultRootWindow (dpy); screen = DefaultScreen (dpy); white = WhitePixel (dpy, screen); black = BlackPixel (dpy, screen); w = XCreateSimpleWindow(dpy, root, 100, 100, WIDTH, HEIGHT, BORDER, black, white); /* Make Buttons */ quit = XCreateSimpleWindow(dpy, w, 10, 3, 30, 12, BORDER, black, white); clearButton = XCreateSimpleWindow(dpy, w, 52, 3, 37, 12, BORDER, black, white); drawButton = XCreateSimpleWindow(dpy, w, 100, 3, 35, 12, BORDER, black, white); gc = XCreateGC(dpy, w, 0, NULL); pointNum = 0; isDraw = 0; t = 0; wait.tv_sec = 0; wait.tv_nsec = NANOTIME; for (i = 0; i < 20; i++) { usrPoints[i].x = 0; usrPoints[i].y = 0; bufPoints[i].x = 0; bufPoints[i].y = 0; } //********************************************* XSelectInput(dpy, w, ButtonPressMask | ExposureMask); XSelectInput(dpy, quit, ButtonPressMask); XSelectInput(dpy, clearButton, ButtonPressMask); XSelectInput(dpy, drawButton, ButtonPressMask); XMapWindow(dpy, w); XMapSubwindows(dpy, w); XSetForeground(dpy, gc, white); XSetForeground(dpy, gc, black); //*************************************loop**** while(1){ if(XEventsQueued(dpy, QueuedAfterReading)){ XDrawString(dpy, quit, gc, 4, 10, "Exit", 4); XDrawString(dpy, clearButton, gc, 4, 10, "Clear", 5); XDrawString(dpy, drawButton, gc, 4, 10, "Draw", 4); //***********************************event**** XNextEvent(dpy, &e); switch(e.type){ case ButtonPress : if (e.xany.window == quit) { return 0; } else if (e.xany.window == clearButton) { XClearWindow(dpy, w); t = 0; isDraw = 0; pointNum = 0; } else if (e.xany.window == drawButton) { if (!pointNum) break; isDraw = 1; } else { if (0 < t && t < 1) XClearWindow(dpy, w); selectedPoints[pointNum].x = e.xbutton.x; selectedPoints[pointNum].y = e.xbutton.y; bufPoints[pointNum] = selectedPoints[pointNum]; pointNum++; drawPointDetail(dpy, w, gc, bufPoints, pointNum); isDraw = 0; t = 0; } break; case Expose: drawPointDetail(dpy, w, gc, bufPoints, pointNum); isDraw = 0; t = 0; } } else { //********************************animation**** if (t < 1 && isDraw) { nanosleep(&wait, NULL); drawBeizerCurve(dpy, w, gc, selectedPoints, bufPoints, t, pointNum); t += 0.00001; } else if (t >= 1 && isDraw) { isDraw = 0; } } XFlush(dpy); } return 0; }
void X11OpenGLWindow::enableOpenGL() { if (forceOpenGL3) { // Get the default screen's GLX extension list const char *glxExts = glXQueryExtensionsString( m_data->m_dpy, DefaultScreen( m_data->m_dpy ) ); // NOTE: It is not necessary to create or make current to a context before // calling glXGetProcAddressARB, unless we dynamically load OpenGL/GLX/X11 glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" ); GLXContext ctx = 0; // Install an X error handler so the application won't exit if GL 3.0 // context allocation fails. // // Note this error handler is global. All display connections in all threads // of a process use the same error handler, so be sure to guard against other // threads issuing X commands while this code is running. ctxErrorOccurred = false; int (*oldHandler)(Display*, XErrorEvent*) = MyXSetErrorHandler(&ctxErrorHandler); // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. if ( !isExtensionSupported( glxExts, "GLX_ARB_create_context" ) || !glXCreateContextAttribsARB ) { printf( "glXCreateContextAttribsARB() not found" " ... using old-style GLX context\n" ); ctx = glXCreateNewContext( m_data->m_dpy, m_data->m_bestFbc, GLX_RGBA_TYPE, 0, True ); } // If it does, try to get a GL 3.0 context! else { int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB ,3, GLX_CONTEXT_MINOR_VERSION_ARB, 2, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,None }; /* int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 2, //GLX_CONTEXT_FLAGS_ARB , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; */ printf( "Creating context\n" ); ctx = glXCreateContextAttribsARB( m_data->m_dpy, m_data->m_bestFbc, 0, True, context_attribs ); // Sync to ensure any errors generated are processed. MyXSync( m_data->m_dpy, False ); if ( !ctxErrorOccurred && ctx ) printf( "Created GL 3.0 context\n" ); else { // Couldn't create GL 3.0 context. Fall back to old-style 2.x context. // When a context version below 3.0 is requested, implementations will // return the newest context version compatible with OpenGL versions less // than version 3.0. // GLX_CONTEXT_MAJOR_VERSION_ARB = 1 context_attribs[1] = 1; // GLX_CONTEXT_MINOR_VERSION_ARB = 0 context_attribs[3] = 0; ctxErrorOccurred = false; printf( "Failed to create GL 3.0 context" " ... using old-style GLX context\n" ); ctx = glXCreateContextAttribsARB( m_data->m_dpy, m_data->m_bestFbc, 0, True, context_attribs ); } } // Sync to ensure any errors generated are processed. MyXSync( m_data->m_dpy, False ); // Restore the original error handler MyXSetErrorHandler( oldHandler ); if ( ctxErrorOccurred || !ctx ) { printf( "Failed to create an OpenGL context\n" ); exit(1); } // Verifying that context is a direct context if ( ! glXIsDirect ( m_data->m_dpy, ctx ) ) { printf( "Indirect GLX rendering context obtained\n" ); } else { printf( "Direct GLX rendering context obtained\n" ); } printf( "Making context current\n" ); glXMakeCurrent( m_data->m_dpy, m_data->m_win, ctx ); } else { m_data->m_glc = glXCreateContext(m_data->m_dpy, m_data->m_vi, NULL, GL_TRUE); glXMakeCurrent(m_data->m_dpy, m_data->m_win, m_data->m_glc); } #ifdef GLEW_INIT_OPENGL11_FUNCTIONS { GLboolean res = glewOpenGL11Init(); if (res==0) { printf("glewOpenGL11Init OK!\n"); } else { printf("ERROR: glewOpenGL11Init failed, exiting!\n"); exit(0); } } #endif //GLEW_INIT_OPENGL11_FUNCTIONS const GLubyte* ven = glGetString(GL_VENDOR); printf("GL_VENDOR=%s\n", ven); const GLubyte* ren = glGetString(GL_RENDERER); printf("GL_RENDERER=%s\n",ren); const GLubyte* ver = glGetString(GL_VERSION); printf("GL_VERSION=%s\n", ver); const GLubyte* sl = glGetString(GL_SHADING_LANGUAGE_VERSION); printf("GL_SHADING_LANGUAGE_VERSION=%s\n", sl); //Access pthreads as a workaround for a bug in Linux/Ubuntu //See https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-319/+bug/1248642 int i=pthread_getconcurrency(); printf("pthread_getconcurrency()=%d\n",i); // const GLubyte* ext = glGetString(GL_EXTENSIONS); // printf("GL_EXTENSIONS=%s\n", ext); }
/* ** GLW_SetMode */ int GLW_SetMode( const char *drivername, int mode, qboolean fullscreen ) { int attrib[] = { GLX_RGBA, // 0 GLX_RED_SIZE, 4, // 1, 2 GLX_GREEN_SIZE, 4, // 3, 4 GLX_BLUE_SIZE, 4, // 5, 6 GLX_DOUBLEBUFFER, // 7 GLX_DEPTH_SIZE, 1, // 8, 9 GLX_STENCIL_SIZE, 1, // 10, 11 None }; // these match in the array #define ATTR_RED_IDX 2 #define ATTR_GREEN_IDX 4 #define ATTR_BLUE_IDX 6 #define ATTR_DEPTH_IDX 9 #define ATTR_STENCIL_IDX 11 Window root; XVisualInfo *visinfo; XSetWindowAttributes attr; XSizeHints sizehints; unsigned long mask; int colorbits, depthbits, stencilbits; int tcolorbits, tdepthbits, tstencilbits; int dga_MajorVersion, dga_MinorVersion; int actualWidth, actualHeight; int i; const char* glstring; // bk001130 - from cvs1.17 (mkv) ri.Printf( PRINT_ALL, "Initializing OpenGL display\n"); ri.Printf (PRINT_ALL, "...setting mode %d:", mode ); if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) ) { ri.Printf( PRINT_ALL, " invalid mode\n" ); return RSERR_INVALID_MODE; } ri.Printf( PRINT_ALL, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight); if (!(dpy = XOpenDisplay(NULL))) { fprintf(stderr, "Error couldn't open the X display\n"); return RSERR_INVALID_MODE; } scrnum = DefaultScreen(dpy); root = RootWindow(dpy, scrnum); actualWidth = glConfig.vidWidth; actualHeight = glConfig.vidHeight; // Get video mode list #ifdef HAVE_XF86DGA if (!XF86VidModeQueryVersion(dpy, &vidmode_MajorVersion, &vidmode_MinorVersion)) { #endif /* HAVE_XF86DGA */ vidmode_ext = qfalse; #ifdef HAVE_XF86DGA } else { ri.Printf(PRINT_ALL, "Using XFree86-VidModeExtension Version %d.%d\n", vidmode_MajorVersion, vidmode_MinorVersion); vidmode_ext = qtrue; } #endif /* HAVE_XF86DGA */ // Check for DGA dga_MajorVersion = 0, dga_MinorVersion = 0; #ifdef HAVE_XF86DGA if (in_dgamouse->value) { if (!XF86DGAQueryVersion(dpy, &dga_MajorVersion, &dga_MinorVersion)) { // unable to query, probably not supported ri.Printf( PRINT_ALL, "Failed to detect XF86DGA Mouse\n" ); ri.Cvar_Set( "in_dgamouse", "0" ); } else { ri.Printf( PRINT_ALL, "XF86DGA Mouse (Version %d.%d) initialized\n", dga_MajorVersion, dga_MinorVersion); } } #endif /* HAVE_XF86DGA */ #ifdef HAVE_XF86DGA if (vidmode_ext) { int best_fit, best_dist, dist, x, y; XF86VidModeGetAllModeLines(dpy, scrnum, &num_vidmodes, &vidmodes); // Are we going fullscreen? If so, let's change video mode if (fullscreen) { best_dist = 9999999; best_fit = -1; for (i = 0; i < num_vidmodes; i++) { if (glConfig.vidWidth > vidmodes[i]->hdisplay || glConfig.vidHeight > vidmodes[i]->vdisplay) continue; x = glConfig.vidWidth - vidmodes[i]->hdisplay; y = glConfig.vidHeight - vidmodes[i]->vdisplay; dist = (x * x) + (y * y); if (dist < best_dist) { best_dist = dist; best_fit = i; } } if (best_fit != -1) { actualWidth = vidmodes[best_fit]->hdisplay; actualHeight = vidmodes[best_fit]->vdisplay; // change to the mode XF86VidModeSwitchToMode(dpy, scrnum, vidmodes[best_fit]); vidmode_active = qtrue; // Move the viewport to top left XF86VidModeSetViewPort(dpy, scrnum, 0, 0); ri.Printf(PRINT_ALL, "XFree86-VidModeExtension Activated at %dx%d\n", actualWidth, actualHeight); } else { fullscreen = 0; ri.Printf(PRINT_ALL, "XFree86-VidModeExtension: No acceptable modes found\n"); } } else { ri.Printf(PRINT_ALL, "XFree86-VidModeExtension: Ignored on non-fullscreen/Voodoo\n"); } } #endif /* HAVE_XF86DGA */ if (!r_colorbits->value) colorbits = 24; else colorbits = r_colorbits->value; if ( !Q_stricmp( r_glDriver->string, _3DFX_DRIVER_NAME ) ) colorbits = 16; if (!r_depthbits->value) depthbits = 24; else depthbits = r_depthbits->value; stencilbits = r_stencilbits->value; for (i = 0; i < 16; i++) { // 0 - default // 1 - minus colorbits // 2 - minus depthbits // 3 - minus stencil if ((i % 4) == 0 && i) { // one pass, reduce switch (i / 4) { case 2 : if (colorbits == 24) colorbits = 16; break; case 1 : if (depthbits == 24) depthbits = 16; else if (depthbits == 16) depthbits = 8; case 3 : if (stencilbits == 24) stencilbits = 16; else if (stencilbits == 16) stencilbits = 8; } } tcolorbits = colorbits; tdepthbits = depthbits; tstencilbits = stencilbits; if ((i % 4) == 3) { // reduce colorbits if (tcolorbits == 24) tcolorbits = 16; } if ((i % 4) == 2) { // reduce depthbits if (tdepthbits == 24) tdepthbits = 16; else if (tdepthbits == 16) tdepthbits = 8; } if ((i % 4) == 1) { // reduce stencilbits if (tstencilbits == 24) tstencilbits = 16; else if (tstencilbits == 16) tstencilbits = 8; else tstencilbits = 0; } if (tcolorbits == 24) { attrib[ATTR_RED_IDX] = 8; attrib[ATTR_GREEN_IDX] = 8; attrib[ATTR_BLUE_IDX] = 8; } else { // must be 16 bit attrib[ATTR_RED_IDX] = 4; attrib[ATTR_GREEN_IDX] = 4; attrib[ATTR_BLUE_IDX] = 4; } attrib[ATTR_DEPTH_IDX] = tdepthbits; // default to 24 depth attrib[ATTR_STENCIL_IDX] = tstencilbits; visinfo = qglXChooseVisual(dpy, scrnum, attrib); if (!visinfo) { continue; } ri.Printf( PRINT_ALL, "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n", attrib[ATTR_RED_IDX], attrib[ATTR_GREEN_IDX], attrib[ATTR_BLUE_IDX], attrib[ATTR_DEPTH_IDX], attrib[ATTR_STENCIL_IDX]); glConfig.colorBits = tcolorbits; glConfig.depthBits = tdepthbits; glConfig.stencilBits = tstencilbits; break; } if (!visinfo) { ri.Printf( PRINT_ALL, "Couldn't get a visual\n" ); return RSERR_INVALID_MODE; } /* window attributes */ attr.background_pixel = BlackPixel(dpy, scrnum); attr.border_pixel = 0; attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone); attr.event_mask = X_MASK; if (vidmode_active) { mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect; attr.override_redirect = True; attr.backing_store = NotUseful; attr.save_under = False; } else mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; win = XCreateWindow(dpy, root, 0, 0, actualWidth, actualHeight, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr); XStoreName( dpy, win, CLIENT_WINDOW_TITLE ); /* GH: Don't let the window be resized */ sizehints.flags = PMinSize | PMaxSize; sizehints.min_width = sizehints.max_width = actualWidth; sizehints.min_height = sizehints.max_height = actualHeight; XSetWMNormalHints( dpy, win, &sizehints ); XMapWindow( dpy, win ); if (vidmode_active) XMoveWindow(dpy, win, 0, 0); XFlush(dpy); XSync(dpy,False); // bk001130 - from cvs1.17 (mkv) ctx = qglXCreateContext(dpy, visinfo, NULL, True); XSync(dpy,False); // bk001130 - from cvs1.17 (mkv) /* GH: Free the visinfo after we're done with it */ XFree( visinfo ); qglXMakeCurrent(dpy, win, ctx); // bk001130 - from cvs1.17 (mkv) glstring = (char *)qglGetString (GL_RENDERER); ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glstring ); // bk010122 - new software token (Indirect) if ( !Q_stricmp( glstring, "Mesa X11") || !Q_stricmp( glstring, "Mesa GLX Indirect") ) { if ( !r_allowSoftwareGL->integer ) { ri.Printf( PRINT_ALL, "\n\n***********************************************************\n" ); ri.Printf( PRINT_ALL, " You are using software Mesa (no hardware acceleration)! \n" ); ri.Printf( PRINT_ALL, " Driver DLL used: %s\n", drivername ); ri.Printf( PRINT_ALL, " If this is intentional, add\n" ); ri.Printf( PRINT_ALL, " \"+set r_allowSoftwareGL 1\"\n" ); ri.Printf( PRINT_ALL, " to the command line when starting the game.\n" ); ri.Printf( PRINT_ALL, "***********************************************************\n"); GLimp_Shutdown( ); return RSERR_INVALID_MODE; } else { ri.Printf( PRINT_ALL, "...using software Mesa (r_allowSoftwareGL==1).\n" ); } } return RSERR_OK; }
void X11OpenGLWindow::createWindow(const b3gWindowConstructionInfo& ci) { m_data->m_dpy = MyXOpenDisplay(NULL); if(m_data->m_dpy == NULL) { printf("\n\tcannot connect to X server\n\n"); exit(0); } m_data->m_root = DefaultRootWindow(m_data->m_dpy); #ifdef GLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS GLboolean res = glewXInit(); if (res==0) { printf("glewXInit OK\n"); } else { printf("glewXInit failed, exit\n"); exit(0); } #endif //GLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS if (ci.m_openglVersion < 3) { forceOpenGL3 = false; } if (forceOpenGL3) { int glxMinor, glxMajor; if (!glXQueryVersion(m_data->m_dpy,&glxMajor,&glxMinor) || (((glxMajor==1)&&(glxMinor<3)) || (glxMajor<1))) { printf("Invalid GLX version: major %d, minor %d\n",glxMajor,glxMinor); exit(0); } static int visual_attribs[] = { GLX_X_RENDERABLE , True, GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR, GLX_RED_SIZE , 8, GLX_GREEN_SIZE , 8, GLX_BLUE_SIZE , 8, GLX_ALPHA_SIZE , 8, GLX_DEPTH_SIZE , 24, GLX_STENCIL_SIZE , 8, GLX_DOUBLEBUFFER , True, None }; int fbcount; GLXFBConfig* fbc = glXChooseFBConfig(m_data->m_dpy, DefaultScreen(m_data->m_dpy), visual_attribs, &fbcount); if (!fbc) { printf( "Failed to retrieve a framebuffer config\n" ); exit(1); } ///don't use highest samples, it is really slow on some NVIDIA Quadro cards #ifdef USE_HIGHEST_SAMPLES int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; int i; for (i=0; i<fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig( m_data->m_dpy, fbc[i] ); if ( vi ) { int samp_buf, samples; glXGetFBConfigAttrib( m_data->m_dpy, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf ); glXGetFBConfigAttrib( m_data->m_dpy, fbc[i], GLX_SAMPLES , &samples ); //printf( " Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d," // " SAMPLES = %d\n", // i, vi -> visualid, samp_buf, samples ); if ( best_fbc < 0 || (samp_buf && (samples > best_num_samp)) ) best_fbc = i, best_num_samp = samples; if ( worst_fbc < 0 || (!samp_buf || (samples < worst_num_samp)) ) worst_fbc = i, worst_num_samp = samples; } MyXFree( vi ); } m_data->m_bestFbc = fbc[ best_fbc ]; #else m_data->m_bestFbc = *fbc; #endif // Be sure to free the FBConfig list allocated by glXChooseFBConfig() MyXFree( fbc ); m_data->m_vi = glXGetVisualFromFBConfig( m_data->m_dpy, m_data->m_bestFbc ); m_data->m_swa.colormap = m_data->m_cmap = MyXCreateColormap( m_data->m_dpy, RootWindow( m_data->m_dpy, m_data->m_vi->screen ), m_data->m_vi->visual, AllocNone ); m_data->m_swa.background_pixmap = None ; m_data->m_swa.border_pixel = 0; m_data->m_swa.event_mask = ExposureMask | KeyReleaseMask | KeyPressMask |ButtonPressMask | ButtonReleaseMask |PointerMotionMask|StructureNotifyMask; ; m_data->m_root = RootWindow( m_data->m_dpy, m_data->m_vi->screen ); m_data->m_win = MyXCreateWindow( m_data->m_dpy, m_data->m_root, 0, 0, ci.m_width, ci.m_height, 0, m_data->m_vi->depth, InputOutput, m_data->m_vi->visual, CWBorderPixel|CWColormap|CWEventMask, &m_data->m_swa ); //m_data->m_win = m_data->m_x11_XCreateWindow(m_data->m_dpy, m_data->m_root, 0, 0, ci.m_width, ci.m_height, 0, m_data->m_vi->depth, InputOutput, m_data->m_vi->visual, CWColormap | CWEventMask, &m_data->m_swa); if (!m_data->m_win) { printf("Cannot create window\n"); exit(0); } MyXMapWindow(m_data->m_dpy, m_data->m_win); MyXStoreName(m_data->m_dpy, m_data->m_win, "OpenGL3 Window"); } else { m_data->m_vi = glXChooseVisual(m_data->m_dpy, 0, att); printf("4\n"); if(m_data->m_vi == NULL) { printf("\n\tno appropriate visual found\n\n"); exit(0); } else { printf("\n\tvisual %p selected\n", (void *)m_data->m_vi->visualid); /* %p creates hexadecimal output like in glxinfo */ } m_data->m_cmap = MyXCreateColormap(m_data->m_dpy, m_data->m_root, m_data->m_vi->visual, AllocNone); m_data->m_swa.colormap = m_data->m_cmap; m_data->m_swa.event_mask = ExposureMask | KeyReleaseMask | KeyPressMask |ButtonPressMask | ButtonReleaseMask |PointerMotionMask|StructureNotifyMask; m_data->m_win = MyXCreateWindow(m_data->m_dpy, m_data->m_root, 0, 0, ci.m_width, ci.m_height, 0, m_data->m_vi->depth, InputOutput, m_data->m_vi->visual, CWColormap | CWEventMask, &m_data->m_swa); MyXMapWindow(m_data->m_dpy, m_data->m_win); MyXStoreName(m_data->m_dpy, m_data->m_win, "OpenGL2 Window"); } enableOpenGL(); }
int main() { XTextProperty title; XEvent event; XSizeHints *hints; XWMHints *wm_hints; KeySym key; Pixmap pix; pthread_t thread; /* grepare toPlot function */ spline_init(); /* visual routines */ int pressed_1[3] = {0, 0, 0}; // pressed state of button1: condition and coordinates char *caption = "Interpolation"; char *dpy_str = getenv("DISPLAY"); fprintf(stderr, "Connecting to %s\t ", dpy_str); dpy = XOpenDisplay(dpy_str); if( !dpy ) { fprintf(stderr, "Unable to connect\n"); exit(EXIT_FAILURE); } else { fprintf(stderr, "OK\n"); } scr = DefaultScreen(dpy); getColors(); width = 2 * DisplayWidth(dpy, scr) / 3; height = 2 * DisplayHeight(dpy, scr) / 3; win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr), 0, 0, width, height, 0, black, white ); XStringListToTextProperty(&caption, 1, &title); XSetWMName(dpy, win, &title); XSetWMIconName(dpy, win, &title); cont = XCreateGC(dpy, win, 0, NULL); if( cont<0 ) { fprintf(stderr, "XCReateGC: unable to set GC"); exit(EXIT_FAILURE); } /* making window unresizeable */ hints = XAllocSizeHints(); if( !hints ) { fprintf(stderr, "XAllocSizeHints: out of memory"); exit(EXIT_FAILURE); } hints->flags = PMaxSize | PMinSize; hints->min_width = width; hints->min_height = height; hints->max_width = width; hints->max_height = height; XSetWMNormalHints(dpy, win, hints); XFree(hints); /* setting icon */ pix = XCreateBitmapFromData(dpy, win, icon_bits, icon_width, icon_height); if( !pix ) { fprintf(stderr, "XCreateBitmapFromData: cannot create icon"); exit(EXIT_FAILURE); } wm_hints = XAllocWMHints(); if( !wm_hints ) { fprintf(stderr, "XAllocWMHints: out of memory"); exit(EXIT_FAILURE); } wm_hints->flags = IconPixmapHint | StateHint | IconPositionHint; wm_hints->icon_pixmap = pix; wm_hints->initial_state = IconicState; wm_hints->icon_x = 0; wm_hints->icon_y = 0; XSetWMHints(dpy, win, wm_hints); XFree(wm_hints); /* making window visible */ XMapWindow(dpy, win); draw(2,1); XSelectInput(dpy, win, ExposureMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask); while( 1 ) { XNextEvent(dpy, &event); switch( event.type ) { case Expose: if( event.xexpose.count>0 ) break; draw(0,1); XFlush(dpy); break; case KeyPress: XLookupString((XKeyEvent*) &event, NULL, 0, &key, NULL); /* moving window */ switch( key ) { case XK_Down: pthread_create(&thread, NULL, dec, (void*)&shift_y); break; case XK_Up: pthread_create(&thread, NULL, inc, (void*)&shift_y); break; case XK_Right: pthread_create(&thread, NULL, dec, (void*)&shift_x); break; case XK_Left: pthread_create(&thread, NULL, inc, (void*)&shift_x); break; case XK_plus: pthread_create(&thread, NULL, inc, (void*)&shift_pix); break; case XK_minus: pthread_create(&thread, NULL, dec, (void*)&shift_pix); break; case XK_equal: pthread_create(&thread, NULL, def, (void*)NULL); break; case XK_Escape: XCloseDisplay(dpy); exit(EXIT_SUCCESS); default: break; } break; case ButtonPress: switch( event.xbutton.button ) { case Button1: pressed_1[0]=1; pressed_1[1]=event.xmotion.x; pressed_1[2]=event.xmotion.y; break; default: break; } break; case ButtonRelease: switch( event.xbutton.button ) { case Button1: pressed_1[0]=0; break; default: break; } break; case MotionNotify: if( pressed_1[0] ) { /* if button_1 is pressed while moving */ draw(1,0); shift_x-=pressed_1[1]-event.xmotion.x; shift_y-=pressed_1[2]-event.xmotion.y; pressed_1[1]=event.xmotion.x; pressed_1[2]=event.xmotion.y; draw(1,1); } pos_x=event.xmotion.x; pos_y=event.xmotion.y; drawInfo(); break; default: break; } /* switch(event.type) */ } /* endless loop */ XCloseDisplay(dpy); return EXIT_SUCCESS; }
bool CWinSystemEGL::CreateNewWindow(const CStdString& name, bool fullScreen, RESOLUTION_INFO& res, PHANDLE_EVENT_FUNC userFunction) { #if defined(EMPOWER) && defined(HAS_OPENKODE) KDboolean b; KDDisplayModeNV mode; KDint desktopSize[2] = { res.iWidth, res.iHeight }; #endif #ifdef _WIN32 EGL_BASE_CLASS::CreateNewWindow(name, fullScreen, res, userFunction); #endif m_nWidth = res.iWidth; m_nHeight = res.iHeight; m_bFullScreen = fullScreen; EGLBoolean eglStatus; EGLint configCount; EGLConfig* configList = NULL; #if defined(EMPOWER) && defined(HAS_OPENKODE) //CLog::Log(LOGDEBUG, "NV: GetDisplay"); m_kdDisplay = kdGetDisplayNV(KD_DEFAULT_DISPLAY_NV, KD_NULL); if (!m_kdDisplay) { CLog::Log(LOGERROR, "Could not obtain KDDisplayNV pointer"); return false; } b = KD_FALSE; //CLog::Log(LOGDEBUG, "NV: SetDisplayProperty"); kdSetDisplayPropertybvNV(m_kdDisplay, KD_DISPLAYPROPERTY_ENABLED_NV, &b); kdReleaseDisplayNV(m_kdDisplay); // MZL: enable HDMI display //CLog::Log(LOGDEBUG, "NV: SetDisplayPropertybyNV"); kdSetDisplayPropertybvNV(m_kdDisplay, KD_DISPLAYPROPERTY_ENABLED_NV, &b); m_kdDisplay = kdGetDisplayNV("Tegra:HDMI0", KD_NULL); if (!m_kdDisplay) { CLog::Log(LOGERROR, "Could not obtain KDDisplayNV pointer"); return false; } b = KD_TRUE; kdSetDisplayPropertybvNV(m_kdDisplay, KD_DISPLAYPROPERTY_ENABLED_NV, &b); kdSetDisplayPropertycvNV(m_kdDisplay, KD_DISPLAYPROPERTY_DESKTOP_NAME_NV, KD_DEFAULT_DESKTOP_NV); mode.width = res.iWidth; mode.height = res.iHeight; mode.refresh = 60; //CLog::Log(LOGDEBUG, "NV: SetDisplayPropertyNV"); if (kdSetDisplayModeNV(m_kdDisplay, &mode, KD_DISPLAY_PROTOCOL_AUTOMATIC_NV)) { CLog::Log(LOGERROR, "Could not set display mode\n"); return false; } //CLog::Log(LOGDEBUG, "NV: GetDesktopNV"); m_kdDesktop = kdGetDesktopNV(KD_DEFAULT_DESKTOP_NV, KD_NULL); if (!m_kdDesktop) { CLog::Log(LOGERROR, "Could not obtain KDDesktopNV pointer"); return false; } //CLog::Log(LOGDEBUG, "NV: SetDesktopivNV"); if (kdSetDesktopPropertyivNV(m_kdDesktop, KD_DESKTOPPROPERTY_SIZE_NV, desktopSize)) { CLog::Log(LOGERROR, "Could not set desktop size"); return false; } #endif #ifdef HAS_X11 m_x11Display = XOpenDisplay(NULL); if (!m_x11Display) { CLog::Log(LOGERROR, "Could not open X11"); return false; } XSetErrorHandler(ApplicationErrorHandler) ; #endif //CLog::Log(LOGDEBUG, "eglGetDisplay"); #if defined(HAS_OPENKODE) || defined(HAS_GDL) m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); #elif defined(_WIN32) m_display = eglGetDisplay(m_hDC); #elif defined(HAS_X11) m_display = eglGetDisplay((EGLNativeDisplayType) m_x11Display); #endif if (m_display == EGL_NO_DISPLAY) { CLog::Log(LOGERROR, "EGL failed to obtain display"); return false; } //CLog::Log(LOGDEBUG, "eglInitialize"); if (!eglInitialize(m_display, 0, 0)) { CLog::Log(LOGERROR, "EGL failed to initialize"); return false; } EGLint configAttrs[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 8, EGL_SAMPLE_BUFFERS, 0, EGL_SAMPLES, 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; // Find out how many configurations suit our needs //CLog::Log(LOGDEBUG, "eglChooseConfig"); eglStatus = eglChooseConfig(m_display, configAttrs, NULL, 0, &configCount); if (!eglStatus || !configCount) { CLog::Log(LOGERROR, "EGL failed to return any matching configurations"); return false; } // Allocate room for the list of matching configurations configList = (EGLConfig*)malloc(configCount * sizeof(EGLConfig)); if (!configList) { CLog::Log(LOGERROR, "kdMalloc failure obtaining configuration list"); return false; } // Obtain the configuration list from EGL eglStatus = eglChooseConfig(m_display, configAttrs, configList, configCount, &configCount); if (!eglStatus || !configCount) { CLog::Log(LOGERROR, "EGL failed to populate configuration list"); return false; } // Select an EGL configuration that matches the native window m_config = configList[0]; EGLint* attribList = NULL; #ifdef EMPOWER EGLint windowAttrs[3]; int windowIndex = 0; windowAttrs[windowIndex++] = EGL_RENDER_BUFFER; windowAttrs[windowIndex++] = EGL_BACK_BUFFER; windowAttrs[windowIndex++] = EGL_NONE; attribList = windowAttrs; #endif #ifdef HAS_OPENKODE //CLog::Log(LOGDEBUG, "KD: kdCreateWindow"); m_kdWindow = kdCreateWindow(m_display, m_config, KD_NULL); if (!m_kdWindow) { CLog::Log(LOGERROR, "Error creating native window"); return false; } //CLog::Log(LOGDEBUG, "KD: kdRealizeWindow"); if (kdRealizeWindow(m_kdWindow, &m_nativeWindow)) { CLog::Log(LOGERROR, "Could not realize native window"); return false; } #elif defined HAS_X11 int screen = DefaultScreen(m_x11Display); XSetWindowAttributes windowAttributes; windowAttributes.colormap = DefaultColormap(m_x11Display, screen); windowAttributes.border_pixel = 0; windowAttributes.event_mask = ExposureMask | VisibilityChangeMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | SubstructureNotifyMask | FocusChangeMask; m_nativeWindow = (NativeWindowType) XCreateWindow( m_x11Display, RootWindow(m_x11Display, screen), 0, 0, // x/y position of top-left outside corner of the window res.iWidth, res.iHeight, // Width and height of window 0, // Border width DefaultDepth(m_x11Display, screen), InputOutput, DefaultVisual(m_x11Display, screen), CWBorderPixel | CWColormap | CWEventMask, &windowAttributes ); XSetStandardProperties(m_x11Display, (Window) m_nativeWindow, name, name, None, NULL, 0, NULL); Atom wmDeleteMessage = XInternAtom(m_x11Display, "WM_DELETE_WINDOW", False); XSetWMProtocols(m_x11Display, (Window) m_nativeWindow, &wmDeleteMessage, 1); if (fullScreen && !SetFullScreen(fullScreen, res, false)) { return false; } XMapRaised(m_x11Display, (Window) m_nativeWindow); #endif #ifdef _WIN32 m_nativeWindow = m_hWnd; DEVMODE dm; ZeroMemory(&dm, sizeof(dm)); dm.dmSize = sizeof(dm); EnumDisplaySettingsEx(NULL, ENUM_CURRENT_SETTINGS, &dm, 0); m_nLeft = (dm.dmPelsWidth / 2) - (m_nWidth / 2); m_nTop = (dm.dmPelsHeight / 2) - (m_nHeight / 2); RECT rc; rc.left = m_nLeft; rc.top = m_nTop; rc.right = rc.left + m_nWidth; rc.bottom = rc.top + m_nHeight; AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, false ); SetWindowPos(m_hWnd, 0, rc.left, rc.top, 0, 0, SWP_NOSIZE); #endif #if defined(HAS_GDL) m_nativeWindow = (NativeWindowType)GDL_GRAPHICS_PLANE; #endif m_surface = eglCreateWindowSurface(m_display, m_config, m_nativeWindow, attribList); if (!m_surface) { CLog::Log(LOGERROR, "EGL couldn't create window"); return false; } #ifdef CANMORE eglStatus = eglBindAPI(EGL_OPENGL_ES_API); if (!eglStatus) { CLog::Log(LOGERROR, "EGL failed to bind API"); return false; } #endif EGLint contextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; // Create an EGL context //CLog::Log(LOGDEBUG, "eglCreateContext"); m_context = eglCreateContext(m_display, m_config, NULL, contextAttrs); if (!m_context) { CLog::Log(LOGERROR, "EGL couldn't create context"); return false; } // Make the context and surface current for rendering eglStatus = eglMakeCurrent(m_display, m_surface, m_surface, m_context); if (!eglStatus) { CLog::Log(LOGERROR, "EGL couldn't make context/surface current"); return false; } free(configList); eglSwapInterval(m_display, 0); m_bWindowCreated = true; CLog::Log(LOGINFO, "Window creation complete"); return true; }
static CoglBool _cogl_winsys_egl_onscreen_init (CoglOnscreen *onscreen, EGLConfig egl_config, CoglError **error) { CoglFramebuffer *framebuffer = COGL_FRAMEBUFFER (onscreen); CoglContext *context = framebuffer->context; CoglDisplay *display = context->display; CoglRenderer *renderer = display->renderer; CoglRendererEGL *egl_renderer = renderer->winsys; CoglXlibRenderer *xlib_renderer = _cogl_xlib_renderer_get_data (renderer); CoglOnscreenXlib *xlib_onscreen; CoglOnscreenEGL *egl_onscreen = onscreen->winsys; Window xwin; /* FIXME: We need to explicitly Select for ConfigureNotify events. * For foreign windows we need to be careful not to mess up any * existing event mask. * We need to document that for windows we create then toolkits * must be careful not to clear event mask bits that we select. */ /* XXX: Note we ignore the user's original width/height when * given a foreign X window. */ if (onscreen->foreign_xid) { Status status; CoglXlibTrapState state; XWindowAttributes attr; int xerror; xwin = onscreen->foreign_xid; _cogl_xlib_renderer_trap_errors (display->renderer, &state); status = XGetWindowAttributes (xlib_renderer->xdpy, xwin, &attr); xerror = _cogl_xlib_renderer_untrap_errors (display->renderer, &state); if (status == 0 || xerror) { char message[1000]; XGetErrorText (xlib_renderer->xdpy, xerror, message, sizeof (message)); _cogl_set_error (error, COGL_WINSYS_ERROR, COGL_WINSYS_ERROR_CREATE_ONSCREEN, "Unable to query geometry of foreign " "xid 0x%08lX: %s", xwin, message); return FALSE; } _cogl_framebuffer_winsys_update_size (framebuffer, attr.width, attr.height); /* Make sure the app selects for the events we require... */ onscreen->foreign_update_mask_callback (onscreen, COGL_ONSCREEN_X11_EVENT_MASK, onscreen-> foreign_update_mask_data); } else { int width; int height; CoglXlibTrapState state; XVisualInfo *xvisinfo; XSetWindowAttributes xattr; unsigned long mask; int xerror; width = cogl_framebuffer_get_width (framebuffer); height = cogl_framebuffer_get_height (framebuffer); _cogl_xlib_renderer_trap_errors (display->renderer, &state); xvisinfo = get_visual_info (display, egl_config); if (xvisinfo == NULL) { _cogl_set_error (error, COGL_WINSYS_ERROR, COGL_WINSYS_ERROR_CREATE_ONSCREEN, "Unable to retrieve the X11 visual of context's " "fbconfig"); return FALSE; } /* window attributes */ xattr.background_pixel = WhitePixel (xlib_renderer->xdpy, DefaultScreen (xlib_renderer->xdpy)); xattr.border_pixel = 0; /* XXX: is this an X resource that we are leaking‽... */ xattr.colormap = XCreateColormap (xlib_renderer->xdpy, DefaultRootWindow (xlib_renderer->xdpy), xvisinfo->visual, AllocNone); xattr.event_mask = COGL_ONSCREEN_X11_EVENT_MASK; mask = CWBorderPixel | CWColormap | CWEventMask; xwin = XCreateWindow (xlib_renderer->xdpy, DefaultRootWindow (xlib_renderer->xdpy), 0, 0, width, height, 0, xvisinfo->depth, InputOutput, xvisinfo->visual, mask, &xattr); XFree (xvisinfo); XSync (xlib_renderer->xdpy, False); xerror = _cogl_xlib_renderer_untrap_errors (display->renderer, &state); if (xerror) { char message[1000]; XGetErrorText (xlib_renderer->xdpy, xerror, message, sizeof (message)); _cogl_set_error (error, COGL_WINSYS_ERROR, COGL_WINSYS_ERROR_CREATE_ONSCREEN, "X error while creating Window for CoglOnscreen: %s", message); return FALSE; } } xlib_onscreen = g_slice_new (CoglOnscreenXlib); egl_onscreen->platform = xlib_onscreen; xlib_onscreen->xwin = xwin; xlib_onscreen->is_foreign_xwin = onscreen->foreign_xid ? TRUE : FALSE; egl_onscreen->egl_surface = eglCreateWindowSurface (egl_renderer->edpy, egl_config, (NativeWindowType) xlib_onscreen->xwin, NULL); return TRUE; }
bool CIrrDeviceLinux::createWindow(const core::dimension2d<s32>& windowSize, u32 bits) { Width = windowSize.Width; Height = windowSize.Height; #ifdef _IRR_COMPILE_WITH_X11_ #ifdef _DEBUG os::Printer::log("Creating X window...", ELL_INFORMATION); XSetErrorHandler(IrrPrintXError); #endif display = XOpenDisplay(0); if (!display) { os::Printer::log("Error: Need running XServer to start Irrlicht Engine.", ELL_ERROR); return false; } screennr = DefaultScreen(display); // query extension if (Fullscreen) { s32 eventbase, errorbase; s32 bestMode = -1; s32 defaultDepth=DefaultDepth(display,screennr); #ifdef _IRR_LINUX_X11_VIDMODE_ if (XF86VidModeQueryExtension(display, &eventbase, &errorbase)) { // enumerate video modes s32 modeCount; XF86VidModeModeInfo** modes; XF86VidModeGetAllModeLines(display, screennr, &modeCount, &modes); // save current video mode oldVideoMode = *modes[0]; // find fitting mode VideoModeList.setDesktop(defaultDepth, core::dimension2d<s32>( modes[0]->hdisplay, modes[0]->vdisplay)); for (s32 i = 0; i<modeCount; ++i) { if (bestMode==-1 && modes[i]->hdisplay >= Width && modes[i]->vdisplay >= Height) bestMode = i; else if (bestMode!=-1 && modes[i]->hdisplay >= Width && modes[i]->vdisplay >= Height && modes[i]->hdisplay < modes[bestMode]->hdisplay && modes[i]->vdisplay < modes[bestMode]->vdisplay) bestMode = i; VideoModeList.addMode(core::dimension2d<s32>( modes[i]->hdisplay, modes[i]->vdisplay), defaultDepth); } if (bestMode != -1) { os::Printer::log("Starting fullscreen mode...", ELL_INFORMATION); XF86VidModeSwitchToMode(display, screennr, modes[bestMode]); XF86VidModeSetViewPort(display, screennr, 0, 0); UseXVidMode=true; } else { os::Printer::log("Could not find specified video mode, running windowed.", ELL_WARNING); Fullscreen = false; } XFree(modes); } else #endif #ifdef _IRR_LINUX_X11_RANDR_ if (XRRQueryExtension(display, &eventbase, &errorbase)) { s32 modeCount; XRRScreenConfiguration *config=XRRGetScreenInfo(display,DefaultRootWindow(display)); oldRandrMode=XRRConfigCurrentConfiguration(config,&oldRandrRotation); XRRScreenSize *modes=XRRConfigSizes(config,&modeCount); VideoModeList.setDesktop(defaultDepth, core::dimension2d<s32>( modes[oldRandrMode].width, modes[oldRandrMode].height)); for (s32 i = 0; i<modeCount; ++i) { if (bestMode==-1 && (u32)modes[i].width >= Width && (u32)modes[i].height >= Height) bestMode = i; else if (bestMode!=-1 && (u32)modes[i].width >= Width && (u32)modes[i].height >= Height && modes[i].width < modes[bestMode].width && modes[i].height < modes[bestMode].height) bestMode = i; VideoModeList.addMode(core::dimension2d<s32>( modes[i].width, modes[i].height), defaultDepth); } if (bestMode != -1) { XRRSetScreenConfig(display,config,DefaultRootWindow(display),bestMode,oldRandrRotation,CurrentTime); UseXRandR=true; } XRRFreeScreenConfigInfo(config); } else #endif { os::Printer::log("VidMode or RandR extension must be installed to allow Irrlicht " "to switch to fullscreen mode. Running in windowed mode instead.", ELL_WARNING); Fullscreen = false; } } #ifdef _IRR_COMPILE_WITH_OPENGL_ Context=0; GLXFBConfig glxFBConfig; int major, minor; bool isAvailableGLX=false; if (DriverType==video::EDT_OPENGL) { isAvailableGLX=glXQueryExtension(display,&major,&minor); if (isAvailableGLX && glXQueryVersion(display, &major, &minor)) { if (major==1 && minor>2) { const int MAX_SAMPLES = 16; // attribute array for the draw buffer int visualAttrBuffer[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_RED_SIZE, 4, GLX_GREEN_SIZE, 4, GLX_BLUE_SIZE, 4, GLX_ALPHA_SIZE, 4, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, GL_TRUE, GLX_STENCIL_SIZE, 1, GLX_SAMPLE_BUFFERS_ARB, GL_TRUE, GLX_SAMPLES_ARB, MAX_SAMPLES, None }; GLXFBConfig *configList=0; int nitems=0; if (!AntiAlias) { visualAttrBuffer[17] = GL_FALSE; visualAttrBuffer[19] = 0; } if (StencilBuffer) { configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); if (!configList && AntiAlias) { while (!configList && (visualAttrBuffer[19]>1)) { visualAttrBuffer[19] >>= 1; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); } if (!configList) { visualAttrBuffer[17] = GL_FALSE; visualAttrBuffer[19] = 0; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); if (configList) { os::Printer::log("No FSAA available.", ELL_WARNING); AntiAlias=false; } else { //reenable multisampling visualAttrBuffer[17] = GL_TRUE; visualAttrBuffer[19] = MAX_SAMPLES; } } } } // Next try without stencil buffer if (!configList) { if (StencilBuffer) os::Printer::log("No stencilbuffer available, disabling stencil shadows.", ELL_WARNING); StencilBuffer = false; visualAttrBuffer[15]=0; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); if (!configList && AntiAlias) { while (!configList && (visualAttrBuffer[19]>1)) { visualAttrBuffer[19] >>= 1; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); } if (!configList) { visualAttrBuffer[17] = GL_FALSE; visualAttrBuffer[19] = 0; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); if (configList) { os::Printer::log("No FSAA available.", ELL_WARNING); AntiAlias=false; } else { //reenable multisampling visualAttrBuffer[17] = GL_TRUE; visualAttrBuffer[19] = MAX_SAMPLES; } } } } // Next try without double buffer if (!configList) { os::Printer::log("No doublebuffering available.", ELL_WARNING); visualAttrBuffer[13] = GL_FALSE; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); if (!configList && AntiAlias) { while (!configList && (visualAttrBuffer[19]>1)) { visualAttrBuffer[19] >>= 1; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); } if (!configList) { visualAttrBuffer[17] = GL_FALSE; visualAttrBuffer[19] = 0; configList=glXChooseFBConfig(display, screennr, visualAttrBuffer,&nitems); if (configList) { os::Printer::log("No FSAA available.", ELL_WARNING); AntiAlias=false; } else { //reenable multisampling visualAttrBuffer[17] = GL_TRUE; visualAttrBuffer[19] = MAX_SAMPLES; } } } } if (configList) { glxFBConfig=configList[0]; XFree(configList); UseGLXWindow=true; visual = glXGetVisualFromFBConfig(display,glxFBConfig); } } else {
int OglCreatePBuffer (tPixelBuffer *pb, int nWidth, int nHeight, int nDepth) { #ifdef _WIN32 int pf; UINT nPf; static int pfAttribs [] = { WGL_SUPPORT_OPENGL_ARB, TRUE, WGL_DRAW_TO_PBUFFER_ARB, TRUE, WGL_BIND_TO_TEXTURE_RGBA_ARB, TRUE, WGL_RED_BITS_ARB, 8, WGL_GREEN_BITS_ARB, 8, WGL_BLUE_BITS_ARB, 8, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, 24, //WGL_STENCIL_BITS_ARB, 1, WGL_DOUBLE_BUFFER_ARB, FALSE, 0}; static int pbAttribs [] = { WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB, WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, 0}; if (!gameStates.ogl.bRender2TextureOk) return 0; OglDestroyPBuffer (pb); hGlDC = wglGetCurrentDC (); hGlRC = wglGetCurrentContext (); if (nWidth > 0) pb->nWidth = nWidth; if (nHeight > 0) pb->nHeight = nHeight; wglChoosePixelFormatARB (hGlDC, (const int *) pfAttribs, NULL, 1, &pf, &nPf); if (!nPf) return 0; if (!(pb->hBuf = wglCreatePbufferARB (hGlDC, pf, pb->nWidth, pb->nHeight, pbAttribs))) return 0; if (!(pb->hDC = wglGetPbufferDCARB (pb->hBuf))) { wglDestroyPbufferARB (pb->hBuf); pb->hBuf = NULL; return 0; } if (!(pb->hRC = wglCreateContext (pb->hDC))) { wglReleasePbufferDCARB (pb->hBuf, pb->hDC); wglDestroyPbufferARB (pb->hBuf); pb->hDC = NULL; pb->hBuf = NULL; return 0; } wglShareLists (hGlRC, pb->hRC); #else //!_WIN32 XVisualInfo *vi; GLXFBConfig *pfd; // pixel format descriptor int nScreen, nFd; static int pfAttribs [] = { GLX_DOUBLEBUFFER, 0, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT, 0 }; int pbAttribs [] = { GLX_PBUFFER_WIDTH, 0, GLX_PBUFFER_HEIGHT, 0, GLX_LARGEST_PBUFFER, 0, None }; if (!gameStates.ogl.bRender2TextureOk) return 0; hGlWindow = glXGetCurrentDrawable (); hGlDC = glXGetCurrentDisplay (); hGlRC = glXGetCurrentContext (); nScreen = DefaultScreen (hGlDC); pfd = glXChooseFBConfig (hGlDC, nScreen, pfAttribs, &nFd); if (nWidth > 0) pb->nWidth = nWidth; if (nHeight > 0) pb->nHeight = nHeight; pbAttribs [1] = nWidth; pbAttribs [3] = nHeight; if (!(pb->hBuf = glXCreatePbuffer (hGlDC, pfd [0], pbAttribs))) { XFree (pfd); return 0; } if (!(vi = glXGetVisualFromFBConfig (hGlDC, pfd [0]))) { glXDestroyPbuffer (pb->hDC, pb->hBuf); XFree (pfd); return 0; } if (!(pb->hRC = glXCreateContext (hGlDC, vi, hGlRC, GL_TRUE))) {// Share display lists and textures with the regular window glXDestroyPbuffer (pb->hDC, pb->hBuf); XFree (pfd); XFree (vi); return 0; } XFree (pfd); #endif //!_WIN32 OglGenTextures (1, &pb->texId); OGL_BINDTEX (pb->texId); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR /*GL_LINEAR_MIPMAP_LINEAR*/); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); return 1; }
MainWin * mainwin_create(Display *dpy, dlist *config) { const char *tmp; XColor screen_color, exact_color; XSetWindowAttributes wattr; XWindowAttributes rootattr; unsigned long valuemask = CWEventMask; #ifdef XINERAMA int event_base, error_base; #endif /* XINERAMA */ MainWin *mw = (MainWin *)malloc(sizeof(MainWin)); mw->screen = DefaultScreen(dpy); mw->visual = imlib_get_best_visual(dpy, mw->screen, &mw->depth); mw->colormap = DefaultColormap(dpy, mw->screen); mw->root = RootWindow(dpy, mw->screen); mw->background = 0; mw->bg_pixmap = None; #ifdef XINERAMA mw->xin_info = mw->xin_active = 0; mw->xin_screens = 0; #endif /* XINERAMA */ mw->x = mw->y = 0; mw->no_free_color = 0; mw->pressed = mw->focus = 0; mw->tooltip = 0; mw->cod = 0; mw->cm_normal = mw->cm_highlight = 0; mw->key_up = XKeysymToKeycode(dpy, XK_Up); mw->key_down = XKeysymToKeycode(dpy, XK_Down); mw->key_left = XKeysymToKeycode(dpy, XK_Left); mw->key_right = XKeysymToKeycode(dpy, XK_Right); mw->key_enter = XKeysymToKeycode(dpy, XK_Return); mw->key_space = XKeysymToKeycode(dpy, XK_space); mw->key_escape = XKeysymToKeycode(dpy, XK_Escape); mw->key_q = XKeysymToKeycode(dpy, XK_q); XGetWindowAttributes(dpy, mw->root, &rootattr); mw->width = rootattr.width; mw->height = rootattr.height; mw->dpy = dpy; valuemask |= CWBackPixel; wattr.background_pixel = BlackPixel(dpy, mw->screen); wattr.event_mask = VisibilityChangeMask | ButtonReleaseMask; mw->window = XCreateWindow(dpy, mw->root, 0, 0, mw->width, mw->height, 0, CopyFromParent, InputOutput, CopyFromParent, valuemask, &wattr); if(mw->window == None) { free(mw); return 0; } #ifdef XINERAMA # ifdef DEBUG fprintf(stderr, "--> checking for Xinerama extension... "); # endif /* DEBUG */ if(XineramaQueryExtension(dpy, &event_base, &error_base)) { # ifdef DEBUG fprintf(stderr, "yes\n--> checking if Xinerama is enabled... "); # endif /* DEBUG */ if(XineramaIsActive(dpy)) { # ifdef DEBUG fprintf(stderr, "yes\n--> fetching Xinerama info... "); # endif /* DEBUG */ mw->xin_info = XineramaQueryScreens(mw->dpy, &mw->xin_screens); # ifdef DEBUG fprintf(stderr, "done (%i screens)\n", mw->xin_screens); # endif /* DEBUG */ } # ifdef DEBUG else fprintf(stderr, "no\n"); # endif /* DEBUG */ } # ifdef DEBUG else fprintf(stderr, "no\n"); # endif /* DEBUG */ #endif /* XINERAMA */ tmp = config_get(config, "normal", "border", "black"); if(! XAllocNamedColor(mw->dpy, mw->colormap, tmp, &screen_color, &exact_color)) { fprintf(stderr, "WARNING: Invalid color '%s', reverting to black.\n", tmp); BORDER_COLOR(mw) = BlackPixel(mw->dpy, mw->screen); mw->no_free_color = 1; } else BORDER_COLOR(mw) = screen_color.pixel; tmp = config_get(config, "highlight", "border", "#d0d0ff"); if(! XAllocNamedColor(mw->dpy, mw->colormap, tmp, &screen_color, &exact_color)) { fprintf(stderr, "WARNING: Invalid color '%s', reverting to white.\n", tmp); HIGHLIGHT_COLOR(mw) = WhitePixel(mw->dpy, mw->screen); mw->no_free_color |= 2; } else HIGHLIGHT_COLOR(mw) = screen_color.pixel; tmp = config_get(config, "general", "distance", "50"); DISTANCE(mw) = MAX(1, strtol(tmp, 0, 10)); if(! strcasecmp(config_get(config, "tooltip", "show", "true"), "true")) mw->tooltip = tooltip_create(mw, config); mw->cm_normal = create_modifier(mw, config, "normal", "0.0", "white", "200"); mw->cm_highlight = create_modifier(mw, config, "highlight", "0.05", "#d0d0ff", "255"); return mw; }
int main(int argc,char *argv[]) { int screen; int d_depth; XWMHints mywmhints; Pixel back_pix,fore_pix; int i; unsigned int borderwidth; char *wname="wmswallow"; int remainarg, remainargc; XEvent Event; XTextProperty name; XClassHint classHint; remainarg=parseargs(argc, argv); /* remainarg > 0 afterwards */ remainargc=argc-remainarg; #ifdef DEBUG fprintf(stderr, "remainarg: %d, remainargc: %d, argc: %d\n", remainarg, remainargc,argc); fflush(stderr); #endif if (!(dpy = XOpenDisplay(display_name))) { fprintf(stderr,"wmswallow: can't open display %s\n", XDisplayName(display_name)); exit (1); } screen=DefaultScreen(dpy); Root=RootWindow(dpy, screen); /* So, now we've got everything we need to get Events from the XServer */ if (remainargc>1) { winid=startandfind(remainargc-1, argv+remainarg+1, argv[remainarg]); if (winid==0) { perror("wmswallow: startandfind failed"); /* Real error handling in execstuff()*/ exit (1); } } d_depth=DefaultDepth(dpy, screen); /* XConnectionNumber(dpy); */ /* useless */ 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=WIDTH; mysizehints.height=HEIGHT; if (geometry!=NULL) { #ifdef DEBUG fprintf(stderr,"Setting geometry to: %s\n",geometry); fflush(stderr); #endif XParseGeometry(geometry, &mysizehints.x, &mysizehints.y, &mysizehints.width, &mysizehints.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); XSetWMNormalHints(dpy, win, &mysizehints); classHint.res_name="wmswallow"; classHint.res_class="WMswallow"; XSetClassHint(dpy, win, &classHint); XSelectInput(dpy, win, MW_EVENTS); XSelectInput(dpy, iconwin, MW_EVENTS); if(XStringListToTextProperty(&wname, 1, &name)==0) { fprintf(stderr, "wmswallow: can't allocate window name\n"); exit(-1); } XSetWMName(dpy, win, &name); 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(dpy, win, &mywmhints); XSetCommand(dpy, win, argv, argc); if (winid==0) { swallowed=findnamedwindow(argv[remainarg]); /* Find which window to swallow*/ #ifdef DEBUG fprintf(stderr,"%s has Window-id 0x%lx\n", argv[remainarg], swallowed); fflush(stderr); #endif } else swallowed=winid; /* "Swallow" it */ XReparentWindow(dpy, swallowed, iconwin, 0, 0); if (getclick) { /* softenwindow (swallowed); */ /* Change some attributes */ XSelectInput(dpy, swallowed, SW_EVENTS|ButtonPressMask); } else { XSelectInput(dpy, swallowed, SW_EVENTS); /* Workaround for apps like perfmeter that don't let us get their mouseclicks :-( */ } XSetWindowBorderWidth(dpy, swallowed,0); XMoveResizeWindow(dpy, swallowed, 0, 0, mysizehints.width, mysizehints.height); /* Now we do some special juju for shaped windows: */ /* ...tell the window to repaint itself, please! */ if (shape) { sendexpose(swallowed); /* ... ok, window should be repainted and a shaped window should have updated its mask accordingly! (-: End of shape-juju :-) */ /* Now steal the shape of the Window we just swallowed! */ stealshape(swallowed); } XMapWindow(dpy,win); XMapSubwindows(dpy,win); FlushWindow(); while(1) { while (XPending(dpy)) { XNextEvent(dpy,&Event); switch(Event.type) { case ButtonPress: #ifdef DEBUG fprintf (stderr, "wmswallow: Got ButtonPress Event\n"); fflush(stderr); #endif if (getclick) system(execstring); break; case Expose: if(Event.xexpose.count == 0 ) { #ifdef DEBUG fprintf (stderr, "wmswallow: Got Expose Event, count==0\n"); fflush(stderr); #endif if (shape) stealshape(swallowed); /* Oclock changes its shape! That's why we have to steal it *again* */ FlushWindow(); XMapRaised(dpy,swallowed); /* the following Produces "focus-flicker" */ /* XMapSubwindows(dpy,win); */ /* XMapWindow(dpy,win); */ } break; case EnterNotify: if (focus) XSetInputFocus(dpy, swallowed, RevertToPointerRoot, CurrentTime); break; case LeaveNotify: if (focus) XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); break; case DestroyNotify: XCloseDisplay(dpy); exit(0); default: #ifdef DEBUG /* fprintf (stderr, "wmswallow: Got Some Other Event\n"); fflush(stderr); */ #endif break; } } XFlush(dpy); usleep(50000L); } return 1; }
void ColorInitialize(Display *aDisp) { disp = aDisp; colormap = DefaultColormap(disp, DefaultScreen(disp)); visual = DefaultVisual(disp, DefaultScreen(disp)); }
static void glxtest() { // we want to redirect to /dev/null stdout, stderr, and while we're at it, // any PR logging file descriptors. To that effect, we redirect all positive // file descriptors up to what open() returns here. In particular, 1 is stdout and 2 is stderr. int fd = open("/dev/null", O_WRONLY); for (int i = 1; i < fd; i++) dup2(fd, i); close(fd); if (getenv("MOZ_AVOID_OPENGL_ALTOGETHER")) fatal_error("The MOZ_AVOID_OPENGL_ALTOGETHER environment variable is defined"); ///// Open libGL and load needed symbols ///// #ifdef __OpenBSD__ #define LIBGL_FILENAME "libGL.so" #else #define LIBGL_FILENAME "libGL.so.1" #endif void *libgl = dlopen(LIBGL_FILENAME, RTLD_LAZY); if (!libgl) fatal_error("Unable to load " LIBGL_FILENAME); typedef void* (* PFNGLXGETPROCADDRESS) (const char *); PFNGLXGETPROCADDRESS glXGetProcAddress = cast<PFNGLXGETPROCADDRESS>(dlsym(libgl, "glXGetProcAddress")); if (!glXGetProcAddress) fatal_error("Unable to find glXGetProcAddress in " LIBGL_FILENAME); typedef GLXFBConfig* (* PFNGLXQUERYEXTENSION) (Display *, int *, int *); PFNGLXQUERYEXTENSION glXQueryExtension = cast<PFNGLXQUERYEXTENSION>(glXGetProcAddress("glXQueryExtension")); typedef GLXFBConfig* (* PFNGLXQUERYVERSION) (Display *, int *, int *); PFNGLXQUERYVERSION glXQueryVersion = cast<PFNGLXQUERYVERSION>(dlsym(libgl, "glXQueryVersion")); typedef XVisualInfo* (* PFNGLXCHOOSEVISUAL) (Display *, int, int *); PFNGLXCHOOSEVISUAL glXChooseVisual = cast<PFNGLXCHOOSEVISUAL>(glXGetProcAddress("glXChooseVisual")); typedef GLXContext (* PFNGLXCREATECONTEXT) (Display *, XVisualInfo *, GLXContext, Bool); PFNGLXCREATECONTEXT glXCreateContext = cast<PFNGLXCREATECONTEXT>(glXGetProcAddress("glXCreateContext")); typedef Bool (* PFNGLXMAKECURRENT) (Display*, GLXDrawable, GLXContext); PFNGLXMAKECURRENT glXMakeCurrent = cast<PFNGLXMAKECURRENT>(glXGetProcAddress("glXMakeCurrent")); typedef void (* PFNGLXDESTROYCONTEXT) (Display*, GLXContext); PFNGLXDESTROYCONTEXT glXDestroyContext = cast<PFNGLXDESTROYCONTEXT>(glXGetProcAddress("glXDestroyContext")); typedef GLubyte* (* PFNGLGETSTRING) (GLenum); PFNGLGETSTRING glGetString = cast<PFNGLGETSTRING>(glXGetProcAddress("glGetString")); if (!glXQueryExtension || !glXQueryVersion || !glXChooseVisual || !glXCreateContext || !glXMakeCurrent || !glXDestroyContext || !glGetString) { fatal_error("glXGetProcAddress couldn't find required functions"); } ///// Open a connection to the X server ///// Display *dpy = XOpenDisplay(nullptr); if (!dpy) fatal_error("Unable to open a connection to the X server"); ///// Check that the GLX extension is present ///// if (!glXQueryExtension(dpy, nullptr, nullptr)) fatal_error("GLX extension missing"); XSetErrorHandler(x_error_handler); ///// Get a visual ///// int attribs[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, None }; XVisualInfo *vInfo = glXChooseVisual(dpy, DefaultScreen(dpy), attribs); if (!vInfo) fatal_error("No visuals found"); // using a X11 Window instead of a GLXPixmap does not crash // fglrx in indirect rendering. bug 680644 Window window; XSetWindowAttributes swa; swa.colormap = XCreateColormap(dpy, RootWindow(dpy, vInfo->screen), vInfo->visual, AllocNone); swa.border_pixel = 0; window = XCreateWindow(dpy, RootWindow(dpy, vInfo->screen), 0, 0, 16, 16, 0, vInfo->depth, InputOutput, vInfo->visual, CWBorderPixel | CWColormap, &swa); ///// Get a GL context and make it current ////// GLXContext context = glXCreateContext(dpy, vInfo, nullptr, True); glXMakeCurrent(dpy, window, context); ///// Look for this symbol to determine texture_from_pixmap support ///// void* glXBindTexImageEXT = glXGetProcAddress("glXBindTexImageEXT"); ///// Get GL vendor/renderer/versions strings ///// enum { bufsize = 1024 }; char buf[bufsize]; const GLubyte *vendorString = glGetString(GL_VENDOR); const GLubyte *rendererString = glGetString(GL_RENDERER); const GLubyte *versionString = glGetString(GL_VERSION); if (!vendorString || !rendererString || !versionString) fatal_error("glGetString returned null"); int length = snprintf(buf, bufsize, "VENDOR\n%s\nRENDERER\n%s\nVERSION\n%s\nTFP\n%s\n", vendorString, rendererString, versionString, glXBindTexImageEXT ? "TRUE" : "FALSE"); if (length >= bufsize) fatal_error("GL strings length too large for buffer size"); ///// Clean up. Indeed, the parent process might fail to kill us (e.g. if it doesn't need to check GL info) ///// so we might be staying alive for longer than expected, so it's important to consume as little memory as ///// possible. Also we want to check that we're able to do that too without generating X errors. glXMakeCurrent(dpy, None, nullptr); // must release the GL context before destroying it glXDestroyContext(dpy, context); XDestroyWindow(dpy, window); XFreeColormap(dpy, swa.colormap); XCloseDisplay(dpy); dlclose(libgl); ///// Finally write data to the pipe write(write_end_of_the_pipe, buf, length); }
void X11EmbedContainer::embedSystemTrayClient(WId clientId) { Display *display = QX11Info::display(); if (!XGetWindowAttributes(display, clientId, &d->attr)) { emit error(QX11EmbedContainer::Unknown); return; } XSetWindowAttributes sAttr; sAttr.background_pixel = BlackPixel(display, DefaultScreen(display)); sAttr.border_pixel = BlackPixel(display, DefaultScreen(display)); sAttr.colormap = d->attr.colormap; WId parentId = parentWidget() ? parentWidget()->winId() : DefaultRootWindow(display); Window winId = XCreateWindow(display, parentId, 0, 0, d->attr.width, d->attr.height, 0, d->attr.depth, InputOutput, d->attr.visual, CWBackPixel | CWBorderPixel | CWColormap, &sAttr); XWindowAttributes attr; if (!XGetWindowAttributes(display, winId, &attr)) { emit error(QX11EmbedContainer::Unknown); return; } create(winId); #if defined(HAVE_XCOMPOSITE) && defined(HAVE_XFIXES) && defined(HAVE_XDAMAGE) XRenderPictFormat *format = XRenderFindVisualFormat(display, d->attr.visual); if (format && format->type == PictTypeDirect && format->direct.alphaMask && FdoSelectionManager::manager()->haveComposite()) { // Redirect ARGB windows to offscreen storage so we can composite them ourselves XRenderPictureAttributes attr; attr.subwindow_mode = IncludeInferiors; d->picture = XRenderCreatePicture(display, clientId, format, CPSubwindowMode, &attr); XCompositeRedirectSubwindows(display, winId, CompositeRedirectManual); FdoSelectionManager::manager()->addDamageWatch(this, clientId); //kDebug() << "Embedded client uses an ARGB visual -> compositing."; } else { //kDebug() << "Embedded client is not using an ARGB visual."; } #endif // repeat everything from QX11EmbedContainer's ctor that might be relevant setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setAcceptDrops(true); setEnabled(false); XSelectInput(display, winId, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | KeymapStateMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | FocusChangeMask | ExposureMask | StructureNotifyMask | SubstructureNotifyMask); XFlush(display); embedClient(clientId); // FIXME: This checks that the client is still valid. Qt won't pick it up // if the client closes before embedding completes. However, what happens // if the close happens after this point? Should checks happen on a timer // until embedding completes perhaps? if (!XGetWindowAttributes(QX11Info::display(), clientId, &d->attr)) { emit error(QX11EmbedContainer::Unknown); return; } }
extern "C" KDE_EXPORT int kdemain(int argc, char *argv[]) { bool restored = false; for(int arg = 1; arg < argc; arg++) { if(!qstrcmp(argv[arg], "-session")) { restored = true; break; } } if(!restored) { // we only do the multihead fork if we are not restored by the session // manager, since the session manager will register multiple kwins, // one for each screen... QCString multiHead = getenv("KDE_MULTIHEAD"); if(multiHead.lower() == "true") { Display *dpy = XOpenDisplay(NULL); if(!dpy) { fprintf(stderr, "%s: FATAL ERROR while trying to open display %s\n", argv[0], XDisplayName(NULL)); exit(1); } int number_of_screens = ScreenCount(dpy); KWinInternal::screen_number = DefaultScreen(dpy); int pos; // temporarily needed to reconstruct DISPLAY var if multi-head QCString display_name = XDisplayString(dpy); XCloseDisplay(dpy); dpy = 0; if((pos = display_name.findRev('.')) != -1) display_name.remove(pos, 10); // 10 is enough to be sure we removed ".s" QCString envir; if(number_of_screens != 1) { for(int i = 0; i < number_of_screens; i++) { // if execution doesn't pass by here, then kwin // acts exactly as previously if(i != KWinInternal::screen_number && fork() == 0) { KWinInternal::screen_number = i; // break here because we are the child process, we don't // want to fork() anymore break; } } // in the next statement, display_name shouldn't contain a screen // number. If it had it, it was removed at the "pos" check envir.sprintf("DISPLAY=%s.%d", display_name.data(), KWinInternal::screen_number); if(putenv(strdup(envir.data()))) { fprintf(stderr, "%s: WARNING: unable to set DISPLAY environment variable\n", argv[0]); perror("putenv()"); } } } } KGlobal::locale()->setMainCatalogue("kwin"); KAboutData aboutData("kwin", I18N_NOOP("KWin"), version, description, KAboutData::License_GPL, I18N_NOOP("(c) 1999-2005, The KDE Developers")); aboutData.addAuthor("Matthias Ettrich", 0, "*****@*****.**"); aboutData.addAuthor("Cristian Tibirna", 0, "*****@*****.**"); aboutData.addAuthor("Daniel M. Duley", 0, "*****@*****.**"); aboutData.addAuthor("Luboš Luňák", I18N_NOOP("Maintainer"), "*****@*****.**"); KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions(args); if(signal(SIGTERM, KWinInternal::sighandler) == SIG_IGN) signal(SIGTERM, SIG_IGN); if(signal(SIGINT, KWinInternal::sighandler) == SIG_IGN) signal(SIGINT, SIG_IGN); if(signal(SIGHUP, KWinInternal::sighandler) == SIG_IGN) signal(SIGHUP, SIG_IGN); KApplication::disableAutoDcopRegistration(); KWinInternal::Application a; KWinInternal::SessionManaged weAreIndeed; KWinInternal::SessionSaveDoneHelper helper; fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, 1); QCString appname; if(KWinInternal::screen_number == 0) appname = "kwin"; else appname.sprintf("kwin-screen-%d", KWinInternal::screen_number); DCOPClient *client = a.dcopClient(); client->registerAs(appname.data(), false); client->setDefaultObject("KWinInterface"); return a.exec(); }
int main(int argc, char**argv) { char **missing_charset_list; int missing_charset_count; XGCValues xgcv; unsigned long mask; Display* dpy; int scr; Window w, root; XSetWindowAttributes set_attr; int i; XIMStyle *style; static char buf[128]; KeySym keysym = 0; Status status; XWMHints wm_hints; XClassHint class_hints; XIMStyle input_style = 0; char **font_name_list; char *def_string; XFontStruct **font_struct_list; char **font_encoding_list; int nb_font; int len = 0; int no_xim = 0; char **missing_charset_list_return; int missing_charset_count_return; char *def_string_return; if (!setlocale(LC_ALL, "")) puts("locale not supported by C library, locale unchanged"); if (!XSetLocaleModifiers("")) puts("X locale modifiers not supported, using default"); dpy = XOpenDisplay(0); scr = DefaultScreen(dpy); root = RootWindow(dpy, scr); set_attr.event_mask = KeyPressMask|FocusChangeMask; set_attr.background_pixel = WhitePixel(dpy, DefaultScreen(dpy)); set_attr.border_pixel = BlackPixel(dpy, DefaultScreen(dpy)); w = XCreateWindow(dpy, root, 10,10,200,100,0, DefaultDepth(dpy, DefaultScreen(dpy)), InputOutput, DefaultVisual(dpy, DefaultScreen(dpy)), CWEventMask | CWBackPixel | CWBorderPixel, &set_attr); class_hints.res_name = "test"; class_hints.res_class = "Test"; wm_hints.input = True; wm_hints.flags = InputHint; XmbSetWMProperties(dpy, w, "test", "test", NULL, 0, NULL, &wm_hints, &class_hints); XMapWindow(dpy, w); xim_im = XOpenIM(dpy, NULL, "test", "Test"); XGetIMValues(xim_im, XNQueryInputStyle, &xim_styles, NULL, NULL); for (i = 0, style = xim_styles->supported_styles; i < xim_styles->count_styles; i++, style++) { if (*style == (XIMStatusNone|XIMPreeditNone)) { printf("this is not a XIM server !!!\n"); no_xim = 1; } printf("input style : 0x%X\n", *style); } XFree(xim_styles); xim_ic = XCreateIC(xim_im, XNInputStyle, (XIMPreeditNothing | XIMStatusNothing), XNClientWindow, w, XNFocusWindow, w, NULL); XSetICFocus(xim_ic); /*************************************************************** * I don't recommend to use a font base name list similar * to the following one in a real application ;-) ***************************************************************/ fontset = XCreateFontSet(dpy, "-*-*-*-*-*-*-*-*-*-*-*-*-iso8858-3," /* not valid */ "-*-*-medium-r-*-*-*-*-*-*-*-*-iso8859-1," "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-6," "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-8," "-*-symbol-*-*-*-*-*-*-*-*-*-*-adobe-fontspecific," "-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-2," "-*-*-*-*-*-*-*-*-*-*-*-*-koi8-1," "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0208.1983-0," "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0212.1990-0," "-*-*-*-*-*-*-*-*-*-*-*-*-big5-0," "-*-*-*-*-*-*-*-*-*-*-*-*-jisx0201.1976-0," "-*-unifont-*-*-*-*-*-*-*-*-*-*-iso10646-1[0x300 0x400_0x500]," "-*-*-*-*-*-*-*-*-*-*-*-*-*-*", &missing_charset_list_return, &missing_charset_count_return, &def_string_return); mask = (GCForeground | GCBackground); xgcv.foreground = BlackPixel(dpy, DefaultScreen(dpy)); xgcv.background = WhitePixel(dpy, DefaultScreen(dpy)); gc = XCreateGC(dpy, w, mask, &xgcv); /***************************************************************/ while (1) { int filtered; static XEvent xevent; static XVaNestedList list1 = 0; int r; XNextEvent(dpy, &xevent); if (xevent.type == KeyPress) { XKeyEvent *e = (XKeyEvent*) &xevent; printf ("0x%X %d\n", e->state, e->keycode); } filtered = XFilterEvent(&xevent, w); if (xevent.type == FocusOut) XUnsetICFocus(xim_ic); if (xevent.type == FocusIn) XSetICFocus(xim_ic); if (xevent.type == KeyPress && !filtered) { len = Xutf8LookupString(xim_ic, &xevent.xkey, buf, 127, &keysym, &status); Xutf8DrawImageString(dpy, w, fontset, gc, x, y, buf, len); Xutf8DrawString(dpy, w, fontset, gc, 0, 20, jp_txt, strlen(jp_txt)); Xutf8DrawString(dpy, w, fontset, gc, 50, 90, rtl_txt, strlen(rtl_txt)); buf[len] = 0; printf("'%s' %d\n", buf, keysym); buf[0] = 0; XCloseIM(xim_im); } if (filtered) { printf("Dead key\n"); } } XFreeFontSet(dpy, fontset); return 0; }