Beispiel #1
0
static void ungrab_keys(int screen)
{
    Window root = RootWindow(dpy, screen);
    XUngrabKey(dpy, AnyKey, AnyModifier, root);
}
Beispiel #2
0
int main(int argc, char**argv) {
  char **missing_charset_list;
  int missing_charset_count;
  XGCValues xgcv;
  unsigned long mask;
  Display* dpy;
  int scr;
  gi_window_id_t 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;
  gi_ufont_t **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 = gi_init();
  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 recommend 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 = gi_create_gc( w, mask, &xgcv);
  if (!gc) {
    puts("cannot create Graphic Context.\n");
    exit(-1);
  }

  /***************************************************************/
  while (1) {
    int filtered;
    static gi_msg_t 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;
}
JNIEXPORT jlong JNICALL Java_org_lwjgl_opengl_LinuxDisplay_getRootWindow(JNIEnv *env, jclass clazz, jlong display, jint screen) {
	Display *disp = (Display *)(intptr_t)display;
	return RootWindow(disp, screen);
}
int wincreat( int x, int y, int width, int height, char *title)
{ 
  XSetWindowAttributes   swa; 
  Colormap               cmap;
  XVisualInfo           *vi;
  int                    dummy;
  GLXContext             glcx;
  XEvent                 event;
  int                    attributes[] = { GLX_RGBA,
                                          GLX_DEPTH_SIZE, 16,
                                          GLX_RED_SIZE, 8,
                                          GLX_GREEN_SIZE, 8,
                                          GLX_BLUE_SIZE, 8,
                                          GLX_ALPHA_SIZE, 8,
                                          GLX_DOUBLEBUFFER,
                                          None }; 

    if( !(dpy = XOpenDisplay( NULL )) )    /* defaults to $DISPLAY */
  {
      fprintf( stderr, "Unable to open display.\n" );
      exit( 1 );

  } else {

    /*printf( "Connected to display... %s (%s).\n", dpy->display_name, dpy->vendor );*/

  }   /* end if( ) */

  if( !glXQueryExtension( dpy, &dummy, &dummy ) )
  {
      fprintf( stderr, "Unable to query GLX extensions.\n" );
      exit( 1 );

  }   /* end if( ) */

  if( !(vi = glXChooseVisual( dpy, DefaultScreen( dpy ), attributes )) )
  {
      fprintf( stderr, "Unable get a visual.\n" );
      exit( 1 );

  }   /* end if( ) */

  if( vi->class != TrueColor )
  {
      fprintf( stderr, "Need TrueColor class.\n" );
      exit( 1 );
  }

  if( !(glcx = glXCreateContext( dpy, vi, None, GL_TRUE )) )
  {
      fprintf( stderr, "Unable create a GL context.\n" );
      exit( 1 );

  }   /* end if( ) */

  cmap = XCreateColormap( dpy, RootWindow( dpy, vi->screen ),
                                     vi->visual, AllocNone );

  swa.colormap                  = cmap;
  swa.border_pixel              = 0;
  swa.event_mask                = ExposureMask
                                | KeyPressMask
                                | StructureNotifyMask;

  glwin = XCreateWindow(        dpy,
                                RootWindow( dpy, vi->screen ),
                                x,
                                y,
                                width,
                                height,
                                0,
                                vi->depth,
                                InputOutput,
                                vi->visual,
                                CWBorderPixel   |
                                CWColormap      |
                                CWEventMask,
                                &swa
                        );

/* Make a clear cursor so it looks like we have none. */
  {
      Pixmap pixmap;
      Cursor cursor;
      XColor color;
      char clear_bits[32];

      memset(clear_bits, 0, sizeof(clear_bits));

      pixmap = XCreatePixmapFromBitmapData(dpy, glwin, clear_bits,
                                           16, 16, 1, 0, 1);
      cursor = XCreatePixmapCursor(dpy, pixmap, pixmap, &color, &color, 8, 8);
      XDefineCursor(dpy, glwin, cursor);

      XFreePixmap(dpy, pixmap);
  }


  XSetStandardProperties( dpy, glwin, title, title, None, NULL, 0, NULL );

  if( !glXMakeCurrent( dpy, glwin, glcx ) )
  {
      fprintf( stderr, "Failed to make the GL context current.\n" );
      exit( 1 );
  }

  XMapWindow( dpy, glwin );
  XIfEvent( dpy, &event, WaitForMapNotify, (char *)glwin );

  return( 1 );

} /* end int APIENTRY pglc_wincreat( ) */
Beispiel #5
0
void
Fake_glXUseXFont(Font font, int first, int count, int listbase)
{
   Display *dpy;
   Window win;
   Pixmap pixmap;
   GC gc;
   XGCValues values;
   unsigned long valuemask;
   XFontStruct *fs;
   GLint swapbytes, lsbfirst, rowlength;
   GLint skiprows, skippixels, alignment;
   unsigned int max_width, max_height, max_bm_width, max_bm_height;
   GLubyte *bm;
   int i;

   dpy = glXGetCurrentDisplay();
   if (!dpy)
      return;			/* I guess glXMakeCurrent wasn't called */
   win = RootWindow(dpy, DefaultScreen(dpy));

   fs = XQueryFont(dpy, font);
   if (!fs) {
      _mesa_error(NULL, GL_INVALID_VALUE,
		  "Couldn't get font structure information");
      return;
   }

   /* Allocate a bitmap that can fit all characters.  */
   max_width = fs->max_bounds.rbearing - fs->min_bounds.lbearing;
   max_height = fs->max_bounds.ascent + fs->max_bounds.descent;
   max_bm_width = (max_width + 7) / 8;
   max_bm_height = max_height;

   bm = (GLubyte *) MALLOC((max_bm_width * max_bm_height) * sizeof(GLubyte));
   if (!bm) {
      XFreeFontInfo(NULL, fs, 1);
      _mesa_error(NULL, GL_OUT_OF_MEMORY,
		  "Couldn't allocate bitmap in glXUseXFont()");
      return;
   }

#if 0
   /* get the page info */
   pages = fs->max_char_or_byte2 - fs->min_char_or_byte2 + 1;
   firstchar = (fs->min_byte1 << 8) + fs->min_char_or_byte2;
   lastchar = (fs->max_byte1 << 8) + fs->max_char_or_byte2;
   rows = fs->max_byte1 - fs->min_byte1 + 1;
   unsigned int first_char, last_char, pages, rows;
#endif

   /* Save the current packing mode for bitmaps.  */
   glGetIntegerv(GL_UNPACK_SWAP_BYTES, &swapbytes);
   glGetIntegerv(GL_UNPACK_LSB_FIRST, &lsbfirst);
   glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowlength);
   glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skiprows);
   glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skippixels);
   glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);

   /* Enforce a standard packing mode which is compatible with
      fill_bitmap() from above.  This is actually the default mode,
      except for the (non)alignment.  */
   glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
   glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
   glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
   glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
   glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

   pixmap = XCreatePixmap(dpy, win, 10, 10, 1);
   values.foreground = BlackPixel(dpy, DefaultScreen(dpy));
   values.background = WhitePixel(dpy, DefaultScreen(dpy));
   values.font = fs->fid;
   valuemask = GCForeground | GCBackground | GCFont;
   gc = XCreateGC(dpy, pixmap, valuemask, &values);
   XFreePixmap(dpy, pixmap);

#ifdef DEBUG
   if (debug_xfonts)
      dump_font_struct(fs);
#endif

   for (i = 0; i < count; i++) {
      unsigned int width, height, bm_width, bm_height;
      GLfloat x0, y0, dx, dy;
      XCharStruct *ch;
      int x, y;
      unsigned int c = first + i;
      int list = listbase + i;
      int valid;

      /* check on index validity and get the bounds */
      ch = isvalid(fs, c);
      if (!ch) {
	 ch = &fs->max_bounds;
	 valid = 0;
      }
      else {
	 valid = 1;
      }

#ifdef DEBUG
      if (debug_xfonts) {
	 char s[7];
	 sprintf(s, isprint(c) ? "%c> " : "\\%03o> ", c);
	 dump_char_struct(ch, s);
      }
#endif

      /* glBitmap()' parameters:
         straight from the glXUseXFont(3) manpage.  */
      width = ch->rbearing - ch->lbearing;
      height = ch->ascent + ch->descent;
      x0 = -ch->lbearing;
      y0 = ch->descent - 0;	/* XXX used to subtract 1 here */
      /* but that caused a conformace failure */
      dx = ch->width;
      dy = 0;

      /* X11's starting point.  */
      x = -ch->lbearing;
      y = ch->ascent;

      /* Round the width to a multiple of eight.  We will use this also
         for the pixmap for capturing the X11 font.  This is slightly
         inefficient, but it makes the OpenGL part real easy.  */
      bm_width = (width + 7) / 8;
      bm_height = height;

      glNewList(list, GL_COMPILE);
      if (valid && (bm_width > 0) && (bm_height > 0)) {

	 memset(bm, '\0', bm_width * bm_height);
	 fill_bitmap(dpy, win, gc, bm_width, bm_height, x, y, c, bm);

	 glBitmap(width, height, x0, y0, dx, dy, bm);
#ifdef DEBUG
	 if (debug_xfonts) {
	    printf("width/height = %u/%u\n", width, height);
	    printf("bm_width/bm_height = %u/%u\n", bm_width, bm_height);
	    dump_bitmap(bm_width, bm_height, bm);
	 }
#endif
      }
      else {
	 glBitmap(0, 0, 0.0, 0.0, dx, dy, NULL);
      }
      glEndList();
   }

   FREE(bm);
   XFreeFontInfo(NULL, fs, 1);
   XFreeGC(dpy, gc);

   /* Restore saved packing modes.  */
   glPixelStorei(GL_UNPACK_SWAP_BYTES, swapbytes);
   glPixelStorei(GL_UNPACK_LSB_FIRST, lsbfirst);
   glPixelStorei(GL_UNPACK_ROW_LENGTH, rowlength);
   glPixelStorei(GL_UNPACK_SKIP_ROWS, skiprows);
   glPixelStorei(GL_UNPACK_SKIP_PIXELS, skippixels);
   glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
}
Beispiel #6
0
void
setup(void) {
    int x, y, screen;
    XSetWindowAttributes wa;
#ifdef XINERAMA
    int n;
    XineramaScreenInfo *info;
#endif

    screen = DefaultScreen(dc->dpy);
    root = RootWindow(dc->dpy, screen);
    utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);

    normcol[ColBG] = getcolor(dc, normbgcolor);
    normcol[ColFG] = getcolor(dc, normfgcolor);
    selcol[ColBG] = getcolor(dc, selbgcolor);
    selcol[ColFG] = getcolor(dc, selfgcolor);

    /* menu geometry */
    bh = dc->font.height + 2;
    lines = MAX(lines, 0);
    mh = (MAX(MIN(lines + 1, itemcount), 1)) * bh;

    if(height < mh) {
        height = mh;
    }
#ifdef XINERAMA
    if((info = XineramaQueryScreens(dc->dpy, &n))) {
        int i, di;
        unsigned int du;
        Window dw;

        XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du);
        for(i = 0; i < n; i++)
            if((monitor == info[i].screen_number)
                    || (monitor < 0 && INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)))
                break;
        x = info[i].x_org;
        y = info[i].y_org + (topbar ? 0 : info[i].height - height);
        mw = info[i].width;
        XFree(info);
    }
    else
#endif
    {
        x = 0;
        y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - height;
        mw = DisplayWidth(dc->dpy, screen);
    }
    /* menu window */
    wa.override_redirect = True;
    wa.background_pixmap = ParentRelative;
    wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
    win = XCreateWindow(dc->dpy, root, x, y, mw, height, 0,
                        DefaultDepth(dc->dpy, screen), CopyFromParent,
                        DefaultVisual(dc->dpy, screen),
                        CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);

    grabkeyboard();
    resizedc(dc, mw, height);
    inputw = MIN(inputw, mw/3);
    promptw = prompt ? textw(dc, prompt) : 0;
    XMapRaised(dc->dpy, win);
    text[0] = '\0';
    match();
}
Beispiel #7
0
static int DeleteXi18nAtom(Xi18n i18n_core)
{
    Display *dpy = i18n_core->address.dpy;
    Window root = RootWindow (dpy, DefaultScreen (dpy));
    Atom realtype;
    int realformat;
    unsigned long bytesafter;
    long *data=NULL;
    unsigned long length;
    Atom atom;
    int i, ret;
    int found;
    char buf[256];

    (void)snprintf(buf, 256, "@server=%s", i18n_core->address.im_name);
    if ((atom = XInternAtom(dpy, buf, False)) == 0)
        return False;
    i18n_core->address.selection = atom;

    if (XIM_Servers == None)
        XIM_Servers = XInternAtom (dpy, XIM_SERVERS, False);
    XGetWindowProperty (dpy,
                        root,
                        XIM_Servers,
                        0L,
                        1000000L,
                        False,
                        XA_ATOM,
                        &realtype,
                        &realformat,
                        &length,
                        &bytesafter,
                        (unsigned char **) (&data));
    if (realtype != XA_ATOM || realformat != 32) {
        if (data != NULL)
            XFree ((char *) data);
        return False;
    }

    found = False;
    for (i = 0; i < length; i++) {
        if (data[i] == atom) {
            found = True;
            break;
        }
    }

    if (found == True) {
        for (i=i+1; i<length; i++)
            data[i-1] = data[i];
        XChangeProperty (dpy,
                         root,
                         XIM_Servers,
                         XA_ATOM,
                         32,
                         PropModeReplace,
                         (unsigned char *)data,
                         length-1);
        ret = True;
    }
    else {
        XChangeProperty (dpy,
                         root,
                         XIM_Servers,
                         XA_ATOM,
                         32,
                         PropModePrepend,
                         (unsigned char *)data,
                         0);
        ret = False;
    }
    if (data != NULL)
        XFree ((char *) data);
    return ret;
}
Beispiel #8
0
static Status
lookup(Display *dpy, int screen, VisualID visualid, Atom property,
       XStandardColormap *cnew, Bool replace)
     /*
      * dpy		- specifies display connection
      * screen		- specifies screen number
      * visualid	- specifies visualid for std map
      * property	- specifies colormap property name
      * cnew		- specifies a standard colormap
      * replace		- specifies whether to replace
      */
{
    register int	i;
    int			count;
    XStandardColormap	*stdcmaps, *s;
    Window		win = RootWindow(dpy, screen);

    /* The property does not already exist */

    if (! XGetRGBColormaps(dpy, win, &stdcmaps, &count, property)) {
	if (cnew)
	    XSetRGBColormaps(dpy, win, cnew, 1, property);
	return 0;
    }

    /* The property exists and is not describing the RGB_DEFAULT_MAP */

    if (property != XA_RGB_DEFAULT_MAP) {
	if (replace) {
	    XmuDeleteStandardColormap(dpy, screen, property);
	    if (cnew)
		XSetRGBColormaps(dpy, win, cnew, 1, property);
	}
	XFree((char *)stdcmaps);
	return 1;
    }

    /* The property exists and is RGB_DEFAULT_MAP */
    
    for (i=0, s=stdcmaps; (i < count) && (s->visualid != visualid); i++, s++)
	;

    /* No RGB_DEFAULT_MAP property matches the given visualid */

    if (i == count) {
	if (cnew) {
	    XStandardColormap	*m, *maps;

	    s = (XStandardColormap *) malloc((unsigned) ((count+1) * sizeof
					      (XStandardColormap)));

	    for (i = 0, m = s, maps = stdcmaps; i < count; i++, m++, maps++) {
		m->colormap   = maps->colormap;
		m->red_max    = maps->red_max;
		m->red_mult   = maps->red_mult;
		m->green_max  = maps->green_max;
		m->green_mult = maps->green_mult;
		m->blue_max   = maps->blue_max;
		m->blue_mult  = maps->blue_mult;
		m->base_pixel = maps->base_pixel;
		m->visualid   = maps->visualid;
		m->killid     = maps->killid;
	    }
	    m->colormap   = cnew->colormap;
	    m->red_max    = cnew->red_max;
	    m->red_mult   = cnew->red_mult;
	    m->green_max  = cnew->green_max;
	    m->green_mult = cnew->green_mult;
	    m->blue_max   = cnew->blue_max;
	    m->blue_mult  = cnew->blue_mult;
	    m->base_pixel = cnew->base_pixel;
	    m->visualid   = cnew->visualid;
	    m->killid     = cnew->killid;

	    XSetRGBColormaps(dpy, win, s, ++count, property);
	    free((char *) s);
	}
	XFree((char *) stdcmaps);
	return 0;
    }

    /* Found an RGB_DEFAULT_MAP property with a matching visualid */

    if (replace) {
	/* Free old resources first - we may need them, particularly in 
	 * the default colormap of the screen.  However, because of this,
	 * it is possible that we will destroy the old resource and fail 
	 * to create a new one if XmuStandardColormap() fails.
	 */

	if (count == 1) {
	    XmuDeleteStandardColormap(dpy, screen, property);
	    if (cnew)
		XSetRGBColormaps(dpy, win, cnew, 1, property);
	}
	else {
	    XStandardColormap	*map;

	    /* s still points to the matching standard colormap */

	    if (s->killid == ReleaseByFreeingColormap) {
		if ((s->colormap != None) &&
		    (s->colormap != DefaultColormap(dpy, screen)))
		    XFreeColormap(dpy, s->colormap);
	    }
	    else if (s->killid != None)
		XKillClient(dpy, s->killid);

	    map = (cnew) ? cnew : stdcmaps + --count;

	    s->colormap   = map->colormap;
	    s->red_max    = map->red_max;
	    s->red_mult   = map->red_mult;
	    s->green_max  = map->green_max;
	    s->green_mult = map->green_mult;
	    s->blue_max   = map->blue_max;
	    s->blue_mult  = map->blue_mult;
	    s->visualid   = map->visualid;
	    s->killid     = map->killid;

	    XSetRGBColormaps(dpy, win, stdcmaps, count, property);
	}
    }
    XFree((char *) stdcmaps);
    return 1;
}
Beispiel #9
0
controlPanelStruct *
makeControlPanel(void)
{

  Window cw;
  int                  i,num;
  controlPanelStruct   *control;
  buttonStruct         *buttons;
  controlXY            cXY;
  XSetWindowAttributes cwAttrib, controlAttrib;
  XSizeHints           sizehints;
  Pixmap               mousebits,mousemask;
  XColor               foreColor, backColor;

  if (!(control = (controlPanelStruct *)malloc(sizeof(controlPanelStruct)))) {
    fprintf(stderr,"Ran out of memory trying to create a control panel.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }

  cXY = getControlXY(0);

  /* Define and assign a mouse cursor. */
  mousebits = XCreateBitmapFromData(dsply,rtWindow,mouseBitmap_bits,
                                    mouseBitmap_width,mouseBitmap_height);
  mousemask = XCreateBitmapFromData(dsply,rtWindow,mouseMask_bits,
                                    mouseMask_width,mouseMask_height);
  cwAttrib.background_pixel = backgroundColor; /* controlBackground; */
  cwAttrib.border_pixel = foregroundColor;
  cwAttrib.backing_store = WhenMapped;
  cwAttrib.event_mask = controlMASK;
  cwAttrib.colormap = colorMap;
  cwAttrib.override_redirect = overrideManager;
  foreColor.pixel = controlCursorForeground;
  XQueryColor(dsply,colorMap,&foreColor);
  backColor.pixel = controlCursorBackground;
  XQueryColor(dsply,colorMap,&backColor);
  cwAttrib.cursor = XCreatePixmapCursor(dsply,mousebits,mousemask,
                                        &foreColor,&backColor,
                                        mouseBitmap_x_hot,mouseBitmap_y_hot);

  cw = XCreateWindow(dsply,rtWindow,
                     cXY.putX,cXY.putY,controlWidth,controlHeight,3,
                     CopyFromParent,InputOutput,CopyFromParent,
                     controlCreateMASK,&cwAttrib);

  sizehints.flags  = PPosition | PSize;
  sizehints.x      = cXY.putX;
  sizehints.y      = cXY.putY;
  sizehints.width  = controlWidth;
  sizehints.height = controlHeight;

  /*** the None stands for icon pixmap...change.... ***/

  XSetNormalHints(dsply,cw,&sizehints);
  XSetStandardProperties(dsply,cw,"2D Control Panel","2D Control Panel",
                         None,NULL,0,&sizehints);

  control->controlWindow = cw;
  num = initButtons(control->buttonQueue);
  control->numOfButtons = num;
  buttons = control->buttonQueue;

  for (i=0; i<num; i++) {
    controlAttrib.event_mask = (control->buttonQueue[i]).mask;
    (control->buttonQueue[i]).self = XCreateWindow(dsply,cw,
                                       (control->buttonQueue[i]).buttonX,
                                       (control->buttonQueue[i]).buttonY,
                                       (control->buttonQueue[i]).buttonWidth,
                                       (control->buttonQueue[i]).buttonHeight,
                                       0,0,InputOnly,CopyFromParent,
                                       buttonCreateMASK,&controlAttrib);

    XMakeAssoc(dsply,table,(control->buttonQueue[i]).self,
               &((control->buttonQueue[i]).buttonKey));
   /* Use buttonKey instead of i because buttonKey has a permanent address */
    XMapWindow(dsply,(control->buttonQueue[i]).self);
  }

           /* Create message window */
  control->messageWindow = XCreateWindow(dsply,cw,0,controlMessageY,
                                         controlWidth,controlMessageHeight,
                                         0,0,InputOnly,CopyFromParent,
                                         messageCreateMASK,&cwAttrib);
  XMapWindow(dsply,control->messageWindow);

  for (i=0; i<scaleArrowN; i++) {
    scaleArrow[i].x += buttons[scale2D].buttonX;
    scaleArrow[i].y += buttons[scale2D].buttonY;
  }
  for (i=0; i<translateArrowN; i++) {
    translateArrow[i].x += buttons[translate2D].buttonX;
    translateArrow[i].y += buttons[translate2D].buttonY;
  }

  viewport->justMadeControl = yes;
  return(control);

} /* makeControlPanel() */
// Initializes and opens both X11 display and OpenGL ES.
static int initGraphics()
{
    static const EGLint configAttribs[] =
    {
#if (WINDOW_BPP == 16)
        EGL_RED_SIZE,       5,
        EGL_GREEN_SIZE,     5,
        EGL_BLUE_SIZE,      5,
#elif (WINDOW_BPP == 32)
        EGL_RED_SIZE,       8,
        EGL_GREEN_SIZE,     8,
        EGL_BLUE_SIZE,      8,
#else
#error WINDOW_BPP must be 16 or 32
#endif
        EGL_DEPTH_SIZE,     16,
        EGL_ALPHA_SIZE,     EGL_DONT_CARE,
        EGL_STENCIL_SIZE,   EGL_DONT_CARE,
        EGL_SURFACE_TYPE,   EGL_WINDOW_BIT,
        EGL_NONE
    };
    EGLBoolean success;
    EGLint numConfigs;
    EGLint majorVersion;
    EGLint minorVersion;

    int importGLResult;
    importGLResult = importGLInit();
    if (!importGLResult)
        return 0;

    sDisplay = XOpenDisplay(NULL);

    sEglDisplay = eglGetDisplay(sDisplay);
    success = eglInitialize(sEglDisplay, &majorVersion, &minorVersion);
    if (success != EGL_FALSE)
        success = eglGetConfigs(sEglDisplay, NULL, 0, &numConfigs);
    if (success != EGL_FALSE)
        success = eglChooseConfig(sEglDisplay, configAttribs,
                                  &sEglConfig, 1, &numConfigs);
    if (success != EGL_FALSE)
    {
        sEglContext = eglCreateContext(sEglDisplay, sEglConfig, NULL, NULL);
        if (sEglContext == EGL_NO_CONTEXT)
            success = EGL_FALSE;
    }
    if (success != EGL_FALSE)
    {
        XSetWindowAttributes swa;
        XVisualInfo *vi, tmp;
        XSizeHints sh;
        int n;
        EGLint vid;

        eglGetConfigAttrib(sEglDisplay, sEglConfig,
                           EGL_NATIVE_VISUAL_ID, &vid);
        tmp.visualid = vid;
        vi = XGetVisualInfo(sDisplay, VisualIDMask, &tmp, &n);
        swa.colormap = XCreateColormap(sDisplay,
                                       RootWindow(sDisplay, vi->screen),
                                       vi->visual, AllocNone);
        sh.flags = PMinSize | PMaxSize;
        sh.min_width = sh.max_width = sWindowWidth;
        sh.min_height = sh.max_height = sWindowHeight;
        swa.border_pixel = 0;
        swa.event_mask = ExposureMask | StructureNotifyMask |
                         KeyPressMask | ButtonPressMask | ButtonReleaseMask;
        sWindow = XCreateWindow(sDisplay, RootWindow(sDisplay, vi->screen),
                                0, 0, sWindowWidth, sWindowHeight,
                                0, vi->depth, InputOutput, vi->visual,
                                CWBorderPixel | CWColormap | CWEventMask,
                                &swa);
        XMapWindow(sDisplay, sWindow);
        XSetStandardProperties(sDisplay, sWindow, sAppName, sAppName,
                               None, (void *)0, 0, &sh);
    }
    if (success != EGL_FALSE)
    {
        sEglSurface = eglCreateWindowSurface(sEglDisplay, sEglConfig,
                                             (NativeWindowType)sWindow, NULL);
        if (sEglSurface == EGL_NO_SURFACE)
            success = EGL_FALSE;
    }
    if (success != EGL_FALSE)
        success = eglMakeCurrent(sEglDisplay, sEglSurface,
                                 sEglSurface, sEglContext);

    if (success == EGL_FALSE)
        checkEGLErrors();

    return success != EGL_FALSE;
}
Beispiel #11
0
QGLTemporaryContext::QGLTemporaryContext(bool, QWidget *)
    : d(new QGLTemporaryContextPrivate)
{
    d->initialized = false;
    d->window = 0;
    d->context = 0;
    d->surface = 0;
    int screen = 0;

    d->display = QEgl::display();

    EGLConfig config;
    int numConfigs = 0;
    EGLint attribs[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
#ifdef QT_OPENGL_ES_2
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#endif
        EGL_NONE
    };

    eglChooseConfig(d->display, attribs, &config, 1, &numConfigs);
    if (!numConfigs) {
        qWarning("QGLTemporaryContext: No EGL configurations available.");
        return;
    }

    XVisualInfo visualInfo;
    XVisualInfo *vi;
    int numVisuals;

    visualInfo.visualid = QEgl::getCompatibleVisualId(config);
    vi = XGetVisualInfo(X11->display, VisualIDMask, &visualInfo, &numVisuals);
    if (!vi || numVisuals < 1) {
        qWarning("QGLTemporaryContext: Unable to get X11 visual info id.");
        return;
    }

    XSetWindowAttributes attr;
    unsigned long mask;
    attr.background_pixel = 0;
    attr.border_pixel = 0;
    attr.colormap = XCreateColormap(X11->display, DefaultRootWindow(X11->display), vi->visual, AllocNone);
    attr.event_mask = StructureNotifyMask | ExposureMask;
    mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

    d->window = XCreateWindow(X11->display, RootWindow(X11->display, screen),
                              0, 0, 1, 1, 0,
                              vi->depth, InputOutput, vi->visual,
                              mask, &attr);

    d->surface = eglCreateWindowSurface(d->display, config, (EGLNativeWindowType) d->window, NULL);

    if (d->surface == EGL_NO_SURFACE) {
        qWarning("QGLTemporaryContext: Error creating EGL surface.");
        XFree(vi);
        XDestroyWindow(X11->display, d->window);
        return;
    }

    EGLint contextAttribs[] = {
#ifdef QT_OPENGL_ES_2
        EGL_CONTEXT_CLIENT_VERSION, 2,
#endif
        EGL_NONE
    };
    d->context = eglCreateContext(d->display, config, 0, contextAttribs);
    if (d->context != EGL_NO_CONTEXT
        && eglMakeCurrent(d->display, d->surface, d->surface, d->context))
    {
        d->initialized = true;
    } else {
        qWarning("QGLTemporaryContext: Error creating EGL context.");
        eglDestroySurface(d->display, d->surface);
        XDestroyWindow(X11->display, d->window);
    }
    XFree(vi);
}
Beispiel #12
0
static Bool
print_screen_info(Display *dpy, int scrnum, Bool allowDirect,
                  Bool coreProfile, Bool es2Profile, Bool limits,
                  Bool singleLine, Bool coreWorked)
{
   Window win;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   GLXContext ctx = NULL;
   XVisualInfo *visinfo;
   int width = 100, height = 100;
   GLXFBConfig *fbconfigs;
   const char *oglstring = coreProfile ? "OpenGL core profile" :
                           es2Profile ? "OpenGL ES profile" : "OpenGL";

   root = RootWindow(dpy, scrnum);

   /*
    * Choose FBConfig or XVisualInfo and create a context.
    */
   fbconfigs = choose_fb_config(dpy, scrnum);
   if (fbconfigs) {
      ctx = create_context_with_config(dpy, fbconfigs[0],
                                       coreProfile, es2Profile, allowDirect);
      if (!ctx && allowDirect && !coreProfile) {
         /* try indirect */
         ctx = create_context_with_config(dpy, fbconfigs[0],
                                          coreProfile, es2Profile, False);
      }

      visinfo = glXGetVisualFromFBConfig(dpy, fbconfigs[0]);
      XFree(fbconfigs);
   }
   else if (!coreProfile && !es2Profile) {
      visinfo = choose_xvisinfo(dpy, scrnum);
      if (visinfo)
	 ctx = glXCreateContext(dpy, visinfo, NULL, allowDirect);
   } else
      visinfo = NULL;

   if (!visinfo && !coreProfile && !es2Profile) {
      fprintf(stderr, "Error: couldn't find RGB GLX visual or fbconfig\n");
      return False;
   }

   if (!ctx) {
      if (!coreProfile && !es2Profile)
	 fprintf(stderr, "Error: glXCreateContext failed\n");
      XFree(visinfo);
      return False;
   }

   /*
    * Create a window so that we can just bind the context.
    */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
   win = XCreateWindow(dpy, root, 0, 0, width, height,
		       0, visinfo->depth, InputOutput,
		       visinfo->visual, mask, &attr);

   if (glXMakeCurrent(dpy, win, ctx)) {
      const char *serverVendor = glXQueryServerString(dpy, scrnum, GLX_VENDOR);
      const char *serverVersion = glXQueryServerString(dpy, scrnum, GLX_VERSION);
      const char *serverExtensions = glXQueryServerString(dpy, scrnum, GLX_EXTENSIONS);
      const char *clientVendor = glXGetClientString(dpy, GLX_VENDOR);
      const char *clientVersion = glXGetClientString(dpy, GLX_VERSION);
      const char *clientExtensions = glXGetClientString(dpy, GLX_EXTENSIONS);
      const char *glxExtensions = glXQueryExtensionsString(dpy, scrnum);
      const char *glVendor = (const char *) glGetString(GL_VENDOR);
      const char *glRenderer = (const char *) glGetString(GL_RENDERER);
      const char *glVersion = (const char *) glGetString(GL_VERSION);
      char *glExtensions;
      int glxVersionMajor;
      int glxVersionMinor;
      char *displayName = NULL;
      char *colon = NULL, *period = NULL;
      struct ext_functions extfuncs;

      CheckError(__LINE__);

      /* Get some ext functions */
      extfuncs.GetProgramivARB = (GETPROGRAMIVARBPROC)
         glXGetProcAddressARB((GLubyte *) "glGetProgramivARB");
      extfuncs.GetStringi = (GETSTRINGIPROC)
         glXGetProcAddressARB((GLubyte *) "glGetStringi");
      extfuncs.GetConvolutionParameteriv = (GETCONVOLUTIONPARAMETERIVPROC)
         glXGetProcAddressARB((GLubyte *) "glGetConvolutionParameteriv");

      /* Get list of GL extensions */
      if (coreProfile) {
         glExtensions = build_core_profile_extension_list(&extfuncs);
      }
      else {
         glExtensions = (char *) glGetString(GL_EXTENSIONS);
      }

      CheckError(__LINE__);

      if (! glXQueryVersion( dpy, & glxVersionMajor, & glxVersionMinor )) {
         fprintf(stderr, "Error: glXQueryVersion failed\n");
         exit(1);
      }

      if (!coreWorked) {
         /* Strip the screen number from the display name, if present. */
         if (!(displayName = (char *) malloc(strlen(DisplayString(dpy)) + 1))) {
            fprintf(stderr, "Error: malloc() failed\n");
            exit(1);
         }
         strcpy(displayName, DisplayString(dpy));
         colon = strrchr(displayName, ':');
         if (colon) {
            period = strchr(colon, '.');
            if (period)
               *period = '\0';
         }

         printf("display: %s  screen: %d\n", displayName, scrnum);
         free(displayName);
         printf("direct rendering: ");
         if (glXIsDirect(dpy, ctx)) {
            printf("Yes\n");
         }
         else {
            if (!allowDirect) {
               printf("No (-i specified)\n");
            }
            else if (getenv("LIBGL_ALWAYS_INDIRECT")) {
               printf("No (LIBGL_ALWAYS_INDIRECT set)\n");
            }
            else {
               printf("No (If you want to find out why, try setting "
                      "LIBGL_DEBUG=verbose)\n");
            }
         }
         printf("server glx vendor string: %s\n", serverVendor);
         printf("server glx version string: %s\n", serverVersion);
         printf("server glx extensions:\n");
         print_extension_list(serverExtensions, singleLine);
         printf("client glx vendor string: %s\n", clientVendor);
         printf("client glx version string: %s\n", clientVersion);
         printf("client glx extensions:\n");
         print_extension_list(clientExtensions, singleLine);
         printf("GLX version: %u.%u\n", glxVersionMajor, glxVersionMinor);
         printf("GLX extensions:\n");
         print_extension_list(glxExtensions, singleLine);
         printf("OpenGL vendor string: %s\n", glVendor);
         printf("OpenGL renderer string: %s\n", glRenderer);
      } else
         printf("\n");

      printf("%s version string: %s\n", oglstring, glVersion);

      version = (glVersion[0] - '0') * 10 + (glVersion[2] - '0');

      CheckError(__LINE__);

#ifdef GL_VERSION_2_0
      if (version >= 20) {
         char *v = (char *) glGetString(GL_SHADING_LANGUAGE_VERSION);
         printf("%s shading language version string: %s\n", oglstring, v);
      }
#endif
      CheckError(__LINE__);
#ifdef GL_VERSION_3_0
      if (version >= 30 && !es2Profile) {
         GLint flags;
         glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
         printf("%s context flags: %s\n", oglstring, context_flags_string(flags));
      }
#endif
      CheckError(__LINE__);
#ifdef GL_VERSION_3_2
      if (version >= 32 && !es2Profile) {
         GLint mask;
         glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);
         printf("%s profile mask: %s\n", oglstring, profile_mask_string(mask));
      }
#endif

      CheckError(__LINE__);

      printf("%s extensions:\n", oglstring);
      print_extension_list(glExtensions, singleLine);

      CheckError(__LINE__);

      if (limits) {
         print_limits(glExtensions, oglstring, version, &extfuncs);
      }

      if (coreProfile)
         free(glExtensions);
   }
   else {
      fprintf(stderr, "Error: glXMakeCurrent failed\n");
   }

   glXDestroyContext(dpy, ctx);
   XFree(visinfo);
   XDestroyWindow(dpy, win);
   XSync(dpy, 1);
   return True;
}
Beispiel #13
0
void* iupdrvImageCreateImage(Ihandle *ih, const char* bgcolor, int make_inactive)
{
  int y, x, bpp, bgcolor_depend = 0,
      width = ih->currentwidth,
      height = ih->currentheight;
  unsigned char *imgdata = (unsigned char*)ih->handle;
  Pixmap pixmap;
  unsigned char bg_r=0, bg_g=0, bg_b=0;
  GC gc;
  Pixel color2pixel[256];

  bpp = iupAttribGetInt(ih, "BPP");

  iupStrToRGB(bgcolor, &bg_r, &bg_g, &bg_b);

  if (bpp == 8)
  {
    int i, colors_count = 0;
    iupColor colors[256];

    iupImageInitColorTable(ih, colors, &colors_count);

    for (i=0;i<colors_count;i++)
    {
      if (colors[i].a == 0)
      {
        colors[i].r = bg_r;
        colors[i].g = bg_g;
        colors[i].b = bg_b;
        colors[i].a = 255;
        bgcolor_depend = 1;
      }

      if (make_inactive)
          iupImageColorMakeInactive(&(colors[i].r), &(colors[i].g), &(colors[i].b), 
                                    bg_r, bg_g, bg_b);

      color2pixel[i] = iupmotColorGetPixel(colors[i].r, colors[i].g, colors[i].b);
    }
  }

  pixmap = XCreatePixmap(iupmot_display,
          RootWindow(iupmot_display,iupmot_screen),
          width, height, iupdrvGetScreenDepth());
  if (!pixmap)
    return NULL;

  gc = XCreateGC(iupmot_display,pixmap,0,NULL);
  for (y=0;y<height;y++)
  {
    for(x=0;x<width;x++)
    {
      unsigned long p;
      if (bpp == 8)
        p = color2pixel[imgdata[y*width+x]];
      else
      {
        int channels = (bpp==24)? 3: 4;
        unsigned char *pixel_data = imgdata + y*width*channels + x*channels;
        unsigned char r = *(pixel_data),
                      g = *(pixel_data+1),
                      b = *(pixel_data+2);

        if (bpp == 32)
        {
          unsigned char a = *(pixel_data+3);
          if (a != 255)
          {
            r = iupALPHABLEND(r, bg_r, a);
            g = iupALPHABLEND(g, bg_g, a);
            b = iupALPHABLEND(b, bg_b, a);
            bgcolor_depend = 1;
          }
        }

        if (make_inactive)
          iupImageColorMakeInactive(&r, &g, &b, bg_r, bg_g, bg_b);

        p = iupmotColorGetPixel(r, g, b);
      }

      XSetForeground(iupmot_display,gc,p);
      XDrawPoint(iupmot_display,pixmap,gc,x,y);
    }
  }
  XFreeGC(iupmot_display,gc);

  if (bgcolor_depend || make_inactive)
    iupAttribSetStr(ih, "_IUP_BGCOLOR_DEPEND", "1");

 return (void*)pixmap;
}
Beispiel #14
0
void* iupdrvImageCreateCursor(Ihandle *ih)
{
  int bpp,y,x,hx,hy,
      width = ih->currentwidth,
      height = ih->currentheight,
      line_size = (width+7)/8,
      size_bytes = line_size*height;
  unsigned char *imgdata = (unsigned char*)ih->handle;
  char *sbits, *mbits, *sb, *mb;
  Pixmap source, mask;
  XColor fg, bg;
  unsigned char r, g, b;
  Cursor cursor;

  bpp = iupAttribGetInt(ih, "BPP");
  if (bpp > 8)
    return NULL;

  sbits = (char*)malloc(2*size_bytes);
  if (!sbits) return (Cursor)NULL;
  memset(sbits, 0, 2*size_bytes);
  mbits = sbits + size_bytes;

  sb = sbits;
  mb = mbits;
  for (y=0; y<height; y++)
  {
    for (x=0; x<width; x++)
    {
      int byte = x/8;
      int bit = x%8;
      int cor = (int)imgdata[y*width+x];
      if (cor == 1)
        sb[byte] = (char)(sb[byte] | (1<<bit));
      if (cor != 0)
        mb[byte] = (char)(mb[byte] | (1<<bit));
    }

    sb += line_size;
    mb += line_size;
  }

  r = 255; g = 255; b = 255;
  iupStrToRGB(iupAttribGet(ih, "1"), &r, &g, &b );
  fg.red   = iupCOLOR8TO16(r);
  fg.green = iupCOLOR8TO16(g);
  fg.blue  = iupCOLOR8TO16(b);
  fg.flags = DoRed | DoGreen | DoBlue;

  r = 0; g = 0; b = 0;
  iupStrToRGB(iupAttribGet(ih, "2"), &r, &g, &b );
  bg.red   = iupCOLOR8TO16(r);
  bg.green = iupCOLOR8TO16(g);
  bg.blue  = iupCOLOR8TO16(b);
  bg.flags = DoRed | DoGreen | DoBlue;

  hx=0; hy=0;
  iupStrToIntInt(iupAttribGet(ih, "HOTSPOT"), &hx, &hy, ':');

  source = XCreateBitmapFromData(iupmot_display, 
             RootWindow(iupmot_display,iupmot_screen),
             sbits, width, height);
  mask   = XCreateBitmapFromData(iupmot_display, 
             RootWindow(iupmot_display,iupmot_screen),
             mbits, width, height);

  cursor = XCreatePixmapCursor(iupmot_display, source, mask, &fg, &bg, hx, hy);

  free(sbits);
  return (void*)cursor;
}
Beispiel #15
0
static Colormap choose_cmap( Display *dpy, XVisualInfo *vi )
{
    if ( !cmap_dict ) {
	cmap_dict = new QIntDict<CMapEntry>;
	const char *v = glXQueryServerString( dpy, vi->screen, GLX_VERSION );
	if ( v )
	    mesa_gl = strstr(v,"Mesa") != 0;
	qAddPostRoutine( cleanup_cmaps );
    }

    CMapEntry *x = cmap_dict->find( (long) vi->visualid + ( vi->screen * 256 ) );
    if ( x )					// found colormap for visual
	return x->cmap;

    x = new CMapEntry();

    XStandardColormap *c;
    int n, i;

    // qDebug( "Choosing cmap for vID %0x", vi->visualid );

    if ( vi->visualid ==
	 XVisualIDFromVisual( (Visual*)QPaintDevice::x11AppVisual( vi->screen ) ) ) {
	// qDebug( "Using x11AppColormap" );
	return QPaintDevice::x11AppColormap( vi->screen );
    }

    if ( mesa_gl ) {				// we're using MesaGL
	Atom hp_cmaps = XInternAtom( dpy, "_HP_RGB_SMOOTH_MAP_LIST", TRUE );
	if ( hp_cmaps && vi->visual->c_class == TrueColor && vi->depth == 8 ) {
	    if ( XGetRGBColormaps(dpy,RootWindow(dpy,vi->screen),&c,&n,
				  hp_cmaps) ) {
		i = 0;
		while ( i < n && x->cmap == 0 ) {
		    if ( c[i].visualid == vi->visual->visualid ) {
			x->cmap = c[i].colormap;
			x->scmap = c[i];
			//qDebug( "Using HP_RGB scmap" );

		    }
		    i++;
		}
		XFree( (char *)c );
	    }
	}
    }
#if !defined(Q_OS_SOLARIS)
    if ( !x->cmap ) {
#ifdef QT_DLOPEN_OPENGL
	typedef Status (*_XmuLookupStandardColormap)( Display *dpy, int screen, VisualID visualid, unsigned int depth,
						      Atom property, Bool replace, Bool retain );
	_XmuLookupStandardColormap qt_XmuLookupStandardColormap;
	qt_XmuLookupStandardColormap = (_XmuLookupStandardColormap) QLibrary::resolve("Xmu", "XmuLookupStandardColormap");
	if (!qt_XmuLookupStandardColormap)
	    qFatal("Unable to resolve Xmu symbols - please check your Xmu library installation.");
#define XmuLookupStandardColormap qt_XmuLookupStandardColormap

#endif

	if ( XmuLookupStandardColormap(dpy,vi->screen,vi->visualid,vi->depth,
					  XA_RGB_DEFAULT_MAP,FALSE,TRUE) ) {
	    if ( XGetRGBColormaps(dpy,RootWindow(dpy,vi->screen),&c,&n,
				  XA_RGB_DEFAULT_MAP) ) {
		i = 0;
		while ( i < n && x->cmap == 0 ) {
		    if ( c[i].visualid == vi->visualid ) {
			x->cmap = c[i].colormap;
			x->scmap = c[i];
			//qDebug( "Using RGB_DEFAULT scmap" );
		    }
		    i++;
		}
		XFree( (char *)c );
	    }
	}
    }
#endif
    if ( !x->cmap ) {				// no shared cmap found
	x->cmap = XCreateColormap( dpy, RootWindow(dpy,vi->screen), vi->visual,
				   AllocNone );
	x->alloc = TRUE;
	// qDebug( "Allocating cmap" );
    }

    // associate cmap with visualid
    cmap_dict->insert( (long) vi->visualid + ( vi->screen * 256 ), x );
    return x->cmap;
}
Beispiel #16
0
int main(int argc, char *argv[])
{
	XSetWindowAttributes attr;
	Colormap cmap;
	Pixmap bitmap;
	Cursor cursor;
	XColor bg = { 0 };
	XColor fg = { 0 };
	char data[8] = { 0x01 };
	char *display;
	const char *ext;
	int mask, major, minor, verbose = 0;
	int opt;
	
	while ((opt = getopt(argc, argv, "v")) != -1) {
		switch(opt) {
		case 'v':
			verbose = 1;
			break;
		default:
			fprintf(stderr, "%d (%c) is unknown to me\n", opt, opt);
			break;
		}
	}
	
	if ((argc - optind) != 1) {
		fprintf(stderr, "usage: %s <mac wolf3d resource fork>\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	
	if (InitResources(argv[optind])) {
		fprintf(stderr, "could not load %s\n", argv[optind]);
		exit(EXIT_FAILURE);
	}
	
	display = getenv("DISPLAY");
	dpy = XOpenDisplay(getenv(display));
	if (dpy == NULL) {
		fprintf(stderr, "Unable to open display %s\n", XDisplayName(display));
		exit(EXIT_FAILURE);
	}
	
	screen = DefaultScreen(dpy);
	
	root = RootWindow(dpy, screen);
	
	if (glXQueryExtension(dpy, NULL, NULL) == False) {
		fprintf(stderr, "Display %s does not support the GLX Extension\n", XDisplayName(display));
		exit(EXIT_FAILURE);
	}
	
	if (glXQueryVersion(dpy, &major, &minor) == False) {
		fprintf(stderr, "glXQueryVersion returned False?\n");
		exit(EXIT_FAILURE);
	} else if (verbose) {
		printf("GLX Version %d.%d\n", major, minor);
		printf("GLX Client:\n");
		printf("GLX_VENDOR: %s\n", glXGetClientString(dpy, GLX_VENDOR));
		printf("GLX_VERSION: %s\n", glXGetClientString(dpy, GLX_VERSION));
		printf("GLX_EXTENSIONS: %s\n", glXGetClientString(dpy, GLX_EXTENSIONS));
		printf("GLX Server:\n");
		printf("GLX_VENDOR: %s\n", glXQueryServerString(dpy, screen, GLX_VENDOR));
		printf("GLX_VERSION: %s\n", glXQueryServerString(dpy, screen, GLX_VERSION));
		printf("GLX_EXTENSIONS: %s\n", glXQueryServerString(dpy, screen, GLX_EXTENSIONS));
		printf("Both:\n");
		printf("GLX_EXTENSIONS: %s\n", glXQueryExtensionsString(dpy, screen));
	}
	
	vi = glXChooseVisual(dpy, screen, attrib);
	if (vi == NULL) {
		fprintf(stderr, "No usable GL visual found on %s:%d\n", XDisplayName(display), screen);
		exit(EXIT_FAILURE);
	}
		
	ctx = glXCreateContext(dpy, vi, NULL, True);
	if (ctx == NULL) {
 		fprintf(stderr, "GLX context creation failed\n");
		exit(EXIT_FAILURE);
	}
	
	cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
	
	attr.colormap = cmap;
	attr.event_mask = KeyPressMask | KeyReleaseMask | ExposureMask |
	                  StructureNotifyMask;
	mask = CWColormap | CWEventMask;
	
	win = XCreateWindow(dpy, root, 0, 0, 640, 480, 0, CopyFromParent,
			    InputOutput, vi->visual, mask, &attr);
	
	if (win == None) {
		fprintf(stderr, "Unable to create window\n");
		exit(EXIT_FAILURE);
	}
	
	XSetWMProperties(dpy, win, NULL, NULL, argv, argc, None, None, None);
	
	XStoreName(dpy, win, "Wolfenstein 3D");
	XSetIconName(dpy, win, "Wolfenstein 3D");
	
	wmDeleteWindow = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
	XSetWMProtocols(dpy, win, &wmDeleteWindow, 1);
	
	bitmap = XCreateBitmapFromData(dpy, win, data, 8, 8);
	cursor = XCreatePixmapCursor(dpy, bitmap, bitmap, &fg, &bg, 0, 0);
	XDefineCursor(dpy, win, cursor);
	
	glXMakeCurrent(dpy, win, ctx);
	
 	if (verbose) {
		printf("GL Library:\n");
		printf("GL_VENDOR: %s\n", glGetString(GL_VENDOR));
		printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
		printf("GL_VERSION: %s\n", glGetString(GL_VERSION));
		printf("GL_EXTENSIONS: %s\n", glGetString(GL_EXTENSIONS));
	}
	
	XMapWindow(dpy, win);
	XFlush(dpy);
	
	ext = (const char *)glGetString(GL_EXTENSIONS);
#ifdef GL_EXT_shared_texture_palette
	UseSharedTexturePalette = 0;
	if (CheckToken(ext, "GL_EXT_shared_texture_palette")) {
		pglColorTableEXT = glXGetProcAddressARB((unsigned const char *)"glColorTableEXT");
		if (pglColorTableEXT) {
			UseSharedTexturePalette = 0;
			printf("GL_EXT_shared_texture_palette found...\n");
		}
	}
#endif
	
	glShadeModel(GL_FLAT);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	
	InitData();
	
	SlowDown = 1;
	GameViewSize = 3;	
	NewGameWindow(GameViewSize); 

	ClearTheScreen(BLACK);
	BlastScreen();

	/* NoEnemies = 1; */
		
	return WolfMain(argc, argv);
}
Beispiel #17
0
	int32_t run(Filesystem* fs, ConfigSettings* cs)
	{
		// http://tronche.com/gui/x/xlib/display/XInitThreads.html
		Status xs = XInitThreads();
		CE_ASSERT(xs != 0, "XInitThreads: error");
		CE_UNUSED(xs);

		_x11_display = XOpenDisplay(NULL);
		CE_ASSERT(_x11_display != NULL, "XOpenDisplay: error");

		int screen = DefaultScreen(_x11_display);
		int depth = DefaultDepth(_x11_display, screen);
		Visual* visual = DefaultVisual(_x11_display, screen);

		_x11_parent_window = (cs->parent_window == 0) ? RootWindow(_x11_display, screen) :
			(Window) cs->parent_window;

		// Create main window
		XSetWindowAttributes win_attribs;
		win_attribs.background_pixmap = 0;
		win_attribs.border_pixel = 0;
		win_attribs.event_mask = FocusChangeMask
			| StructureNotifyMask
			| KeyPressMask
			| KeyReleaseMask
			| ButtonPressMask
			| ButtonReleaseMask
			| PointerMotionMask;

		_x11_window = XCreateWindow(_x11_display
			, _x11_parent_window
			, 0
			, 0
			, cs->window_width
			, cs->window_height
			, 0
			, depth
			, InputOutput
			, visual
			, CWBorderPixel | CWEventMask
			, &win_attribs);
		CE_ASSERT(_x11_window != None, "XCreateWindow: error");

		// Do we have detectable autorepeat?
		Bool detectable;
		_x11_detectable_autorepeat = (bool) XkbSetDetectableAutoRepeat(_x11_display, true, &detectable);

		// Build hidden cursor
		Pixmap bm_no;
		XColor black, dummy;
		Colormap colormap;
		static char no_data[] = { 0, 0, 0, 0, 0, 0, 0, 0 };

		colormap = XDefaultColormap(_x11_display, screen);
		XAllocNamedColor(_x11_display, colormap, "black", &black, &dummy);
		bm_no = XCreateBitmapFromData(_x11_display, _x11_window, no_data, 8, 8);
		_x11_hidden_cursor = XCreatePixmapCursor(_x11_display, bm_no, bm_no, &black, &black, 0, 0);

		_wm_delete_message = XInternAtom(_x11_display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(_x11_display, _x11_window, &_wm_delete_message, 1);

		oswindow_set_window(_x11_display, _x11_window);
		bgfx::x11SetDisplayWindow(_x11_display, _x11_window);
		XMapRaised(_x11_display, _x11_window);

		// Save screen configuration
		_screen_config = XRRGetScreenInfo(_x11_display, RootWindow(_x11_display, screen));

		Rotation rr_old_rot;
		const SizeID rr_old_sizeid = XRRConfigCurrentConfiguration(_screen_config, &rr_old_rot);

		// Start main thread
		MainThreadArgs mta;
		mta.fs = fs;
		mta.cs = cs;

		Thread main_thread;
		main_thread.start(func, &mta);

		while (!s_exit)
		{
			pump_events();
		}

		main_thread.stop();

		// Restore previous screen configuration
		Rotation rr_rot;
		const SizeID rr_sizeid = XRRConfigCurrentConfiguration(_screen_config, &rr_rot);

		if (rr_rot != rr_old_rot || rr_sizeid != rr_old_sizeid)
		{
			XRRSetScreenConfig(_x11_display
				, _screen_config
				, RootWindow(_x11_display, screen)
				, rr_old_sizeid
				, rr_old_rot
				, CurrentTime);
		}
		XRRFreeScreenConfigInfo(_screen_config);

		XDestroyWindow(_x11_display, _x11_window);
		XCloseDisplay(_x11_display);
		return EXIT_SUCCESS;
	}
Beispiel #18
0
int main(void)
{
	Display *display;
	Window window;      // initialization for a window
	int screen;         // which screen

	/* open connection with the server */
	display = XOpenDisplay(NULL);
	if (display == NULL) {
		fprintf(stderr, "cannot open display\n");
		return 0;
	}

	screen = DefaultScreen(display);

	/* set window position */
	int x = 0;
	int y = 0;

	/* border width in pixels */
	int border_width = 0;

	/* create window */
	window = XCreateSimpleWindow(display, RootWindow(display, screen), x, y, width, height, border_width,
					BlackPixel(display, screen), WhitePixel(display, screen));

	/* create graph */
	GC gc;
	XGCValues values;
	long valuemask = 0;

	gc = XCreateGC(display, window, valuemask, &values);
	XSetForeground (display, gc, BlackPixel (display, screen));
	XSetBackground(display, gc, 0X0000FF00);
	XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);

	/* map(show) the window */
	XMapWindow(display, window);
	XSync(display, 0);

	struct timespec start, finish; // time
	double elapsed;
	clock_gettime(CLOCK_MONOTONIC, &start);

	/* draw points */
	Compl z, c;
	int repeats;
	double temp, lengthsq;
	int i, j;
	for (i = 0; i < width; i++) {
		for (j = 0; j < height; j++) {
			z.real = 0.0;
			z.imag = 0.0;
			c.real = -2.0 + (double)i * (4.0 / (double)width);
			c.imag = -2.0 + (double)j * (4.0 / (double)height);
			repeats = 0;
			lengthsq = 0.0;

			while (repeats < 100000 && lengthsq < 4.0) {
				/* Theorem : If c belongs to M, then |Zn| <= 2. So Zn^2 <= 4 */
				temp = z.real * z.real - z.imag * z.imag + c.real;
				z.imag = 2 * z.real * z.imag + c.imag;
				z.real = temp;
				lengthsq = z.real * z.real + z.imag * z.imag;
				repeats++;
			}

			pixels[i][j] = 1024 * 1024 * (repeats % 256);
		}
	}

	clock_gettime(CLOCK_MONOTONIC, &finish);
	elapsed = finish.tv_sec - start.tv_sec;
	elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
	printf("Total time: %lfs\n", elapsed);
	printf("Drawing...\n");

	/* drawing */
	for (i = 0; i < width; i++) {
		for (j = 0; j < height; j++) {
			XSetForeground(display, gc, pixels[i][j]);
			XDrawPoint(display, window, gc, i, j);
		}
	}
	XFlush(display);
	sleep(2);

	return 0;
}
Beispiel #19
0
static int SetXi18nSelectionOwner(Xi18n i18n_core)
{
    Display *dpy = i18n_core->address.dpy;
    Window ims_win = i18n_core->address.im_window;
    Window root = RootWindow (dpy, DefaultScreen (dpy));
    Atom realtype;
    int realformat;
    unsigned long bytesafter;
    long *data=NULL;
    unsigned long length;
    Atom atom;
    int i;
    int found;
    int forse = False;
    char buf[256];

    (void)snprintf(buf, 256, "@server=%s", i18n_core->address.im_name);
    if ((atom = XInternAtom(dpy, buf, False)) == 0)
        return False;
    i18n_core->address.selection = atom;

    if (XIM_Servers == None)
        XIM_Servers = XInternAtom (dpy, XIM_SERVERS, False);
    /*endif*/
    XGetWindowProperty (dpy,
                        root,
                        XIM_Servers,
                        0L,
                        1000000L,
                        False,
                        XA_ATOM,
                        &realtype,
                        &realformat,
                        &length,
                        &bytesafter,
                        (unsigned char **) (&data));
    if (realtype != None && (realtype != XA_ATOM || realformat != 32)) {
        if (data != NULL)
            XFree ((char *) data);
        return False;
    }

    found = False;
    for (i = 0; i < length; i++) {
        if (data[i] == atom) {
            Window owner;
            found = True;
            if ((owner = XGetSelectionOwner (dpy, atom)) != ims_win) {
                if (owner == None  ||  forse == True)
                    XSetSelectionOwner (dpy, atom, ims_win, CurrentTime);
                else
                    return False;
            }
            break;
        }
    }

    if (found == False) {
        XSetSelectionOwner (dpy, atom, ims_win, CurrentTime);
        XChangeProperty (dpy,
                         root,
                         XIM_Servers,
                         XA_ATOM,
                         32,
                         PropModePrepend,
                         (unsigned char *) &atom,
                         1);
    }
    else {
	/* 
	 * We always need to generate the PropertyNotify to the Root Window 
	 */
        XChangeProperty (dpy,
                         root,
                         XIM_Servers,
                         XA_ATOM,
                         32,
                         PropModePrepend,
                         (unsigned char *) data,
                         0);
    }
    if (data != NULL)
        XFree ((char *) data);
    
    /* Intern "LOCALES" and "TRANSOPORT" Target Atoms */
    i18n_core->address.Localename = XInternAtom (dpy, LOCALES, False);
    i18n_core->address.Transportname = XInternAtom (dpy, TRANSPORT, False);
    return (XGetSelectionOwner (dpy, atom) == ims_win);
}
Beispiel #20
0
int main ( int argc, char **argv )
{

    // Get DISPLAY
    const char *display_str = getenv ( "DISPLAY" );
    if ( !( display = XOpenDisplay ( display_str ) ) ) {
        fprintf ( stderr, "cannot open display!\n" );
        return EXIT_FAILURE;
    }

    TASSERT( display != NULL );
    Screen *screen = DefaultScreenOfDisplay ( display );
    Window root    = RootWindow ( display, XScreenNumberOfScreen ( screen ) );
    Window mw = XCreateSimpleWindow ( display, root, 0, 0, 200, 100,
                                           config.menu_bw,
                                           color_get ( display, config.menu_bc ),
                                           color_get ( display, config.menu_bg ) );
    TASSERT( mw != None );

    textbox_setup ( config.menu_bg, config.menu_fg, 
                    config.menu_hlbg, config.menu_hlfg ); 
    textbox *box = textbox_create(mw , TB_EDITABLE|TB_AUTOWIDTH|TB_AUTOHEIGHT, 0,0, -1, -1, NORMAL, "test");
    TASSERT( box != NULL );

    textbox_cursor_end ( box );
    TASSERT ( box->cursor == 4); 
    textbox_cursor ( box, -1 );
    TASSERT ( box->cursor == 0 ); 
    textbox_cursor ( box, 8 );
    TASSERT ( box->cursor == 4 ); 
    textbox_cursor ( box, 2 );
    TASSERT ( box->cursor == 2 ); 
    textbox_insert ( box, 3, "bo");
    TASSERT ( strcmp(box->text, "tesbot") == 0 ); 
    textbox_cursor_end ( box );
    TASSERT ( box->cursor == 6); 

    TASSERT( textbox_get_width( box) > 0 );
    TASSERT( textbox_get_height( box) > 0 );

    TASSERT( textbox_get_width( box) >= textbox_get_font_width( box)  );
    TASSERT( textbox_get_height( box) >= textbox_get_font_height( box)  );

    TASSERT( textbox_get_estimated_char_width ( box) > 0 );

    textbox_cursor_bkspc ( box );
    TASSERT ( strcmp(box->text, "tesbo") == 0 ); 
    TASSERT ( box->cursor == 5); 

    textbox_cursor_dec ( box );
    TASSERT ( box->cursor == 4); 
    textbox_cursor_del ( box );
    TASSERT ( strcmp(box->text, "tesb") == 0 ); 
    textbox_cursor_dec ( box );
    TASSERT ( box->cursor == 3); 
    textbox_cursor_inc ( box );
    TASSERT ( box->cursor == 4); 
    textbox_cursor_inc ( box );
    TASSERT ( box->cursor == 4); 
    // Cursor after delete section.
    textbox_delete ( box, 0, 1 );
    TASSERT ( strcmp(box->text, "esb") == 0 ); 
    TASSERT ( box->cursor == 3); 
    // Cursor before delete.
    textbox_text( box, "aap noot mies");
    TASSERT ( strcmp(box->text, "aap noot mies") == 0 ); 
    textbox_cursor( box, 3 );
    TASSERT ( box->cursor == 3); 
    textbox_delete ( box, 3, 6 );
    TASSERT ( strcmp(box->text, "aapmies") == 0 ); 
    TASSERT ( box->cursor == 3); 

    // Cursor within delete
    textbox_text( box, "aap noot mies");
    TASSERT ( strcmp(box->text, "aap noot mies") == 0 ); 
    textbox_cursor( box, 5 );
    TASSERT ( box->cursor == 5); 
    textbox_delete ( box, 3, 6 );
    TASSERT ( strcmp(box->text, "aapmies") == 0 ); 
    TASSERT ( box->cursor == 3); 
    // Cursor after delete. 
    textbox_text( box, "aap noot mies");
    TASSERT ( strcmp(box->text, "aap noot mies") == 0 ); 
    textbox_cursor( box, 11 );
    TASSERT ( box->cursor == 11); 
    textbox_delete ( box, 3, 6 );
    TASSERT ( strcmp(box->text, "aapmies") == 0 ); 
    TASSERT ( box->cursor == 5); 


    textbox_font ( box, HIGHLIGHT );
    textbox_draw( box );

    textbox_show( box );
    textbox_move ( box, 12, 13);
    TASSERT ( box->x == 12 );
    TASSERT ( box->y == 13 );
    textbox_hide( box );

    textbox_free(box);
    textbox_cleanup();
    XDestroyWindow ( display, mw);
    XCloseDisplay ( display );
}
Beispiel #21
0
/*
 * Create an RGB, double-buffered window.
 * Return the window and context handles.
 */
static void
make_window( Display *dpy, const char *name,
             int x, int y, int width, int height,
             Window *winRet, GLXContext *ctxRet)
{
   int attrib[] = { GLX_RGBA,
		    GLX_RED_SIZE, 1,
		    GLX_GREEN_SIZE, 1,
		    GLX_BLUE_SIZE, 1,
		    GLX_DOUBLEBUFFER,
		    GLX_DEPTH_SIZE, 1,
		    None };
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;
   GLXContext ctx;
   XVisualInfo *visinfo;

   scrnum = DefaultScreen( dpy );
   root = RootWindow( dpy, scrnum );

   visinfo = glXChooseVisual( dpy, scrnum, attrib );
   if (!visinfo) {
      printf("Error: couldn't get an RGB, Double-buffered visual\n");
      exit(1);
   }

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow( dpy, root, 0, 0, width, height,
		        0, visinfo->depth, InputOutput,
		        visinfo->visual, mask, &attr );

   /* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(dpy, win, &sizehints);
      XSetStandardProperties(dpy, win, name, name,
                              None, (char **)NULL, 0, &sizehints);
   }

   ctx = glXCreateContext( dpy, visinfo, NULL, True );
   if (!ctx) {
      printf("Error: glXCreateContext failed\n");
      exit(1);
   }

   XFree(visinfo);

   *winRet = win;
   *ctxRet = ctx;
}
Beispiel #22
0
int main(int argc, const char **argv) {
    /* process command line arguments */
    command_line(argc,argv);
    /* some ugly but needed initializations */
    XInitThreads();
    g_type_init();
    /* open X connection & create window */
    if (!(dpy= XOpenDisplay(NULL))) die("Failed opening X display\n");
    scr = DefaultScreen(dpy);
    root = RootWindow(dpy,scr);
    if (!sw) sw = DisplayWidth(dpy,scr);
    if (!sh) sh = DisplayHeight(dpy,scr);
    win = XCreateSimpleWindow(dpy,root,0,0,sw,sh,1,0,0);
    /* set attributes and map */
    XStoreName(dpy,win,"Slider");
    XSetWindowAttributes wa;
    wa.event_mask =  ExposureMask|KeyPressMask|ButtonPressMask|StructureNotifyMask;
    XChangeWindowAttributes(dpy,win,CWEventMask,&wa);
    XMapWindow(dpy, win);
    /* check for EWMH compliant WM */
    Atom type, NET_CHECK = XInternAtom(dpy,"_NET_SUPPORTING_WM_CHECK",False);
    Window *wins;
    int fmt;
    unsigned long after,nwins;
    XGetWindowProperty(dpy,root,NET_CHECK,0,UINT_MAX,False,XA_WINDOW,
                       &type,&fmt,&nwins,&after,(unsigned char**)&wins);
    if ( type == XA_WINDOW && nwins > 0 && wins[0] != None) netwm = True;
    else netwm = False;
    XFree(wins);
    /* set up Xlib graphics contexts */
    XGCValues val;
    XColor color;
    Colormap cmap = DefaultColormap(dpy,scr);
    /* black, background, default */
    val.foreground = BlackPixel(dpy,scr);
    gc = XCreateGC(dpy,root,GCForeground,&val);
    /* white, mute_white */
    val.foreground = WhitePixel(dpy,scr);
    wgc = XCreateGC(dpy,root,GCForeground,&val);
    /* dotted lines for loading slides in overview mode */
    XAllocNamedColor(dpy,cmap,colors[0],&color,&color);
    val.foreground = color.pixel;
    val.line_style = LineDoubleDash;
    lgc = XCreateGC(dpy,root,GCForeground|GCLineStyle,&val); /* lines */
    /* highlight box for slide overview */
    XAllocNamedColor(dpy,cmap,colors[1],&color,&color);
    val.foreground = color.pixel;
    val.line_width = 3;
    hgc = XCreateGC(dpy,root,GCForeground|GCLineWidth,&val);
    /* pixmap for overview */
    sorter.view = XCreatePixmap(dpy,root,sw,sh,DefaultDepth(dpy,scr));
    /* create cursor(s) */
    char curs_data = 0;
    Pixmap curs_map = XCreateBitmapFromData(dpy,win,&curs_data,1,1);
    invisible_cursor = XCreatePixmapCursor(dpy,curs_map,curs_map,&color,&color,0,0);
    XFreePixmap(dpy,curs_map);
    /* start rendering thread */
    pthread_t render_thread;
    pthread_create(&render_thread,NULL,render_all,NULL);
    /* wait for first frame to render */
    while (!first_page_rendered) usleep(50000);
    if (fullscreen_mode) {
        fullscreen_mode = ! fullscreen_mode;
        fullscreen(NULL);
    }
    XDefineCursor(dpy,win,invisible_cursor);
    /* main loop */
    draw(NULL);
    XEvent ev;
    running = True;
    if (autoplay && autoplaydelay > 0) {
        int fd, r;
        struct timeval tv;
        fd_set rfds;
        fd = ConnectionNumber(dpy);
        while (running) {
            memset(&tv,0,sizeof(tv));
            tv.tv_sec = autoplaydelay;
            FD_ZERO(&rfds);
            FD_SET(fd,&rfds);
            r = select(fd+1,&rfds,0,0,&tv);
            if (r == 0) move("down");
            while (XPending(dpy)) {
                XNextEvent(dpy,&ev);
                if (ev.type > 32) continue; /* workaround for cairo F(&* up. */
                if (handler[ev.type]) handler[ev.type](&ev);
            }
        }
    }
    else while ( running && ! XNextEvent(dpy, &ev) ) {
            if (ev.type > 32) continue; /* workaround for cairo F(&* up. */
            if (handler[ev.type]) handler[ev.type](&ev);
        }

    /* clean up */
    if (presenter_mode) {
        printf("SLIDER END\n");
        fflush(stdout);
    }
    if (show.rendered < show.count) { /* quiting before render thread ended */
        cancel_render = True;	/* give thread time to quit */
        usleep(250000);
    }
    int i;
    for (i = 0; i < show.rendered; i++)
        XFreePixmap(dpy,show.slide[i]);
    XFreePixmap(dpy,sorter.view);
    free(show.slide);
    free(uri);
    XCloseDisplay(dpy);
    return 0;
}
Beispiel #23
0
JNIEXPORT jboolean JNICALL
Java_sun_java2d_opengl_GLXSurfaceData_initPixmap
    (JNIEnv *env, jobject glxsd,
     jlong pCtx, jlong pData,
     jint width, jint height, jint depth)
{
    OGLSDOps *oglsdo = (OGLSDOps *)jlong_to_ptr(pData);
    OGLContext *oglc = (OGLContext *)jlong_to_ptr(pCtx);
    GLXSDOps *glxsdo;
    GLXCtxInfo *ctxinfo;
    Pixmap pixmap;
    GLXPixmap glxpixmap;

    J2dTraceLn2(J2D_TRACE_INFO, "in GLXSD_initPixmap (w=%d h=%d)",
                width, height);

    if (oglsdo == NULL) {
        J2dTraceLn(J2D_TRACE_ERROR, "ops are null");
        return JNI_FALSE;
    }

    glxsdo = (GLXSDOps *)oglsdo->privOps;
    if (glxsdo == NULL) {
        J2dTraceLn(J2D_TRACE_ERROR, "glx ops are null");
	return JNI_FALSE;
    }

    if (oglc == NULL) {
        J2dTraceLn(J2D_TRACE_ERROR, "context is null");
        return JNI_FALSE;
    }

    ctxinfo = (GLXCtxInfo *)oglc->ctxInfo;
    if (ctxinfo == NULL) {
        J2dTraceLn(J2D_TRACE_ERROR, "glx context info is null");
        return JNI_FALSE;
    }

    pixmap = XCreatePixmap(awt_display,
                           RootWindow(awt_display,  
                                      glxsdo->configData->awt_visInfo.screen),
                           width, height, depth);
    if (pixmap == 0) {
        J2dTraceLn(J2D_TRACE_ERROR, "could not create pixmap");
        return JNI_FALSE;
    }

    glxpixmap = j2d_glXCreatePixmap(awt_display, ctxinfo->fbconfig,
                                    pixmap, NULL);
    if (glxpixmap == 0) {
        J2dTraceLn(J2D_TRACE_ERROR, "could not create glx pixmap");
        XFreePixmap(awt_display, pixmap);
        return JNI_FALSE;
    }

    oglsdo->drawableType = OGLSD_PIXMAP;
    oglsdo->width = width;
    oglsdo->height = height;
    oglsdo->xOffset = 0;
    oglsdo->yOffset = 0;
    oglsdo->isPremult = JNI_TRUE;

    glxsdo->drawable = glxpixmap;
    glxsdo->xdrawable = pixmap;

    return JNI_TRUE;
}
Beispiel #24
0
static void
X11_GL_InitExtensions(_THIS)
{
    Display *display = ((SDL_VideoData *) _this->driverdata)->display;
    int screen = DefaultScreen(display);
    XVisualInfo *vinfo;
    XSetWindowAttributes xattr;
    Window w;
    GLXContext context;
    const char *(*glXQueryExtensionsStringFunc) (Display *, int);
    const char *extensions;

    vinfo = X11_GL_GetVisual(_this, display, screen);
    if (!vinfo) {
        return;
    }
    xattr.background_pixel = 0;
    xattr.border_pixel = 0;
    xattr.colormap =
        X11_XCreateColormap(display, RootWindow(display, screen), vinfo->visual,
                        AllocNone);
    w = X11_XCreateWindow(display, RootWindow(display, screen), 0, 0, 32, 32, 0,
                      vinfo->depth, InputOutput, vinfo->visual,
                      (CWBackPixel | CWBorderPixel | CWColormap), &xattr);
    context = _this->gl_data->glXCreateContext(display, vinfo, NULL, True);
    if (context) {
        _this->gl_data->glXMakeCurrent(display, w, context);
    }
    X11_XFree(vinfo);

    glXQueryExtensionsStringFunc =
        (const char *(*)(Display *, int)) X11_GL_GetProcAddress(_this,
                                                                "glXQueryExtensionsString");
    if (glXQueryExtensionsStringFunc) {
        extensions = glXQueryExtensionsStringFunc(display, screen);
    } else {
        extensions = NULL;
    }

    /* Check for GLX_EXT_swap_control(_tear) */
    _this->gl_data->HAS_GLX_EXT_swap_control_tear = SDL_FALSE;
    if (HasExtension("GLX_EXT_swap_control", extensions)) {
        _this->gl_data->glXSwapIntervalEXT =
            (void (*)(Display*,GLXDrawable,int))
                X11_GL_GetProcAddress(_this, "glXSwapIntervalEXT");
        if (HasExtension("GLX_EXT_swap_control_tear", extensions)) {
            _this->gl_data->HAS_GLX_EXT_swap_control_tear = SDL_TRUE;
        }
    }

    /* Check for GLX_MESA_swap_control */
    if (HasExtension("GLX_MESA_swap_control", extensions)) {
        _this->gl_data->glXSwapIntervalMESA =
            (int(*)(int)) X11_GL_GetProcAddress(_this, "glXSwapIntervalMESA");
        _this->gl_data->glXGetSwapIntervalMESA =
            (int(*)(void)) X11_GL_GetProcAddress(_this,
                                                   "glXGetSwapIntervalMESA");
    }

    /* Check for GLX_SGI_swap_control */
    if (HasExtension("GLX_SGI_swap_control", extensions)) {
        _this->gl_data->glXSwapIntervalSGI =
            (int (*)(int)) X11_GL_GetProcAddress(_this, "glXSwapIntervalSGI");
    }

    /* Check for GLX_EXT_visual_rating */
    if (HasExtension("GLX_EXT_visual_rating", extensions)) {
        _this->gl_data->HAS_GLX_EXT_visual_rating = SDL_TRUE;
    }

    /* Check for GLX_EXT_visual_info */
    if (HasExtension("GLX_EXT_visual_info", extensions)) {
        _this->gl_data->HAS_GLX_EXT_visual_info = SDL_TRUE;
    }
    
    /* Check for GLX_EXT_create_context_es2_profile */
    if (HasExtension("GLX_EXT_create_context_es2_profile", extensions)) {
        _this->gl_data->HAS_GLX_EXT_create_context_es2_profile = SDL_TRUE;
    }

    /* Check for GLX_MESA_query_renderer */
    if (HasExtension("GLX_MESA_query_renderer", extensions)) {
        _this->gl_data->glXQueryRendererIntegerMESA =
            (int(*)(int)) X11_GL_GetProcAddress(
                _this, "glXQueryRendererIntegerMESA");
        _this->gl_data->glXQueryCurrentRendererIntegerMESA =
            (int(*)(void)) X11_GL_GetProcAddress(
                _this, "glXQueryCurrentRendererIntegerMESA");
        _this->gl_data->glXQueryRendererStringMESA =
            (int(*)(int)) X11_GL_GetProcAddress(
                _this, "glXQueryRendererStringMESA");
        _this->gl_data->glXQueryCurrentRendererStringMESA =
            (int(*)(void)) X11_GL_GetProcAddress(
                _this, "glXQueryCurrentRendererStringMESA");
    }
    
    /* Check for GL_NVX_gpu_memory_info */
    if (HasExtension("GL_NVX_gpu_memory_info", extensions)) {
        _this->gl_data->HAS_GL_NVX_gpu_memory_info = SDL_TRUE;
    }
    
    /* Check for GL_NVX_gpu_memory_info */
    if (HasExtension("GL_NVX_gpu_memory_info", extensions)) {
        _this->gl_data->HAS_GL_NVX_gpu_memory_info = SDL_TRUE;
    }
    
    if (context) {
        _this->gl_data->glXMakeCurrent(display, None, NULL);
        _this->gl_data->glXDestroyContext(display, context);
    }
    X11_XDestroyWindow(display, w);
    X11_PumpEvents(_this);
}
Beispiel #25
0
void
getGraphFromViewman(int i)
{
 /** This routine should be called right after a read of the graph key
     was made from the viewport manager (or defined in some other way). **/

  int j,k,xPointsNeeded;
  pointListStruct *llPtr;
  pointStruct     *p;

  readViewman(&(graphArray[i].xmin),floatSize);
  readViewman(&(graphArray[i].xmax),floatSize);
  readViewman(&(graphArray[i].ymin),floatSize);
  readViewman(&(graphArray[i].ymax),floatSize);
  readViewman(&(graphArray[i].xNorm),floatSize);
  readViewman(&(graphArray[i].yNorm),floatSize);
  readViewman(&(graphArray[i].spadUnitX),floatSize);
  readViewman(&(graphArray[i].spadUnitY),floatSize);
  readViewman(&(graphArray[i].unitX),floatSize);
  readViewman(&(graphArray[i].unitY),floatSize);
  readViewman(&(graphArray[i].originX),floatSize);
  readViewman(&(graphArray[i].originY),floatSize);
  readViewman(&(graphArray[i].numberOfLists),intSize);

  if (!(llPtr = (pointListStruct *)malloc(graphArray[i].numberOfLists * sizeof(pointListStruct)))) {
    fprintf(stderr,"VIEW2D: Fatal Error>> Ran out of memory trying to receive a graph.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }
  graphArray[i].listOfListsOfPoints = llPtr;

  xPointsNeeded = 0;
  for (j=0; j<graphArray[i].numberOfLists; j++) {
    readViewman(&(llPtr->numberOfPoints),intSize);
    if (!(p = (pointStruct *)malloc(llPtr->numberOfPoints * sizeof(pointStruct)))) {
      fprintf(stderr,"VIEW2D: (pointStruct) ran out of memory trying to create a new graph.\n");
      exitWithAck(RootWindow(dsply,scrn),Window,-1);
    }
    llPtr->listOfPoints = p;             /** point to current point list **/
    for (k=0; k<llPtr->numberOfPoints; k++) {
      readViewman(&(p->x),floatSize);
      readViewman(&(p->y),floatSize);
      readViewman(&(p->hue),floatSize);
      readViewman(&(p->shade),floatSize);
      p++;
    }   /* for k in list of points */
    readViewman(&(llPtr->pointColor),intSize);
    readViewman(&(llPtr->lineColor),intSize);
    readViewman(&(llPtr->pointSize),intSize);

    xPointsNeeded += llPtr->numberOfPoints;
    llPtr++;
  }   /* for j in list of lists of points */

  /* read in graph state for the existing graph (override default values) */
  readViewman(&(graphStateArray[i].scaleX),floatSize);
  readViewman(&(graphStateArray[i].scaleY),floatSize);
  readViewman(&(graphStateArray[i].deltaX),floatSize);
  readViewman(&(graphStateArray[i].deltaY),floatSize);
  readViewman(&(graphStateArray[i].pointsOn),intSize);
  readViewman(&(graphStateArray[i].connectOn),intSize);
  readViewman(&(graphStateArray[i].splineOn),intSize);
  readViewman(&(graphStateArray[i].axesOn),intSize);
  readViewman(&(graphStateArray[i].axesColor),intSize);
  readViewman(&(graphStateArray[i].unitsOn),intSize);
  readViewman(&(graphStateArray[i].unitsColor),intSize);
  readViewman(&(graphStateArray[i].showing),intSize);
  graphStateArray[i].selected = yes;
  graphStateBackupArray[i] = graphStateArray[i];

  graphStateArray[i].deltaX = graphStateArray[0].deltaX;
  graphStateArray[i].deltaY = graphStateArray[0].deltaY;
  graphStateArray[i].scaleX = graphStateArray[0].scaleX;
  graphStateArray[i].scaleY = graphStateArray[0].scaleY;

  /* allocate memory for xPoints (used in drawViewport) */
  if (!(xPointsArray[i].xPoint = (XPoint *)malloc(xPointsNeeded * sizeof(XPoint)))) {
    fprintf(stderr,"VIEW2D: (XPoint) Ran out of memory (malloc) trying to create a new graph.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }
  if (!(xPointsArray[i].x10Point = (Vertex *)malloc(xPointsNeeded * sizeof(Vertex)))) {
    fprintf(stderr,
            "VIEW2D: (X10Point) Ran out of memory (malloc) trying to create a new graph.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }
  if (!(xPointsArray[i].arc = (XArc *)malloc(xPointsNeeded * sizeof(XArc)))) {
    fprintf(stderr,"VIEW2D: (XArc) Ran out of memory (malloc) trying to create a new graph.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }

}   /* getGraphFromViewman */
Beispiel #26
0
void GLWindow::initWindow(const char* windowName,bool decorate)
	{
	/* Check if the window's screen matches the context's: */
	if(screen!=context->getScreen())
		Misc::throwStdErr("GLWindow: OpenGL contexts cannot be shared between screens %d and %d on display %s",screen,context->getScreen(),context->getDisplayName());
	
	/* Get a handle to the root window: */
	root=RootWindow(context->getDisplay(),screen);
	
	/* Create an X colormap (visual might not be default): */
	colorMap=XCreateColormap(context->getDisplay(),root,context->getVisual(),AllocNone);
	
	/* Create an X window with the selected visual: */
	XSetWindowAttributes swa;
	swa.colormap=colorMap;
	swa.border_pixel=0;
	swa.override_redirect=False;
	if(fullscreen) // Create a fullscreen window
		{
		windowPos.origin[0]=0;
		windowPos.origin[1]=0;
		windowPos.size[0]=DisplayWidth(context->getDisplay(),screen);
		windowPos.size[1]=DisplayHeight(context->getDisplay(),screen);
		// decorate=false;
		swa.override_redirect=True;
		}
	swa.event_mask=PointerMotionMask|ButtonPressMask|ButtonReleaseMask|KeyPressMask|KeyReleaseMask|ExposureMask|StructureNotifyMask;
	unsigned long attributeMask=CWBorderPixel|CWColormap|CWOverrideRedirect|CWEventMask;
	window=XCreateWindow(context->getDisplay(),root,
	                     windowPos.origin[0],windowPos.origin[1],windowPos.size[0],windowPos.size[1],
	                     0,context->getDepth(),InputOutput,context->getVisual(),attributeMask,&swa);
	XSetStandardProperties(context->getDisplay(),window,windowName,windowName,None,0,0,0);
	
	if(!decorate&&!fullscreen)
		{
		/*******************************************************************
		Ask the window manager not to decorate this window:
		*******************************************************************/
		
		/* Create and fill in window manager hint structure inherited from Motif: */
		struct MotifHints // Structure to pass hints to window managers
			{
			/* Elements: */
			public:
			Misc::UInt32 flags;
			Misc::UInt32 functions;
			Misc::UInt32 decorations;
			Misc::SInt32 inputMode;
			Misc::UInt32 status;
			} hints;
		hints.flags=2U; // Only change decorations bit
		hints.functions=0U;
		hints.decorations=0U;
		hints.inputMode=0;
		hints.status=0U;
		
		/* Get the X atom to set hint properties: */
		Atom hintProperty=XInternAtom(context->getDisplay(),"_MOTIF_WM_HINTS",True);
		if(hintProperty!=None)
			{
			/* Set the window manager hint property: */
			XChangeProperty(context->getDisplay(),window,hintProperty,hintProperty,32,PropModeReplace,reinterpret_cast<unsigned char*>(&hints),5);
			}
		else
			Misc::userError("GLWindow::GLWindow: Unable to disable window decorations");
		}
	
	if(fullscreen)
		{
		/* Get relevant window manager protocol atoms: */
		Atom netwmBypassCompositorAtom=XInternAtom(context->getDisplay(),"_NET_WM_BYPASS_COMPOSITOR",True);
		if(netwmBypassCompositorAtom!=None)
			{
			/* Ask the window manager to let this window bypass the compositor: */
			XEvent bypassCompositorEvent;
			memset(&bypassCompositorEvent,0,sizeof(XEvent));
			bypassCompositorEvent.xclient.type=ClientMessage;
			bypassCompositorEvent.xclient.serial=0;
			bypassCompositorEvent.xclient.send_event=True;
			bypassCompositorEvent.xclient.display=context->getDisplay();
			bypassCompositorEvent.xclient.window=window;
			bypassCompositorEvent.xclient.message_type=netwmBypassCompositorAtom;
			bypassCompositorEvent.xclient.format=32;
			bypassCompositorEvent.xclient.data.l[0]=1; // Bypass compositor
			XSendEvent(context->getDisplay(),RootWindow(context->getDisplay(),screen),False,SubstructureRedirectMask|SubstructureNotifyMask,&bypassCompositorEvent);
			XFlush(context->getDisplay());
			}
		else
			Misc::userError("GLWindow::GLWindow: Unable to bypass desktop compositor");
		}
	
	/* Initiate window manager communication: */
	wmProtocolsAtom=XInternAtom(context->getDisplay(),"WM_PROTOCOLS",False);
	wmDeleteWindowAtom=XInternAtom(context->getDisplay(),"WM_DELETE_WINDOW",False);
	XSetWMProtocols(context->getDisplay(),window,&wmDeleteWindowAtom,1);
	
	/* Display the window on the screen: */
	XMapWindow(context->getDisplay(),window);
	
	/* Flush the X queue in case there are events in the receive queue from opening a previous window: */
	XFlush(context->getDisplay());
	
	/* Process events up until the first Expose event to determine the initial window position and size: */
	bool receivedConfigureNotify=false;
	int winX=0,winY=0;
	while(true)
		{
		XEvent event;
		XWindowEvent(context->getDisplay(),window,ExposureMask|StructureNotifyMask,&event);
		
		if(event.type==ConfigureNotify)
			{
			/* Retrieve the window position and size: */
			winX=event.xconfigure.x;
			winY=event.xconfigure.y;
			windowPos.size[0]=event.xconfigure.width;
			windowPos.size[1]=event.xconfigure.height;
			receivedConfigureNotify=true;
			}
		else if(event.type==Expose)
			{
			/* Put the event back into the queue: */
			XPutBackEvent(context->getDisplay(),&event);
			
			/* We're done here: */
			break;
			}
		}
	
	if(receivedConfigureNotify)
		{
		/*********************************************************************
		Since modern window managers ignore window positions when opening
		windows, we now need to move the window to its requested position.
		Fix suggested by William Sherman.
		*********************************************************************/
		
		if(decorate)
			{
			/* As it so happens, the initial window position is this window's offset inside its parent, so we can use that to calculate the parent position: */
			XMoveWindow(context->getDisplay(),window,windowPos.origin[0]-winX,windowPos.origin[1]-winY);
			}
		else
			{
			/* Move the window's top-left corner to the requested position: */
			XMoveWindow(context->getDisplay(),window,windowPos.origin[0],windowPos.origin[1]);
			}
		
		/* Wait for the final ConfigureNotify event to determine the final window position and size: */
		while(true)
			{
			XEvent event;
			XWindowEvent(context->getDisplay(),window,StructureNotifyMask,&event);
		
			if(event.type==ConfigureNotify)
				{
				/* Retrieve the final window position and size: */
				windowPos.origin[0]=event.xconfigure.x;
				windowPos.origin[1]=event.xconfigure.y;
				windowPos.size[0]=event.xconfigure.width;
				windowPos.size[1]=event.xconfigure.height;
				
				break;
				}
			}
		}
	
	if(fullscreen)
		{
		/* Grab pointer and keyboard: */
		XGrabPointer(context->getDisplay(),window,True,0,GrabModeAsync,GrabModeAsync,None,None,CurrentTime);
		XGrabKeyboard(context->getDisplay(),window,True,GrabModeAsync,GrabModeAsync,CurrentTime);
		}
	
	/* Initialize the OpenGL context: */
	context->init(window);
	
	/* Query needed GLX extension entry points: */
	glXSwapIntervalEXTProc=GLExtensionManager::getFunction<PFNGLXSWAPINTERVALEXTPROC>("glXSwapIntervalEXT");
	glXWaitVideoSyncSGIProc=GLExtensionManager::getFunction<PFNGLXWAITVIDEOSYNCSGIPROC>("glXWaitVideoSyncSGI");
	glXDelayBeforeSwapNVProc=GLExtensionManager::getFunction<PFNGLXDELAYBEFORESWAPNVPROC>("glXDelayBeforeSwapNV");
	}
Beispiel #27
0
/*
 * createXworkWindow()
 *
 * Utility to create an X-Window.
 * Borrowed heavily from function by the same name in xcontrol.c
 *
 */
static Window
createXWorkWindow(Display *dpy, CROddp* psa)
{
    Window                  win;
    static  XWMHints        xwmh = {
        (InputHint | StateHint ),/* flags                       */
        True,                   /* input                        */
        NormalState,            /* initial_state                */
        0,                      /* icon pixmap                  */
        0,                      /* icon window                  */
        0, 0,                   /* icon location                */
        0,                      /* icon mask                    */
        0                       /* Window group                 */
    };
    static XClassHint xch = {
        "xgks", /* resource name                */
        "Xgks"  /* class name                   */
    };
    XSizeHints              xsh = { /* Size hints for window manager*/
        (PMinSize),
        0,0,                    /* obsolete ????                */
        DEFAULT_WIDTH,          /* obsolete ????                */
        DEFAULT_HEIGHT,         /* obsolete ????                */
        MIN_WIDTH, MIN_HEIGHT,  /* minimum usefull win dim      */
        0,0,                    /* max dim (not used)           */
        0,0,                    /* not used                     */
        {0,0},                  /* not used                     */
        {0,0},                  /* not used                     */
        0,
        0,                      /* dimensions of window         */
        0
    };
    char                    *geometry=NULL;
    int                     geom_mask = 0;
    XSetWindowAttributes    xswa;   /* Set Window Attribute struct  */
    XTextProperty           window_name, icon_name;
    unsigned long           bw = 0; /* Border width                 */
    XEvent                   event; /* Event received               */
    Atom                    wm_del;

    xsh.x = psa->window_pos_x;
    xsh.y = psa->window_pos_y;
    xsh.width = psa->image_width;
    xsh.height = psa->image_height;
    geom_mask = XValue | YValue | WidthValue | HeightValue;

    /*
     * see if user specified a window position.
     */
    if ((geom_mask & XValue) || (geom_mask & YValue)) {
        xsh.flags |= USPosition;
    }

    /*
     * deal with negative position
     */
    if ((geom_mask & XValue) && (geom_mask & XNegative)) {
        xsh.x = DisplayWidth (dpy, DefaultScreen(dpy)) + xsh.x -
            xsh.width - bw * 2;
    }

    if ((geom_mask & YValue) && (geom_mask & YNegative)) {
        xsh.y = DisplayWidth (dpy, DefaultScreen(dpy)) + xsh.y -
            xsh.height - bw * 2;
    }


    /*
     * see if user specified a dimension, else we use program defaults
     */
    if ((geom_mask & WidthValue) || (geom_mask & HeightValue)) {
        xsh.flags |= USSize;
    }
    else {
        xsh.flags |= PSize;
    }

    /*
     * Ensure that the window's colormap field points to the default
     * colormap,  so that the window manager knows the correct
     * colormap to use for the window.
     */
    xswa.bit_gravity = CenterGravity;
    xswa.backing_store = WhenMapped;
    xswa.background_pixel = WhitePixel(dpy, DefaultScreen(dpy));
    xswa.border_pixel = WhitePixel(dpy, DefaultScreen(dpy)); 

    /*
     * Create the Window with the information in the XSizeHints, the
     * border width, and the border & background pixels.
     */
    win = XCreateWindow(dpy, RootWindow(dpy,DefaultScreen(dpy)),
                        xsh.x, xsh.y, xsh.width, xsh.height,
                        bw,CopyFromParent,InputOutput,CopyFromParent,
                        (CWBitGravity|CWBackingStore|CWBackPixel|CWBorderPixel),&xswa);

    /*
     * Set the standard properties for the window managers.
     */
    window_name.encoding = XA_STRING;
    window_name.format = 8;
    window_name.value = (unsigned char *) psa->window_title;
    window_name.nitems = strlen ((char *)window_name.value);

    icon_name.encoding = XA_STRING;
    icon_name.format = 8;
    icon_name.value = (unsigned char *) psa->icon_title;
    icon_name.nitems = strlen ((char *)icon_name.value);

    XSetWMProperties(dpy,win,&window_name,&icon_name,NULL,0,&xsh,&xwmh,
                     &xch);

    /*
     * Select notification of Expose event that is generated when
     * the window is first mapped (becomes visible) to the screen.
     */
    XSelectInput(dpy, win, ExposureMask);

    /*
     * Map the window to make it visible.
     */
    XMapWindow(dpy, win);

    /*
     *      get expose event as window becomes visible. we can't
     *      draw until after this
     */
    while(1) {
        /* get next event       */
        XNextEvent(dpy, &event);

        /*
         * find the last expose event on the event queue.
         */
        if (event.type == Expose && event.xexpose.count == 0) {

            /*
             * Remove any other pending Expose events from
             * the queue to avoid multiple repaints.
             */
            /*SUPPRESS570*/
            while (XCheckTypedEvent(dpy, Expose, &event));

            break;
        }
    }

    /*
     * Select input for "pause" and destroy of window.
     */
    XSelectInput(dpy,win,
                 (ButtonPressMask|KeyPressMask|StructureNotifyMask));

    /*
     * Request clientMessage events for WM_DELETE_WINDOW.
     */

    wm_del = XInternAtom(dpy,"WM_DELETE_WINDOW",False);
    XSetWMProtocols(dpy,win,&wm_del,1);

    return win;
}
Beispiel #28
0
static void
make_window(Display *x_dpy, const char *name,
            int x, int y, int width, int height,
            Window *winRet)
{
   static const EGLint attribs[] = {
      EGL_RED_SIZE, 8,
      EGL_GREEN_SIZE, 8,
      EGL_BLUE_SIZE, 8,
      EGL_ALPHA_SIZE, 8,
      EGL_DEPTH_SIZE, 8,
      EGL_NONE
   };

   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;
   XVisualInfo *visInfo, visTemplate;
   int num_visuals;
   EGLConfig config;
   EGLint num_configs, vid;

   scrnum = DefaultScreen( x_dpy );
   root = RootWindow( x_dpy, scrnum );

   if (!eglChooseConfig(dpy, attribs, &config, 1, &num_configs) ||
       !num_configs) {
      printf("Error: couldn't get an EGL visual config\n");
      exit(1);
   }

   if (!eglGetConfigAttrib(dpy, config, EGL_NATIVE_VISUAL_ID, &vid)) {
      printf("Error: eglGetConfigAttrib() failed\n");
      exit(1);
   }

   /* The X window visual must match the EGL config */
   visTemplate.visualid = vid;
   visInfo = XGetVisualInfo(x_dpy, VisualIDMask, &visTemplate, &num_visuals);
   if (!visInfo) {
      printf("Error: couldn't get X visual\n");
      exit(1);
   }

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap( x_dpy, root, visInfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   attr.override_redirect = 0;
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

   win = XCreateWindow( x_dpy, root, 0, 0, width, height,
		        0, visInfo->depth, InputOutput,
		        visInfo->visual, mask, &attr );

   /* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(x_dpy, win, &sizehints);
      XSetStandardProperties(x_dpy, win, name, name,
                              None, (char **)NULL, 0, &sizehints);
   }

   ctx_win = eglCreateContext(dpy, config, EGL_NO_CONTEXT, NULL );
   if (!ctx_win) {
      printf("Error: eglCreateContext failed\n");
      exit(1);
   }

   surf_win = eglCreateWindowSurface(dpy, config, win, NULL);

   XFree(visInfo);

   *winRet = win;
}
Beispiel #29
0
/* Create and set up our X11 dialog box indow. */
static int
X11_MessageBoxCreateWindow( SDL_MessageBoxDataX11 *data )
{
    int x, y;
    XSizeHints *sizehints;
    XSetWindowAttributes wnd_attr;
    Atom _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DIALOG;
    Display *display = data->display;
    SDL_WindowData *windowdata = NULL;
    const SDL_MessageBoxData *messageboxdata = data->messageboxdata;

    if ( messageboxdata->window ) {
        SDL_DisplayData *displaydata =
            (SDL_DisplayData *) SDL_GetDisplayForWindow(messageboxdata->window)->driverdata;
        windowdata = (SDL_WindowData *)messageboxdata->window->driverdata;
        data->screen = displaydata->screen;
    } else {
        data->screen = DefaultScreen( display );
    }

    data->event_mask = ExposureMask |
                       ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
                       StructureNotifyMask | FocusChangeMask | PointerMotionMask;
    wnd_attr.event_mask = data->event_mask;

    data->window = X11_XCreateWindow(
                       display, RootWindow(display, data->screen),
                       0, 0,
                       data->dialog_width, data->dialog_height,
                       0, CopyFromParent, InputOutput, CopyFromParent,
                       CWEventMask, &wnd_attr );
    if ( data->window == None ) {
        return SDL_SetError("Couldn't create X window");
    }

    if ( windowdata ) {
        /* http://tronche.com/gui/x/icccm/sec-4.html#WM_TRANSIENT_FOR */
        X11_XSetTransientForHint( display, data->window, windowdata->xwindow );
    }

    X11_XStoreName( display, data->window, messageboxdata->title );

    /* Let the window manager know this is a dialog box */
    _NET_WM_WINDOW_TYPE = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
    _NET_WM_WINDOW_TYPE_DIALOG = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False);
    X11_XChangeProperty(display, data->window, _NET_WM_WINDOW_TYPE, XA_ATOM, 32,
                    PropModeReplace,
                    (unsigned char *)&_NET_WM_WINDOW_TYPE_DIALOG, 1);

    /* Allow the window to be deleted by the window manager */
    data->wm_protocols = X11_XInternAtom( display, "WM_PROTOCOLS", False );
    data->wm_delete_message = X11_XInternAtom( display, "WM_DELETE_WINDOW", False );
    X11_XSetWMProtocols( display, data->window, &data->wm_delete_message, 1 );

    if ( windowdata ) {
        XWindowAttributes attrib;
        Window dummy;

        X11_XGetWindowAttributes(display, windowdata->xwindow, &attrib);
        x = attrib.x + ( attrib.width - data->dialog_width ) / 2;
        y = attrib.y + ( attrib.height - data->dialog_height ) / 3 ;
        X11_XTranslateCoordinates(display, windowdata->xwindow, RootWindow(display, data->screen), x, y, &x, &y, &dummy);
    } else {
        x = ( DisplayWidth( display, data->screen ) - data->dialog_width ) / 2;
        y = ( DisplayHeight( display, data->screen ) - data->dialog_height ) / 3 ;
    }
    X11_XMoveWindow( display, data->window, x, y );

    sizehints = X11_XAllocSizeHints();
    if ( sizehints ) {
        sizehints->flags = USPosition | USSize | PMaxSize | PMinSize;
        sizehints->x = x;
        sizehints->y = y;
        sizehints->width = data->dialog_width;
        sizehints->height = data->dialog_height;

        sizehints->min_width = sizehints->max_width = data->dialog_width;
        sizehints->min_height = sizehints->max_height = data->dialog_height;

        X11_XSetWMNormalHints( display, data->window, sizehints );

        X11_XFree( sizehints );
    }

    X11_XMapRaised( display, data->window );
    return 0;
}
Beispiel #30
0
static void grab_keys(int screen)
{
    // use default input method
    XIM xim = XOpenIM(dpy, NULL, NULL, NULL);
    if (xim == NULL)
        error_exit("XOpenIM failed");

    XIMStyle xim_style = 0;
    if (xim)
    {
        XIMStyles *xim_styles;
        char* imvalret = XGetIMValues (xim, XNQueryInputStyle, &xim_styles, NULL);
        if (imvalret != NULL || xim_styles == NULL)
            error_exit("input method doesn't support any styles");

        if (xim_styles)
        {
            int i;
            for (i = 0;  i < xim_styles->count_styles;  i++)
            {
                if (xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing))
                {
                    xim_style = xim_styles->supported_styles[i];
                    break;
                }
            }
            if (xim_style == 0)
                error_exit("input method doesn't support the style we support");
            XFree(xim_styles);
        }
    }

    XSetWindowAttributes attr;
    attr.event_mask = (KeyPressMask | KeyReleaseMask);

    Window root = RootWindow(dpy, screen);
    Window w = root;
    XWindowAttributes wattr;
    XGetWindowAttributes(dpy, w, &wattr);

    XSelectInput(dpy, w, attr.event_mask);

    // Grab all supported keys
    KeySym ks;
    for (ks = 0; ks <= 255; ks++)
    {
        KeyCode kc = XKeysymToKeycode(dpy, ks);
        if (kc != 0)
        {
            XGrabKey(dpy, kc,         0, root, False, GrabModeAsync, GrabModeAsync);
            XGrabKey(dpy, kc, ShiftMask, root, False, GrabModeAsync, GrabModeAsync);
        }
    }
    int iks;
    for (iks = 0; iks < nkeygrabs; iks++)
    {
        KeyCode kc = XKeysymToKeycode(dpy, keygrabs[iks]);
        if (kc != 0)
        {
            XGrabKey(dpy, kc,         0, root, False, GrabModeAsync, GrabModeAsync);
            XGrabKey(dpy, kc, ShiftMask, root, False, GrabModeAsync, GrabModeAsync);
        }
    }

    XIC xic = NULL;
    if (xim && xim_style)
    {
        xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, w, XNFocusWindow, w, NULL);
        if (xic == NULL)
            error_exit("XCreateIC failed");
    }
}