Esempio n. 1
0
/**********************************************************************
 *	XG_INIT
 *	- initializes plotting variables, the colortable, and the GC
 **********************************************************************/
void xg_init(Display *display, Window can_xid, 
		int *can_bounds, char *fontname, void **xgid)
{
	/* local variables */
	struct xg_graphic *graphic;
	XGCValues gc_val;
	int	i;

	/* allocate memory for xg_graphic structure */
	if ((graphic = (struct xg_graphic *) 
		calloc(1,sizeof(struct xg_graphic))) == NULL)
		exit(1);

	/* copy input variables to global variables */
	graphic->dpy = display;
	graphic->xid = can_xid;
	for (i=0;i<4;i++)
		graphic->bounds[i] = can_bounds[i];

	/* check for the type of display and set the display_type */
	graphic->display_depth = DisplayPlanes(graphic->dpy, 
			DefaultScreen(graphic->dpy));
/*fprintf(stderr,"graphic->display_depth:%d Default Visual:%d\n", 
graphic->display_depth,
DefaultVisual(graphic->dpy, DefaultScreen(graphic->dpy)));*/
	if (graphic->display_depth == 1 )
		{
		if (XMatchVisualInfo(graphic->dpy,DefaultScreen(graphic->dpy),
			1,StaticGray,&(graphic->visinfo)) == 0)
			{
			fprintf(stderr,"Error: Could not Match an 1 bit GrayScale plane\n");
			exit(-1);
			}
		graphic->display_type = StaticGray;
		graphic->visual = graphic->visinfo.visual;  
		}
	else if (graphic->display_depth == 8)
		{
		if (XMatchVisualInfo(graphic->dpy, DefaultScreen(graphic->dpy),
			8,PseudoColor,&(graphic->visinfo)) == 0)
			{
			fprintf(stderr,"Error: Could not Match an 8 bit Pseudo-Color plane\n");
			exit(-1);
			}
		graphic->display_type = PseudoColor;
		graphic->visual = graphic->visinfo.visual;  
		}
	else if (graphic->display_depth == 16)
		{
		if (XMatchVisualInfo(graphic->dpy, DefaultScreen(graphic->dpy),
			16,TrueColor,&(graphic->visinfo)) != 0)
			{
			graphic->display_type = TrueColor;
			graphic->visual = graphic->visinfo.visual;  
			}
		else if (XMatchVisualInfo(graphic->dpy, DefaultScreen(graphic->dpy),
			16,PseudoColor,&(graphic->visinfo)) != 0)
			{
			graphic->display_type = PseudoColor;
			graphic->visual = graphic->visinfo.visual;  
			}
		else
			{
			fprintf(stderr,"Error: Could not Match a 16 bit TrueColor or Pseudocolor plane\n");
			exit(-1);
			}
		}
	else if (graphic->display_depth == 24)
		{
		if (XMatchVisualInfo(graphic->dpy, DefaultScreen(graphic->dpy),
			24,TrueColor,&(graphic->visinfo)) == 0)
			{
			fprintf(stderr,"Error: Could not Match a 24 bit TrueColor plane\n");
			exit(-1);
			}
		graphic->display_type = TrueColor;
		graphic->visual = graphic->visinfo.visual;  
		}
	else
		{
		graphic->visual = DefaultVisual(graphic->dpy, DefaultScreen(graphic->dpy));
		graphic->display_type = 0;
		}

	/* set foreground and background colors */
	if (graphic->display_type == StaticGray 
		|| graphic->display_type == PseudoColor
	        || graphic->display_type == TrueColor)
		{
		graphic->bg_pixel = WhitePixel(graphic->dpy, 
			DefaultScreen(graphic->dpy));
		graphic->fg_pixel = BlackPixel(graphic->dpy, 
			DefaultScreen(graphic->dpy));
		}
	else
		{
		fprintf(stderr, "Error: Could not Match a one, eight, or twentyfour bit plane\n");
		exit(-1);
		}

	/* load font */
	if ((graphic->font_info = XLoadQueryFont(graphic->dpy, fontname)) 
		== NULL)
		{
		printf("X Error: Cannot load font: %s\n",fontname);
		exit(-1);
		}

	/* set up graphics context */
	gc_val.foreground = graphic->fg_pixel;
	gc_val.background = graphic->bg_pixel;
	gc_val.font = graphic->font_info->fid;

	/* set gc with solid lines */
	gc_val.plane_mask = AllPlanes;
	gc_val.line_style = LineSolid;
	graphic->gc_solid = XCreateGC(graphic->dpy, graphic->xid, 
		(GCForeground | GCBackground | GCFont 
		| GCPlaneMask | GCLineStyle),
		&(gc_val));

	/* set gc with dash lines */
	gc_val.line_style = LineOnOffDash;
	graphic->gc_dash = XCreateGC(graphic->dpy, graphic->xid, 
		(GCForeground | GCBackground | GCFont 
		| GCPlaneMask | GCLineStyle),
		&(gc_val));
		
	/* return pointer to xg_graphic structure */
	*xgid = (void *) graphic;

}
Esempio n. 2
0
static void winopen(void)
{
	XWMHints *wmhints;
	XClassHint *classhint;

	xdpy = XOpenDisplay(NULL);
	if (!xdpy)
		fz_throw(gapp.ctx, FZ_ERROR_GENERIC, "cannot open display");

	XA_CLIPBOARD = XInternAtom(xdpy, "CLIPBOARD", False);
	XA_TARGETS = XInternAtom(xdpy, "TARGETS", False);
	XA_TIMESTAMP = XInternAtom(xdpy, "TIMESTAMP", False);
	XA_UTF8_STRING = XInternAtom(xdpy, "UTF8_STRING", False);
	WM_DELETE_WINDOW = XInternAtom(xdpy, "WM_DELETE_WINDOW", False);
	NET_WM_STATE = XInternAtom(xdpy, "_NET_WM_STATE", False);
	NET_WM_STATE_FULLSCREEN = XInternAtom(xdpy, "_NET_WM_STATE_FULLSCREEN", False);
	WM_RELOAD_PAGE = XInternAtom(xdpy, "_WM_RELOAD_PAGE", False);

	xscr = DefaultScreen(xdpy);

	ximage_init(xdpy, xscr, DefaultVisual(xdpy, xscr));

	xcarrow = XCreateFontCursor(xdpy, XC_left_ptr);
	xchand = XCreateFontCursor(xdpy, XC_hand2);
	xcwait = XCreateFontCursor(xdpy, XC_watch);
	xccaret = XCreateFontCursor(xdpy, XC_xterm);

	xbgcolor.red = 0x7000;
	xbgcolor.green = 0x7000;
	xbgcolor.blue = 0x7000;

	xshcolor.red = 0x4000;
	xshcolor.green = 0x4000;
	xshcolor.blue = 0x4000;

	XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xbgcolor);
	XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xshcolor);

	xwin = XCreateWindow(xdpy, DefaultRootWindow(xdpy),
		10, 10, 200, 100, 0,
		ximage_get_depth(),
		InputOutput,
		ximage_get_visual(),
		0,
		NULL);
	if (xwin == None)
		fz_throw(gapp.ctx, FZ_ERROR_GENERIC, "cannot create window");

	XSetWindowColormap(xdpy, xwin, ximage_get_colormap());
	XSelectInput(xdpy, xwin,
		StructureNotifyMask | ExposureMask | KeyPressMask |
		PointerMotionMask | ButtonPressMask | ButtonReleaseMask);

	mapped = 0;

	xgc = XCreateGC(xdpy, xwin, 0, NULL);

	XDefineCursor(xdpy, xwin, xcarrow);

	wmhints = XAllocWMHints();
	if (wmhints)
	{
		wmhints->flags = IconPixmapHint | IconMaskHint;
		xicon = XCreateBitmapFromData(xdpy, xwin,
			(char*)mupdf_icon_bitmap_16_bits,
			mupdf_icon_bitmap_16_width,
			mupdf_icon_bitmap_16_height);
		xmask = XCreateBitmapFromData(xdpy, xwin,
			(char*)mupdf_icon_bitmap_16_mask_bits,
			mupdf_icon_bitmap_16_mask_width,
			mupdf_icon_bitmap_16_mask_height);
		if (xicon && xmask)
		{
			wmhints->icon_pixmap = xicon;
			wmhints->icon_mask = xmask;
			XSetWMHints(xdpy, xwin, wmhints);
		}
		XFree(wmhints);
	}

	classhint = XAllocClassHint();
	if (classhint)
	{
		classhint->res_name = "mupdf";
		classhint->res_class = "MuPDF";
		XSetClassHint(xdpy, xwin, classhint);
		XFree(classhint);
	}

	XSetWMProtocols(xdpy, xwin, &WM_DELETE_WINDOW, 1);

	x11fd = ConnectionNumber(xdpy);
}
Esempio n. 3
0
void
InitWindow(int argc, char **argv)
{
	XGCValues gc_values;
	XWMHints wmhints;
	Widget	w;
	XClassHint	classHint;
	GC	iconGC;

	progName = (char *)rindex(argv[0], '/');
	if (progName)
		progName++;
	else
		progName = argv[0];

	/*
	 * We cheat here by using the Toolkit to do the initialization work.
	 * We just ignore the top-level widget that gets created.
	 */

	w = XtAppInitialize(&app_con, progName, opTable, XtNumber(opTable),
			&argc, argv, default_resources, NULL, ZERO);

	if ((argc > 1) && (strcmp("-robot", argv[1]) == 0))
	  { argc--;
	    app_resources.robotic = TRUE;
	  }
	else {app_resources.robotic = FALSE;}

	printf("set robot. ");
	dpy = XtDisplay(w);
	screen = DefaultScreen(dpy);

	printf("set Xscreen. ");

	XtGetApplicationResources(w, (caddr_t) &app_resources, resources,
				XtNumber(resources), NULL, (Cardinal) 0);

	printf("set XResource. ");

	if (!app_resources.scoreFont)
		MWError("cannot open font");
	scoreFontInfo = XQueryFont(dpy, app_resources.scoreFont);

	printf("set XQueue. ");

        cur_width = MIN_X_DIM;
        cur_height = MIN_Y_DIM + (MAX_RATS+1) *
	             (scoreFontInfo->max_bounds.ascent +
		      scoreFontInfo->max_bounds.descent);

	mwWindow = XCreateSimpleWindow(dpy,
					RootWindow(dpy, screen),
					0, 0,
					cur_width, cur_height,
					app_resources.borderWidth, 0,
				       app_resources.bg_pixel);
	XStoreName(dpy, mwWindow, "MazeWar");
	XSetIconName(dpy, mwWindow, "MazeWar");
	classHint.res_name = (char *)("cs244Bmazewar");
	classHint.res_class = (char *)("cs244Bmazewar");
	XSetClassHint(dpy, mwWindow, &classHint);

	gc_values.function = GXcopy;
	gc_values.foreground = app_resources.fg_pixel;
	gc_values.background = app_resources.bg_pixel;
	gc_values.font = app_resources.scoreFont;
	gc_values.line_width = 0;
	copyGC = XCreateGC(dpy, mwWindow,
		       GCFunction | GCForeground | GCBackground
		       | GCLineWidth | GCFont,
		       &gc_values);

	gc_values.function = GXxor;
	gc_values.plane_mask = AllPlanes;
	gc_values.foreground = app_resources.fg_pixel ^ app_resources.bg_pixel;
	gc_values.background = 0;
	xorGC = XCreateGC(dpy, mwWindow,
		       GCFunction | GCForeground | GCBackground | GCPlaneMask,
		       &gc_values);

	icon_pixmap = XCreatePixmapFromBitmapData(
			dpy, mwWindow,
			(char *)icon_bits,
			icon_width, icon_height,
			app_resources.fg_pixel, app_resources.bg_pixel,
			XDefaultDepth(dpy, screen));

	/* is this even used? */
	gc_values.function = GXclear;
	gc_values.plane_mask = AllPlanes;
	iconGC = XCreateGC(dpy, mwWindow,
			GCFunction | GCPlaneMask,
			&gc_values);
	iconmask_pixmap = XCreatePixmap(dpy, mwWindow,
					icon_width, icon_height,
					XDefaultDepth(dpy, screen));
	XFillRectangle(dpy, iconmask_pixmap, iconGC, 0, 0,
			icon_width, icon_height);

	icon_reverse_pixmap = XCreatePixmapFromBitmapData(dpy, mwWindow,
						  (char *)icon_bits,
						  icon_width, icon_height,
						  app_resources.bg_pixel,
						  app_resources.fg_pixel,
						  XDefaultDepth(dpy, screen));

	wmhints.input = TRUE;
        wmhints.flags = IconPixmapHint | IconMaskHint | InputHint;
        wmhints.icon_pixmap = icon_pixmap;
        wmhints.icon_mask = iconmask_pixmap;
        XSetWMHints(dpy, mwWindow, &wmhints);

	initCursors();
	arrowImage = XCreateImage(dpy, DefaultVisual(dpy, DefaultScreen(dpy)),
				1, XYBitmap, 0, NULL,
				16, 16, 8, 2);
	arrowImage->byte_order = MSBFirst;
	arrowImage->bitmap_bit_order = MSBFirst;
}
Esempio n. 4
0
// ---------------------------------------------------------------------------
int main (int argc, char* argv[])
{
  int i;
  struct timezone          zone;
  struct timeval           time;
  struct HEXON_TIME_STRUCT hexon;
  struct DAYSEC_STRUCT     daysec;

  Widget       shell;
  XtAppContext app;
  Widget       button[0x11];
  Pixmap       pix[0x11];
  Pixel        fg;
  Pixel        bg;

  const char* pixmap_filename[] =
  {
    "hexal-0-10x10.xpm",
    "hexal-1-10x10.xpm",
    "hexal-2-10x10.xpm",
    "hexal-3-10x10.xpm",
    "hexal-4-10x10.xpm",
    "hexal-5-10x10.xpm",
    "hexal-6-10x10.xpm",
    "hexal-7-10x10.xpm",
    "hexal-8-10x10.xpm",
    "hexal-9-10x10.xpm",
    "hexal-A-10x10.xpm",
    "hexal-B-10x10.xpm",
    "hexal-C-10x10.xpm",
    "hexal-D-10x10.xpm",
    "hexal-E-10x10.xpm",
    "hexal-F-10x10.xpm"
    "hexal-dot-10x10.xpm"
  };

#ifdef USE_PIXMAP_FROM_DATA
  const char** pixmap_data[] =
  {
    (const char**) hexal_0_10x10_xpm,
    (const char**) hexal_1_10x10_xpm,
    (const char**) hexal_2_10x10_xpm,
    (const char**) hexal_3_10x10_xpm,
    (const char**) hexal_4_10x10_xpm,
    (const char**) hexal_5_10x10_xpm,
    (const char**) hexal_6_10x10_xpm,
    (const char**) hexal_7_10x10_xpm,
    (const char**) hexal_8_10x10_xpm,
    (const char**) hexal_9_10x10_xpm,
    (const char**) hexal_A_10x10_xpm,
    (const char**) hexal_B_10x10_xpm,
    (const char**) hexal_C_10x10_xpm,
    (const char**) hexal_D_10x10_xpm,
    (const char**) hexal_E_10x10_xpm,
    (const char**) hexal_F_10x10_xpm,
    (const char**) hexal_dot_10x10_xpm
  };
#endif

  Set_Epoch  (DEFAULT_EPOCH);
  Set_Format (DEFAULT_FORMAT);

  shell = XtAppInitialize (&app, "xHexClock", NULL, 0,
                           &argc, argv, NULL, NULL, 0);

  for (i = 1; i < argc; i++)
  {
    char* argument = argv[i];
    if ((strcmp (argument, "--help") == 0) || (strcmp (argument, "-h") == 0)) Usage();
    else if (strequ (argument, "--epoch=" )) Set_Epoch  (strchr (argument, '=') + 1);
    else if (strequ (argument, "--format=")) Set_Format (strchr (argument, '=') + 1);
    else if (strequ (argument, "--verbose")) verbose = 1;
    else
    {
      fprintf (stderr, PROGRAM_NAME ": *** error: unknown option \"%s\".\n\n", argument);
      Usage();
    }
  }

  gettimeofday (&time, &zone);

  Set_Unix_Time (&daysec, &time, &zone);

  if (verbose)
  {
    printf ("Unix time    (seconds.microseconds): %lu.%06lu (hex 0x%lx/0x%05lx.\n",
            time.tv_sec, time.tv_usec, time.tv_sec, time.tv_usec);
    printf ("Unix daysec  (days.seconds): %lu.%05lu (hex 0x%lx/0x%05lx.\n",
            daysec.day, (long) daysec.sec, daysec.day, (long) daysec.sec);
    printf ("Epoch daysec (days.seconds): %lu.%05lu (hex 0x%lx/0x%05lx.\n",
            epoch.day, (long) epoch.sec, epoch.day, (long) epoch.sec);
  }

  daysec_sub (&daysec, &daysec, &epoch);

  if (verbose)
  {
    printf ("Daysec since epoch  (days.seconds): %lu.%05lu (hex 0x%lx/0x%05lx.\n",
            daysec.day, (long) daysec.sec, daysec.day, (long) daysec.sec);
  }

  Hexon_Set_Day_Second (&hexon, daysec.day, daysec.sec);

  if (verbose)
  {
    printf ("Decimal hexon = %20.6f.\n", hexon.hexon);
  }

//  if (!Hexon_Print (stdout, output_format, &hexon))
//  {
//    fprintf (stderr, PROGRAM_NAME ": *** error: could not print using format \"%s\".\n", Null_Check (output_format));
//    return 1;
//  }

  XtVaGetValues (shell,
                 XmNforeground, &fg,
                 XmNbackground, &bg,
                 NULL);

  XtRealizeWidget (shell);

  for (i = 0; i < 3 /* 0x10 */; i++)
  {
#if defined (USE_PIXMAP_FROM_DATA)
    XpmAttributes  attributes;
    int            status;
    Display*       display = XtDisplay (shell);
    Pixmap         mask;
    XpmColorSymbol symbols[2];
#endif

//    button[i] = XtCreateManagedWidget (pixmap_filename[i], xmLabelWidgetClass, shell, NULL, 0);
    button[i] = XtVaCreateManagedWidget (pixmap_filename[i], xmLabelWidgetClass, shell,
                                         XmNx, i * 32,
                                         XmNy, 0,
                                         NULL);

#if !defined (USE_PIXMAP_FROM_DATA)
    pix[i] = XmGetPixmap (XtScreen (shell), (char*) pixmap_filename[i], fg, bg);

    if (pix[i])
    {
      XtVaSetValues (button[i],
                     XmNlabelType,   XmPIXMAP,
                     XmNlabelPixmap, pix[i],
#if 0
                     XmNx,           0,
                     XmNy,           0,
                     XmNwidth,       16,
                     XmNheight,      16,
#endif
                     NULL);
    }
#else
    symbols[0].name  = "background";
    symbols[0].value = NULL;
    symbols[0].pixel = bg;
//    symbols[1].name  = "foreground";
//    symbols[1].value = NULL;
//    symbols[1].pixel = fg;

    attributes.colorsymbols = symbols;
    attributes.numsymbols = 1;

    XtVaGetValues (button[i],
                   XmNdepth,      &attributes.depth,
                   XmNcolormap,   &attributes.colormap,
                   NULL);

    attributes.visual = DefaultVisual (display, DefaultScreen (display));
    attributes.valuemask = 0; // XpmDepth | XpmColormap | XpmVisual | XpmColorSymbols;

    status = XpmCreatePixmapFromData (display,
                                      DefaultRootWindow (display),
                                      (char**) pixmap_data[i],
                                      &pix[i],
                                      &mask,
                                      &attributes);

    if (mask /* != NULL */) XFreePixmap (display, mask);

    if (status == XpmSuccess)
    {
      XtVaSetValues (button[i],
                     XmNlabelType,   XmPIXMAP,
                     XmNlabelPixmap, pix[i],
                     XmNx,           i * 16,
                     XmNy,           0,
                     XmNwidth,       16,
                     XmNheight,      16,
                     NULL);
    }
#endif
  }   // For each hexal symbol pixmap.

//  XtRealizeWidget (shell);
  XtAppMainLoop (app);

  return 0;
}   // main
Esempio n. 5
0
int main (int argc, char **argv)
{
	
	Visual *vis;
	Colormap cm;
	Display *_display;
	Imlib_Context context;
	Imlib_Image image;
	Pixmap pixmap;
	Imlib_Color_Modifier modifier = NULL;
	_display = XOpenDisplay (NULL);
	int width, height, depth, i, alpha;

	
	char str1[40];
	char str2[40];
	char str3[40];
	char str4[40];
	char str5[40];
	
	int ck0;
	int w, h; 
	w = 0;
	h = 0;
		
			
	for (screen = 0; screen < ScreenCount (_display); screen++)
	{
		display = XOpenDisplay (NULL);

		context = imlib_context_new ();
		imlib_context_push (context);

		imlib_context_set_display (display);
		vis = DefaultVisual (display, screen);
		cm = DefaultColormap (display, screen);

		width = DisplayWidth (display, screen);
		height = DisplayHeight (display, screen);

		depth = DefaultDepth (display, screen);

		pixmap =
			XCreatePixmap (display, RootWindow (display, screen),
							width, height, depth);

		imlib_context_set_visual (vis);
		imlib_context_set_colormap (cm);
		imlib_context_set_drawable (pixmap);
		imlib_context_set_color_range (imlib_create_color_range ());
		
		image = imlib_create_image (width, height);
		imlib_context_set_image (image);
				
		imlib_context_set_color (0, 0, 0, 255);
		imlib_image_fill_rectangle (0, 0, width, height);

		imlib_context_set_dither (1);
		imlib_context_set_blend (1);
		
		alpha = 255;


	for (i = 1; i < argc; i++)
	{
		if (modifier != NULL)
		{
			imlib_apply_color_modifier ();
			imlib_free_color_modifier ();
		}

	modifier = imlib_create_color_modifier ();
	imlib_context_set_color_modifier (modifier);

		if (strcmp (argv[i], "-alpha") == 0)
		{
			if ((++i) >= argc)
			{
				fprintf (stderr, "Missing alpha\n");
				continue;
			}
				if (sscanf (argv[i], "%i", &alpha) == 0)
				{
					fprintf (stderr, "Bad alpha (%s)\n", argv[i]);
					continue;
				}
		}
	else if (strcmp (argv[i], "-solid") == 0)
	{
		Color c;
		
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if (parse_color (argv[i], &c, alpha) == 1)
			{
				fprintf (stderr, "Bad color (%s)\n", argv[i]);
				continue;
			}

		imlib_context_set_color (c.r, c.g, c.b, c.a);
		imlib_image_fill_rectangle (0, 0, width, height);
	}
		else if (strcmp (argv[i], "-clear") == 0)
		{
			imlib_free_color_range ();
			imlib_context_set_color_range (imlib_create_color_range ());
		}
	else if (strcmp (argv[i], "-add") == 0)
	{
		Color c;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if (parse_color (argv[i], &c, alpha) == 1)
			{
				fprintf (stderr, "Bad color (%s)\n", argv[i - 1]);
				continue;
			}

		imlib_context_set_color (c.r, c.g, c.b, c.a);
		imlib_add_color_to_color_range (1);
	}
	else if (strcmp (argv[i], "-addd") == 0)
	{
		Color c;
		int distance;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if ((++i) >= argc)
			{
				fprintf (stderr, "Missing distance\n");
				continue;
			}
				if (parse_color (argv[i - 1], &c, alpha) == 1)
				{
					fprintf (stderr, "Bad color (%s)\n", argv[i - 1]);
					continue;
				}
					if (sscanf (argv[i], "%i", &distance) == 1)
					{
						fprintf (stderr, "Bad distance (%s)\n", argv[i]);
						continue;
					}

				imlib_context_set_color (c.r, c.g, c.b, c.a);
				imlib_add_color_to_color_range (distance);
	}
	else if (strcmp (argv[i], "-gradient") == 0)
	{
		int angle;
		 
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing angle\n");
			continue;
		}
			if (sscanf (argv[i], "%i", &angle) == 1)
			{
				fprintf (stderr, "Bad angle (%s)\n", argv[i]);
				continue;
			}
			
		imlib_image_fill_color_range_rectangle (0, 0, width, height,
												angle);
	}

	 else if (strcmp (argv[i], "-fill") == 0)
	 {
		if ((++i) >= argc)
		{
		  fprintf (stderr, "Missing image\n");
		  continue;
		}
		
		if ( load_Mod_image(Fill, argv[i], width, height, alpha, image, ck0) == 1)
		{
		  fprintf (stderr, "Bad image (%s)\n", argv[i]);
		  continue;
		}
	 }
	else if (strcmp (argv[i], "-dia") == 0)
	{ 
		if((++i) >= argc)
		{
			fprintf(stderr, "missing information to load image\n");
			continue;
		}
			strcpy (str1, argv[i]);
			strcpy (str2, str1);
		
				if ( findX(str1, &w, &h) == 1 )
			{
				fprintf(stderr, " Bad Format < %s >\n", argv[i]);
				continue;
			}
			else if (findX(str2, &w, &h) == 0 && ((++i) >= argc))
			{ 
				fprintf(stderr, "Bad Format: try -dia <size>x<size> <image> \n");
				continue;
			}
			else
			{
				//if format is correct then assign a number for
				//load_Mod_Image to check
				ck0 = -2;
				w = w; // newW
				h = w; //newH;
			}
			
			if( load_Mod_image(Dia, argv[i], w, h, alpha, image, ck0) == 1 )
			{
			fprintf(stderr, "Bad Image or Bad Image Dimensions \n");
			}
	} 
	else if (strcmp (argv[i], "-tile") == 0)
	{
		if ((++i) >= argc)

			{
			fprintf(stderr, "format 0 missing \n");
			continue;
			}
				strcpy (str1, argv[i]);
				strcpy (str2, str1);
				strcpy (str3, str2);
				strcpy (str4, str3);
				strcpy (str5, str4);

				//check for proper format -tile 0 <image>
			if ( findX(str1, &w, &h) == 3 &&  ((++i) >= argc))
			{ 
				continue;
			} //check to see if format is -tile 0 image is there then load img
			else if (findX(str2, &w, &h) == 3)
			{  
				 ck0 = 3; 
				if( load_Mod_image(Tile, argv[i], width, height, alpha, image, ck0) == 1 )
				{
					fprintf(stderr, "Bad Image |%s|\n", argv[i]);
					continue;
				}
			}
				// check for dimentions -tile <dia>x<dia> <image>
			if (findX(str3, &w, &h) == 1)
			{
				fprintf(stderr, "Bad Format\n");
				continue;
			}
			 if (findX(str4, &w, &h) == 0 && ((++i) >= argc))
			{
				fprintf(stderr, "Bad Format: try %s 0 %s \n",argv[i-2], argv[i-1]);
				continue;
			}
			if (findX (str5, &w, &h) == 0 )
			{
				ck0 = 2;
				w = w;
				h = h;
			}
			
			if( load_Mod_image(Tile, argv[i], w, h, alpha, image, ck0) == 1 )
			{
			fprintf(stderr, "Bad Image <%s> \n", argv[i]);
			}

	}

	else if (strcmp (argv[i], "-center") == 0)
	{ 
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing image\n");
			continue;
		}
			if (load_Mod_image (Center, argv[i], width, height, alpha, image, ck0) == 1)
			{ 
				fprintf (stderr, "Bad image (%s)\n", argv[i]);
				continue;
			}
	}
	else if (strcmp (argv[i], "-tint") == 0)
	{
		Color c;
		DATA8 r[256], g[256], b[256], a[256];
		int j;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing color\n");
			continue;
		}
			if (parse_color (argv[i], &c, 255) == 1)
			{
				fprintf (stderr, "Bad color\n");
				continue;
			}

		imlib_get_color_modifier_tables (r, g, b, a);

			for (j = 0; j < 256; j++)
			{
				r[j] = (DATA8) (((double) r[j] / 255.0) * (double) c.r);
				g[j] = (DATA8) (((double) g[j] / 255.0) * (double) c.g);
				b[j] = (DATA8) (((double) b[j] / 255.0) * (double) c.b);
			}

		imlib_set_color_modifier_tables (r, g, b, a);
	}
	else if (strcmp (argv[i], "-blur") == 0)
	{
		int intval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%i", &intval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_image_blur (intval);
	}
	else if (strcmp (argv[i], "-sharpen") == 0)
	{
		int intval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%i", &intval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_image_sharpen (intval);
	}
	else if (strcmp (argv[i], "-contrast") == 0)
	{
		double dblval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%lf", &dblval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_modify_color_modifier_contrast (dblval);
	}
	else if (strcmp (argv[i], "-brightness") == 0)
	{
		double dblval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%lf", &dblval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_modify_color_modifier_brightness (dblval);
	}
	else if (strcmp (argv[i], "-gamma") == 0)
	{
		double dblval;

		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing value\n");
			continue;
		}
			if (sscanf (argv[i], "%lf", &dblval) == 1)
			{
				fprintf (stderr, "Bad value (%s)\n", argv[i]);
				continue;
			}
		imlib_modify_color_modifier_gamma (dblval);
	}
	else if (strcmp (argv[i], "-flipv") == 0)
	{
		imlib_image_flip_vertical ();
	}
	else if (strcmp (argv[i], "-fliph") == 0)
	{
		imlib_image_flip_horizontal ();
	}
	else if (strcmp (argv[i], "-flipd") == 0)
	{
		imlib_image_flip_diagonal ();
	}
	else if (strcmp (argv[i], "-write") == 0)
	{
		if ((++i) >= argc)
		{
			fprintf (stderr, "Missing filename\n");
			continue;
		}
      imlib_save_image (argv[i]);
	}
	else
	{
		usage (argv[0]);
		imlib_free_image ();
		imlib_free_color_range ();

			if (modifier != NULL)
			{
				imlib_context_set_color_modifier (modifier);
				imlib_free_color_modifier ();
				modifier = NULL;
			}
				XFreePixmap (display, pixmap);
				exit (1);
	} // end else
} // end loop off of argc

	if (modifier != NULL)
	{
		imlib_context_set_color_modifier (modifier);
        imlib_apply_color_modifier ();
        imlib_free_color_modifier ();
        modifier = NULL;
	}

		imlib_render_image_on_drawable (0, 0);
		imlib_free_image ();
		imlib_free_color_range ();

		if (setRootAtoms (pixmap) == 0)
			fprintf (stderr, "Couldn't create atoms...\n");

		XKillClient (display, AllTemporary);
		XSetCloseDownMode (display, RetainTemporary);

		XSetWindowBackgroundPixmap (display, RootWindow (display, screen),
									pixmap);

		XClearWindow (display, RootWindow (display, screen));

		XFlush (display);
		XSync (display, False);

		imlib_context_pop ();
		imlib_context_free (context);

	} // end for loop off screen
                  
  return 0;
}
Esempio n. 6
0
		int32_t run(int _argc, char** _argv)
		{
			XInitThreads();
			m_display = XOpenDisplay(0);

			int32_t screen = DefaultScreen(m_display);
			int32_t depth = DefaultDepth(m_display, screen);
			Visual* visual = DefaultVisual(m_display, screen);
			Window root = RootWindow(m_display, screen);

			XSetWindowAttributes windowAttrs;
			memset(&windowAttrs, 0, sizeof(windowAttrs) );
			windowAttrs.background_pixmap = 0;
			windowAttrs.border_pixel = 0;
			windowAttrs.event_mask = 0
					| ButtonPressMask
					| ButtonReleaseMask
					| ExposureMask
					| KeyPressMask
					| KeyReleaseMask
					| PointerMotionMask
					| ResizeRedirectMask
					| StructureNotifyMask
					;

			m_window = XCreateWindow(m_display
									, root
									, 0, 0
									, ENTRY_DEFAULT_WIDTH, ENTRY_DEFAULT_HEIGHT, 0, depth
									, InputOutput
									, visual
									, CWBorderPixel|CWEventMask
									, &windowAttrs
									);

			XMapWindow(m_display, m_window);
			XStoreName(m_display, m_window, "BGFX");

			bgfx::x11SetDisplayWindow(m_display, m_window);

			MainThreadEntry mte;
			mte.m_argc = _argc;
			mte.m_argv = _argv;

			bx::Thread thread;
			thread.init(mte.threadFunc, &mte);

			while (!m_exit)
			{
				if (XPending(m_display) )
				{
					XEvent event;
					XNextEvent(m_display, &event);

					switch (event.type)
					{
						case Expose:
							break;

						case ConfigureNotify:
							break;

						case ButtonPress:
						case ButtonRelease:
							{
								const XButtonEvent& xbutton = event.xbutton;
								MouseButton::Enum mb;
								switch (xbutton.button)
								{
									case Button1: mb = MouseButton::Left;   break;
									case Button2: mb = MouseButton::Middle; break;
									case Button3: mb = MouseButton::Right;  break;
									default:      mb = MouseButton::None;   break;
								}

								if (MouseButton::None != mb)
								{
									m_eventQueue.postMouseEvent(xbutton.x
										, xbutton.y
										, mb
										, event.type == ButtonPress
										);
								}
							}
							break;

						case MotionNotify:
							{
								const XMotionEvent& xmotion = event.xmotion;
								m_eventQueue.postMouseEvent(xmotion.x
										, xmotion.y
										);
							}
							break;

						case KeyPress:
						case KeyRelease:
							{
								XKeyEvent& xkey = event.xkey;
								KeySym keysym = XLookupKeysym(&xkey, 0);
								switch (keysym)
								{
								case XK_Meta_L:    setModifier(Modifier::LeftMeta,   KeyPress == event.type); break;
								case XK_Meta_R:    setModifier(Modifier::RightMeta,  KeyPress == event.type); break;
								case XK_Control_L: setModifier(Modifier::LeftCtrl,   KeyPress == event.type); break;
								case XK_Control_R: setModifier(Modifier::RightCtrl,  KeyPress == event.type); break;
								case XK_Shift_L:   setModifier(Modifier::LeftShift,  KeyPress == event.type); break;
								case XK_Shift_R:   setModifier(Modifier::RightShift, KeyPress == event.type); break;
								case XK_Alt_L:     setModifier(Modifier::LeftAlt,    KeyPress == event.type); break;
								case XK_Alt_R:     setModifier(Modifier::RightAlt,   KeyPress == event.type); break;

								default:
									{
										Key::Enum key = fromXk(keysym);
										if (Key::None != key)
										{
											m_eventQueue.postKeyEvent(key, m_modifiers, KeyPress == event.type);
										}
									}
									break;
								}
							}
							break;

						case ResizeRequest:
							{
								const XResizeRequestEvent& xresize = event.xresizerequest;
								XResizeWindow(m_display, m_window, xresize.width, xresize.height);
							}
							break;
					}
				}
			}

			thread.shutdown();

			XUnmapWindow(m_display, m_window);
			XDestroyWindow(m_display, m_window);

			return EXIT_SUCCESS;
		}
Esempio n. 7
0
void
setup(int topbar, const char *bg, unsigned int lines) {
    int x = 0, y = 0; /* position of the window */
    /* if (!dc) { */
        dc = initdc();
    /* } */
    initfont(dc, font);
    XInitThreads();
    screen = DefaultScreen(dc->dpy);
    Window root = RootWindow(dc->dpy, screen);
    XSetWindowAttributes swa;
    XIM xim;
#ifdef XINERAMA
    int n;
    XineramaScreenInfo *info;
#endif

    clip = XInternAtom(dc->dpy, "CLIPBOARD",   False);
    utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);

    /* calculate menu geometry */
    bh = dc->font.height + 2;
    lines = MAX(lines, 0);
    mh = (lines + 1) * bh;
#ifdef XINERAMA
    if((info = XineramaQueryScreens(dc->dpy, &n))) {
        int a, j, di, i = 0, area = 0;
        unsigned int du;
        Window w, pw, dw, *dws;
        XWindowAttributes wa;

        XGetInputFocus(dc->dpy, &w, &di);
        if(w != root && w != PointerRoot && w != None) {
            /* find top-level window containing current input focus */
            do {
                if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
                    XFree(dws);
            } while(w != root && w != pw);
            /* find xinerama screen with which the window intersects most */
            if(XGetWindowAttributes(dc->dpy, pw, &wa))
                for(j = 0; j < n; j++)
                    if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
                        area = a;
                        i = j;
                    }
        }
        /* no focused window is on screen, so use pointer location instead */
        if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
            for(i = 0; i < n; i++)
                if(INTERSECT(x, y, 1, 1, info[i]))
                    break;

        x = info[i].x_org;
        y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
        mw = info[i].width;
        XFree(info);
    }
    else
#endif
    {
        x = 0;
        y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
        mw = DisplayWidth(dc->dpy, screen);
    }

    /* create menu window */
    swa.override_redirect = True;
    swa.background_pixel = getcolor(dc, bg);
    swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
    win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
            DefaultDepth(dc->dpy, screen), CopyFromParent,
            DefaultVisual(dc->dpy, screen),
            CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);

    XResizeWindow(dc->dpy, win, mw, mh);
    /* open input methods */
    xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
    xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
            XNClientWindow, win, XNFocusWindow, win, NULL);

    XMapRaised(dc->dpy, win);
    resizedc(dc, mw, mh);
    mapdc(dc, win, mw, mh);
}
Esempio n. 8
0
Visual *XDefaultVisual(Display *dpy, int scr)
{
    return (DefaultVisual(dpy, scr));
}
Esempio n. 9
0
/* Create auxiliary (toplevel) windows with the current visual */
static void create_aux_windows(_THIS)
{
    int x = 0, y = 0;
    char classname[1024];
    XSetWindowAttributes xattr;
    XWMHints *hints;
    unsigned long app_event_mask;
    int def_vis = (SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen));

    /* Look up some useful Atoms */
    WM_DELETE_WINDOW = XInternAtom(SDL_Display, "WM_DELETE_WINDOW", False);

    /* Don't create any extra windows if we are being managed */
    if ( SDL_windowid ) {
	FSwindow = 0;
	WMwindow = SDL_strtol(SDL_windowid, NULL, 0);
        return;
    }

    if(FSwindow)
	XDestroyWindow(SDL_Display, FSwindow);

#if SDL_VIDEO_DRIVER_X11_XINERAMA
    if ( use_xinerama ) {
        x = xinerama_info.x_org;
        y = xinerama_info.y_org;
    }
#endif
    xattr.override_redirect = True;
    xattr.background_pixel = def_vis ? BlackPixel(SDL_Display, SDL_Screen) : 0;
    xattr.border_pixel = 0;
    xattr.colormap = SDL_XColorMap;

    FSwindow = XCreateWindow(SDL_Display, SDL_Root,
                             x, y, 32, 32, 0,
			     this->hidden->depth, InputOutput, SDL_Visual,
			     CWOverrideRedirect | CWBackPixel | CWBorderPixel
			     | CWColormap,
			     &xattr);

    XSelectInput(SDL_Display, FSwindow, StructureNotifyMask);

    /* Tell KDE to keep the fullscreen window on top */
    {
	XEvent ev;
	long mask;

	SDL_memset(&ev, 0, sizeof(ev));
	ev.xclient.type = ClientMessage;
	ev.xclient.window = SDL_Root;
	ev.xclient.message_type = XInternAtom(SDL_Display,
					      "KWM_KEEP_ON_TOP", False);
	ev.xclient.format = 32;
	ev.xclient.data.l[0] = FSwindow;
	ev.xclient.data.l[1] = CurrentTime;
	mask = SubstructureRedirectMask;
	XSendEvent(SDL_Display, SDL_Root, False, mask, &ev);
    }

    hints = NULL;
    if(WMwindow) {
	/* All window attributes must survive the recreation */
	hints = XGetWMHints(SDL_Display, WMwindow);
	XDestroyWindow(SDL_Display, WMwindow);
    }

    /* Create the window for windowed management */
    /* (reusing the xattr structure above) */
    WMwindow = XCreateWindow(SDL_Display, SDL_Root,
                             x, y, 32, 32, 0,
			     this->hidden->depth, InputOutput, SDL_Visual,
			     CWBackPixel | CWBorderPixel | CWColormap,
			     &xattr);

    /* Set the input hints so we get keyboard input */
    if(!hints) {
	hints = XAllocWMHints();
	hints->input = True;
	hints->flags = InputHint;
    }
    XSetWMHints(SDL_Display, WMwindow, hints);
    XFree(hints);
    X11_SetCaptionNoLock(this, this->wm_title, this->wm_icon);

    app_event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
	| PropertyChangeMask | StructureNotifyMask | KeymapStateMask;
    XSelectInput(SDL_Display, WMwindow, app_event_mask);

    /* Set the class hints so we can get an icon (AfterStep) */
    get_classname(classname, sizeof(classname));
    {
	XClassHint *classhints;
	classhints = XAllocClassHint();
	if(classhints != NULL) {
	    classhints->res_name = classname;
	    classhints->res_class = classname;
	    XSetClassHint(SDL_Display, WMwindow, classhints);
	    XFree(classhints);
	}
    }

	/* Setup the communication with the IM server */
	/* create_aux_windows may be called several times against the same
	   Display.  We should reuse the SDL_IM if one has been opened for
	   the Display, so we should not simply reset SDL_IM here.  */

	#ifdef X_HAVE_UTF8_STRING
	if (SDL_X11_HAVE_UTF8) {
		/* Discard obsolete resources if any.  */
		if (SDL_IM != NULL && SDL_Display != XDisplayOfIM(SDL_IM)) {
			/* Just a double check. I don't think this
		           code is ever executed. */
			SDL_SetError("display has changed while an IM is kept");
			if (SDL_IC) {
				XUnsetICFocus(SDL_IC);
				XDestroyIC(SDL_IC);
				SDL_IC = NULL;
			}
			XCloseIM(SDL_IM);
			SDL_IM = NULL;
		}

		/* Open an input method.  */
		if (SDL_IM == NULL) {
			char *old_locale = NULL, *old_modifiers = NULL;
			const char *p;
			size_t n;
			/* I'm not comfortable to do locale setup
			   here.  However, we need C library locale
			   (and xlib modifiers) to be set based on the
			   user's preference to use XIM, and many
			   existing game programs doesn't take care of
			   users' locale preferences, so someone other
			   than the game program should do it.
			   Moreover, ones say that some game programs
			   heavily rely on the C locale behaviour,
			   e.g., strcol()'s, and we can't change the C
			   library locale.  Given the situation, I
			   couldn't find better place to do the
			   job... */

			/* Save the current (application program's)
			   locale settings.  */
			p = setlocale(LC_ALL, NULL);
			if ( p ) {
				n = SDL_strlen(p)+1;
				old_locale = SDL_stack_alloc(char, n);
				if ( old_locale ) {
					SDL_strlcpy(old_locale, p, n);
				}
			}
			p = XSetLocaleModifiers(NULL);
			if ( p ) {
				n = SDL_strlen(p)+1;
				old_modifiers = SDL_stack_alloc(char, n);
				if ( old_modifiers ) {
					SDL_strlcpy(old_modifiers, p, n);
				}
			}

			/* Fetch the user's preferences and open the
			   input method with them.  */
			setlocale(LC_ALL, "");
			XSetLocaleModifiers("");
			SDL_IM = XOpenIM(SDL_Display, NULL, classname, classname);

			/* Restore the application's locale settings
			   so that we don't break the application's
			   expected behaviour.  */
			if ( old_locale ) {
				/* We need to restore the C library
				   locale first, since the
				   interpretation of the X modifier
				   may depend on it.  */
				setlocale(LC_ALL, old_locale);
				SDL_stack_free(old_locale);
			}
			if ( old_modifiers ) {
				XSetLocaleModifiers(old_modifiers);
				SDL_stack_free(old_modifiers);
			}
		}

		/* Create a new input context for the new window just created.  */
		if (SDL_IM == NULL) {
			SDL_SetError("no input method could be opened");
		} else {
			if (SDL_IC != NULL) {
				/* Discard the old IC before creating new one.  */
			    XUnsetICFocus(SDL_IC);
			    XDestroyIC(SDL_IC);
			}
			/* Theoretically we should check the current IM supports
			   PreeditNothing+StatusNothing style (i.e., root window method)
			   before creating the IC.  However, it is the bottom line method,
			   and we supports any other options.  If the IM didn't support
			   root window method, the following call fails, and SDL falls
			   back to pre-XIM keyboard handling.  */
			SDL_IC = pXCreateIC(SDL_IM,
					XNClientWindow, WMwindow,
					XNFocusWindow, WMwindow,
					XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
					XNResourceName, classname,
					XNResourceClass, classname,
					NULL);

			if (SDL_IC == NULL) {
				SDL_SetError("no input context could be created");
				XCloseIM(SDL_IM);
				SDL_IM = NULL;
			} else {
				/* We need to receive X events that an IM wants and to pass
				   them to the IM through XFilterEvent. The set of events may
				   vary depending on the IM implementation and the options
				   specified through various routes. Although unlikely, the
				   xlib specification allows IM to change the event requirement
				   with its own circumstances, it is safe to call SelectInput
				   whenever we re-create an IC.  */
				unsigned long mask = 0;
				char *ret = pXGetICValues(SDL_IC, XNFilterEvents, &mask, NULL);
				if (ret != NULL) {
					XUnsetICFocus(SDL_IC);
					XDestroyIC(SDL_IC);
					SDL_IC = NULL;
					SDL_SetError("no input context could be created");
					XCloseIM(SDL_IM);
					SDL_IM = NULL;
				} else {
					XSelectInput(SDL_Display, WMwindow, app_event_mask | mask);
					XSetICFocus(SDL_IC);
				}
			}
		}
	}
Esempio n. 10
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 *param, *offset;
    int ret = 0;
    AVRational framerate;

    param = av_strdup(s1->filename);
    offset = strchr(param, '+');
    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, param, x_off, y_off, x11grab->width, x11grab->height);

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

    st = avformat_new_stream(s1, NULL);
    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;
}
Esempio n. 11
0
int svlWindowManagerX11::DoModal(bool show, bool fullscreen)
{
    Destroy();
    DestroyFlag = false;

    unsigned int i, atom_count;
    int x, y, prevright, prevbottom;
    unsigned int lastimage = 0;
    unsigned long black, white;
    XSizeHints wsh;

#if CISST_SVL_HAS_XV
    Atom atoms[3];
    unsigned int xvadaptorcount;
    XvAdaptorInfo *xvai;
    XVisualInfo xvvinfo;
    bool xvupdateimage = true;
#else // CISST_SVL_HAS_XV
    Atom atoms[2];
#endif // CISST_SVL_HAS_XV

    // setting decoration hints for borderless mode
    struct {
        unsigned long 	flags;
        unsigned long 	functions;
        unsigned long 	decorations;
        signed long 	input_mode;
        unsigned long 	status;
    } mwm;
    mwm.flags = MWM_HINTS_DECORATIONS;
    mwm.decorations = 0;
    mwm.functions = 0;
    mwm.input_mode = 0;
    mwm.status = 0;
    
    // resetting DestroyedSignal event
    if (DestroyedSignal) delete(DestroyedSignal);
    DestroyedSignal = new osaThreadSignal();
    if (DestroyedSignal == 0) goto labError;

    // initialize display and pick default screen
    xDisplay = XOpenDisplay(reinterpret_cast<char*>(0));
    xScreen = DefaultScreen(xDisplay);

#if CISST_SVL_HAS_XV
    // check if 24bpp is suppoted by the display
    if (XMatchVisualInfo(xDisplay, xScreen, 24, TrueColor, &xvvinfo) == 0) goto labError;
#endif // CISST_SVL_HAS_XV

    // pick colors
    black = BlackPixel(xDisplay, xScreen);
    white = WhitePixel(xDisplay, xScreen);

    // create windows
    xWindows = new Window[NumOfWins];
    memset(xWindows, 0, NumOfWins * sizeof(Window));
    xGCs = new GC[NumOfWins];
    memset(xGCs, 0, NumOfWins * sizeof(GC));

    // create atoms for overriding default window behaviours
    atoms[0] = XInternAtom(xDisplay, "WM_DELETE_WINDOW", False);
    atoms[1] = XInternAtom(xDisplay, "_MOTIF_WM_HINTS", False);
#if CISST_SVL_HAS_XV
    atoms[2] = XInternAtom(xDisplay, "XV_SYNC_TO_VBLANK", False);
#endif // CISST_SVL_HAS_XV

    // create title strings
    Titles = new std::string[NumOfWins];
    CustomTitles = new std::string[NumOfWins];
    CustomTitleEnabled = new int[NumOfWins];

#if CISST_SVL_HAS_XV
    xvImg = new XvImage*[NumOfWins];
    xvShmInfo = new XShmSegmentInfo[NumOfWins];
    xvPort = new XvPortID[NumOfWins];
    if (xvImg == 0 || xvShmInfo == 0 || xvPort == 0) goto labError;
    memset(xvImg, 0, NumOfWins * sizeof(XvImage*));
    memset(xvShmInfo, 0, NumOfWins * sizeof(XShmSegmentInfo));
    memset(xvPort, 0, NumOfWins * sizeof(XvPortID));
#else // CISST_SVL_HAS_XV
    // create images
    xImageBuffers = new unsigned char*[NumOfWins];
    for (i = 0; i < NumOfWins; i ++) {
        xImageBuffers[i] = new unsigned char[Width[i] * Height[i] * 4];
    }
    xImg = new XImage*[NumOfWins];
    memset(xImg, 0, NumOfWins * sizeof(XImage*));
    if (xImg == 0) goto labError;
    for (i = 0; i < NumOfWins; i ++) {
        xImg[i] = XCreateImage(xDisplay,
                               DefaultVisual(xDisplay, xScreen),
                               24,
                               ZPixmap,
                               0,
                               reinterpret_cast<char*>(xImageBuffers[i]),
                               Width[i],
                               Height[i],
                               32,
                               0);
    }
#endif // CISST_SVL_HAS_XV

    prevright = prevbottom = 0;
    for (i = 0; i < NumOfWins; i ++) {
        if (PosX == 0 || PosY == 0) {
            if (fullscreen) {
                x = prevright;
                y = 0;
                prevright += Width[i];
            }
            else {
                x = prevright;
                y = prevbottom;
                prevright += 50;
                prevbottom += 50;
            }
        }
        else {
            x = PosX[i];
            y = PosY[i];
        }

        xWindows[i] = XCreateSimpleWindow(xDisplay, DefaultRootWindow(xDisplay),
                                          x,
                                          y,
                                          Width[i],
                                          Height[i],
                                          0,
                                          black,
                                          white);
        if (xWindows[i] == 0) goto labError;

        // overriding default behaviours:
        //    - borderless mode
        //    - closing window
        if (fullscreen) {
            XChangeProperty(xDisplay, xWindows[i],
                            atoms[1], atoms[1], 32,
                            PropModeReplace, reinterpret_cast<unsigned char*>(&mwm), 5);
            atom_count = 2;
        }
        else {
            atom_count = 1;
        }
        XSetWMProtocols(xDisplay, xWindows[i], atoms, atom_count);

        wsh.flags = PPosition|PSize;
        wsh.x = x;
        wsh.y = y;
        wsh.width = Width[i];
        wsh.height = Height[i];
        XSetNormalHints(xDisplay, xWindows[i], &wsh);

        // set window title
        CustomTitleEnabled[i] = 0;

        std::ostringstream ostring;
        if (Title.length() > 0) {
            if (NumOfWins > 0) ostring << Title << " #" << i;
            else ostring << Title;
        }
        else {
            if (NumOfWins > 0) ostring << Title << "svlImageWindow #" << i;
            else ostring << "svlImageWindow";
        }

        Titles[i] = ostring.str();
        XSetStandardProperties(xDisplay, xWindows[i],
                               Titles[i].c_str(), Titles[i].c_str(),
                               None, NULL, 0, NULL);

        // set even mask
        XSelectInput(xDisplay, xWindows[i], ExposureMask|PointerMotionMask|ButtonPressMask|KeyPressMask);

        // set window colormap
        XSetWindowColormap(xDisplay, xWindows[i], DefaultColormapOfScreen(DefaultScreenOfDisplay(xDisplay)));

#if CISST_SVL_HAS_XV
        // query shared memory extension
        if (!XShmQueryExtension(xDisplay)) goto labError;

        // query video adaptors
        if (XvQueryAdaptors(xDisplay, DefaultRootWindow(xDisplay), &xvadaptorcount, &xvai) != Success) goto labError;
        xvPort[i] = xvai->base_id + i;
        XvFreeAdaptorInfo(xvai);

        // overriding default Xvideo vertical sync behavior
        XvSetPortAttribute (xDisplay, xvPort[i], atoms[2], 1);
#endif // CISST_SVL_HAS_XV

        // create graphics context
        xGCs[i] = XCreateGC(xDisplay, xWindows[i], 0, 0);

        // set default colors
        XSetBackground(xDisplay, xGCs[i], white);
        XSetForeground(xDisplay, xGCs[i], black);

#if CISST_SVL_HAS_XV
        // create image in shared memory
        xvImg[i] = XvShmCreateImage(xDisplay, xvPort[i], 0x32595559/*YUV2*/, 0, Width[i], Height[i], &(xvShmInfo[i]));
        if (xvImg[i]->width < static_cast<int>(Width[i]) || xvImg[i]->height < static_cast<int>(Height[i])) {
            CMN_LOG_INIT_ERROR << "DoModal - image too large for XV to display (requested="
                               << Width[i] << "x" << Height[i] << "; allowed="
                               << xvImg[i]->width << "x" << xvImg[i]->height << ")" << std::endl;
            goto labError;
        }
        xvShmInfo[i].shmid = shmget(IPC_PRIVATE, xvImg[i]->data_size, IPC_CREAT | 0777);
        xvShmInfo[i].shmaddr = xvImg[i]->data = reinterpret_cast<char*>(shmat(xvShmInfo[i].shmid, 0, 0));
        xvShmInfo[i].readOnly = False;
        if (!XShmAttach(xDisplay, &(xvShmInfo[i]))) goto labError;
#endif // CISST_SVL_HAS_XV

        // clear window
        XClearWindow(xDisplay, xWindows[i]);

        // show window if requested
        if (show) XMapRaised(xDisplay, xWindows[i]);
    }

    // signal that initialization is done
    if (InitReadySignal) InitReadySignal->Raise();

	// main message loop
    XEvent event;
    KeySym code;
    unsigned int winid;

    while (1) {
        osaSleep(0.001);
#if CISST_SVL_HAS_XV
        if (!xvupdateimage) {
            for (int events = XPending(xDisplay); events > 0; events --) {
#else // CISST_SVL_HAS_XV
        if (XPending(xDisplay)) {
#endif // CISST_SVL_HAS_XV
                XNextEvent(xDisplay, &event);

                // find recipient
                for (winid = 0; winid < NumOfWins; winid ++) {
                    if (event.xany.window == xWindows[winid]) break;
                }
                if (winid == NumOfWins) continue;

                // override default window behaviour
                if (event.type == ClientMessage) {
                    if (static_cast<unsigned long>(event.xclient.data.l[0]) == atoms[0]) {
                        // X11 server wants to close window
                        // Do nothing.... we will destroy it ourselves later
                    }
                    continue;
                }

                // window should be closed
                if (event.type == UnmapNotify) {
                    printf("destroy\n");
                    if (xGCs[winid]) {
                        XFreeGC(xDisplay, xGCs[winid]);
                        xGCs[winid] = 0;
                    }
                    xWindows[winid] = 0;
                    continue;
                }

                // window should be updated
                if (event.type == Expose && event.xexpose.count == 0) {
                    XClearWindow(xDisplay, xWindows[winid]);
                    continue;
                }

                if (event.type == KeyPress) {
                    code = XLookupKeysym(&event.xkey, 0);
                    if (code >= 48 && code <= 57) { // ascii numbers
                        OnUserEvent(winid, true, code);
                        continue;
                    }
                    if (code >= 97 && code <= 122) { // ascii letters
                        OnUserEvent(winid, true, code);
                        continue;
                    }
                    if (code == 13 ||
                        code == 32) { // special characters with correct ascii code
                        OnUserEvent(winid, true, code);
                        continue;
                    }
                    if (code >= 0xffbe && code <= 0xffc9) { // F1-F12
                        OnUserEvent(winid, false, winInput_KEY_F1 + (code - 0xffbe));
                        continue;
                    }
                    switch (code) {
                        case 0xFF55:
                            OnUserEvent(winid, false, winInput_KEY_PAGEUP);
                        break;

                        case 0xFF56:
                            OnUserEvent(winid, false, winInput_KEY_PAGEDOWN);
                        break;

                        case 0xFF50:
                            OnUserEvent(winid, false, winInput_KEY_HOME);
                        break;

                        case 0xFF57:
                            OnUserEvent(winid, false, winInput_KEY_END);
                        break;

                        case 0xFF63:
                            OnUserEvent(winid, false, winInput_KEY_INSERT);
                        break;

                        case 0xFFFF:
                            OnUserEvent(winid, false, winInput_KEY_DELETE);
                        break;

                        case 0xFF51:
                            OnUserEvent(winid, false, winInput_KEY_LEFT);
                        break;

                        case 0xFF53:
                            OnUserEvent(winid, false, winInput_KEY_RIGHT);
                        break;

                        case 0xFF52:
                            OnUserEvent(winid, false, winInput_KEY_UP);
                        break;

                        case 0xFF54:
                            OnUserEvent(winid, false, winInput_KEY_DOWN);
                        break;
                    }
                    continue;
                }

                if (event.type == ButtonPress) {
                    if (event.xbutton.button == Button1) {
                        if (!LButtonDown && !RButtonDown) {
                            LButtonDown = true;
                            XGrabPointer(xDisplay, xWindows[winid], false,
                                         PointerMotionMask|ButtonReleaseMask,
                                         GrabModeAsync, GrabModeAsync,
                                         None,
                                         None,
                                         CurrentTime);
                        }
                        OnUserEvent(winid, false, winInput_LBUTTONDOWN);
                    }
                    else if (event.xbutton.button == Button3) {
                        if (!LButtonDown && !RButtonDown) {
                            RButtonDown = true;
                            XGrabPointer(xDisplay, xWindows[winid], false,
                                         PointerMotionMask|ButtonReleaseMask,
                                         GrabModeAsync, GrabModeAsync,
                                         None,
                                         None,
                                         CurrentTime);
                        }
                        OnUserEvent(winid, false, winInput_RBUTTONDOWN);
                    }
                }
                
                if (event.type == ButtonRelease) {
                    if (event.xbutton.button == Button1) {
                        OnUserEvent(winid, false, winInput_LBUTTONUP);
                        if (LButtonDown && !RButtonDown) {
                            LButtonDown = false;
                            XUngrabPointer(xDisplay, CurrentTime);
                        }
                    }
                    else if (event.xbutton.button == Button3) {
                        OnUserEvent(winid, false, winInput_RBUTTONUP);
                        if (!LButtonDown && RButtonDown) {
                            RButtonDown = false;
                            XUngrabPointer(xDisplay, CurrentTime);
                        }
                    }
                }

                if (event.type == MotionNotify) {
                    SetMousePos(static_cast<short>(event.xmotion.x), static_cast<short>(event.xmotion.y));
                    OnUserEvent(winid, false, winInput_MOUSEMOVE);
                }

#if CISST_SVL_HAS_XV
                // image update complete
                if (event.type == XShmGetEventBase(xDisplay) + ShmCompletion) {
                    xvupdateimage = true;
                    continue;
                }
            }
            if (!xvupdateimage) signalImage.Wait(0.01);
#endif // CISST_SVL_HAS_XV
        }
        else {
            if (DestroyFlag) break;

            if (ImageCounter > lastimage) {
                csImage.Enter();
                    lastimage = ImageCounter;

#if CISST_SVL_HAS_XV
                    for (i = 0; i < NumOfWins; i ++) {
                        XvShmPutImage(xDisplay,
                                      xvPort[i],
                                      xWindows[i],
                                      xGCs[i],
                                      xvImg[i],
                                      0, 0, Width[i], Height[i],
                                      0, 0, Width[i], Height[i], True);
                    }
                    xvupdateimage = false;
#else // CISST_SVL_HAS_XV
                    for (i = 0; i < NumOfWins; i ++) {
                        xImg[i]->data = reinterpret_cast<char*>(xImageBuffers[i]);
                        XPutImage(xDisplay,
                                  xWindows[i],
                                  xGCs[i],
                                  xImg[i],
                                  0, 0, 0, 0,
                                  Width[i], Height[i]);
                    }
#endif // CISST_SVL_HAS_XV
/*
                    for (i = 0; i < NumOfWins; i ++) {
                        if (CustomTitleEnabled[i] < 0) {
                            // Restore original timestamp
                            XSetStandardProperties(xDisplay, xWindows[i],
                                                   Titles[i].c_str(), Titles[i].c_str(),
                                                   None, NULL, 0, NULL);
                        }
                        else if (CustomTitleEnabled[i] > 0) {
                            // Set custom timestamp
                            XSetStandardProperties(xDisplay, xWindows[i],
                                                   CustomTitles[i].c_str(), CustomTitles[i].c_str(),
                                                   None, NULL, 0, NULL);
                        }
                    }
*/
                csImage.Leave();
            }
        }
    }

labError:

#if CISST_SVL_HAS_XV
    if (xvShmInfo) {
        for (i = 0; i < NumOfWins; i ++) {
            XShmDetach(xDisplay, &(xvShmInfo[i]));
            shmdt(xvShmInfo[i].shmaddr);
        }
        delete [] xvShmInfo; 
        xvShmInfo = 0;
    }
#endif // CISST_SVL_HAS_XV
    XSync(xDisplay, 0);
    for (i = 0; i < NumOfWins; i ++) {
        if (xGCs[i]) XFreeGC(xDisplay, xGCs[i]);
        if (xWindows[i]) XDestroyWindow(xDisplay, xWindows[i]);
    }
    XCloseDisplay(xDisplay);
#if CISST_SVL_HAS_XV
    if (xvImg) {
        for (i = 0; i < NumOfWins; i ++) {
            if (xvImg[i]) XFree(xvImg[i]); 
        }
        delete [] xvImg; 
        xvImg = 0;
    }
    if (xvPort) {
        delete [] xvPort; 
        xvPort = 0;
    }
#else // CISST_SVL_HAS_XV
    if (xImg) {
        for (i = 0; i < NumOfWins; i ++) {
            if (xImg[i]) XDestroyImage(xImg[i]); 
        }
        delete [] xImg; 
        xImg = 0;
    }
    if (xImageBuffers) {
        delete [] xImageBuffers;
        xImageBuffers = 0;
    }
#endif // CISST_SVL_HAS_XV
    if (xGCs) {
        delete [] xGCs;
        xGCs = 0;
    }
    if (xWindows) {
        delete [] xWindows;
        xWindows = 0;
    }
    if (Titles) {
        delete [] Titles;
        Titles = 0;
    }
    if (CustomTitles) {
        delete [] CustomTitles;
        CustomTitles = 0;
    }
    if (CustomTitleEnabled) {
        delete [] CustomTitleEnabled;
        CustomTitleEnabled = 0;
    }

    xScreen = 0;
    xDisplay = 0;

    if (DestroyedSignal) DestroyedSignal->Raise();

    return 0;
}
Esempio n. 12
0
File: slock.c Progetto: eepp/slock
static Lock *
lockscreen(Display *dpy, int screen) {
	char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
	unsigned int len;
	Lock *lock;
	XColor color;
	XSetWindowAttributes wa;
	Cursor invisible;
	int hue1, hue2;

	if(dpy == NULL || screen < 0)
		return NULL;

	lock = malloc(sizeof(Lock));
	if(lock == NULL)
		return NULL;

	lock->screen = screen;
	lock->root = RootWindow(dpy, lock->screen);

	/* init */
	wa.override_redirect = 1;
	lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
			0, DefaultDepth(dpy, lock->screen), CopyFromParent,
			DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
	
	/* locked color */
	hue1 = rand() % 360;
	gen_random_pastel(&color, hue1);
	XAllocColor(dpy, DefaultColormap(dpy, lock->screen), &color);
	lock->colors[0] = color.pixel;
	XSetWindowBackground(dpy, lock->win, lock->colors[0]);
	
	/* trying to unlock color */
	hue2 = hue1 + 180;
	if (hue2 >= 360) {
		hue2 -= 360;
	}
	gen_random_pastel(&color, hue2);
	XAllocColor(dpy, DefaultColormap(dpy, lock->screen), &color);
	lock->colors[1] = color.pixel;
	
	lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
	invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
	XDefineCursor(dpy, lock->win, invisible);
	XMapRaised(dpy, lock->win);
	for(len = 1000; len; len--) {
		if(XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
			GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
			break;
		usleep(1000);
	}
	if(running && (len > 0)) {
		for(len = 1000; len; len--) {
			if(XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
				== GrabSuccess)
				break;
			usleep(1000);
		}
	}

	running &= (len > 0);
	if(!running) {
		unlockscreen(dpy, lock);
		lock = NULL;
	}
	else 
		XSelectInput(dpy, lock->root, SubstructureNotifyMask);

	return lock;
}
Esempio n. 13
0
XSilChessWindow::XSilChessWindow(XtAppContext app, Widget toplevel,
                                 Visual * vsl, int vsldepth, Colormap cmap)
{
	char tmp[512];
	Arg al[10];
	int i;
	XmString xms;

	// Initialize member variables
	App=app;
	TopLevel=toplevel;
	Disp=XtDisplay(TopLevel);
	Vsl=vsl;
	VslDepth=vsldepth;
	CMap=cmap;
	DlgVsl=DefaultVisual(Disp,XScreenNumberOfScreen(XtScreen(TopLevel)));
	DlgVslDepth=DefaultDepth(Disp,XScreenNumberOfScreen(XtScreen(TopLevel)));
	DlgCMap=DefaultColormap(Disp,XScreenNumberOfScreen(XtScreen(TopLevel)));
	PixelSize=(VslDepth<=8 ? 1 : (VslDepth<=16 ? 2 : 4));
	RedMask=Vsl->red_mask;
	GreenMask=Vsl->green_mask;
	BlueMask=Vsl->blue_mask;
	SelX=SelY-1;
	IsSearching=false;
	AbortSearching=false;
	NeedPainting=false;
	IsPainting=false;
	HintWanted=false;
	HintValid=false;

	// Create main window
	MainWin=XtVaCreateManagedWidget(
		"mainWin",xmMainWindowWidgetClass,TopLevel,
		(char*)NULL
	);

	// Create main menu bar
	MainMenu=XmCreateMenuBar(MainWin,(char*)"mainMenu",NULL,0);
	XtManageChild(MainMenu);

	// Create menu item: file
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	FileMenu=XmCreatePulldownMenu(MainMenu,(char*)"fileMenu",al,3);
	BFile=XtVaCreateManagedWidget(
		"file",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,FileMenu,
		(char*)NULL
	);

	// Create menu item: file/load
	BFileLoad=XtVaCreateManagedWidget(
		"load",xmPushButtonWidgetClass,FileMenu,
		(char*)NULL
	);
	XtAddCallback(BFileLoad,XmNactivateCallback,HandleCallback,this);

	// Create menu item: file/save
	BFileSave=XtVaCreateManagedWidget(
		"save",xmPushButtonWidgetClass,FileMenu,
		(char*)NULL
	);
	XtAddCallback(BFileSave,XmNactivateCallback,HandleCallback,this);

	// Create menu item: file/exit
	XtVaCreateManagedWidget(
		"separator",xmSeparatorWidgetClass,FileMenu,
		(char*)NULL
	);
	BFileExit=XtVaCreateManagedWidget(
		"exit",xmPushButtonWidgetClass,FileMenu,
		(char*)NULL
	);
	XtAddCallback(BFileExit,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	GameMenu=XmCreatePulldownMenu(MainMenu,(char*)"gameMenu",al,3);
	BGame=XtVaCreateManagedWidget(
		"game",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,GameMenu,
		(char*)NULL
	);

	// Create menu item: game/new
	BGameNew=XtVaCreateManagedWidget(
		"new",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameNew,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game/flip
	BGameFlip=XtVaCreateManagedWidget(
		"flip",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameFlip,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game/undo
	BGameUndo=XtVaCreateManagedWidget(
		"undo",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameUndo,XmNactivateCallback,HandleCallback,this);

	// Create menu item: game/list
	BGameList=XtVaCreateManagedWidget(
		"list",xmPushButtonWidgetClass,GameMenu,
		(char*)NULL
	);
	XtAddCallback(BGameList,XmNactivateCallback,HandleCallback,this);

	// Create menu item: computer
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	CompMenu=XmCreatePulldownMenu(MainMenu,(char*)"compMenu",al,3);
	BComp=XtVaCreateManagedWidget(
		"comp",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,CompMenu,
		(char*)NULL
	);

	// Create menu item: computer/hint
	BCompHint=XtVaCreateManagedWidget(
		"hint",xmPushButtonWidgetClass,CompMenu,
		(char*)NULL
	);
	XtAddCallback(BCompHint,XmNactivateCallback,HandleCallback,this);

	// Create menu item: computer/depth
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	XtSetArg(al[3],XmNradioBehavior,True);
	DepthMenu=XmCreatePulldownMenu(CompMenu,(char*)"depthMenu",al,4);
	BCompDepth=XtVaCreateManagedWidget(
		"depth",xmCascadeButtonWidgetClass,CompMenu,
		XmNsubMenuId,DepthMenu,
		(char*)NULL
	);

	// Create menu items: computer/depth/1...
	for (i=0; i<=SilChessMachine::MAX_SEARCH_DEPTH; i++) {
		sprintf(tmp,"%d",i);
		BDepth[i]=XtVaCreateManagedWidget(
			tmp,xmToggleButtonWidgetClass,DepthMenu,
			(char*)NULL
		);
		XtAddCallback(BDepth[i],XmNvalueChangedCallback,HandleCallback,this);
	}

	// Create menu item: help
	XtSetArg(al[0],XmNvisual,Vsl);
	XtSetArg(al[1],XmNdepth,VslDepth);
	XtSetArg(al[2],XmNcolormap,CMap);
	HelpMenu=XmCreatePulldownMenu(MainMenu,(char*)"helpMenu",al,3);
	BHelp=XtVaCreateManagedWidget(
		"help",xmCascadeButtonWidgetClass,MainMenu,
		XmNsubMenuId,HelpMenu,
		(char*)NULL
	);
	XtVaSetValues(MainMenu,XmNmenuHelpWidget,BHelp,(char*)NULL);

	// Create menu item: help/about
	BHelpAbout=XtVaCreateManagedWidget(
		"about",xmPushButtonWidgetClass,HelpMenu,
		(char*)NULL
	);
	XtAddCallback(BHelpAbout,XmNactivateCallback,HandleCallback,this);

	// Create a parent for status bar and view
	MainForm=XtVaCreateManagedWidget(
		"mainForm",xmFormWidgetClass,MainWin,
		(char*)NULL
	);

	// Create status line
	StatusFrame=XtVaCreateManagedWidget(
		"statusFrame",xmFrameWidgetClass,MainForm,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNtopAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	StatusLabel=XtVaCreateManagedWidget(
		"statusLabel",xmLabelWidgetClass,StatusFrame,
		XmNalignment, XmALIGNMENT_BEGINNING,
		(char*)NULL
	);

	// Create the chess board view
	ViewFrame=XtVaCreateManagedWidget(
		"viewFrame",xmFrameWidgetClass,MainForm,
		XmNtopAttachment,XmATTACH_WIDGET,
		XmNtopWidget,StatusFrame,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	ViewArea=XtVaCreateManagedWidget(
		"viewArea",xmDrawingAreaWidgetClass,ViewFrame,
		XmNtopAttachment,XmATTACH_FORM,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	XtAddCallback(ViewArea,XmNexposeCallback,HandleCallback,this);
	XtAddCallback(ViewArea,XmNresizeCallback,HandleCallback,this);
	XtAddEventHandler(
		ViewArea,ButtonPressMask|ButtonMotionMask|ButtonReleaseMask|
		StructureNotifyMask,False,HandleEvent,this
	);
	XtVaGetValues(ViewArea,XmNwidth,&ViewWidth,(char*)NULL);
	XtVaGetValues(ViewArea,XmNheight,&ViewHeight,(char*)NULL);
	ViewWin=0;
	ViewGC=NULL;

	// Create dialog: load game
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage,True);
	LoadDialog=XmCreateFileSelectionDialog(TopLevel,(char*)"loadDialog",al,4);
	XtAddCallback(LoadDialog,XmNokCallback,HandleCallback,this);
	XtUnmanageChild(XmFileSelectionBoxGetChild(LoadDialog,XmDIALOG_HELP_BUTTON));

	// Create dialog: save game
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage, True);
	SaveDialog=XmCreateFileSelectionDialog(TopLevel,(char*)"saveDialog",al,4);
	XtAddCallback(SaveDialog,XmNokCallback,HandleCallback,this);
	XtUnmanageChild(XmFileSelectionBoxGetChild(SaveDialog,XmDIALOG_HELP_BUTTON));

	// Create dialog: file exists, overwrite?
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage, True);
	OverwriteDialog=XmCreateWarningDialog(TopLevel,(char*)"overwriteDialog",al,4);
	XtUnmanageChild(XmMessageBoxGetChild(OverwriteDialog,XmDIALOG_HELP_BUTTON));
	XtAddCallback(OverwriteDialog,XmNokCallback,HandleCallback,this);

	// Create dialog: error message
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage, True);
	ErrorBox=XmCreateWarningDialog(TopLevel,(char*)"errorBox",al,4);
	XtUnmanageChild(XmMessageBoxGetChild(ErrorBox,XmDIALOG_CANCEL_BUTTON));
	XtUnmanageChild(XmMessageBoxGetChild(ErrorBox,XmDIALOG_HELP_BUTTON));

	// Create dialog: list of moves
	ListDialogPopup=XtVaCreateWidget(
		"listDialog_popup",xmDialogShellWidgetClass,TopLevel,
		XmNvisual,DlgVsl,
		XmNdepth,DlgVslDepth,
		XmNcolormap,DlgCMap,
		(char*)NULL
	);
	ListDialog=XtVaCreateWidget(
		"listDialog",xmFormWidgetClass,ListDialogPopup,
		(char*)NULL
	);
	LDClose=XtVaCreateManagedWidget(
		"close",xmPushButtonWidgetClass,ListDialog,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_FORM,
		(char*)NULL
	);
	XtAddCallback(LDClose,XmNactivateCallback,HandleCallback,this);
	LDScroll=XtVaCreateManagedWidget(
		"scroll",xmScrolledWindowWidgetClass,ListDialog,
		XmNscrollingPolicy,XmAUTOMATIC,
		XmNscrollBarDisplayPolicy,XmAS_NEEDED,
		XmNleftAttachment,XmATTACH_FORM,
		XmNrightAttachment,XmATTACH_FORM,
		XmNtopAttachment,XmATTACH_FORM,
		XmNbottomAttachment,XmATTACH_WIDGET,
		XmNbottomWidget,LDClose,
		(char*)NULL
	);
	LDList=XtVaCreateManagedWidget(
		"list",xmLabelGadgetClass,LDScroll,
		XmNalignment,XmALIGNMENT_BEGINNING,
		(char*)NULL
	);

	// Create dialog: about
	xms=XmStringCreateLtoR((char*)AboutText,XmFONTLIST_DEFAULT_TAG);
	XtSetArg(al[0],XmNvisual,DlgVsl);
	XtSetArg(al[1],XmNdepth,DlgVslDepth);
	XtSetArg(al[2],XmNcolormap,DlgCMap);
	XtSetArg(al[3],XmNautoUnmanage,True);
	XtSetArg(al[4],XmNmessageString,xms);
	XtSetArg(al[5],XmNmessageAlignment,XmALIGNMENT_CENTER);
	AboutDialog=XmCreateMessageDialog(TopLevel,(char*)"aboutDialog",al,6);
	XmStringFree(xms);
	XtUnmanageChild(XmMessageBoxGetChild(AboutDialog,XmDIALOG_CANCEL_BUTTON));
	XtUnmanageChild(XmMessageBoxGetChild(AboutDialog,XmDIALOG_HELP_BUTTON));

	// Set main window areas
	XmMainWindowSetAreas(MainWin,MainMenu,NULL,NULL,NULL,MainForm);

	// Create chess machine
	Machine = new SilChessMachine();

	// Setup ray tracer
	RT.SetViewSize(ViewWidth,ViewHeight);
	RT.SetWorld(Machine);

	// Update all
	UpdateStatusBar();
	UpdateMovesList();
	UpdateView();
	UpdateDepthMenu();
}
Esempio n. 14
0
XImage *
read_ppm_file(Display *disp, Colormap cmap, int depth, IOSTREAM *fd)
{ XImage *img;
  long here = Stell(fd);
  int c;
  int fmt, encoding;
  int width, height, bytes_per_line, scale=0;
  char *data;
  int allocdepth;
  int pad = XBitmapPad(disp);
  Visual *v = DefaultVisual(disp, DefaultScreen(disp));

  ncolours = nmapped = nfailed = 0;	/* statistics */
  assert(pad%8 == 0);

  if ( (c=Sgetc(fd)) != 'P' )
  { Sungetc(c, fd);
    return NULL;
  }

  if ( !cmap )
    cmap = DefaultColormap(disp, DefaultScreen(disp));

  c = Sgetc(fd);
  if ( c < '1' || c > '9' )
    goto errout;
  c -= '0';
  fmt      = ((c - 1) % 3) + 1;
  encoding = c - fmt;

  width = getNum(fd);
  height = getNum(fd);

  if ( fmt == PNM_PBM )
  { depth = 1;
  } else
  { scale = getNum(fd);
    if ( !depth )
      depth = DefaultDepth(disp, DefaultScreen(disp));
  }

  if ( width < 0 || height < 0 || scale < 0 )
    goto errout;

  allocdepth = (depth >= 24 ? 32 : depth);
  bytes_per_line = roundup((width*allocdepth+7)/8, pad/8);
  data = (char *)pceMalloc(height * bytes_per_line);

  img = XCreateImage(disp,
		     v,
		     depth,
		     fmt == PNM_PBM ? XYBitmap : ZPixmap,
		     0,
		     data,
		     width, height,
		     pad, bytes_per_line);
  if ( !img )
  { perror("XCreateImage");
    pceFree(data);
    goto errout;
  }
  img->bits_per_pixel = depth;

  switch(encoding)
  { int x, y;

    case PNM_ASCII:
    { switch(fmt)
      { case PNM_PBM:
	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int value = getNum(fd);

	      if ( value < 0 || value > 1 )
		goto errout;

	      XPutPixel(img, x, y, value);
	    }
	  }
	  break;
	case PNM_PGM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int g = getNum(fd);
	      unsigned long pixel;

	      if ( g < 0 || g > scale )
		goto errout;
	      if ( scale != 255 )
		g = rescale(g, scale, 255);

	      pixel = colourPixel(disp, depth, cmap, t, g, g, g);
	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	case PNM_PPM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int r = getNum(fd);
	      int g = getNum(fd);
	      int b = getNum(fd);
	      unsigned long pixel;

	      if ( r < 0 || r > scale ||
		   g < 0 || g > scale ||
		   b < 0 || b > scale )
		goto errout;

	      if ( scale != 255 )
	      { r = rescale(r, scale, 255);
		g = rescale(g, scale, 255);
		b = rescale(b, scale, 255);
	      }

	      pixel = colourPixel(disp, depth, cmap, t, r, g, b);

	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	break;
      }
      break;
    }
    case PNM_RAWBITS:
    { switch(fmt)
      { case PNM_PBM:
	{ int byte = 0;
	  int bit = 0;

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { if ( !bit )
	      { byte = Sgetc(fd);
		bit = 8;
	      }

	      bit--;
	      XPutPixel(img, x, y, (byte & (1<<bit)) ? 1 : 0);
	    }
	    bit = 0;			/* scanlines are byte-aligned */
	  }
	  break;
	}
	case PNM_PGM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int g;
	      unsigned long pixel;

	      if ( Sfeof(fd) || (g=Sgetc(fd)) > scale )
		goto errout;
	      if ( scale != 255 )
		g = rescale(g, scale, 255);

	      pixel = colourPixel(disp, depth, cmap, t, g, g, g);
	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	case PNM_PPM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { int r, g, b;
	      unsigned long pixel;

	      if ( Sfeof(fd) ||
		   (r=Sgetc(fd)) > scale ||
		   (g=Sgetc(fd)) > scale ||
		   (b=Sgetc(fd)) > scale )
		goto errout;

	      if ( scale != 255 )
	      { r = rescale(r, scale, 255);
		g = rescale(g, scale, 255);
		b = rescale(b, scale, 255);
	      }

	      pixel = colourPixel(disp, depth, cmap, t, r, g, b);

	      XPutPixel(img, x, y, pixel);
	    }
	  }
	  freeTable(t);

	  break;
	}
	break;
      }
      break;
    }
    case PNM_RUNLEN:
    { int rlen = 0;
      unsigned long cpixel = NOPIXEL;

      switch(fmt)
      { case PNM_PGM:
	{ Table t = newTable(64);

	  DEBUG(NAME_pnm, Cprintf("Reading runlength encoded graymap\n"));

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { if ( rlen-- > 0 )
	      { XPutPixel(img, x, y, cpixel);
	      } else
	      { int g;

		if ( (g=Sgetc(fd)) > scale ||
		     (rlen = Sgetc(fd)) == EOF )
		  goto errout;
		rlen &= 0xff;
		if ( scale != 255 )
		  g = rescale(g, scale, 255);

		cpixel = colourPixel(disp, depth, cmap, t, g, g, g);
		XPutPixel(img, x, y, cpixel);
		rlen--;
	      }
	    }
	  }
	  freeTable(t);

	  break;
	}
	case PNM_PPM:
	{ Table t = newTable(64);

	  for(y=0; y<height; y++)
	  { for(x=0; x<width; x++)
	    { if ( rlen-- > 0 )
	      { XPutPixel(img, x, y, cpixel);
	      } else
	      { int r, g, b;

		if ( (r=Sgetc(fd)) > scale ||
		     (g=Sgetc(fd)) > scale ||
		     (b=Sgetc(fd)) > scale ||
		     (rlen = Sgetc(fd)) == EOF )
		  goto errout;

		rlen &= 0xff;
		if ( scale != 255 )
		{ r = rescale(r, scale, 255);
		  g = rescale(g, scale, 255);
		  b = rescale(b, scale, 255);
		}

		cpixel = colourPixel(disp, depth, cmap, t, r, g, b);

		XPutPixel(img, x, y, cpixel);
		rlen--;
	      }
	    }
	  }
	  freeTable(t);

	  break;
	}
      }
    }
  }

  DEBUG(NAME_ppm,
	Cprintf("PNM: Converted %dx%dx%d image, %d colours (%d mapped, %d failed)\n",
		width, height, depth, ncolours, nmapped, nfailed));

  return img;

errout:
  DEBUG(NAME_ppm,
	Cprintf("PNM: Format error, index = %d\n", Stell(fd)));
  Sseek(fd, here, SEEK_SET);
  return NULL;
}
Esempio n. 15
0
    framebuffer( uint32_t width = 800, uint32_t height = 600 ) : width_(width), height_(height) {
        
        
        {
            // select display and screen
            const char *dpyName = ":0";
            display_ = XOpenDisplay( dpyName );
            scrnum_ = DefaultScreen( display_ );
            if( display_ == 0 ) {
                throw std::runtime_error( "X11 display == 0\n" );
            }
        
        }
        
        
        {
            // create window
            
            Window root;
            root = RootWindow( display_, scrnum_ );
            
            XSetWindowAttributes attr;                   
            attr.background_pixel = 0;
            attr.border_pixel = 0;
            attr.colormap = XCreateColormap( display_, root, DefaultVisual( display_, 0 ), AllocNone );
            attr.event_mask =  StructureNotifyMask | ExposureMask | KeyPressMask | FocusChangeMask;
            unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
            
            window_ = XCreateWindow( display_, root, 0, 0, width, height,
                                      0, DefaultDepth(display_, 0), InputOutput, DefaultVisual(display_, 0), mask, &attr );
            
            if( window_ == 0 )
            {
                
                throw std::runtime_error( "XCreateWindow failed\n" );
            }
        
        }
        
        
        {
            // additional window setup
            XSizeHints sizehints;
            sizehints.width = width_;
            sizehints.height = height_;
            sizehints.flags = USSize;
            XSetNormalHints( display_, window_, &sizehints );
            
            const char *name = "Human Interface";
            // is XSetNormalHints above just plain stupid?
            XSetStandardProperties( display_, window_, name, name, None, (char**)0, 0, &sizehints );   
        }
        
        
        XMapWindow( display_, window_ );
        
        // wait for map notify
        while(true) {
            XEvent e;
            XNextEvent(display_, &e);
            std::cout << "event: " << e.type << "\n";
            if (e.type == MapNotify) {
                break;
            }
        }
        
        
        // done
        
        gc_ = XCreateGC( display_, window_, 0, 0 );
    
        
//         shminfo.
#if 0    
        XImage *xi = XShmCreateImage(display_, DefaultVisual( display_, 0 ), DefaultDepthOfScreen(screen),
                          ZPixmap, NULL, &shminfo,
                          width_, height_);
#endif   
     
        
    }
Esempio n. 16
0
void
Tk_DrawChars(
    Display *display,		/* Display on which to draw. */
    Drawable drawable,		/* Window or pixmap in which to draw. */
    GC gc,			/* Graphics context for drawing characters. */
    Tk_Font tkfont,		/* Font in which characters will be drawn;
				 * must be the same as font used in GC. */
    CONST char *source,		/* UTF-8 string to be displayed. Need not be
				 * '\0' terminated. All Tk meta-characters
				 * (tabs, control characters, and newlines)
				 * should be stripped out of the string that
				 * is passed to this function. If they are not
				 * stripped out, they will be displayed as
				 * regular printing characters. */
    int numBytes,		/* Number of bytes in string. */
    int x, int y)		/* Coordinates at which to place origin of
				 * string when drawing. */
{
    const int maxCoord = 0x7FFF;/* Xft coordinates are 16 bit values */
    UnixFtFont *fontPtr = (UnixFtFont *) tkfont;
    XGCValues values;
    XColor xcolor;
    int clen, nspec;
    XftGlyphFontSpec specs[NUM_SPEC];
    XGlyphInfo metrics;

    if (fontPtr->ftDraw == 0) {
#if DEBUG_FONTSEL
	printf("Switch to drawable 0x%x\n", drawable);
#endif /* DEBUG_FONTSEL */
	fontPtr->ftDraw = XftDrawCreate(display, drawable,
		DefaultVisual(display, fontPtr->screen),
		DefaultColormap(display, fontPtr->screen));
    } else {
	Tk_ErrorHandler handler = Tk_CreateErrorHandler(display, -1, -1, -1,
		NULL, (ClientData) NULL);

	XftDrawChange(fontPtr->ftDraw, drawable);
	Tk_DeleteErrorHandler(handler);
    }
    XGetGCValues(display, gc, GCForeground, &values);
    if (values.foreground != fontPtr->color.pixel) {
	xcolor.pixel = values.foreground;
	XQueryColor(display, DefaultColormap(display, fontPtr->screen),
		&xcolor);
	fontPtr->color.color.red = xcolor.red;
	fontPtr->color.color.green = xcolor.green;
	fontPtr->color.color.blue = xcolor.blue;
	fontPtr->color.color.alpha = 0xffff;
	fontPtr->color.pixel = values.foreground;
    }
    nspec = 0;
    while (numBytes > 0 && x <= maxCoord && y <= maxCoord) {
	XftFont *ftFont;
	FcChar32 c;

	clen = FcUtf8ToUcs4((FcChar8 *) source, &c, numBytes);
	if (clen <= 0) {
	    /*
	     * This should not happen, but it can.
	     */

	    return;
	}
	source += clen;
	numBytes -= clen;

	ftFont = GetFont(fontPtr, c);
	if (ftFont) {
	    specs[nspec].font = ftFont;
	    specs[nspec].glyph = XftCharIndex(fontPtr->display, ftFont, c);
	    specs[nspec].x = x;
	    specs[nspec].y = y;
	    XftGlyphExtents(fontPtr->display, ftFont, &specs[nspec].glyph, 1,
		    &metrics);
	    x += metrics.xOff;
	    y += metrics.yOff;
	    nspec++;
	    if (nspec == NUM_SPEC) {
		XftDrawGlyphFontSpec(fontPtr->ftDraw, &fontPtr->color,
			specs, nspec);
		nspec = 0;
	    }
	}
    }
    if (nspec) {
	XftDrawGlyphFontSpec(fontPtr->ftDraw, &fontPtr->color, specs, nspec);
    }
}
Esempio n. 17
0
static void createWindow()
{
	int scr = DefaultScreen(dpy);
	int width = DisplayWidth(dpy, scr);
	int height = DisplayHeight(dpy, scr);
	XSetWindowAttributes attr;
	attr.event_mask = ButtonPress | ButtonRelease;
	win = XCreateWindow(dpy, RootWindow(dpy, scr), 0, 0, width, height, 0, 0, InputOnly, DefaultVisual(dpy, scr), CWEventMask, &attr);
}
Esempio n. 18
0
Status
XmuLookupStandardColormap(Display *dpy, int screen, VisualID visualid,
			  unsigned int depth, Atom property,
			  Bool replace, Bool retain)
     /*
      * dpy		- specifies X server connection
      * screen 		- specifies screen of display
      * visualid	- specifies the visual type
      * depth		- specifies  the visual type
      * property	- a standard colormap property
      * replace		- specifies whether to replace
      * retain		- specifies whether to retain
      */
{
    Display		*odpy;		/* original display connection */
    XStandardColormap	*colormap;
    XVisualInfo		vinfo_template, *vinfo;	/* visual */
    long		vinfo_mask;
    unsigned long	r_max, g_max, b_max;	/* allocation */
    int			count;
    Colormap		cmap;			/* colormap ID */
    Status		status = 0;


    /* Match the requested visual */

    vinfo_template.visualid = visualid;
    vinfo_template.screen = screen;
    vinfo_template.depth = depth;
    vinfo_mask = VisualIDMask | VisualScreenMask | VisualDepthMask;
    if ((vinfo = XGetVisualInfo(dpy, vinfo_mask, &vinfo_template, &count)) ==
	NULL)
	return 0;

    /* Monochrome visuals have no standard maps */

    if (vinfo->colormap_size <= 2) {
	XFree((char *) vinfo);
	return 0;
    }

    /* If the requested property already exists on this screen, and,
     * if the replace flag has not been set to true, return success.
     * lookup() will remove a pre-existing map if replace is true.
     */

    if (lookup(dpy, screen, visualid, property, (XStandardColormap *) NULL,
	       replace) && !replace) {
	XFree((char *) vinfo);
	return 1;
    }

    /* Determine the best allocation for this property under the requested
     * visualid and depth, and determine whether or not to use the default
     * colormap of the screen.
     */

    if (!XmuGetColormapAllocation(vinfo, property, &r_max, &g_max, &b_max)) {
	XFree((char *) vinfo);
	return 0;
    }

    cmap = (property == XA_RGB_DEFAULT_MAP &&
	    visualid == XVisualIDFromVisual(DefaultVisual(dpy, screen)))
	? DefaultColormap(dpy, screen) : None;

    /* If retaining resources, open a new connection to the same server */

    if (retain) {
	odpy = dpy;
	if ((dpy = XOpenDisplay(XDisplayString(odpy))) == NULL) {
	    XFree((char *) vinfo);
	    return 0;
	}
    }

    /* Create the standard colormap */

    colormap = XmuStandardColormap(dpy, screen, visualid, depth, property,
				   cmap, r_max, g_max, b_max);

    /* Set the standard colormap property */

    if (colormap) {
	XGrabServer(dpy);

	if (lookup(dpy, screen, visualid, property, colormap, replace) &&
	    !replace) {
	    /* Someone has defined the property since we last looked.
	     * Since we will not replace it, release our own resources.
	     * If this is the default map, our allocations will be freed
	     * when this connection closes.
	     */
	    if (colormap->killid == ReleaseByFreeingColormap)
		XFreeColormap(dpy, colormap->colormap);
	}
	else if (retain) {
		XSetCloseDownMode(dpy, RetainPermanent);
	}
	XUngrabServer(dpy);
	XFree((char *) colormap);
	status = 1;
    }

    if (retain)
	XCloseDisplay(dpy);
    XFree((char *) vinfo);
    return status;
}
Esempio n. 19
0
  int main (void)
  {
    int i;
  
    int allocateOK;
  
    ximg = NULL;
  
  	
    d = XOpenDisplay (NULL);
  
    if (!d)
      fputs ("Couldn't open display\n", stderr), exit (1);
  
    screen = DefaultScreen (d);
    gc = DefaultGC (d, screen);
  
    /* Find a visual */
  
    vis.screen = screen;
    vlist = XGetVisualInfo (d, VisualScreenMask, &vis, &match);
  
    if (!vlist)
      fputs ("No matched visuals\n", stderr), exit (1);
  
    vis = vlist[0];
    XFree (vlist);
		
  	// That's not a fair comparison colormap_size is depth in bits!
    // if (vis.colormap_size < COLORS)
      // printf("Colormap is too small: %i.\n",vis.colormap_size); // , exit (1);
		// printf("Colour depth: %i\n",vis.colormap_size);
		// No way this number means nothing!  It is 64 for 16-bit truecolour and 256 for 8-bit!
  
    win = XCreateSimpleWindow (d, DefaultRootWindow (d),
			       0, 0, WIN_W, WIN_H, 0,
			       WhitePixel (d, screen), BlackPixel (d, screen));
  
	  int xclass=get_xvisinfo_class(vis);
		// printf("class = %i\n",xclass);
	  stylee = ( vis.depth > 8 ? styleeTrueColor : styleePrivate );
	  // printf("stylee=%i\n",stylee);
  
    if ( get_xvisinfo_class(vis) % 2 == 1) {	/* The odd numbers can redefine colors */
  
			  // printf("%i\n",get_xvisinfo_class(vis));
	  	
      colormap = DefaultColormap (d, screen);
		  Visual *defaultVisual=DefaultVisual(d,screen);
	  	
      /* Allocate cells */
      allocateOK = (XAllocColorCells (d, colormap, 1,
							      NULL, 0, color, COLORS) != 0);

			printf("Allocated OK? %i\n",allocateOK);
			
      if (allocateOK) {
  
			  // printf("Allocated OK\n");
        // This doesn't work for installed colormap!
  
        /* Modify the colorcells */
        for (i = 0; i < COLORS; i++)
				  xrgb[i].pixel = color[i];
  
        XStoreColors (d, colormap, xrgb, COLORS);
  
		  } else {

			  colormap = XCreateColormap(d,win,defaultVisual,AllocNone);
		  	
    	  // redocolors();
					  	
      }
  
		  // black = XBlackPixel(d,screen);
		  // white = XWhitePixel(d,screen);
  
			XAllocColorCells(d,colormap,1,0,0,color,colors);
			XSetWindowColormap(d,win,colormap);

    } else if ( get_xvisinfo_class(vis) == TrueColor) {
      colormap = DefaultColormap (d, screen);
					  // printf("TrueColor %i = %i\n",xclass,TrueColor);
      /* This will lookup the color and sets the xrgb[i].pixel value */
      // for (i = 0; i < COLORS; i++)
        // XAllocColor (d, colormap, &xrgb[i]);
    } else
      fprintf (stderr, "Not content with visual class %d.\n",
	       get_xvisinfo_class(vis) ), exit (1);
  
    /* Find out if MITSHM is supported and useable */
    printf ("MITSHM: ");
  
    if (XShmQueryVersion (d, &mitshm_major_code,
			  &mitshm_minor_code, &shared_pixmaps)) {
      int (*handler) (Display *, XErrorEvent *);
      ximg = XShmCreateImage (d, vis.visual,
			     vis.depth, XShmPixmapFormat (d),
			     NULL, &shminfo, WIN_W, WIN_H);
      shminfo.shmid = shmget (IPC_PRIVATE,
			      ximg->bytes_per_line * ximg->height,
			      IPC_CREAT | 0777);
      shminfo.shmaddr = (char *)shmat (shminfo.shmid, 0, 0);
		  ximg->data = (char *)shminfo.shmaddr;
  
      handler = XSetErrorHandler (mitshm_handler);
      XShmAttach (d, &shminfo);	/* Tell the server to attach */
      XSync (d, 0);
      XSetErrorHandler (handler);
  
      shmctl (shminfo.shmid, IPC_RMID, 0);
      /* Mark this shm segment for deletion at once. The segment will
       * automatically become released when both the server and this
       * client have detached from it.
       * (Process termination automagically detach shm segments) */
  
      if (!can_use_mitshm) {
        shmdt (shminfo.shmaddr);
        ximg = NULL;
      }
    }
  
    if (ximg == NULL) {
      can_use_mitshm = 0;
      /* XInitImage(ximg); */
      ximg = XCreateImage (d, vis.visual, vis.depth, ZPixmap,
			  0, (char *)malloc (WIN_W * WIN_H), WIN_W, WIN_H, 8, 0);
    }
  
    if (can_use_mitshm)
      printf ("YES!\n");
    else
      printf ("NO, using fallback instead.\n");
  
    // DrawFractal (ximg,xrgb);
  
    XSelectInput (d, win, ButtonPressMask | ExposureMask);
    XMapWindow (d, win);
  
  
  
  
    real_main();


  
      // XNextEvent (d, &ev);
      // switch (ev.type) {
      // case ButtonPress:
        // should_quit = 1;
        // break;
      // case Expose:
        // if (can_use_mitshm)
				  // XShmPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H, True);
        // else
				  // XPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H);
        // break;
      // default:
			  // break;
      // }
  
  
  
    if (get_xvisinfo_class(vis) % 2 == 1 || get_xvisinfo_class(vis) == TrueColor) {
      unsigned long color[COLORS];
  
      if (allocateOK) {
        for (i = 0; i < COLORS; i++)
				  color[i] = xrgb[i].pixel;
        XFreeColors (d, colormap, color, COLORS, 0);
      }				/* Allocated colors freed */
    } else {
      XUninstallColormap (d, colormap);
    }
  
    if (can_use_mitshm) {
      XShmDetach (d, &shminfo);	/* Server detached */
      XDestroyImage (ximg);	/* Image struct freed */
      shmdt (shminfo.shmaddr);	/* We're detached */
    } else
      XDestroyImage (ximg);	/* Image struct freed */
  
    XDestroyWindow (d, win);	/* Window removed */
    XCloseDisplay (d);		/* Display disconnected */
  
    /* So you can see how your computer compares to your friend's */
    getrusage (RUSAGE_SELF, &resource_utilization);
		float seconds=(float)resource_utilization.ru_utime.tv_sec
						     +(float)resource_utilization.ru_utime.tv_usec*0.000000001;
		printf("CPU seconds per frame: %f\n",seconds/(float)frameno);
    // printf ("CPU seconds consumed: %ds and %dµs\n",
	    // (int) resource_utilization.ru_utime.tv_sec,
	    // (int) resource_utilization.ru_utime.tv_usec);
  
    return 0;
  }
Esempio n. 20
0
static void
setup(void)
{
	int x, y;
	XSetWindowAttributes swa;
	XIM xim;
#ifdef XINERAMA
	XineramaScreenInfo *info;
	Window w, pw, dw, *dws;
	XWindowAttributes wa;
	int a, j, di, n, i = 0, area = 0;
	unsigned int du;
#endif

	/* init appearance */
	scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
	scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
	scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
	scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
	scheme[SchemeOut].bg = drw_clr_create(drw, outbgcolor);
	scheme[SchemeOut].fg = drw_clr_create(drw, outfgcolor);

	clip = XInternAtom(dpy, "CLIPBOARD",   False);
	utf8 = XInternAtom(dpy, "UTF8_STRING", False);

	/* calculate menu geometry */
	bh = drw->fonts[0]->h + 2;
	lines = MAX(lines, 0);
	mh = (lines + 1) * bh;
#ifdef XINERAMA
	if ((info = XineramaQueryScreens(dpy, &n))) {
		XGetInputFocus(dpy, &w, &di);
		if (mon != -1 && mon < n)
			i = mon;
		else if (w != root && w != PointerRoot && w != None) {
			/* find top-level window containing current input focus */
			do {
				if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
					XFree(dws);
			} while (w != root && w != pw);
			/* find xinerama screen with which the window intersects most */
			if (XGetWindowAttributes(dpy, pw, &wa))
				for (j = 0; j < n; j++)
					if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
						area = a;
						i = j;
					}
		}
		/* no focused window is on screen, so use pointer location instead */
		if (mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
			for (i = 0; i < n; i++)
				if (INTERSECT(x, y, 1, 1, info[i]))
					break;

		x = info[i].x_org;
		y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
		mw = info[i].width;
		XFree(info);
	} else
#endif
	{
		x = 0;
		y = topbar ? 0 : sh - mh;
		mw = sw;
	}
	promptw = (prompt && *prompt) ? TEXTW(prompt) : 0;
	inputw = MIN(inputw, mw/3);
	fuzzymatch();

	/* create menu window */
	swa.override_redirect = True;
	swa.background_pixel = scheme[SchemeNorm].bg->pix;
	swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
	win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
	                    DefaultDepth(dpy, screen), CopyFromParent,
	                    DefaultVisual(dpy, screen),
	                    CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);

	/* open input methods */
	xim = XOpenIM(dpy, NULL, NULL, NULL);
	xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
	                XNClientWindow, win, XNFocusWindow, win, NULL);

	XMapRaised(dpy, win);
	drw_resize(drw, mw, mh);
	drawmenu();
}
Esempio n. 21
0
ImageDraw::operator Image() const
{
	GuiLock __;
	XImage *xim = XGetImage(Xdisplay, dw, 0, 0, max(size.cx, 1), max(size.cy, 1), AllPlanes, ZPixmap);
	if(!xim)
		return Null;
	Visual *v = DefaultVisual(Xdisplay, Xscreenno);
	RasterFormat fmt;

	RGBA   palette[256];

	switch(xim->depth) {
	case 15:
	case 16:
		if(xim->byte_order == LSBFirst)
			fmt.Set16le(v->red_mask, v->green_mask, v->blue_mask);
		else
			fmt.Set16be(v->red_mask, v->green_mask, v->blue_mask);
		break;
	case 8: {
		int n = min(v->map_entries, 256);
		XColor colors[256];
		for(int i = 0; i < 256; i++) {
			colors[i].pixel = i;
			colors[i].flags = DoRed|DoGreen|DoBlue;
		}
		XQueryColors(Xdisplay, Xcolormap, colors, n);
		XColor *s = colors;
		XColor *e = s + n;
		while(s < e) {
			RGBA& t = palette[s->pixel];
			t.r = s->red >> 8;
			t.g = s->green >> 8;
			t.b = s->blue >> 8;
			t.a = 255;
			s++;
		}
		fmt.Set8();
		break;
	}
	default:
		if(xim->bits_per_pixel == 32)
			if(xim->byte_order == LSBFirst)
				fmt.Set32le(v->red_mask, v->green_mask, v->blue_mask);
			else
				fmt.Set32be(v->red_mask, v->green_mask, v->blue_mask);
		else
			if(xim->byte_order == LSBFirst)
				fmt.Set24le(v->red_mask, v->green_mask, v->blue_mask);
			else
				fmt.Set24be(v->red_mask, v->green_mask, v->blue_mask);
		break;
	}

	ImageBuffer ib(size);
	const byte *s = (const byte *)xim->data;
	RGBA *t = ib;
	for(int y = 0; y < size.cy; y++) {
		fmt.Read(t, s, size.cx, palette);
		s += xim->bytes_per_line;
		t += size.cx;
	}
	XDestroyImage(xim);
	if(has_alpha) {
		xim = XGetImage(Xdisplay, alpha.dw, 0, 0, max(size.cx, 1), max(size.cy, 1), AllPlanes, ZPixmap);
		if(xim) {
			const byte *s = (const byte *)xim->data;
			t = ib;
			Buffer<RGBA> line(size.cx);
			for(int y = 0; y < size.cy; y++) {
				fmt.Read(line, s, size.cx, palette);
				for(int x = 0; x < size.cx; x++)
					(t++)->a = line[x].r;
				s += xim->bytes_per_line;
			}
			XDestroyImage(xim);
		}
	}
	Premultiply(ib);
	return ib;
}
Esempio n. 22
0
XImage *xNewImage (Display *dpy         /* display pointer */, 
		   unsigned long pmin   /* minimum pixel value (corresponding to byte=0) */, 
		   unsigned long pmax   /* maximum pixel value (corresponding to byte=255) */,
		   int width            /* number of bytes in x dimension */, 
		   int height           /* number of bytes in y dimension */, 
		   float blank          /* portion for blanking (0 to 1) */, 
		   unsigned char *bytes /* unsigned bytes to be mapped to an image */)
/*< make a new image of pixels from bytes >*/
/******************************************************************************
Author:		Dave Hale, Colorado School of Mines, 06/08/90
*****************************************************************************/
{
	int scr=DefaultScreen(dpy);
	int i,j,k,line,iline,jline,widthpad;
	float base,scale;
	unsigned long map[256],bkgnd;
	unsigned char *data;
	int byte_perpixel;
	unsigned int depth;
	XImage *xim;
	
	xim=(XImage *) NULL;

	depth=(unsigned int)DefaultDepth(dpy,scr);	
	byte_perpixel=4;
	if(depth<=8) byte_perpixel=1;
	else if(depth<=16) byte_perpixel=2;

/*	else if(depth<=24) byte_perpixel=3;*/



	/* build map for translating bytes to pixels */
	base = ((double) pmin)+0.499;
	scale = ((double) (pmax-pmin))/255.0;
	for (i=0; i<=255; ++i){
		map[i] = base+i*scale;
	}

	/* blanking */
	bkgnd = (unsigned long) WhitePixel(dpy,scr);
	j = SF_MAX(0,SF_MIN(256,(int)(256*blank)));
	for (i = 0; i < j; i++)
		map[255-i] = bkgnd;

	/* allocate memory for image data */
	widthpad = (1+(width-1)/(BitmapPad(dpy)/8))*BitmapPad(dpy)/8;
	data = (unsigned char*) sf_alloc(widthpad*height,byte_perpixel);

	xim=XCreateImage(	(Display *) dpy,
				(Visual *) DefaultVisual(dpy,scr),
				(unsigned int) DefaultDepth(dpy,scr),
				(int) ZPixmap,
				(int) 0,
				(char *) data,
				(unsigned int) widthpad,
				(unsigned int) height,
/*				(int) BitmapPad(dpy),
				(int) widthpad*byte_perpixel
*/
				8,0);
	byte_perpixel=xim->bits_per_pixel/8;
/*	fprintf(stderr,"\nbyte_perpixel = %d, depth= %d\n", byte_perpixel,depth); */

	/* translate bytes to pixels, padding scanlines as necessary */
	for (line=0; line<height; line++) {
		iline = line*width;
		jline = line*widthpad;
		for (i=iline,j=jline,k=0; k<width; ++i,++j,++k)
		{       if(byte_perpixel==1)
			((unsigned char *)data)[j] =(unsigned char)map[bytes[i]];
			if(byte_perpixel==2)
			  {
			    int edn=xim->byte_order;
			    if(edn==LSBFirst){
			      ((unsigned char *)data)[j*2+0] =(unsigned char)(truecolor_pixel[bytes[i]]);
			      ((unsigned char *)data)[j*2+1] =(unsigned char)(truecolor_pixel[bytes[i]]>>8);
			    }else{
			      ((unsigned char *)data)[j*2+0] =(unsigned char)(truecolor_pixel[bytes[i]]>>24); 
			      ((unsigned char *)data)[j*2+1] =(unsigned char)(truecolor_pixel[bytes[i]]>>16);
			      }

			    /*((unsigned short *)data)[j] =(unsigned short)(truecolor_pixel[bytes[i]]);*/
			  }	
Esempio n. 23
0
void xskin_start_interface( int pipe_in ) {

  int xskin_sc;
  XEvent xskin_e;
  XSetWindowAttributes xskin_attr;

  XSizeHints xskin_hint;
  XClassHint xskin_chint;
  XTextProperty ct;
  char *namlist[2];


  /* setup window */

  xskin_d     = XOpenDisplay( NULL );
  xskin_sc    = DefaultScreen( xskin_d );
  xskin_r     = RootWindow( xskin_d, xskin_sc );
  xskin_gc    = DefaultGC( xskin_d, xskin_sc );
  xskin_vis   = DefaultVisual( xskin_d, xskin_sc );
  xskin_depth = DefaultDepth( xskin_d, xskin_sc );

  xskin_w = XCreateSimpleWindow( xskin_d, xskin_r, 0, 0,
				 skin_width, skin_height, 0,
				 WhitePixel( xskin_d, xskin_sc ),
				 BlackPixel( xskin_d, xskin_sc ) );

  xskin_attr.backing_store = True;
  xskin_attr.override_redirect = False;
  XChangeWindowAttributes( xskin_d, xskin_w,
			   CWBackingStore|CWOverrideRedirect, &xskin_attr );

  XSelectInput( xskin_d, xskin_w,
		KeyPressMask|ExposureMask|
		EnterWindowMask|LeaveWindowMask|
		ButtonPressMask|ButtonReleaseMask|
		Button1MotionMask );

  xskin_hint.flags = USSize | PMinSize | PMaxSize | USPosition;
  xskin_hint.width = xskin_hint.min_width = xskin_hint.max_width
    = skin_width;
  xskin_hint.height = xskin_hint.min_height = xskin_hint.max_height
    = skin_height;
  XSetNormalHints( xskin_d, xskin_w, &xskin_hint );

  xskin_chint.res_name  = XSKIN_RES_NAME;
  xskin_chint.res_class = XSKIN_RES_CLASS;
  XSetClassHint( xskin_d, xskin_w, &xskin_chint );

  namlist[0]=(char *)safe_malloc(strlen(XSKIN_WINDOW_NAME)+1);
  strcpy( namlist[0], XSKIN_WINDOW_NAME );
  XmbTextListToTextProperty( xskin_d, namlist, 1, XCompoundTextStyle, &ct );
  XSetWMName( xskin_d, xskin_w, &ct );
  XSetWMIconName( xskin_d, xskin_w, &ct );
  free(namlist[0]);


  /* setup pixmaps */

  if ( load_skins()!=0 ) goto finish;

  XSetWindowBackgroundPixmap( xskin_d, xskin_w, xskin_back );
  XClearWindow( xskin_d, xskin_w );

  XMapWindow( xskin_d, xskin_w );
  while( 1 ) {
    XNextEvent( xskin_d, &xskin_e );
    if ( xskin_e.type == Expose ) break; 
  }

  fshuf=0;
  frep=0;
  fequ=1;
  fpll=1;
  fplay=0;
  fpause=0;
  fremain=0;
  play_val=1;
  vol_val=50;
  last_current_time=0;
  total_time=0;
  speana_buf = NULL;
  strcpy( last_text, "welcome to timidity" );

  install_sighandler();

  repaint();
  ts_spectrum( -1, speana_buf );

  XFlush(xskin_d);

  xskin_jobs( pipe_in );   /* tskin main jobs */

finish:
  signal_vector(0);  /* finish */
}
Esempio n. 24
0
	int32_t run(Filesystem* fs, ConfigSettings* cs)
	{
		// Create main window
		XInitThreads();
		XSetErrorHandler(x11_error_handler);
		m_x11_display = XOpenDisplay(NULL);

		CE_ASSERT(m_x11_display != NULL, "Unable to open X11 display");

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

		m_x11_parent_window = (m_parent_window_handle == 0) ? RootWindow(m_x11_display, screen) :
			(Window) m_parent_window_handle;

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

		m_x11_window = XCreateWindow(m_x11_display,
			m_x11_parent_window,
			0, 0,
			cs->window_width,
			cs->window_height,
			0,
			depth,
			InputOutput,
			visual,
			CWBorderPixel | CWEventMask,
			&win_attribs
		);
		CE_ASSERT(m_x11_window != None, "Unable to create X window");

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

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

		colormap = XDefaultColormap(m_x11_display, screen);
		XAllocNamedColor(m_x11_display, colormap, "black", &black, &dummy);
		bm_no = XCreateBitmapFromData(m_x11_display, m_x11_window, no_data, 8, 8);
		m_x11_hidden_cursor = XCreatePixmapCursor(m_x11_display, bm_no, bm_no, &black, &black, 0, 0);

		m_wm_delete_message = XInternAtom(m_x11_display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(m_x11_display, m_x11_window, &m_wm_delete_message, 1);

		oswindow_set_window(m_x11_display, m_x11_window);
		bgfx::x11SetDisplayWindow(m_x11_display, m_x11_window);
		XMapRaised(m_x11_display, m_x11_window);

		// Get screen configuration
		m_screen_config = XRRGetScreenInfo(m_x11_display, RootWindow(m_x11_display, screen));

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

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

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

		while (!s_exit)
		{
			pump_events();
		}

		main_thread.stop();

		// Restore previous screen configuration if changed
		Rotation rr_cur_rot;
		const SizeID rr_cur_sizeid = XRRConfigCurrentConfiguration(m_screen_config, &rr_cur_rot);

		if (rr_cur_rot != rr_old_rot || rr_cur_sizeid != rr_old_sizeid)
		{
			XRRSetScreenConfig(m_x11_display,
				m_screen_config,
				RootWindow(m_x11_display, screen),
				rr_old_sizeid,
				rr_old_rot,
				CurrentTime);
		}
		XRRFreeScreenConfigInfo(m_screen_config);

		XDestroyWindow(m_x11_display, m_x11_window);
		XCloseDisplay(m_x11_display);
		return EXIT_SUCCESS;
	}
Esempio n. 25
0
Visual * QXlibScreen::defaultVisual() const
{
    return DefaultVisual(display()->nativeDisplay(), xScreenNumber());
}
Esempio n. 26
0
void CGX_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
{
#if 0
	SDL_Surface *sicon;
	XWMHints *wmhints;
	XImage *icon_image;
	Pixmap icon_pixmap;
	Pixmap mask_pixmap;
#ifdef USE_ICON_WINDOW
	Window icon_window;
#endif
	GC GC;
	XGCValues GCvalues;
	int i, b, dbpp;
	SDL_Rect bounds;
	Uint8 *LSBmask, *color_tried;
	Visual *dvis;

	/* Lock the event thread, in multi-threading environments */
	SDL_Lock_EventThread();

	/* The icon must use the default visual, depth and colormap of the
	   screen, so it might need a conversion */
	dbpp = DefaultDepth(SDL_Display, SDL_Screen);
	switch(dbpp) {
	case 15:
	    dbpp = 16; break;
	case 24:
	    dbpp = 32; break;
	}
	dvis = DefaultVisual(SDL_Display, SDL_Screen);

	/* The Visual struct is supposed to be opaque but we cheat a little */
	sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
				     dbpp,
				     dvis->red_mask, dvis->green_mask,
				     dvis->blue_mask, 0);

	if ( sicon == NULL ) {
		goto done;
	}
	/* If we already have allocated colours from the default colormap,
	   copy them */
	if(SDL_Visual == dvis && SDL_XColorMap == SDL_DisplayColormap
	   && this->screen->format->palette && sicon->format->palette) {
	    memcpy(sicon->format->palette->colors,
		   this->screen->format->palette->colors,
		   this->screen->format->palette->ncolors * sizeof(SDL_Color));
	}

	bounds.x = 0;
	bounds.y = 0;
	bounds.w = icon->w;
	bounds.h = icon->h;
	if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 )
		goto done;

	/* Lock down the colors used in the colormap */
	color_tried = NULL;
	if ( sicon->format->BitsPerPixel == 8 ) {
		SDL_Palette *palette;
		Uint8 *p;
		XColor wanted;

		palette = sicon->format->palette;
		color_tried = malloc(palette->ncolors);
		if ( color_tried == NULL ) {
			goto done;
		}
		if ( SDL_iconcolors != NULL ) {
			free(SDL_iconcolors);
		}
		SDL_iconcolors = malloc(palette->ncolors
					* sizeof(*SDL_iconcolors));
		if ( SDL_iconcolors == NULL ) {
			free(color_tried);
			goto done;
		}
		memset(color_tried, 0, palette->ncolors);
		memset(SDL_iconcolors, 0,
		       palette->ncolors * sizeof(*SDL_iconcolors));

		p = (Uint8 *)sicon->pixels; 
		for ( i = sicon->w*sicon->h; i > 0; --i, ++p ) {
			if ( ! color_tried[*p] ) {
				wanted.pixel = *p;
				wanted.red   = (palette->colors[*p].r<<8);
				wanted.green = (palette->colors[*p].g<<8);
				wanted.blue  = (palette->colors[*p].b<<8);
				wanted.flags = (DoRed|DoGreen|DoBlue);
				if (XAllocColor(SDL_Display,
						SDL_DisplayColormap, &wanted)) {
					++SDL_iconcolors[wanted.pixel];
				}
				color_tried[*p] = 1;
			}
		}
	}
	if ( color_tried != NULL ) {
		free(color_tried);
	}

	/* Translate mask data to LSB order and set the icon mask */
	i = (sicon->w/8)*sicon->h;
	LSBmask = (Uint8 *)malloc(i);
	if ( LSBmask == NULL ) {
		goto done;
	}
	memset(LSBmask, 0, i);
	while ( --i >= 0 ) {
		for ( b=0; b<8; ++b )
			LSBmask[i] |= (((mask[i]>>b)&0x01)<<(7-b));
	}
	mask_pixmap = XCreatePixmapFromBitmapData(SDL_Display, WMwindow,
					LSBmask, sicon->w, sicon->h, 1L, 0L, 1);

	/* Transfer the image to an X11 pixmap */
	icon_image = XCreateImage(SDL_Display,
			DefaultVisual(SDL_Display, SDL_Screen),
			DefaultDepth(SDL_Display, SDL_Screen),
			ZPixmap, 0, (char *)sicon->pixels, sicon->w, sicon->h,
			((sicon->format)->BytesPerPixel == 3) ? 32 :
				(sicon->format)->BytesPerPixel*8, 0);
	icon_pixmap = XCreatePixmap(SDL_Display, SDL_Root, sicon->w, sicon->h,
			DefaultDepth(SDL_Display, SDL_Screen));
	GC = XCreateGC(SDL_Display, icon_pixmap, 0, &GCvalues);
	XPutImage(SDL_Display, icon_pixmap, GC, icon_image,
					0, 0, 0, 0, sicon->w, sicon->h);
	XFreeGC(SDL_Display, GC);
	XDestroyImage(icon_image);
	free(LSBmask);
	sicon->pixels = NULL;

#ifdef USE_ICON_WINDOW
	/* Create an icon window and set the pixmap as its background */
	icon_window = XCreateSimpleWindow(SDL_Display, SDL_Root,
					0, 0, sicon->w, sicon->h, 0,
					CopyFromParent, CopyFromParent);
	XSetWindowBackgroundPixmap(SDL_Display, icon_window, icon_pixmap);
	XClearWindow(SDL_Display, icon_window);
#endif

	/* Set the window icon to the icon pixmap (and icon window) */
	wmhints = XAllocWMHints();
	wmhints->flags = (IconPixmapHint | IconMaskHint);
	wmhints->icon_pixmap = icon_pixmap;
	wmhints->icon_mask = mask_pixmap;
#ifdef USE_ICON_WINDOW
	wmhints->flags |= IconWindowHint;
	wmhints->icon_window = icon_window;
#endif
	XSetWMHints(SDL_Display, WMwindow, wmhints);
	XFree(wmhints);
	XSync(SDL_Display, False);

  done:
	SDL_Unlock_EventThread();
	if ( sicon != NULL ) {
		SDL_FreeSurface(sicon);
	}
#endif
	return;
}
Esempio n. 27
0
void textbox_draw(textbox *tb)
{
	int i;
	XGlyphInfo extents;

	GC context    = XCreateGC(display, tb->window, 0, 0);
	Pixmap canvas = XCreatePixmap(display, tb->window, tb->w, tb->h, DefaultDepth(display, screen_id));
	XftDraw *draw = XftDrawCreate(display, canvas, DefaultVisual(display, screen_id), DefaultColormap(display, screen_id));

	// clear canvas
	XftDrawRect(draw, &tb->color_bg, 0, 0, tb->w, tb->h);

	char *line   = tb->text,
		*text   = tb->text ? tb->text: "",
		*prompt = tb->prompt ? tb->prompt: "";

	int text_len    = strlen(text);
	int length      = text_len;
	int line_height = tb->font->ascent + tb->font->descent;
	int line_width  = 0;

	int cursor_x      = 0;
	int cursor_offset = 0;
	int cursor_width  = MAX(2, line_height/10);

	if (tb->flags & TB_EDITABLE)
	{
		int prompt_len = strlen(prompt);
		length = text_len + prompt_len;
		cursor_offset = MIN(tb->cursor + prompt_len, length);

		line = alloca(length + 10);
		sprintf(line, "%s%s", prompt, text);

		// replace spaces so XftTextExtents8 includes their width
		for (i = 0; i < length; i++) if (isspace(line[i])) line[i] = '_';

		// calc cursor position
		XftTextExtents8(display, tb->font, (unsigned char*)line, cursor_offset, &extents);
		cursor_x = extents.width;

		// restore correct text string with spaces
		sprintf(line, "%s%s", prompt, text);
	}

	// calc full input text width
	XftTextExtents8(display, tb->font, (unsigned char*)line, length, &extents);
	line_width = extents.width;

	int x = 0, y = tb->font->ascent;
	if (tb->flags & TB_RIGHT)  x = tb->w - line_width;
	if (tb->flags & TB_CENTER) x = (tb->w - line_width) / 2;

	// draw the text, including any prompt in edit mode
	XftDrawString8(draw, &tb->color_fg, tb->font, x, y, (unsigned char*)line, length);

	// draw the cursor
	if (tb->flags & TB_EDITABLE)
		XftDrawRect(draw, &tb->color_fg, cursor_x, 2, cursor_width, line_height-4);

	// flip canvas to window
	XCopyArea(display, canvas, tb->window, context, 0, 0, tb->w, tb->h, 0, 0);

	XFreeGC(display, context);
	XftDrawDestroy(draw);
	XFreePixmap(display, canvas);
}
Esempio n. 28
0
void
initSpace(Window window)
{
	Display    *display = dsp;
	XWindowAttributes xwa;


	(void) XGetWindowAttributes(dsp, window, &xwa);
	int         n;
	XVisualInfo *wantVis, vTemplate;
	int  VisualClassWanted=-1;

	vTemplate.screen = screen;
	vTemplate.depth = xwa.depth;

	if (VisualClassWanted == -1) {
	  vTemplate.c_class = DefaultVisual(display, screen)->c_class;
	} else {
	  vTemplate.c_class = VisualClassWanted;
	}

	wantVis = XGetVisualInfo(display,
				 VisualScreenMask | VisualDepthMask | VisualClassMask,
				 &vTemplate, &n);

	if (VisualClassWanted != -1 && n == 0) {
	  /* Wanted visual not found so use default */

	  vTemplate.c_class = DefaultVisual(display, screen)->c_class;

	  wantVis = XGetVisualInfo(display,
				   VisualScreenMask | VisualDepthMask | VisualClassMask,
				   &vTemplate, &n);
	}
	/* if User asked for color, try that first, then try mono */
	/* if User asked for mono.  Might fail on 16/24 bit displays,
	   so fall back on color, but keep the mono "look & feel". */

	if (!getVisual(wantVis, n)) {
	  if (!getVisual(wantVis, n)) {
	    kdError() << i18n("GL can not render with root visual\n") << endl;
	    return;
	  }
	}

	/* PURIFY 3.0a on SunOS4 reports a 104 byte memory leak on the next line each
	 * time that morph3d mode is run in random mode. */

	glx_context = glXCreateContext(display, wantVis, 0, True);

	XFree((char *) wantVis);


	glXMakeCurrent(display, window, glx_context);
	glDrawBuffer(GL_FRONT);

	if (mono) {
	  glIndexi(WhitePixel(display, screen));
	  glClearIndex(BlackPixel(display, screen));
	}

	retqshape(xwa.width, xwa.height);
	Init();
}
Esempio n. 29
0
File: xdemo.c Progetto: cuzz/xrdp
int drawBMP(char *filename, int scroll_type)
{
    struct   pic_info pic_info;
    XImage   *image;
    Visual   *visual;
    Pixmap   pixmap;
    int      depth;
    int      i;
    int      j;

    if (parse_bmp(filename, &pic_info) < 0) {
        exit(-1);
    }
    XClearArea(g_disp, g_win, 0, 0, g_winWidth, g_winHeight, 0);

    depth = DefaultDepth(g_disp, DefaultScreen(g_disp));
    visual = DefaultVisual(g_disp, DefaultScreen(g_disp));

    // create empty pixmap
    pixmap = XCreatePixmap(g_disp, g_win, pic_info.width, pic_info.height, depth);

    // create an image from pixel data
    image = XCreateImage(g_disp, visual, depth, ZPixmap, 0, pic_info.pixel_data,
                         pic_info.width, pic_info.height, 32, 0);

    if (pic_info.height <= g_winHeight) {
        // image is too small to scroll
        XFlush(g_disp);
        XPutImage(g_disp, g_win, g_gc, image, 0, 0, 0, 0, pic_info.width, pic_info.height);
        XFlush(g_disp);
        return 0;
    }

    // copy image to pixelmap
    XPutImage(g_disp, pixmap, g_gc, image, 0, 0, 0, 0, pic_info.width, pic_info.height);

    if (scroll_type == SCROLL_JUMP) {

        if (pic_info.height <= g_winHeight) {
            // image too small - no scrolling required
            XFlush(g_disp);
            XCopyArea(g_disp,           // connection to X server
                      pixmap,           // source drawable
                      g_win,            // dest drawable
                      g_gc,             // graphics context
                      0, 0,             // source x,y
                      pic_info.width,   // width
                      pic_info.height,  // height
                      0, 0);            // dest x,y
            XFlush(g_disp);
            return 0;
        }

        j = pic_info.height / g_winHeight;
        if (pic_info.height % g_winHeight != 0) {
            // need to include the last part of the image
            j++;
        }
        XFlush(g_disp);
        for (i = 0; i < j; i++)
        {
            XCopyArea(g_disp,               // connection to X server
                      pixmap,               // source drawable
                      g_win,                // dest drawable
                      g_gc,                 // graphics context
                      0, i * g_winHeight,   // source x,y
                      pic_info.width,       // width
                      pic_info.height,      // height
                      0, 0);                // dest x,y
            XFlush(g_disp);
            sleep(3);
        }
    }

    /*
    ** smooth scroll the image
    */

    // number of lines to be scrolled
    j = pic_info.height - g_winHeight;

    if (scroll_type == SCROLL_SMOOTH1) {
        printf("running SCROLL_SMOOTH1\n");
        XFlush(g_disp);
        XPutImage(g_disp, g_win, g_gc, image, 0, 0, 0, 0, pic_info.width, pic_info.height);
        XFlush(g_disp);
        usleep(10000);
        for (i = 0; i < j; i++)
        {
            XCopyArea(g_disp, g_win, g_win, g_gc, 0, 1, g_winWidth, g_winHeight - 1, 0, 0);
            XPutImage(g_disp, g_win, g_gc, image, 0, g_winHeight + i, 0, g_winHeight -1 , pic_info.width, 1);
            XFlush(g_disp);
            usleep(10000);
        }
        return 0;
    }

    if (scroll_type == SCROLL_SMOOTH2) {
        printf("running SCROLL_SMOOTH2\n");
        XFlush(g_disp);
        for (i = 0; i < j; i++)
        {
            XPutImage(g_disp, g_win, g_gc, image, 0, i, 0, 0, pic_info.width, pic_info.height - i);
            XFlush(g_disp);
            usleep(10000);
        }
    }
    if (scroll_type == SCROLL_SMOOTH3) {
        printf("running SCROLL_SMOOTH3\n");
        XFlush(g_disp);
        XCopyArea(g_disp, pixmap, g_win, g_gc, 0, 0, pic_info.width, pic_info.height, 0, 0);
        XFlush(g_disp);
        usleep(10000);
        for (i = 0; i < j; i++)
        {
            XCopyArea(g_disp, g_win, g_win, g_gc, 0, 1, g_winWidth, g_winHeight - 1, 0, 0);
            XCopyArea(g_disp, pixmap, g_win, g_gc, 0, g_winHeight + i, pic_info.width, 1, 0, g_winHeight -1);
            XFlush(g_disp);
            usleep(10000);
        }
        return 0;
    }

    if (scroll_type == SCROLL_SMOOTH4) {
        printf("running SCROLL_SMOOTH4\n");
        XFlush(g_disp);
        for (i = 0; i < j; i++)
        {
            XCopyArea(g_disp, pixmap, g_win, g_gc, 0, i, pic_info.width, pic_info.height - i, 0, 0);
            XFlush(g_disp);
            usleep(10000);
        }
    }

    return 0;
}
Esempio n. 30
0
Window mume_x11_create_window(
    Display *display, int type, Window parent,
    int x, int y, unsigned int width, unsigned int height,
    unsigned int clazz, int eventmask)
{
    int screen;
    int depth;
    Visual *visual;
    unsigned long valuemask;
    XSetWindowAttributes attributes;
    XSizeHints *size_hints;
    XWMHints *wm_hints;
    XClassHint *class_hints;
    Window window;

    screen = DefaultScreen(display);
    visual = DefaultVisual(display, screen);

    if (clazz != InputOnly) {
        depth = DefaultDepth(display, screen);
        valuemask = CWBackPixel | CWBorderPixel;
        attributes.background_pixel = WhitePixel(display, screen);
        attributes.border_pixel = BlackPixel(display, screen);

        if (MUME_BACKWIN_MENU == type) {
            assert(RootWindow(display, screen) == parent);

            valuemask |= CWSaveUnder | CWOverrideRedirect;
            attributes.save_under = True;
            attributes.override_redirect = True;
        }
    }
    else {
        depth = 0;
        valuemask = 0;
    }

    if (None == parent)
        parent = RootWindow(display, screen);

    window = XCreateWindow(
        display, parent, x, y, width, height, 0, depth,
        clazz, visual, valuemask, &attributes);

    if (clazz != InputOnly) {
        /* Setup standard properties. */
        if (!(size_hints = XAllocSizeHints()))
            mume_abort(("allocating memory failed!\n"));

        if (!(wm_hints = XAllocWMHints()))
            mume_abort(("allocating memory failed!\n"));

        if (!(class_hints = XAllocClassHint()))
            mume_abort(("allocating memory failed!\n"));

        size_hints->flags = PPosition | PSize | PMinSize;
        size_hints->min_width = 0;
        size_hints->min_height = 0;
        wm_hints->initial_state = NormalState;
        wm_hints->input = True;
        /* wm_hints->icon_pixmap = icon_pixmap; */
        wm_hints->flags = StateHint/* | IconPixmapHint*/ | InputHint;
        class_hints->res_name = "mume";
        class_hints->res_class = "mume";

        /* or use XSizeHints, XSetClassHint, XSetWMHints */
        XmbSetWMProperties(display, window, "mume", "mume",
                           NULL, 0, size_hints, wm_hints, class_hints);

        XFree(wm_hints);
        XFree(class_hints);
        XFree(size_hints);
    }

    /* Select event */
    XSelectInput(display, window, eventmask);

    return window;
}