Exemplo n.º 1
0
int main(int argc, char *argv[]){
	FILE *fp;
	char buff[1000];
	int ch, i, j, x, y;
	int line_count = 0;

	count = -1;
	count_intersect = 0;
	k = 0;
	
	fp = fopen(argv[1], "r");

	if (fp == NULL){
		printf("There's no input file.\n");
		exit(0);
	}
	else{
		if( (display = XOpenDisplay(display_name)) == NULL ){ 
			printf("Could not open display. \n"); 
			exit(-1);
		}
		printf("Connected to X server  %s\n", XDisplayName(display_name) );
		
		screen_num = DefaultScreen(display);
		screen = DefaultScreenOfDisplay(display);
		colormap = XDefaultColormap(display, screen_num);
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);

		//obtaining line count
		while(!feof(fp)){
			ch = fgetc(fp);
			if (ch == '\n'){
				line_count++;
			}
		}
		rewind(fp);
	}

	//int m[line_count][6];
	int m[line_count+1][6];

	//Creating window
	border_width = 10;
	win_x = 0; win_y = 0;
	win_width = display_width/2;
	win_height = display_height * 0.8;
	//win_height = (int)(win_width/1.7); //rectangular window

	printf("window width: %d\n window height: %d\n", display_width, display_height);

	//win = XCreateSimpleWindow(display, RootWindow(display, 0), 1, 1, win_width, win_height, 10, WhitePixel (display, 0), WhitePixel (display, 0));
	win = XCreateSimpleWindow(display, RootWindow(display, screen_num), 
		win_x, win_y, win_width, win_height, border_width,
		BlackPixel(display, screen_num), WhitePixel(display, screen_num));
	

	//Maps window on screen
	size_hints = XAllocSizeHints();
	wm_hints = XAllocWMHints();
	class_hints = XAllocClassHint();
	if (size_hints == NULL || wm_hints == NULL || class_hints == NULL){
		printf("Error allocating memory for hints\n");
		exit(-1);
	}

	size_hints -> flags = PPosition | PSize | PMinSize;
	size_hints -> min_width = 60;
	size_hints -> min_height = 60;

	XStringListToTextProperty(&win_name_string, 1, &win_name);
	XStringListToTextProperty(&icon_name_string, 1, &icon_name);

	wm_hints -> flags = StateHint | InputHint;
	wm_hints -> initial_state = NormalState;
	wm_hints -> input = False;

	class_hints -> res_name = "x_use_example";
	class_hints -> res_class = "homework1";
	
	XSetWMProperties(display, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints );
	XSelectInput(display, win, ExposureMask | KeyPressMask | ButtonPressMask);

	// put on screen
	XMapWindow(display, win);
	XFlush(display);

	//graphics setup
	green_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, green, &green_col);
	if (XAllocColor(display, colormap, &green_col) == 0){
		printf("Failed to get color green\n");
		exit(-1);
	}
	else{
		printf("Success green!\n");
		XSetForeground(display, green_gc, green_col.pixel);

	}

	red_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, red, &red_col);
	if (XAllocColor(display, colormap, &red_col) == 0){
		printf("Failed to get color red\n");
		exit(-1);
	}
	else{
		printf("Success red!\n");
		XSetForeground(display, red_gc, red_col.pixel);
	}


	black_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, black, &black_col);
	if (XAllocColor(display, colormap, &black_col) == 0){
		printf("Failed to get color black\n");
		exit(-1);
	}
	else{
		printf("Success black!\n");
		XSetForeground(display, black_gc, black_col.pixel);
	}


	light_purple_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, light_purple, &light_purple_col);
	if (XAllocColor(display, colormap, &light_purple_col) == 0){
		printf("Failed to get color light purple\n");
		exit(-1);
	}
	else{
		printf("Success light purple!\n");
		XSetForeground(display, light_purple_gc, light_purple_col.pixel);
	}


	white_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, white, &white_col);	
	if (XAllocColor(display, colormap, &white_col) == 0){
		printf("Failed to get color white\n");
		exit(-1);
	}
	else{
		printf("Success white!\n");
		XSetForeground(display, white_gc, white_col.pixel);	
	}
	

	
	while(1){
		XNextEvent(display, &report);
		switch(report.type){
			case Expose:
			{	
				
				for (i = 0; i <= line_count; i++){
					fscanf(fp, "%*s ( %d, %d) ( %d, %d) (%d, %d)", &m[i][0], &m[i][1], &m[i][2], &m[i][3], &m[i][4], &m[i][5]);
				}

				m[line_count+1][0] = -5;

				for (i = 0; i <= line_count ; i++){
					for (j=0; j<6; j+=2){
						m[i][j] = m[i][j] + 100;
						m[i][j+1] = m[i][j+1] + 100;
					}
				}

				for (i = 0; i <=line_count; i++){
					//Draw the triangles
					XDrawLine(display, win, green_gc, m[i][0], m[i][1], m[i][2], m[i][3]);
					XDrawLine(display, win, green_gc, m[i][2], m[i][3], m[i][4], m[i][5]);
					XDrawLine(display, win, green_gc, m[i][4], m[i][5], m[i][0], m[i][1]);
				}

				rewind(fp);

				if (valid_vertex[0][0] != 0.0){
					for (i= 0; i<k; i++){
						if  (valid_vertex[i][6] == 0.0 || valid_vertex[i][6] == -4.0){
							printf("from (%d, %d) to (%d, %d) length: %f and path length: %f\n", (int)valid_vertex[i][0], (int)valid_vertex[i][1], (int)valid_vertex[i][2], (int)valid_vertex[i][3], valid_vertex[i][4], valid_vertex[i][5]);
							XDrawLine(display, win, light_purple_gc, valid_vertex[i][0], valid_vertex[i][1], valid_vertex[i][2], valid_vertex[i][3]);
						}
					}

					XFillArc( display, win, black_gc, start_x, start_y, win_width/200, win_width/200, 0, 360*64);
					XFillArc( display, win, black_gc, target_x, target_y, win_width/200, win_width/200, 0, 360*64);
				}
				else{}
				//printf("exposed\n");
				XFlush(display);
				break;
			}
			case ButtonPress:
			{
				//printf("Button press %d, %d.\n",report.xbutton.x, report.xbutton.y);
				double distance1;
				x = report.xbutton.x;
				y = report.xbutton.y;
				int inTriangle;

				if (report.xbutton.button == Button1){
					/* left click */
					count++;
					
					inTriangle = check_if_in_triangle(line_count, m, x, y);

					if (inTriangle == 0){
						XFillArc( display, win, black_gc, x, y, win_width/200, win_width/200, 0, 360*64);
					}
					

				}
				else{
					printf("Closing Window.\n");
					XDestroyWindow(display, win);
					XCloseDisplay(display);
					exit(1);
				}

				//printf("count: %d\n", count);

				if (count == 0){
					reset(m, line_count);
					start_x = x;
					start_y = y;

					if (inTriangle == 1){
						count = -1;
					}
				}
				else if (count == 1){

					if (inTriangle == 0){
						target_x = x;
						target_y = y;

						printf("\n\nStarting point: (%d, %d)\nTarget point: (%d, %d)\n", start_x, start_y, target_x, target_y);

						int vertex[line_count][6];
						int * nearest_triangles;
						int * result_line_seg;

						for(i=0;i<=line_count;i++){
							//store formatted input file in array m
							fscanf(fp, "%*s ( %d, %d) ( %d, %d) (%d, %d)", &vertex[i][0], &vertex[i][1], &vertex[i][2], &vertex[i][3], &vertex[i][4], &vertex[i][5]);					
						}
						rewind(fp);
						
						printf("Total triangles: %d\n", line_count+1);

						for (i = 0; i <= line_count ; i++){
							for (j=0; j<6; j+=2){
								vertex[i][j] = vertex[i][j] + 100;
								vertex[i][j+1] = vertex[i][j+1] + 100;
							}
						}

						start_graph(line_count, vertex, start_x, start_y, target_x, target_y);

						printf("Applied start_graph()\n");
						
						shortest_path();

						printf("Applied shortest_path()\n");

						organize();

						printf("The shortest path: \n");

						for (i= 0; i<k; i++){
							if  (valid_vertex[i][6] == 0.0 || valid_vertex[i][6] == -4.0){
								printf("from (%d, %d) to (%d, %d) length: %f and path length: %f\n", (int)valid_vertex[i][0], (int)valid_vertex[i][1], (int)valid_vertex[i][2], (int)valid_vertex[i][3], valid_vertex[i][4], valid_vertex[i][5]);
								XDrawLine(display, win, light_purple_gc, valid_vertex[i][0], valid_vertex[i][1], valid_vertex[i][2], valid_vertex[i][3]);
							}
						}
						
						printf("DONE\n");
						
						count = -1;
						
					}
				}

				XFlush(display);
				break;
			}
			default:
				break;
		}
	}
	fclose(fp);
	return 0;
}
Exemplo n.º 2
0
static unsigned long * SetPalette(struct state *st )
{
	XWindowAttributes XWinAttribs;
	XColor Color, *aColors;
	signed short iColor;
	float nHalfColors;
	
	XGetWindowAttributes( st->dpy, st->window, &XWinAttribs );
	
	Color.red =   RANDOM() % 0xFFFF;
	Color.green = RANDOM() % 0xFFFF;
	Color.blue =  RANDOM() % 0xFFFF;

	if( strcasecmp( st->sColor, "random" ) && !XParseColor( st->dpy, XWinAttribs.colormap, st->sColor, &Color ) )
		fprintf( stderr, "%s: color %s not found in database. Choosing to random...\n", progname, st->sColor );

#ifdef VERBOSE
	printf( "%s: Base color (RGB): <%d, %d, %d>\n", progname, Color.red, Color.green, Color.blue );
#endif  /*  VERBOSE */

	st->iColorCount = get_integer_resource(st->dpy,  "ncolors", "Integer" );
	if( st->iColorCount <   2 )	st->iColorCount = 2;
	if( st->iColorCount > 255 )	st->iColorCount = 255;

	aColors    = calloc( st->iColorCount, sizeof(XColor) );
	st->aiColorVals = calloc( st->iColorCount, sizeof(unsigned long) );
	
	for( iColor=0; iColor<st->iColorCount; iColor++ )
	{
		nHalfColors = st->iColorCount / 2.0F;
		/* Black -> Base Color */
		if( iColor < (st->iColorCount/2) )
		{
			aColors[ iColor ].red   = ( Color.red   / nHalfColors ) * iColor;
			aColors[ iColor ].green = ( Color.green / nHalfColors ) * iColor;
			aColors[ iColor ].blue  = ( Color.blue  / nHalfColors ) * iColor;
		}
		/* Base Color -> White */
		else
		{
			aColors[ iColor ].red   = ( ( ( 0xFFFF - Color.red )   / nHalfColors ) * ( iColor - nHalfColors ) ) + Color.red;
			aColors[ iColor ].green = ( ( ( 0xFFFF - Color.green ) / nHalfColors ) * ( iColor - nHalfColors ) ) + Color.green;
			aColors[ iColor ].blue  = ( ( ( 0xFFFF - Color.blue )  / nHalfColors ) * ( iColor - nHalfColors ) ) + Color.blue;
		}

		if( !XAllocColor( st->dpy, XWinAttribs.colormap, &aColors[ iColor ] ) )
		{
			/* start all over with less colors */	
			XFreeColors( st->dpy, XWinAttribs.colormap, st->aiColorVals, iColor, 0 );
			free( aColors );
			free( st->aiColorVals );
			st->iColorCount--;
			aColors     = calloc( st->iColorCount, sizeof(XColor) );
			st->aiColorVals = calloc( st->iColorCount, sizeof(unsigned long) );
			iColor = -1;
		}
		else
			st->aiColorVals[ iColor ] = aColors[ iColor ].pixel;
	}

	free( aColors );

	XSetWindowBackground( st->dpy, st->window, st->aiColorVals[ 0 ] );

	return st->aiColorVals;
}
Exemplo n.º 3
0
Status
XAllocNamedColor(
register Display *dpy,
Colormap cmap,
_Xconst char *colorname, /* STRING8 */
XColor *hard_def, /* RETURN */
XColor *exact_def) /* RETURN */
{

    long nbytes;
    xAllocNamedColorReply rep;
    xAllocNamedColorReq *req;

    XcmsCCC ccc;
    XcmsColor cmsColor_exact;
    Status ret;

    /*
     * Let's Attempt to use Xcms and i18n approach to Parse Color
     */
    if ((ccc = XcmsCCCOfColormap(dpy, cmap)) != (XcmsCCC)NULL) {
	const char *tmpName = colorname;

	switch (_XcmsResolveColorString(ccc, &tmpName, &cmsColor_exact,
					XcmsRGBFormat)) {
	case XcmsSuccess:
	case XcmsSuccessWithCompression:
	    _XcmsRGB_to_XColor(&cmsColor_exact, exact_def, 1);
	    memcpy((char *)hard_def, (char *)exact_def, sizeof(XColor));
	    ret = XAllocColor(dpy, cmap, hard_def);
	    exact_def->pixel = hard_def->pixel;
	    return(ret);
	case XcmsFailure:
	case _XCMS_NEWNAME:
	    /*
	     * if the result was _XCMS_NEWNAME tmpName points to
	     * a string in cmsColNm.c:pairs table, for example,
	     * gray70 would become tekhvc:0.0/70.0/0.0
	     */
	    break;
	}
    }

    /*
     * Xcms and i18n approach failed.
     */
    LockDisplay(dpy);
    GetReq(AllocNamedColor, req);

    req->cmap = cmap;
    nbytes = req->nbytes = strlen(colorname);
    req->length += (nbytes + 3) >> 2; /* round up to mult of 4 */

    _XSend(dpy, colorname, nbytes);
       /* _XSend is more efficient that Data, since _XReply follows */

    if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
	UnlockDisplay(dpy);
        SyncHandle();
        return (0);
    }

    exact_def->red = rep.exactRed;
    exact_def->green = rep.exactGreen;
    exact_def->blue = rep.exactBlue;

    hard_def->red = rep.screenRed;
    hard_def->green = rep.screenGreen;
    hard_def->blue = rep.screenBlue;

    exact_def->pixel = hard_def->pixel = rep.pixel;

    UnlockDisplay(dpy);
    SyncHandle();
    return (1);
}
Exemplo n.º 4
0
dsxc_lutput (void)

/* C-- */
{
    float tcol[LVX*3];
    int   k, istat, ka, kdiv;

    char  flags;
    unsigned short int j;
    /* Cbegin */


    DSOPEN = F77_NAMED_COMMON(ds_genb).dsopen;
    PDSOPEN = F77_NAMED_COMMON(ds_panelb).pdsopen;
    NUMDDCOL = F77_NAMED_COMMON(lutacom).numddcol;

    (void) dsxc_lutload ( tcol );	 			/* Load LUT into working LUT */

    flags = DoRed | DoGreen | DoBlue;

    if ( DSOPEN || PDSOPEN ) {

        if ( OWNCOL ) {

            kdiv = LVX/NUMDDCOL;
            for ( k = 15; k<15+LVX; k++ ) {
                ka = 15 + ((k-15)/kdiv);
                COLOUR[ka].pixel = PC_ID[ka];
                COLOUR[ka].flags = flags;
                j = tcol[3*(k-15)+0]*65535.0;
                COLOUR[ka].red = j;
                j = tcol[3*(k-15)+1]*65535.0;
                COLOUR[ka].green = j;
                j = tcol[3*(k-15)+2]*65535.0;
                COLOUR[ka].blue = j;
            }

            XStoreColors ( VD_ID, CM_ID, COLOUR, 15+NUMDDCOL );
            XInstallColormap ( VD_ID, CM_ID );
            XFlush ( VD_ID );
        }
        else {

            for ( k = 15; k < 15+LVX; k++ ) {
                COLOUR[k].flags = flags;
                j = tcol[3*(k-15)+0]*65535.0;
                COLOUR[k].red = j;
                j = tcol[3*(k-15)+1]*65535.0;
                COLOUR[k].green = j;
                j = tcol[3*(k-15)+2]*65535.0;
                COLOUR[k].blue = j;
                istat = XAllocColor ( VD_ID, CM_ID, &COLOUR[k] );
                if ( istat==0 ) {
                    (void) c_printo ( "ERROR: Colour pixel not allocated" );
                    PC_ID[k] = 0 ;
                }
                else
                    PC_ID[k] = COLOUR[k].pixel;
            }
            XFlush ( VD_ID );

        }

    }


}
Exemplo n.º 5
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;
}
Exemplo n.º 6
0
void init_blue() {
    blue_gc = XCreateGC(dis, win, 0, 0);
    XParseColor(dis, colormap, blue, &blue_col);
    XAllocColor(dis, colormap, &blue_col);
    XSetForeground(dis, blue_gc, blue_col.pixel);
}
Exemplo n.º 7
0
/*
 *	NAME
 *		XcmsAllocNamedColor -
 *
 *	SYNOPSIS
 */
Status
XcmsAllocNamedColor (
    Display *dpy,
    Colormap cmap,
    _Xconst char *colorname,
    XcmsColor *pColor_scrn_return,
    XcmsColor *pColor_exact_return,
    XcmsColorFormat result_format)
/*
 *	DESCRIPTION
 *		Finds the color specification associated with the color
 *		name in the Device-Independent Color Name Database, then
 *		converts that color specification to an RGB format.  This
 *		RGB value is then used in a call to XAllocColor to allocate
 *		a read-only color cell.
 *
 *	RETURNS
 *		0 if failed to parse string or find any entry in the database.
 *		1 if succeeded in converting color name to XcmsColor.
 *		2 if succeeded in converting color name to another color name.
 *
 */
{
    long nbytes;
    xAllocNamedColorReply rep;
    xAllocNamedColorReq *req;
    XColor hard_def;
    XColor exact_def;
    Status retval1 = 1;
    Status retval2 = XcmsSuccess;
    XcmsColor tmpColor;
    XColor XColor_in_out;
    XcmsCCC ccc;

    /*
     * 0. Check for invalid arguments.
     */
    if (dpy == NULL || colorname[0] == '\0' || pColor_scrn_return == 0
	    || pColor_exact_return == NULL) {
	return(XcmsFailure);
    }

    if ((ccc = XcmsCCCOfColormap(dpy, cmap)) == (XcmsCCC)NULL) {
	return(XcmsFailure);
    }

    /*
     * 1. Convert string to a XcmsColor using Xcms and i18n mechanism
     */
    if ((retval1 = _XcmsResolveColorString(ccc, &colorname,
	    &tmpColor, result_format)) == XcmsFailure) {
	return(XcmsFailure);
    }
    if (retval1 == _XCMS_NEWNAME) {
	goto PassToServer;
    }
    memcpy((char *)pColor_exact_return, (char *)&tmpColor, sizeof(XcmsColor));

    /*
     * 2. Convert tmpColor to RGB
     *	Assume pColor_exact_return is now adjusted to Client White Point
     */
    if ((retval2 = XcmsConvertColors(ccc, &tmpColor,
	    1, XcmsRGBFormat, (Bool *) NULL)) == XcmsFailure) {
	return(XcmsFailure);
    }

    /*
     * 3. Convert to XColor and call XAllocColor
     */
    _XcmsRGB_to_XColor(&tmpColor, &XColor_in_out, 1);
    if (XAllocColor(ccc->dpy, cmap, &XColor_in_out) == 0) {
	return(XcmsFailure);
    }

    /*
     * 4. pColor_scrn_return
     *
     * Now convert to the target format.
     *    We can ignore the return value because we're already in a
     *    device-dependent format.
     */
    _XColor_to_XcmsRGB(ccc, &XColor_in_out, pColor_scrn_return, 1);
    if (result_format != XcmsRGBFormat) {
	if (result_format == XcmsUndefinedFormat) {
	    result_format = pColor_exact_return->format;
	}
	if (XcmsConvertColors(ccc, pColor_scrn_return, 1, result_format,
		(Bool *) NULL) == XcmsFailure) {
	    return(XcmsFailure);
	}
    }

    return(retval1 > retval2 ? retval1 : retval2);

PassToServer:
    /*
     * All previous methods failed, so lets pass it to the server
     * for parsing.
     */
    dpy = ccc->dpy;
    LockDisplay(dpy);
    GetReq(AllocNamedColor, req);

    req->cmap = cmap;
    nbytes = req->nbytes = strlen(colorname);
    req->length += (nbytes + 3) >> 2; /* round up to mult of 4 */

    _XSend(dpy, colorname, nbytes);
       /* _XSend is more efficient that Data, since _XReply follows */

    if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
	UnlockDisplay(dpy);
        SyncHandle();
        return (0);
    }

    exact_def.red = rep.exactRed;
    exact_def.green = rep.exactGreen;
    exact_def.blue = rep.exactBlue;

    hard_def.red = rep.screenRed;
    hard_def.green = rep.screenGreen;
    hard_def.blue = rep.screenBlue;

    exact_def.pixel = hard_def.pixel = rep.pixel;

    UnlockDisplay(dpy);
    SyncHandle();

    /*
     * Now convert to the target format.
     */
    _XColor_to_XcmsRGB(ccc, &exact_def, pColor_exact_return, 1);
    _XColor_to_XcmsRGB(ccc, &hard_def, pColor_scrn_return, 1);
    if (result_format != XcmsRGBFormat
	    && result_format != XcmsUndefinedFormat) {
	if (XcmsConvertColors(ccc, pColor_exact_return, 1, result_format,
		(Bool *) NULL) == XcmsFailure) {
	    return(XcmsFailure);
	}
	if (XcmsConvertColors(ccc, pColor_scrn_return, 1, result_format,
		(Bool *) NULL) == XcmsFailure) {
	    return(XcmsFailure);
	}
    }

    return(XcmsSuccess);
}
Exemplo n.º 8
0
static int initGraphics(struct state *st)
{
  XGCValues xgcv;
  XWindowAttributes xgwa;
/*  XSetWindowAttributes xswa;*/
  Colormap cmap;
  XColor color;
  int n, i;
  
  initCMap(st);

  XGetWindowAttributes(st->dpy,st->win,&xgwa);
  cmap=xgwa.colormap;
/*  xswa.backing_store=Always;
  XChangeWindowAttributes(st->dpy,st->win,CWBackingStore,&xswa);*/
  xgcv.function=GXcopy;

  st->delay = get_integer_resource(st->dpy, "delay","Integer");
  
  xgcv.foreground=get_pixel_resource (st->dpy, cmap, "background", "Background");
  st->fgc[0]=XCreateGC(st->dpy, st->win, GCForeground|GCFunction,&xgcv);
#ifdef HAVE_COCOA
  jwxyz_XSetAntiAliasing (st->dpy, st->fgc[0], False);
#endif
  
  n=0;
  if (mono_p) {
    xgcv.foreground=get_pixel_resource (st->dpy, cmap, "foreground", "Foreground");
    st->fgc[1]=XCreateGC(st->dpy,st->win,GCForeground|GCFunction,&xgcv);
#ifdef HAVE_COCOA
    jwxyz_XSetAntiAliasing (st->dpy, st->fgc[1], False);
#endif
    for (i=0;i<st->numColors;i+=2) st->fgc[i]=st->fgc[0];
    for (i=1;i<st->numColors;i+=2) st->fgc[i]=st->fgc[1];
  } else {
    for (i = 0; i < st->numColors; i++) {
      color.red=st->colors[n++]<<8;
      color.green=st->colors[n++]<<8;
      color.blue=st->colors[n++]<<8;
      color.flags=DoRed|DoGreen|DoBlue;
      XAllocColor(st->dpy,cmap,&color);
      xgcv.foreground=color.pixel;
      st->fgc[i] = XCreateGC(st->dpy, st->win, GCForeground | GCFunction,&xgcv);
#ifdef HAVE_COCOA
      jwxyz_XSetAntiAliasing (st->dpy, st->fgc[i], False);
#endif
    }
  }
  st->cgc = XCreateGC(st->dpy,st->win,GCForeground|GCFunction,&xgcv);
  XSetGraphicsExposures(st->dpy,st->cgc,False);
#ifdef HAVE_COCOA
  jwxyz_XSetAntiAliasing (st->dpy, st->cgc, False);
#endif

  st->xsize = xgwa.width;
  st->ysize = xgwa.height;
  st->xc = st->xsize >> 1;
  st->yc = st->ysize >> 1;

  st->maxx = 1.0;
  st->maxy = st->ysize/(float)st->xsize;

  if (st->colorScheme < 0) st->colorScheme = random()%NUM_SCHEMES;

  return True;
}
/* PROGRAM EXECUTION BEGINS HERE */
int main(int argc, char** argv)
{
    /** Declare variables **/
    /* People */
    int total_number_of_people = 50;
    int total_num_initially_infected = 1;
    int total_num_infected = 1;
    int our_number_of_people = 50;
    int our_person1 = 0;
    int our_current_infected_person = 0;
    int our_num_initially_infected = 1;
    int our_num_infected = 0;
    int our_current_location_x = 0;
    int our_current_location_y = 0;
    int our_num_susceptible = 0;
    int our_num_immune = 0;
    int our_num_dead = 0;
    int my_current_person_id = 0;
    int my_num_infected_nearby = 0;
    int my_person2 = 0;

    /* Environment */
    int environment_width = 30;
    int environment_height = 30;

    /* Disease */
    int infection_radius = 3;
    int duration_of_disease = 50;
    int contagiousness_factor = 30;
    int deadliness_factor = 30;
#ifdef SHOW_RESULTS
    double our_num_infections = 0.0;
    double our_num_infection_attempts = 0.0;
    double our_num_deaths = 0.0;
    double our_num_recovery_attempts = 0.0;
#endif

    /* Time */
    int total_number_of_days = 250;
    int our_current_day = 0;
    int microseconds_per_day = 100000;

    /* Movement */
    int my_x_move_direction = 0; 
    int my_y_move_direction = 0;

    /* Distributed Memory Information */
    int total_number_of_processes = 1;
    int our_rank = 0;
    //#ifdef MPI
    // int current_rank = 0;
    // int current_displ = 0;
    //#endif

    /* getopt */
    int c = 0;

    /* Integer arrays, a.k.a. integer pointers */
    int *x_locations;
    int *y_locations;
    int *our_x_locations;
    int *our_y_locations;
    int *our_infected_x_locations;
    int *our_infected_y_locations;
    int *their_infected_x_locations;
    int *their_infected_y_locations;
    int *our_num_days_infected;
    int *recvcounts;
    int *displs;

    /* Character arrays, a.k.a. character pointers */
    char *states;
    char *our_states;

#ifdef TEXT_DISPLAY
    /* Array of character arrays, a.k.a. array of character pointers, for text
     *  display */
    char **environment;
#endif

#ifdef X_DISPLAY
    /* Declare X-related variables */
    Display *display;
    Window window;
    int screen;
    Atom delete_window;
    GC gc;
    XColor infected_color;
    XColor immune_color;
    XColor susceptible_color;
    XColor dead_color;
    Colormap colormap;
    char red[] = "#FF0000";
    char green[] = "#00FF00";
    char black[] = "#000000";
    char white[] = "#FFFFFF";
#endif

    //#ifdef MPI
    /* Each process initializes the distributed memory environment */
    //MPI_Init(&argc, &argv);
    //#endif

    /* ALG I: Each process determines its rank and the total number of processes     */
    //#ifdef MPI
    //  MPI_Comm_rank(MPI_COMM_WORLD, &our_rank);
    //  MPI_Comm_size(MPI_COMM_WORLD, &total_number_of_processes);
    //#else
    our_rank = 0;
    total_number_of_processes = 1;
    //#endif

    /* ALG II: Each process is given the parameters of the simulation */
    /* Get command line options -- this follows the idiom presented in the
     *  getopt man page (enter 'man 3 getopt' on the shell for more) */
    while((c = getopt(argc, argv, "n:i:w:h:t:T:c:d:D:m:")) != -1)
    {
        switch(c)
        {
            case 'n':
                total_number_of_people = atoi(optarg);
                break;
            case 'i':
                total_num_initially_infected = atoi(optarg);
                break;
            case 'w':
                environment_width = atoi(optarg);
                break;
            case 'h':
                environment_height = atoi(optarg);
                break;
            case 't':
                total_number_of_days = atoi(optarg);
                break;
            case 'T':
                duration_of_disease = atoi(optarg);
                break;
            case 'c':
                contagiousness_factor = atoi(optarg);
                break;
            case 'd':
                infection_radius = atoi(optarg);
                break;
            case 'D':
                deadliness_factor = atoi(optarg);
                break;
            case 'm':
                microseconds_per_day = atoi(optarg);
                break;
                /* If the user entered "-?" or an unrecognized option, we need 
                 *  to print a usage message before exiting. */
            case '?':
            default:
                fprintf(stderr, "Usage: ");
                //#ifdef MPI
                //              fprintf(stderr, "mpirun -np total_number_of_processes ");
                //#endif
                fprintf(stderr, "%s [-n total_number_of_people][-i total_num_initially_infected][-w environment_width][-h environment_height][-t total_number_of_days][-T duration_of_disease][-c contagiousness_factor][-d infection_radius][-D deadliness_factor][-m microseconds_per_day]\n", argv[0]);
                exit(-1);
        }
    }
    argc -= optind;
    argv += optind;

    /* ALG III: Each process makes sure that the total number of initially 
     *  infected people is less than the total number of people */
    if(total_num_initially_infected > total_number_of_people)
    {
        fprintf(stderr, "ERROR: initial number of infected (%d) must be less than total number of people (%d)\n", total_num_initially_infected, 
                total_number_of_people);
        exit(-1);
    }

    /* ALG IV: Each process determines the number of people for which it is 
     *  responsible */
    our_number_of_people = total_number_of_people / total_number_of_processes;

    /* ALG V: The last process is responsible for the remainder */
    if(our_rank == total_number_of_processes - 1)
    {
        our_number_of_people += total_number_of_people % total_number_of_processes;
    }

    /* ALG VI: Each process determines the number of initially infected people 
     *  for which it is responsible */
    our_num_initially_infected = total_num_initially_infected 
        / total_number_of_processes;

    /* ALG VII: The last process is responsible for the remainder */
    if(our_rank == total_number_of_processes - 1)
    {
        our_num_initially_infected += total_num_initially_infected 
            % total_number_of_processes;
    }

    /* Allocate the arrays */
    x_locations = (int*)malloc(total_number_of_people * sizeof(int));
    y_locations = (int*)malloc(total_number_of_people * sizeof(int));
    our_x_locations = (int*)malloc(our_number_of_people * sizeof(int));
    our_y_locations = (int*)malloc(our_number_of_people * sizeof(int));
    our_infected_x_locations = (int*)malloc(our_number_of_people * sizeof(int));
    our_infected_y_locations = (int*)malloc(our_number_of_people * sizeof(int));
    their_infected_x_locations = (int*)malloc(total_number_of_people 
            * sizeof(int));
    their_infected_y_locations = (int*)malloc(total_number_of_people 
            * sizeof(int));
    our_num_days_infected = (int*)malloc(our_number_of_people * sizeof(int));
    recvcounts = (int*)malloc(total_number_of_processes * sizeof(int));
    displs = (int*)malloc(total_number_of_processes * sizeof(int));
    states = (char*)malloc(total_number_of_people * sizeof(char));
    our_states = (char*)malloc(our_number_of_people * sizeof(char));

#ifdef TEXT_DISPLAY
    environment = (char**)malloc(environment_width * environment_height
            * sizeof(char*));
    for(our_current_location_x = 0;
            our_current_location_x <= environment_width - 1;
            our_current_location_x++)
    {
        environment[our_current_location_x] = (char*)malloc(environment_height
                * sizeof(char));
    }
#endif

    /* ALG VIII: Each process seeds the random number generator based on the
     *  current time */
    srandom(time(NULL));

    /* ALG IX: Each process spawns threads to set the states of the initially 
     *  infected people and set the count of its infected people */
#pragma omp parallel for private(my_current_person_id) \
    reduction(+:our_num_infected)
    for(my_current_person_id = 0; my_current_person_id 
            <= our_num_initially_infected - 1; my_current_person_id++)
    {
        our_states[my_current_person_id] = INFECTED;
        our_num_infected++;
    }

    /* ALG X: Each process spawns threads to set the states of the rest of its 
     *  people and set the count of its susceptible people */
#pragma omp parallel for private(my_current_person_id) \
    reduction(+:our_num_susceptible)
    for(my_current_person_id = our_num_initially_infected; 
            my_current_person_id <= our_number_of_people - 1; 
            my_current_person_id++)
    {
        our_states[my_current_person_id] = SUSCEPTIBLE;
        our_num_susceptible++;
    }

    /* ALG XI: Each process spawns threads to set random x and y locations for 
     *  each of its people */
#pragma omp parallel for private(my_current_person_id)
    for(my_current_person_id = 0;
            my_current_person_id <= our_number_of_people - 1; 
            my_current_person_id++)
    {
        our_x_locations[my_current_person_id] = random() % environment_width;
        our_y_locations[my_current_person_id] = random() % environment_height;
    }

    /* ALG XII: Each process spawns threads to initialize the number of days 
     *  infected of each of its people to 0 */
#pragma omp parallel for private(my_current_person_id)
    for(my_current_person_id = 0;
            my_current_person_id <= our_number_of_people - 1;
            my_current_person_id++)
    {
        our_num_days_infected[my_current_person_id] = 0;
    }

    /* ALG XIII: Rank 0 initializes the graphics display */
#ifdef X_DISPLAY
    if(our_rank == 0)
    {
        /* Initialize the X Windows Environment
         * This all comes from 
         *   http://en.wikibooks.org/wiki/X_Window_Programming/XLib
         *   http://tronche.com/gui/x/xlib-tutorial
         *   http://user.xmission.com/~georgeps/documentation/tutorials/
         *      Xlib_Beginner.html
         */

        /* Open a connection to the X server */
        display = XOpenDisplay(NULL);
        if(display == NULL)
        {
            fprintf(stderr, "Error: could not open X display\n");
        }
        screen = DefaultScreen(display);
        window = XCreateSimpleWindow(display, RootWindow(display, screen),
                0, 0, environment_width * PIXEL_WIDTH_PER_PERSON, 
                environment_height * PIXEL_HEIGHT_PER_PERSON, 1,
                BlackPixel(display, screen), WhitePixel(display, screen));
        delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0);
        XSetWMProtocols(display, window, &delete_window, 1);
        XSelectInput(display, window, ExposureMask | KeyPressMask);
        XMapWindow(display, window);
        colormap = DefaultColormap(display, 0);
        gc = XCreateGC(display, window, 0, 0);
        XParseColor(display, colormap, red, &infected_color);
        XParseColor(display, colormap, green, &immune_color);
        XParseColor(display, colormap, white, &dead_color);
        XParseColor(display, colormap, black, &susceptible_color);
        XAllocColor(display, colormap, &infected_color);
        XAllocColor(display, colormap, &immune_color);
        XAllocColor(display, colormap, &susceptible_color);
        XAllocColor(display, colormap, &dead_color);
    }
#endif

    /* ALG XIV: Each process starts a loop to run the simulation for the
     *  specified number of days */
    for(our_current_day = 0; our_current_day <= total_number_of_days - 1; 
            our_current_day++)
    {
        /* ALG XIV.A: Each process determines its infected x locations and 
         *  infected y locations */
        our_current_infected_person = 0;
        for(our_person1 = 0; our_person1 <= our_number_of_people - 1;
                our_person1++)
        {
            if(our_states[our_person1] == INFECTED)
            {
                our_infected_x_locations[our_current_infected_person] =
                    our_x_locations[our_person1];
                our_infected_y_locations[our_current_infected_person] =
                    our_y_locations[our_person1];
                our_current_infected_person++;
            }
        }
        //#ifdef MPI
        /* ALG XIV.B: Each process sends its count of infected people to all the
         *  other processes and receives their counts */
        //      MPI_Allgather(&our_num_infected, 1, MPI_INT, recvcounts, 1, 
        //              MPI_INT, MPI_COMM_WORLD);

        //      total_num_infected = 0;
        //      for(current_rank = 0; current_rank <= total_number_of_processes - 1;
        //              current_rank++)
        //      {
        //          total_num_infected += recvcounts[current_rank];
        //      }

        /* Set up the displacements in the receive buffer (see the man page for 
         *  MPI_Allgatherv) */
        //      current_displ = 0;
        //      for(current_rank = 0; current_rank <= total_number_of_processes - 1;
        //              current_rank++)
        //      {
        //          displs[current_rank] = current_displ;
        //          current_displ += recvcounts[current_rank];
        //      }

        /* ALG XIV.C: Each process sends the x locations of its infected people 
         *  to all the other processes and receives the x locations of their 
         *  infected people */
        //      MPI_Allgatherv(our_infected_x_locations, our_num_infected, MPI_INT, 
        //              their_infected_x_locations, recvcounts, displs, 
        //              MPI_INT, MPI_COMM_WORLD);

        /* ALG XIV.D: Each process sends the y locations of its infected people 
         *  to all the other processes and receives the y locations of their 
         *  infected people */
        //       MPI_Allgatherv(our_infected_y_locations, our_num_infected, MPI_INT, 
        //               their_infected_y_locations, recvcounts, displs, 
        //               MPI_INT, MPI_COMM_WORLD);
        //#else
        total_num_infected = our_num_infected;
        for(my_current_person_id = 0;
                my_current_person_id <= total_num_infected - 1;
                my_current_person_id++)
        {
            their_infected_x_locations[my_current_person_id] = 
                our_infected_x_locations[my_current_person_id];
            their_infected_y_locations[my_current_person_id] =
                our_infected_y_locations[my_current_person_id];
        }
        //#endif

#if defined(X_DISPLAY) || defined(TEXT_DISPLAY)
        /* ALG XIV.E: If display is enabled, Rank 0 gathers the states, x 
         *  locations, and y locations of the people for which each process is 
         *  responsible */
        //#ifdef MPI
        /* Set up the receive counts and displacements in the receive buffer 
         *  (see the man page for MPI_Gatherv) */
        //      current_displ = 0;
        //      for(current_rank = 0; current_rank <= total_number_of_processes - 1;
        //              current_rank++)
        //      {
        //          displs[current_rank] = current_displ;
        //          recvcounts[current_rank] = total_number_of_people
        //              / total_number_of_processes;
        //          if(current_rank == total_number_of_processes - 1)
        //          {
        //              recvcounts[current_rank] += total_number_of_people
        //                  % total_number_of_processes;
        //          }
        //          current_displ += recvcounts[current_rank];
        //      }

        //      MPI_Gatherv(our_states, our_number_of_people, MPI_CHAR, states,
        //              recvcounts, displs, MPI_CHAR, 0, MPI_COMM_WORLD);
        //      MPI_Gatherv(our_x_locations, our_number_of_people, MPI_INT, x_locations,
        //              recvcounts, displs, MPI_INT, 0, MPI_COMM_WORLD);
        //      MPI_Gatherv(our_y_locations, our_number_of_people, MPI_INT, y_locations,
        //              recvcounts, displs, MPI_INT, 0, MPI_COMM_WORLD);
        //#else
#pragma omp parallel for private(my_current_person_id)
        for(my_current_person_id = 0; my_current_person_id 
                <= total_number_of_people - 1; my_current_person_id++)
        {
            states[my_current_person_id] = our_states[my_current_person_id];
            x_locations[my_current_person_id] 
                = our_x_locations[my_current_person_id];
            y_locations[my_current_person_id] 
                = our_y_locations[my_current_person_id];
        }
        //#endif
#endif

        /* ALG XIV.F: If display is enabled, Rank 0 displays a graphic of the 
         *  current day */
#ifdef X_DISPLAY
        if(our_rank == 0)
        {
            XClearWindow(display, window);
            for(my_current_person_id = 0; my_current_person_id 
                    <= total_number_of_people - 1; my_current_person_id++)
            {
                if(states[my_current_person_id] == INFECTED)
                {
                    XSetForeground(display, gc, infected_color.pixel);
                }
                else if(states[my_current_person_id] == IMMUNE)
                {
                    XSetForeground(display, gc, immune_color.pixel);
                }
                else if(states[my_current_person_id] == SUSCEPTIBLE)
                {
                    XSetForeground(display, gc, susceptible_color.pixel);
                }
                else if(states[my_current_person_id] == DEAD)
                {
                    XSetForeground(display, gc, dead_color.pixel);
                }
                else
                {
                    fprintf(stderr, "ERROR: person %d has state '%c'\n",
                            my_current_person_id, states[my_current_person_id]);
                    exit(-1);
                }
                XFillRectangle(display, window, gc,
                        x_locations[my_current_person_id] 
                        * PIXEL_WIDTH_PER_PERSON, 
                        y_locations[my_current_person_id]
                        * PIXEL_HEIGHT_PER_PERSON, 
                        PIXEL_WIDTH_PER_PERSON, 
                        PIXEL_HEIGHT_PER_PERSON);
            }
            XFlush(display);
        }
#endif
#ifdef TEXT_DISPLAY
        if(our_rank == 0)
        {
            for(our_current_location_y = 0; 
                    our_current_location_y <= environment_height - 1;
                    our_current_location_y++)
            {
                for(our_current_location_x = 0; our_current_location_x 
                        <= environment_width - 1; our_current_location_x++)
                {
                    environment[our_current_location_x][our_current_location_y] 
                        = ' ';
                }
            }

            for(my_current_person_id = 0; 
                    my_current_person_id <= total_number_of_people - 1;
                    my_current_person_id++)
            {
                environment[x_locations[my_current_person_id]]
                    [y_locations[my_current_person_id]] = 
                    states[my_current_person_id];
            }

            printf("----------------------\n");
            for(our_current_location_y = 0;
                    our_current_location_y <= environment_height - 1;
                    our_current_location_y++)
            {
                for(our_current_location_x = 0; our_current_location_x 
                        <= environment_width - 1; our_current_location_x++)
                {
                    printf("%c", environment[our_current_location_x]
                            [our_current_location_y]);
                }
                printf("\n");
            }
        }
#endif

#if defined(X_DISPLAY) || defined(TEXT_DISPLAY)
        /* Wait between frames of animation */
        usleep(microseconds_per_day);
#endif

        /* ALG XIV.G: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id, my_x_move_direction, \
        my_y_move_direction)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.G.1: If the person is not dead, then */
            if(our_states[my_current_person_id] != DEAD)
            {
                /* ALG XIV.G.1.a: The thread randomly picks whether the person 
                 *  moves left or right or does not move in the x dimension */
                my_x_move_direction = (random() % 3) - 1;

                /* ALG XIV.G.1.b: The thread randomly picks whether the person 
                 *  moves up or down or does not move in the y dimension */
                my_y_move_direction = (random() % 3) - 1;

                /* ALG XIV.G.1.c: If the person will remain in the bounds of the
                 *  environment after moving, then */
                if((our_x_locations[my_current_person_id] 
                            + my_x_move_direction >= 0)
                        && (our_x_locations[my_current_person_id] 
                            + my_x_move_direction < environment_width)
                        && (our_y_locations[my_current_person_id] 
                            + my_y_move_direction >= 0)
                        && (our_y_locations[my_current_person_id] 
                            + my_y_move_direction < environment_height))
                {
                    /* ALG XIV.G.i: The thread moves the person */
                    our_x_locations[my_current_person_id] 
                        += my_x_move_direction;
                    our_y_locations[my_current_person_id] 
                        += my_y_move_direction;
                }
            }
        }

        /* ALG XIV.H: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id, my_num_infected_nearby, \
        my_person2) reduction(+:our_num_infection_attempts) \
        reduction(+:our_num_infected) reduction(+:our_num_susceptible) \
        reduction(+:our_num_infections)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.H.1: If the person is susceptible, then */
            if(our_states[my_current_person_id] == SUSCEPTIBLE)
            {
                /* ALG XIV.H.1.a: For each of the infected people (received
                 *  earlier from all processes) or until the number of infected 
                 *  people nearby is 1, the thread does the following */
                my_num_infected_nearby = 0;
                for(my_person2 = 0; my_person2 <= total_num_infected - 1
                        && my_num_infected_nearby < 1; my_person2++)
                {
                    /* ALG XIV.H.1.a.i: If person 1 is within the infection 
                     *  radius, then */
                    if((our_x_locations[my_current_person_id] 
                                > their_infected_x_locations[my_person2]
                                - infection_radius)
                            && (our_x_locations[my_current_person_id] 
                                < their_infected_x_locations[my_person2] 
                                + infection_radius)
                            && (our_y_locations[my_current_person_id]
                                > their_infected_y_locations[my_person2] 
                                - infection_radius)
                            && (our_y_locations[my_current_person_id]
                                < their_infected_y_locations[my_person2] 
                                + infection_radius))
                    {
                        /* ALG XIV.H.1.a.i.1: The thread increments the number 
                         *  of infected people nearby */
                        my_num_infected_nearby++;
                    }
                }

#ifdef SHOW_RESULTS
                if(my_num_infected_nearby >= 1)
                    our_num_infection_attempts++;
#endif

                /* ALG XIV.H.1.b: If there is at least one infected person 
                 *  nearby, and a random number less than 100 is less than or
                 *  equal to the contagiousness factor, then */
                if(my_num_infected_nearby >= 1 && (random() % 100) 
                        <= contagiousness_factor)
                {
                    /* ALG XIV.H.1.b.i: The thread changes person1’s state to 
                     *  infected */
                    our_states[my_current_person_id] = INFECTED;

                    /* ALG XIV.H.1.b.ii: The thread updates the counters */
                    our_num_infected++;
                    our_num_susceptible--;

#ifdef SHOW_RESULTS
                    our_num_infections++;
#endif
                }
            }
        }

        /* ALG XIV.I: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id) \
        reduction(+:our_num_recovery_attempts) reduction(+:our_num_dead) \
        reduction(+:our_num_infected) reduction(+:our_num_deaths) \
        reduction(+:our_num_immune)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.I.1: If the person is infected and has been for the full 
             *  duration of the disease, then */
            if(our_states[my_current_person_id] == INFECTED
                    && our_num_days_infected[my_current_person_id] 
                    == duration_of_disease)
            {
#ifdef SHOW_RESULTS
                our_num_recovery_attempts++;
#endif
                /* ALG XIV.I.a: If a random number less than 100 is less than 
                 *  the deadliness factor, then */
                if((random() % 100) < deadliness_factor)
                {
                    /* ALG XIV.I.a.i: The thread changes the person’s state to 
                     *  dead */
                    our_states[my_current_person_id] = DEAD;

                    /* ALG XIV.I.a.ii: The thread updates the counters */
                    our_num_dead++;
                    our_num_infected--;

#ifdef SHOW_RESULTS
                    our_num_deaths++;
#endif
                }
                /* ALG XIV.I.b: Otherwise, */
                else
                {
                    /* ALG XIV.I.b.i: The thread changes the person’s state to 
                     *  immune */
                    our_states[my_current_person_id] = IMMUNE;

                    /* ALG XIV.I.b.ii: The thread updates the counters */
                    our_num_immune++;
                    our_num_infected--;
                }
            }
        }

        /* ALG XIV.J: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.J.1: If the person is infected, then */
            if(our_states[my_current_person_id] == INFECTED)
            {
                /* ALG XIV.J.1.a: Increment the number of days the person has 
                 *  been infected */
                our_num_days_infected[my_current_person_id]++;
            }
        }
    }

    /* ALG XV: If X display is enabled, then Rank 0 destroys the X Window and 
     *  closes the display */
#ifdef X_DISPLAY
    if(our_rank == 0)
    {
        XDestroyWindow(display, window);
        XCloseDisplay(display);
    }
#endif

#ifdef SHOW_RESULTS
    printf("Final counts: %d susceptible, %d infected, %d immune, \
            %d dead\nActual contagiousness: %f\nActual deadliness: \
            %f\n", our_num_susceptible, our_num_infected, our_num_immune, 
            our_num_dead, 100.0 * (our_num_infections / 
                (our_num_infection_attempts == 0 ? 1 : our_num_infection_attempts)),
            100.0 * (our_num_deaths / (our_num_recovery_attempts == 0 ? 1 
                    : our_num_recovery_attempts)));
#endif

    /* Deallocate the arrays -- we have finished using the memory, so now we
     *  "free" it back to the heap */
#ifdef TEXT_DISPLAY 
    for(our_current_location_x = environment_width - 1; 
            our_current_location_x >= 0; our_current_location_x--)
    {
        free(environment[our_current_location_x]);
    }
    free(environment);
#endif
    free(our_states);
    free(states);
    free(displs);
    free(recvcounts);
    free(our_num_days_infected);
    free(their_infected_y_locations);
    free(their_infected_x_locations);
    free(our_infected_y_locations);
    free(our_infected_x_locations);
    free(our_y_locations);
    free(our_x_locations);
    free(y_locations);
    free(x_locations);

    //#ifdef MPI
    /* MPI execution is finished; no MPI calls are allowed after this */
    //    MPI_Finalize();
    //#endif

    /* The program has finished executing successfully */
    return 0;
}
Exemplo n.º 10
0
/******************************************************************************
* Routine to allocate the requested colors from the X server.		      *
* Two stages are performed:						      *
* 1. Colors are requested directly.					      *
* 2. If not enough colors can be allocated, the closest current color	      *
*    in current table is selected instead.				      *
* This allocation is not optimal as when fail to allocate all colors one      *
* should pick the right colors to do allocate in order to minimize the        *
* closest distance from the unallocated ones under some norm (what is a good  *
* norm for the RGB space?). Improve it if you are bored.		      *
******************************************************************************/
static void AllocateColors2(void)
{
    int i, j, Index = 0, Count = 0, XNumOfColors;
    char Msg[80];
    unsigned long D, Distance, AvgDistance = 0, Red, Green, Blue;
    GifBooleanType Failed = FALSE;
    XColor *XOldColorTable;

    for (i = 0; i < 256; i++) {
	if (i < ColorMapSize) {          /* Prepere color entry in X format. */
	    XColorTable[i].red = ColorMap[i].Red << 8;
	    XColorTable[i].green = ColorMap[i].Green << 8;
	    XColorTable[i].blue = ColorMap[i].Blue << 8;
	    XColorTable[i].flags = DoRed | DoGreen | DoBlue;
	    XPixelTable[i] = -1;		       /* Not allocated yet. */
	}
	else
	    XPixelTable[i] = 0;    /* Put reasonable color for out of range. */
    }

    for (i = 0; i < ColorMapSize; i++)	      /* Allocate the colors from X: */
	if (XAllocColor(XDisplay, XColorMap, &XColorTable[i]))
	    XPixelTable[i] = XColorTable[i].pixel;
	else
	    Failed = TRUE;

    if (Failed) {
	XNumOfColors = DisplayCells(XDisplay, XScreen);
	XOldColorTable = (XColor *) malloc(sizeof(XColor) * XNumOfColors);
	for (i = 0; i < XNumOfColors; i++) XOldColorTable[i].pixel = i;
	XQueryColors(XDisplay, XColorMap, XOldColorTable, XNumOfColors);
	
	for (i = 0; i < ColorMapSize; i++) {
	    /* Allocate closest colors from X: */
	    if (XPixelTable[i] == -1) {      /* Failed to allocate this one. */
		Distance = 0xffffffff;

		Red = XColorTable[i].red;
		Green = XColorTable[i].green;
		Blue = XColorTable[i].blue;

		for (j = 0; j < XNumOfColors; j++) {
		    /* Find the closest color in 3D RGB space using L1 norm. */
		    if ((D = ABS(Red - XOldColorTable[j].red) +
			     ABS(Green - XOldColorTable[j].green) +
			     ABS(Blue - XOldColorTable[j].blue)) < Distance) {
			Distance = D;
			Index = j;
		    }
		}
	        XPixelTable[i] = Index;

		AvgDistance += Distance;
		Count++;
	    }
	}
	free(XOldColorTable);

	sprintf(Msg, "Colors will be approximated (average error = %d).\n",
		AvgDistance / Count);
	GIF_MESSAGE(Msg);
    }
}
Exemplo n.º 11
0
int main () {
	printf ("X11 demo\n");

	Display* display = NULL;
	GC graphics_context;
	Window window;
	int black_colour, white_colour;

	{ // create window and display combo
		printf ("init window...\n");
		display = XOpenDisplay (NULL);
		if (!display) {
			fprintf (stderr, "ERROR: opening display\n");
			return 1;
		}
		black_colour = BlackPixel (display, DefaultScreen (display));
		white_colour = WhitePixel (display, DefaultScreen (display));
		// colour map
		Colormap colour_map;
		char green[] = "#00FF00";
		char charcoal[] ="RGBi:0.01/0.02/0.01";
		char lcharcoal[] = "RGBi:0.02/0.03/0.02";//"#445544";
		char textc[] = "#DDEEDD";
		char linenoc[] = "#667766";
		char rulerc[] = "#556655";
		colour_map = DefaultColormap (display, 0);
		// add colours
		XParseColor (display, colour_map, green, &green_col);
		XAllocColor (display, colour_map, &green_col);
		XParseColor (display, colour_map, charcoal, &charcoal_col);
		XAllocColor (display, colour_map, &charcoal_col);
		XParseColor (display, colour_map, lcharcoal, &lcharcoal_col);
		XAllocColor (display, colour_map, &lcharcoal_col);
		XParseColor (display, colour_map, textc, &text_col);
		XAllocColor (display, colour_map, &text_col);
		XParseColor (display, colour_map, rulerc, &ruler_col);
		XAllocColor (display, colour_map, &ruler_col);
		XParseColor (display, colour_map, linenoc, &lineno_col);
		XAllocColor (display, colour_map, &lineno_col);
		// note: can use CopyFromParent instead of colour index
		// note: there is also XCreateWindow with more params
		// simplewindow also clears the window to background colour
		// 0,0 is request position, other 0 is border (not used)
		window = XCreateSimpleWindow (display, DefaultRootWindow (display), 0, 0,
			1024, 768, 0, charcoal_col.pixel, charcoal_col.pixel);
		XStoreName (display, window, "Anton's X11 demo");
		// get MapNotify events etc.
		XSelectInput (display, window, ExposureMask); // was StructureNotifyMask
		// put window on screen command
		XMapWindow (display, window);
		// create graphics context
		graphics_context = XCreateGC (display, window, 0, 0);
	} // endinitwindow

	{ // draw
		// note: can also unload a font
		const char* font_name = "-*-Monospace-*-10-*";
		XFontStruct* font = XLoadQueryFont (display, font_name);
		if (!font) {
			fprintf (stderr, "ERROR: could not load font %s\n", font_name);
			font = XLoadQueryFont (display, "fixed");
			if (!font) {
				fprintf (stderr, "ERROR: default font fixed did not load\n");
				return 1;
			}
		}
		XSetFont (display, graphics_context, font->fid);

		event_loop (display, window, graphics_context);
	} // enddraw

	return 0;
}
Exemplo n.º 12
0
XColor *xGetXColor(Display *display,
		   Colormap cmap,
		   x_color_list_index_t *list_index,
		   const char *colorname)

{

  int pixval;
  int get_next;
  x_color_list_t *new_entry, *this_entry;

  if (list_index->n_entries == 0) {

    new_entry = (x_color_list_t *)
      umalloc (sizeof(x_color_list_t));

    list_index->first_entry = new_entry;

  } else {

    this_entry = list_index->first_entry;

    get_next = TRUE;

    while (get_next) {

      if (!strcmp(colorname, this_entry->colorname))
	return(&this_entry->x_color);

      if (this_entry->next == NULL) {
	get_next = FALSE;
      } else {
	this_entry = this_entry->next;
      }

    } /* while */

    new_entry = (x_color_list_t *)
      umalloc (sizeof(x_color_list_t));

    this_entry->next = new_entry;

  } /* if (list_index ..... */

  list_index->n_entries++;
  new_entry->next = NULL;
  new_entry->duplicate = FALSE;
  new_entry->colorname = (char *)
    umalloc (strlen(colorname) + 1);
  strcpy(new_entry->colorname, colorname);

  if (XParseColor(display, cmap, colorname, &new_entry->x_color) == 0) {

    fprintf(stderr, "ERROR - xGetXColor\n");
    fprintf(stderr, "Cannot match color '%s'\n", colorname);
    return(NULL);

  }

  XAllocColor(display, cmap, &new_entry->x_color);

  new_entry->gc = XCreateGC(display, DefaultRootWindow(display),
			     0, 0);
  XSetForeground(display, new_entry->gc, new_entry->x_color.pixel);

  /*
   * search through the list to check whether the same pixel value has
   * been allocated to a previous entry - this sometimes happens
   * if the server has run out of color cells. If there is a duplicate
   * entry, set the duplicate flag in the new entry
   */

  pixval = new_entry->x_color.pixel;

  this_entry = list_index->first_entry;

  while (this_entry->next != NULL) {

    if (this_entry->x_color.pixel == pixval) {
      new_entry->duplicate = TRUE;
      break;
    }

    this_entry = this_entry->next;

  } /* while */

  return(&new_entry->x_color);

}
Exemplo n.º 13
0
PetscErrorCode PetscDrawSetUpColormap_Private(Display *display,int screen,Visual *visual,Colormap colormap)
{
  int            i,found;
  Colormap       defaultmap = DefaultColormap(display,screen);
  XColor         colordef;
  PetscBool      fast = PETSC_FALSE;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  if (colormap) gColormap = colormap;
  else          gColormap = XCreateColormap(display,RootWindow(display,screen),visual,AllocAll);

  cmap_base = 0;

  ierr = PetscMemzero(cmap_pixvalues_used,256*sizeof(PetscBool));CHKERRQ(ierr);

  /* set the basic colors into the color map */
  for (i=0; i<PETSC_DRAW_BASIC_COLORS; i++) {
    XParseColor(display,gColormap,colornames[i],&colordef);
    /* try to allocate the color in the default-map */
    found = XAllocColor(display,defaultmap,&colordef);
    /* use it, if it it exists and is not already used in the new colormap */
    if (found && colordef.pixel < 256  && !cmap_pixvalues_used[colordef.pixel]) {
      cmap_pixvalues_used[colordef.pixel] = PETSC_TRUE;
      /* otherwise search for the next available slot */
    } else {
      while (cmap_pixvalues_used[cmap_base]) cmap_base++;
      colordef.pixel                   = cmap_base;
      cmap_pixvalues_used[cmap_base++] = PETSC_TRUE;
    }
    XStoreColor(display,gColormap,&colordef);
    gCmapping[i] = colordef.pixel;
  }

  /* set the contour colors into the colormap */
  ierr = PetscOptionsGetBool(NULL,NULL,"-draw_fast",&fast,NULL);CHKERRQ(ierr);
  if (!fast) {
    int ncolors = 256-PETSC_DRAW_BASIC_COLORS;
    unsigned char  *red,*green,*blue;
    ierr = PetscMalloc3(ncolors,&red,ncolors,&green,ncolors,&blue);CHKERRQ(ierr);
    ierr = PetscDrawUtilitySetCmap(NULL,ncolors,red,green,blue);CHKERRQ(ierr);
    for (i=0; i<ncolors; i++) {
      colordef.red   = (unsigned short)(red[i]   << 8);
      colordef.green = (unsigned short)(green[i] << 8);
      colordef.blue  = (unsigned short)(blue[i]  << 8);
      colordef.flags = DoRed|DoGreen|DoBlue;
      /* try to allocate the color in the default-map */
      found = XAllocColor(display,defaultmap,&colordef);
      /* use it, if it it exists and is not already used in the new colormap */
      if (found && colordef.pixel < 256  && !cmap_pixvalues_used[colordef.pixel]) {
        cmap_pixvalues_used[colordef.pixel] = PETSC_TRUE;
        /* otherwise search for the next available slot */
      } else {
        while (cmap_pixvalues_used[cmap_base]) cmap_base++;
        colordef.pixel                   = cmap_base;
        cmap_pixvalues_used[cmap_base++] = PETSC_TRUE;
      }
      XStoreColor(display,gColormap,&colordef);
      gCmapping[PETSC_DRAW_BASIC_COLORS + i] = colordef.pixel;
    }
    ierr = PetscFree3(red,green,blue);CHKERRQ(ierr);
  }

  ierr = PetscInfo(0,"Successfully allocated colors\n");CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Exemplo n.º 14
0
void
do_setcustompalette (XColor * inpal)
{
  int i, n, me = 0, flag[256], vid;
  int depth;
  long unsigned int plane_masks[3];
  XColor pal[256];
  int writeable_p;

  display.cmap = XDefaultColormap (display.dpy, display.screen);
  depth = DefaultDepth (display.dpy, display.screen);

  /* Decide, if the colormap is writable */
  {
    Visual *visual = DefaultVisual (display.dpy, display.screen);
#if defined(__cplusplus) || defined(c_plusplus)
    int visual_class = visual->c_class;
#else
    int visual_class = visual->class;
#endif
    writeable_p = (visual_class == PseudoColor || visual_class == GrayScale);
  }

  if (writeable_p)
    {
      if (XAllocColorCells (display.dpy, display.cmap, 0
			    ,plane_masks, 0, colour_table, 256) == 0)
	{
	  me = (*DefaultVisual (display.dpy, display.screen)).map_entries;
	  vid = (*DefaultVisual (display.dpy, display.screen)).visualid;
	  display.cmap = XCreateColormap (display.dpy, display.win
				,DefaultVisual (display.dpy, display.screen)
	  /*      ,PseudoColor */
					  ,AllocNone);
	  if (me == 256 && depth != 24)
	    {
	      if (XAllocColorCells (display.dpy, display.cmap, 0
				    ,plane_masks, 0, colour_table, 256) != 0) {
		  /* printf ("Allocated 256 cells\n"); */
	      }
	      else {
		  printf ("Couldn't allocate 256 cells\n");
	      }
	    }
	  else
	    for (i = 0; i < 256; i++)
	      colour_table[i] = i;
	}
      if (!display.cmap)
	HandleError ("No default colour map", FATAL);
    }

  for (i = 0; i < 256; i++)
    flag[i] = 0;

  for (n = 0; n < 256; n++)
    {
      pal[n].red = inpal[n].red << 10;
      pal[n].green = inpal[n].green << 10;
      pal[n].blue = inpal[n].blue << 10;
      pal[n].flags = DoRed | DoGreen | DoBlue;
      if (writeable_p)
	pal[n].pixel = colour_table[n];
      else
	{
	  if (XAllocColor (display.dpy
			   ,display.cmap, &(pal[n])) == 0)
	    HandleError ("alloc colour failed"
			 ,FATAL);
	  colour_table[n] = pal[n].pixel;
	  XSetForeground (display.dpy
			  ,display.pixcolour_gc[n]
			  ,colour_table[n]);
	}
      flag[n] = 1;
    }

  if (writeable_p)
    {
      XStoreColors (display.dpy, display.cmap, pal, 256);
      XFlush (display.dpy);
    }
  XSetWindowColormap (display.dpy, display.win, display.cmap);
}
Exemplo n.º 15
0
Arquivo: stepgfx.c Projeto: att/uwin
/*
 ***********************************************************************
 * Allocates colors and fill a pixel value array. Color values are
 * truncated with RED_MASK, GREEN_MASK and BLUE_MASK
 *
 * from,to are the primary colors to use
 * maxcols is the number of colors
 * colors is the array of pixel values
 * light,dark are the colors for the relief
 * dr,dg,db are the increment values for the colors
 * alloc_relief if colors for relief should be allocated
 * incr - 0 if gradient is light to dark, 1 if dark to light
 ***********************************************************************
 */
int MakeColors(Display *dpy, Drawable d, int from[3], int to[3], int maxcols,
	       unsigned long *colors, unsigned long *dark,
	       unsigned long *light, int dr, int dg, int db,
	       int alloc_relief, int incr)
{
    float rv, gv, bv;
    float sr,sg,sb;
    int red, green, blue;
    XColor color;
    int i;

    sr = (float)dr / (float)maxcols;
    sg = (float)dg / (float)maxcols;
    sb = (float)db / (float)maxcols;
    rv = (float)from[0];
    gv = (float)from[1];
    bv = (float)from[2];
    /* kludge to frce color allocation in the first iteration on any case */
    color.red = (from[0] == 0) ? 0xffff : 0;
    color.green = 0;
    color.blue = 0;
    for(i = 0; i < maxcols; i++) {
	/* color allocation saver */
	red = ((short)rv) & RED_MASK;
	green = ((short)gv) & GREEN_MASK;
	blue = ((short)bv) & BLUE_MASK;
	if (color.red != red || color.green != green || color.blue != blue) {
	    color.red = red;
	    color.green = green;
	    color.blue = blue;
	    if (XAllocColor(dpy, DefaultColormap(dpy, DefaultScreen(dpy)),
			&color)==0) {
	        return 0;
	    }
	}
	colors[i] = color.pixel;
	rv += sr;
	gv += sg;
	bv += sb;
	if ((rv > 65535.0) || (rv < 0.0)) rv -= sr;
	if ((gv > 65535.0) || (gv < 0.0)) gv -= sg;
	if ((bv > 65535.0) || (bv < 0.0)) bv -= sb;
    }
    /* allocate 2 colors for the bevel */
    if (alloc_relief) {
	if (incr) {
	    rv = (float)from[0] * 0.8;
	    gv = (float)from[1] * 0.8;
	    bv = (float)from[2] * 0.8;
	} else {
	    rv = (float)to[0] * 0.8;
	    gv = (float)to[1] * 0.8;
	    bv = (float)to[2] * 0.8;
	}
	color.red = (unsigned short)(rv<0?0:rv);
    color.green = (unsigned short)(gv<0?0:gv);
	color.blue = (unsigned short)(bv<0?0:bv);
	if (XAllocColor(dpy, DefaultColormap(dpy, DefaultScreen(dpy)),&color))
	  *dark = color.pixel;
	else
	  *dark = colors[incr ? 0 : maxcols-1];

	if (incr) {
	    float avg;
	    avg = (float)(to[0]+to[1]+to[2])/3;
	    rv = avg + (float)(to[0]/2);
	    gv = avg + (float)(to[1]/2);
	    bv = avg + (float)(to[2]/2);
	} else {
            float avg;
	    avg = (float)(from[0]+from[1]+from[2])/3;
	    rv = avg + (float)(from[0]/2);
	    gv = avg + (float)(from[1]/2);
	    bv = avg + (float)(from[2]/2);
	}
	color.red = (unsigned short)(rv>65535.0 ? 65535.0:rv);
    color.green = (unsigned short)(gv>65535.0 ? 65535.0:gv);
	color.blue = (unsigned short)(bv>65535.0 ? 65535.0:bv);
	if (XAllocColor(dpy, DefaultColormap(dpy, DefaultScreen(dpy)),
			&color))
	  *light = color.pixel;
	else
	  *light = colors[incr ? maxcols-1 : 0];
    } else {
	*light = colors[incr ? maxcols-1 : 0];
	*dark = colors[incr ? 0 : maxcols-1];
    }
    return 1;
}
Exemplo n.º 16
0
static Bool InitializeAll(struct state *st)
{
  XGCValues xgcv;
  XWindowAttributes xgwa;
/*  XSetWindowAttributes xswa;*/
  Colormap cmap;
  XColor color;
  int n,i;
  double rspeed;

  st->cosilines = True;

  XGetWindowAttributes(st->dpy,st->win[0],&xgwa);
  cmap=xgwa.colormap;
/*  xswa.backing_store=Always;
  XChangeWindowAttributes(st->dpy,st->win[0],CWBackingStore,&xswa);*/
  xgcv.function=GXcopy;

  xgcv.foreground=get_pixel_resource (st->dpy, cmap, "background", "Background");
  st->fgc[32]=XCreateGC(st->dpy,st->win[0],GCForeground|GCFunction,&xgcv);

  n=0;
  if (mono_p)
    {
      st->fgc[0]=st->fgc[32];
      xgcv.foreground=get_pixel_resource (st->dpy, cmap, "foreground", "Foreground");
      st->fgc[1]=XCreateGC(st->dpy,st->win[0],GCForeground|GCFunction,&xgcv);
      for (i=0;i<32;i+=2) st->fgc[i]=st->fgc[0];
      for (i=1;i<32;i+=2) st->fgc[i]=st->fgc[1];
    } else
    for (i=0;i<32;i++)
      {
        color.red=colors[n++]<<8;
        color.green=colors[n++]<<8;
        color.blue=colors[n++]<<8;
        color.flags=DoRed|DoGreen|DoBlue;
        XAllocColor(st->dpy,cmap,&color);
        xgcv.foreground=color.pixel;
        st->fgc[i]=XCreateGC(st->dpy,st->win[0],GCForeground|GCFunction,&xgcv);
      }
  st->cgc=XCreateGC(st->dpy,st->win[0],GCForeground|GCFunction,&xgcv);
  XSetGraphicsExposures(st->dpy,st->cgc,False);

  st->cosilines = get_boolean_resource(st->dpy, "random","Boolean");

#ifdef HAVE_DOUBLE_BUFFER_EXTENSION
  if (get_boolean_resource (st->dpy, "useDBE", "Boolean"))
    st->usedouble = True;
  st->win[1] = xdbe_get_backbuffer (st->dpy, st->win[0], XdbeUndefined);
  if (!st->win[1])
    {
      st->usedouble = False;
      st->win[1] = st->win[0];
    }
#endif /* HAVE_DOUBLE_BUFFER_EXTENSION */

  st->delay=get_integer_resource(st->dpy, "delay","Integer");
  rspeed=get_float_resource(st->dpy, "speed","Float");
  if (rspeed<0.0001 || rspeed>0.2)
    {
      fprintf(stderr,"Speed not in valid range! (0.0001 - 0.2), using 0.1 \n");
      rspeed=0.1;
    }

  st->sizx=xgwa.width;
  st->sizy=xgwa.height;
  st->midx=st->sizx>>1;
  st->midy=st->sizy>>1;
  st->stateX=0;
  st->stateY=0;

  if (!make_rots(st,rspeed,rspeed))
    {
      fprintf(stderr,"Not enough memory for tables!\n");
      return False;
    }
  return True;
}
Exemplo n.º 17
0
int InitX() {
  XColor    xColor;
  Colormap  colormap;

  dpy = XOpenDisplay(NULL);
  if(dpy == NULL) {
    fprintf(stderr, "ERROR: Unable to open X display\n");
    return 1;
  }

  clrBlack = BlackPixel(dpy, DefaultScreen(dpy));
  clrWhite = WhitePixel(dpy, DefaultScreen(dpy));

  colormap = DefaultColormap(dpy, DefaultScreen(dpy));
  XParseColor(dpy, colormap, "red", &xColor);
  XAllocColor(dpy, colormap, &xColor);
  clrRed = xColor.pixel;

  XParseColor(dpy, colormap, "blue", &xColor);
  XAllocColor(dpy, colormap, &xColor);
  clrBlue = xColor.pixel;

  XParseColor(dpy, colormap, "orange", &xColor);
  XAllocColor(dpy, colormap, &xColor);
  clrOrange = xColor.pixel;

  wmDeleteMessage = XInternAtom(dpy, "WM_DELETE_WINDOW", False);

  // Create the window
  win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 
			    400, 300, 8, clrBlack, clrWhite);

  XSetWMProtocols(dpy, win, &wmDeleteMessage, 1);
  XSelectInput(dpy, win, StructureNotifyMask | ExposureMask | KeyPressMask);

  XGCValues    values;
  XFontStruct *font;

  font = XLoadQueryFont(dpy, "fixed");
  if(!font) {
    fprintf(stderr, "No fixed font?\n");
    return 2;
  }
  
  values.line_width = 1;
  values.line_style = LineSolid;
  values.font = font->fid;
  gc = XCreateGC(dpy, win, GCLineWidth|GCLineStyle|GCFont,
		 &values);

  XStoreName(dpy, win, "xtemp");
  
  // Map the window (that is, make it appear on the screen)
  XMapWindow(dpy, win);

  // Tell the GC we draw using black on white
  XSetForeground(dpy, gc, clrBlack);
  XSetBackground(dpy, gc, clrWhite);

  // Wait for the MapNotify event
  for(;;) {
    XEvent e;
    XNextEvent(dpy, &e);
    if (e.type == MapNotify)
      break;
  }

  return 0;
}
Exemplo n.º 18
0
int main (int argc, char **argv) {
	Cursor cursor;
	Display *display;
	Window root, blub, *blubs = NULL;
	unsigned clients;
	unsigned long pixel;
	char *cname;
	XColor color;
	int cnt;
	Atom prop;
	Pixmap save_pixmap = (Pixmap)None;

	display = XOpenDisplay(NULL);
	if(!display) return 1;

	cname = argc == 2 ? argv[1] : "black";

	screen = DefaultScreen(display);
	root = RootWindow(display, screen);
	pixel = BlackPixel(display, screen);

	if(XParseColor(display, DefaultColormap(display, screen), cname, &color)) {
	if(XAllocColor(display, DefaultColormap(display, screen), &color)) {
		pixel = color.pixel;
	}
	}

	XSetWindowBackground(display, root, pixel);
	XClearWindow(display, root);
	cursor = CreateCursorFromName(display,"watch");
	if (cursor) {
		XDefineCursor (display, root, cursor);
		XFreeCursor (display, cursor);
	}
	
	if (fork() == 0) {
		Window win;
		XEvent xev;

		close(0); close(1); close(2);
		chdir("/");

		display = XOpenDisplay(NULL);

		// open a client...
		if (display) {
			win = XCreateSimpleWindow (
				display, root, 0, 0, 1, 1, 0, 0, pixel
			);
			XSync(display, False);
		}
		// wait within event loop...
		for(;;) XNextEvent(display, &xev);
	}

	// wait until the child has opened a client
	cnt = 100;
	do {
	if (!XQueryTree (display, root, &blub, &blub, &blubs, &clients)) {
		XCloseDisplay(display);
		return 0;
	}
	usleep(50000);
	} while(clients < 1 && cnt--);

	save_pixmap = XCreatePixmap (display, root, 1, 1, 1);
	prop = XInternAtom (display, "_XSETROOT_ID", False);
	XChangeProperty (
		display, root, prop, XA_PIXMAP, 32, 
		PropModeReplace, (unsigned char *) &save_pixmap, 1
	);
	XSetCloseDownMode (display, RetainPermanent);

	// enable accessX
	// XAccess (display,NULL);
	XCloseDisplay(display);

	RunWindowManager();
	return 0;
}
Exemplo n.º 19
0
void init_red() {
    red_gc = XCreateGC(dis, win, 0, 0);
    XParseColor(dis, colormap, red, &red_col);
    XAllocColor(dis, colormap, &red_col);
    XSetForeground(dis, red_gc, red_col.pixel);
}
Exemplo n.º 20
0
int Init_X (int swidth, int sheight)
{
    XGCValues vals;
    Colormap TheColormap;
    XColor TheColor;
    int i;

    TheWidth = swidth ;
    TheHeight = sheight ;


    TheDisplay = XOpenDisplay("\0");
    TheRootWindow = DefaultRootWindow(TheDisplay);
    TheScreenNumber = DefaultScreen(TheDisplay); 
    TheDepth = DefaultDepth(TheDisplay, TheScreenNumber);
    if (TheDepth != 24) {
      printf("24 bit color not supported.\n") ;
      printf("Color function not likely to work.\n") ;
    }
    TheWindow = XCreateSimpleWindow(TheDisplay, TheRootWindow,
                        0, 0, TheWidth, TheHeight, 0, 0, 0);

    if (!TheWindow) return 0 ;

    ThePixmap = XCreatePixmap(TheDisplay, TheRootWindow, TheWidth, TheHeight, 
				TheDepth);

    if (!ThePixmap) return 0 ;

    TheDrawable = ThePixmap;

    
    XMapWindow(TheDisplay, TheWindow);
    XSelectInput(TheDisplay, TheWindow, ExposureMask |
					StructureNotifyMask |
					PointerMotionMask | 
					ButtonPressMask |
					KeyPressMask );




    /*
    TheWindowContext = XCreateGC(TheDisplay, TheWindow, 0, 0);
    // this is a bad idea ... see test t02.c for an example
    // of what can happen to the behavior of the event handler,
    //       int Handle_Events_X(int *px, int *py)
    // if you do this, you'll get runaway calls to Handle_Events
    // with the default condition being met and this produces
    // a great deal of tearing in the animation of t02.c
    */




    /* also a bad idea...same behavior as above
    vals.graphics_exposures = 1; // True
    */

    // so this is what you want :
    vals.graphics_exposures = 0; // False
    TheWindowContext = XCreateGC(TheDisplay, TheWindow,
                                 GCGraphicsExposures, &vals);
    if (!TheWindowContext) return 0;


    ThePixmapContext = XCreateGC(TheDisplay, ThePixmap, 0, 0);
    if (!ThePixmapContext) return 0;


    TheColormap = DefaultColormap(TheDisplay, TheScreenNumber);
    for(i = 0; i < 256; i++) {
	TheColor.green = TheColor.blue = TheColor.red = (i << 8) | i;
	TheColor.flags = DoRed | DoGreen | DoBlue;
	XAllocColor(TheDisplay, TheColormap, &TheColor);
	Grays[i] = TheColor.pixel;
    }
 

    TheFontInfo = XLoadQueryFont(TheDisplay, TheFont) ;
    XSetFont(TheDisplay, TheWindowContext, TheFontInfo->fid) ;




    //   XClearWindow(TheDisplay, TheWindow);
    //   XClearArea(TheDisplay, TheWindow, 0,0,0,0,False); // same as above
    XClearArea(TheDisplay, TheWindow, 0,0,0,0,True); 
                  // Does the boolean matter here?


    // most people expect a white piece of paper
    // with a black pencil
    Set_Color_Rgb_X (255,255,255) ; // white
    Clear_Buffer_X() ; // otherwise you can inherit garbage
    // from the parent window

    //    Set_Color_Rgb_X (255,0,255) ; // purple
    //    Fill_Rectangle_X(10,10,50,80) ;
    // above was just a test

    Copy_Buffer_X() ;
    XFlush(TheDisplay);  

    // XSync(TheDisplay, False) ; // seems unnecessary

    Set_Color_Rgb_X (0,0,0) ; // black pencil
    return 1 ;
}
Exemplo n.º 21
0
dsxc_lutcol (void)

/* C-- */
{
    int   k, ka, kdiv;
    Status istat;
    unsigned short int c;
    char flags;
    /* Cbegin */


    DSOPEN = F77_NAMED_COMMON(ds_genb).dsopen;
    PDSOPEN = F77_NAMED_COMMON(ds_panelb).pdsopen;
    NUMDDCOL = F77_NAMED_COMMON(lutacom).numddcol;

    flags = DoRed | DoGreen | DoBlue;

    if ( DSOPEN || PDSOPEN ) {

        (void) dsxc_lutvget();

        if ( OWNCOL ) {

            kdiv = LVX/NUMDDCOL;
            for ( k = 15; k<15+LVX; k++ ) {
                ka = 15 + ((k-15)/kdiv);
                COLOUR[ka].pixel = PC_ID[ka];
                COLOUR[ka].flags = flags;
                c = LUTC_VAL[(k-15)][0]*65535.0;
                COLOUR[ka].red = c;
                c = LUTC_VAL[(k-15)][1]*65535.0;
                COLOUR[ka].green = c;
                c = LUTC_VAL[(k-15)][2]*65535.0;
                COLOUR[ka].blue = c;
            }

            XStoreColors ( VD_ID, CM_ID, COLOUR, 15+NUMDDCOL );
            XInstallColormap ( VD_ID, CM_ID );
            XFlush ( VD_ID );

        }
        else {

            for (k = 15; k<15+LVX; k++ ) {
                COLOUR[k].flags = flags;
                c = LUTC_VAL[(k-15)][0]*65535.0;
                COLOUR[k].red = c;
                c = LUTC_VAL[(k-15)][1]*65535.0;
                COLOUR[k].green = c;
                c = LUTC_VAL[(k-15)][2]*65535.0;
                COLOUR[k].blue = c;
                istat = XAllocColor ( VD_ID, CM_ID, &COLOUR[k] );
                if ( istat==0 ) {
                    (void) c_printo ( "ERROR,x_lut: Colour pixel not allocated" );
                    PC_ID[k] = 0;
                }
                else
                    PC_ID[k] = COLOUR[k].pixel;
            }
            XFlush ( VD_ID );

        }

    }

}
Exemplo n.º 22
0
static Bool
GradientLoader(XawParams *params, Screen *screen, Colormap colormap, int depth,
	       Pixmap *pixmap_return, Pixmap *mask_return,
	       Dimension *width_return, Dimension *height_return)
{
  double ired, igreen, iblue, red, green, blue;
  XColor start, end, color;
  XGCValues values;
  GC gc;
  double i, inc, x, y, xend, yend;
  Pixmap pixmap;
  XawArgVal *argval;
  int orientation, dimension, steps;
  char *value;

  if (XmuCompareISOLatin1(params->name, "vertical") == 0)
    orientation = VERTICAL;
  else if (XmuCompareISOLatin1(params->name, "horizontal") == 0)
    orientation = HORIZONTAL;
  else
    return (False);

  if ((argval = XawFindArgVal(params, "dimension")) != NULL
      && argval->value)
    {
      dimension = atoi(argval->value);
      if (dimension <= 0)
	return (False);
    }
  else
    dimension = 50;

  if ((argval = XawFindArgVal(params, "steps")) != NULL
      && argval->value)
    {
      steps = atoi(argval->value);
      if (steps <= 0)
	return (False);
    }
  else
      steps = dimension;

  steps = XawMin(steps, dimension);

  value = NULL;
  if ((argval = XawFindArgVal(params, "start")) != NULL)
    value = argval->value;
  if (value && !XAllocNamedColor(DisplayOfScreen(screen), colormap, value,
			    &start, &color))
    return (False);
  else if (!value)
    {
      start.pixel = WhitePixelOfScreen(screen);
      XQueryColor(DisplayOfScreen(screen), colormap, &start);
    }
  value = NULL;
  if ((argval = XawFindArgVal(params, "end")) != NULL)
    value = argval->value;
  if (value && !XAllocNamedColor(DisplayOfScreen(screen), colormap, value,
			    &end, &color))
    return (False);
  else if (!value)
    {
      end.pixel = BlackPixelOfScreen(screen);
      XQueryColor(DisplayOfScreen(screen), colormap, &end);
    }

  if ((pixmap = XCreatePixmap(DisplayOfScreen(screen),
			      RootWindowOfScreen(screen),
			      orientation == VERTICAL ? 1 : dimension,
			      orientation == VERTICAL ? dimension : 1, depth))
      == 0)
    return (False);

  ired   = (double)(end.red   - start.red)   / (double)steps;
  igreen = (double)(end.green - start.green) / (double)steps;
  iblue  = (double)(end.blue  - start.blue)  / (double)steps;

  red   = color.red   = start.red;
  green = color.green = start.green;
  blue  = color.blue  = start.blue;

  inc = (double)dimension / (double)steps;

  gc = XCreateGC(DisplayOfScreen(screen), pixmap, 0, &values);

  x = y = 0.0;
  if (orientation == VERTICAL)
    {
      xend = 1;
      yend = 0;
    }
  else
    {
      xend = 0;
      yend = 1;
    }

  color.flags = DoRed | DoGreen | DoBlue;

  XSetForeground(DisplayOfScreen(screen), gc, start.pixel);
  for (i = 0.0; i < dimension; i += inc)
    {
      if ((int)color.red != (int)red || (int)color.green != (int)green
	  || (int)color.blue != (int)blue)
	{
	  XFillRectangle(DisplayOfScreen(screen), pixmap, gc, (int)x, (int)y,
			 (unsigned int)xend, (unsigned int)yend);
	  color.red   = (unsigned short)red;
	  color.green = (unsigned short)green;
	  color.blue  = (unsigned short)blue;
	  if (!XAllocColor(DisplayOfScreen(screen), colormap, &color))
	    {
	      XFreePixmap(DisplayOfScreen(screen), pixmap);
	      return (False);
	    }
	  XSetForeground(DisplayOfScreen(screen), gc, color.pixel);
	  if (orientation == VERTICAL)
	    y = yend;
	  else
	    x = xend;
	}
      red   += ired;
      green += igreen;
      blue  += iblue;
      if (orientation == VERTICAL)
	yend += inc;
      else
	xend += inc;
    }
  XFillRectangle(DisplayOfScreen(screen), pixmap, gc, (int)x, (int)y,
		 (unsigned int)xend, (unsigned int)yend);

  *pixmap_return = pixmap;
  *mask_return = None;
  *width_return = orientation == VERTICAL ? 1 : dimension;
  *height_return = orientation == VERTICAL ? dimension : 1;

  XFreeGC(DisplayOfScreen(screen), gc);

  return (True);
}
Exemplo n.º 23
0
WTexSolid *wTextureMakeSolid(WScreen * scr, XColor * color)
{
	WTexSolid *texture;
	int gcm;
	XGCValues gcv;

	texture = wmalloc(sizeof(WTexture));

	texture->type = WTEX_SOLID;
	texture->subtype = 0;

	XAllocColor(dpy, scr->w_colormap, color);
	texture->normal = *color;
	if (color->red == 0 && color->blue == 0 && color->green == 0) {
		texture->light.red = 0xb6da;
		texture->light.green = 0xb6da;
		texture->light.blue = 0xb6da;
		texture->dim.red = 0x6185;
		texture->dim.green = 0x6185;
		texture->dim.blue = 0x6185;
	} else {
		RColor rgb;
		RHSVColor hsv, hsv2;
		int v;

		rgb.red = color->red >> 8;
		rgb.green = color->green >> 8;
		rgb.blue = color->blue >> 8;
		RRGBtoHSV(&rgb, &hsv);
		RHSVtoRGB(&hsv, &rgb);
		hsv2 = hsv;

		v = hsv.value * 16 / 10;
		hsv.value = (v > 255 ? 255 : v);
		RHSVtoRGB(&hsv, &rgb);
		texture->light.red = rgb.red << 8;
		texture->light.green = rgb.green << 8;
		texture->light.blue = rgb.blue << 8;

		hsv2.value = hsv2.value / 2;
		RHSVtoRGB(&hsv2, &rgb);
		texture->dim.red = rgb.red << 8;
		texture->dim.green = rgb.green << 8;
		texture->dim.blue = rgb.blue << 8;
	}
	texture->dark.red = 0;
	texture->dark.green = 0;
	texture->dark.blue = 0;
	XAllocColor(dpy, scr->w_colormap, &texture->light);
	XAllocColor(dpy, scr->w_colormap, &texture->dim);
	XAllocColor(dpy, scr->w_colormap, &texture->dark);

	gcm = GCForeground | GCBackground | GCGraphicsExposures;
	gcv.graphics_exposures = False;

	gcv.background = gcv.foreground = texture->light.pixel;
	texture->light_gc = XCreateGC(dpy, scr->w_win, gcm, &gcv);

	gcv.background = gcv.foreground = texture->dim.pixel;
	texture->dim_gc = XCreateGC(dpy, scr->w_win, gcm, &gcv);

	gcv.background = gcv.foreground = texture->dark.pixel;
	texture->dark_gc = XCreateGC(dpy, scr->w_win, gcm, &gcv);

	gcv.background = gcv.foreground = color->pixel;
	texture->normal_gc = XCreateGC(dpy, scr->w_win, gcm, &gcv);

	return texture;
}
Exemplo n.º 24
0
GuiCalibratorX11::GuiCalibratorX11(Calibrator* calibrator0)
  : calibrator(calibrator0), time_elapsed(0)
{
    display = XOpenDisplay(NULL);
    if (display == NULL) {
        throw std::runtime_error("Unable to connect to X server");
    }
    screen_num = DefaultScreen(display);
    // Load font and get font information structure
    font_info = XLoadQueryFont(display, "9x15");
    if (font_info == NULL) {
        // fall back to native font
        font_info = XLoadQueryFont(display, "fixed");
        if (font_info == NULL) {
            XCloseDisplay(display);
            throw std::runtime_error("Unable to open neither '9x15' nor 'fixed' font");
        }
    }

#ifdef HAVE_X11_XRANDR
    // get screensize from xrandr
    int nsizes;
    XRRScreenSize* randrsize = XRRSizes(display, screen_num, &nsizes);
    if (nsizes != 0) {
        set_display_size(randrsize->width, randrsize->height);
    } else {
        set_display_size(DisplayWidth(display, screen_num),
                         DisplayHeight(display, screen_num));
    }
# else
    set_display_size(DisplayWidth(display, screen_num),
                     DisplayHeight(display, screen_num));
#endif

    // Register events on the window
    XSetWindowAttributes attributes;
    attributes.override_redirect = True;
    attributes.event_mask = ExposureMask | KeyPressMask | ButtonPressMask;

    win = XCreateWindow(display, RootWindow(display, screen_num),
                0, 0, display_width, display_height, 0,
                CopyFromParent, InputOutput, CopyFromParent,
                CWOverrideRedirect | CWEventMask,
                &attributes);
    XMapWindow(display, win);

    // Listen to events
    XGrabKeyboard(display, win, False, GrabModeAsync, GrabModeAsync,
                CurrentTime);
    calib_input = calibrator->register_events();
    if (!calib_input) {
            XGrabPointer(display, win, False, ButtonPressMask, GrabModeAsync,
                GrabModeAsync, None, None, CurrentTime);
    }

    Colormap colormap = DefaultColormap(display, screen_num);
    XColor color;
    for (int i = 0; i != nr_colors; i++) {
        XParseColor(display, colormap, colors[i], &color);
        XAllocColor(display, colormap, &color);
        pixel[i] = color.pixel;
    }
    XSetWindowBackground(display, win, pixel[GRAY]);
    XClearWindow(display, win);

    gc = XCreateGC(display, win, 0, NULL);
    XSetFont(display, gc, font_info->fid);

    // Setup timer for animation
    signal(SIGALRM, sigalarm_handler);
    struct itimerval timer;
    timer.it_value.tv_sec = time_step/1000;
    timer.it_value.tv_usec = (time_step % 1000) * 1000;
    timer.it_interval = timer.it_value;
    setitimer(ITIMER_REAL, &timer, NULL);
}
Exemplo n.º 25
0
// #includ ur #life
int main(int argc, char *argv[]) {
  bool q = false;
  if(argv[1] != NULL && strcmp(argv[1], "-q") == 0) q=true;
  Display *disp;
  Window win;
  XEvent e;
  int screen;
  int winy = 0;
  int winx = 0;
  int winheight = 300;
  int winwidth = 500;
  int borderwidth = 10;
  int stdcposx = 20;
  int stdcposy = 20;
  int cposx = stdcposx;
  int cposy = stdcposy;
  int lastdeltime = 0;
  int lastrowlength = 0;
  int lastkeysym = 0;
  char *msg = "Clear";
  int bwidth=strlen(msg)*6;
  int bheight=15;
  int btop=20;
  int bmargin = 2;
  int bleft=winwidth - bwidth - 20;
  GC white;
  XColor white_color;
  Colormap colormap;
  char whiteidk[] = "#FFFFFF";
  GC red;
  XColor red_color;
  Colormap rcolormap;
  char redidk[] = "#FF0000";

  disp = XOpenDisplay(NULL);
  if (disp == NULL) {
    fprintf(stderr, "Cannot open display\n");
    exit(1);
  }

  screen = DefaultScreen(disp);
  win = XCreateSimpleWindow(disp, RootWindow(disp, screen), winx, winy, winwidth, winheight, borderwidth,
  BlackPixel(disp, screen), WhitePixel(disp, screen));
  XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask);
  // Window XCreateWindow(display, parent, x, y, width, height, border_width, depth,
  //                    class, visual, valuemask, attributes)
  XMapWindow(disp, win);
  colormap = DefaultColormap(disp, 0);
  white = XCreateGC(disp, win, 0, 0);
  XParseColor(disp, colormap, whiteidk, &white_color);
  XAllocColor(disp, colormap, &white_color);
  XSetForeground(disp, white, white_color.pixel);
  rcolormap = DefaultColormap(disp, 0);
  red = XCreateGC(disp, win, 0, 0);
  XParseColor(disp, colormap, redidk, &red_color);
  XAllocColor(disp, colormap, &red_color);
  XSetForeground(disp, red, red_color.pixel);
  while (1) {
    XNextEvent(disp, &e);
    if (e.type == Expose)
      {
        XFillRectangle(disp, win, red, bleft, btop, bwidth, bheight);
        XDrawString(disp, win, white, bleft+bmargin, btop+bmargin+9, msg, strlen(msg));
        //http://tronche.com/gui/x/xlib/graphics/drawing-text/XDrawString.html
      }
      if(e.type == 4) // button press
        {
          int x=e.xbutton.x;
          int y=e.xbutton.y;
          int button = e.xbutton.button;
          if(!q) printf("Button pressed. X: %d, Y: %d Button: %d\n",x,y,button);
          if(button == 1)
            {
              if(y < bheight+btop && x < bwidth+bleft)
                {
                  if(y > btop && x > bleft)
                    {
                      if(!q) printf("You've hitten the button!!\nClearing...\n");
                      XFillRectangle(disp, win, white, 0, 0, winwidth, winheight);
                      cposx = stdcposx;
                      cposy = stdcposy;
                      if(!q) printf("Repainting clearbutton...\n");
                      XFillRectangle(disp, win, red, bleft, btop, bwidth, bheight);
                      XDrawString(disp, win, white, bleft+bmargin, btop+bmargin+9, msg, strlen(msg));
                    }
                  }
                }
              }
              if (e.type == KeyPress)
                {
                  if(!q) printf("Keycode: %d\n", e.xkey.keycode);
                  unsigned long keysym = XLookupKeysym(&e.xkey, 0);
                  if(!q) printf("Keysym: %lu\n",keysym);
                  char *ascii = XKeysymToString(keysym);
                  if(!q) printf("ASCII: %s\n",ascii);
                  if(keysym == 65307 && lastkeysym == 65406) // alt+ESC
                    {
                      printf("Exiting...\n");
                      return 0;
                    }
                    else if(keysym == 65293) // line break
                    {
                      cposy+=10;
                      lastrowlength = cposx;
                      cposx = stdcposx;
                    }
                    else if(keysym == 32) // " "
                    {
                      cposx+=6;
                    }
                    else if(keysym == 65288) // delete
                    {
                      time_t now = time(0);
                      if(!q) printf("Time: %ld\n",now);
                      int diff = now-lastdeltime;
                      if(!q) printf("Time since last deletion: %d\n",diff);
                      XFillRectangle(disp, win, white, cposx-6, cposy-9, 6, 11);
                      if(diff == 0)
                        {
                          XFillRectangle(disp, win, white, cposx-12, cposy-9, 6, 11);
                        }
                        lastdeltime = now;
                        if(cposx <= stdcposx)
                          {
                            if(cposy != stdcposy)
                              {
                                cposy-=10;
                                cposx = lastrowlength;
                              }
                            }
                            else
                              {
                                cposx-=6;
                                if(diff == 0 && cposx-6 > stdcposx)
                                  {
                                    cposx-=6;
                                  }
                                }
                              }
                              else if(keysym == 43) // plus
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "+", 1);
                                cposx+=6;
                              }
                              else if(keysym == 44) // comma
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ",", 1);
                                cposx+=6;
                              }
                              else if(keysym == 45) // minus
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "-", 1);
                                cposx+=6;
                              }
                              else if(keysym == 46) // period
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ".", 1);
                                cposx+=6;
                              }
                              else if(keysym == 65289) // tab
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "   ", 3);
                                cposx+=18;
                              }
                              else
                                {
                                  if(lastkeysym != 65506 || lastkeysym != 65505)
                                    {
                                      if(keysym == 49)
                                        {
                                          ascii = "!";
                                        }
                                        else if(keysym == 43)
                                        {
                                          ascii = "?";
                                        }
                                      }
                                      if(keysym != 65506 && keysym != 65505)
                                        {
                                          XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ascii, strlen(ascii));
                                          cposx+=strlen(ascii)*6;
                                        }
                                      }
                                      lastkeysym = keysym;
                                    }
                                  }
                                  XCloseDisplay(disp);
                                  return 0;
                                }
Exemplo n.º 26
0
Arquivo: slock.c Projeto: 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;
}
Exemplo n.º 27
0
void
init_tik_tak(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	int         i, max_objects, size_object;
	tik_takstruct *tiktak;

/* initialize */
	if (tik_taks == NULL) {
		if ((tik_taks = (tik_takstruct *) calloc(MI_NUM_SCREENS(mi),
				sizeof (tik_takstruct))) == NULL)
			return;
	}
	tiktak = &tik_taks[MI_SCREEN(mi)];
	tiktak->mi = mi;

	if (tiktak->gc == None) {
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			XColor      color;

#ifndef STANDALONE
			tiktak->fg = MI_FG_PIXEL(mi);
			tiktak->bg = MI_BG_PIXEL(mi);
#endif
			tiktak->blackpixel = MI_BLACK_PIXEL(mi);
			tiktak->whitepixel = MI_WHITE_PIXEL(mi);
			if ((tiktak->cmap = XCreateColormap(display, window,
					MI_VISUAL(mi), AllocNone)) == None) {
				free_tik_tak(display, tiktak);
				return;
			}
			XSetWindowColormap(display, window, tiktak->cmap);
			(void) XParseColor(display, tiktak->cmap, "black", &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_BLACK_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, tiktak->cmap, "white", &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_WHITE_PIXEL(mi) = color.pixel;
#ifndef STANDALONE
			(void) XParseColor(display, tiktak->cmap, background, &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_BG_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, tiktak->cmap, foreground, &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_FG_PIXEL(mi) = color.pixel;
#endif
			tiktak->colors = (XColor *) NULL;
			tiktak->ncolors = 0;
		}
		if ((tiktak->gc = XCreateGC(display, MI_WINDOW(mi),
			     (unsigned long) 0, (XGCValues *) NULL)) == None) {
			free_tik_tak(display, tiktak);
			return;
		}
	}
/* Clear Display */
	MI_CLEARWINDOW(mi);
	tiktak->painted = False;
	XSetFunction(display, tiktak->gc, GXxor);


/*Set up tik_tak data */
	tiktak->direction = (LRAND() & 1) ? 1 : -1;
	tiktak->win_width = MI_WIDTH(mi);
	tiktak->win_height = MI_HEIGHT(mi);
	tiktak->num_object = MI_COUNT(mi);
        tiktak->x0 = tiktak->win_width / 2;
        tiktak->y0 = tiktak->win_height / 2;
	max_objects = MI_COUNT(mi);
	if (tiktak->num_object == 0) {
		tiktak->num_object = DEF_NUM_OBJECT;
		max_objects = DEF_NUM_OBJECT;
	} else if (tiktak->num_object < 0) {
		max_objects = -tiktak->num_object;
		tiktak->num_object = NRAND(-tiktak->num_object) + 1;
	}
	if (tiktak->object == NULL)
		if ((tiktak->object = (tik_takobject *) calloc(max_objects,
				sizeof (tik_takobject))) == NULL) {
			free_tik_tak(display, tiktak);
			return;
		}
	size_object = MIN( tiktak->win_width , tiktak->win_height) / 3;
	if ( abs( MI_SIZE(mi) ) > size_object) {
	   if ( MI_SIZE( mi ) < 0 )
	     {
		size_object = -size_object;
	     }
	}
   else
     {
	size_object = MI_SIZE(mi);
     }
	if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
/* Set up colour map */
		if (tiktak->colors != NULL) {
			if (tiktak->ncolors && !tiktak->no_colors)
				free_colors(display, tiktak->cmap, tiktak->colors, tiktak->ncolors);
			free(tiktak->colors);
			tiktak->colors = (XColor *) NULL;
		}
		tiktak->ncolors = MI_NCOLORS(mi);
		if (tiktak->ncolors < 2)
			tiktak->ncolors = 2;
		if (tiktak->ncolors <= 2)
			tiktak->mono_p = True;
		else
			tiktak->mono_p = False;

		if (tiktak->mono_p)
			tiktak->colors = (XColor *) NULL;
		else
			if ((tiktak->colors = (XColor *) malloc(sizeof (*tiktak->colors) *
					(tiktak->ncolors + 1))) == NULL) {
				free_tik_tak(display, tiktak);
				return;
			}
		tiktak->cycle_p = has_writable_cells(mi);
		if (tiktak->cycle_p) {
			if (MI_IS_FULLRANDOM(mi)) {
				if (!NRAND(8))
					tiktak->cycle_p = False;
				else
					tiktak->cycle_p = True;
			} else {
				tiktak->cycle_p = cycle_p;
			}
		}
		if (!tiktak->mono_p) {
			if (!(LRAND() % 10))
				make_random_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
						tiktak->cmap, tiktak->colors, &tiktak->ncolors,
						True, True, &tiktak->cycle_p);
			else if (!(LRAND() % 2))
				make_uniform_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
                  tiktak->cmap, tiktak->colors, &tiktak->ncolors,
						      True, &tiktak->cycle_p);
			else
				make_smooth_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
                 tiktak->cmap, tiktak->colors, &tiktak->ncolors,
						     True, &tiktak->cycle_p);
		}
		XInstallColormap(display, tiktak->cmap);
		if (tiktak->ncolors < 2) {
			tiktak->ncolors = 2;
			tiktak->no_colors = True;
		} else
			tiktak->no_colors = False;
		if (tiktak->ncolors <= 2)
			tiktak->mono_p = True;

		if (tiktak->mono_p)
			tiktak->cycle_p = False;

	}
	for (i = 0; i < tiktak->num_object; i++) {
		tik_takobject *object0;

		object0 = &tiktak->object[i];
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			if (tiktak->ncolors > 2)
				object0->colour = NRAND(tiktak->ncolors - 2) + 2;
			else
				object0->colour = 1;	/* Just in case */
			XSetForeground(display, tiktak->gc, tiktak->colors[object0->colour].pixel);
		} else {
			if (MI_NPIXELS(mi) > 2)
				object0->colour = MI_PIXEL(mi, NRAND(MI_NPIXELS(mi)));
			else
				object0->colour = 1;	/*Xor'red so WHITE may not be appropriate */
			XSetForeground(display, tiktak->gc, object0->colour);
		}
		object0->angle = NRAND(90) * PI_RAD;
		object0->angle1 = NRAND(90) * PI_RAD;
		object0->velocity_a = (NRAND(7) - 3) * PI_RAD;
		object0->velocity_a1 = (NRAND(7) - 3) * PI_RAD;
		if (size_object == 0)
			object0->size_ob = 9;
		else if (size_object > 0)
			object0->size_ob = size_object;
		else
			object0->size_ob = NRAND(-size_object) + 1;
		object0->size_ob++;
		object0->num_point = NRAND(6)+3;
	   if (LRAND() & 1)
	     object0->size_mult = 1.0;
	   else
	     {
		object0->num_point *= 2;
		object0->size_mult = 1.0 - ( 1.0 / (float) ((LRAND() & 1) +
							    2 ) );
	     }
	   if (object0->xy != NULL)
			free(object0->xy);
	   if ((object0->xy = (XPoint *) malloc(sizeof( XPoint ) *
				(2 * object0->num_point + 2))) == NULL) {
			free_tik_tak(display, tiktak);
			return;
		}
	   if ((LRAND() & 1) || object0->size_ob < 10 )
	     {
		object0->inner = False;
		if ( object0->xy1 != NULL ) free( object0->xy1 );
		object0->xy1 = (XPoint *) NULL;
	     }
	   else
	     {
		object0->inner = True;
	        object0->size_ob1 = object0->size_ob -
		  NRAND( object0->size_ob / 5 ) - 1;
		object0->num_point1 = NRAND(6)+3;
		if (LRAND() & 1)
		  object0->size_mult1 = 1.0;
		else
		  {
		     object0->num_point1 *= 2;
		     object0->size_mult1 = 1.0 -
		        ( 1.0 / (float) ((LRAND() & 1) + 2 ) );
		  }
		if (object0->xy1 != NULL)
			free(object0->xy1);
		if ((object0->xy1 = (XPoint *) malloc(sizeof( XPoint ) *
				(2 * object0->num_point1 + 2))) == NULL) {
			free_tik_tak(display, tiktak);
			return;
		}
		object0->size_mult1 = 1.0;
	     }
		tik_tak_setupobject( mi , object0);
		tik_tak_reset_object( object0);
		tik_tak_drawobject(mi, object0 );
	}
	XFlush(display);
	XSetFunction(display, tiktak->gc, GXcopy);
}
Exemplo n.º 28
0
static BackgroundTexture *parseTexture(RContext * rc, char *text)
{
	BackgroundTexture *texture = NULL;
	WMPropList *texarray;
	WMPropList *val;
	int count;
	char *tmp;
	char *type;

#define GETSTRORGOTO(val, str, i, label) \
    val = WMGetFromPLArray(texarray, i);\
    if (!WMIsPLString(val)) {\
    wwarning("could not parse texture %s", text);\
    goto label;\
    }\
    str = WMGetFromPLString(val)

	texarray = WMCreatePropListFromDescription(text);
	if (!texarray || !WMIsPLArray(texarray)
	    || (count = WMGetPropListItemCount(texarray)) < 2) {

		wwarning("could not parse texture %s", text);
		if (texarray)
			WMReleasePropList(texarray);
		return NULL;
	}

	texture = wmalloc(sizeof(BackgroundTexture));

	GETSTRORGOTO(val, type, 0, error);

	if (strcasecmp(type, "solid") == 0) {
		XColor color;
		Pixmap pixmap;

		texture->solid = 1;

		GETSTRORGOTO(val, tmp, 1, error);

		if (!XParseColor(dpy, DefaultColormap(dpy, scr), tmp, &color)) {
			wwarning("could not parse color %s in texture %s", tmp, text);
			goto error;
		}
		XAllocColor(dpy, DefaultColormap(dpy, scr), &color);

		pixmap = XCreatePixmap(dpy, root, 8, 8, DefaultDepth(dpy, scr));
		XSetForeground(dpy, DefaultGC(dpy, scr), color.pixel);
		XFillRectangle(dpy, pixmap, DefaultGC(dpy, scr), 0, 0, 8, 8);

		texture->pixmap = pixmap;
		texture->color = color;
		texture->width = 8;
		texture->height = 8;
	} else if (strcasecmp(type, "vgradient") == 0
		   || strcasecmp(type, "dgradient") == 0 || strcasecmp(type, "hgradient") == 0) {
		XColor color;
		RColor color1, color2;
		RImage *image;
		Pixmap pixmap;
		RGradientStyle gtype;
		int iwidth, iheight;

		GETSTRORGOTO(val, tmp, 1, error);

		if (!XParseColor(dpy, DefaultColormap(dpy, scr), tmp, &color)) {
			wwarning("could not parse color %s in texture %s", tmp, text);
			goto error;
		}

		color1.red = color.red >> 8;
		color1.green = color.green >> 8;
		color1.blue = color.blue >> 8;

		GETSTRORGOTO(val, tmp, 2, error);

		if (!XParseColor(dpy, DefaultColormap(dpy, scr), tmp, &color)) {
			wwarning("could not parse color %s in texture %s", tmp, text);
			goto error;
		}

		color2.red = color.red >> 8;
		color2.green = color.green >> 8;
		color2.blue = color.blue >> 8;

		switch (type[0]) {
		case 'h':
		case 'H':
			gtype = RHorizontalGradient;
			iwidth = scrWidth;
			iheight = 32;
			break;
		case 'V':
		case 'v':
			gtype = RVerticalGradient;
			iwidth = 32;
			iheight = scrHeight;
			break;
		default:
			gtype = RDiagonalGradient;
			iwidth = scrWidth;
			iheight = scrHeight;
			break;
		}

		image = RRenderGradient(iwidth, iheight, &color1, &color2, gtype);

		if (!image) {
			wwarning("could not render gradient texture:%s", RMessageForError(RErrorCode));
			goto error;
		}

		if (!RConvertImage(rc, image, &pixmap)) {
			wwarning("could not convert texture:%s", RMessageForError(RErrorCode));
			RReleaseImage(image);
			goto error;
		}

		texture->width = image->width;
		texture->height = image->height;
		RReleaseImage(image);

		texture->pixmap = pixmap;
	} else if (strcasecmp(type, "mvgradient") == 0
Exemplo n.º 29
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);
}
Exemplo n.º 30
0
int
main (int argc, char **argv)
{
  Display *dpy;
  int opt, ncolors = 0, i;
  XColor *allocated;
  int nallocated;
  XColor color;
  Colormap cmap;

  while ((opt = getopt (argc, argv, "n:")) != EOF)
    switch (opt)
      {
      case 'n':
	ncolors = atoi (optarg);
	break;

      case '?':
	usage (argv[0]);
      }

  if (ncolors == 0)
    usage (argv[0]);

  dpy = XOpenDisplay ("");
  if (dpy == NULL)
    fatal ("Cannot open display");
  cmap = DefaultColormap (dpy, 0);

  allocated = malloc (ncolors * sizeof *allocated);
  nallocated = 0;
  memset (&color, 0, sizeof color);

  while (nallocated < ncolors
	 && color.red < 65536)
    {
      allocated[nallocated] = color;
      if (XAllocColor (dpy, cmap, &allocated[nallocated]))
	{
	  for (i = 0; i < nallocated; ++i)
	    if (allocated[i].red == allocated[nallocated].red
		&& allocated[i].green == allocated[nallocated].green
		&& allocated[i].blue == allocated[nallocated].blue)
	      break;

	  if (i == nallocated)
	    {
	      printf ("allocated %d/%d/%d\n",
		      allocated[nallocated].red,
		      allocated[nallocated].green,
		      allocated[nallocated].blue);
	      ++nallocated;
	    }
	}

      ++color.red;
      ++color.green;
      ++color.blue;
    }

  fprintf (stderr, "Waiting.  Press ^C to stop.\n");
  while (1)
    sleep (10);

  XCloseDisplay (dpy);
  return 0;
}