Пример #1
0
/*
 * Pøipojit k serveru, zjistit o nìm informace
 */
static void open_display(void)
{
    display_name = XDisplayName(NULL);
    if(!(display = XOpenDisplay(display_name))) {
        fprintf(stderr, "Cannot connect to X server \"%s\"\n", display_name);
        exit(1);
    }
    debug("Connected to X server \"%s\"\n", display_name);

    screen_num = DefaultScreen(display);
    screen = DefaultScreenOfDisplay(display);
    debug("Default screen number is %d\n", screen_num);

    screen_width = DisplayWidth(display, screen_num);
    screen_height = DisplayHeight(display, screen_num);
    screen_width_mm = DisplayWidthMM(display, screen_num);
    screen_height_mm = DisplayHeightMM(display, screen_num);
    debug("Screen size is %ux%u pixels, %ux%u mm\n", screen_width,
          screen_height, screen_width_mm, screen_height_mm);

    root = RootWindow(display, screen_num);
    black = BlackPixel(display, screen_num);
    white = WhitePixel(display, screen_num);
    debug("Root window ID is %#lx, black is %#lx, white is %#lx\n", root,
          black, white);

    def_gc = DefaultGC(display, screen_num);
    if(!(def_font = XQueryFont(display, XGContextFromGC(def_gc)))) {
        fprintf(stderr, "XQueryFont() failed\n");
        exit(1);
    }
}
Пример #2
0
/*
 * Pøipojit k serveru, zjistit o nìm informace
 */
static void open_display(void)
{
    display_name = XDisplayName(NULL);
    if(!(display = XOpenDisplay(display_name))) {
	fprintf(stderr, "Cannot connect to X server \"%s\"\n", display_name);
	exit(1);
    }
    debug("Connected to X server \"%s\"\n", display_name);
    
    screen_num = DefaultScreen(display);
    screen = DefaultScreenOfDisplay(display);
    debug("Default screen number is %d\n", screen_num);
    
    screen_width = DisplayWidth(display, screen_num);
    screen_height = DisplayHeight(display, screen_num);
    screen_width_mm = DisplayWidthMM(display, screen_num);
    screen_height_mm = DisplayHeightMM(display, screen_num);
    debug("Screen size is %ux%u pixels, %ux%u mm\n", screen_width,
	  screen_height, screen_width_mm, screen_height_mm);
    
    root = RootWindow(display, screen_num);
    black = BlackPixel(display, screen_num);
    white = WhitePixel(display, screen_num);
    debug("Root window ID is %#lx, black is %#lx, white is %#lx\n", root,
	  black, white);

    def_gc = DefaultGC(display, screen_num);
    /* Toto volání XQueryFont() do def_font->fid neulo¾í ID fontu, ale
     * grafického kontextu! Nevím, jak získat ID nebo jméno standardního
     * fontu. */
    if(!(def_font = XQueryFont(display, XGContextFromGC(def_gc)))) {
	fprintf(stderr, "XQueryFont() failed\n");
	exit(1);
    }
}
Пример #3
0
// Set up a window.
int initWindow( long width, long height ) {
  int defScreen;
  XSetWindowAttributes wAttr;
  XGCValues gcValues;
  char buffer[64] = "Graphics";
  XTextProperty xtp = {(unsigned char *)buffer, 125, 8, strlen(buffer)};

  /*
   * connect to the X server.  uses the server specified in the
   * DISPLAY environment variable
   */
  curDisplay = XOpenDisplay((char *) NULL);
  if ((Display *) NULL == curDisplay) {
    fprintf(stderr, "Fish School Stats Display:  could not open display.\n");
      exit(-1);
  }
   
  /*
   * begin to create a window
   */
  defdepth = DefaultDepth(curDisplay,0);
  bytesPerPixel = defdepth/8;
  bytesPerPixel = bytesPerPixel == 3 ? 4 : bytesPerPixel;

  defScreen = DefaultScreen(curDisplay);

  curWindow = XCreateWindow(curDisplay, DefaultRootWindow(curDisplay),
                            10, 10, width, height, 0, 
                            defdepth, InputOutput, 
                            DefaultVisual(curDisplay, defScreen),
                            0, &wAttr);


  /*
   * request mouse button and keypress events
   */
  wAttr.event_mask = ButtonPressMask | KeyPressMask | ExposureMask;
  XChangeWindowAttributes(curDisplay, curWindow, CWEventMask, &wAttr);

  /*
   * force it to appear on the screen
   */
  XSetWMName(curDisplay, curWindow, &xtp);
  XMapWindow(curDisplay, curWindow);

  /*
   * create a graphics context.  this stores a drawing state; stuff like
   * current color and line width.  this gc is for drawing into our
   * window. 
   */
  curGC = XCreateGC(curDisplay, curWindow, 0, &gcValues);
  defaultFont = XQueryFont(curDisplay, XGContextFromGC(curGC));

  XSetWindowColormap( curDisplay,
                      curWindow,
                      DefaultColormapOfScreen(DefaultScreenOfDisplay(curDisplay)));

  return(bytesPerPixel);
}
Пример #4
0
int tela_strlen(tela_t *tela, char *s)
{
    XCharStruct char_struct;
    int z;
    XQueryTextExtents(tela->display, XGContextFromGC(tela->gc), s, strlen(s),
                      &z, &z, &z, &char_struct);
    return char_struct.width;
}
Пример #5
0
int
DPSCAPFreeGCProc(
    Display *pdpy,
    GC gc,
    XExtCodes *codes)
{
    register xCAPNotifyReq *req;
    DPSCAPData my;
    Display *dpy = pdpy;  /* Stupid macros insists on Display being 'dpy' */
    XExtData *extData = XFindOnExtensionList(
      CSDPSHeadOfDpyExt(dpy),
      codes->extension);

    if (extData)
        my = (DPSCAPData) extData->private_data;
    else
        return(0);

    /* Notify the agent that the client deleted a GC.  Let the
       agent figure out if it cares. */

    /* ASSERT: called from within LockDisplay section */

    dpy = my->agent;
    if (dpy == (Display *)NULL || dpy == pdpy)
        return(0);

    /* May need to sync changes to GC */
    if (gNXSyncGCMode == DPSNXSYNCGCMODE_DELAYED)
        XDPSLSync(pdpy);

    {
    Display *xdpy = pdpy;			    /* pdpy is X server */
    NXMacroGetReq(CAPNotify, req);
    }
    req->reqType = DPSCAPOPCODEBASE;
    req->type = X_CAPNotify;
    req->cxid = 0;
    req->notification = DPSCAPNOTE_FREEGC;
    req->data = XGContextFromGC(gc);
    req->extra = 0;
    /* Guarantee that everyone sees GC go away */
    XSync(pdpy, False);                             /* pdpy is X server */
    if (gNXSyncGCMode == DPSNXSYNCGCMODE_FLUSH)
        {
        LockDisplay(dpy);                           /* dpy means agent here */
        N_XFlush(dpy);
        UnlockDisplay(dpy);
	}
    else
        XDPSLSync(pdpy);

    /* ASSERT: SynchHandle called by caller */
    return(1);
}
Пример #6
0
tamanho_t tela_tamanho_texto(tela_t *t, char *s)
{
    XCharStruct char_struct;
    tamanho_t tam;
    int z;
    XQueryTextExtents(t->display, XGContextFromGC(t->gc), s, strlen(s),
		      &z, &z, &z, &char_struct);
    tam.larg= char_struct.width;
    tam.alt= char_struct.ascent;	// + char_struct.descent;
    return tam;
}
Пример #7
0
void HelloWorld::_drawStringCentered(const GC& gc, const char* str, int x, int y,
                                     int w, int h) {
    int direction, ascent, descent;
    XCharStruct strDimensions;
    XTextExtents(XQueryFont(_display, XGContextFromGC(gc)), str, strlen(str),
            &direction, &ascent, &descent, &strDimensions);

    int newX = x + (w - strDimensions.width) / 2;
    int newY = y + (h + strDimensions.ascent - strDimensions.descent) / 2;
    _drawString(gc, str, newX, newY);
}
Пример #8
0
static int query_font_geometry (Display *dpy, GC gc, const char *txt, int *w, int *h, int *a, int *d) {
	XCharStruct text_structure;
	int font_direction, font_ascent, font_descent;
	XFontStruct *fontinfo = XQueryFont (dpy, XGContextFromGC (gc));

	if (!fontinfo) { return -1; }
	XTextExtents (fontinfo, txt, strlen (txt), &font_direction, &font_ascent, &font_descent, &text_structure);
	if (w) *w = XTextWidth (fontinfo, txt, strlen (txt));
	if (h) *h = text_structure.ascent + text_structure.descent;
	if (a) *a = text_structure.ascent;
	if (d) *d = text_structure.descent;
	XFreeFontInfo (NULL, fontinfo, 1);
	return 0;
}
Пример #9
0
/*
 * Set specified font for that GC.
 * Return font that is used for this GC, even if setting a new
 * font failed (return default font in that case).
 */
static XFontStruct* Set_font(Display* display, GC gc,
			     const char* fontName,
			     const char *resName)
{
    XFontStruct*	font;

    if ((font = XLoadQueryFont(display, fontName)) == NULL) {
	error("Couldn't find font '%s' for %s, using default font",
	      fontName, resName);
	font = XQueryFont(display, XGContextFromGC(gc));
    } else
	XSetFont(display, gc, font->fid);

    return font;
}
Пример #10
0
static void
load_font(XFontStruct **font_info, char *fontname)
{
   if ((*font_info = XLoadQueryFont(gXDisplay, fontname)) == NULL) {
        fprintf(stderr, "(HyperDoc) Cannot load font %s ; using default.\n",
            fontname);

        if ((*font_info = XQueryFont(gXDisplay,
               XGContextFromGC(DefaultGC(gXDisplay, gXScreenNumber)))) == NULL)
        {
            fprintf(stderr, "(HyperDoc) Cannot get default font ; exiting.\n");
            exit(-1);
        }
   }
}
Пример #11
0
void
print_help() 
{
    static char str[80];
    static int y_str, spacing;
    static int ascent, descent, dir;
    static XCharStruct overall;
    static GC gc;

    gc = Data_GC[1];
    XClearWindow(dpy, help);
    y_str = 60;
    sprintf(str,"During run-time, interactive control can be exerted via : ");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    XQueryTextExtents(dpy,(XID)XGContextFromGC(gc),"Hey!",
			4,&dir,&ascent,&descent,&overall);
    spacing = ascent + descent + 5;
    y_str += 2 * spacing;
    sprintf(str,"        - lowers the value of mincolindex, + raises it");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        f or F saves coral to a PPM file");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        h or H or ? displays this message");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        n goes on to the next coral");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        N creates a new replacement coral");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        r or s spins the colorwheel");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        w decrements, W increments the color wheel index");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"        q or Q exits");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
    y_str += 2*spacing;
    sprintf(str,"Press 'h', 'H', or '?' to unmap the help window");
    XDrawImageString(dpy,help,gc,x_str,y_str,str,strlen(str));
}
Пример #12
0
      rectangle get_text_rect ( std::string text )
	{
	  int direction = 0, font_ascent = 0, font_descent = 0;
	  XCharStruct char_struct;

	  XQueryTextExtents ( m_display,
			      XGContextFromGC(m_gc),
			      text.c_str(),
			      text.size(),
			      &direction,
			      &font_ascent,
			      &font_descent,
			      &char_struct );

	  rectangle rect ( point(0,0),
			   char_struct.rbearing - char_struct.lbearing,
			   char_struct.ascent - char_struct.descent );

	  return rect;

	}
Пример #13
0
void
Tk_FreeGC(
    Display *display,		/* Display for which gc was allocated. */
    GC gc)			/* Graphics context to be released. */
{
    Tcl_HashEntry *idHashPtr;
    register TkGC *gcPtr;
    TkDisplay *dispPtr = TkGetDisplay(display);

    if (!dispPtr->gcInit) {
	Tcl_Panic("Tk_FreeGC called before Tk_GetGC");
    }
    if (dispPtr->gcInit < 0) {
	/*
	 * The GCCleanup has been called, and remaining GCs have been freed.
	 * This may still get called by other things shutting down, but the
	 * GCs should no longer be in use.
	 */

	return;
    }

    idHashPtr = Tcl_FindHashEntry(&dispPtr->gcIdTable, (char *) gc);
    if (idHashPtr == NULL) {
	Tcl_Panic("Tk_FreeGC received unknown gc argument");
    }
    gcPtr = Tcl_GetHashValue(idHashPtr);
    gcPtr->refCount--;
    if (gcPtr->refCount == 0) {
	Tk_FreeXId(gcPtr->display, (XID) XGContextFromGC(gcPtr->gc));
	XFreeGC(gcPtr->display, gcPtr->gc);
	Tcl_DeleteHashEntry(gcPtr->valueHashPtr);
	Tcl_DeleteHashEntry(idHashPtr);
	ckfree(gcPtr);
    }
}
Пример #14
0
void ptitle ( char *title, int *titleIndex )
#endif


/***********************************************************************
 *
 *	Copyright 1997, University Corporation for Atmospheric Research.
 *
 *	ptitle.c
 *
 *	Image display routine.
 *
 *	History:
 *
 *	11/97	COMET	Original copy
 *	11/97	COMET	Changed titleIndex to index starting at "0"
 *			instead of "1">
 *	 3/98	COMET	Added test for title display.
 *	 3/98	COMET	Added XFlush() call and reset text attributes.
 *	 3/98	COMET	Removed XFlush() and added color setting
 *	 5/99	COMET	Return if title length < 2 since a blank title
 *			is lengthened to 1 by MakeMotTitle.
 *	 5/99	COMET	Commented out GEMPAK color setting functions
 *			to get correct title color.
 *
 ***********************************************************************/

{
	WindowObjectType	*wo;
	GlobalDataObjectType	*gd;
	TitleObjectType		*tot;

	int    		ipxm; 
	Pixmap 		gempixmap; 
	GC     		gemgc; 
	Dimension	width;		/* string width in pixels */
	Dimension	iy, ix;
        int             direction, ascent, descent;
	int		lenstr;
	int		itype = 0, lineWidth;
	int		i, iret, verbose, titleLine;
	Dimension	xmax, ymax;
        XCharStruct     overall;
	Display		*display;
	char		*str;

        int     gcolr, oldcolr;
        int     mode, gtxfn, gtxhw, gtxwid, dtxfn, dtxhw, dtxwid;
        float   gsztext, dsztext;
	int     ibrdr, irrotn, ijust, dbrdr, drrotn, djust; /* chiz */

/*---------------------------------------------------------------------*/

	verbose = GetVerboseLevel();
	if( verbose > VERBOSE_0 )
	    printf ( "ptitle\n" );

	wo = GetActiveWindowObject();
	tot = wo->titleObject;
	gd = GetGlobalDataObject();

/*
 *	Return if there is no title or if title is toggled off.
 *	MakeMotTitle returns a title of at least one character.
 */
	if ( title == NULL || strlen ( title ) < 2 ) return;
	if ( ! GetTitleFlag ( gd ) ) return;

/*
 *	Remove trailing blanks.
 */
	strbrm ( title );

/*
 *	Set the title line number.
 */
	titleLine = -1 * (*titleIndex + 1);
	i = *titleIndex;

	str = strdup ( title );
	strbrm ( str );
	lenstr = strlen ( str );

	/* chiz/Unidata update for xwcmn.h array of pixmaps */	
        ipxm      = gemwindow[current_window].curpxm[0]; 
        gempixmap = gemwindow[current_window].pxms[0][ipxm]; 
        gemgc     = gemwindow[current_window].gc; 
	display   = GetWindowObjectDisplay( wo );

/*
 *	Make sure the text attributes are set correctly, since we are
 *	bypassing GEMPAK routines to draw the title.
 */
/*
        gqtext ( &gtxfn, &gtxhw, &gsztext, &gtxwid, &ibrdr, &irrotn, &ijust, &iret);
        dstext ( &gtxfn, &gtxhw, &gsztext, &gtxwid, &ibrdr, &irrotn, &ijust,
                 &dtxfn, &dtxhw, &dsztext, &dtxwid, &dbrdr, &drrotn, &djust, &iret);
	gqcolr ( &gcolr, &iret );
	dscolr ( &gcolr, &oldcolr, &iret );
*/

        /*
         * Get string width for alignment
         */

        XQueryTextExtents(gemdisplay, XGContextFromGC(gemgc),
                str, lenstr, &direction, &ascent, &descent,
                &overall);

        width = overall.width;
	lineWidth = ascent + descent;

	xmax = GetWindowObjectWidth ( wo );
	ymax = GetWindowObjectHeight ( wo );

	/*
	 * Justify alignment for different value of *itype
	 */

	switch (itype) {
	    case  0: /* centered */

			ix = (xmax - width) / 2;
			break;

	    case  1: /* right justified */

			ix = xmax - width;
			break;

	    case -1: /* left justified */
			ix = 2;
			break;

	    default: 
			ix = 2;
			break;
	    }
	
	/*
	 * Draw string on window
	 */

	iy = ymax + ((titleLine + 1) * lineWidth) - descent;

/*
 *	Define cursor active region for title.
 */
	if ( verbose > VERBOSE_1 )
	    printf("  title number = %d\n", i );

	tot->region[i].x1 = ix;
	tot->region[i].y1 = iy;
	tot->region[i].x2 = ix + width;
	tot->region[i].y2 = iy - lineWidth;

	if ( verbose > VERBOSE_1 ) {
	    printf("  region: %d,", tot->region[i].x1 );
	    printf(" %d",           tot->region[i].y1 );
	    printf("     %d,",      tot->region[i].x2 );
	    printf(" %d\n",         tot->region[i].y2 ); 
	}
/*
 *	Write title.
 */
	XDrawString ( gemdisplay, gempixmap, gemgc, ix, iy, str,
                      lenstr );

/*
 *	Draw rectangle around string.
 */
/*
	XDrawRectangle ( gemdisplay, gempixmap, gemgc,
	  tot->region[i].x1,
	  tot->region[i].y2,
	  tot->region[i].x2 - tot->region[i].x1,
	  tot->region[i].y1 - tot->region[i].y2 );
*/
	
	Free ( str );
}
Пример #15
0
void
initializeWindowSystem(void)
{
    char *display_name = NULL;
    XColor fg, bg;
#if 0
    XColor rgbdef;
#endif
    Colormap cmap;
    Pixmap  mousebits, mousemask;
/*    fprintf(stderr,"initx:initializeWindowSystem:entered\n");*/
    /* Try to open the display */
/*    fprintf(stderr,"initx:initializeWindowSystem:XOpenDisplay\n");*/
    if ((gXDisplay = XOpenDisplay(display_name)) == NULL) {
        fprintf(stderr, "(HyperDoc) Cannot connect to the X11 server!\n");
        exit(-1);
    }

    /* Get the screen */
/*    fprintf(stderr,"initx:initializeWindowSystem:DefaultScreen\n");*/
    gXScreenNumber = scrn = DefaultScreen(gXDisplay);
/*    fprintf(stderr,"initx:initializeWindowSystem:XGContextFromGC\n");*/
    server_font =XGContextFromGC(DefaultGC(gXDisplay, gXScreenNumber));

    /* Get the cursors we need. */

/*    fprintf(stderr,"initx:initializeWindowSystem:DefaultColormap\n");*/
    cmap = DefaultColormap(gXDisplay, gXScreenNumber);
/*    fprintf(stderr,"initx:initializeWindowSystem:WhitePixel\n");*/
    fg.pixel = WhitePixel(gXDisplay,gXScreenNumber);
/*    fprintf(stderr,"initx:initializeWindowSystem:XQueryColor\n");*/
    XQueryColor(gXDisplay, cmap, &fg );
/*    fprintf(stderr,"initx:initializeWindowSystem:BlackPixel\n");*/
    bg.pixel = BlackPixel(gXDisplay,gXScreenNumber);
/*    fprintf(stderr,"initx:initializeWindowSystem:XQueryColor2\n");*/
    XQueryColor(gXDisplay, cmap, &bg );
#if 0
    XAllocNamedColor(gXDisplay, cmap, "Black", &fg, &rgbdef);
    XAllocNamedColor(gXDisplay, cmap, "White", &bg, &rgbdef);
#endif

#ifdef USE_BORING_OLD_CURSORS
    gActiveCursor = XCreateFontCursor(gXDisplay, XC_circle);
    gNormalCursor = XCreateFontCursor(gXDisplay, XC_dot);
#else
/*  fprintf(stderr,"initx:initializeWindowSystem:XCreateBitmapFromData 1\n");*/
    mousebits = XCreateBitmapFromData(gXDisplay,
        RootWindow(gXDisplay, gXScreenNumber),
        ucharp_to_charp(mouseBitmap_bits),
        mouseBitmap_width,mouseBitmap_height);
/* fprintf(stderr,"initx:initializeWindowSystem:XCreateBitmapFromData 2\n");*/
    mousemask = XCreateBitmapFromData(gXDisplay,
        RootWindow(gXDisplay, gXScreenNumber),
        ucharp_to_charp(mouseMask_bits), mouseMask_width,mouseMask_height);
/* fprintf(stderr,"initx:initializeWindowSystem:XCreateBitmapFromData 2\n");*/
    gActiveCursor = XCreatePixmapCursor(gXDisplay,
        mousebits, mousemask, &fg, &bg,
        mouseBitmap_x_hot,mouseBitmap_y_hot);

/*    fprintf(stderr,"initx:initializeWindowSystem:XCreateFontCursor\n");*/
    gNormalCursor = XCreateFontCursor(gXDisplay, XC_left_ptr);
#endif

/*    fprintf(stderr,"initx:initializeWindowSystem:XCreateFontCursor 2\n");*/
    gBusyCursor = XCreateFontCursor(gXDisplay, XC_watch);

    /* Now initialize all the colors and fonts */

/*    fprintf(stderr,"initx:initializeWindowSystem:ingItColors_and_fonts\n");*/
    ingItColors_and_fonts();
/*    fprintf(stderr,"initx:initializeWindowSystem:init_text\n");*/
    init_text();
/*    fprintf(stderr,"initx:initializeWindowSystem:exited\n");*/

}
Пример #16
0
/*
 * General text formatting routine which does wrap around
 * if necessary at whitespaces.  The function returns the
 * vertical position it ended at.
 */
int DrawShadowText(Display *display, Window w, GC gc,
		   int x_border, int y_start, const char *str,
		   unsigned long fg, unsigned long bg)
{
    XFontStruct		*font = XQueryFont(display, XGContextFromGC(gc));
    int			y, x, tmp;
    int                 count = 1;
    XWindowAttributes	wattr;

    if (str == NULL || *str == '\0')
	return 0;

    /* Get width of window */
    XGetWindowAttributes(display, w, &wattr);

    /* Start position */
    x = x_border;
    y = y_start + font->ascent;

    do {
	char word[LINE_MAX];
	int wordLen, i;

	for (i = 0; *str && !isspace(*str) && i < LINE_MAX-1; str++, i++)
	    word[i] = *str;
	word[i] = '\0';

	/* Word length in pixels */
	wordLen = XTextWidth(font, word, i);

	/* We need a linebreak? */
	if (x + wordLen > wattr.width - BORDER) {
	    x = x_border;
	    y += font->ascent + font->descent + 1;
	}

	/* Draw word and move cursor to point to after this word */
	ShadowDrawString(display, w, gc, x, y, word, fg, bg);
	x += wordLen;

	/* Handle whitespace */
	for (; isspace(*str); str++)
	    switch (*str) {
		/* New paragraph */
	    case '\n':
		x = x_border;
		y += font->ascent + font->descent + 1;
		break;

		/* Just a space */
	    default:
		x += XTextWidth(font, " ", 1);
		break;
	    }
    } while (*str != '\0');

    tmp = font->descent+1;

    XFreeFontInfo(NULL, font, count);

    return y + tmp;
}
Пример #17
0
/* ARGSUSED */
static void Initialize (
    Widget greq,
    Widget gnew,
    ArgList args,
    Cardinal *num_args)
{
    LoginWidget w = (LoginWidget)gnew;
    XtGCMask	valuemask, xvaluemask;
    XGCValues	myXGCV;
    Arg		position[2];
    Position	x, y;
#ifdef USE_XINERAMA
    XineramaScreenInfo *screens;
    int                 s_num;
#endif

#ifdef XPM
    myXGCV.foreground = w->login.hipixel;
    myXGCV.background = w->core.background_pixel;
    valuemask = GCForeground | GCBackground;
    w->login.hiGC = XtGetGC(gnew, valuemask, &myXGCV);

    myXGCV.foreground = w->login.shdpixel;
    myXGCV.background = w->core.background_pixel;
    valuemask = GCForeground | GCBackground;
    w->login.shdGC = XtGetGC(gnew, valuemask, &myXGCV);
#endif /* XPM */

    myXGCV.foreground = w->login.textpixel;
    myXGCV.background = w->core.background_pixel;
    valuemask = GCForeground | GCBackground;
    if (w->login.font) {
	myXGCV.font = w->login.font->fid;
	valuemask |= GCFont;
    }
    w->login.textGC = XtGetGC(gnew, valuemask, &myXGCV);
    myXGCV.foreground = w->core.background_pixel;
    w->login.bgGC = XtGetGC(gnew, valuemask, &myXGCV);

    myXGCV.foreground = w->login.textpixel ^ w->core.background_pixel;
    myXGCV.function = GXxor;
    xvaluemask = valuemask | GCFunction;
    w->login.xorGC = XtGetGC (gnew, xvaluemask, &myXGCV);

    /*
     * Note that the second argument is a GCid -- QueryFont accepts a GCid and
     * returns the curently contained font.
     */

    if (w->login.font == NULL)
	w->login.font = XQueryFont (XtDisplay (w),
		XGContextFromGC (XDefaultGCOfScreen (XtScreen (w))));

    xvaluemask = valuemask;
    if (w->login.promptFont == NULL)
        w->login.promptFont = w->login.font;
    else
	xvaluemask |= GCFont;

    myXGCV.foreground = w->login.promptpixel;
    myXGCV.font = w->login.promptFont->fid;
    w->login.promptGC = XtGetGC (gnew, xvaluemask, &myXGCV);

    xvaluemask = valuemask;
    if (w->login.greetFont == NULL)
    	w->login.greetFont = w->login.font;
    else
	xvaluemask |= GCFont;

    myXGCV.foreground = w->login.greetpixel;
    myXGCV.font = w->login.greetFont->fid;
    w->login.greetGC = XtGetGC (gnew, xvaluemask, &myXGCV);

    xvaluemask = valuemask;
    if (w->login.failFont == NULL)
	w->login.failFont = w->login.font;
    else
	xvaluemask |= GCFont;

    myXGCV.foreground = w->login.failpixel;
    myXGCV.font = w->login.failFont->fid;
    w->login.failGC = XtGetGC (gnew, xvaluemask, &myXGCV);

#ifdef XPM
    w->login.logoValid = False;

    if (NULL != w->login.logoFileName)
    {
        XpmAttributes myAttributes = { 0 };
        Window tmpWindow = { 0 };
        struct stat myBuffer = { 0 };
        unsigned int myPixmapDepth = 0;

        if (0 != stat(w->login.logoFileName, &myBuffer))
        {
            LogError("Unable to stat() pixmap file %s\n",
                w->login.logoFileName);
            w->login.logoValid = False;
            goto SkipXpmLoad;
        }
        else

        myAttributes.valuemask |= XpmReturnPixels;
        myAttributes.valuemask |= XpmReturnExtensions;

        XpmReadFileToPixmap(XtDisplay(w),            /* display */
            RootWindowOfScreen(XtScreen(w)),         /* window */
            w->login.logoFileName,                   /* XPM filename */
            &(w->login.logoPixmap),                  /* pixmap */
            &(w->login.logoMask),                    /* pixmap mask */
            &myAttributes);                          /* XPM attributes */
        w->login.logoValid = True;

        XGetGeometry(XtDisplay(w), w->login.logoPixmap,
            &tmpWindow,
            &(w->login.logoX),
            &(w->login.logoY),
            &(w->login.logoWidth),
            &(w->login.logoHeight),
            &(w->login.logoBorderWidth),
            &myPixmapDepth);
    } else {
	w->login.logoX = 0;
	w->login.logoY = 0;
	w->login.logoWidth = 0;
	w->login.logoHeight = 0;
	w->login.logoBorderWidth = 0;
    }


SkipXpmLoad:
#endif /* XPM */
    w->login.data.name[0] = '\0';
    w->login.data.passwd[0] = '\0';
    w->login.state = GET_NAME;
    w->login.cursor = 0;
    w->login.failUp = 0;
    if (w->core.width == 0)
	w->core.width = max (GREET_W(w), FAIL_W(w)) + PAD_X(w);
    if (w->core.height == 0) {
	int fy = FAIL_Y(w);
	int pady = PAD_Y(w);

#ifndef XPM
	w->core.height = fy + pady;	/* for stupid compilers */
#else
/*	w->core.height = fy + pady;	* for stupid compilers */

        w->core.height = max(fy + pady,
            (w->login.logoHeight + (2*w->login.logoPadding)) + pady);
        
#endif /* XPM */
    }
#ifdef USE_XINERAMA
    if (
	XineramaIsActive(XtDisplay(w)) &&
	(screens = XineramaQueryScreens(XtDisplay(w), &s_num)) != NULL
       )
    {
	if ((x = w->core.x) == -1)
	    x = screens[0].x_org + (int)(screens[0].width - w->core.width) / 2;
	if ((y = w->core.y) == -1)
	    y = screens[0].y_org + (int)(screens[0].height - w->core.height) / 3;
	
	XFree(screens);
    }
    else
#endif
    {
	if ((x = w->core.x) == -1)
	    x = (int)(XWidthOfScreen (XtScreen (w)) - w->core.width) / 2;
	if ((y = w->core.y) == -1)
	    y = (int)(XHeightOfScreen (XtScreen (w)) - w->core.height) / 3;
    }
    XtSetArg (position[0], XtNx, x);
    XtSetArg (position[1], XtNy, y);
    XtSetValues (XtParent (w), position, (Cardinal) 2);
}
Пример #18
0
 long id() { return XGContextFromGC(m_gc); }
Пример #19
0
void
DPSCAPChangeGC(
    register Display *agent,
    GC gc,
    unsigned long valuemask,
    XGCValues *values)
{
    register xChangeGCReq *req;
    unsigned long oldDirty = gc->dirty;

    /* ASSERT: called from within LockDisplay section */

    /* Always include the clip_mask */
    valuemask |= GCClipMask;
    /* +++ HACK!  Hide the gc->rects flag in arc_mode */
    valuemask |= GCArcMode;
    valuemask &= (1L << (GCLastBit + 1)) - 1;

    /* Stupid macro insists on Display being called 'dpy' */
    {
    Display *dpy = agent;
    Display *xdpy = (Display *)NULL;
    NXMacroGetReq(ChangeGC, req);
    }
    req->gc = XGContextFromGC(gc);
    gc->dirty = req->mask = valuemask;
    {
/* Derived from MIT XCrGC.c, _XGenerateGCList:
Copyright 1985, 1986, 1987, 1988, 1989 by the
Massachusetts Institute of Technology

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of M.I.T. not be used in advertising or
publicity pertaining to distribution of the software without specific,
written prior permission.  M.I.T. makes no representations about the
suitability of this software for any purpose.  It is provided "as is"
without express or implied warranty.
*/
    /* Warning!  This code assumes that "unsigned int" is 32-bits wide */

    unsigned int vals[32];
    register unsigned int *value = vals;
    long nvalues;
    register XGCValues *gv = values;
    register unsigned long dirty = gc->dirty;

    /*
     * Note: The order of these tests are critical; the order must be the
     * same as the GC mask bits in the word.
     */
    if (dirty & GCFunction)          *value++ = gv->function;
    if (dirty & GCPlaneMask)         *value++ = gv->plane_mask;
    if (dirty & GCForeground)        *value++ = gv->foreground;
    if (dirty & GCBackground)        *value++ = gv->background;
    if (dirty & GCLineWidth)         *value++ = gv->line_width;
    if (dirty & GCLineStyle)         *value++ = gv->line_style;
    if (dirty & GCCapStyle)          *value++ = gv->cap_style;
    if (dirty & GCJoinStyle)         *value++ = gv->join_style;
    if (dirty & GCFillStyle)         *value++ = gv->fill_style;
    if (dirty & GCFillRule)          *value++ = gv->fill_rule;
    if (dirty & GCTile)              *value++ = gv->tile;
    if (dirty & GCStipple)           *value++ = gv->stipple;
    if (dirty & GCTileStipXOrigin)   *value++ = gv->ts_x_origin;
    if (dirty & GCTileStipYOrigin)   *value++ = gv->ts_y_origin;
    if (dirty & GCFont)              *value++ = gv->font;
    if (dirty & GCSubwindowMode)     *value++ = gv->subwindow_mode;
    if (dirty & GCGraphicsExposures) *value++ = gv->graphics_exposures;
    if (dirty & GCClipXOrigin)       *value++ = gv->clip_x_origin;
    if (dirty & GCClipYOrigin)       *value++ = gv->clip_y_origin;
    if (dirty & GCClipMask)          *value++ = gv->clip_mask;
    if (dirty & GCDashOffset)        *value++ = gv->dash_offset;
    if (dirty & GCDashList)          *value++ = gv->dashes;
    /* +++ HACK!  Hide gc->rects flag in GCArcMode */
    if (dirty & GCArcMode)           *value++ = gc->rects;

    req->length += (nvalues = value - vals);

    /*
     * note: Data is a macro that uses its arguments multiple
     * times, so "nvalues" is changed in a separate assignment
     * statement
     */

    nvalues <<= 2;
    Data32 (agent, (long *) vals, nvalues);
    }

    gc->dirty = oldDirty;

    /* ASSERT: SyncHandle called by caller */
}
Пример #20
0
/* function */
void xContour(Display *dpy, Window win,GC gcc, GC gcl, 
	       float *cp,int nx, float x[], int ny, float y[], float z[], 
	       char lcflag,char *lcf,char *lcc, float *w, int nplaces)
/**************************************************************************
xContour - draw contour of a two-dimensional array via X
***************************************************************************
Input:
dpy                     the display to make the contour
win                     the window to draw in
gcc                     GC for the contour lines
gcl                     GC for the contour labels
cp			pointer to the contour value
nx			number of x-coordinates
x			array of x-coordinates (see notes below)
ny			number of y-coordinates
y			array of y-coordinates (see notes below)
lcflag                  flag that defines if we actually are going to have labels 
Least Significat Bits:
z			array of nx*ny z(x,y) values (see notes below)
w			array of nx*ny z(x,y) values (see notes below)
***************************************************************************
Notes:
The two-dimensional array z is actually passed as a one-dimensional
array containing nx*ny values, stored with nx fast and ny slow.

The x and y arrays define a grid that is not necessarily 
uniformly-sampled.  Linear interpolation of z values on the 
grid defined by the x and y arrays is used to determine z values 
between the gridpoints.
		 
The two least significant bits of z are used to mark intersections
of the contour with the x,y grid; therefore, the z values will
almost always be altered (slightly) by contour.

xContour is a modified version of psContour where the use of conmove
and condraw call have been changed to match X-Windows.

Since XDrawLine requires a start and end point, the use of a manually update
of the position variables x0 and y0 is used instead of conmove.

if lcflag is zero no labels are drawn

The w array is used to restrict the range of contour labeling that 
occurs only if w<1. 

As suggested in the reference, the following scheme is used to refer
to a cell of the two-dimensional array z:

                north (0)
      (ix,iy+1)	--------- (ix+1,iy+1)
                | cell  |
       west (3)	| ix,iy	| east (1)
                |       |
        (ix,iy) --------- (ix+1,iy)
                south (2)

***************************************************************************
Reference:
Cottafava, G. and Le Moli, G., 1969, Automatic contour map:
Commuincations of the ACM, v. 12, n. 7, July, 1969.

***************************************************************************
Author:  Morten Wendell Pedersen Aarhus University 07/20/96
Heavily based on psContour by
  Dave Hale, Colorado School of Mines, 06/28/89
  and with contour labeling added by: Zhenyue Liu, June 1993
(actually most of the credit should go to these two guys)
***************************************************************************/
{
	int ix,iy,non,cell,startcell;
	float d;
	float xmin = MIN(x[0],x[nx-1]), xmax = MAX(x[0],x[nx-1]);
	float ymin = MIN(y[0],y[ny-1]), ymax = MAX(y[0],y[ny-1]);
	float xc=0.0, yc=0.0;	/* contour labeling centered at (xc,yc)	*/
 	float xw, yw;	/* width and length of contour labeling */
	float xd, yd;	/* point on contour			*/
	float x0, y0;    /* start plot values (instead of move operation )*/   
	float xdmin, xdmax, ydmin, ydmax; /* range of contour	*/
	int id;	/* =0 if a point on contour has been used as (xc,yc) */
	int cells=0;
	char str[20];
	XCharStruct overall;
	int dummy;
	float c=*cp; /* stupid thing I had to do since I couldn't transfer
			a float without messing up everything 
			but I could transfer a pointer....strange thing
			I will have to track this thing down one day*/

	/* convert a number into a string */
	sprintf(str,"%.*g",nplaces,c);

	/* determine length and width for printing the string */
	XQueryTextExtents(dpy,XGContextFromGC(gcl),str,(int) strlen(str),&dummy,&dummy,&dummy,&overall);
	xw=overall.width;
        yw=overall.ascent+overall.descent;

	/* restrict contour labeling from edges */
	for (iy=0; iy<ny-1; iy++)  
		for (ix=0,cell=iy*nx; ix<nx-1; ix++,cell++) {
			if(x[ix]<xmin+2.0*xw || x[ix]>xmax-2.0*xw 
 				|| y[iy]<ymin+yw || y[iy]>ymax-yw)
  				w[cell] += 1.;
 		}
 
	/* count intersections with cell boundaries */
	non = 0;

	/* find all the intersections */
	for (iy=0; iy<ny; iy++) {
		for (ix=0,cell=iy*nx; ix<nx; ix++,cell++) {

			/* check for intersection with west edge of cell */
			if (iy<ny-1 && BTWN(c,z[cell],z[cell+nx])) {
				SETW(z[cell]);  non++;
			} else {
				CLRW(z[cell]);
			}

			/* check for intersection with south edge of cell */
			if (ix<nx-1 && BTWN(c,z[cell],z[cell+1])) {
				SETS(z[cell]);  non++;
			} else {
				CLRS(z[cell]);
			}
		}
	}


	/* follow contours intersecting north boundary */
	for (ix=0,startcell=(ny-1)*nx; non>0&&ix<nx-1; ix++,startcell++) {
		if (SSET(z[startcell])) {
			d = DELTA(c,z[startcell],z[startcell+1]);
			x0=(1.0-d)*x[ix]+d*x[ix+1];
			y0=y[ny-1];
			CLRS(z[startcell]);  non--;
			cell = startcell-nx;
			id = 1; 
			xdmin = xmax;
			xdmax = xmin;
			ydmin = ymax;
			ydmax = ymin;
			while (connect(dpy, win,gcc,c,nx,x,ny,y,z,&cell,&xd,&yd,&x0,&y0)){
			  x0=xd;y0=yd;
				 non--;
				if(w[cell]<0.5 && id) {
					xc = xd; yc = yd;
					cells = cell;
					id = 0;
				}
				xdmin = MIN(xdmin,xd);
				xdmax = MAX(xdmax,xd);
				ydmin = MIN(ydmin,yd);
				ydmax = MAX(ydmax,yd);
			}
			if(lcflag && id==0 && xdmax+ydmax-xdmin-ydmin>xw+yw) {
				wcell(nx,x,ny,y,w,cells,xc,yc,xw,yw);
 				labelc(dpy,win,gcl,xc-xw/2,yc-yw/2,xw,yw,str,lcf,lcc);
			}
		}
	}

	/* follow contours intersecting east boundary */
	for (iy=0,startcell=nx-1; non>0&&iy<ny-1; iy++,startcell+=nx) {
		if (WSET(z[startcell])) {
			d = DELTA(c,z[startcell],z[startcell+nx]);
			x0=x[nx-1];
			y0=(1.0-d)*y[iy]+d*y[iy+1];
			CLRW(z[startcell]);  non--;
			cell = startcell-1;
			id = 1; 
			xdmin = xmax;
			xdmax = xmin;
			ydmin = ymax;
			ydmax = ymin;
			while (connect(dpy, win,gcc,c,nx,x,ny,y,z,&cell,&xd,&yd,&x0,&y0)){
			  x0=xd;y0=yd;
				 non--;
				if(w[cell]<0.5 && id) {
					xc = xd; yc = yd;
					cells = cell;
					id = 0;
				}
				xdmin = MIN(xdmin,xd);
				xdmax = MAX(xdmax,xd);
				ydmin = MIN(ydmin,yd);
				ydmax = MAX(ydmax,yd);
			}
			if(lcflag && id==0 && xdmax+ydmax-xdmin-ydmin>xw+yw) {
				wcell(nx,x,ny,y,w,cells,xc,yc,xw,yw);
 				labelc(dpy,win,gcl,xc-xw/2,yc-yw/2,xw,yw,str,lcf,lcc);
			}
		}
	}

	/* follow contours intersecting south boundary */
	for (ix=0,startcell=0; non>0&&ix<nx-1; ix++,startcell++) {
		if (SSET(z[startcell])) {
			d = DELTA(c,z[startcell],z[startcell+1]);
			x0=(1.0-d)*x[ix]+d*x[ix+1];
			y0=y[0];
			CLRS(z[startcell]);  non--;
			cell = startcell;
			id = 1; 
			xdmin = xmax;
			xdmax = xmin;
			ydmin = ymax;
			ydmax = ymin;
			while (connect(dpy, win,gcc,c,nx,x,ny,y,z,&cell,&xd,&yd,&x0,&y0)){
			  x0=xd;y0=yd;
				 non--;
				if(w[cell]<0.5 && id) {
					xc = xd; yc = yd;
					cells = cell;
					id = 0;
				}
				xdmin = MIN(xdmin,xd);
				xdmax = MAX(xdmax,xd);
				ydmin = MIN(ydmin,yd);
				ydmax = MAX(ydmax,yd);
			}
			if(lcflag && id==0 && xdmax+ydmax-xdmin-ydmin>xw+yw) {
				wcell(nx,x,ny,y,w,cells,xc,yc,xw,yw);
 				labelc(dpy,win,gcl,xc-xw/2,yc-yw/2,xw,yw,str,lcf,lcc);
			}
		}		 
	}

	/* follow contours intersecting west boundary */
	for (iy=0,startcell=0; non>0&&iy<ny-1; iy++,startcell+=nx) {
		if (WSET(z[startcell])) {
			d = DELTA(c,z[startcell],z[startcell+nx]);
			x0=x[0];
			y0=(1.0-d)*y[iy]+d*y[iy+1];
			CLRW(z[startcell]);  non--;
			cell = startcell;
			id = 1; 
			xdmin = xmax;
			xdmax = xmin;
			ydmin = ymax;
			ydmax = ymin;
			while (connect(dpy, win,gcc,c,nx,x,ny,y,z,&cell,&xd,&yd,&x0,&y0)){
			  x0=xd;y0=yd;
				 non--;
				if(w[cell]<0.5 && id) {
					xc = xd; yc = yd;
					cells = cell;
					id = 0;
				}
				xdmin = MIN(xdmin,xd);
				xdmax = MAX(xdmax,xd);
				ydmin = MIN(ydmin,yd);
				ydmax = MAX(ydmax,yd);
			}
			if(lcflag && id==0 && xdmax+ydmax-xdmin-ydmin>xw+yw) {
				wcell(nx,x,ny,y,w,cells,xc,yc,xw,yw);
 				labelc(dpy,win,gcl,xc-xw/2,yc-yw/2,xw,yw,str,lcf,lcc);
			}
		}
	}

	/* follow interior contours */
	for (iy=1; iy<ny-1; iy++) {
		for (ix=0,startcell=iy*nx; non>0&&ix<nx-1; ix++,startcell++) {

			/* check south edge of cell */
			if (SSET(z[startcell])) {
				d = DELTA(c,z[startcell],z[startcell+1]);
				x0=(1.0-d)*x[ix]+d*x[ix+1];
				y0=y[iy];

				/* clear south edge where we started */
				CLRS(z[startcell]);  non--;

				cell = startcell;

				/* if another intersection exists in this cell */
				if (connect(dpy, win,gcc,c,nx,x,ny,y,z,&cell,&xd,&yd,&x0,&y0)) {
				  x0=xd;y0=yd;
			  
				  /* set south edge so that we finish where we started */
					SETS(z[startcell]);  non++;
			
					/* follow the contour */
			id = 1; 
			xdmin = xmax;
			xdmax = xmin;
			ydmin = ymax;
			ydmax = ymin;
			while (connect(dpy, win,gcc,c,nx,x,ny,y,z,&cell,&xd,&yd,&x0,&y0)){
			  x0=xd;y0=yd;
				 non--;
				if(w[cell]<0.5 && id) {
					xc = xd; yc = yd;
					cells = cell;
					id = 0;
				}
				xdmin = MIN(xdmin,xd);
				xdmax = MAX(xdmax,xd);
				ydmin = MIN(ydmin,yd);
				ydmax = MAX(ydmax,yd);
			}
			if(lcflag && id==0 && xdmax+ydmax-xdmin-ydmin>xw+yw) {
				wcell(nx,x,ny,y,w,cells,xc,yc,xw,yw);
 				labelc(dpy,win,gcl,xc-xw/2,yc-yw/2,xw,yw,str,lcf,lcc);
			}	
				} 		 
			}
		}
	}
	/* contour drawing is done */
}
Пример #21
0
Show_Info()
{

    extern int found_arc, mandel, maxcrit, numattrs, maxhist, minhist;
    extern double sea_level, sky_level;
#ifdef NorthSouth
    extern double singularity, A_zero, A_one, A_two, A_star, B_zero, B_one;
    extern double S_singularity, H_one, H_zero, O_B_zero, O_B_one;
    extern double S_A_zero, S_A_one, S_A_two, S_A_star, S_B_zero, S_B_one;
    extern double O_S_B_zero, O_S_B_one;
    extern double pB, A2T, A1T, CT, ET, FT, GT;
    extern pair GNP, RK;
    static char *mops[HALF] = { "delta", "s    ", "a1   ", "a2   ", "c1   ",
	      "c2   ", "D    ", "Kbar ", "Lbar ", "alpha", "beta ", "gamma" };
#endif
    static int numparams[NUMMAPS]= {12,5,4,12,4,12,2,
#ifdef NorthSouth
#ifdef Gardini
	12,3,2,2,
#else
	12,
#endif
#else
#ifdef Gardini
	3,2,2,
#endif
#endif
	2,3,2,2,2,3,7,4,3,12,2,7,8,4
#ifdef Plendo
	, 12, 6, 2, 5
#endif
	};
    static int i, x_str, y_str;
    static GC gc;
    static char ops[HALF] = { 'A','B','C','D','E','F','G','I','J','K','L','M' };

    if (displayplanes > 1)
	gc = Data_GC[CG];
    else
	gc = Data_GC[1];
    XClearWindow(dpy, info);
    y_str = 20; x_str = 175;
    sprintf(str,"Iterating the %s Map ",Mapnames[mapindex]);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    XQueryTextExtents(dpy,(XID)XGContextFromGC(gc),"X",
			1,&dir,&ascent,&descent,&overall);
    spacing = ascent + descent + 7;
    y_str += spacing; 
    x_str = 40;
    XDrawImageString(dpy,info,gc,x_str,y_str,Mapdefs[2*mapindex],
		strlen(Mapdefs[2*mapindex]));
    y_str += spacing; 
    XDrawImageString(dpy,info,gc,x_str,y_str,Mapdefs[2*mapindex+1],
		strlen(Mapdefs[2*mapindex+1]));
    x_str = 0;
    y_str += 2*spacing; 
#ifdef NorthSouth
    if (mapindex == 7) {
    	sprintf(str,"          South      North");
    	XDrawImageString(dpy,info,gc,x_str,y_str, str, strlen(str));
    	y_str += spacing; 
    	for (i=0;i<HALF;i++) {
			sprintf(str," %s  %8.4f  %8.4f", mops[i],params[i],params[HALF+i]);
			XDrawImageString(dpy,info,gc,x_str,y_str, str, strlen(str));
			y_str += spacing; 
    	}
    }
    else
#endif /* NorthSouth */
    if (mapindex == 24) {
    	sprintf(str,"       X             Y");
    	XDrawImageString(dpy,info,gc,x_str,y_str, str, strlen(str));
    	y_str += spacing; 
    	for (i=0;i<numparams[mapindex];i++) {
			sprintf(str," %c = %8.4f  %c = %8.4f", 
				ops[i], params[i], tolower(ops[i]), params[HALF+i]);
			XDrawImageString(dpy,info,gc,x_str,y_str, str, strlen(str));
        	y_str += spacing; 
		}
	}
	else
		for (i=0;i<numparams[mapindex];i++) {
			sprintf(str,"   %c=%lf",ops[i],params[i]);
			XDrawImageString(dpy,info,gc,x_str,y_str, str, strlen(str));
			y_str += spacing;
		}
    x_str = 50 + (23*overall.width);
    y_str = 5*spacing; 
    sprintf(str,"width = %d, height = %d, run = %d", width,height,run);
    if ((criwidth != width) || (criheight != height))
        sprintf(str,"%s, cwidth=%d, cheight=%d",str,criwidth,criheight);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"settle = %d, dwell = %d, maxcrit = %d",settle,dwell,maxcrit);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    sprintf(str,"delta = %6.5f, cdelta = %6.5f, radius = %d",
				delta, cdelt, maxradius);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    if (lyap) {
		if (p1 < HALF) {
#ifdef NorthSouth
		if (mapindex == 7)
            sprintf(str,"x-axis = (%lf,%lf), parameter = South %s, range = %lf",
				min_x, max_x, mops[p1], x_range);
		else
#endif
            sprintf(str,"x-axis = (%lf,%lf), parameter = %c, range = %lf",
			min_x, max_x, ops[p1], x_range);
		}
		else {
#ifdef NorthSouth
		if (mapindex == 7)
            sprintf(str,"x-axis = (%lf,%lf), parameter = North %s, range = %lf",
			min_x, max_x, mops[p1-HALF], x_range);
		else
#endif
            sprintf(str,"x-axis = (%lf,%lf), parameter = %c, range = %lf",
			min_x, max_x, tolower(ops[p1-HALF]), x_range);
		}
    }
    else
        sprintf(str,"x-axis = (%lf,%lf), x-range = %lf",min_x,max_x,x_range);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    if (lyap) {
		if (p2 < HALF) {
#ifdef NorthSouth
		if (mapindex == 7)
            sprintf(str,"y-axis = (%lf,%lf), parameter = South %s, range = %lf",
			min_y, max_y, mops[p2], y_range);
		else
#endif
            sprintf(str,"y-axis = (%lf,%lf), parameter = %c, range = %lf",
			min_y, max_y,ops[p2], y_range);
		}
		else {
#ifdef NorthSouth
		if (mapindex == 7)
            sprintf(str,"y-axis = (%lf,%lf), parameter = North %s, range = %lf",
			min_y, max_y, mops[p2-HALF], y_range);
		else
#endif
            sprintf(str,"y-axis = (%lf,%lf), parameter = %c, range = %lf",
			min_y, max_y, tolower(ops[p2-HALF]), y_range);
		}
    }
    else
        sprintf(str,"y-axis = (%lf,%lf), y-range = %lf",min_y,max_y,y_range);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    if ((c_min_x != min_x) || (c_min_y != min_y) ||
		(c_x_range != x_range) || (c_y_range != y_range)) {
        sprintf(str,"critical axes = (%lf, %lf) x (%lf, %lf)",
		c_min_x, c_min_x + c_x_range, c_min_y, c_min_y + c_y_range);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
    }
    if ((t_min_x != min_x) || (t_min_y != min_y) ||
		(t_x_range != x_range) || (t_y_range != y_range)) {
        sprintf(str,"orbit axes = (%lf, %lf) x (%lf, %lf)",
		t_min_x, t_min_x + t_x_range, t_min_y, t_min_y + t_y_range);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
    }
    sprintf(str,
	   "numcolors=%d STARTCOLOR=%d MINCOLINDEX=%d histogram=%d sea=%lf sky=%lf",
				numcolors,STARTCOLOR,MINCOLINDEX,histogram,sea_level,sky_level);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
#ifdef NorthSouth
    if (mapindex == 7) {
        y_str += spacing;
        sprintf(str, "North: A0 =%8.6f A1 =%8.6f A2 =%8.6f A* =%8.6f", 
					A_zero, A_one, A_two, A_star);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str,
			"       H0 =%8.6f H1 =%8.6f B0 =%8.6f (%8.6f) B1 =%8.6f (%8.6f)", 
				H_zero, H_one, B_zero, O_B_zero, B_one, O_B_one);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str,
   				"South: A0 =%8.6f A1 =%8.6f A2 =%8.6f A* =%12.10lf", 
						S_A_zero, S_A_one, S_A_two, S_A_star);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str,
   				"       B0 =%8.6f (%8.6f) B1 =%8.6f (%8.6f)", 
						S_B_zero, O_S_B_zero, S_B_one, O_S_B_one);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str,"Singularities in the North and South at %lf and %lf", 
		singularity, S_singularity);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    }
    else if (mapindex == 8) {
        y_str += spacing;
        sprintf(str, 
		"Currently: pB = %8.6f ET = %8.6f FT = %8.6f CT = %8.6f GT = %8.6f",
			pB, ET, FT, CT, GT);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str, "North rK = %8.4f  South rK = %8.4f", RK.x, RK.y);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str,"Singularities in the North and South at %lf and %lf",
			singularity, S_singularity);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    }
    else if (mapindex == 9) {
        y_str += spacing;
        sprintf(str, 
		"Currently: pB = %8.6f ET = %8.6f FT = %8.6f CT = %8.6f GT = %8.6f",
			pB, ET, FT, CT, GT);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str, "North GNP = %8.4f  South GNP = %8.4f", GNP.x, GNP.y);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
        y_str += spacing;
        sprintf(str,"Singularities in the North and South at %lf and %lf",
			singularity, S_singularity);
        XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    }
#endif
    y_str += spacing;
    sprintf(str,"find = %d, portrait = %d, attractors = %d, critical = %d",
		find,portrait,attractors,critical);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
    y_str += spacing;
    if (lyap)
        sprintf(str,"lyap = %d, mandel = %d, initial (x,y) = (%lf,%lf)",
			lyap,mandel,start_x,start_y);
    else
		if (histogram)
        	sprintf(str,
				"mandel=%d intersections=%d numattrs=%d minhist=%d maxhist=%d", 
				mandel, found_arc, numattrs, minhist, maxhist);
		else
        	sprintf(str,"mandel = %d, intersections = %d, numattrs = %d", 
							mandel, found_arc, numattrs);
    XDrawImageString(dpy,info,gc,x_str,y_str,str,strlen(str));
}
Пример #22
0
int XDPSSetContextParameters(
    DPSContext context,
    Screen *screen,
    int depth,
    Drawable drawable,
    int height,
    XDPSStandardColormap *rgbMap,
    XDPSStandardColormap *grayMap,
    unsigned int flags)
{
    ContextInfo c = FindContextInfo(context);
    Bool doDepth = False, doDrawable = False, doRGB = False, doGray = False;
    Colormap map = None;
    XStandardColormap cmap;
    GC gc;
    GContext gctx = None;
    DisplayInfo d;
    Display *dpy;
    int rgb_base_pixel = 0;
    int red_max = 0;
    int red_mult = 0;
    int green_max = 0;
    int green_mult = 0;
    int blue_max = 0;
    int blue_mult = 0;
    int gray_base_pixel = 0;
    int gray_max = 0;
    int gray_mult = 0;
    
    if (c == NULL) return dps_status_unregistered_context;
    d = c->displayInfo;

    (void) XDPSXIDFromContext(&dpy, context);

    if (flags & XDPSContextScreenDepth) {
	doDepth = True;

	if (DisplayOfScreen(screen) != dpy) {
	    return dps_status_illegal_value;
	}

	gc = DisplayInfoSharedGC(d, screen, depth);
	if (gc == NULL) return dps_status_illegal_value;

	gctx = XGContextFromGC(gc);
    }

    if (flags & XDPSContextDrawable) {
	doDrawable = True;
	if (drawable != None && height <= 0) return dps_status_illegal_value;
    }

    if (flags & XDPSContextRGBMap) {
	doRGB = True;
	if (rgbMap == NULL) {
	    XDPSGetDefaultColorMaps(dpy, screen, drawable, &cmap,
				    (XStandardColormap *) NULL);
	    rgb_base_pixel = cmap.base_pixel;
	    red_max = cmap.red_max;
	    red_mult = cmap.red_mult;
	    green_max = cmap.green_max;
	    green_mult = cmap.green_mult;
	    blue_max = cmap.blue_max;
	    blue_mult = cmap.blue_mult;
	    map = cmap.colormap;
	} else {
	    rgb_base_pixel = rgbMap->base_pixel;
	    red_max = rgbMap->red_max;
	    red_mult = rgbMap->red_mult;
	    green_max = rgbMap->green_max;
	    green_mult = rgbMap->green_mult;
	    blue_max = rgbMap->blue_max;
	    blue_mult = rgbMap->blue_mult;
	    map = rgbMap->colormap;
	}
    }

    if (flags & XDPSContextGrayMap) {
	doGray = True;
	if (grayMap == NULL) {
	    XDPSGetDefaultColorMaps(dpy, screen, drawable,
				    (XStandardColormap *) NULL, &cmap);
	    gray_base_pixel = cmap.base_pixel;
	    gray_max = cmap.red_max;
	    gray_mult = cmap.red_mult;
	    if (doRGB && map != cmap.colormap) {
		return dps_status_illegal_value;
	    } else map = cmap.colormap;
	} else {
	    gray_base_pixel = grayMap->base_pixel;
	    gray_max = grayMap->red_max;
	    gray_mult = grayMap->red_mult;
	    if (doRGB && map != grayMap->colormap) {
		return dps_status_illegal_value;
	    } else map = grayMap->colormap;
	}
    } 

    if (doDepth || doDrawable || doRGB || doGray) {
	_DPSSSetContextParameters(context, gctx, drawable, height, map,
				  rgb_base_pixel, red_max, red_mult,
				  green_max, green_mult, blue_max, blue_mult,
				  gray_base_pixel, gray_max, gray_mult,
				  doDepth, doDrawable, doRGB, doGray);
    }
    return dps_status_success;
}
Пример #23
0
/**
 * main application method
 * 
 * usage / command line arguments
 * xgravity [planet count] [calculation threads]
 * 
 * @param argc
 * @param argv
 */
int main(int argc, char *argv[]) {
  
  pthread_t calcThreads[MAX_THREADS];
  pthread_barrier_t calcBarrier;
  pthread_mutex_t calcMutex = PTHREAD_MUTEX_INITIALIZER;
  calcArgs calcThreadArgs;
  int threads; // number of calculation threads to run
  
  planet *planets[MAXCOUNT];
  planet *aPlanet;
  
  double minx, maxx, miny, maxy, cx, cy, massMax, massMin, timeFactor, forceMultiplier, radiusScale;
  int pi, count; // planet iterator
  long int zoomFactor; // zoom factor
  int centerID; // id of object to use for auto centering
  int radius; // radius in pixels

  double fg, td, dist; // temporary accelerating force and direction
  
  int shownum; // show stat numbers flag
  int showforce; // show force lines flag

  int winw, winh; // window dimensions

  Display *display;
  int screen;
  Window window;
  XEvent event;
  KeySym key;
  char text[255];
  Pixmap pixmap;
  GC gc;
  Colormap colormap;
  
  XGCValues values_return;
  XFontStruct *font_info;
  GContext gid;

  
  // check for planet count in arguments
  if( argc > 1 ) {
    // first argument is planet count
    count = atoi(argv[1]);
    if( count > MAXCOUNT ) count = MAXCOUNT;
  }
  else {
    count = COUNT;
  }
  
  // check for thread count in arguments
  if( argc > 2 ) {
    // first argument is planet count
    threads = atoi(argv[2]);
    if ( threads < 1 )
    {
      threads = THREAD_COUNT;
    }
    else if ( threads > MAX_THREADS )
    {
      threads = MAX_THREADS;
    }
  }
  else {
    threads = THREAD_COUNT;
  }

  // set default control values
  timeFactor = 1; // calculation time factor in seconds
  zoomFactor = 4; // start zoomed out a bit
  forceMultiplier = 1e-8; // need a small multiplier to shrink force lines
  shownum = 0; // do not show numbers
  showforce = 0; // do not show force lines
  centerID = -1; // not centered on any planets
  winw = WINW;
  winh = WINH;
  cx = 0;
  cy = 0;

  // setup Xwindow
  display = XOpenDisplay(NULL);
  if( display == NULL) {
    printf("Cannot open display\n");
    exit(1);
  }

  screen = DefaultScreen(display);
  window = XCreateSimpleWindow(
    display, 
    RootWindow(display, screen), 
    10, 
    10, 
    winw, 
    winh, 
    1,
    WhitePixel(display, screen), 
    BlackPixel(display, screen));
  XMapWindow(display, window);
  XFlush(display);

  // show the window ID in case need to use for screen grab / cast
  printf("Window ID:%d\r\n", window);

  XSelectInput (display, window, KeyPressMask | StructureNotifyMask | ButtonPressMask);

  pixmap = XCreatePixmap(display, window, winw, winh, DefaultDepth(display, screen));
  XFlush(display);

  colormap = DefaultColormap(display, 0);
  gc = XCreateGC(display, pixmap, 0, 0);

  // define color codes
  char *colorCodes[] = {
    "#009900",
    "#4444FF",
    "#FF4400",
    "#FFFFFF",
    "#000000",
    "#FFFF00",
    "#A0A0A0",
    "#E0D1FF"
  };
  
  // create colors for palette
  XColor drawColors[COLOR_COUNT];
  for(pi = 0; pi < COLOR_COUNT; pi++)
  {
    XParseColor(display, colormap, colorCodes[pi], &drawColors[pi]);
    XAllocColor(display, colormap, &drawColors[pi]);
  }
  
  gid = XGContextFromGC(gc);
  font_info = XQueryFont(display, gid);

  XSetForeground(display, gc, drawColors[COLOR_BACKGROUND].pixel);
  XFillRectangle(display, pixmap, gc, 0, 0, winw, winh);
  XCopyArea(display, pixmap, window, gc, 0, 0, winw, winh, 0, 0);
  XFlush(display);

  
  // allocate memory for planet data
  for ( pi = 0; pi < count; pi++ ) {
    planets[pi] = (planet *) malloc(sizeof(planet));
  }
  
  // initialize planets
  randomizePlanets(planets, count);

  // initialize the thread barrier to thread count plus main
  pthread_barrier_init(&calcBarrier, NULL, threads + 1);

  // collect thread arguments into struct
  calcThreadArgs.planetData = planets;
  calcThreadArgs.count = count;
  calcThreadArgs.calcBarrier = &calcBarrier;
  calcThreadArgs.calcMutex = &calcMutex;
  
  // initialize threads
  for(pi = 0; pi < threads; pi++)
  {
    pthread_create(&calcThreads[pi], NULL, &calcWorker, &calcThreadArgs);
  }
  
  // main application loop
  while(1) {

    // keyboard events
    if( XCheckMaskEvent(display, KeyPressMask, &event) && XLookupString(&event.xkey, text, 255, &key, 0)==1 ) {
      // quit
      if (text[0]=='q') {
        XCloseDisplay(display);
        exit(0);
      }
      
      // toggle show force lines
      if( text[0] == 'f' ) {
        showforce += 1;
        if( showforce > 3 ) showforce = 0;
      }
      
      // adjust force line multiplier dimension
      if( text[0] == 'd' ) forceMultiplier = forceMultiplier / 10;
      if( text[0] == 'D' ) forceMultiplier = forceMultiplier * 10;
      
      // toggle show stat numbers
      if( text[0] == 'o' ) {
        shownum += 1;
        if( shownum > 6 ) shownum = 0;
      }
      
      // toggle calculation time factor in seconds
      else if( text[0] == 't' ) timeFactor = timeFactor / 10;
      else if( text[0] == 'T' ) timeFactor = timeFactor * 10;
      
      // zoom in
      else if( text[0] == 'z' ) {
        zoomFactor -= 1;
        if( zoomFactor < 1 ) zoomFactor = 1;
      }
      else if( text[0] == 'Z' ) {
        zoomFactor = zoomFactor / 2;
        if( zoomFactor < 1 ) zoomFactor = 1;
      }
      
      // zoom out
      else if( text[0] == 'x' ) zoomFactor += 1;
      else if( text[0] == 'X' ) zoomFactor = 2 * zoomFactor;
      
      // reset view to no zoom
      else if( text[0] == 'v' ) zoomFactor = 1;
      
      // reset center
      else if( text[0] == 'c' ) {
        cx = 0;
        cy = 0;
      }
      
      // auto zoom to show all planets
      else if( text[0] == 'a' ) {
        minx = 0;
        maxx = 0;
        miny = 0;
        maxy = 0;
        
        // use planets to find minimum and maximum position values for zoom window
        for(pi = 0; pi < count; pi++) {
          if( planets[pi]->mass > 0 ) {
            if( planets[pi]->x < minx ) minx = planets[pi]->x - 500;
            if( planets[pi]->x > maxx ) maxx = planets[pi]->x + 500;
            if( planets[pi]->y < miny ) miny = planets[pi]->y - 500;
            if( planets[pi]->y > maxy ) maxy = planets[pi]->y + 500;
          }
        }
        
        // calculate zoom factor
        if( (maxx - minx) / (double)winw > (maxy - miny) / (double)winh ) zoomFactor = (long int)((maxx - minx) / (double)winw);
        else zoomFactor = (long int)((maxy - miny) / (double)winh) + 1;

        // fractional zoom not allowed
        if( zoomFactor < 1 ) zoomFactor = 1;

        // recenter view
        cx = (double)-1.0 * (minx + (maxx - minx) / (double)2.0);
        cy = (double)-1.0 * (miny + (maxy - miny) / (double)2.0);
      }
      
      // re-randomize planets
      else if( text[0] == 'r' ) {
        randomizePlanets(planets, count);
      }
      
      // wipe all planets
      else if( text[0] == 'w' ) {
        massMax = 0;
        massMin = DBL_MAX;
        clearPlanets(planets, count);
      }
      
      else if( text[0] == 's' ) {
        // create a gravitation well
        createGravityWell(planets, count, cx, cy);
      }
      
      else if( text[0] == 'b' ) {
        // create a binary gravitation well
        createBinaryWell(planets, count, cx, cy);
      }
      
      else if( text[0] == 'h' ) {
        // create a heliocentric system
        createHeliocentricSystem(planets, count, cx, cy);
      }
      
      else if( text[0] == 'g' ) {
        // create some geocentric nonsense
        createGeocentricSystem(planets, count, cx, cy);
      }
      
      else if( text[0] == 'p' ) {
        // create Sol planetary system
        createPlanetarySystem(planets, count, cx, cy);
      }
      else if( text[0] == 'm' ) {
        // create molniya orbit
        createMolniyaOrbit(planets, count, cx, cy);
      }
    } // end of keyboard events

    // window config events
    if( XCheckMaskEvent(display, StructureNotifyMask, &event) && event.type == ConfigureNotify ) {
      if (event.xconfigure.window == window) {
        winw = event.xconfigure.width;
        winh = event.xconfigure.height;
        XFreePixmap(display, pixmap);
        XFlush(display);

        pixmap = XCreatePixmap(display, window, winw, winh, DefaultDepth(display, screen));
        XFlush(display);
      }
    }

    // mouse button events
    if( XCheckMaskEvent(display, ButtonPressMask, &event) ) {
      centerID = -1;

      // if clicked on planet then select as centerID for auto centering
      for(pi = 0; pi < count; pi++) {
        dist = sqrt(pow((cx + planets[pi]->x) / zoomFactor + (winw / 2) - event.xbutton.x, 2) + pow((cy + planets[pi]->y) / zoomFactor + (winh / 2) - event.xbutton.y, 2));
        if( dist < 4 ) {
          centerID = pi;
          continue;
        }
      }

      // if not centered on a planet then recenter to click point
      if( centerID == -1 ) {
        cx += zoomFactor * (winw / 2 - event.xbutton.x);
        cy += zoomFactor * (winh / 2 - event.xbutton.y);
      }
      // keep in mind that cx, cy is not the center coordinate, it is the direction to shift
    }


    // set calculation state on for each planet that has mass
    for(pi = 0; pi < count; pi++)
    {
      if ( planets[pi]->mass > 0 )
      {
        planets[pi]->calc = 1;
      }
    }
    
    // wait for all threads to start calculations
    pthread_barrier_wait(&calcBarrier);
    
    // wait for all threads to end calculations
    pthread_barrier_wait(&calcBarrier);
    
    // move planets after calculations
    movePlanets(timeFactor, planets, count);
    
    // calculate collisions
    calculateCollisions(planets, count);
    massMax = getMassMax(planets, count);
    massMin = getMassMin(planets, count);
        
    // clear display
    XSetForeground(display, gc, drawColors[COLOR_BACKGROUND].pixel);
    XFillRectangle(display, pixmap, gc, 0, 0, winw, winh);

    // if following a planet then recenter display on the planet
    if( centerID > -1 ) {
      cx = -1 * planets[centerID]->x;
      cy = -1 * planets[centerID]->y;
    }

    // set radius scale of kg per pixel
    radiusScale = (massMax - massMin) / (MAX_PIXEL_RADIUS - MIN_PIXEL_RADIUS);
  
    // draw each planet
    for(pi = 0; pi < count; pi++) {
      // if planet has mass and is within the display area then we draw
      if( planets[pi]->mass > 0 && 
          (cx + planets[pi]->x) / zoomFactor > -1 * (winw / 2) && (cx + planets[pi]->x) / zoomFactor < (winw / 2) && 
          (cy + planets[pi]->y) / zoomFactor > -1 * (winh / 2) && (cy + planets[pi]->y) / zoomFactor < (winh / 2) ) {
        // calculate radius relative to mass and other planets
        radius = (int)(planets[pi]->mass / radiusScale) + MIN_PIXEL_RADIUS;

        // determine color by flash or radius divisions
        if( planets[pi]->flash ) {
            XSetForeground(display, gc, drawColors[COLOR_FLASH].pixel);
            radius = radius * planets[pi]->flash;
            planets[pi]->flash -= 1;
        }
        else if( radius > 16 ) {
          // size is color for a star
          XSetForeground(display, gc, drawColors[COLOR_STAR].pixel);
        }
        else if( radius <= 16 && radius > 12 ) {
          // size is color of blue planet
          XSetForeground(display, gc, drawColors[COLOR_BLUE].pixel);
        }
        else {
          // default color for smallest is green
          XSetForeground(display, gc, drawColors[COLOR_GREEN].pixel);
        }

        // draw planet dot
        XFillArc(display, pixmap, gc, 
                 ((cx + planets[pi]->x) / zoomFactor + (winw / 2) - radius / 2), 
                 ((cy + planets[pi]->y) / zoomFactor + (winh / 2) - radius / 2), 
                 radius, radius, 0, 360 * 64);

        // draw black border
        XSetForeground(display, gc, drawColors[COLOR_BLACK].pixel);
        XDrawArc(display, pixmap, gc, 
                 ((cx + planets[pi]->x) / zoomFactor + (winw / 2) - radius / 2), 
                 ((cy + planets[pi]->y) / zoomFactor + (winh / 2) - radius / 2), 
                 radius, radius, 0, 360 * 64);

        // show force vectors
        if( showforce > 0 ) {
          switch( showforce ) {
            case 1:
              //draw gravitational force
              XSetForeground(display, gc, drawColors[COLOR_RED].pixel);
              XDrawLine(display, pixmap, gc, 
                 ((cx + planets[pi]->x) / zoomFactor + (winw / 2)),
                 ((cy + planets[pi]->y) / zoomFactor + (winh / 2)),
                 ((cx + planets[pi]->x + (planets[pi]->mass * planets[pi]->acceleration.accelerationX) * forceMultiplier) / zoomFactor + (winw / 2)),
                 ((cy + planets[pi]->y + (planets[pi]->mass * planets[pi]->acceleration.accelerationY) * forceMultiplier) / zoomFactor + (winh / 2)));

              XSetForeground(display, gc, drawColors[COLOR_BLUE].pixel);
              XDrawLine(display, pixmap, gc,
                 ((cx + planets[pi]->x) / zoomFactor + (winw / 2)),
                 ((cy + planets[pi]->y) / zoomFactor + (winh / 2)),
                 ((cx + planets[pi]->x + (planets[pi]->mass * planets[pi]->velocityX * forceMultiplier / 10)) / zoomFactor + (winw / 2)),
                 ((cy + planets[pi]->y + (planets[pi]->mass * planets[pi]->velocityY * forceMultiplier / 10)) / zoomFactor + (winh / 2)));

              break;

            case 2:
             //draw gravitational acceleration
              XSetForeground(display, gc, drawColors[COLOR_WHITE].pixel);
              XDrawLine(display, pixmap, gc,
                 ((cx + planets[pi]->x) / zoomFactor + (winw / 2)),
                 ((cy + planets[pi]->y) / zoomFactor + (winh / 2)),
                 ((cx + planets[pi]->x + (planets[pi]->acceleration.accelerationX) * forceMultiplier) / zoomFactor + (winw / 2)),
                 ((cy + planets[pi]->y + (planets[pi]->acceleration.accelerationY) * forceMultiplier) / zoomFactor + (winh / 2)));

              break;
          }
        }

        // show stat values
        if( shownum > 0 ) {
          // set text color
          XSetForeground(display, gc, drawColors[COLOR_WHITE].pixel);

          switch( shownum ) {
            // show planet id number
            case 1:
              sprintf(text, "ID:%d", pi);
              break;

            // show planet mass
            case 2:
              sprintf(text, "%2.2E kg", planets[pi]->mass);
              break;

            // show planet velocity
            case 3:
              fg = sqrt(pow(planets[pi]->velocityX, 2) + pow(planets[pi]->velocityY, 2));
              td = atan2(planets[pi]->velocityY, planets[pi]->velocityX);
              if( isinf(td) ) td = M_PI / 2;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) > 0 ) td = 0;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) < 0 ) td = M_PI;
              td = td * 180 / M_PI + 180;
              sprintf(text, "%2.2G m/s %3.0f degrees", fg, td);
              break;

            // show planet coordinates
            case 4:
              sprintf(text, "%G, %G", planets[pi]->x, planets[pi]->y);
              break;

            // show mass and velocity
            case 5:
              fg = sqrt(pow(planets[pi]->velocityX, 2) + pow(planets[pi]->velocityY, 2));
              td = atan2(planets[pi]->velocityY, planets[pi]->velocityX);
              if( isinf(td) ) td = M_PI / 2;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) > 0 ) td = 0;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) < 0 ) td = M_PI;
              td = td * 180 / M_PI + 180;
  //font_info
  //font_height = font_info->max_bounds.ascent +
  //font_info->max_bounds.descent;

              sprintf(text, "%2.2E kg", planets[pi]->mass);
              XDrawString(display, pixmap, gc, 
                          (cx + planets[pi]->x) / zoomFactor + (winw / 2), 
                          (cy + planets[pi]->y) / zoomFactor + (winh / 2) + 
                            font_info->max_bounds.ascent +
                            font_info->max_bounds.descent, 
                          text, strlen(text));
              sprintf(text, "%2.2G m/s %3.0f degrees", fg, td);

              break;

            // show inertia and acting gravitational force
            case 6:
              fg = planets[pi]->mass * sqrt(pow(planets[pi]->velocityX, 2) + pow(planets[pi]->velocityY, 2));
              td = atan2(planets[pi]->velocityY, planets[pi]->velocityX);
              if( isinf(td) ) td = M_PI / 2;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) > 0 ) td = 0;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) < 0 ) td = M_PI;
              td = td * 180 / M_PI + 180;

              sprintf(text, "   P = %2.2G Ns %3.0f degrees", fg, td);
              XDrawString(display, pixmap, gc,
                          (cx + planets[pi]->x) / zoomFactor + (winw / 2),
                          (cy + planets[pi]->y) / zoomFactor + (winh / 2) +
                            font_info->max_bounds.ascent +
                            font_info->max_bounds.descent,
                          text, strlen(text));


              fg = planets[pi]->mass * sqrt(pow(planets[pi]->acceleration.accelerationX, 2) + pow(planets[pi]->acceleration.accelerationY, 2));
              td = atan2(planets[pi]->acceleration.accelerationY, planets[pi]->acceleration.accelerationX);
              if( isinf(td) ) td = M_PI / 2;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) > 0 ) td = 0;
              if( isnan(td) && (planets[pi]->velocityX - planets[pi]->velocityX) < 0 ) td = M_PI;
              td = td * 180 / M_PI + 180;
              sprintf(text, "   Fg = %2.2G N %3.0f degrees", fg, td);

              break;

          }
          
          XDrawString(display, pixmap, gc, (cx + planets[pi]->x) / zoomFactor + (winw / 2), (cy + planets[pi]->y) / zoomFactor + (winh / 2), text, strlen(text));
        }
      }
    }

    // apply drawn bitmap
    XCopyArea(display, pixmap, window, gc, 0, 0, winw, winh, 0, 0);
    XFlush(display);

  }

  XCloseDisplay(display);

}
Пример #24
0
int
main(void)
{

  XGCValues       controlGCVals;
  int             i,code;
  view2DStruct    viewData;

  char property[256];
  char *prop = &property[0];
  char *str_type[20];
  XrmValue value;


  /**** Set up display ****/
  if ((dsply = XOpenDisplay(getenv("DISPLAY"))) == NULL)
    fprintf(stderr,"Could not open the display.\n");
  scrn  = DefaultScreen(dsply);
  rtWindow  = RootWindow(dsply,scrn);

  /**** link Xwindows to viewports - X10 feature ****/
  table        = XCreateAssocTable(nbuckets);

  /**** Create FriCAS color map ****/
  totalColors = XInitSpadFill(dsply,scrn,&colorMap,
                              &totalHues,&totalSolidShades,
                              &totalDitheredAndSolids,&totalShades);

  if (totalColors < 0) {
    fprintf(stderr,">>Error: Could not allocate all the necessary colors.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }

  mergeDatabases();


  /*** Determine whether monochrome or color is used ***/
  if (XrmGetResource(rDB,"Axiom.2D.monochrome","",str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop, "off");

  mono = ((totalSolid == 2) || (strcmp(prop,"on") == 0));

  if (XrmGetResource(rDB,"Axiom.2D.inverse","",str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop, "off");

  if (mono)
    if (strcmp(prop,"on") == 0) {             /* 0 if equal (inverse video) */
      foregroundColor = WhitePixel(dsply,scrn);
      backgroundColor = BlackPixel(dsply,scrn);
    } else {                                  /* off (no inverse video) */
      foregroundColor = BlackPixel(dsply,scrn);
      backgroundColor = WhitePixel(dsply,scrn);
    }
  else   /* inverse of inverse in color (for some strange reason) */
    if (strcmp(prop,"on") == 0) {         /* 0 if equal (inverse video) */
      foregroundColor = WhitePixel(dsply,scrn);
      backgroundColor = BlackPixel(dsply,scrn);
    } else {                                  /* off (no inverse video) */
      foregroundColor = BlackPixel(dsply,scrn);
      backgroundColor = WhitePixel(dsply,scrn);
    }


  /* read default file name for postScript output */
  if (XrmGetResource(rDB,
                     "Axiom.2D.postscriptFile",
                     "",
                     str_type, &value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop, "axiom2D.ps");

  PSfilename = (char *)malloc(strlen(prop)+1);
  strcpy(PSfilename,prop);



  /**** Open global fonts ****/
  serverFont = XQueryFont(dsply,XGContextFromGC(DefaultGC(dsply,scrn)));

  if (XrmGetResource(rDB,
                     "Axiom.2D.messageFont",
                     "Axiom.2D.Font",
                     str_type, &value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,messageFontDefault);
  if ((globalFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for messageFont\n",prop);
    globalFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.buttonFont",
                     "Axiom.2D.Font",
                     str_type, &value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,buttonFontDefault);
  if ((buttonFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for buttonFont\n",prop);
    buttonFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.headerFont",
                     "Axiom.2D.Font",
                     str_type, &value) == True)
     (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,headerFontDefault);

  if ((headerFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for headerFont\n",prop);
    headerFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.titleFont",
                     "Axiom.2D.Font",
                     str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,titleFontDefault);

  if ((titleFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for titleFont\n",prop);
    titleFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.graphFont",
                     "Axiom.2D.Font",
                     str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,graphFontDefault);

  if ((graphFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for graphFont\n",prop);
    graphFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.unitFont",
                     "Axiom.2D.Font",
                     str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,unitFontDefault);

  if ((unitFont = XLoadQueryFont(dsply, prop)) == NULL) {
     fprintf(stderr,
             "Warning:  could not get the %s font for unitFont\n",prop);
     unitFont = serverFont;
  }


  /**** Create widely used Graphic Contexts ****/
  PSGlobalInit();
  /* must initiate before using any G/PS functions
     need character name: used as postscript GC variable
     need to create ps GCs for all GCs used by drawings in viewWindow */

  /* globalGC1 */

  controlGCVals.foreground = monoColor(axesColorDefault);
  controlGCVals.background = backgroundColor;
  globalGC1 = XCreateGC(dsply,rtWindow,GCForeground | GCBackground ,
                        &controlGCVals);
  carefullySetFont(globalGC1,globalFont);


  /* create the equivalent GCs for ps */
  PSCreateContext(globalGC1, "globalGC1", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* controlMessageGC */

  controlGCVals.foreground = controlMessageColor;
  controlMessageGC = XCreateGC(dsply,rtWindow,GCForeground | GCBackground
                               ,&controlGCVals);
  carefullySetFont(controlMessageGC,globalFont);

  /* globalGC2 */

  controlGCVals.foreground = monoColor(labelColor);
  controlGCVals.background = backgroundColor;
  globalGC2 = XCreateGC(dsply,rtWindow,GCForeground | GCBackground,
                        &controlGCVals);
  carefullySetFont(globalGC2,buttonFont);
  PSCreateContext(globalGC2, "globalGC2", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* trashGC  */

  trashGC = XCreateGC(dsply,rtWindow,0,&controlGCVals);
  carefullySetFont(trashGC,buttonFont);
  PSCreateContext(trashGC, "trashGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* globGC */

  globGC = XCreateGC(dsply,rtWindow,0,&controlGCVals);
  carefullySetFont(globGC,headerFont);
  PSCreateContext(globGC, "globGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* anotherGC  */

  controlGCVals.line_width = colorWidth;
  anotherGC  = XCreateGC(dsply,rtWindow,GCBackground,&controlGCVals);
  carefullySetFont(anotherGC,titleFont);
  PSCreateContext(anotherGC, "anotherGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* processGC */

  gcVals.background = backgroundColor;
  processGC         = XCreateGC(dsply,rtWindow,GCBackground ,&gcVals);
  carefullySetFont(processGC,buttonFont);

  /* graphGC */

  graphGC           = XCreateGC(dsply,rtWindow,GCBackground,&gcVals);
  carefullySetFont(graphGC,graphFont);
  PSCreateContext(graphGC, "graphGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* unitGC */

  unitGC            = XCreateGC(dsply,rtWindow,GCBackground ,&gcVals);
  carefullySetFont(unitGC,unitFont);
  PSCreateContext(unitGC, "unitGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /**** Initialize Graph States ****/

  for (i=0; i<maxGraphs; i++) {
    graphStateArray[i].scaleX = 0.9;
    graphStateArray[i].scaleY = 0.9;
    graphStateArray[i].deltaX = 0.0;
    graphStateArray[i].deltaY = 0.0;
    graphStateArray[i].centerX = 0.0;
    graphStateArray[i].centerY = 0.0;
    graphStateArray[i].pointsOn  = yes;
    graphStateArray[i].connectOn = yes;
    graphStateArray[i].splineOn  = no;
    graphStateArray[i].axesOn    = yes;
    graphStateArray[i].unitsOn   = no;
    graphStateArray[i].showing   = no;
    graphStateArray[i].selected  = no;
    graphStateBackupArray[i] = graphStateArray[i];
  }

  /**** Get Data from the Viewport Manager ****/

  i = 123;
  code=check(write(Socket,&i,intSize));

  /* Check if I am getting stuff from FriCAS or, if I am viewAlone. */
  readViewman(&viewAloned,intSize);
  readViewman(&viewData,sizeof(view2DStruct));
  readViewman(&i,intSize);

  if (!(viewData.title = (char *)malloc(i))) {
    fprintf(stderr,
            "ERROR: Ran out of memory trying to receive the title.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }
  readViewman(viewData.title,i);

  for (i=0; i<maxGraphs; i++) {
    readViewman(&(graphArray[i].key),intSize);
    if (graphArray[i].key) {            /** this graph slot has data **/
      getGraphFromViewman(i);
    } /* if graph exists (graphArray[i].key is not zero) */
  } /* for i in graphs */

  viewport = makeView2D(&viewData);
  control = viewport->controlPanel;

  bsdSignal(SIGTERM,goodbye,DontRestartSystemCalls);

  /* send acknowledgement to viewport manager */
  i = 345;
  check(write(Socket,&(viewport->viewWindow),sizeof(Window)));

  processEvents();

  goodbye(-1);
  return(0);  /* control never reaches here but compiler complains */
} /* main() */