static void QInitColors( void ) { XColor color,exact; Status result; int i; if( MAXCOLOR < 16 ) Error("xgraph: Error in dimension of color table"); MyColormap = XDefaultColormap(MyDisplay,MyScreen); for(i=0;i<16;i++) { result=XAllocNamedColor(MyDisplay,MyColormap,MyColorNames[i] ,&color,&exact); if(result) MyColors[i]=color; else { Error("QInitColors : Error allocating color"); } } MaxColors = 16; }
/* Assumes a Pseudo graphic display. */ void init_colormaps (Display *dpy) { screen = XDefaultScreen (dpy); fprintf(stderr, "Number of display cells = %d\n", XDisplayCells(dpy, screen)); fprintf(stderr, "Number of display planes = %d\n", XDisplayPlanes(dpy, screen)); colormap = XDefaultColormap(dpy, screen); while (XAllocColorCells(display_, colormap, False, NULL, 0, &(pixels[cmapsize]), 1)) cmapsize++; cmapsize = (cmapsize > 60) ? 60 : cmapsize; fprintf(stderr, "Number of colors available = %d\n", cmapsize); if (cmapsize<5) { fprintf(stderr, "Number of colors available = %d\n", cmapsize); fprintf(stderr, "This is too few to run the display software.\n"); fprintf(stderr, "Shut down windows, or restart X server.\n"); exit(-1); } /* build a grey scale colormap as a default, so that other programs */ /* can't grab the colors*/ { XColor xcolor; int i; xcolor.flags= DoRed | DoGreen | DoBlue; for (i = 0 ; i < cmapsize; i++) { xcolor.pixel = pixels[i]; xcolor.red = (unsigned short) (i<<8); xcolor.green = (unsigned short) (i<<8); xcolor.blue = (unsigned short) (i<<8); XStoreColor (display_, colormap, &xcolor); } } /* Generate global gamma correction table for this display */ { Pixel index; double gamma = 1.0/1.0; for(index =0; index < 255; index++) { GammaCorrect[index] = (Pixel)(0.5 + 255.0 * (double) pow((double)(index)/255.0, gamma)); } } /* Set up the internal histogram tables*/ translate_init(); return; }
int SetPixmapsBackground(Image * image, Drawable drawable, Pixel color) { XpmImage xpmimage; XpmAttributes xpmattr; XpmColorSymbol xpmcolor[1]; unsigned int i; xpmattr.valuemask = XpmCloseness; xpmattr.closeness = 32768; /* * By default, the XPM library assumes screen 0, so we have * to pass in the real values. Submitted by Caveh Frank Jalali */ xpmattr.valuemask |= XpmVisual | XpmColormap | XpmDepth; xpmattr.visual = Scr->d_visual; xpmattr.colormap = XDefaultColormap(dpy, Scr->screen); xpmattr.depth = Scr->d_depth; if (XpmCreateXpmImageFromPixmap(dpy, image->pixmap, image->mask, &xpmimage, &xpmattr) != XpmSuccess) { fprintf(stderr, "Failed to XpmCreateImage\n"); return (0); } for (i = 0; i < xpmimage.ncolors; i++) if (!strcmp(xpmimage.colorTable[i].c_color, "None")) break; if (i < xpmimage.ncolors) { XFreePixmap(dpy, image->pixmap); XFreePixmap(dpy, image->mask); xpmcolor[0].name = NULL; xpmcolor[0].value = "none"; xpmcolor[0].pixel = color; xpmattr.colorsymbols = xpmcolor; xpmattr.numsymbols = 1; xpmattr.valuemask |= XpmColorSymbols; XpmCreatePixmapFromXpmImage(dpy, drawable, &xpmimage, &image->pixmap, &image->mask, &xpmattr); } i = xpmimage.ncolors; XpmFreeXpmImage(&xpmimage); return (i); }
/////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////// CXWindow::CXWindow(int SizeX, int SizeY) { display = XOpenDisplay(0); FATAL(!display); win = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0, SizeX, SizeY, 0, // Border width 0, 0); { XGCValues gcv; gcv.graphics_exposures = False; gc = XCreateGC(display, win, GCGraphicsExposures, &gcv); } screen = XDefaultScreen(display); pvis = XDefaultVisual(display, screen); map = XDefaultColormap(display,DefaultScreen(display)); XColor exact; XAllocNamedColor(display, map, "white", &White, &exact); XAllocNamedColor(display, map, "black", &Black, &exact); XAllocNamedColor(display, map, "grey41", &DimGrey, &exact); XAllocNamedColor(display, map, "grey82", &LightGrey, &exact); if (pvis->red_mask && pvis->green_mask && pvis->blue_mask) { RMult = MultValue(pvis->red_mask); RMax = MaxValue(pvis->red_mask); GMult = MultValue(pvis->green_mask); GMax = MaxValue(pvis->green_mask); BMult = MultValue(pvis->blue_mask); BMax = MaxValue(pvis->blue_mask); } else RMult = RMax = GMult = GMax = BMult = BMax = 0; wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0); XSetWMProtocols(display, win, &wm_delete_window, 1); XMapRaised(display, win); }
static void LoadXPMImage(char *path, Image * img, Pixel color) { XpmAttributes attributes; XpmColorSymbol xpmcolor[1]; int ErrorStatus; attributes.valuemask = XpmReturnPixels; attributes.valuemask |= XpmCloseness; attributes.closeness = 32768; if (color) { xpmcolor[0].name = NULL; xpmcolor[0].value = "none"; xpmcolor[0].pixel = color; attributes.colorsymbols = xpmcolor; attributes.numsymbols = 1; attributes.valuemask |= XpmColorSymbols; } /* * By default, the XPM library assumes screen 0, so we have * to pass in the real values. Submitted by Caveh Frank Jalali */ attributes.valuemask |= XpmVisual | XpmColormap | XpmDepth; attributes.visual = Scr->d_visual; attributes.colormap = XDefaultColormap(dpy, Scr->screen); attributes.depth = Scr->d_depth; if ((ErrorStatus = XpmReadFileToPixmap(dpy, Scr->Root, path, &img->pixmap, &img->mask, &attributes)) != XpmSuccess) { img->pixmap = None; } else { img->height = attributes.height; img->width = attributes.width; img->type = IMAGE_TYPE_XPM; } }
/* * Main program */ int main (int argc, char **argv) { Arg arg[1] ; MrmInitialize (); /* * Initialize the toolkit. This call returns the id of a "shell," * whose only child should be the main window of the application. */ CommonTestInit(argc, argv); XtSetArg (arg[0], XtNallowShellResize, TRUE) ; XtSetValues (Shell1, arg, 1) ; if(argc>1 && argv[1]){global_current_file=stringdup(argv[1]);} dpy = XtDisplay(Shell1); cmap = XDefaultColormap(dpy,0); XtGetApplicationResources(Shell1, &data, resources, XtNumber(resources), NULL, 0); /* * Define the Mrm.hierarchy */ if (MrmOpenHierarchy (num_uid_files, /* number of files */ uid_files, /* files */ NULL, /* os_ext_list (null) */ &s_MrmHierarchy) /* ptr to returned id */ != MrmSUCCESS) { printf ("Color: cannot open UID hierarchy.\n\ Check UIDPATH environment variable\n\ Goodbye."); return(0); }
int Visualiza(int largura, int altura, struct ponto2D * P) { Display * display; GC gc; Window win, root_window; unsigned long valuemask = 0; XGCValues values; XColor cor; int x = 0, y = 0, screennumber, espessura = 10, i; unsigned long white_pixel, black_pixel; display = XOpenDisplay(NULL); screennumber = DefaultScreen(display); root_window = RootWindow(display, screennumber); black_pixel = BlackPixel(display,screennumber); white_pixel = WhitePixel(display, screennumber); win = XCreateSimpleWindow(display,root_window,x,y,largura,altura,espessura,black_pixel,white_pixel); XMapWindow(display, win); gc = XCreateGC(display, win, valuemask, &values); XSync(display, False); XSetForeground(display, gc, white_pixel); XSetBackground(display, gc, black_pixel); XAllocNamedColor(display, XDefaultColormap(display, screennumber), "#FF7F00", &cor, &cor); XSetForeground(display, gc, cor.pixel); for (i=1;i<=8;++i) XDrawPoint(display, win, gc, P[i].x, P[i].y); Desenha_reta(display, gc, win, P[1], P[2]); Desenha_reta(display, gc, win, P[3], P[1]); Desenha_reta(display, gc, win, P[4], P[2]); Desenha_reta(display, gc, win, P[3], P[4]); Desenha_reta(display, gc, win, P[5], P[6]); Desenha_reta(display, gc, win, P[8], P[6]); Desenha_reta(display, gc, win, P[7], P[5]); Desenha_reta(display, gc, win, P[7], P[8]); Desenha_reta(display, gc, win, P[3], P[7]); Desenha_reta(display, gc, win, P[4], P[8]); Desenha_reta(display, gc, win, P[1], P[5]); Desenha_reta(display, gc, win, P[2], P[6]); XFlush(display); getchar(); XFreeGC(display,gc); XCloseDisplay(display); return 0; }
void FindPixel (char *windowName, int x, int y, Display *display, Window rootWindow) { Window parent; Window *children; Window *child; XImage *image; XWindowAttributes winAttr; XColor color; XTextProperty wmName; unsigned int noOfChildren; unsigned long pixel; int status; int i, red, green, blue; char **list; status = XGetWMName (display, rootWindow, &wmName); if ((status) && (wmName.value) && (wmName.nitems)) { if (strcmp(windowName, wmName.value) == 0) { XGetWindowAttributes(display, rootWindow, &winAttr); image = XGetImage(display, rootWindow, 0, 0, winAttr.width, winAttr.height, XAllPlanes(), ZPixmap); color.pixel = XGetPixel(image, x, y); XQueryColor(display, XDefaultColormap(display, XDefaultScreen(display)), &color); red = floor(color.red * 0.003891051); green = floor(color.green * 0.003891051); blue = floor(color.blue * 0.003891051); printf("%i %i %i\n", red, green, blue); } } status = XQueryTree (display, rootWindow, &rootWindow, &parent, &children, &noOfChildren); for (i=0; i < noOfChildren; i++) { FindPixel (windowName, x, y, display, children[i]); } XFree ((char*) children); }
/* ------------------------------------------------------------------ */ int initGraphics() { theDisplay = XOpenDisplay(XDisplayName(NULL)); if (theDisplay == NULL) { printf("You need to run the program under X-window.\n\n"); exit(1); } theScreen = XDefaultScreen(theDisplay); rootW = RootWindow(theDisplay, theScreen); theGC = XDefaultGC(theDisplay, theScreen); theCmap = XDefaultColormap(theDisplay, theScreen); theVisual = DefaultVisual(theDisplay, theScreen); theDepth = XDefaultDepth(theDisplay, theScreen); // fprintf(stderr, "Visual %x Depth %d\n", theVisual, theDepth); pScreen = XDefaultScreenOfDisplay(theDisplay); sW = XWidthOfScreen(pScreen); sH = XHeightOfScreen(pScreen); theFont = XLoadFont(theDisplay, FONT10 ); XSetFont(theDisplay, theGC, theFont); return 0; }
void InitXGraphics(int argc, char **argv, int ny, int nx, int nd, MET_MAP_PIX *** MetMap) { /* following is for the X11 libraries */ int i, x, y, screen; /* screen is an int. */ int border_width; int c1, c2, c3; float re, best_re; long dy, dx; int best_e, best_ndx, best_ndy; int el, ndxl, ndyl; int buf = 50; #ifdef HAVE_X11 Colormap cmap; /* map from pixel values to colors */ char *window_name = "DHSVM Realtime Display", *display_name = NULL; XSizeHints size_hints; /* connect to Xserver */ if ((display = XOpenDisplay(display_name)) == NULL) { fprintf(stderr, "InitXGraphics: cannot connect to X server %s\n", XDisplayName(display_name)); exit(-1); } /* get screen size */ screen = DefaultScreen(display); dx = 0.95 * DisplayWidth(display, screen); dy = 0.95 * DisplayHeight(display, screen); border_width = 4; x = 0; y = 0; /* figure out the actual size of the window and stuff */ /* now we need to figure out the expansion factor for the number of graphs */ /* want to maximize the size of each graph while constrained by the number of graphs and the screen size */ /* save top 20 pixels of the display for the date counter */ /* save 40 pixels for the X11 window title bar- allocated by system */ /* save left 10 pixels for border */ dx = dx - 10; dy = dy - 60; best_e = -10; best_ndx = 1; for (ndxl = 1; ndxl <= nd; ndxl++) { for (el = -10; el <= 10; el++) { if (el != 0) { if (el < 0) re = 1 / ((float) (-el)); if (el > 0) re = (float) el; ndyl = nd / (ndxl); if (ndxl * ndyl < nd) ndyl = ndyl + 1; c1 = nd * (nx * re + buf) * (ny * re + buf); c2 = ndxl * (nx * re + buf); c3 = ndyl * (ny * re + buf); if (c1 <= dx * dy && c2 <= dx && c3 <= dy) { /* printf("ndx %d ndy %d e %d \n",ndxl,ndy,el); printf("nx ny buf re %d %d %d %f\n",nx,ny,buf,re); printf("c1 c2 c3 rh1 rh2 rh3 %d %d %d %d %d %d \n",c1,c2,c3,dx*dy,dx,dy); */ if (el > best_e) { best_e = el; best_ndx = ndxl; best_re = re; } } } } } printf("best use of display for %d images: \n", nd); printf("Expand images by factor %f with %d columns\n", best_re, best_ndx); e = best_e; ndx = best_ndx; best_ndy = nd / best_ndx; if (best_ndy * best_ndx < nd) best_ndy = best_ndy + 1; /* now create the window given the new size classes */ dx = best_ndx * (nx * best_re + buf) + 10; dy = best_ndy * (ny * best_re + buf) + 60; window = XCreateSimpleWindow(display, RootWindow(display, screen), 0, 0, dx, dy, border_width, WhitePixel(display, screen), WhitePixel(display, screen)); size_hints.flags = PPosition | PSize | PMinSize | PMaxSize; size_hints.x = 0; size_hints.y = 0; size_hints.width = dx; size_hints.height = dy; size_hints.min_width = 200; size_hints.min_height = 200; size_hints.max_width = DisplayWidth(display, screen); size_hints.max_height = DisplayHeight(display, screen); XSetStandardProperties(display, window, window_name, window_name, None, NULL, 0, &size_hints); black = XBlackPixel(display, screen); white = XWhitePixel(display, screen); gc = XCreateGC(display, window, 0, 0); XMapWindow(display, window); cmap = XDefaultColormap(display, screen); /* black to blue */ for (i = 0; i < 10; i++) { my_color[i].red = 0; my_color[i].green = 0; my_color[i].blue = 65535 * i / 9; } /* blue to cyan */ for (i = 10; i < 20; i++) { my_color[i].red = 0; my_color[i].green = i * 65535 / 19; my_color[i].blue = 65535; } /*cyan to green */ for (i = 20; i < 25; i++) { my_color[i].red = 0; my_color[i].green = 65535; my_color[i].blue = 65535 - (65535 * (i - 20) / 5); } /*green to yellow */ for (i = 25; i < 30; i++) { my_color[i].red = (i - 25) * 65535 / 5; my_color[i].green = 65535; my_color[i].blue = 0; } /*yellow to magenta */ for (i = 30; i < 40; i++) { my_color[i].red = 65535; my_color[i].green = 65535 - (65535 * (i - 30) / 9); my_color[i].blue = 65535 * (i - 30) / 9; } /*magenta to red */ for (i = 40; i < 50; i++) { my_color[i].red = 65335; my_color[i].green = 0; my_color[i].blue = 65535 - (65535 * (i - 40) / 9); } for (i = 0; i < 50; i++) { if (XAllocColor(display, cmap, &my_color[i]) == 0) { printf("Can't do DHSVM colors\n"); exit(3); } } /* done initializing the X11 Display, available for drawing */ /* initialize the memory used solely by the drawing functions */ if (!((*MetMap) = (MET_MAP_PIX **) calloc(ny, sizeof(MET_MAP_PIX *)))) ReportError("InitXGraphics", 1); for (y = 0; y < ny; y++) { if (!((*MetMap)[y] = (MET_MAP_PIX *) calloc(nx, sizeof(MET_MAP_PIX)))) ReportError("InitXGraphics", 1); } if ((temp_array = (float **) malloc(ny * sizeof(float *))) == NULL) { ReportError("draw.c", 1); } for (y = 0; y < ny; y++) { if ((temp_array[y] = (float *) malloc(nx * sizeof(float))) == NULL) { ReportError("draw.c", 1); } } #endif }
void Create_Window (char *geometry) { short q; Visual *vid; XSetWindowAttributes xswa; XSizeHints sizehint; XWMHints wmhints; int depth; unsigned char wname[256]; /* Window Name */ unsigned long vmask = CWEventMask | CWBackPixel | CWBackingStore; depth = DefaultDepth (display.dpy, display.screen); xswa.event_mask = 0; xswa.background_pixel = display.bg; xswa.backing_store = Always; printf ("DefaultVisual id=%d bp-rgb=%d map-entries=%d\n" ,(int) (*DefaultVisual (display.dpy, display.screen)).visualid ,(*DefaultVisual (display.dpy, display.screen)).bits_per_rgb ,(*DefaultVisual (display.dpy, display.screen)).map_entries); vid = DefaultVisual (display.dpy, display.screen); display.cmap = XDefaultColormap (display.dpy, display.screen); display.win = XCreateWindow (display.dpy, display.root, winX, winY, display.winW, display.winH, 0, depth, InputOutput, /* vid , */ DefaultVisual (display.dpy, display.screen), /* PseudoColor, */ vmask, &xswa); sizehint.x = winX - 100; sizehint.y = winY; sizehint.width = display.winW; sizehint.height = display.winH; sizehint.min_width = display.winW; sizehint.min_height = display.winH; sizehint.max_width = display.winW; sizehint.max_height = display.winH; /* GCS FIX: Be careful about resizing the opening screen */ /* WCK: Fixed. We lock it now, and unlock it after the opening screen. not gorgeous, but it works for now. Still need to clean up.*/ #define NO_RESIZABLE_WINDOWS 1 if (geometry != NULL) { #if defined (NO_RESIZABLE_WINDOWS) sizehint.flags = USPosition | USSize | PMinSize | PMaxSize; #else sizehint.flags = USPosition | USSize | PMinSize; #endif } else { #if defined (NO_RESIZABLE_WINDOWS) sizehint.flags = PPosition | PSize | PMinSize | PMaxSize; #else sizehint.flags = PPosition | PSize | PMinSize; #endif } XSetNormalHints (display.dpy, display.win, &sizehint); display.protocol_atom = XInternAtom (display.dpy, "WM_PROTOCOLS", False); display.kill_atom = XInternAtom (display.dpy, "WM_DELETE_WINDOW", False); /* Title */ sprintf ((char *) wname, _("xlincity, Version %s, " "(Copyright) IJ Peters - copying policy GNU GPL"), VERSION); XChangeProperty (display.dpy, display.win, XA_WM_NAME, XA_STRING, 8, PropModeReplace, wname, strlen ((char *) wname)); /* Window Manager Hints (This is supposed to make input work.) */ wmhints.flags = InputHint; wmhints.input = True; XSetWMHints (display.dpy, display.win, &wmhints); XMapWindow (display.dpy, display.win); XSelectInput (display.dpy, display.win, KeyPressMask | ButtonPressMask | ButtonReleaseMask | ExposureMask | StructureNotifyMask); for (q = 0; q < 256; q++) { display.pixcolour_gc[q] = XCreateGC (display.dpy ,display.win, 0, NULL); XSetForeground (display.dpy, display.pixcolour_gc[q], q); XSetBackground (display.dpy, display.pixcolour_gc[q] ,display.bg); XSetGraphicsExposures (display.dpy, display.pixcolour_gc[q] ,False); } }
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); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDPSImage() reads a Adobe Postscript image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadDPSImage method is: % % Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *client_name; Display *display; float pixels_per_point; Image *image; int sans, status; Pixmap pixmap; register ssize_t i; register Quantum *q; register size_t pixel; Screen *screen; ssize_t x, y; XColor *colors; XImage *dps_image; XRectangle page, bits_per_pixel; XResourceInfo resource_info; XrmDatabase resource_database; XStandardColormap *map_info; XVisualInfo *visual_info; /* Open X server connection. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); display=XOpenDisplay(image_info->server_name); if (display == (Display *) NULL) return((Image *) NULL); /* Set our forgiving exception handler. */ (void) XSetErrorHandler(XError); /* Open image file. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Get user defaults from X resource database. */ client_name=GetClientName(); resource_database=XGetResourceDatabase(display,client_name); XGetResourceInfo(image_info,resource_database,client_name,&resource_info); /* Allocate standard colormap. */ map_info=XAllocStandardColormap(); visual_info=(XVisualInfo *) NULL; if (map_info == (XStandardColormap *) NULL) ThrowReaderException(ResourceLimitError,"UnableToCreateStandardColormap") else { /* Initialize visual info. */ (void) CloneString(&resource_info.visual_type,"default"); visual_info=XBestVisualInfo(display,map_info,&resource_info); map_info->colormap=(Colormap) NULL; } if ((map_info == (XStandardColormap *) NULL) || (visual_info == (XVisualInfo *) NULL)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Create a pixmap the appropriate size for the image. */ screen=ScreenOfDisplay(display,visual_info->screen); pixels_per_point=XDPSPixelsPerPoint(screen); if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) pixels_per_point=MagickMin(image->resolution.x,image->resolution.y)/ DefaultResolution; status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap, &bits_per_pixel,&page); if ((status == dps_status_failure) || (status == dps_status_no_extension)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Rasterize the file into the pixmap. */ status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth, &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue, &sans); if (status != dps_status_success) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Initialize DPS X image. */ dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (dps_image == (XImage *) NULL) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Get the colormap colors. */ colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size, sizeof(*colors)); if (colors == (XColor *) NULL) { image=DestroyImage(image); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor)) for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=(size_t) i; colors[i].pad=0; } else { size_t blue, blue_bit, green, green_bit, red, red_bit; /* DirectColor or TrueColor visual. */ red=0; green=0; blue=0; red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1); green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1); blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1); for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=red | green | blue; colors[i].pad=0; red+=red_bit; if (red > visual_info->red_mask) red=0; green+=green_bit; if (green > visual_info->green_mask) green=0; blue+=blue_bit; if (blue > visual_info->blue_mask) blue=0; } } (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen), colors,visual_info->colormap_size); /* Convert X image to MIFF format. */ if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor)) image->storage_class=PseudoClass; image->columns=(size_t) dps_image->width; image->rows=(size_t) dps_image->height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); switch (image->storage_class) { case DirectClass: default: { register size_t color, index; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=visual_info->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=visual_info->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=visual_info->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((visual_info->colormap_size > 0) && (visual_info->klass == DirectColor)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); index=(pixel >> red_shift) & red_mask; SetPixelRed(image,ScaleShortToQuantum(colors[index].red),q); index=(pixel >> green_shift) & green_mask; SetPixelGreen(image,ScaleShortToQuantum(colors[index].green),q); index=(pixel >> blue_shift) & blue_mask; SetPixelBlue(image,ScaleShortToQuantum(colors[index].blue),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); color=(pixel >> red_shift) & red_mask; color=(color*65535L)/red_mask; SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> green_shift) & green_mask; color=(color*65535L)/green_mask; SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> blue_shift) & blue_mask; color=(color*65535L)/blue_mask; SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } case PseudoClass: { /* Create colormap. */ if (AcquireImageColormap(image,(size_t) visual_info->colormap_size,exception) == MagickFalse) { image=DestroyImage(image); colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red); image->colormap[colors[i].pixel].green= ScaleShortToQuantum(colors[i].green); image->colormap[colors[i].pixel].blue= ScaleShortToQuantum(colors[i].blue); } /* Convert X image to PseudoClass packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,(unsigned short) XGetPixel(dps_image,x,y),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } }
static BOOL CreateDeviceColormap(Display *display, int screen, int minplanes, int maxplanes) { int i, j; unsigned long *pixels, planes[32]; /* pass 1: allocate colors from default colormap * pass 2: create colormap & allocate colors from new colormap */ DeviceColormapSize = (XDefaultVisual(display, screen))->map_entries; for (i = 0; i < 2; i++) { /* pass 1: get default colormap * pass 2: create custom colormap */ if (i == 0) { DeviceColormap = XDefaultColormap(display, screen); } else { DeviceColormap = XCreateColormap(display, XRootWindow(display, screen), XDefaultVisual(display, screen), AllocNone); } /* pass 1: save default colormap colors for pass 2 * pass 2: initialize with default colormap colors to minimize * techni-color(tm) effect */ if (i == 0) { DeviceColormapValues = (XColor *) WinMalloc(DeviceColormapSize * sizeof(XColor)); for (j = 0; j < DeviceColormapSize; j++) { DeviceColormapValues[j].pixel = j; } XQueryColors(display, DeviceColormap, DeviceColormapValues, DeviceColormapSize); } else { pixels = (unsigned long *) WinMalloc(DeviceColormapSize * sizeof(unsigned long)); XAllocColorCells(display, DeviceColormap, True, planes, 0, pixels, DeviceColormapSize); XStoreColors(display, DeviceColormap, DeviceColormapValues, DeviceColormapSize); XFreeColors(display, DeviceColormap, pixels, DeviceColormapSize, 0L); } /* allocate as many color planes as possible */ if ((minplanes < 1) || (maxplanes < 1)) break; for (j = maxplanes; j >= minplanes; j--) { if (!XAllocColorCells(display, DeviceColormap, True, pixel_masks, j, &pixel0, 1)) { continue; } pixel_numplanes = j; pixel_mask0 = ~0; for (pixel_mask = 0, j = 0; j < pixel_numplanes; j++) { pixel_mask |= pixel_masks[j]; pixel_mask0 = min(pixel_mask0, pixel_masks[j]); } break; } if (j >= minplanes) break; } if (i == 2) { ERRSTR((LF_WARNING, "%s: Unable to alloc %d to %d planes.\n", "CreateDeviceColormap", minplanes, maxplanes)); return (FALSE); } /* success */ return (TRUE); }
int main(int argc, char **argv) { FILE *fp; int x_1,y_1,x_2,y_2,x_3,y_3; char a; int i,j; int outside; int ButtonPressed = 0; int temp_x, temp_y; pixel_count = 0; for(i=0;i<302;i++) { for(j=0;j<302;j++) { cost[i][j] = 9999; } } if( (display_ptr = 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_ptr ); screen_ptr = DefaultScreenOfDisplay( display_ptr ); color_map = XDefaultColormap( display_ptr, screen_num ); display_width = DisplayWidth( display_ptr, screen_num ); display_height = DisplayHeight( display_ptr, screen_num ); printf("Width %d, Height %d, Screen Number %d\n", display_width, display_height, screen_num); border_width = 10; win_x = 0; win_y = 0; win_width = display_width; win_height = display_height; win= XCreateSimpleWindow( display_ptr, RootWindow( display_ptr, screen_num), win_x, win_y, win_width, win_height, border_width, BlackPixel(display_ptr, screen_num), WhitePixel(display_ptr, screen_num) ); 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 = "examples"; XSetWMProperties( display_ptr, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints ); XSelectInput( display_ptr, win, ExposureMask | StructureNotifyMask | ButtonPressMask ); XMapWindow( display_ptr, win ); XFlush(display_ptr); gc_red = XCreateGC( display_ptr, win, valuemask, &gc_red_values); XSetLineAttributes( display_ptr, gc_red, 3, LineSolid, CapRound, JoinRound); if( XAllocNamedColor( display_ptr, color_map, "red", &tmp_color1, &tmp_color2 ) == 0 ) {printf("failed to get color red\n"); exit(-1);} else XSetForeground( display_ptr, gc_red, tmp_color1.pixel ); gc_black = XCreateGC( display_ptr, win, valuemask, &gc_black_values); XSetLineAttributes(display_ptr, gc_black, 3, LineSolid,CapRound, JoinRound); if( XAllocNamedColor( display_ptr, color_map, "black", &tmp_color1, &tmp_color2 ) == 0 ) {printf("failed to get color black\n"); exit(-1);} else XSetForeground( display_ptr, gc_black, tmp_color1.pixel ); gc_blue = XCreateGC( display_ptr, win, valuemask, &gc_blue_values); XSetLineAttributes(display_ptr, gc_blue, 3, LineSolid,CapRound, JoinRound); if( XAllocNamedColor( display_ptr, color_map, "blue", &tmp_color1, &tmp_color2 ) == 0 ) {printf("failed to get blue yellow\n"); exit(-1);} else XSetForeground( display_ptr, gc_blue, tmp_color1.pixel ); gc_white = XCreateGC( display_ptr, win, valuemask, &gc_white_values); XSetLineAttributes(display_ptr, gc_white, 3, LineSolid,CapRound, JoinRound); if( XAllocNamedColor( display_ptr, color_map, "white", &tmp_color1, &tmp_color2 ) == 0 ) {printf("failed to get color white\n"); exit(-1);} else XSetForeground( display_ptr, gc_white, tmp_color1.pixel ); if ( argc != 2 ) { printf( "Usage: %s filename.extension \n", argv[0] ); exit(-1); } fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(stderr, "Can't open file %s!\n", argv[1]); printf( "Usage: %s filename.extension or Check whether file is present or not\n", argv[0] ); exit(-1); } triangle_count = 0; while (fscanf(fp, "%c %c%d%c%d%c %c%d%c%d%c %c%d%c%d%c%c", &a,&a,&x_1,&a,&y_1,&a,&a,&x_2,&a,&y_2,&a,&a,&x_3,&a,&y_3,&a,&a) != EOF) { if(get_x_min(x_1,x_2,x_3) >= 0 && get_y_min(y_1,y_2,y_3) >= 0 && get_x_max(x_1,x_2,x_3) <= display_width - 300 && get_y_max(y_1,y_2,y_3) <= display_height - 200) { t[triangle_count].x1 = x_1; t[triangle_count].x2 = x_2; t[triangle_count].x3 = x_3; t[triangle_count].y1 = y_1; t[triangle_count].y2 = y_2; t[triangle_count].y3 = y_3; triangle_count++; } } x_min = t[0].x1; x_max = x_min; y_min = t[0].y1; y_max = y_min; for(i=0;i<triangle_count;i++) { if(x_min > t[i].x1) x_min = t[i].x1; if(x_min > t[i].x2) x_min = t[i].x2; if(x_min > t[i].x2) x_min = t[i].x3; if(y_min > t[i].y1) y_min = t[i].y1; if(y_min > t[i].y2) y_min = t[i].y2; if(y_min > t[i].y3) y_min = t[i].y3; if(x_max < t[i].x1) x_max = t[i].x1; if(x_max < t[i].x2) x_max = t[i].x2; if(x_max < t[i].x3) x_max = t[i].x3; if(y_max < t[i].y1) y_max = t[i].y1; if(y_max < t[i].y2) y_max = t[i].y2; if(y_max < t[i].y3) y_max = t[i].y3; } x_center = win_width / 2; y_center = win_height / 2; x_gap = x_max - x_min; y_gap = y_max - y_min; x_start = x_center - x_gap/2 - 50; y_start = y_center - y_gap/2 - 50; x_end = x_start + x_gap + 100; y_end = y_start + y_gap + 100; rec_width = x_end - x_start; rec_height = y_end - y_start; for(i=0;i<triangle_count;i++) { t[i].x1 = t[i].x1 + x_start + 50 - x_min; t[i].x2 = t[i].x2 + x_start + 50 - x_min; t[i].x3 = t[i].x3 + x_start + 50 - x_min; t[i].y1 = t[i].y1 + y_start + 50 - y_min; t[i].y2 = t[i].y2 + y_start + 50 - y_min; t[i].y3 = t[i].y3 + y_start + 50 - y_min; } for(i=0;i<triangle_count;i++) { t[i].point_1_inside_triangle = 0; t[i].point_2_inside_triangle = 0; t[i].point_3_inside_triangle = 0; } for(i=0;i<triangle_count;i++) { for(j=0;j<triangle_count;j++) { if(j!=i) { if(point_in_triangle(t[i].x1,t[i].y1,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1) { t[i].point_1_inside_triangle = 1; } if(point_in_triangle(t[i].x2,t[i].y2,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1) { t[i].point_2_inside_triangle = 1; } if(point_in_triangle(t[i].x3,t[i].y3,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1) { t[i].point_3_inside_triangle = 1; } } } } while(1) { XNextEvent( display_ptr, &report ); switch( report.type ) { case Expose: for(i=0;i<triangle_count;i++) { XDrawLine(display_ptr, win, gc_black, t[i].x1, t[i].y1, t[i].x2, t[i].y2); XDrawLine(display_ptr, win, gc_black, t[i].x2, t[i].y2, t[i].x3, t[i].y3); XDrawLine(display_ptr, win, gc_black, t[i].x3, t[i].y3, t[i].x1, t[i].y1); } XDrawRectangle(display_ptr, win, gc_black, x_start, y_start, rec_width, rec_height ); break; case ConfigureNotify: win_width = report.xconfigure.width; win_height = report.xconfigure.height; break; case ButtonPress: { int x, y; x = report.xbutton.x; y = report.xbutton.y; if (report.xbutton.button == Button1 ) { outside = 0; if(x <= x_start || y <= y_start || x >= x_end || y >= y_end) { outside = 1; } for(i=0;i<triangle_count;i++) { if(point_in_triangle(x,y,t[i].x1,t[i].y1,t[i].x2,t[i].y2,t[i].x3,t[i].y3)==1) { outside = 1; break; } } if(outside == 0) { ButtonPressed++; if(ButtonPressed == 1) { temp_x = x; temp_y = y; pixel_count = 0; XFillArc( display_ptr, win, gc_red, x - win_height/150, y - win_height/150, win_height/100, win_height/100, 0, 360*64); pixel[pixel_count].name = pixel_count; pixel[pixel_count].x = x; pixel[pixel_count].y = y; pixel_count++; } else if(ButtonPressed == 2) { if(temp_x == x && temp_y == y) { ButtonPressed = 1; break; } XFillArc( display_ptr, win, gc_red, x - win_height/150, y - win_height/150, win_height/100, win_height/100, 0, 360*64); for(i=0;i<triangle_count;i++) { if(t[i].point_1_inside_triangle != 1) { pixel[pixel_count].name = pixel_count; pixel[pixel_count].x = t[i].x1; pixel[pixel_count].y = t[i].y1; pixel_count++; } if(t[i].point_2_inside_triangle != 1) { pixel[pixel_count].name = pixel_count; pixel[pixel_count].x = t[i].x2; pixel[pixel_count].y = t[i].y2; pixel_count++; } if(t[i].point_3_inside_triangle != 1) { pixel[pixel_count].name = pixel_count; pixel[pixel_count].x = t[i].x3; pixel[pixel_count].y = t[i].y3; pixel_count++; } } pixel[pixel_count].name = pixel_count; pixel[pixel_count].x = x; pixel[pixel_count].y = y; pixel_count++; for(i=0;i<pixel_count-1;i++) { for(j=i+1;j<pixel_count;j++) { if(can_see(pixel[i].x,pixel[i].y,pixel[j].x,pixel[j].y)==1) { cost[pixel[i].name][pixel[j].name] = cost[pixel[j].name][pixel[i].name] = eculidian_dist(pixel[i].x,pixel[i].y,pixel[j].x,pixel[j].y); } } } dijsktra(pixel[0].name, pixel[pixel_count-1].name); } else { clear_cost(); expose(); ButtonPressed = 0; } } } else { XFlush(display_ptr); XCloseDisplay(display_ptr); exit(0); } } break; default: break; } } exit(0); }
int32_t run(Filesystem* fs, ConfigSettings* cs) { // Create main window XInitThreads(); XSetErrorHandler(x11_error_handler); m_x11_display = XOpenDisplay(NULL); CE_ASSERT(m_x11_display != NULL, "Unable to open X11 display"); int screen = DefaultScreen(m_x11_display); int depth = DefaultDepth(m_x11_display, screen); Visual* visual = DefaultVisual(m_x11_display, screen); m_x11_parent_window = (m_parent_window_handle == 0) ? RootWindow(m_x11_display, screen) : (Window) m_parent_window_handle; // Create main window XSetWindowAttributes win_attribs; win_attribs.background_pixmap = 0; win_attribs.border_pixel = 0; win_attribs.event_mask = FocusChangeMask | StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask; m_x11_window = XCreateWindow(m_x11_display, m_x11_parent_window, 0, 0, cs->window_width, cs->window_height, 0, depth, InputOutput, visual, CWBorderPixel | CWEventMask, &win_attribs ); CE_ASSERT(m_x11_window != None, "Unable to create X window"); // Do we have detectable autorepeat? Bool detectable; m_x11_detectable_autorepeat = (bool) XkbSetDetectableAutoRepeat(m_x11_display, true, &detectable); // Build hidden cursor Pixmap bm_no; XColor black, dummy; Colormap colormap; static char no_data[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; colormap = XDefaultColormap(m_x11_display, screen); XAllocNamedColor(m_x11_display, colormap, "black", &black, &dummy); bm_no = XCreateBitmapFromData(m_x11_display, m_x11_window, no_data, 8, 8); m_x11_hidden_cursor = XCreatePixmapCursor(m_x11_display, bm_no, bm_no, &black, &black, 0, 0); m_wm_delete_message = XInternAtom(m_x11_display, "WM_DELETE_WINDOW", False); XSetWMProtocols(m_x11_display, m_x11_window, &m_wm_delete_message, 1); oswindow_set_window(m_x11_display, m_x11_window); bgfx::x11SetDisplayWindow(m_x11_display, m_x11_window); XMapRaised(m_x11_display, m_x11_window); // Get screen configuration m_screen_config = XRRGetScreenInfo(m_x11_display, RootWindow(m_x11_display, screen)); Rotation rr_old_rot; const SizeID rr_old_sizeid = XRRConfigCurrentConfiguration(m_screen_config, &rr_old_rot); // Start main thread MainThreadArgs mta; mta.fs = fs; mta.cs = cs; Thread main_thread; main_thread.start(func, &mta); while (!s_exit) { pump_events(); } main_thread.stop(); // Restore previous screen configuration if changed Rotation rr_cur_rot; const SizeID rr_cur_sizeid = XRRConfigCurrentConfiguration(m_screen_config, &rr_cur_rot); if (rr_cur_rot != rr_old_rot || rr_cur_sizeid != rr_old_sizeid) { XRRSetScreenConfig(m_x11_display, m_screen_config, RootWindow(m_x11_display, screen), rr_old_sizeid, rr_old_rot, CurrentTime); } XRRFreeScreenConfigInfo(m_screen_config); XDestroyWindow(m_x11_display, m_x11_window); XCloseDisplay(m_x11_display); return EXIT_SUCCESS; }
int main(int argc, char **argv) { /* opening display: basic connection to X Server */ if( (display_ptr = 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_ptr ); screen_ptr = DefaultScreenOfDisplay( display_ptr ); color_map = XDefaultColormap( display_ptr, screen_num ); display_width = DisplayWidth( display_ptr, screen_num ); display_height = DisplayHeight( display_ptr, screen_num ); printf("Width %d, Height %d, Screen Number %d\n", display_width, display_height, screen_num); /* creating the window */ border_width = 10; win_x = 0; win_y = 0; win_width = display_width/2; win_height = (int) (win_width / 1.7); /*rectangular window*/ win= XCreateSimpleWindow( display_ptr, RootWindow( display_ptr, screen_num), win_x, win_y, win_width, win_height, border_width, BlackPixel(display_ptr, screen_num), WhitePixel(display_ptr, screen_num) ); /* now try to put it on screen, this needs cooperation of window manager */ 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 = "examples"; XSetWMProperties( display_ptr, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints ); /* what events do we want to receive */ XSelectInput( display_ptr, win, ExposureMask | StructureNotifyMask | ButtonPressMask ); /* finally: put window on screen */ XMapWindow( display_ptr, win ); XFlush(display_ptr); /* create graphics context, so that we may draw in this window */ gc = XCreateGC( display_ptr, win, valuemask, &gc_values); XSetForeground( display_ptr, gc, BlackPixel( display_ptr, screen_num ) ); XSetLineAttributes( display_ptr, gc, 4, LineSolid, CapRound, JoinRound); /* and three other graphics contexts, to draw in yellow and red and grey*/ gc_yellow = XCreateGC( display_ptr, win, valuemask, &gc_yellow_values); XSetLineAttributes(display_ptr, gc_yellow, 6, LineSolid,CapRound, JoinRound); if( XAllocNamedColor( display_ptr, color_map, "yellow", &tmp_color1, &tmp_color2 ) == 0 ) { printf("failed to get color yellow\n"); exit(-1); } else XSetForeground( display_ptr, gc_yellow, tmp_color1.pixel ); gc_red = XCreateGC( display_ptr, win, valuemask, &gc_red_values); XSetLineAttributes( display_ptr, gc_red, 6, LineSolid, CapRound, JoinRound); if( XAllocNamedColor( display_ptr, color_map, "red", &tmp_color1, &tmp_color2 ) == 0 ) { printf("failed to get color red\n"); exit(-1); } else XSetForeground( display_ptr, gc_red, tmp_color1.pixel ); gc_grey = XCreateGC( display_ptr, win, valuemask, &gc_grey_values); if( XAllocNamedColor( display_ptr, color_map, "light grey", &tmp_color1, &tmp_color2 ) == 0 ) { printf("failed to get color grey\n"); exit(-1); } else XSetForeground( display_ptr, gc_grey, tmp_color1.pixel ); /* and now it starts: the event loop */ while(1) { XNextEvent( display_ptr, &report ); switch( report.type ) { case Expose: /* (re-)draw the example figure. This event happens each time some part ofthe window gets exposed (becomes visible) */ XDrawLine(display_ptr, win, gc, win_width /4, win_height/ 3, 3*win_width/4, win_height/3 ); XDrawLine(display_ptr, win, gc_red, win_width /4, 2*win_height/ 3, 3*win_width/4, 2*win_height/3 ); XFillArc( display_ptr, win, gc_grey, win_width/2-win_height/6, win_height/3, win_height/3, win_height/3, 0, 360*64); XDrawArc( display_ptr, win, gc_yellow, win_width/4, win_height/3, win_height/6, win_height/3, 90*64, 180*64); break; case ConfigureNotify: /* This event happens when the user changes the size of the window*/ win_width = report.xconfigure.width; win_height = report.xconfigure.height; break; case ButtonPress: /* This event happens when the user pushes a mouse button. I draw a circle to show the point where it happened, but do not save the position; so when the next redraw event comes, these circles disappear again. */ { int x, y; x = report.xbutton.x; y = report.xbutton.y; if (report.xbutton.button == Button1 ) XFillArc( display_ptr, win, gc_red, x -win_height/40, y- win_height/40, win_height/20, win_height/20, 0, 360*64); else XFillArc( display_ptr, win, gc_yellow, x - win_height/40, y - win_height/40, win_height/20, win_height/20, 0, 360*64); } break; default: /* this is a catch-all for other events; it does not do anything. One could look at the report type to see what the event was */ break; } } exit(0); }
Menu::Menu(WindowManager *manager, XEvent *e) : m_items(0), m_nItems(0), m_nHidden(0), m_hasSubmenus(False), m_windowManager(manager), m_event(e) { if (!m_initialised) { XGCValues *values; XSetWindowAttributes *attr; m_menuGC = (GC *) malloc(m_windowManager->screensTotal() * sizeof(GC)); m_window = (Window *) malloc(m_windowManager->screensTotal() * sizeof(Window)); #ifdef CONFIG_USE_XFT char *fi = strdup(CONFIG_MENU_FONT); char *ffi = fi, *tokstr = fi; while ((fi = strtok(tokstr, ","))) { fprintf(stderr, "fi = \"%s\"\n", fi); tokstr = 0; FcPattern *pattern = FcPatternCreate(); FcPatternAddString(pattern, FC_FAMILY, (FcChar8 *)fi); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN); #ifndef FC_WEIGHT_REGULAR #define FC_WEIGHT_REGULAR FC_WEIGHT_MEDIUM #endif FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_REGULAR); FcPatternAddInteger(pattern, FC_PIXEL_SIZE, CONFIG_MENU_FONT_SIZE); FcConfigSubstitute(FcConfigGetCurrent(), pattern, FcMatchPattern); FcResult result = FcResultMatch; FcPattern *match = FcFontMatch(FcConfigGetCurrent(), pattern, &result); FcPatternDestroy(pattern); if (!match || result != FcResultMatch) { if (match) FcPatternDestroy(match); continue; } m_font = XftFontOpenPattern(display(), match); if (m_font) break; FcPatternDestroy(match); } free(ffi); if (!m_font) { m_windowManager->fatal("couldn't load menu Xft font"); } m_xftColour = (XftColor *) malloc(m_windowManager->screensTotal() * sizeof(XftColor)); m_xftDraw = (XftDraw **) malloc(m_windowManager->screensTotal() * sizeof(XftDraw *)); #else m_font = (XFontStruct **) malloc(m_windowManager->screensTotal() * sizeof(XFontStruct *)); #endif values = (XGCValues *) malloc(m_windowManager->screensTotal() * sizeof(XGCValues)); attr = (XSetWindowAttributes *) malloc(m_windowManager->screensTotal() * sizeof(XSetWindowAttributes)); for (int i = 0; i < m_windowManager->screensTotal(); i++) { m_foreground = m_windowManager->allocateColour (i, CONFIG_MENU_FOREGROUND, "menu foreground"); m_background = m_windowManager->allocateColour (i, CONFIG_MENU_BACKGROUND, "menu background"); m_border = m_windowManager->allocateColour (i, CONFIG_MENU_BORDERS, "menu border"); #ifndef CONFIG_USE_XFT char **ml; int mc; char *ds; m_fontset = XCreateFontSet(display(), CONFIG_NICE_MENU_FONT, &ml, &mc, &ds); if (!m_fontset) m_fontset = XCreateFontSet(display(), CONFIG_NASTY_FONT, &ml, &mc, &ds); if (m_fontset) { XFontStruct **fs_list; XFontsOfFontSet(m_fontset, &fs_list, &ml); m_font[i] = fs_list[0]; } else { m_font[i] = NULL; } #define XDrawString(t,u,v,w,x,y,z) XmbDrawString(t,u,m_fontset,v,w,x,y,z) if (!m_font[i]) m_windowManager->fatal("couldn't load menu font\n"); #endif values[i].background = m_background; values[i].foreground = m_foreground ^ m_background; values[i].function = GXxor; values[i].line_width = 0; values[i].subwindow_mode = IncludeInferiors; #ifndef CONFIG_USE_XFT values[i].font = m_font[i]->fid; #endif m_menuGC[i] = XCreateGC (display(), m_windowManager->mroot(i), GCForeground | GCBackground | GCFunction | GCLineWidth | GCSubwindowMode, &values[i]); #ifndef CONFIG_USE_XFT XChangeGC(display(), Border::drawGC(m_windowManager, i), GCFont, &values[i]); #endif m_window[i] = XCreateSimpleWindow (display(), m_windowManager->mroot(i), 0, 0, 1, 1, 1, m_border, m_background); #if ( CONFIG_USE_PIXMAPS != False ) && ( CONFIG_USE_PIXMAP_MENUS != False ) attr[i].background_pixmap = Border::backgroundPixmap(manager); #endif attr[i].save_under = (DoesSaveUnders(ScreenOfDisplay(display(), i)) ? True : False); #if ( CONFIG_USE_PIXMAPS != False ) && ( CONFIG_USE_PIXMAP_MENUS != False ) XChangeWindowAttributes (display(), m_window[i], CWBackPixmap, &attr[i]); #endif XChangeWindowAttributes (display(), m_window[i], CWSaveUnder, &attr[i]); #ifdef CONFIG_USE_XFT XftColorAllocName (display(), XDefaultVisual(display(), i), XDefaultColormap(display(), i), CONFIG_MENU_FOREGROUND, &m_xftColour[i]); m_xftDraw[i] = XftDrawCreate(display(), m_window[i], XDefaultVisual(display(), i), XDefaultColormap(display(), i)); #endif } m_initialised = True; } }
/**************************************************************************** * * Creates an icon window as needed * ****************************************************************************/ int main(int argc, char **argv) { char *display_name = NULL, *string = NULL; int retval = 0; XEvent Event; fd_set in_fdset; int fd_width ; struct timeval value; int fd[2]; fd_width = GetFdWidth(); /* Save our program name - for error messages */ string = strrchr (argv[0], '/'); if (string != (char *) 0) string++; myName = safemalloc (strlen (string) + 1); strcpy (myName, string); if(argc>=3) { /* sever our connection with fvwm, if we have one. */ fd[0] = atoi(argv[1]); fd[1] = atoi(argv[2]); #if 0 if(fd[0]>0)close(fd[0]); if(fd[1]>0)close(fd[1]); #endif /* 0 */ } else { fprintf (stderr, "%s version %s should only be executed by fvwm!\n", myName, VERSION); exit(1); } if (argc > 6) { pixmapName = safemalloc (strlen (argv[6]) + 1); strcpy (pixmapName, argv[6]); } /* Open the display */ if (!(dpy = XOpenDisplay(display_name))) { fprintf(stderr,"FvwmBanner: can't open display %s", XDisplayName(display_name)); exit (1); } screen= DefaultScreen(dpy); Root = RootWindow(dpy, screen); colormap = XDefaultColormap(dpy,screen); d_depth = DefaultDepth(dpy, screen); x_fd = XConnectionNumber(dpy); ScreenHeight = DisplayHeight(dpy,screen); ScreenWidth = DisplayWidth(dpy,screen); parseOptions(fd); /* Get the xpm banner */ if (pixmapName) GetXPMFile(pixmapName,pixmapPath); else #if 0 if(d_depth > 4) GetXPMData(k2_xpm); else #endif /* 0 */ GetXPMData(fvwm2_big_xpm); /* Create a window to hold the banner */ mysizehints.flags= USSize|USPosition|PWinGravity|PResizeInc|PBaseSize|PMinSize|PMaxSize; /* subtract one for the right/bottom border */ mysizehints.width = view.attributes.width; mysizehints.height=view.attributes.height; mysizehints.width_inc = 1; mysizehints.height_inc = 1; mysizehints.base_height = mysizehints.height; mysizehints.base_width = mysizehints.width; mysizehints.min_height = mysizehints.height; mysizehints.min_width = mysizehints.width; mysizehints.max_height = mysizehints.height; mysizehints.max_width = mysizehints.width; mysizehints.win_gravity = NorthWestGravity; mysizehints.x = (ScreenWidth - view.attributes.width)/2; mysizehints.y = (ScreenHeight - view.attributes.height)/2; win = XCreateSimpleWindow(dpy,Root,mysizehints.x,mysizehints.y, mysizehints.width,mysizehints.height, 0,fore_pix ,None); /* Set assorted info for the window */ XSetTransientForHint(dpy,win,Root); wm_del_win = XInternAtom(dpy,"WM_DELETE_WINDOW",False); XSetWMProtocols(dpy,win,&wm_del_win,1); XSetWMNormalHints(dpy,win,&mysizehints); change_window_name("FvwmBanner"); XSetWindowBackgroundPixmap(dpy,win,view.pixmap); #ifdef SHAPE if(view.mask != None) XShapeCombineMask(dpy, win, ShapeBounding,0,0,view.mask, ShapeSet); #endif XMapWindow(dpy,win); XSync(dpy,0); #if 0 usleep(timeout); #else XSelectInput(dpy,win,ButtonReleaseMask); /* Display the window */ value.tv_usec = timeout % 1000000; value.tv_sec = timeout / 1000000; while(1) { FD_ZERO(&in_fdset); FD_SET(x_fd,&in_fdset); if(!XPending(dpy)) retval=select(fd_width,SELECT_TYPE_ARG234 &in_fdset, 0, 0, &value); if (retval==0) { XDestroyWindow(dpy,win); XSync(dpy,0); exit(0); } if(FD_ISSET(x_fd, &in_fdset)) { /* read a packet */ XNextEvent(dpy,&Event); switch(Event.type) { case ButtonRelease: XDestroyWindow(dpy,win); XSync(dpy,0); exit(0); case ClientMessage: if (Event.xclient.format==32 && Event.xclient.data.l[0]==wm_del_win) { XDestroyWindow(dpy,win); XSync(dpy,0); exit(0); } default: break; } } } #endif /* 0 */ return 0; }
int main(){ //Pontos iniciais Ponto P1, P2, P3, P4, P5, P6, P7, P8; float se, co, tz, cpz; //Pontos rotacionados Ponto *rP1, *rP2, *rP3, *rP4, *rP5, *rP6, *rP7, *rP8; //Pontos Projetados perspectivamente Ponto *iP1, *iP2, *iP3, *iP4, *iP5, *iP6, *iP7, *iP8; //Declaração da matriz de rotação struct matriz4x4 mRotaciona; int RXmin,RXmax,RYmin,RYmax,a,b; Window win; Display *display; int width = 256, height = 256, x = 0, y = 0, i, tx, ty,ref,rot; GC gc; unsigned long valuemask = 0; XGCValues values; XColor cor; P1.x = 30; P1.y = -10; P1.z = 10; P1.W = 1; P2.x = 30; P2.y = -10; P2.z = -10; P2.W = 1; P3.x = 30; P3.y = 10; P3.z = 10; P3.W = 1; P4.x = 30; P4.y = 10; P4.z = -10; P4.W = 1; P5.x = -30; P5.y = -10; P5.z = 10; P5.W = 1; P6.x = -30; P6.y = -10; P6.z = -10; P6.W = 1; P7.x = -30; P7.y = 10; P7.z = 10; P7.W = 1; P8.x = -30; P8.y = 10; P8.z = -10; P8.W = 1; //Variaveis para calculo do seno e cosseno do angulo de rotacao se = sin(90*PI/180); co = cos(90*PI/180); //Inicializacao da matriz de Rotacao em relacao ao eixo z mRotaciona.a11 = co; mRotaciona.a12 = -se; mRotaciona.a13 = 0; mRotaciona.a14 = 0; mRotaciona.a21 = se; mRotaciona.a22 = co; mRotaciona.a23 = 0; mRotaciona.a24 = 0; mRotaciona.a31 = 0; mRotaciona.a32 = 0; mRotaciona.a33 = 1; mRotaciona.a34 = 0; mRotaciona.a41 = 0; mRotaciona.a42 = 0; mRotaciona.a43 = 0; mRotaciona.a44 = 1; //************************************** (a) ********************************************** //Estou utilizando a regra da mão direita //Chamada da funcao que rotaciona o ponto rP1 = rotaciona(&mRotaciona, &P1); rP2 = rotaciona(&mRotaciona, &P2); rP3 = rotaciona(&mRotaciona, &P3); rP4 = rotaciona(&mRotaciona, &P4); rP5 = rotaciona(&mRotaciona, &P5); rP6 = rotaciona(&mRotaciona, &P6); rP7 = rotaciona(&mRotaciona, &P7); rP8 = rotaciona(&mRotaciona, &P8); //************************************** (b) ********************************************** //Projeção Perspectiva printf("\n\nDigite o valor Tz: \n"); scanf("%f",&tz); printf("\nDigite o valor Cpz: \n"); scanf("%f",&cpz); iP1 = Projeta(tz, cpz, rP1); iP2 = Projeta(tz, cpz, rP2); iP3 = Projeta(tz, cpz, rP3); iP4 = Projeta(tz, cpz, rP4); iP5 = Projeta(tz, cpz, rP5); iP6 = Projeta(tz, cpz, rP6); iP7 = Projeta(tz, cpz, rP7); iP8 = Projeta(tz, cpz, rP8); //************************************** (c) ********************************************** //Entrada dos valores do retangulo de visualizacao printf("\n\nDigite o valor do RXmin: \n"); scanf("%f",&RXmin); printf("\nDigite o valor RXmax: \n"); scanf("%f",&RXmax); printf("\n\nDigite o valor do RYmin: \n"); scanf("%f",&RYmin); printf("\nDigite o valor RYmax: \n"); scanf("%f",&RYmax); //width = modulo(RXmin) + modulo(RXmax); //height = modulo(RYmin) + modulo(RYmax); win = XCreateSimpleWindow(display, RootWindow(display, DefaultScreen(display)), x, y, width, height, 4, BlackPixel(display, DefaultScreen(display)), WhitePixel(display, DefaultScreen(display))); XMapWindow(display, win); gc = XCreateGC(display, win, valuemask, &values); XSync(display, False); XSetForeground(display, gc, WhitePixel(display, DefaultScreen(display))); XSetBackground(display, gc, BlackPixel(display, DefaultScreen(display))); XAllocNamedColor(display, XDefaultColormap(display, DefaultScreen(display)),"black", &cor, &cor); XSetForeground(display, gc, cor.pixel); //Desenhando os pontos a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); a = iP2->x; b = iP2->y; XDrawPoint(display, win, gc, a, b); a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); a = iP1->x; b = iP1->y; XDrawPoint(display, win, gc, a, b); //Desenhando as 12 retas reta(&win, &gc, display,iP1->x,iP2->x,iP1->y,iP2->y); reta(&win, &gc, display,iP2->x,iP4->x,iP2->y,iP4->y); reta(&win, &gc, display,iP4->x,iP3->x,iP4->y,iP3->y); reta(&win, &gc, display,iP3->x,iP1->x,iP3->y,iP1->y); reta(&win, &gc, display,iP1->x,iP5->x,iP1->y,iP5->y); reta(&win, &gc, display,iP2->x,iP6->x,iP2->y,iP6->y); reta(&win, &gc, display,iP3->x,iP7->x,iP3->y,iP7->y); reta(&win, &gc, display,iP4->x,iP8->x,iP4->y,iP8->y); reta(&win, &gc, display,iP5->x,iP6->x,iP5->y,iP6->y); reta(&win, &gc, display,iP6->x,iP8->x,iP6->y,iP8->y); reta(&win, &gc, display,iP8->x,iP7->x,iP8->y,iP7->y); reta(&win, &gc, display,iP7->x,iP5->x,iP7->y,iP5->y); XFlush(display); sleep(30); XFreeGC(display, gc); XCloseDisplay(display); return 0; }
void OpenGraphics() { Colormap map; char *disp = NULL; XColor exact; int c; if (!(display = XOpenDisplay(disp))) { perror("Cannot open display\n"); exit(-1); } map = XDefaultColormap(display,DefaultScreen(display)); XAllocNamedColor(display,map,"black",&color[BLACK],&exact); XAllocNamedColor(display,map,"grey41",&color[DIM_GREY],&exact); XAllocNamedColor(display,map,"grey69",&color[GREY_69],&exact); XAllocNamedColor(display,map,"grey75",&color[GREY],&exact); XAllocNamedColor(display,map,"grey82",&color[LIGHT_GREY],&exact); XAllocNamedColor(display,map,"white",&color[WHITE],&exact); XAllocNamedColor(display,map,"red",&color[RED],&exact); XAllocNamedColor(display,map,"green",&color[GREEN],&exact); XAllocNamedColor(display,map,"blue",&color[BLUE],&exact); XAllocNamedColor(display,map,"cyan",&color[CYAN],&exact); XAllocNamedColor(display,map,"magenta",&color[MAGENTA],&exact); XAllocNamedColor(display,map,"yellow",&color[YELLOW],&exact); XAllocNamedColor(display,map,"lime green",&color[LIME_GREEN],&exact); XAllocNamedColor(display,map,"#00b0f0",&color[BLUE_CYAN],&exact); XAllocNamedColor(display,map,"#00f0b0",&color[CYAN_GREEN],&exact); XAllocNamedColor(display,map,"#b0f000",&color[GREEN_YELLOW],&exact); XAllocNamedColor(display,map,"#f0b000",&color[YELLOW_RED],&exact); XAllocNamedColor(display,map,"brown",&color[BROWN],&exact); XAllocNamedColor(display,map,"maroon",&color[MAROON],&exact); XAllocNamedColor(display,map,"gold",&color[GOLD],&exact); XAllocNamedColor(display,map,"aquamarine",&color[AQUAMARINE],&exact); XAllocNamedColor(display,map,"firebrick",&color[FIREBRICK],&exact); XAllocNamedColor(display,map,"goldenrod",&color[GOLDENROD],&exact); XAllocNamedColor(display,map,"blue violet",&color[BLUE_VIOLET],&exact); XAllocNamedColor(display,map,"cadet blue",&color[CADET_BLUE],&exact); XAllocNamedColor(display,map,"coral",&color[CORAL],&exact); XAllocNamedColor(display,map,"cornflower blue",&color[CORNFLOWER_BLUE], &exact); XAllocNamedColor(display,map,"dark green",&color[DARK_GREEN],&exact); XAllocNamedColor(display,map,"dark olive green",&color[DARK_OLIVE_GREEN], &exact); XAllocNamedColor(display,map,"peach puff",&color[PEACH_PUFF],&exact); XAllocNamedColor(display,map,"papaya whip",&color[PAPAYA_WHIP],&exact); XAllocNamedColor(display,map,"bisque",&color[BISQUE],&exact); XAllocNamedColor(display,map,"azure",&color[AZURE],&exact); XAllocNamedColor(display,map,"lavender",&color[LAVENDER],&exact); XAllocNamedColor(display,map,"misty rose",&color[MISTY_ROSE],&exact); XAllocNamedColor(display,map,"medium blue",&color[MEDIUM_BLUE],&exact); XAllocNamedColor(display,map,"navy blue",&color[NAVY_BLUE],&exact); XAllocNamedColor(display,map,"pale turquoise",&color[PALE_TURQUOISE], &exact); XAllocNamedColor(display,map,"sea green",&color[SEA_GREEN],&exact); XListFonts(display,FONT1,1,&c); if (c) font=XLoadFont(display,FONT1); else font=XLoadFont(display,FONT2); window = XCreateSimpleWindow(display, RootWindow(display,DefaultScreen(display)), 0,0,WINDOW_W,WINDOW_H,0, WhitePixel(display,DefaultScreen(display)), BlackPixel(display,DefaultScreen(display))); XChangeProperty(display,window,XA_WM_NAME,XA_STRING,8,PropModeReplace, (unsigned char *) "Graphics",47); XChangeProperty(display,window,XA_WM_ICON_NAME,XA_STRING,8,PropModeReplace, (unsigned char *)"Neural Map Simulator",17); XSelectInput(display,window,ExposureMask|KeyPressMask|ButtonPressMask| ButtonReleaseMask|PointerMotionMask); XMapWindow(display,window); gc = XCreateGC(display,window,0,NULL); XSetBackground(display,gc,color[GREY].pixel); XSetFont(display,gc,font); }
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; }
int main(int argc, char ** argv) { setbuf(stdout, NULL); setbuf(stderr, NULL); Display * display = XOpenDisplay(NULL); assert(display != NULL); XSynchronize(display, True); XtAppContext context = XtCreateApplicationContext(); Widget appshell = XtVaAppInitialize(&context, "SoXtTest", NULL, 0, &argc, argv, NULL, NULL); fprintf(stderr, "appshell: %p\n", appshell); #if WANT_VISUALID int i, numvisuals; unsigned int wanted = WANT_VISUALID; XVisualInfo templ; XVisualInfo * visuals = XGetVisualInfo(display, VisualNoMask, &templ, &numvisuals); for ( i = 0; i < numvisuals; i++ ) { if ( visuals[i].visualid == wanted ) goto selected; } assert(0 && "no visual selected"); selected: Visual * visual = visuals[i].visual; int visualid = visuals[i].visualid; int depth = visuals[i].depth; Colormap colormap = 0; fprintf(stderr, "visualid: %d, depth: %d, class: %s\n", visualid, depth, visuals[i].c_class == DirectColor ? "DirectColor" : "Other"); int numcmaps; XStandardColormap * stdcolormaps = NULL; if ( XmuLookupStandardColormap(display, visuals[i].screen, visuals[i].visualid, visuals[i].depth, XA_RGB_DEFAULT_MAP, False, True) && XGetRGBColormaps(display, RootWindow(display, visuals[i].screen), &stdcolormaps, &numcmaps, XA_RGB_DEFAULT_MAP) ) { for ( int j = 0; j < numcmaps; j++ ) { if (stdcolormaps[j].visualid == visuals[i].visualid) { colormap = stdcolormaps[j].colormap; goto cont; } } colormap = XCreateColormap(display, RootWindow(display, visuals[i].screen), visuals[i].visual, AllocNone); fprintf(stderr, "standard RGB colormaps did not work with visual - created own (%ld)", colormap); } else { assert(0); } cont: fprintf(stderr, "colormap: %ld\n", colormap); #else Visual * visual = NULL; int depth = 0; Colormap colormap = 0; int snum = XDefaultScreen(display); visual = XDefaultVisual(display, snum); depth = XDefaultDepth(display, snum); colormap = XDefaultColormap(display, snum); fprintf(stderr, "visual: %p, depth: %d\n", visual, depth); fprintf(stderr, "colormap: %ld\n", colormap); #endif XtVaSetValues(appshell, XmNwidth, 100, XmNheight, 100, XmNvisual, visual, XmNcolormap, colormap, XmNdepth, depth, NULL); Widget form = XtVaCreateManagedWidget( "form", xmFormWidgetClass, appshell, NULL); Widget button = XtVaCreateManagedWidget( "button", xmPushButtonWidgetClass, form, XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, XmNbottomAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, NULL); Pixmap pixmap = createPixmapFromXpm(button, home_xpm); XtVaSetValues(button, XmNlabelType, XmPIXMAP, XmNlabelPixmap, pixmap, XmNlabelInsensitivePixmap, pixmap, XmNselectPixmap, pixmap, XmNselectInsensitivePixmap, pixmap, NULL); Widget list[] = { appshell, form, button, NULL }; XtSetWMColormapWindows(appshell, list, 3); XtRealizeWidget(appshell); XtAppMainLoop(context); }
int main(int argc, char **argv) { /* code add by andrew GONG for reading file from command line argument */ point p[N]; point q[N]; point array[V]; unsigned int G[V][V]; point s = {0, 0}; point t = {0, 0}; int i, j, k; int press; i = j = k = 0; press = 0; for (i = 0; i < N; i++) { p[i].x = p[i].y = 0; q[i].x = q[i].y = 0; } if(argc != 2) { printf("usage:%s filename", argv[0]); } else { FILE *file = fopen(argv[1], "r"); if(file == 0) { printf("Could not open file!\n"); } else { i = 0; printf("%s\n", argv[1]); while(!feof(file)) { if(fscanf(file, "S (%d, %d) (%d, %d)\n", &p[i].x, &p[i].y, &q[i].x, &q[i].y) != 4) { break; } else { i++; } } } fclose(file); } /* opening display: basic connection to X Server */ if( (display_ptr = 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_ptr); screen_ptr = DefaultScreenOfDisplay(display_ptr); color_map = XDefaultColormap(display_ptr, screen_num); display_width = DisplayWidth(display_ptr, screen_num); display_height = DisplayHeight(display_ptr, screen_num); printf("Width %d, Height %d, Screen Number %d\n", display_width, display_height, screen_num); /* creating the window */ border_width = 10; win_x = 0; win_y = 0; win_width = display_width/2; win_height = (unsigned int) (win_width / 1.7); /* rectangular window */ win= XCreateSimpleWindow(display_ptr, RootWindow(display_ptr, screen_num), win_x, win_y, win_width, win_height, border_width, BlackPixel(display_ptr, screen_num), WhitePixel(display_ptr, screen_num)); /* now try to put it on screen, this needs cooperation of window manager */ 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 = "examples"; XSetWMProperties(display_ptr, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints); /* what events do we want to receive */ XSelectInput(display_ptr, win, ExposureMask | StructureNotifyMask | ButtonPressMask); /* finally: put window on screen */ XMapWindow(display_ptr, win); XFlush(display_ptr); /* create graphics context, so that we may draw in this window */ gc = XCreateGC(display_ptr, win, valuemask, &gc_values); XSetForeground(display_ptr, gc, BlackPixel(display_ptr, screen_num)); XSetLineAttributes(display_ptr, gc, 2, LineSolid, CapRound, JoinRound); /* and three other graphics contexts, to draw in yellow and red and grey */ gc_yellow = XCreateGC( display_ptr, win, valuemask, &gc_yellow_values); XSetLineAttributes(display_ptr, gc_yellow, 2, LineSolid, CapRound, JoinRound); if(XAllocNamedColor(display_ptr, color_map, "yellow", &tmp_color1, &tmp_color2 ) == 0) {printf("failed to get color yellow\n"); exit(-1); } else XSetForeground(display_ptr, gc_yellow, tmp_color1.pixel); gc_red = XCreateGC(display_ptr, win, valuemask, &gc_red_values); /* XSetLineAttributes(display_ptr, gc_red, 6, LineSolid, CapRound, JoinRound); */ if( XAllocNamedColor(display_ptr, color_map, "red", &tmp_color1, &tmp_color2) == 0 ) {printf("failed to get color red\n"); exit(-1);} else XSetForeground(display_ptr, gc_red, tmp_color1.pixel); gc_grey = XCreateGC(display_ptr, win, valuemask, &gc_grey_values); if( XAllocNamedColor(display_ptr, color_map, "light grey", &tmp_color1, &tmp_color2) == 0) {printf("failed to get color grey\n"); exit(-1);} else XSetForeground(display_ptr, gc_grey, tmp_color1.pixel); /* and now it starts: the event loop */ while(1) { XNextEvent( display_ptr, &report ); switch(report.type) { case Expose: /* (re-)draw the example figure. This event happens * each time some part ofthe window gets exposed (becomes visible) */ /* print all the obstacles */ for (i = 0; i < N; i++) { if (p[i].x != 0 && p[i].y != 0 && q[i].x != 0 && q[i].y !=0) { XDrawLine(display_ptr, win, gc, p[i].x, p[i].y, q[i].x, q[i].y); } } break; case ConfigureNotify: /* This event happens when the user changes the size of the window */ win_width = report.xconfigure.width; win_height = report.xconfigure.height; break; /* This event happens when the user pushes a mouse button. I draw * a circle to show the point where it happened, but do not save * the position; so when the next redraw event comes, these circles * disappear again. */ case ButtonPress: { int x, y; x = report.xbutton.x; y = report.xbutton.y; /* read point s, t */ if (press == 0) { s.x = report.xbutton.x; s.y = report.xbutton.y; } else if (press == 1) { t.x = report.xbutton.x; t.y = report.xbutton.y; } press += 1; if (report.xbutton.button == Button1) XFillArc(display_ptr, win, gc_red, x - win_height/40, y - win_height/40, win_height / 20, win_height / 20, 0, 360*64); else XFillArc(display_ptr, win, gc_yellow, x - win_height / 40, y - win_height / 40, win_height / 20, win_height / 20, 0, 360*64); printf("%d, %d, %d, %d\n", s.x, s.y, t.x, t.y); printf("press = %d\n", press); if (press == 2) { XFlush(display_ptr); /* construction graph G *s is the first point and t is the last point */ array[0].x = s.x; array[0].y = s.y; array[V-1].x = t.x; array[V-1].y = t.y; for (i = 1; i < V-1; i++) { if ( i <= N ) { array[i].x = p[i-1].x; array[i].y = p[i-1].y; } else if (i > N) { array[i].x = q[i-N-1].x; array[i].y = q[i-N-1].y; } } for (i = 0; i < V; i++) { int j; for(j = 0; j < V; j++) { if (( array[i].x == 0 && array[i].y == 0 ) || ( array[j].x == 0 && array[j].y == 0)) { G[i][j] = INT_MAX; } else { G[i][j] = distant(array[i],array[j]); } for (k = 0; k < N; k++) { if (p[k].x != 0 && p[k].y != 0 && q[k].x != 0 && q[k].y != 0 && array[i].x !=0 && array[i].y !=0 && intersect( array[i], array[j], p[k], q[k])) { G[i][j] = INT_MAX; } } } } dijkstra(G, 0, array); } } break; default: /* this is a catch-all for other events; it does not do anything. *One could look at the report type to see what the event was */ break; } } exit(0); }