Exemple #1
0
int main(int argc,char *argv[]) {
 XSetWindowAttributes xswa;
 XWindowAttributes wattr;
 char *displayname = NULL;
 unsigned long mask = 0;
 Display *dpy;
 Window root;
 Window win;
 GC mgc;
 Visual vis;
 int c;
 int x1     = 0;
 int y1     = 0;
 int depth;
 int width  = 0;
 int height = 0;
 Pixmap bg;

 // get options...
 // ---------------
 while (1) {
  int option_index = 0;
  static struct option long_options[] =
  {
   {"display"    , 1 , 0 , 'd'},
   {"x1"         , 1 , 0 , 'x'},
   {"y1"         , 1 , 0 , 'y'},
   {"width"      , 1 , 0 , 'w'},
   {"height"     , 1 , 0 , 'e'},
   {"help"       , 0 , 0 , 'h'},
   {0            , 0 , 0 , 0  }
  };

  c = getopt_long (argc, argv, "hd:x:y:w:e:",long_options, &option_index);
  if (c == -1)
   break;

  switch (c) {
    case 0:
     break;

    case 'h':
     usage();

    case 'd':
     displayname = (char*)malloc(80*sizeof(char));
     strcpy(displayname,optarg);
     break;

    case 'x':
     x1 = atoi(optarg);
     break;

    case 'y':
     y1 = atoi(optarg);
     break;

    case 'w':
     width = atoi(optarg);
     break;

    case 'e':
     height = atoi(optarg);
     break;

    default:
     /*fprintf (stderr,"?? getopt returned character code 0%o ??\n", c);*/
     usage();
     exit(1);
  }
 }

 // open display...
 // -----------------
 dpy = XOpenDisplay (displayname);
 if (!dpy) {
  fprintf (stderr, "unable to open display %s\n", XDisplayName(displayname));
  exit (1);
 }

 // get screen dimensions...
 // --------------------------
 if (width <= 0) {
  width = DisplayWidth(dpy,XDefaultScreen(dpy));
 }
 if (height <= 0) {
  height = DisplayHeight(dpy,XDefaultScreen(dpy));
 }

 // get root window and default context
 // ------------------------------------
 root  = RootWindow  (dpy,XDefaultScreen(dpy));
 mgc   = DefaultGC   (dpy,XDefaultScreen(dpy));
 depth = DefaultDepth(dpy,XDefaultScreen(dpy));

 xswa.event_mask        = EnterWindowMask | 
  LeaveWindowMask         | 
  ExposureMask            | 
  VisibilityChangeMask    | 
  StructureNotifyMask     | 
  SubstructureNotifyMask  | 
  SubstructureRedirectMask
 ; 
 xswa.background_pixmap = None;
 xswa.override_redirect = True;
 xswa.backing_store     = NotUseful;
 xswa.save_under        = False;
 vis.visualid           = CopyFromParent;
 mask  |= (
  CWBackPixmap   |
  CWOverrideRedirect |
  CWBackingStore |
  CWSaveUnder
 );

 // create windows (top,bottom,left,right)...
 // ---------------------------------------------
 win = XCreateWindow(
  dpy,root,x1,y1,width,height,0,depth,InputOutput,&vis,mask,&xswa
 );
 XMapWindow(dpy,win);
 bg = XCreatePixmap(dpy,win,width,height,depth);
 XCopyArea(dpy,win,bg,mgc,0,0,width,height,0,0);
 XFlush(dpy);

 XGetWindowAttributes(dpy, win, &wattr);
 if (wattr.all_event_masks & ButtonPressMask) {
  xswa.event_mask &= ~ButtonPressMask;
 }
 xswa.event_mask &= ~SubstructureRedirectMask;
 XSelectInput(dpy, win, xswa.event_mask);

 while(1) {
  XEvent event;
  XNextEvent (dpy, &event);
  switch (event.type) {
   case Expose:
    XCopyArea(dpy,bg,win,mgc,0,0,width,height,0,0);
    break;
  }
 }

 // flush and close...
 // -------------------
 XCloseDisplay(dpy);
}
Exemple #2
0
	int main(int argc, char **argv)
	{
		static char *string = "Hello World!";
		Display *display;
		int screen_num;
		Window win;			//窗口ID
		unsigned int width, height;	//窗口尺寸
		unsigned int border_width = 4;	//边界空白
		unsigned int display_width, display_height;//屏幕尺寸
		int count;
		XEvent report;
		GC gc;
		unsigned long valuemask = 0;
		XGCValues values;
		char *display_name = NULL;
	
		// 和X 服务器连接
		if ( (display=XOpenDisplay(display_name)) == NULL )
		{
			printf("Cannot connect to X server %s\n", 
					XDisplayName(display_name));
			exit(-1);
		}

		//获得缺省的 screen_num
		screen_num = DefaultScreen(display);

		//获得屏幕的宽度和高度
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);
	
		//指定所建立窗口的宽度和高度
		width = display_width/3;
		height = display_height/4;
	
		//建立窗口
		win = XCreateSimpleWindow(display, 	//display
			RootWindow(display,screen_num), //父窗口
			0, 0, width, height, 		//位置和大小
			border_width, 			//边界宽度
			BlackPixel(display,screen_num), //前景色
			WhitePixel(display,screen_num));//背景色
	
		//选择窗口感兴趣的事件掩码
		XSelectInput(display, win, 
			ExposureMask | KeyPressMask | 
			ButtonPressMask | StructureNotifyMask);

		//建立GC
		gc = XCreateGC(display, win, valuemask, &values);

		//显示窗口
		XMapWindow(display, win);

		//进入事件循环
		while (1)  {

			//取得队列中的事件
			XNextEvent(display, &report);
			switch  (report.type) {

			//曝光事件, 窗口应重绘
			case Expose:
				//取得最后一个曝光事件
				if (report.xexpose.count != 0) break;
	
				//写字符串
				XDrawString(display, win, gc, width/2,height/2,
					string, strlen(string));
	
				break;

			//窗口尺寸改变, 重新取得窗口的宽度和高度
			case ConfigureNotify:
				width = report.xconfigure.width;
				height = report.xconfigure.height;
				break;

			//鼠标点击或有按键, 释放资源则退出
			case ButtonPress:
			case KeyPress:
				XFreeGC(display, gc);
				XCloseDisplay(display);
				exit(1);
			default:
				
				break;
			}
		}
	}
Exemple #3
0
void _glfwSetVideoModeMODE(int screen, int mode, int rate)
{
    if (_glfwLibrary.X11.RandR.available)
    {
#if defined(_GLFW_HAS_XRANDR)
        XRRScreenConfiguration* sc;
        Window root;

        root = RootWindow(_glfwLibrary.X11.display, screen);
        sc   = XRRGetScreenInfo(_glfwLibrary.X11.display, root);

        // Remember old size and flag that we have changed the mode
        if (!_glfwLibrary.X11.FS.modeChanged)
        {
            _glfwLibrary.X11.FS.oldSizeID = XRRConfigCurrentConfiguration(sc, &_glfwLibrary.X11.FS.oldRotation);
            _glfwLibrary.X11.FS.oldWidth  = DisplayWidth(_glfwLibrary.X11.display, screen);
            _glfwLibrary.X11.FS.oldHeight = DisplayHeight(_glfwLibrary.X11.display, screen);

            _glfwLibrary.X11.FS.modeChanged = GL_TRUE;
        }

        if (rate > 0)
        {
            // Set desired configuration
            XRRSetScreenConfigAndRate(_glfwLibrary.X11.display,
                                      sc,
                                      root,
                                      mode,
                                      RR_Rotate_0,
                                      (short) rate,
                                      CurrentTime);
        }
        else
        {
            // Set desired configuration
            XRRSetScreenConfig(_glfwLibrary.X11.display,
                               sc,
                               root,
                               mode,
                               RR_Rotate_0,
                               CurrentTime);
        }

        XRRFreeScreenConfigInfo(sc);
#endif /*_GLFW_HAS_XRANDR*/
    }
    else if (_glfwLibrary.X11.VidMode.available)
    {
#if defined(_GLFW_HAS_XF86VIDMODE)
        XF86VidModeModeInfo **modelist;
        int modecount;

        // Get a list of all available display modes
        XF86VidModeGetAllModeLines(_glfwLibrary.X11.display, screen,
                                   &modecount, &modelist);

        // Unlock mode switch if necessary
        if (_glfwLibrary.X11.FS.modeChanged)
            XF86VidModeLockModeSwitch(_glfwLibrary.X11.display, screen, 0);

        // Change the video mode to the desired mode
        XF86VidModeSwitchToMode(_glfwLibrary.X11.display, screen, modelist[mode]);

        // Set viewport to upper left corner (where our window will be)
        XF86VidModeSetViewPort(_glfwLibrary.X11.display, screen, 0, 0);

        // Lock mode switch
        XF86VidModeLockModeSwitch(_glfwLibrary.X11.display, screen, 1);

        // Remember old mode and flag that we have changed the mode
        if (!_glfwLibrary.X11.FS.modeChanged)
        {
            _glfwLibrary.X11.FS.oldMode = *modelist[0];
            _glfwLibrary.X11.FS.modeChanged = GL_TRUE;
        }

        XFree(modelist);
#endif /*_GLFW_HAS_XF86VIDMODE*/
    }
}
Exemple #4
0
int
main(int argc, char *argv[])
{
	bool fast = false;
	int i;

	for (i = 1; i < argc; i++)
		/* these options take no arguments */
		if (!strcmp(argv[i], "-v")) {      /* prints version information */
			puts("dmenu-"VERSION);
			exit(0);
		} else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
			topbar = false;
		else if (!strcmp(argv[i], "-f"))   /* grabs keyboard before reading stdin */
			fast = true;
		else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
			fstrncmp = strncasecmp;
			fstrstr = cistrstr;
		} else if (i + 1 == argc)
			usage();
		/* these options take one argument */
		else if (!strcmp(argv[i], "-l"))   /* number of lines in vertical list */
			lines = atoi(argv[++i]);
		else if (!strcmp(argv[i], "-m"))
			mon = atoi(argv[++i]);
		else if (!strcmp(argv[i], "-p"))   /* adds prompt to left of input field */
			prompt = argv[++i];
		else if (!strcmp(argv[i], "-fn"))  /* font or font set */
			fonts[0] = argv[++i];
		else if (!strcmp(argv[i], "-nb"))  /* normal background color */
			normbgcolor = argv[++i];
		else if (!strcmp(argv[i], "-nf"))  /* normal foreground color */
			normfgcolor = argv[++i];
		else if (!strcmp(argv[i], "-sb"))  /* selected background color */
			selbgcolor = argv[++i];
		else if (!strcmp(argv[i], "-sf"))  /* selected foreground color */
			selfgcolor = argv[++i];
		else
			usage();

	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
		fputs("warning: no locale support\n", stderr);
	if (!(dpy = XOpenDisplay(NULL)))
		die("cannot open display\n");
	screen = DefaultScreen(dpy);
	root = RootWindow(dpy, screen);
	sw = DisplayWidth(dpy, screen);
	sh = DisplayHeight(dpy, screen);
	drw = drw_create(dpy, screen, root, sw, sh);
	drw_load_fonts(drw, fonts, LENGTH(fonts));
	if (!drw->fontcount)
		die("no fonts could be loaded.\n");
	drw_setscheme(drw, &scheme[SchemeNorm]);

	if (fast) {
		grabkeyboard();
		readstdin();
	} else {
		readstdin();
		grabkeyboard();
	}
	setup();
	run();

	return 1; /* unreachable */
}
gint
nsFreeTypeXImage::DrawString(nsRenderingContextGTK* aContext,
                            nsDrawingSurfaceGTK* aSurface, nscoord aX,
                            nscoord aY, const PRUnichar* aString,
                            PRUint32 aLength)
{

#if DEBUG_SHOW_GLYPH_BOX
  PRUint32 x, y;
  // grey shows image size
  // red shows character cells
  // green box shows text ink
#endif

  if (aLength < 1) {
    return 0;
  }

  // get the face/size from the FreeType cache
  FT_Face face = getFTFace();
  NS_ASSERTION(face, "failed to get face/size");
  if (!face)
    return 0;

  nsresult rslt;
  PRInt32 leftBearing, rightBearing, ascent, descent, width;
  rslt = doGetBoundingMetrics(aString, aLength, &leftBearing, &rightBearing,
                              &ascent, &descent, &width);
  if (NS_FAILED(rslt))
    return 0;

  // make sure we bring down enough background for blending
  rightBearing = PR_MAX(rightBearing, width+1);

  // offset in the ximage to the x origin
  PRInt32 x_origin = PR_MAX(0, -leftBearing);
  // offset in the ximage to the x origin
  PRInt32 y_origin = ascent;
  PRInt32 x_pos = x_origin;

  int image_width  = x_origin + rightBearing;
  int image_height = y_origin + PR_MAX(descent, 0);
  if ((image_width<=0) || (image_height<=0)) {
    // if we do not have any pixels then no point in trying to draw
    // eg: the space char has 0 height
    NS_ASSERTION(width>=0, "Negative width");
    return width;
  }
  Display *dpy = GDK_DISPLAY();
  Drawable win = GDK_WINDOW_XWINDOW(aSurface->GetDrawable());
  GC gc = GDK_GC_XGC(aContext->GetGC());
  XGCValues values;
  if (!XGetGCValues(dpy, gc, GCForeground, &values)) {
    NS_ERROR("failed to get foreground pixel");
    return 0;
  }
  nscolor color = nsX11AlphaBlend::PixelToNSColor(values.foreground);

#if DEBUG_SHOW_GLYPH_BOX
  // show X/Y origin
  XDrawLine(dpy, win, DefaultGC(dpy, 0), aX-2, aY, aX+2, aY);
  XDrawLine(dpy, win, DefaultGC(dpy, 0), aX, aY-2, aX, aY+2);
  // show width
  XDrawLine(dpy, win, DefaultGC(dpy, 0), aX-x_origin,  aY-y_origin-2,
                                         aX+rightBearing, aY-y_origin-2);
#endif

  //
  // Get the background
  //
  XImage *sub_image = nsX11AlphaBlend::GetBackground(dpy, DefaultScreen(dpy),
                                 win, aX-x_origin, aY-y_origin,
                                 image_width, image_height);
  if (sub_image==nsnull) {
#ifdef DEBUG
    int screen = DefaultScreen(dpy);
    // complain if the requested area is not completely off screen
    int win_width = DisplayWidth(dpy, screen);
    int win_height = DisplayHeight(dpy, screen);
    if (((int)(aX-leftBearing+image_width) > 0)  // not hidden to left
        && ((int)(aX-leftBearing) < win_width)   // not hidden to right
        && ((int)(aY-ascent+image_height) > 0)// not hidden to top
        && ((int)(aY-ascent) < win_height))   // not hidden to bottom
    {
      NS_ASSERTION(sub_image, "failed to get the image");
    }
#endif
    return 0;
  }

#if DEBUG_SHOW_GLYPH_BOX
  DEBUG_AADRAWBOX(sub_image,0,0,image_width,image_height,0,0,0,255/4);
  nscolor black NS_RGB(0,255,0);
  blendPixel blendPixelFunc = nsX11AlphaBlend::GetBlendPixel();
  // x origin
  for (x=0; x<(unsigned int)image_height; x++)
    if (x%4==0) (*blendPixelFunc)(sub_image, x_origin, x, black, 255/2);
  // y origin
  for (y=0; y<(unsigned int)image_width; y++)
    if (y%4==0) (*blendPixelFunc)(sub_image, y, ascent-1, black, 255/2);
#endif

  FTC_Image_Cache icache;
  mFt2->GetImageCache(&icache);
  if (!icache)
    return 0;

  //
  // Get aa glyphs and blend with background
  //
  blendGlyph blendGlyph = nsX11AlphaBlend::GetBlendGlyph();
  PRUint32 i, extraSurrogateLength;
  for (i=0; i<aLength; i+=1+extraSurrogateLength) {
    FT_UInt glyph_index;
    FT_Glyph glyph;
    nsresult rv;
    FT_BBox glyph_bbox;
    FT_ULong code_point = aString[i];
    extraSurrogateLength = 0;

    if(i<aLength-1 && IS_HIGH_SURROGATE(code_point) && IS_LOW_SURROGATE(aString[i+1])) {
      // if surrogate, make UCS4 code point from high aString[i] surrogate and
      // low surrogate aString[i+1]
      code_point = SURROGATE_TO_UCS4(code_point, aString[i+1]);

      // skip aString[i+1], it is already used as low surrogate
      extraSurrogateLength = 1;
    }

    mFt2->GetCharIndex(face, code_point, &glyph_index);
    if (glyph_index) {
      rv = mFt2->ImageCacheLookup(icache, &mImageDesc, glyph_index, &glyph);
    }
    if ((glyph_index) && (NS_SUCCEEDED(rv))) {
      mFt2->GlyphGetCBox(glyph, ft_glyph_bbox_pixels, &glyph_bbox);
    }
    else {
      // draw an empty box for the missing glyphs
      GetFallbackGlyphMetrics(&glyph_bbox, face);
      int x, y, w = glyph_bbox.xMax, h = glyph_bbox.yMax;
      for (x=1; x<w; x++) {
        XPutPixel(sub_image, x_pos+x, ascent-1,   values.foreground);
        XPutPixel(sub_image, x_pos+x, ascent-h, values.foreground);
      }
      for (y=1; y<h; y++) {
        XPutPixel(sub_image, x_pos+1, ascent-y, values.foreground);
        XPutPixel(sub_image, x_pos+w-1, ascent-y, values.foreground);
        x = (y*(w-2))/h;
        XPutPixel(sub_image, x_pos+x+1, ascent-y,   values.foreground);
      }
      x_pos += w + 1;
      continue;
    }

    FT_BitmapGlyph slot = (FT_BitmapGlyph)glyph;
    nsAntiAliasedGlyph aaglyph(glyph_bbox.xMax-glyph_bbox.xMin,
                               glyph_bbox.yMax-glyph_bbox.yMin, 0);
    PRUint8 buf[IMAGE_BUFFER_SIZE]; // try to use the stack for data
    if (!aaglyph.WrapFreeType(&glyph_bbox, slot, buf, IMAGE_BUFFER_SIZE)) {
      NS_ERROR("failed to wrap freetype image");
      XDestroyImage(sub_image);
      return 0;
    }

    //
    // blend the aa-glyph onto the background
    //
    NS_ASSERTION(ascent>=glyph_bbox.yMax,"glyph too tall");
    NS_ASSERTION(x_pos>=-aaglyph.GetLBearing(),"glyph extends too far to left");

#if DEBUG_SHOW_GLYPH_BOX
  // draw box around part of glyph that extends to the left
  // of the main area (negative LBearing)
  if (aaglyph.GetLBearing() < 0) {
    DEBUG_AADRAWBOX(sub_image, x_pos + aaglyph.GetLBearing(),
                    ascent-glyph_bbox.yMax,
                    -aaglyph.GetLBearing(), glyph_bbox.yMax, 255,0,0, 255/4);
  }
  // draw box around main glyph area
  DEBUG_AADRAWBOX(sub_image, x_pos, ascent-glyph_bbox.yMax,
                  aaglyph.GetAdvance(), glyph_bbox.yMax, 0,255,0, 255/4);
  // draw box around part of glyph that extends to the right
  // of the main area (negative LBearing)
  if (aaglyph.GetRBearing() > (int)aaglyph.GetAdvance()) {
    DEBUG_AADRAWBOX(sub_image, x_pos + aaglyph.GetAdvance(),
                    ascent-glyph_bbox.yMax,
                    aaglyph.GetRBearing()-aaglyph.GetAdvance(),
                    glyph_bbox.yMax, 0,0,255, 255/4);
  }
#endif
    (*blendGlyph)(sub_image, &aaglyph, sLinearWeightTable, color,
                  x_pos + aaglyph.GetLBearing(), ascent-glyph_bbox.yMax);

    x_pos += aaglyph.GetAdvance();
  }

  //
  // Send it to the display
  //
  XPutImage(dpy, win, gc, sub_image, 0, 0, aX-x_origin , aY-ascent,
            image_width, image_height);
  XDestroyImage(sub_image);

  return width;
}
Exemple #6
0
int main(int argc, char* argv[])
{
	Display *dpy = NULL;
	ASVisual *asv ;
	int screen = 0, depth = 0;
	int dummy, geom_flags = 0;
	unsigned int to_width, to_height ;
	ASGradient grad ;
	ASGradient default_grad = { 1, 11, &(default_colors[0]), 
									   &(default_offsets[0])} ;
	ASImage *grad_im = NULL;

	/* see ASView.1 : */
	set_application_name( argv[0] );
#if (HAVE_AFTERBASE_FLAG==1)
	set_output_threshold(OUTPUT_LEVEL_DEBUG);
#endif

	if( argc > 1 )
	{
	    if( strcmp( argv[1], "-h") == 0 )
	    {
			usage();
			return 0;
		}
	    /* see ASScale.1 : */
	    geom_flags = XParseGeometry( argv[1], &dummy, &dummy,
		                             &to_width, &to_height );
	}else
		usage();
	memset( &grad, 0x00, sizeof(ASGradient));

#ifndef X_DISPLAY_MISSING
    dpy = XOpenDisplay(NULL);
	_XA_WM_DELETE_WINDOW = XInternAtom( dpy, "WM_DELETE_WINDOW", False);
	screen = DefaultScreen(dpy);
	depth = DefaultDepth( dpy, screen );
#endif

	if( argc >= 5 )
	{
		int i = 2;
		/* see ASGrad.1 : */
		grad.type = atoi( argv[2] );
		grad.npoints = 0 ;
		grad.color = safemalloc( ((argc-2)/2)*sizeof(ARGB32));
		grad.offset = safemalloc( ((argc-2)/2)*sizeof(double));
		while( ++i < argc )
		{
			if( grad.npoints > 0 )
			{
				if( i == argc-1 )
					grad.offset[grad.npoints] = 1.0;
				else
					grad.offset[grad.npoints] = atof( argv[i] );
				++i ;
			}

			/* see ASTile.1 : */
			if( parse_argb_color( argv[i], &(grad.color[grad.npoints])) 
				!= argv[i] )
				if( grad.offset[grad.npoints] >= 0. && 
					grad.offset[grad.npoints]<= 1.0 )
					grad.npoints++ ;
		}
	}else
	{
		grad = default_grad ;
		if( argc >= 3 )
			grad.type = atoi( argv[2] );
	}

	if( grad.npoints <= 0 )
	{
		show_error( " not enough gradient points specified.");
		return 1;
	}

	/* Making sure tiling geometry is sane : */
#ifndef X_DISPLAY_MISSING
	if( !get_flags(geom_flags, WidthValue ) )
		to_width  = DisplayWidth(dpy, screen)*2/3 ;
	if( !get_flags(geom_flags, HeightValue ) )
		to_height = DisplayHeight(dpy, screen)*2/3 ;
#else
	if( !get_flags(geom_flags, WidthValue ) )
		to_width  = 500 ;
	if( !get_flags(geom_flags, HeightValue ) )
		to_height = 500 ;
#endif
	printf( "%s: rendering gradient of type %d to %dx%d\n",
			get_application_name(), grad.type&GRADIENT_TYPE_MASK, 
			to_width, to_height );

	/* see ASView.3 : */
	asv = create_asvisual( dpy, screen, depth, NULL );
	/* see ASGrad.2 : */
	grad_im = make_gradient( asv, &grad, to_width, to_height,
	        	             SCL_DO_ALL,
#ifndef X_DISPLAY_MISSING
							 ASA_XImage,
#else
							 ASA_ASImage,
#endif
							 0, ASIMAGE_QUALITY_DEFAULT );
	if( grad_im )
	{
#ifndef X_DISPLAY_MISSING
		/* see ASView.4 : */
		Window w = create_top_level_window( asv,
		                                    DefaultRootWindow(dpy), 32, 32,
		                        			to_width, to_height, 1, 0, NULL,
											"ASGradient", NULL );
		if( w != None )
		{
			Pixmap p ;

		  	XMapRaised   (dpy, w);
			/* see ASView.5 : */
			p = asimage2pixmap( asv, DefaultRootWindow(dpy), grad_im,
					            NULL, True );
			destroy_asimage( &grad_im );
			/* see common.c: set_window_background_and_free() : */
			p = set_window_background_and_free( w, p );
			/* see common.c: wait_closedown() : */
		}
		wait_closedown(w);
		dpy = NULL;
#else
		ASImage2file( grad_im, NULL, "asgrad.jpg", ASIT_Jpeg, NULL );
		destroy_asimage( &grad_im );
#endif
	}
    return 0 ;
}
    X11EGLSupport::X11EGLSupport()
    {
    mNativeDisplay = getNativeDisplay();
        mGLDisplay = getGLDisplay();

        int dummy;

        if (XQueryExtension((Display*)mNativeDisplay, "RANDR", &dummy, &dummy, &dummy))
        {
            XRRScreenConfiguration *screenConfig;

            mRandr = true;
            screenConfig = XRRGetScreenInfo((Display*)mNativeDisplay, DefaultRootWindow((Display*)mNativeDisplay));

            if (screenConfig)
            {
                XRRScreenSize *screenSizes;
                int nSizes = 0;
                Rotation currentRotation;
                int currentSizeID = XRRConfigCurrentConfiguration(screenConfig, &currentRotation);

                screenSizes = XRRConfigSizes(screenConfig, &nSizes);
                mCurrentMode.first.first = screenSizes[currentSizeID].width;
                mCurrentMode.first.second = screenSizes[currentSizeID].height;
                mCurrentMode.second = XRRConfigCurrentRate(screenConfig);
                mOriginalMode = mCurrentMode;

                for (int sizeID = 0; sizeID < nSizes; sizeID++)
                {
                    short *rates;
                    int nRates = 0;

                    rates = XRRConfigRates(screenConfig, sizeID, &nRates);
                    for (int rate = 0; rate < nRates; rate++)
                    {
                        VideoMode mode;

                        mode.first.first = screenSizes[sizeID].width;
                        mode.first.second = screenSizes[sizeID].height;
                        mode.second = rates[rate];

                        mVideoModes.push_back(mode);
                    }
                }
                XRRFreeScreenConfigInfo(screenConfig);
            }
        }
        else
        {
            mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
            mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
            mCurrentMode.second = 0;
            mOriginalMode = mCurrentMode;
            mVideoModes.push_back(mCurrentMode);
        }

        EGLConfig *glConfigs;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(NULL, &nConfigs);

        for (config = 0; config < nConfigs; config++)
        {
            int caveat, samples;

            getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

            if (caveat != EGL_SLOW_CONFIG)
            {
                getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
                mSampleLevels.push_back(StringConverter::toString(samples));
            }
        }

        free(glConfigs);

        removeDuplicates(mSampleLevels);
    }
Exemple #8
0
static int init_geom(client_t *c, strut_t *s)
{
    Atom win_type, state;
    int screen_x = DisplayWidth(dpy, screen);
    int screen_y = DisplayHeight(dpy, screen);
    int wmax = screen_x - s->left - s->right;
    int hmax = screen_y - s->top - s->bottom;
    int mouse_x, mouse_y;

    /* We decide the geometry for these types of windows, so we can just
     * ignore everything and return right away. If c->zoomed is set, that
     * means we've already set things up, but otherwise, we do it here. */
    if (c->zoomed)
        return 1;
    if (get_atoms(c->win, net_wm_state, XA_ATOM, 0, &state, 1, NULL) &&
            state == net_wm_state_fs) {
        c->geom.x = 0;
        c->geom.y = 0;
        c->geom.w = screen_x;
        c->geom.h = screen_y;
        return 1;
    }

    /* Here, we merely set the values; they're in the same place regardless
     * of whether the user or the program specified them. We'll distinguish
     * between the two cases later, if we need to. */
    if (c->size.flags & (USSize|PSize)) {
        if (c->size.width > 0) c->geom.w = c->size.width;
        if (c->size.height > 0) c->geom.h = c->size.height;
    }
    if (c->size.flags & (USPosition|PPosition)) {
        if (c->size.x > 0) c->geom.x = c->size.x;
        if (c->size.y > 0) c->geom.y = c->size.y;
    }

    /* Several types of windows can put themselves wherever they want, but we
     * need to read the size hints to get that position before returning. */
    if (get_atoms(c->win, net_wm_wintype, XA_ATOM, 0, &win_type, 1, NULL) &&
            CAN_PLACE_SELF(win_type))
        return 1;

    /* At this point, maybe nothing was set, or something went horribly wrong
     * and the values are garbage. So, make a guess, based on the pointer. */
    if (c->geom.x <= 0 && c->geom.y <= 0) {
        get_pointer(&mouse_x, &mouse_y);
        recalc_map(c, c->geom, mouse_x, mouse_y, mouse_x, mouse_y, s);
    }

    /* In any case, if we got this far, we need to do a further sanity check
     * and make sure that the window isn't overlapping any struts -- except
     * for transients, because they might be a panel-type client popping up a
     * notification window over themselves. */
    if (!c->trans) {
        if (c->geom.x + c->geom.w > screen_x - s->right)
            c->geom.x = screen_x - s->right - c->geom.w;
        if (c->geom.y + c->geom.h > screen_y - s->bottom)
            c->geom.y = screen_y - s->bottom - c->geom.h;
        if (c->geom.x < s->left || c->geom.w > wmax)
            c->geom.x = s->left;
        if (c->geom.y < s->top || c->geom.h > hmax)
            c->geom.y = s->top;
    }

    /* Finally, we decide if we were ultimately satisfied with the position
     * given, or if we had to make something up, so that the caller can
     * consider using some other method. */
    return c->trans || c->size.flags & USPosition;
}
/* Must be called in the gl thread */
GstGLWindow *
gst_gl_window_new (gulong external_gl_context)
{
  GstGLWindow *window = g_object_new (GST_GL_TYPE_WINDOW, NULL);
  GstGLWindowPrivate *priv = window->priv;

  EGLint config_attrib[] = {
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
    EGL_DEPTH_SIZE, 16,
    EGL_NONE
  };

  EGLint context_attrib[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };

  EGLint majorVersion;
  EGLint minorVersion;
  EGLint numConfigs;
  EGLConfig config;

  XSetWindowAttributes win_attr;
  XTextProperty text_property;
  XWMHints wm_hints;
  unsigned long mask;
  const gchar *title = "OpenGL renderer";
  Atom wm_atoms[3];

  static gint x = 0;
  static gint y = 0;

  setlocale (LC_NUMERIC, "C");

  priv->x_lock = g_mutex_new ();
  priv->cond_send_message = g_cond_new ();
  priv->running = TRUE;
  priv->visible = FALSE;
  priv->parent = 0;
  priv->allow_extra_expose_events = TRUE;

  g_mutex_lock (priv->x_lock);

  priv->device = XOpenDisplay (priv->display_name);

  XSynchronize (priv->device, FALSE);

  g_debug ("gl device id: %ld\n", (gulong) priv->device);

  priv->disp_send = XOpenDisplay (priv->display_name);

  XSynchronize (priv->disp_send, FALSE);

  g_debug ("gl display sender: %ld\n", (gulong) priv->disp_send);

  priv->screen_num = DefaultScreen (priv->device);
  priv->root = RootWindow (priv->device, priv->screen_num);
  priv->depth = DefaultDepth (priv->device, priv->screen_num);

  g_debug ("gl root id: %lud\n", (gulong) priv->root);

  priv->device_width = DisplayWidth (priv->device, priv->screen_num);
  priv->device_height = DisplayHeight (priv->device, priv->screen_num);

  priv->visual_info = g_new0 (XVisualInfo, 1);
  XMatchVisualInfo (priv->device, priv->screen_num, priv->depth, TrueColor,
      priv->visual_info);

  win_attr.event_mask =
      StructureNotifyMask | ExposureMask | VisibilityChangeMask;
  win_attr.do_not_propagate_mask = NoEventMask;

  win_attr.background_pixmap = None;
  win_attr.background_pixel = 0;
  win_attr.border_pixel = 0;

  win_attr.colormap =
      XCreateColormap (priv->device, priv->root, priv->visual_info->visual,
      AllocNone);

  mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;

  x += 20;
  y += 20;

  priv->internal_win_id = XCreateWindow (priv->device, priv->root, x, y,
      1, 1, 0, priv->visual_info->depth, InputOutput,
      priv->visual_info->visual, mask, &win_attr);

  XSync (priv->device, FALSE);

  XSetWindowBackgroundPixmap (priv->device, priv->internal_win_id, None);

  g_debug ("gl window id: %lud\n", (gulong) priv->internal_win_id);

  g_debug ("gl window props: x:%d y:%d\n", x, y);

  wm_atoms[0] = XInternAtom (priv->device, "WM_DELETE_WINDOW", True);
  if (wm_atoms[0] == None)
    g_debug ("Cannot create WM_DELETE_WINDOW\n");

  wm_atoms[1] = XInternAtom (priv->device, "WM_GL_WINDOW", False);
  if (wm_atoms[1] == None)
    g_debug ("Cannot create WM_GL_WINDOW\n");

  wm_atoms[2] = XInternAtom (priv->device, "WM_QUIT_LOOP", False);
  if (wm_atoms[2] == None)
    g_debug ("Cannot create WM_QUIT_LOOP\n");

  XSetWMProtocols (priv->device, priv->internal_win_id, wm_atoms, 2);

  wm_hints.flags = StateHint;
  wm_hints.initial_state = NormalState;
  wm_hints.input = False;

  XStringListToTextProperty ((char **) &title, 1, &text_property);

  XSetWMProperties (priv->device, priv->internal_win_id, &text_property,
      &text_property, 0, 0, NULL, &wm_hints, NULL);

  XFree (text_property.value);

  priv->gl_display = eglGetDisplay ((EGLNativeDisplayType) priv->device);

  if (eglInitialize (priv->gl_display, &majorVersion, &minorVersion))
    g_debug ("egl initialized: %d.%d\n", majorVersion, minorVersion);
  else
    g_debug ("failed to initialize egl %ld, %s\n", (gulong) priv->gl_display,
        EGLErrorString ());

  if (eglChooseConfig (priv->gl_display, config_attrib, &config, 1,
          &numConfigs))
    g_debug ("config set: %ld, %ld\n", (gulong) config, (gulong) numConfigs);
  else
    g_debug ("failed to set config %ld, %s\n", (gulong) priv->gl_display,
        EGLErrorString ());

  priv->gl_surface =
      eglCreateWindowSurface (priv->gl_display, config,
      (EGLNativeWindowType) priv->internal_win_id, NULL);
  if (priv->gl_surface != EGL_NO_SURFACE)
    g_debug ("surface created: %ld\n", (gulong) priv->gl_surface);
  else
    g_debug ("failed to create surface %ld, %ld, %ld, %s\n",
        (gulong) priv->gl_display, (gulong) priv->gl_surface,
        (gulong) priv->gl_display, EGLErrorString ());

  priv->gl_context =
      eglCreateContext (priv->gl_display, config,
      (EGLContext) (guint) external_gl_context, context_attrib);
  if (priv->gl_context != EGL_NO_CONTEXT)
    g_debug ("gl context created: %ld\n", (gulong) priv->gl_context);
  else
    g_debug ("failed to create glcontext %ld, %ld, %s\n",
        (gulong) priv->gl_context, (gulong) priv->gl_display,
        EGLErrorString ());

  if (!eglMakeCurrent (priv->gl_display, priv->gl_surface, priv->gl_surface,
          priv->gl_context))
    g_debug ("failed to make opengl context current %ld, %s\n",
        (gulong) priv->gl_display, EGLErrorString ());

  g_mutex_unlock (priv->x_lock);

  return window;
}
Exemple #10
0
/* [email protected] - Gets the real current screen size */
void get_current_screen_size(saver_info *si, saver_screen_info* ssi) {
   ssi->width = DisplayWidth(si->dpy, DefaultScreen(si->dpy));
   ssi->height = DisplayHeight (si->dpy, DefaultScreen(si->dpy));
}
Exemple #11
0
/*
 * Create a balloon-evaluation area for a Widget.
 * There can be either a "mesg" for a fixed string or "mesgCB" to generate a
 * message by calling this callback function.
 * When "mesg" is not NULL it must remain valid for as long as the balloon is
 * used.  It is not freed here.
 * Returns a pointer to the resulting object (NULL when out of memory).
 */
    BalloonEval *
gui_mch_create_beval_area(
    void	*target,
    char_u	*mesg,
    void	(*mesgCB)(BalloonEval *, int),
    void	*clientData)
{
#ifndef FEAT_GUI_GTK
    char	*display_name;	    /* get from gui.dpy */
    int		screen_num;
    char	*p;
#endif
    BalloonEval	*beval;

    if (mesg != NULL && mesgCB != NULL)
    {
	EMSG(_("E232: Cannot create BalloonEval with both message and callback"));
	return NULL;
    }

    beval = (BalloonEval *)alloc(sizeof(BalloonEval));
    if (beval != NULL)
    {
#ifdef FEAT_GUI_GTK
	beval->target = GTK_WIDGET(target);
	beval->balloonShell = NULL;
	beval->timerID = 0;
#else
	beval->target = (Widget)target;
	beval->balloonShell = NULL;
	beval->timerID = (XtIntervalId)NULL;
	beval->appContext = XtWidgetToApplicationContext((Widget)target);
#endif
	beval->showState = ShS_NEUTRAL;
	beval->x = 0;
	beval->y = 0;
	beval->msg = mesg;
	beval->msgCB = mesgCB;
	beval->clientData = clientData;

	/*
	 * Set up event handler which will keep its eyes on the pointer,
	 * and when the pointer rests in a certain spot for a given time
	 * interval, show the beval.
	 */
	addEventHandler(beval->target, beval);
	createBalloonEvalWindow(beval);

#ifndef FEAT_GUI_GTK
	/*
	 * Now create and save the screen width and height. Used in drawing.
	 */
	display_name = DisplayString(gui.dpy);
	p = strrchr(display_name, '.');
	if (p != NULL)
	    screen_num = atoi(++p);
	else
	    screen_num = 0;
	beval->screen_width = DisplayWidth(gui.dpy, screen_num);
	beval->screen_height = DisplayHeight(gui.dpy, screen_num);
#endif
    }

    return beval;
}
void GLUTAPIENTRY
glutInit(int *argcp, char **argv)
{
  char *display = NULL;
  char *str, *geometry = NULL;
#ifdef OLD_VMS
   struct timeval6 unused;
#else
   struct timeval unused;
#endif
  int i;

  if (__glutDisplay) {
    __glutWarning("glutInit being called a second time.");
    return;
  }
  /* Determine temporary program name. */
  str = strrchr(argv[0], '/');
  if (str == NULL) {
    __glutProgramName = argv[0];
  } else {
    __glutProgramName = str + 1;
  }

  /* Make private copy of command line arguments. */
  __glutArgc = *argcp;
  __glutArgv = (char **) malloc(__glutArgc * sizeof(char *));
  if (!__glutArgv)
    __glutFatalError("out of memory.");
  for (i = 0; i < __glutArgc; i++) {
    __glutArgv[i] = __glutStrdup(argv[i]);
    if (!__glutArgv[i])
      __glutFatalError("out of memory.");
  }

  /* determine permanent program name */
  str = strrchr(__glutArgv[0], '/');
  if (str == NULL) {
    __glutProgramName = __glutArgv[0];
  } else {
    __glutProgramName = str + 1;
  }

  /* parse arguments for standard options */
  for (i = 1; i < __glutArgc; i++) {
    if (!strcmp(__glutArgv[i], "-display")) {
#if defined(_WIN32)
      __glutWarning("-display option not supported by Win32 GLUT.");
#endif
      if (++i >= __glutArgc) {
        __glutFatalError(
          "follow -display option with X display name.");
      }
      display = __glutArgv[i];
      removeArgs(argcp, &argv[1], 2);
    } else if (!strcmp(__glutArgv[i], "-geometry")) {
      if (++i >= __glutArgc) {
        __glutFatalError(
          "follow -geometry option with geometry parameter.");
      }
      geometry = __glutArgv[i];
      removeArgs(argcp, &argv[1], 2);
    } else if (!strcmp(__glutArgv[i], "-direct")) {
#if defined(_WIN32)
      __glutWarning("-direct option not supported by Win32 GLUT.");
#endif
      if (!__glutTryDirect)
        __glutFatalError(
          "cannot force both direct and indirect rendering.");
      __glutForceDirect = GL_TRUE;
      removeArgs(argcp, &argv[1], 1);
    } else if (!strcmp(__glutArgv[i], "-indirect")) {
#if defined(_WIN32)
      __glutWarning("-indirect option not supported by Win32 GLUT.");
#endif
      if (__glutForceDirect)
        __glutFatalError(
          "cannot force both direct and indirect rendering.");
      __glutTryDirect = GL_FALSE;
      removeArgs(argcp, &argv[1], 1);
    } else if (!strcmp(__glutArgv[i], "-iconic")) {
      __glutIconic = GL_TRUE;
      removeArgs(argcp, &argv[1], 1);
    } else if (!strcmp(__glutArgv[i], "-gldebug")) {
      __glutDebug = GL_TRUE;
      removeArgs(argcp, &argv[1], 1);
    } else if (!strcmp(__glutArgv[i], "-sync")) {
#if defined(_WIN32)
      __glutWarning("-sync option not supported by Win32 GLUT.");
#endif
      synchronize = GL_TRUE;
      removeArgs(argcp, &argv[1], 1);
    } else {
      /* Once unknown option encountered, stop command line
         processing. */
      break;
    }
  }
#if defined(__OS2__)
  __glutOpenOS2Connection(display);
#elif defined(_WIN32)
  __glutOpenWin32Connection(display);
#else
  __glutOpenXConnection(display);
#endif
  if (geometry) {
    int flags, x, y, width, height;

    /* Fix bogus "{width|height} may be used before set"
       warning */
    width = 0;
    height = 0;

    flags = XParseGeometry(geometry, &x, &y,
      (unsigned int *) &width, (unsigned int *) &height);
    if (WidthValue & flags) {
      /* Careful because X does not allow zero or negative
         width windows */
      if (width > 0)
        __glutInitWidth = width;
    }
    if (HeightValue & flags) {
      /* Careful because X does not allow zero or negative
         height windows */
      if (height > 0)
        __glutInitHeight = height;
    }
    glutInitWindowSize(__glutInitWidth, __glutInitHeight);
    if (XValue & flags) {
      if (XNegative & flags)
        x = DisplayWidth(__glutDisplay, __glutScreen) +
          x - __glutSizeHints.width;
      /* Play safe: reject negative X locations */
      if (x >= 0)
        __glutInitX = x;
    }
    if (YValue & flags) {
      if (YNegative & flags)
        y = DisplayHeight(__glutDisplay, __glutScreen) +
          y - __glutSizeHints.height;
      /* Play safe: reject negative Y locations */
      if (y >= 0)
        __glutInitY = y;
    }
    glutInitWindowPosition(__glutInitX, __glutInitY);
  }
  __glutInitTime(&unused);

  /* check if GLUT_FPS env var is set */
  {
     const char *fps = getenv("GLUT_FPS");
     if (fps) {
        sscanf(fps, "%d", &__glutFPS);
        if (__glutFPS <= 0)
           __glutFPS = 5000;  /* 5000 milliseconds */
     }
  }
}
Exemple #13
0
/**
 * Perform the required libGL-side initialization and call the client-side
 * driver's \c __driCreateNewScreen function.
 * 
 * \param dpy    Display pointer.
 * \param scrn   Screen number on the display.
 * \param psc    DRI screen information.
 * \param driDpy DRI display information.
 * \param createNewScreen  Pointer to the client-side driver's
 *               \c __driCreateNewScreen function.
 * \returns A pointer to the \c __DRIscreen structure returned by
 *          the client-side driver on success, or \c NULL on failure.
 */
static void *
CallCreateNewScreen(Display *dpy, int scrn, struct dri_screen *psc,
                    struct dri_display * driDpy)
{
   void *psp = NULL;
   drm_handle_t hSAREA;
   drmAddress pSAREA = MAP_FAILED;
   char *BusID;
   __DRIversion ddx_version;
   __DRIversion dri_version;
   __DRIversion drm_version;
   __DRIframebuffer framebuffer;
   int fd = -1;
   int status;

   drm_magic_t magic;
   drmVersionPtr version;
   int newlyopened;
   char *driverName;
   drm_handle_t hFB;
   int junk;
   const __DRIconfig **driver_configs;
   struct glx_config *visual, *configs = NULL, *visuals = NULL;

   /* DRI protocol version. */
   dri_version.major = driDpy->driMajor;
   dri_version.minor = driDpy->driMinor;
   dri_version.patch = driDpy->driPatch;

   framebuffer.base = MAP_FAILED;
   framebuffer.dev_priv = NULL;
   framebuffer.size = 0;

   if (!XF86DRIOpenConnection(dpy, scrn, &hSAREA, &BusID)) {
      ErrorMessageF("XF86DRIOpenConnection failed\n");
      goto handle_error;
   }

   fd = drmOpenOnce(NULL, BusID, &newlyopened);

   free(BusID);                /* No longer needed */

   if (fd < 0) {
      ErrorMessageF("drmOpenOnce failed (%s)\n", strerror(-fd));
      goto handle_error;
   }

   if (drmGetMagic(fd, &magic)) {
      ErrorMessageF("drmGetMagic failed\n");
      goto handle_error;
   }

   version = drmGetVersion(fd);
   if (version) {
      drm_version.major = version->version_major;
      drm_version.minor = version->version_minor;
      drm_version.patch = version->version_patchlevel;
      drmFreeVersion(version);
   }
   else {
      drm_version.major = -1;
      drm_version.minor = -1;
      drm_version.patch = -1;
   }

   if (newlyopened && !XF86DRIAuthConnection(dpy, scrn, magic)) {
      ErrorMessageF("XF86DRIAuthConnection failed\n");
      goto handle_error;
   }

   /* Get device name (like "radeon") and the ddx version numbers.
    * We'll check the version in each DRI driver's "createNewScreen"
    * function. */
   if (!XF86DRIGetClientDriverName(dpy, scrn,
                                   &ddx_version.major,
                                   &ddx_version.minor,
                                   &ddx_version.patch, &driverName)) {
      ErrorMessageF("XF86DRIGetClientDriverName failed\n");
      goto handle_error;
   }

   free(driverName);           /* No longer needed. */

   /*
    * Get device-specific info.  pDevPriv will point to a struct
    * (such as DRIRADEONRec in xfree86/driver/ati/radeon_dri.h) that
    * has information about the screen size, depth, pitch, ancilliary
    * buffers, DRM mmap handles, etc.
    */
   if (!XF86DRIGetDeviceInfo(dpy, scrn, &hFB, &junk,
                             &framebuffer.size, &framebuffer.stride,
                             &framebuffer.dev_priv_size,
                             &framebuffer.dev_priv)) {
      ErrorMessageF("XF86DRIGetDeviceInfo failed");
      goto handle_error;
   }

   framebuffer.width = DisplayWidth(dpy, scrn);
   framebuffer.height = DisplayHeight(dpy, scrn);

   /* Map the framebuffer region. */
   status = drmMap(fd, hFB, framebuffer.size,
                   (drmAddressPtr) & framebuffer.base);
   if (status != 0) {
      ErrorMessageF("drmMap of framebuffer failed (%s)", strerror(-status));
      goto handle_error;
   }

   /* Map the SAREA region.  Further mmap regions may be setup in
    * each DRI driver's "createNewScreen" function.
    */
   status = drmMap(fd, hSAREA, SAREA_MAX, &pSAREA);
   if (status != 0) {
      ErrorMessageF("drmMap of SAREA failed (%s)", strerror(-status));
      goto handle_error;
   }

   psp = (*psc->legacy->createNewScreen) (scrn,
                                          &ddx_version,
                                          &dri_version,
                                          &drm_version,
                                          &framebuffer,
                                          pSAREA,
                                          fd,
                                          loader_extensions,
                                          &driver_configs, psc);

   if (psp == NULL) {
      ErrorMessageF("Calling driver entry point failed");
      goto handle_error;
   }

   configs = driConvertConfigs(psc->core, psc->base.configs, driver_configs);
   visuals = driConvertConfigs(psc->core, psc->base.visuals, driver_configs);

   if (!configs || !visuals)
       goto handle_error;

   glx_config_destroy_list(psc->base.configs);
   psc->base.configs = configs;
   glx_config_destroy_list(psc->base.visuals);
   psc->base.visuals = visuals;

   psc->driver_configs = driver_configs;

   /* Visuals with depth != screen depth are subject to automatic compositing
    * in the X server, so DRI1 can't render to them properly. Mark them as
    * non-conformant to prevent apps from picking them up accidentally.
    */
   for (visual = psc->base.visuals; visual; visual = visual->next) {
      XVisualInfo template;
Exemple #14
0
/*
 * Name      : void vOpenWindow()
 *
 * Parameters: None.
 *
 * Returns   : void
 *
 * Purpose   : Creates the main viewing window.
 */
void vOpenWindow()
{

    unsigned int display_width, display_height;
    unsigned int window_width, window_height, border_width = 2;
    unsigned int keys_buttons;
    int screen;
    int window_x = 0, window_y = 0;
    int x0, y0, x1, y1, rx, ry;
    XSizeHints size_hints;
    char *display_name = NULL;
    XSetWindowAttributes attribs;
    int visualAttribList[10];
    XVisualInfo *visual;


    /* make a connection to the Xwindows display server */
    if( (display=XOpenDisplay(display_name))==NULL ) {
        (void)fprintf( stderr, "Main: cannot connect to X server %s\n",
                       XDisplayName(display_name) );
        exit( -1 );
    }

    /* query some values that we will need later */
    screen         = DefaultScreen( display );
    display_width  = DisplayWidth( display, screen );
    window_width   = display_width / 2;
    display_height = DisplayHeight( display, screen );
    window_height  = display_height / 2;

    /* Check to see if the Xserver supports OpenGL */
    if( !glXQueryExtension(display, (int *) 0, (int *) 0) ) {
        fprintf( stderr, "Main: this X server does not support OpenGL\n" );
        exit( -2 );
    }

    /* find an OpenGL visual that is RGB, single buffered and has at least
       4 bits per colour component of r,g and b (ie. at least 12 bit per
       pixel visual) */
    visual = findVisual( display, 4 );

    /* tell x what events I want the window to accept */
    attribs.event_mask = KeyPressMask | ExposureMask | StructureNotifyMask;

    /* I do not know why but you MUST specify a border pixel value for
       XCreateWindow to work. If you do not do this, you WILL get a run
       time error. */
    attribs.border_pixel = BlackPixel(display,screen);

    attribs.colormap = allocateColourmap( display, visual );

    /* this is the more complicated way of opening an X window but we must
       use it because we want to specifiy the visual that the window is to
       use. This is necessary for OpenGL */
    win = XCreateWindow( display, RootWindow( display, screen ),
                         window_x, window_y,
                         window_width, window_height,
                         border_width,
                         visual->depth,
                         InputOutput,
                         visual->visual,
                         CWColormap | CWEventMask | CWBorderPixel,
                         &attribs );

    XStoreName( display, win, "Interaction Demo - Press 'Q' To Quit" );
    XClearWindow( display, win );
    XFlush( display );

    /* This is the call you need to make to tell X which events to pass on
       to the program for tis window. The events are specified in by the
       event masks being or'ed together as the last parameter. To get more
       or less events in this window, add or remove some of the masks. */
    XSelectInput(display,
                 win,
                 ExposureMask | KeyPressMask | ButtonPressMask |
                 ButtonReleaseMask | StructureNotifyMask | ButtonMotionMask);

    if (get_GC( win, visual, &gc ) != 0) {
        XDestroyWindow( display, win );
        XCloseDisplay( display );
        exit( -3 );
    }

    /* we are now done with the visual so we should free the storage */
    XFree( visual );


    XMapWindow( display, win );
}
Exemple #15
0
/**
 * Initialize the x11 grab device demuxer (public device demuxer API).
 *
 * @param s1 Context from avformat core
 * @param ap Parameters from avformat core
 * @return <ul>
 *          <li>AVERROR(ENOMEM) no memory left</li>
 *          <li>AVERROR(EIO) other failure case</li>
 *          <li>0 success</li>
 *         </ul>
 */
static int
x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
{
    struct x11_grab *x11grab = s1->priv_data;
    Display *dpy;
    AVStream *st = NULL;
    enum PixelFormat input_pixfmt;
    XImage *image;
    int x_off = 0;
    int y_off = 0;
    int screen;
    int use_shm;
    char *dpyname, *offset;
    int ret = 0;
    AVRational framerate;

    dpyname = av_strdup(s1->filename);
    offset = strchr(dpyname, '+');
    if (offset) {
        sscanf(offset, "%d,%d", &x_off, &y_off);
        x11grab->draw_mouse = !strstr(offset, "nomouse");
        *offset= 0;
    }

    if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {
        av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
        goto out;
    }
    if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {
        av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);
        goto out;
    }
    av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
           s1->filename, dpyname, x_off, y_off, x11grab->width, x11grab->height);

    dpy = XOpenDisplay(dpyname);
    av_freep(&dpyname);
    if(!dpy) {
        av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
        ret = AVERROR(EIO);
        goto out;
    }

    st = av_new_stream(s1, 0);
    if (!st) {
        ret = AVERROR(ENOMEM);
        goto out;
    }
    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    screen = DefaultScreen(dpy);

    if (x11grab->follow_mouse) {
        int screen_w, screen_h;
        Window w;

        screen_w = DisplayWidth(dpy, screen);
        screen_h = DisplayHeight(dpy, screen);
        XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off, &ret, &ret, &ret);
        x_off -= x11grab->width / 2;
        y_off -= x11grab->height / 2;
        x_off = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
        y_off = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
        av_log(s1, AV_LOG_INFO, "followmouse is enabled, resetting grabbing region to x: %d y: %d\n", x_off, y_off);
    }

    use_shm = XShmQueryExtension(dpy);
    av_log(s1, AV_LOG_INFO, "shared memory extension%s found\n", use_shm ? "" : " not");

    if(use_shm) {
        int scr = XDefaultScreen(dpy);
        image = XShmCreateImage(dpy,
                                DefaultVisual(dpy, scr),
                                DefaultDepth(dpy, scr),
                                ZPixmap,
                                NULL,
                                &x11grab->shminfo,
                                x11grab->width, x11grab->height);
        x11grab->shminfo.shmid = shmget(IPC_PRIVATE,
                                        image->bytes_per_line * image->height,
                                        IPC_CREAT|0777);
        if (x11grab->shminfo.shmid == -1) {
            av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");
            ret = AVERROR(ENOMEM);
            goto out;
        }
        x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);
        x11grab->shminfo.readOnly = False;

        if (!XShmAttach(dpy, &x11grab->shminfo)) {
            av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");
            /* needs some better error subroutine :) */
            ret = AVERROR(EIO);
            goto out;
        }
    } else {
        image = XGetImage(dpy, RootWindow(dpy, screen),
                          x_off,y_off,
                          x11grab->width, x11grab->height,
                          AllPlanes, ZPixmap);
    }

    switch (image->bits_per_pixel) {
    case 8:
        av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");
        input_pixfmt = PIX_FMT_PAL8;
        break;
    case 16:
        if (       image->red_mask   == 0xf800 &&
                   image->green_mask == 0x07e0 &&
                   image->blue_mask  == 0x001f ) {
            av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");
            input_pixfmt = PIX_FMT_RGB565;
        } else if (image->red_mask   == 0x7c00 &&
                   image->green_mask == 0x03e0 &&
                   image->blue_mask  == 0x001f ) {
            av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");
            input_pixfmt = PIX_FMT_RGB555;
        } else {
            av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
            ret = AVERROR(EIO);
            goto out;
        }
        break;
    case 24:
        if (        image->red_mask   == 0xff0000 &&
                    image->green_mask == 0x00ff00 &&
                    image->blue_mask  == 0x0000ff ) {
            input_pixfmt = PIX_FMT_BGR24;
        } else if ( image->red_mask   == 0x0000ff &&
                    image->green_mask == 0x00ff00 &&
                    image->blue_mask  == 0xff0000 ) {
            input_pixfmt = PIX_FMT_RGB24;
        } else {
            av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);
            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);
            ret = AVERROR(EIO);
            goto out;
        }
        break;
    case 32:
        input_pixfmt = PIX_FMT_RGB32;
        break;
    default:
        av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);
        ret = AVERROR(EINVAL);
        goto out;
    }

    x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;
    x11grab->dpy = dpy;
    x11grab->time_base  = (AVRational){framerate.den, framerate.num};
    x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
    x11grab->x_off = x_off;
    x11grab->y_off = y_off;
    x11grab->image = image;
    x11grab->use_shm = use_shm;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codec->codec_id = CODEC_ID_RAWVIDEO;
    st->codec->width  = x11grab->width;
    st->codec->height = x11grab->height;
    st->codec->pix_fmt = input_pixfmt;
    st->codec->time_base = x11grab->time_base;
    st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;

out:
    return ret;
}
void
parse_xargs (int argc, char **argv, char **geometry)
{
    int option;
    extern char *optarg;

#ifdef ALLOW_PIX_DOUBLING
    char* option_string = "vbrndg:wR:G:B:";
#else
    char* option_string = "vbrng:wR:G:B:";
#endif
    while ((option = getopt (argc, argv, option_string)) != EOF) {
	switch (option)
	{
	case 'v':
	    verbose = TRUE;
	    break;
	case 'g':
	    *geometry = optarg;
	    break;
#ifdef ALLOW_PIX_DOUBLING
	case 'd':
	    pix_double = 1;
	    /* Fall through.  We are not allowed a border with pix doubling */
#endif
	case 'b':
	    borderx = 0;
	    bordery = 0;
	    break;
	case 'r':
	    borderx = BORDERX;
	    bordery = BORDERY;
	    break;
	case 'n':
	    no_init_help = TRUE;
	    break;
	case 'w':
	    gamma_correct_red = GAMMA_CORRECT_RED;
	    gamma_correct_green = GAMMA_CORRECT_GREEN;
	    gamma_correct_blue = GAMMA_CORRECT_BLUE;
	    break;
	case 'R':
	    sscanf (optarg, "%f", &gamma_correct_red);
	    break;
	case 'G':
	    sscanf (optarg, "%f", &gamma_correct_green);
	    break;
	case 'B':
	    sscanf (optarg, "%f", &gamma_correct_blue);
	    break;


	}
    }
    if (verbose)
	printf (_("Version %s\n"), VERSION);
    if (!(display.dpy = XOpenDisplay (display.dname)))
    {
	printf (" Can't open the dispay!\n");
	HandleError ("Cannot open display.\n", FATAL);
	exit (-1);
    }
    /* Record the screen number and root window. */
    display.screen = DefaultScreen (display.dpy);
    display.root = RootWindow (display.dpy, display.screen);

    display.winW = WINWIDTH + borderx * 2 + pix_double * WINWIDTH;
    display.winH = WINHEIGHT + bordery * 2 + pix_double * WINHEIGHT;
    winX = (DisplayWidth (display.dpy, display.screen) - display.winW) / 2;
    winY = (DisplayHeight (display.dpy, display.screen) - display.winH) / 2;
    if (*geometry != NULL)
	XParseGeometry (*geometry, &winX, &winY, &display.winW, &display.winH);
}
Exemple #17
0
/**
 * Grab a frame from x11 (public device demuxer API).
 *
 * @param s1 Context from avformat core
 * @param pkt Packet holding the brabbed frame
 * @return frame size in bytes
 */
static int
x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
{
    struct x11_grab *s = s1->priv_data;
    Display *dpy = s->dpy;
    XImage *image = s->image;
    int x_off = s->x_off;
    int y_off = s->y_off;

    int screen;
    Window root;
    int follow_mouse = s->follow_mouse;

    int64_t curtime, delay;
    struct timespec ts;

    /* Calculate the time of the next frame */
    s->time_frame += INT64_C(1000000);

    /* wait based on the frame rate */
    for(;;) {
        curtime = av_gettime();
        delay = s->time_frame * av_q2d(s->time_base) - curtime;
        if (delay <= 0) {
            if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {
                s->time_frame += INT64_C(1000000);
            }
            break;
        }
        ts.tv_sec = delay / 1000000;
        ts.tv_nsec = (delay % 1000000) * 1000;
        nanosleep(&ts, NULL);
    }

    av_init_packet(pkt);
    pkt->data = image->data;
    pkt->size = s->frame_size;
    pkt->pts = curtime;

    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    if (follow_mouse) {
        int screen_w, screen_h;
        int pointer_x, pointer_y, _;
        Window w;

        screen_w = DisplayWidth(dpy, screen);
        screen_h = DisplayHeight(dpy, screen);
        XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);
        if (follow_mouse == -1) {
            // follow the mouse, put it at center of grabbing region
            x_off += pointer_x - s->width  / 2 - x_off;
            y_off += pointer_y - s->height / 2 - y_off;
        } else {
            // follow the mouse, but only move the grabbing region when mouse
            // reaches within certain pixels to the edge.
            if (pointer_x > x_off + s->width - follow_mouse) {
                x_off += pointer_x - (x_off + s->width - follow_mouse);
            } else if (pointer_x < x_off + follow_mouse)
                x_off -= (x_off + follow_mouse) - pointer_x;
            if (pointer_y > y_off + s->height - follow_mouse) {
                y_off += pointer_y - (y_off + s->height - follow_mouse);
            } else if (pointer_y < y_off + follow_mouse)
                y_off -= (y_off + follow_mouse) - pointer_y;
        }
        // adjust grabbing region position if it goes out of screen.
        s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
        s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);

        if (s->show_region && s->region_win)
            XMoveWindow(dpy, s->region_win,
                        s->x_off - REGION_WIN_BORDER,
                        s->y_off - REGION_WIN_BORDER);
    }

    if (s->show_region) {
        if (s->region_win) {
            XEvent evt;
            // clean up the events, and do the initinal draw or redraw.
            for (evt.type = NoEventMask; XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask, &evt); );
            if (evt.type)
                x11grab_draw_region_win(s);
        } else {
            x11grab_region_win_init(s);
        }
    }

    if(s->use_shm) {
        if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes)) {
            av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");
        }
    } else {
        if (!xget_zpixmap(dpy, root, image, x_off, y_off)) {
            av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");
        }
    }

    if (s->draw_mouse) {
        paint_mouse_pointer(image, s);
    }

    return s->frame_size;
}
Exemple #18
0
bool x11_init(XRESOURCES* res, CFG* config){
	Window root;
	XSetWindowAttributes window_attributes;
	unsigned width, height;
	Atom wm_state_fullscreen;
	int xdbe_major, xdbe_minor;
	XTextProperty window_name;
	pid_t pid = getpid();

	//allocate some structures
	XSizeHints* size_hints = XAllocSizeHints();
	XWMHints* wm_hints = XAllocWMHints();
	XClassHint* class_hints = XAllocClassHint();

	if(!size_hints || !wm_hints || !class_hints){
		fprintf(stderr, "Failed to allocate X data structures\n");
		return false;
	}

	//x data initialization
	res->display = XOpenDisplay(NULL);

	if(!(res->display)){
		fprintf(stderr, "Failed to open display\n");
		XFree(size_hints);
		XFree(wm_hints);
		XFree(class_hints);
		return false;
	}

	if(config->double_buffer){
		config->double_buffer = (XdbeQueryExtension(res->display, &xdbe_major, &xdbe_minor) != 0);
	}
	else{
		config->double_buffer = false;
	}
	errlog(config, LOG_INFO, "Double buffering %s\n", config->double_buffer ? "enabled":"disabled");

	res->screen = DefaultScreen(res->display);
	root = RootWindow(res->display, res->screen);

	//start xft
	if(!XftInit(NULL)){
		fprintf(stderr, "Failed to initialize Xft\n");
		XFree(size_hints);
		XFree(wm_hints);
		XFree(class_hints);
		return false;
	}

	//set up colors
	res->text_color = colorspec_parse(config->text_color, res->display, res->screen);
	res->bg_color = colorspec_parse(config->bg_color, res->display, res->screen);
	res->debug_color = colorspec_parse(config->debug_color, res->display, res->screen);

	//set up window params
	window_attributes.background_pixel = res->bg_color.pixel;
	window_attributes.cursor = None;
	window_attributes.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask;
	width = DisplayWidth(res->display, res->screen);
	height = DisplayHeight(res->display, res->screen);

	//create window
	res->main = XCreateWindow(res->display,
				root,
				0,
				0,
				width,
				height,
				0,
				CopyFromParent,
				InputOutput,
				CopyFromParent,
				CWBackPixel | CWCursor | CWEventMask,
				&window_attributes);

	//set window properties
	if(XStringListToTextProperty(&(config->window_name), 1, &window_name) == 0){
		fprintf(stderr, "Failed to create string list, aborting\n");
		return false;
	}

	wm_hints->flags = 0;
	class_hints->res_name = "xecho";
	class_hints->res_class = "xecho";

	XSetWMProperties(res->display, res->main, &window_name, NULL, NULL, 0, NULL, wm_hints, class_hints);

	XFree(window_name.value);
	XFree(size_hints);
	XFree(wm_hints);
	XFree(class_hints);

	//set fullscreen mode
	if(!config->windowed){
		wm_state_fullscreen = XInternAtom(res->display, "_NET_WM_STATE_FULLSCREEN", False);
		XChangeProperty(res->display, res->main, XInternAtom(res->display, "_NET_WM_STATE", False), XA_ATOM, 32, PropModeReplace, (unsigned char*) &wm_state_fullscreen, 1);
	}

	XChangeProperty(res->display, res->main, XInternAtom(res->display, "_NET_WM_PID", False), XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&pid, 1);

	//allocate back drawing buffer
	if(config->double_buffer){
		res->back_buffer = XdbeAllocateBackBufferName(res->display, res->main, XdbeBackground);
	}

	//make xft drawable from window
	res->drawable = XftDrawCreate(res->display, (config->double_buffer?res->back_buffer:res->main), DefaultVisual(res->display, res->screen), DefaultColormap(res->display, res->screen));

	if(!res->drawable){
		fprintf(stderr, "Failed to allocate drawable\n");
		return false;
	}

	//register for WM_DELETE_WINDOW messages
	res->wm_delete = XInternAtom(res->display, "WM_DELETE_WINDOW", False);
	XSetWMProtocols(res->display, res->main, &(res->wm_delete), 1);

	//map window
	XMapRaised(res->display, res->main);

	//get x socket fds
	if(!xfd_add(&(res->xfds), XConnectionNumber(res->display))){
		fprintf(stderr, "Failed to allocate xfd memory\n");
		return false;
	}
	if(XAddConnectionWatch(res->display, xconn_watch, (void*)(&(res->xfds))) == 0){
		fprintf(stderr, "Failed to register connection watch procedure\n");
		return false;
	}

	return true;
}
Exemple #19
0
OpenGLDisplay::OpenGLDisplay( char *display_name,
			      double movie_sar,
			      uint s_framewidth, uint s_frameheight,
			      uint s_dispwidth, uint s_dispheight )
  : opq( opqueue_len )
{
  state.framewidth = s_framewidth;
  state.frameheight = s_frameheight;
  state.dispwidth = s_dispwidth;
  state.dispheight = s_dispheight;
  
  if ( 0 == XInitThreads() ) {
    fprintf( stderr, "XInitThreads() failed." );
    throw DisplayError();
  }

  state.display = XOpenDisplay( display_name );
  if ( state.display == NULL ) {
    fprintf( stderr, "Couldn't open display.\n" );
    throw DisplayError();
  }

  /* Figure out the dimensions given the width and height,
     the video sample aspect ratio, and the screen pixel aspect ratio */
  double display_sar = ((double)DisplayHeight( state.display, DefaultScreen( state.display ) )
			/ (double)DisplayHeightMM( state.display, DefaultScreen( state.display ) ))
    / ((double)DisplayWidth( state.display, DefaultScreen( state.display ) )
       / (double)DisplayWidthMM( state.display, DefaultScreen( state.display ) ));

  state.sar = movie_sar / display_sar;

  // sar = 1; /* XXX */

  if ( state.sar > 1 ) {
    state.width = lrint( (double)state.dispwidth * state.sar );
    state.height = state.dispheight;
  } else {
    state.width = state.dispwidth;
    state.height = lrint( (double)state.dispheight / state.sar );
  }

  fprintf( stderr, "Display is %dx%d with pixel AR %.3f:1, display AR %.3f:1.\n",
	   DisplayWidth( state.display, DefaultScreen( state.display ) ),
	   DisplayHeight( state.display, DefaultScreen( state.display ) ),
	   display_sar,
	   (double)DisplayWidthMM( state.display, DefaultScreen( state.display ) )
	   / (double)DisplayHeightMM( state.display, DefaultScreen( state.display ) ) );

  fprintf( stderr, "MPEG-2 sequence is %dx%d with sample AR %.3f:1, display AR %.3f:1.\n",
	   state.dispwidth, state.dispheight,
	   movie_sar,
	   movie_sar * state.dispwidth / (double)state.dispheight );

  fprintf( stderr, "Video SAR in display pixel units = %.3f:1. Display size = %dx%d.\n",
	   state.sar, state.width, state.height );

  state.GetSync = (Bool (*)(Display*, GLXDrawable, int64_t*, int64_t*, int64_t*))glXGetProcAddress( (GLubyte *) "glXGetSyncValuesOML" );

  ahabassert( state.GetSync );

  state.last_mbc = -1;
  state.last_us = -1;

  unixassert( pthread_create( &thread_handle, NULL,
			      thread_helper, this ) );

  int prio = sched_get_priority_max( SCHED_FIFO );
  ahabassert( prio != -1 );

  struct sched_param params;
  params.sched_priority = prio;

  unixassert( pthread_setschedparam( thread_handle,
				     SCHED_FIFO, &params ) );
}
Exemple #20
0
int main (int argc, char** argv) {

	/* Connect to the X server */
	Display *display = XOpenDisplay(NULL);
	int screen_num;

	XGCValues values;
	Colormap colormap;

	/* Check if the XInput Extension is available */
	int opcode, event, error;
	if (!XQueryExtension(display, "XInputExtension", &opcode, &event, &error)) {
		printf("X Input extension not available.\n");
		return -1;
	}

	/* Check for XI2 support */
	int major = 2, minor = 0;
	if (XIQueryVersion(display, &major, &minor) == BadRequest) {
		printf("XI2 not available. Server supports %d.%d\n", major, minor);
		return -1;
	}

	/* Get screen size from display structure macro */
	screen_num = DefaultScreen(display);
	int display_width = DisplayWidth(display, screen_num);
	int display_height = DisplayHeight(display, screen_num);
	printf("screen_num: %d\n", screen_num);
	printf("display_width: %d\n", display_width);
	printf("display_height: %d\n", display_height);

	/* set window dimensions */
	int width = display_width/4*3;
	int height = display_height/4*3;
	int border_width = 3;
	printf("width: %d\n", width);
	printf("height: %d\n", height);

	/* create opaque window */
	Window win = XCreateSimpleWindow(display, DefaultRootWindow(display), 
			0, 0, width, height, border_width, WhitePixel(display,
			screen_num), BlackPixel(display,screen_num));

	printf("win: %d\n", (int)win);

	/* Display window */
	XMapWindow(display, win);
	XSync( display, False );

	/* Set default values for pens (GCs) to draw lines with */
	values.foreground = WhitePixel(display, screen_num);
	values.line_width = 10;
	values.line_style = LineSolid;
	values.cap_style = CapRound;

	/* Create colormap */
	colormap = DefaultColormap(display, screen_num);


	/* Set up MPX events */
	XIEventMask eventmask;
	unsigned char mask[1] = { 0 };

	eventmask.deviceid = XIAllMasterDevices;
	eventmask.mask_len = sizeof(mask);
	eventmask.mask = mask;

	/* Events we want to listen for */
	XISetMask(mask, XI_Motion);
	XISetMask(mask, XI_ButtonPress);
	XISetMask(mask, XI_ButtonRelease);
	XISetMask(mask, XI_KeyPress);
	XISetMask(mask, XI_KeyRelease);

	/* Register events on the window */
	XISelectEvents(display, win, &eventmask, 1);


	/* Maximum pointer count */
	const unsigned int numPointers = 0xFF;
	Pointer pointers[numPointers];

	/* Initialize pointers */
	int i;
	for(i=0; i<numPointers; i++) {
		pointers[i].down = 0;
		pointers[i].p.x = -1;
		pointers[i].p.y = -1;
		pointers[i].lastp.x = -1;
		pointers[i].lastp.y = -1;
	}

	/* Event loop */
	while(1) {

		XEvent ev;
		/* Get next event; blocks until an event occurs */
		XNextEvent(display, &ev);
		if (ev.xcookie.type == GenericEvent &&
		    ev.xcookie.extension == opcode &&
		    XGetEventData(display, &ev.xcookie))
		{
			XIDeviceEvent* evData = (XIDeviceEvent*)(ev.xcookie.data);
			int deviceID = evData->deviceid;
			Pointer *pointer = &pointers[deviceID];

			switch(ev.xcookie.evtype)
			{
			case XI_Motion:
				printf("motion\n");
				if(pointer->down) {
					/* Draw a line from the last point to the next one;
					   multiple lines of these create a stroke */
					XDrawLine(display, win, pointer->gc, pointer->lastp.x,
					          pointer->lastp.y, evData->event_x, evData->event_y);

					// Comment out the following for interesting structures
					pointer->lastp.x = evData->event_x;
					pointer->lastp.y = evData->event_y;
				}
				break;

			case XI_ButtonPress:
				printf("click - ");
				printf("button: %d - ", evData->detail);
				printf("abs X:%f Y:%f - ", evData->root_x, evData->root_y);
				printf("win X:%f Y:%f\n", evData->event_x, evData->event_y);

				/* Create random color for each stroke */
				values.foreground = rand() % 0xFFFFFF;
				pointer->gc = XCreateGC(display, win,
				                        GCForeground|GCLineWidth|GCLineStyle|GCCapStyle,
				                        &values);

				XDrawLine(display, win, pointer->gc, evData->event_x,
					      evData->event_y, evData->event_x, evData->event_y);

				pointer->down = 1;
				pointer->p.x = evData->event_x;
				pointer->p.y = evData->event_y;
				pointer->lastp.x = evData->event_x;
				pointer->lastp.y = evData->event_y;

				break;

			case XI_ButtonRelease:
				printf("unclick\n");
				pointer->down = 0;
				break;

			case XI_KeyPress:
				printf("key down\n");
				break;

			case XI_KeyRelease:
				printf("key up\n");
				break;
			}
		}
		XFreeEventData(display, &ev.xcookie);
	}

	XDestroyWindow(display, win);
	return 0;

}
Exemple #21
0
Boolean
CreateHelp()
{
  struct stat fileinfo;		/* file information from fstat. */
  FILE * help_file;		/* The stream of the help file. */
  char * help_page;		/* The help text strored in memory. */
  int help_width;		/* The width of the help window. (default). */
  Arg arglist[10];		/* The arglist */
  Cardinal num_args;		/* The number of arguments. */
  Widget pane;			/* The Vpane, that will contain the help info.
				   */
  static XtCallbackRec Callbacks[] = {
    { PopdownHelp, NULL },
    { NULL, NULL },
  };
  
  if (help_widget != NULL)	/* If we already have a help widget. 
				   then do not create one. */
    return(TRUE);

/* Open help_file and read it into memory. */

/*
 * Get file size and allocate a chunk of memory for the file to be 
 * copied into.
 */

  if( (help_file = fopen(help_file_name, "r")) == NULL ) {
    PrintWarning("Could not open help file, NO HELP WILL BE AVALIABLE.");
    return(FALSE);
  }

  if ( stat(help_file_name, &fileinfo) ) {
    PrintWarning("Failure in fstat, NO HELP WILL BE AVALIABLE.");
    return(FALSE);
  }

  /* leave space for the NULL */
  help_page = (char *) malloc(fileinfo.st_size + 1);	

  if (help_page == NULL) {
    PrintWarning(
      "Could not allocate memory for help file, NO HELP WILL BE AVALIABLE.");
    return(FALSE);
  }

/*
 * Copy the file into memory. 
 */
 
  fread(help_page,sizeof(char),fileinfo.st_size,help_file); 
  fclose(help_file);
    
/* put NULL at end of buffer. */

  *(help_page + fileinfo.st_size) = '\0';

/*
 * Help file now loaded in to memory. Create widgets do display it. 
 */

  num_args = 0;
  XtSetArg(arglist[num_args], XtNallowShellResize, TRUE);
  num_args++;

  help_widget = XtCreateApplicationShell("help", applicationShellWidgetClass, 
				   arglist, num_args);

  num_args = 0;
  help_width = DisplayWidth(XtDisplay(help_widget), 
			    DefaultScreen(XtDisplay(help_widget)));
  help_width /= 2;
  XtSetArg(arglist[num_args], XtNwidth, help_width);
  num_args++;

#if XtSpecificationRelease < 4
  pane = XtCreateWidget("Help_VPaned",vPanedWidgetClass,help_widget,
			arglist,num_args);
#else
  pane = XtCreateWidget("Help_Paned",panedWidgetClass,help_widget,
			arglist,num_args);
#endif

  num_args = 0;
  XtSetArg(arglist[num_args], XtNborderWidth, 0);
  num_args++;
  XtSetArg(arglist[num_args], XtNlabel, "Done With Help");
  num_args++;
  XtSetArg(arglist[num_args], XtNcallback, Callbacks);
  num_args++;

  (void) XtCreateManagedWidget("Help_Quit",commandWidgetClass, pane,
			       arglist, num_args);

  num_args = 0;
  XtSetArg(arglist[num_args], XtNborderWidth, 0);
  num_args++;
  XtSetArg(arglist[num_args], XtNstring, help_page);
  num_args++;
#if XtSpecificationRelease < 4
  XtSetArg(arglist[num_args], XtNtextOptions, scrollVertical);
  num_args++;
#else
  XtSetArg(arglist[num_args],XtNscrollVertical,XawtextScrollAlways);
  num_args++;
  XtSetArg(arglist[num_args],XtNscrollHorizontal,XawtextScrollWhenNeeded);
  num_args++;
  XtSetArg(arglist[num_args],XtNuseStringInPlace, TRUE);
  num_args++;
#endif
  /* make the text shown a square box. */
  XtSetArg(arglist[num_args], XtNheight, help_width);
  num_args++;
  

#if XtSpecificationRelease < 4
  (void) XtCreateManagedWidget("Help_Text",asciiStringWidgetClass, pane,
			       arglist, num_args);
#else
  (void) XtCreateManagedWidget("Help_Text",asciiTextWidgetClass, pane,
			       arglist, num_args);
#endif

  XtManageChild(pane);
  XtRealizeWidget(help_widget);
  AddCursor(help_widget,help_cursor);

  return(TRUE);
}
void
dev_open(
	char  *id
)
{
	extern char	*getenv();
	static RGBPRIMS	myprims = STDPRIMS;
	static int	atlBest[] = {GLX_RGBA, GLX_RED_SIZE,8,
				GLX_GREEN_SIZE,8, GLX_BLUE_SIZE,8,
				GLX_DEPTH_SIZE,15, None};
	char	*ev;
	double	gamval = GAMMA;
	RGBPRIMP	dpri = stdprims;
	XSetWindowAttributes	ourwinattr;
	XWMHints	ourxwmhints;
	XSizeHints	oursizhints;
					/* set quadtree globals */
	qtMinNodesiz = 3;
	qtDepthEps = 0.07;
					/* open display server */
	ourdisplay = XOpenDisplay(NULL);
	if (ourdisplay == NULL)
		error(USER, "cannot open X-windows; DISPLAY variable set?\n");
					/* find a usable visual */
	ourvinf = glXChooseVisual(ourdisplay, ourscreen, atlBest);
	if (ourvinf == NULL)
		error(USER, "no suitable visuals available");
					/* get a context */
	gctx = glXCreateContext(ourdisplay, ourvinf, NULL, GL_TRUE);
					/* set gamma and tone mapping */
	if ((ev = XGetDefault(ourdisplay, "radiance", "gamma")) != NULL
			|| (ev = getenv("DISPLAY_GAMMA")) != NULL)
		gamval = atof(ev);
	if ((ev = getenv("DISPLAY_PRIMARIES")) != NULL &&
			sscanf(ev, "%f %f %f %f %f %f %f %f",
				&myprims[RED][CIEX],&myprims[RED][CIEY],
				&myprims[GRN][CIEX],&myprims[GRN][CIEY],
				&myprims[BLU][CIEX],&myprims[BLU][CIEY],
				&myprims[WHT][CIEX],&myprims[WHT][CIEY]) >= 6)
		dpri = myprims;
	tmGlobal = tmInit(mytmflags(), dpri, gamval);
	if (tmGlobal == NULL)
		error(SYSTEM, "not enough memory in dev_open");
					/* open window */
	ourwinattr.background_pixel = ourblack;
	ourwinattr.border_pixel = ourblack;
	ourwinattr.event_mask = ourmask;
					/* this is stupid */
	ourwinattr.colormap = XCreateColormap(ourdisplay, ourroot,
				ourvinf->visual, AllocNone);
	gwind = XCreateWindow(ourdisplay, ourroot, 0, 0,
		DisplayWidth(ourdisplay,ourscreen)-2*BORWIDTH,
		DisplayHeight(ourdisplay,ourscreen)-2*BORWIDTH,
		BORWIDTH, ourvinf->depth, InputOutput, ourvinf->visual,
		CWBackPixel|CWBorderPixel|CWColormap|CWEventMask, &ourwinattr);
	if (gwind == 0)
		error(SYSTEM, "cannot create window\n");
   	XStoreName(ourdisplay, gwind, id);
					/* set window manager hints */
	ourxwmhints.flags = InputHint|IconPixmapHint;
	ourxwmhints.input = True;
	ourxwmhints.icon_pixmap = XCreateBitmapFromData(ourdisplay,
			gwind, x11icon_bits, x11icon_width, x11icon_height);
	XSetWMHints(ourdisplay, gwind, &ourxwmhints);
	oursizhints.min_width = MINWIDTH;
	oursizhints.min_height = MINHEIGHT;
	oursizhints.flags = PMinSize;
	XSetNormalHints(ourdisplay, gwind, &oursizhints);
					/* set GLX context */
	glXMakeCurrent(ourdisplay, gwind, gctx);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glShadeModel(GL_FLAT);
	glDisable(GL_DITHER);
	glDisable(GL_CULL_FACE);
	glMatrixMode(GL_PROJECTION);
	glOrtho(0., 1., 0., 1., -.01, 1.01);
	glTranslated(0., 0., -1.01);
					/* figure out sensible view */
	pwidth = (double)DisplayWidthMM(ourdisplay, ourscreen) /
			DisplayWidth(ourdisplay, ourscreen);
	pheight = (double)DisplayHeightMM(ourdisplay, ourscreen) /
			DisplayHeight(ourdisplay, ourscreen);
	odev.v = stdview;
	odev.v.type = VT_PER;
					/* map the window */
	XMapWindow(ourdisplay, gwind);
	dev_input();			/* sets size and view angles */
					/* allocate our leaf pile */
	if (!qtAllocLeaves(DisplayWidth(ourdisplay,ourscreen) *
			DisplayHeight(ourdisplay,ourscreen) * 3 /
			(qtMinNodesiz*qtMinNodesiz*2)))
		error(SYSTEM, "insufficient memory for value storage");
	odev.name = id;
	odev.ifd = ConnectionNumber(ourdisplay);
					/* initialize cone array */
	initcones();
}
Exemple #23
0
	int main(int argc, char **argv)
	{
		int i;
		Display *display;
		int screen_num;
		Window win;			//窗口ID
		unsigned int width, height;	//窗口尺寸
		unsigned int border_width = 4;	//边界空白
		unsigned int display_width, display_height;//屏幕尺寸
		int count;
		XEvent report;			//X 事件
		GC gc;				//GC
		unsigned long valuemask = 0;
		XGCValues values;
		char *display_name = NULL;
		Colormap default_cmap;		//缺省颜色表
		Cursor cursor;			//光标
		Pixmap bitmap;			//光标的pixmap
		unsigned int bitmap_width, bitmap_height;
		int hotspot_x, hotspot_y;	//光标的热点位置
		int rc;				//返回值
		XColor cursor_fg, cursor_bg;	//光标的颜色

		// 和X 服务器连接
		if ( (display=XOpenDisplay(display_name)) == NULL )
		{
			printf("Cannot connect to X server %s\n", 
					XDisplayName(display_name));
			exit(-1);
		}

		//获得缺省的 screen_num
		screen_num = DefaultScreen(display);

		//获得屏幕的宽度和高度
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);
		default_cmap = DefaultColormap(display, screen_num);

		//指定所建立窗口的宽度和高度
		//width = display_width/2;
		//height = display_height/2;
		width = 600;
		height = 400;

		//建立窗口
		win = XCreateSimpleWindow(display, 	//display
			RootWindow(display,screen_num), //父窗口
			0, 0, width, height, 		//位置和大小
			border_width, 			//边界宽度
			BlackPixel(display,screen_num), //前景色
			WhitePixel(display,screen_num));//背景色
	
		//选择窗口感兴趣的事件掩码
		XSelectInput(display, win, 
			ExposureMask | KeyPressMask | 
			ButtonPressMask | StructureNotifyMask);

		//建立GC
		gc = XCreateGC(display, win, valuemask, &values);

		//读入位图
		rc = XReadBitmapFile(display, win,
                             "icon.xbm",		//位图文件名
                             &bitmap_width, &bitmap_height,//返回位图尺寸
                             &bitmap,			//位图图像
                             &hotspot_x, &hotspot_y);	//热点
		switch (rc) {
        		case BitmapOpenFailed:
				printf("Cannot open file icon.xbm\n");
				exit(1);
			case BitmapFileInvalid:
				printf("bitmap file is not valid.\n");
				exit(1);
			case BitmapNoMemory:
				printf("No enough memory.\n");
			exit(1);
		}

		//分配颜色
		rc = XAllocNamedColor(display, default_cmap, 
			"red", &cursor_fg, &cursor_fg);
		if (rc == 0) { 
			printf("Canot allocate color.\n");
			exit(1);
		}
		rc = XAllocNamedColor(display, default_cmap,
                            "white", &cursor_bg, &cursor_bg);
		if (rc == 0) {
			printf("Canot allocate color\n");
			exit(1);
		}

		//建立光标
		cursor = XCreatePixmapCursor(display, 
			bitmap, 	//光标形状
			bitmap,		//掩码形状
			&cursor_fg, 	//前景色
			&cursor_bg,	//背景色
			5, 4);		//热点位置, 靠近左上方



                //让 window 使用光标
                XDefineCursor(display, win, cursor);

		XSync(display, False);

		//显示窗口
		XMapWindow(display, win);

		//进入事件循环
		while (1)  {

			//取得队列中的事件
			XNextEvent(display, &report);
			switch  (report.type) {

			//曝光事件, 窗口应重绘
			case Expose:
				//取得最后一个曝光事件
				if (report.xexpose.count != 0) break;
				draw(display, win, gc);
				break;

			//窗口尺寸改变, 重新取得窗口的宽度和高度
			case ConfigureNotify:
				width = report.xconfigure.width;
				height = report.xconfigure.height;
				break;

			//鼠标点击或有按键, 释放资源则退出
			case ButtonPress:
			case KeyPress:
				XFreeGC(display, gc);
				XCloseDisplay(display);
				exit(1);
			default:
				
				break;
			}
		}
	}
Exemple #24
0
/* This function gets the X Display and global info about it. Everything is
   stored in our object and will be cleaned when the object is disposed. Note
   here that caps for supported format are generated without any window or
   image creation */
GstXContext *
ximageutil_xcontext_get (GstElement * parent, const gchar * display_name)
{
  GstXContext *xcontext = NULL;
  XPixmapFormatValues *px_formats = NULL;
  gint nb_formats = 0, i;

  xcontext = g_new0 (GstXContext, 1);

  xcontext->disp = XOpenDisplay (display_name);
  GST_DEBUG_OBJECT (parent, "opened display %p", xcontext->disp);
  if (!xcontext->disp) {
    g_free (xcontext);
    return NULL;
  }
  xcontext->screen = DefaultScreenOfDisplay (xcontext->disp);
  xcontext->screen_num = DefaultScreen (xcontext->disp);
  xcontext->visual = DefaultVisual (xcontext->disp, xcontext->screen_num);
  xcontext->root = DefaultRootWindow (xcontext->disp);
  xcontext->white = XWhitePixel (xcontext->disp, xcontext->screen_num);
  xcontext->black = XBlackPixel (xcontext->disp, xcontext->screen_num);
  xcontext->depth = DefaultDepthOfScreen (xcontext->screen);

  xcontext->width = DisplayWidth (xcontext->disp, xcontext->screen_num);
  xcontext->height = DisplayHeight (xcontext->disp, xcontext->screen_num);

  xcontext->widthmm = DisplayWidthMM (xcontext->disp, xcontext->screen_num);
  xcontext->heightmm = DisplayHeightMM (xcontext->disp, xcontext->screen_num);

  xcontext->caps = NULL;

  GST_DEBUG_OBJECT (parent, "X reports %dx%d pixels and %d mm x %d mm",
      xcontext->width, xcontext->height, xcontext->widthmm, xcontext->heightmm);
  ximageutil_calculate_pixel_aspect_ratio (xcontext);

  /* We get supported pixmap formats at supported depth */
  px_formats = XListPixmapFormats (xcontext->disp, &nb_formats);

  if (!px_formats) {
    XCloseDisplay (xcontext->disp);
    g_free (xcontext);
    return NULL;
  }

  /* We get bpp value corresponding to our running depth */
  for (i = 0; i < nb_formats; i++) {
    if (px_formats[i].depth == xcontext->depth)
      xcontext->bpp = px_formats[i].bits_per_pixel;
  }

  XFree (px_formats);

  xcontext->endianness =
      (ImageByteOrder (xcontext->disp) ==
      LSBFirst) ? G_LITTLE_ENDIAN : G_BIG_ENDIAN;

#ifdef HAVE_XSHM
  /* Search for XShm extension support */
  if (XShmQueryExtension (xcontext->disp) &&
      ximageutil_check_xshm_calls (xcontext)) {
    xcontext->use_xshm = TRUE;
    GST_DEBUG ("ximageutil is using XShm extension");
  } else {
    xcontext->use_xshm = FALSE;
    GST_DEBUG ("ximageutil is not using XShm extension");
  }
#endif /* HAVE_XSHM */

  /* our caps system handles 24/32bpp RGB as big-endian. */
  if ((xcontext->bpp == 24 || xcontext->bpp == 32) &&
      xcontext->endianness == G_LITTLE_ENDIAN) {
    xcontext->endianness = G_BIG_ENDIAN;
    xcontext->r_mask_output = GUINT32_TO_BE (xcontext->visual->red_mask);
    xcontext->g_mask_output = GUINT32_TO_BE (xcontext->visual->green_mask);
    xcontext->b_mask_output = GUINT32_TO_BE (xcontext->visual->blue_mask);
    if (xcontext->bpp == 24) {
      xcontext->r_mask_output >>= 8;
      xcontext->g_mask_output >>= 8;
      xcontext->b_mask_output >>= 8;
    }
// Initialize GLUT & OpenSG and start the cluster server
int main(int argc,char **argv)
{
    const char     *name           = "ClusterServer";
    const char     *connectionType = "StreamSock";
    bool            fullscreen     = true;
    std::string     address        = "";
    bool            doStereo       = false;
    std::string     serviceGroup   = "224.245.211.234";


    // evaluate params
    for(int a=1 ; a<argc ; ++a)
    {
        if(argv[a][0] == '-')
        {
            switch(argv[a][1])
            {
                case 'm': 
                    connectionType="Multicast";
                          break;

                case 's':
                    doStereo=true;
                    break;

                case 'w': 
                    fullscreen=false;
                    break;

                case 'e':
                    exitOnError=true;
                    break;

                case 'a': address = argv[a][2] ? argv[a]+2 : argv[++a];
                          if(address == argv[argc])
                          { 
                              SLOG << "address missing" << OSG::endLog;
                              return 0;
                          }
                          std::cout << address << OSG::endLog;
                          break;


                case 'j':
                    if(argv[a][2] != '\0')
                        serviceGroup=argv[a]+2;
                    else
                        serviceGroup=argv[++a];
                    break;
              
                case 'h':
                default:  
                    std::cout << argv[0] 
                              << "-m "
                              << "-s "
                              << "-w "
                              << "-e "
                              << "-a Address "
                              << "-j group "
                              << std::endl;
                    std::cout << "-m         use multicast" << std::endl;
                    std::cout << "-s         enable stereo" << std::endl;
                    std::cout << "-w         no fullscreen" << std::endl;
                    std::cout << "-e         exit after closed connection" 
                              << std::endl;
                    std::cout << "-a Address Server network address"
                              << std::endl;
                    std::cout << "-m Address wait for requests on "
                              << "multicast group" << std::endl;
                    std::cout << "-p port    wait for requests on port"
                              << std::endl;
                    return 0;
            }
        }
        else
        {
            name=argv[a];
        }
    }
    try
    {
        // init OpenSG
        OSG::osgInit(argc, argv);

        int snglBuf[] = {GLX_RGBA, 
                         GLX_DEPTH_SIZE, 16, 
                         None};
        
        int dblBuf[16];

        dblBuf[0] = GLX_RGBA;
        dblBuf[1] = GLX_DEPTH_SIZE;
        dblBuf[2] = 16;
        dblBuf[3] = GLX_DOUBLEBUFFER;
        dblBuf[4] = (doStereo == true) ? GLX_STEREO : None;
        dblBuf[5] = None;

        // X init
        OSG::DisplayP dpy = XOpenDisplay(NULL);

        if(dpy == NULL) 
        {
            std::cerr << "Error: Could not open display!" << std::endl;
        }

        int dummy;

        if(!glXQueryExtension( dpy, &dummy, &dummy))
        {
            std::cerr << "Error: X server has no OpenGL GLX extension"
                      << std::endl;
        }
        
        XVisualInfo *vi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf);

        if(vi == NULL) 
        {
            vi = glXChooseVisual(dpy, DefaultScreen(dpy), snglBuf);

            if(vi == NULL)
            {
                std::cerr << "no RGB visual with depth buffer" << std::endl;
            }
        }

        if(vi->c_class != TrueColor)
        {
            std::cerr << "TrueColor visual required for this program"
                      << std::endl;
        }
        
        Colormap cmap = XCreateColormap(dpy, 
                                        RootWindow(dpy, vi->screen), 
                                        vi->visual, 
                                        AllocNone);
        XSetWindowAttributes swa;

        swa.colormap = cmap;
        swa.border_pixel = 0;
        swa.event_mask = 
            ExposureMask      | 
            ButtonPressMask   | 
            ButtonReleaseMask |
            KeyPressMask      |
            Button1MotionMask |
            Button2MotionMask |
            Button3MotionMask | 
            StructureNotifyMask;
        
        // Create Window
        
        // Create a Window and connect it to the main display dpy
        OSG::X11Window hwin = XCreateWindow(dpy, 
                                            RootWindow(dpy, vi->screen), 
                                            0, 0, 300, 300, 
                                            0, 
                                            vi->depth,
                                            InputOutput, 
                                            vi->visual, 
                                            CWBorderPixel | 
                                            CWColormap    | 
                                            CWEventMask, 
                                            &swa );
        
        XSetStandardProperties(dpy, hwin, "testWindowX", "testWindowX", 
                               None, argv, argc, NULL);
        
        if(fullscreen == true)
        {
            Atom noDecorAtom = XInternAtom(dpy, 
                                           "_MOTIF_WM_HINTS",
                                           0);
            
            if(noDecorAtom == None) 
            {
                fprintf(stderr,
                        "Could not intern X atom for _MOTIF_WM_HINTS.\n");
            }
            
            struct NoDecorHints 
            {
                long flags;
                long functions;
                long decorations;
                long input_mode;
            };
            
            NoDecorHints oHints;
            
            oHints.flags = 2;
            oHints.decorations = 0;
            
            XChangeProperty(dpy, 
                            hwin,
                            noDecorAtom, 
                            noDecorAtom, 
                            32,
                            PropModeReplace, 
                            reinterpret_cast<unsigned char *>(&oHints), 4);

        }
        

        // create the render action
        ract = OSG::RenderAction::create();

        // setup the OpenSG Glut window
        window     = OSG::XWindow::create();
        window->setDisplay ( dpy );
        window->setWindow ( hwin );
        window->init();

        XEvent        event;

        XMapWindow(dpy, hwin);
        XIfEvent(dpy, &event, wait_for_map_notify, reinterpret_cast<char *>(hwin));

        if(fullscreen == true)
        {
            XMoveWindow  (dpy, hwin, 0, 0);
            XResizeWindow(dpy, hwin,
                          DisplayWidth (dpy, vi->screen),
                          DisplayHeight(dpy, vi->screen));

            static char data[1] = {0};

            Cursor cursor;
            Pixmap blank;
            XColor dummyCol;
            
            blank = XCreateBitmapFromData(dpy, 
                                          hwin,
                                          data, 1, 1);

            cursor = XCreatePixmapCursor(dpy, 
                                         blank, 
                                         blank,
                                         &dummyCol, &dummyCol, 0, 0);

            XFreePixmap(dpy, blank);

            XDefineCursor(dpy,
                          hwin, 
                          cursor);
            XFlush(dpy);
        }

        window->activate();
       
        glEnable( GL_LIGHTING );
        glEnable( GL_LIGHT0 );
        glEnable( GL_NORMALIZE );

        // create the cluster server
        server     = new OSG::ClusterServer(window,name,connectionType,address);
        // start the server
        server->start();

        bool   stopIt = false;
        int ip;

        while(!stopIt) 
        {
            while((ip = XPending(dpy)) != 0)
            {
                XNextEvent(dpy, &event);

                switch (event.type) 
                {
                    case ConfigureNotify:
                    {
                        reshape(event.xconfigure.width,
                                event.xconfigure.height);
                    }
                    break;

                    case Expose:
                        display();
                        break;

                } 
                
            }

            display();
        }   
    }
    catch(OSG_STDEXCEPTION_NAMESPACE::exception &e)
    {
        SLOG << e.what() << OSG::endLog;
        delete server;

        ract   = NULL;
        window = NULL;
        
        OSG::osgExit(); 
    }
    return 0;
}
int CompressAndWrite(const char* filename, int frame_rate,
		int video_time_length, const char* SeverIpAddress)
{
	Window desktop;
	Display* display;
	XImage* base_img;
	XImage* new_img;
	unsigned int Frame_number = 0;
	unsigned int block_x;
	unsigned int block_y;
	unsigned int block_width;
	unsigned int block_height;
	unsigned long uncompress_block_size = 0;
	unsigned long blen;
	unsigned char* buf = NULL;
	int block_num = 0;
	char* block_data = NULL;
	display = XOpenDisplay(NULL); //connect to a local display
	if (NULL == display)
	{
		printf("CaptureDesktop cannot get root window");
		return 0;
	}
	desktop = RootWindow(display, 0); //refer to root window
	if (desktop == 0)
	{
		printf("CaptureDesktop cannot get root window");
		return 0;
	}
	//get the image of the root window
	//FILE *fp = fopen(filename, "wb");
	gzFile gfp = gzopen(filename, "wb9"); //用于测试文件格式
	if (gfp == 0)
	{
		printf("could not open  file!!");
		return 0;
	}
	unsigned int screen_width = DisplayWidth(display, 0);
	unsigned int screen_height = DisplayHeight(display, 0);
	base_img = XGetImage(display, desktop, 0, 0, screen_width, screen_height,
			~0,
			ZPixmap);
	/* new_img = XCreateImage(display, DefaultVisual(display, 0), 24, ZPixmap, 0,
	 NULL, screen_width, screen_height, 32, 0);*/
	time_t start_time, end_time;
	time(&start_time);
	struct timeval start_tv;
	gettimeofday(&start_tv, NULL);
	//printf("%s", ctime(&start_time));
	int x = 0; //测试用,可删除
	while (1)
	{ //控制帧率的块
		x += block_num; //测试用,可删除
		new_img = XGetImage(display, desktop, 0, 0, screen_width, screen_height,
				~0,
				ZPixmap);
		unsigned int* block_parameter;
		int i = 0; //处理blocks的循环变量
		if ((block_parameter = (unsigned int*) malloc(2200)) == NULL)
		{
			printf("no enough memory!\n");
			return -1;
		}
		block_num = CaptureAndCompare(display, desktop, base_img, new_img,
				block_parameter);

		if (Frame_number != 0 && block_num == 0)
		{
			size_t no_update = 0;
			//fwrite(&no_update, sizeof(size_t), 1, fp);
			gzwrite(gfp, &no_update, sizeof(size_t)); //用于测试文件格式
			continue;
		}
		if (Frame_number == 0)
		{
			block_num = 1;
			block_x = 0;
			block_y = 0;
			block_width = screen_width;
			block_height = screen_height;
		}

		for (i = 0; i < block_num; i++)
		{
			if (Frame_number != 0)
			{ //赋值给block变量
				block_x = *(block_parameter + i * 4);
				block_y = *(block_parameter + i * 4 + 1);
				block_width = *(block_parameter + i * 4 + 2);
				block_height = *(block_parameter + i * 4 + 3);
				printf("%d %d %d %d 帧号:%d 块数:%d\n", block_x, block_y,
						block_width, block_height, Frame_number, x);
			}

			uncompress_block_size = block_width * block_height * 4;
			if ((block_data = (char*) malloc(uncompress_block_size)) == NULL)
			{
				printf("no enough memory!\n");
				return -1;
			}
			if (GetDatablockFromXImage(new_img, block_data, block_x, block_y,
					block_width, block_height) != 1)
			{
				printf("the GetDatablockFromXImage function has an error!\n");
				return -1;
			}

			//压缩部分 计算缓冲区大小,并为其分配内存
			blen = compressBound(uncompress_block_size);  //压缩后的长度是不会超过blen的
			if ((buf = (unsigned char*) malloc(sizeof(unsigned char) * blen))
					== NULL)
			{
				printf("no enough memory!\n");
				return -1;
			}

			//压缩
			if (compress(buf, &blen, (unsigned char*) block_data,
					uncompress_block_size) != Z_OK)
			{
				printf("compress failed!\n");
				return -1;
			}
			/*			WriteBlockToDisk(buf, blen, fp, Frame_number, block_x, block_y,
			 block_width, block_height);*/
			if (SeverIpAddress != NULL)
			{  //直播传输

			}
			gzWriteBlockToDisk(buf, blen, gfp, Frame_number, block_x, block_y,
					block_width, block_height);  //用于测试文件格式
			if (buf != NULL || block_data != NULL)
			{
				free(buf);
				free(block_data);
				block_data = NULL;
				buf = NULL;

			}
		}

		Frame_number++;  //帧号
		free(block_parameter);
		block_parameter = NULL;
		XDestroyImage(new_img);

		while (1)
		{  //控制帧率
			struct timeval end_tv;
			gettimeofday(&end_tv, NULL);
			if (((end_tv.tv_sec - start_tv.tv_sec)
					+ 0.000001 * (end_tv.tv_usec - start_tv.tv_usec))
					>= Frame_number * 1.0 / frame_rate)
			{
				break;
			}
		}
		time(&end_time);
		if (difftime(end_time, start_time) >= video_time_length)
		{
			break;
		}
		//控制帧率的块end
	}

	/* 释放内存 */
	//fflush(fp);
	//fclose(fp);
	//fp = NULL;
	gzclose(gfp);	//用于测试文件格式
	XDestroyImage(base_img);
	XCloseDisplay(display);

	printf("CompressAndWrite performs successfully!\n");
	return 1;

}
Exemple #27
0
/* This function calculates the pixel aspect ratio */
static GValue *
gst_vdp_sink_calculate_par (Display * display)
{
  static const gint par[][2] = {
    {1, 1},                     /* regular screen */
    {16, 15},                   /* PAL TV */
    {11, 10},                   /* 525 line Rec.601 video */
    {54, 59},                   /* 625 line Rec.601 video */
    {64, 45},                   /* 1280x1024 on 16:9 display */
    {5, 3},                     /* 1280x1024 on 4:3 display */
    {4, 3}                      /*  800x600 on 16:9 display */
  };
  gint screen_num;
  gint width, height;
  gint widthmm, heightmm;
  gint i;
  gint index;
  gdouble ratio;
  gdouble delta;
  GValue *par_value;

#define DELTA(idx) (ABS (ratio - ((gdouble) par[idx][0] / par[idx][1])))

  screen_num = DefaultScreen (display);
  width = DisplayWidth (display, screen_num);
  height = DisplayHeight (display, screen_num);
  widthmm = DisplayWidthMM (display, screen_num);
  heightmm = DisplayHeightMM (display, screen_num);

  /* first calculate the "real" ratio based on the X values;
   * which is the "physical" w/h divided by the w/h in pixels of the display */
  ratio = (gdouble) (widthmm * height)
      / (heightmm * width);

  /* DirectFB's X in 720x576 reports the physical dimensions wrong, so
   * override here */
  if (width == 720 && height == 576) {
    ratio = 4.0 * 576 / (3.0 * 720);
  }
  GST_DEBUG ("calculated pixel aspect ratio: %f", ratio);

  /* now find the one from par[][2] with the lowest delta to the real one */
  delta = DELTA (0);
  index = 0;

  for (i = 1; i < sizeof (par) / (sizeof (gint) * 2); ++i) {
    gdouble this_delta = DELTA (i);

    if (this_delta < delta) {
      index = i;
      delta = this_delta;
    }
  }

  GST_DEBUG ("Decided on index %d (%d/%d)", index,
      par[index][0], par[index][1]);

  par_value = g_new0 (GValue, 1);
  g_value_init (par_value, GST_TYPE_FRACTION);
  gst_value_set_fraction (par_value, par[index][0], par[index][1]);
  GST_DEBUG ("set X11 PAR to %d/%d",
      gst_value_get_fraction_numerator (par_value),
      gst_value_get_fraction_denominator (par_value));

  return par_value;
}
Exemple #28
0
void sdlvideo_monitor_refresh(sdl_monitor_info *monitor)
{
	#if (SDLMAME_SDL2)
	SDL_DisplayMode dmode;

	SDL_GetDesktopDisplayMode(monitor->handle, &dmode);
	monitor->monitor_width = dmode.w;
	monitor->monitor_height = dmode.h;
	monitor->center_width = dmode.w;
	monitor->center_height = dmode.h;
	#else
	#if defined(SDLMAME_WIN32)  // Win32 version
	MONITORINFOEX info;
	info.cbSize = sizeof(info);
	GetMonitorInfo((HMONITOR)monitor->handle, (LPMONITORINFO)&info);
	monitor->center_width = monitor->monitor_width = info.rcMonitor.right - info.rcMonitor.left;
	monitor->center_height = monitor->monitor_height = info.rcMonitor.bottom - info.rcMonitor.top;
	char *temp = utf8_from_wstring(info.szDevice);
	strcpy(monitor->monitor_device, temp);
	osd_free(temp);
	#elif defined(SDLMAME_MACOSX)   // Mac OS X Core Imaging version
	CGDirectDisplayID primary;
	CGRect dbounds;

	// get the main display
	primary = CGMainDisplayID();
	dbounds = CGDisplayBounds(primary);

	monitor->center_width = monitor->monitor_width = dbounds.size.width - dbounds.origin.x;
	monitor->center_height = monitor->monitor_height = dbounds.size.height - dbounds.origin.y;
	strcpy(monitor->monitor_device, "Mac OS X display");
	#elif defined(SDLMAME_X11) || defined(SDLMAME_NO_X11)       // X11 version
	{
		#if defined(SDLMAME_X11)
		// X11 version
		int screen;
		SDL_SysWMinfo info;
		SDL_VERSION(&info.version);

		if ( SDL_GetWMInfo(&info) && (info.subsystem == SDL_SYSWM_X11) )
		{
			screen = DefaultScreen(info.info.x11.display);
			SDL_VideoDriverName(monitor->monitor_device, sizeof(monitor->monitor_device)-1);
			monitor->monitor_width = DisplayWidth(info.info.x11.display, screen);
			monitor->monitor_height = DisplayHeight(info.info.x11.display, screen);

			if ((XineramaIsActive(info.info.x11.display)) && video_config.restrictonemonitor)
			{
				XineramaScreenInfo *xineinfo;
				int numscreens;

					xineinfo = XineramaQueryScreens(info.info.x11.display, &numscreens);

				monitor->center_width = xineinfo[0].width;
				monitor->center_height = xineinfo[0].height;

				XFree(xineinfo);
			}
			else
			{
				monitor->center_width = monitor->monitor_width;
				monitor->center_height = monitor->monitor_height;
			}
		}
		else
		#endif // defined(SDLMAME_X11)
		{
			static int first_call=0;
			static int cw = 0, ch = 0;

			SDL_VideoDriverName(monitor->monitor_device, sizeof(monitor->monitor_device)-1);
			if (first_call==0)
			{
				char *dimstr = osd_getenv(SDLENV_DESKTOPDIM);
				const SDL_VideoInfo *sdl_vi;

				sdl_vi = SDL_GetVideoInfo();
				#if (SDL_VERSION_ATLEAST(1,2,10))
				cw = sdl_vi->current_w;
				ch = sdl_vi->current_h;
				#endif
				first_call=1;
				if ((cw==0) || (ch==0))
				{
					if (dimstr != NULL)
					{
						sscanf(dimstr, "%dx%d", &cw, &ch);
					}
					if ((cw==0) || (ch==0))
					{
						mame_printf_warning("WARNING: SDL_GetVideoInfo() for driver <%s> is broken.\n", monitor->monitor_device);
						mame_printf_warning("         You should set SDLMAME_DESKTOPDIM to your desktop size.\n");
						mame_printf_warning("            e.g. export SDLMAME_DESKTOPDIM=800x600\n");
						mame_printf_warning("         Assuming 1024x768 now!\n");
						cw=1024;
						ch=768;
					}
				}
			}
			monitor->monitor_width = cw;
			monitor->monitor_height = ch;
			monitor->center_width = cw;
			monitor->center_height = ch;
		}
	}
	#elif defined(SDLMAME_OS2)      // OS2 version
	monitor->center_width = monitor->monitor_width = WinQuerySysValue( HWND_DESKTOP, SV_CXSCREEN );
	monitor->center_height = monitor->monitor_height = WinQuerySysValue( HWND_DESKTOP, SV_CYSCREEN );
	strcpy(monitor->monitor_device, "OS/2 display");
	#else
	#error Unknown SDLMAME_xx OS type!
	#endif

	{
		static int info_shown=0;
		if (!info_shown)
		{
			mame_printf_verbose("SDL Device Driver     : %s\n", monitor->monitor_device);
			mame_printf_verbose("SDL Monitor Dimensions: %d x %d\n", monitor->monitor_width, monitor->monitor_height);
			info_shown = 1;
		}
	}
	#endif //  (SDLMAME_SDL2)
}
Exemple #29
0
int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate)
{
    int i, match, bestmatch;

    if (_glfwLibrary.X11.RandR.available)
    {
#if defined(_GLFW_HAS_XRANDR)
        int sizecount, bestsize;
        int ratecount, bestrate;
        short* ratelist;
        XRRScreenConfiguration* sc;
        XRRScreenSize* sizelist;

        sc = XRRGetScreenInfo(_glfwLibrary.X11.display,
                              RootWindow(_glfwLibrary.X11.display, screen));

        sizelist = XRRConfigSizes(sc, &sizecount);

        // Find the best matching mode
        bestsize  = -1;
        bestmatch = INT_MAX;
        for (i = 0;  i < sizecount;  i++)
        {
            match = (*width - sizelist[i].width) *
                    (*width - sizelist[i].width) +
                    (*height - sizelist[i].height) *
                    (*height - sizelist[i].height);
            if (match < bestmatch)
            {
                bestmatch = match;
                bestsize  = i;
            }
        }

        if (bestsize != -1)
        {
            // Report width & height of best matching mode
            *width = sizelist[bestsize].width;
            *height = sizelist[bestsize].height;

            if (*rate > 0)
            {
                ratelist = XRRConfigRates(sc, bestsize, &ratecount);

                bestrate = -1;
                bestmatch = INT_MAX;
                for (i = 0;  i < ratecount;  i++)
                {
                    match = abs(ratelist[i] - *rate);
                    if (match < bestmatch)
                    {
                        bestmatch = match;
                        bestrate = ratelist[i];
                    }
                }

                if (bestrate != -1)
                    *rate = bestrate;
            }
        }

        XRRFreeScreenConfigInfo(sc);

        if (bestsize != -1)
            return bestsize;
#endif /*_GLFW_HAS_XRANDR*/
    }
    else if (_glfwLibrary.X11.VidMode.available)
    {
#if defined(_GLFW_HAS_XF86VIDMODE)
        XF86VidModeModeInfo** modelist;
        int bestmode, modecount;

        // Get a list of all available display modes
        XF86VidModeGetAllModeLines(_glfwLibrary.X11.display, screen,
                                   &modecount, &modelist);

        // Find the best matching mode
        bestmode  = -1;
        bestmatch = INT_MAX;
        for (i = 0;  i < modecount;  i++)
        {
            match = (*width - modelist[i]->hdisplay) *
                    (*width - modelist[i]->hdisplay) +
                    (*height - modelist[i]->vdisplay) *
                    (*height - modelist[i]->vdisplay);
            if (match < bestmatch)
            {
                bestmatch = match;
                bestmode  = i;
            }
        }

        if (bestmode != -1)
        {
            // Report width & height of best matching mode
            *width = modelist[bestmode]->hdisplay;
            *height = modelist[bestmode]->vdisplay;
        }

        XFree(modelist);

        if (bestmode != -1)
            return bestmode;
#endif /*_GLFW_HAS_XF86VIDMODE*/
    }

    // Default: Simply use the screen resolution
    *width = DisplayWidth(_glfwLibrary.X11.display, screen);
    *height = DisplayHeight(_glfwLibrary.X11.display, screen);

    return 0;
}
Exemple #30
0
#undef __FUNCT__
#define __FUNCT__ "PetscDrawXGetDisplaySize_Private"
PetscErrorCode PetscDrawXGetDisplaySize_Private(const char name[],int *width,int *height)
{
  Display *display;

  PetscFunctionBegin;
  display = XOpenDisplay(name);
  if (!display) {
    *width  = 0;
    *height = 0;
    SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Unable to open display on %s\n.  Make sure your COMPUTE NODES are authorized to connect \n\
    to this X server and either your DISPLAY variable\n\
    is set or you use the -display name option\n",name);
  }
  *width  = DisplayWidth(display,0);
  *height = DisplayHeight(display,0);
  XCloseDisplay(display);
  PetscFunctionReturn(0);
}

EXTERN_C_BEGIN
#undef __FUNCT__
#define __FUNCT__ "PetscDrawCreate_X"
PetscErrorCode  PetscDrawCreate_X(PetscDraw draw)
{
  PetscDraw_X    *Xwin;
  PetscErrorCode ierr;
  PetscMPIInt    rank;
  PetscInt       xywh[4],osize = 4;
  int            x = draw->x,y = draw->y,w = draw->w,h = draw->h;