/*** redraw_range *****************************************************
   Redraw part of a Color Widget.
   Input:  c - which Color Widget
           a,b - range of entries of table to redraw.
**********************************************************************/
static void redraw_range( LUI_COLORBAR *cb, int a, int b )
{
   Window win;
   int i;
   int x,y, px,py;
   int x1, y1, x2, y2;

   win = cb->window;

   if (a<0)  a = 0;
   if (b>=cb->table_size)  b = cb->table_size-1;

   /* calc region to update */
   x1 = index_to_x( cb, a );
   x2 = index_to_x( cb, b);

   y1 = intensity_to_y( cb, 255 );
   y2 = intensity_to_y( cb, 0 ); 

   /* erase region */
   XFillRectangle( LUI_Display, win, LUI_GC_black,
                   x1,y1, x2-x1+1, y2-y1+1 );

   /* redraw region of entries in interval [a,b] */
   if (a>0) a--;
   if (b<cb->table_size-1)  b++;

   /* draw red levels */
   for (i=a;i<=b;i++) {
      x = index_to_x( cb, i );
      y = intensity_to_y( cb, UNPACK_RED(cb->table[i]) );
      if (i!=a)
         XDrawLine( LUI_Display, win, LUI_GC_red, px, py, x, y );
      px = x;  py = y;
   }

   /* draw green levels */
   for (i=a;i<=b;i++) {
      x = index_to_x( cb, i );
      y = intensity_to_y( cb, UNPACK_GREEN(cb->table[i]) );
      if (i!=a)
         XDrawLine( LUI_Display, win, LUI_GC_green, px,py, x,y );
      px = x;  py = y;
   }

   /* draw blue levels */
   for (i=a;i<=b;i++) {
      x = index_to_x( cb, i );
      y = intensity_to_y( cb, UNPACK_BLUE(cb->table[i]) );
      if (i!=a)
         XDrawLine( LUI_Display, win, LUI_GC_blue, px,py, x,y );
      px = x;  py = y;
   }

   /* draw alpha levels */
   if (cb->minalpha<255 || cb->maxalpha<255) {
      for (i=a;i<=b;i++) {
         x = index_to_x( cb, i );
         y = intensity_to_y( cb, UNPACK_ALPHA(cb->table[i]) );
         if (i!=a)
            XDrawLine( LUI_Display, win, LUI_GC_white, px,py, x,y );
         px = x;  py = y;
      }
   }

   /* draw the color bar */
   for (x=x1;x<=x2;x++) {
      int r, g, b;
      unsigned int color;
      i = x_to_index( cb, x );
      color = cb->table[i];
      r = UNPACK_RED( color );
      g = UNPACK_GREEN( color );
      b = UNPACK_BLUE( color );
      XSetForeground( LUI_Display, LUI_Gc, LUI_AllocateColorInt(r,g,b) );
      XDrawLine( LUI_Display, win, LUI_Gc, x, cb->wedge_y,
                 x, cb->wedge_y + WEDGE_HEIGHT );
   }

   if (cb->helpflag) {
      /* print help messages */
      for (i=0;i<HELP_LINES;i++) {
         XDrawString( LUI_Display, win, LUI_GC_white,
                      cb->framewidth+10,
                      cb->framewidth+12+i*(LUI_Font_height+1),
                      help_strings[i], strlen(help_strings[i]) );
      }
   }
}
Exemple #2
0
void display_iteration() 
     /* Siempre hay una estructura grafica con todo lo que debe estar en pantalla. Permite el pintado incremental para los buffers de puntos, borran el incremento viejo y pintan solo el nuevo */
{
  int i;
  Tvoxel kaka;
 
 
  fl_winset(canvas_win); 
  
 if ((track_robot==TRUE)&&
     ((fabs(robot[0]+odometrico[0])>(rango/4.))||
      (fabs(robot[1]+odometrico[1])>(rango/4.))))
   {odometrico[0]=-robot[0];
   odometrico[1]=-robot[1];
   visual_refresh = TRUE;
   if (debug[SCH_GUIXFORMS]) printf("gui: robot tracking, display movement\n"); 
     }

 if (iteracion_display*guixforms_cycle>FORCED_REFRESH) 
   {iteracion_display=0;
   visual_refresh=TRUE;
   }
 else iteracion_display++;


 if (visual_refresh==TRUE)
   {
     if (debug[SCH_GUIXFORMS]) printf(" TOTAL ");
     fl_rectbound(0,0,width,height,FL_WHITE);   
     XFlush(display);
     /*XSync(display,True);*/
   }
 
 
 /* VISUALIZACION de una instantanea ultrasonica */
   if ((((display_state&DISPLAY_SONARS)!=0)&&(visual_refresh==FALSE))
      || (visual_delete_us==TRUE))
     {  
    fl_set_foreground(canvas_gc,FL_WHITE); 
    /* clean last sonars, but only if there wasn't a total refresh. In case of total refresh the white rectangle already cleaned all */
  for(i=0;i<NUM_SONARS*2;i+=2) XDrawLine(display,canvas_win,canvas_gc,us_dpy[i].x,us_dpy[i].y,us_dpy[i+1].x,us_dpy[i+1].y);

     }

  if ((display_state&DISPLAY_SONARS)!=0){
   if (debug[SCH_GUIXFORMS]) printf(" sonars ");
  for(i=0;i<NUM_SONARS;i++)
      {us2xy(i,0.,0.,&kaka); /* Da en el Tvoxel kaka las coordenadas del sensor, pues es distancia 0 */
      xy2canvas(kaka,&us_dpy[2*i]);
      us2xy(i,us[i],0.,&kaka);
      /*us2xy(i,200,0.,&kaka);
	if (i==6) us2xy(i,400,0.,&kaka);*/
      xy2canvas(kaka,&us_dpy[2*i+1]);
      }
  fl_set_foreground(canvas_gc,FL_PALEGREEN);
  for(i=0;i<NUM_SONARS*2;i+=2) XDrawLine(display,canvas_win,canvas_gc,us_dpy[i].x,us_dpy[i].y,us_dpy[i+1].x,us_dpy[i+1].y);
  }

 /* VISUALIZACION de una instantanea laser*/
   if ((((display_state&DISPLAY_LASER)!=0)&&(visual_refresh==FALSE))
      || (visual_delete_laser==TRUE))
     {  
    fl_set_foreground(canvas_gc,FL_WHITE); 
    /* clean last laser, but only if there wasn't a total refresh. In case of total refresh the white rectangle already cleaned all */
    /*for(i=0;i<NUM_LASER;i++) XDrawPoint(display,canvas_win,canvas_gc,laser_dpy[i].x,laser_dpy[i].y);*/
    XDrawPoints(display,canvas_win,canvas_gc,laser_dpy,NUM_LASER,CoordModeOrigin);
     }

  if ((display_state&DISPLAY_LASER)!=0){
   if (debug[SCH_GUIXFORMS]) printf(" laser ");
   for(i=0;i<NUM_LASER;i++)
     {
       laser2xy(i,laser[i],&kaka);
       xy2canvas(kaka,&laser_dpy[i]);
     }
   fl_set_foreground(canvas_gc,FL_BLUE);
   /*for(i=0;i<NUM_LASER;i++) XDrawPoint(display,canvas_win,canvas_gc,laser_dpy[i].x,laser_dpy[i].y);*/
   XDrawPoints(display,canvas_win,canvas_gc,laser_dpy,NUM_LASER,CoordModeOrigin);
  }




  /* VISUALIZACION: pintar o borrar de el PROPIO ROBOT.
     Siempre hay un repintado total. Esta es la ultima estructura que se se pinta, para que ninguna otra se solape encima */

   if ((((display_state&DISPLAY_ROBOT)!=0) &&(visual_refresh==FALSE))
       || (visual_delete_ego==TRUE))
     {  
      fl_set_foreground(canvas_gc,FL_WHITE); 
    /* clean last robot, but only if there wasn't a total refresh. In case of total refresh the white rectangle already cleaned all */
    for(i=0;i<numego;i++) XDrawLine(display,canvas_win,canvas_gc,ego[i].x,ego[i].y,ego[i+1].x,ego[i+1].y);

     }

  if ((display_state&DISPLAY_ROBOT)!=0){
    if (debug[SCH_GUIXFORMS]) printf(" ego ");
    fl_set_foreground(canvas_gc,FL_MAGENTA);
 /* relleno los nuevos */
    us2xy(15,0.,0.,&kaka);
    xy2canvas(kaka,&ego[0]);
    us2xy(3,0.,0.,&kaka);
    xy2canvas(kaka,&ego[1]);
    us2xy(4,0.,0.,&kaka);
    xy2canvas(kaka,&ego[2]);
    us2xy(8,0.,0.,&kaka);
    xy2canvas(kaka,&ego[3]);
    us2xy(15,0.,0.,&kaka);
    xy2canvas(kaka,&ego[EGOMAX-1]);
    for(i=0;i<NUM_SONARS;i++)
      {
      us2xy((15+i)%NUM_SONARS,0.,0.,&kaka); /* Da en el Tvoxel kaka las coordenadas del sensor, pues es distancia 0 */
      xy2canvas(kaka,&ego[i+4]);       
      }
 
    /* pinto los nuevos */
    numego=EGOMAX-1;
    for(i=0;i<numego;i++) XDrawLine(display,canvas_win,canvas_gc,ego[i].x,ego[i].y,ego[i+1].x,ego[i+1].y);
  }

  if (debug[SCH_GUIXFORMS]) printf("\n");



  /* grey imageA display */
  if (((display_state&DISPLAY_GREYIMAGEA)!=0)&&((display_state&DISPLAY_COLORIMAGEA)==0))
     {
       /* Pasa de la imagen capturada (greyA) a la imagen para visualizar (imagenA_buf), "cambiando" de formato adecuadamente */
       if ((vmode==PseudoColor)&&(fl_state[vmode].depth==8))
	 {for(i=0; i<SIFNTSC_ROWS*SIFNTSC_COLUMNS; i++) 
	   {/*shmimage->data[i]= (unsigned char)tabla[(unsigned char)(greyA[i])];*/
	     imagenA_buf[i]= (unsigned char)tabla[(unsigned char)(greyA[i])];}}
       else if ((vmode==TrueColor)&&(fl_state[vmode].depth==16)) 
	 {
	   for(i=0; i<SIFNTSC_ROWS*SIFNTSC_COLUMNS; i++)
	     { imagenA_buf[i*2+1]=(0xf8&(greyA[i]))+((0xe0&(greyA[i]))>>5);
	     imagenA_buf[i*2]=((0xf8&(greyA[i]))>>3)+((0x1c&(greyA[i]))<<3);
	     }
	 }
       else if ((vmode==TrueColor)&&(fl_state[vmode].depth==24)) 
	 {for(i=0; i<SIFNTSC_ROWS*SIFNTSC_COLUMNS; i++) 
	   { imagenA_buf[i*4]=greyA[i]; /* Blue Byte */
	   imagenA_buf[i*4+1]=greyA[i]; /* Green Byte */
	   imagenA_buf[i*4+2]=greyA[i]; /* Red Byte */
	   imagenA_buf[i*4+3]=0; /* dummy byte */  }
	 }
     }
Exemple #3
0
int main( int argc , char *argv[] ){
    Display *display;
    Window window;
    Window pen_window[5];
    Window color_window[5];

    GC     gc;
    char title[]      = "Paint";
    char icon_title[] = "Paint";
    unsigned long background;
    unsigned long foreground;
    int button_size=40;

    char *colors[]={
	"rgb:00/00/00",
	"rgb:ff/00/00",
	"rgb:00/ff/00",
	"rgb:00/00/ff",
	"rgb:ff/ff/00",
    };

    int current_pen=2;
    unsigned long current_color=0;
    int x0,y0,x1,y1;
    int i;
		     
    display = XOpenDisplay(NULL);

    background = WhitePixel(display,0);
    foreground = BlackPixel(display,0);

    window = XCreateSimpleWindow(display,
                                 DefaultRootWindow(display),
                                 0,0,500,400,
                                 0,0,background);

    XSetStandardProperties(display,window,title,icon_title,
			   None,argv,argc,NULL);

    /* GC を生成し、各種設定を行う */
    gc = XCreateGC(display,window,0,0);
    XSetBackground(display,gc,background);
    XSetForeground(display,gc,current_color);
    XSetLineAttributes(display,gc,current_pen,
		       LineSolid,CapRound,JoinMiter);

    /* メインウィンドウのイベントマスクを設定 */
    XSelectInput(display,window,
		 ExposureMask |
		 ButtonPressMask |
		 ButtonMotionMask);

    /* ペンサイズ・色選択ウィンドウを作成 */
    for ( i=0 ; i<sizeof(pen_window)/sizeof(pen_window[0]) ; i++ ){
	pen_window[i] =
	  XCreateSimpleWindow(display,window,
			      10,(button_size+10)*i+30,
			      button_size,button_size,
			      1,mycolor(display,"rgb:aa/aa/aa"),
			      mycolor(display,"rgb:ee/ee/ee"));
	color_window[i] =
	  XCreateSimpleWindow(display,window,
			      500-10-button_size,(button_size+10)*i+30,
			      button_size,button_size,
			      1,mycolor(display,"rgb:aa/aa/aa"),
			      mycolor(display,colors[i]));
	XSelectInput(display,pen_window[i],
		     ButtonPressMask |
		     EnterWindowMask |
		     LeaveWindowMask );
	XSelectInput(display,color_window[i],
		     ButtonPressMask |
		     EnterWindowMask |
		     LeaveWindowMask );
    }

    /* 全てのウィンドウをマップ */
    XMapWindow(display,window);
    XMapSubwindows(display,window);

    while (1){
	XEvent event;
        XNextEvent(display,&event);
        switch ( event.type ){

          case Expose:		/* 再描画 */
	    for ( i=0 ; i<sizeof(pen_window)/sizeof(pen_window[0]) ; i++ ){
		int pen_size = i*3+2;
				/* ペンサイズウィンドウを再描画 */
		XSetForeground(display,gc,foreground);
		XFillArc(display,pen_window[i],gc,
			 button_size/2-pen_size/2,button_size/2-pen_size/2,
			 pen_size,pen_size,0,360*64);

	    }
            break;

	  case EnterNotify:	/* ウィンドウにポインタが入った */
	    XSetWindowBorder(display,event.xany.window,
			     mycolor(display,"black"));
	    break;

	  case LeaveNotify:	/* ウィンドウからポインタが出た */
	    XSetWindowBorder(display,event.xany.window,
			     mycolor(display,"rgb:aa/aa/aa"));
	    break;

	  case MotionNotify:	/* ボタンを押しながらマウスが動いた */
	    x1 = event.xbutton.x;
	    y1 = event.xbutton.y;
	    XDrawLine(display,window,gc,x0,y0,x1,y1);
	    x0 = x1; y0 = y1;
	    break;

	  case ButtonPress:	/* ボタンが押された */

				/* キャンバス上で押された? */
	    if ( event.xany.window == window ){
		x0 = event.xbutton.x;
		y0 = event.xbutton.y;
		XDrawLine(display,window,gc,x0,y0,x0,y0);
		break;
	    }

				/* ペンサイズ/色選択ウィンドウ上で押された? */
	    for ( i=0 ; i<sizeof(pen_window)/sizeof(pen_window[0]) ; i++ ){
				/* ペンサイズを変更 */
		if ( event.xany.window == pen_window[i] ){
		    current_pen = i*3+2;
		    XSetLineAttributes(display,gc,current_pen,
				       LineSolid,CapRound,JoinMiter);
		    break;
		}
				/* 色を変更 */
		if ( event.xany.window == color_window[i] ){
		    current_color = mycolor(display,colors[i]);
		    XSetForeground(display,gc,current_color);
		    break;
		}
	    }
	    break;
        }
    }
}
Exemple #4
0
void Line (int X1,int Y1,int X2,int Y2) 
{
   XDrawLine(dpy, pm, gc, Ox+X1,Oy+Y1,Ox+X2,Oy+Y2);
   drawcounter++;
}
Exemple #5
0
void PlotArea::plot_point(const char *buf)
{
    int point, x, y;
    int assignments = sscanf(buf, "P%1d%4d%4d", &point, &x, &y);  
    if (assignments != 3)
    {
	plot_unknown(buf);
	return;
    }

    if (point == 7) 
    {
	// Set point size
	px = (int) (x * xscale * pointsize);
	py = (int) (y * yscale * pointsize);
	return;
    }

    if (type != LineSolid || width != 0) 
    {
	// Select solid line
	XSetLineAttributes(dpy, gc, 0, LineSolid, CapButt, JoinBevel);
    }

    switch(point) {
    case 0: // Dot
	XDrawLine(dpy,win,gc, X(x), Y(y), X(x), Y(y));
	break;

    case 1: // Diamond
	XDrawLine(dpy,win,gc, X(x)-px, Y(y), X(x), Y(y)-py);
	XDrawLine(dpy,win,gc, X(x), Y(y)-py, X(x)+px, Y(y));
	XDrawLine(dpy,win,gc, X(x)+px, Y(y), X(x), Y(y)+py);
	XDrawLine(dpy,win,gc, X(x), Y(y)+py, X(x)-px, Y(y));
	XDrawLine(dpy,win,gc, X(x), Y(y), X(x), Y(y));
	break;

    case 2: // Plus
	XDrawLine(dpy,win,gc, X(x)-px, Y(y), X(x)+px, Y(y));
	XDrawLine(dpy,win,gc, X(x), Y(y)-py, X(x), Y(y)+py);
	break;

    case 3: // Box
	XDrawLine(dpy,win,gc, X(x)-px, Y(y)-py, X(x)+px, Y(y)-py);
	XDrawLine(dpy,win,gc, X(x)+px, Y(y)-py, X(x)+px, Y(y)+py);
	XDrawLine(dpy,win,gc, X(x)+px, Y(y)+py, X(x)-px, Y(y)+py);
	XDrawLine(dpy,win,gc, X(x)-px, Y(y)+py, X(x)-px, Y(y)-py);
	XDrawLine(dpy,win,gc, X(x), Y(y), X(x), Y(y));
	break;

    case 4: // X
	XDrawLine(dpy,win,gc, X(x)-px, Y(y)-py, X(x)+px, Y(y)+py);
	XDrawLine(dpy,win,gc, X(x)-px, Y(y)+py, X(x)+px, Y(y)-py);
	break;

    case 5: // Triangle
	XDrawLine(dpy,win,gc, X(x), Y(y)-(4*px/3), 
		  X(x)-(4*px/3), Y(y)+(2*py/3));
	XDrawLine(dpy,win,gc, X(x), Y(y)-(4*px/3), 
		  X(x)+(4*px/3), Y(y)+(2*py/3));
	XDrawLine(dpy,win,gc, X(x)-(4*px/3), Y(y)+(2*py/3), 
		  X(x)+(4*px/3), Y(y)+(2*py/3));
	XDrawLine(dpy,win,gc, X(x), Y(y), X(x), Y(y));
	break;

    case 6: // Star
	XDrawLine(dpy,win,gc, X(x)-px, Y(y), X(x)+px, Y(y));
	XDrawLine(dpy,win,gc, X(x), Y(y)-py, X(x), Y(y)+py);
	XDrawLine(dpy,win,gc, X(x)-px, Y(y)-py, X(x)+px, Y(y)+py);
	XDrawLine(dpy,win,gc, X(x)-px, Y(y)+py, X(x)+px, Y(y)-py);
	break;
    }

    if (type != LineSolid || width != 0)
    {  
	// Restore line type
	XSetLineAttributes(dpy, gc, width, type, CapButt, JoinBevel);
    }
}
Exemple #6
0
void GuiCalibratorX11::redraw()
{
    if (calibrator->get_geometry() == NULL) {
        int width = 0, height = 0;
        detect_screen_geometry(&width, &height);
        if (display_width != width || display_height != height) {
            set_display_size(width, height);
        }
    }

    // Print the text
    int text_height = font_info->ascent + font_info->descent;
    int text_width = -1;
    for (std::list<std::string>::iterator it = display_texts.begin();
        it != display_texts.end(); it++) {
        text_width = std::max(text_width, XTextWidth(font_info,
            (*it).c_str(), (*it).length()));
    }

    int x = (display_width - text_width) / 2;
    int y = (display_height - text_height) / 2 - 60;
    XSetForeground(display, gc, pixel[BLACK]);
    XSetLineAttributes(display, gc, 2, LineSolid, CapRound, JoinRound);
    XDrawRectangle(display, win, gc, x - 10, y - (display_texts.size()*text_height) - 10,
                text_width + 20, (display_texts.size()*text_height) + 20);

    // Print help lines
    y -= 3;
    for (std::list<std::string>::reverse_iterator rev_it = display_texts.rbegin();
	     rev_it != display_texts.rend(); rev_it++) {
        int w = XTextWidth(font_info, (*rev_it).c_str(), (*rev_it).length());
        XDrawString(display, win, gc, x + (text_width-w)/2, y,
                (*rev_it).c_str(), (*rev_it).length());
        y -= text_height;
    }

    // Draw the points
    for (int i = 0; i <= calibrator->get_numclicks(); i++) {
        // set color: already clicked or not
        if (i < calibrator->get_numclicks())
            XSetForeground(display, gc, pixel[WHITE]);
        else
            XSetForeground(display, gc, pixel[RED]);
        XSetLineAttributes(display, gc, 1, LineSolid, CapRound, JoinRound);

        XDrawLine(display, win, gc, X[i] - cross_lines, Y[i],
                X[i] + cross_lines, Y[i]);
        XDrawLine(display, win, gc, X[i], Y[i] - cross_lines,
                X[i], Y[i] + cross_lines);
        XDrawArc(display, win, gc, X[i] - cross_circle, Y[i] - cross_circle,
                (2 * cross_circle), (2 * cross_circle), 0, 360 * 64);
    }

    // Draw the clock background
    if(calibrator->get_use_timeout()){
        XSetForeground(display, gc, pixel[DIMGRAY]);
        XSetLineAttributes(display, gc, 0, LineSolid, CapRound, JoinRound);
        XFillArc(display, win, gc, (display_width-clock_radius)/2, (display_height - clock_radius)/2,
                    clock_radius, clock_radius, 0, 360 * 64);
    }
}
Exemple #7
0
/* Draws a 3D rectangle */
void Draw3dRect(
	Window wn, int x, int y, int w, int h, XRectangle *bounding,
	int state, Bool iconified)
{
	colorset_t *cset = &Colorset[0];  /* initialize to avoid warning */
	int d = 1;
	XRectangle r,inter;
	Bool draw;

	if (ThreeDfvwm)
	{
		d = 2;
	}
	if (bounding)
	{
		r.x = bounding->x;
		r.y = bounding->y;
		r.width = bounding->width;
		r.height = bounding->height;
	}
	else
	{
		r.x = x;
		r.y = y;
		r.width = w;
		r.height = h;
	}
	XClearArea (dpy, wn, r.x, r.y, r.width, r.height, False);
	if (iconified)
	{
		draw = frect_get_intersection(
			x + d, y + d, w - 3, h - 3,
			r.x, r.y, r.width, r.height, &inter);
		if (iconcolorset >= 0)
		{
			cset = &Colorset[iconcolorset];
		}
		if (iconcolorset >= 0 && (cset->pixmap || cset->shape_mask)
		    && draw)
		{
			/* we have a colorset background */
			SetClippedRectangleBackground(
				dpy, win, x + d, y + d, w - 3, h - 3, &inter,
				cset, Pdepth, icongraph);
		}
		else if (draw)
		{
			XFillRectangle (
				dpy, wn, iconbackgraph,
				inter.x, inter.y, inter.width, inter.height);
		}
		XDrawLine (dpy, wn, iconhilite, x, y, x+w-2, y);
		XDrawLine (dpy, wn, iconhilite, x, y, x, y+h-2);
		if (ThreeDfvwm)
		{
			XDrawLine (dpy, wn, iconhilite, x, y+1, x+w-2, y+1);
			XDrawLine (dpy, wn, iconhilite, x+1, y, x+1, y+h-2);
		}
		XDrawLine (dpy, wn, iconshadow,  x+1, y+h-2, x+w-2, y+h-2);
		XDrawLine (dpy, wn, iconshadow,  x+w-2, y+h-2, x+w-2, y+1);
		XDrawLine (dpy, wn, blackgc, x, y+h-1, x+w-1, y+h-1);
		XDrawLine (dpy, wn, blackgc, x+w-1, y+h-1, x+w-1, y);
		return;
	}

	switch (state)
	{
	case BUTTON_UP:
		XDrawLine (dpy, wn, hilite, x, y, x+w-2, y);
		XDrawLine (dpy, wn, hilite, x, y, x, y+h-2);
		if (ThreeDfvwm)
		{
			XDrawLine (dpy, wn, hilite, x, y+1, x+w-2, y+1);
			XDrawLine (dpy, wn, hilite, x+1, y, x+1, y+h-2);
		}
		XDrawLine (dpy, wn, shadow,  x+1, y+h-2, x+w-2, y+h-2);
		XDrawLine (dpy, wn, shadow,  x+w-2, y+h-2, x+w-2, y+1);
		XDrawLine (dpy, wn, blackgc, x, y+h-1, x+w-1, y+h-1);
		XDrawLine (dpy, wn, blackgc, x+w-1, y+h-1, x+w-1, y);
		break;
	case BUTTON_BRIGHT:
		draw = frect_get_intersection(
				x + 2, y + 2, w - 4 + (2 - d), h - 4 + (2 - d),
				r.x, r.y, r.width, r.height, &inter);
		if (focuscolorset >= 0)
			cset = &Colorset[focuscolorset];
		if (focuscolorset >= 0 && (cset->pixmap || cset->shape_mask) &&
		    draw)
		{
			/* we have a colorset background */
			SetClippedRectangleBackground(
				dpy, win, x + 2, y + 2, w - 4 + (2 - d),
				h - 4 + (2 - d), &inter, cset, Pdepth,
				focusgraph);
		}
		else if (draw)
		{
			XFillRectangle (
				dpy, wn, focusbackgraph, inter.x, inter.y,
				inter.width, inter.height);
		}
		if (!NoBrightFocus)
			XFillRectangle (
				dpy, wn, checkered, inter.x, inter.y,
				inter.width, inter.height);
		XDrawLine (dpy, wn, blackgc, x, y, x+w-2, y);
		XDrawLine (dpy, wn, blackgc, x, y, x, y+h-2);

		XDrawLine (dpy, wn, focusshadow, x, y+1, x+w-2, y+1);
		XDrawLine (dpy, wn, focusshadow, x+1, y, x+1, y+h-2);
		if (ThreeDfvwm)
		{
			XDrawLine (
				dpy, wn, focushilite,  x+1, y+h-2, x+w-2, y+h-2);
			XDrawLine (
				dpy, wn, focushilite,  x+w-2, y+h-2, x+w-2, y+1);
		}
		XDrawLine (dpy, wn, focushilite, x, y+h-1, x+w-1, y+h-1);
		XDrawLine (dpy, wn, focushilite, x+w-1, y+h-1, x+w-1, y);
		break;
	case BUTTON_DOWN:
		XDrawLine (dpy, wn, blackgc, x, y, x+w-2, y);
		XDrawLine (dpy, wn, blackgc, x, y, x, y+h-2);

		XDrawLine (dpy, wn, shadow, x, y+1, x+w-2, y+1);
		XDrawLine (dpy, wn, shadow, x+1, y, x+1, y+h-2);
		if (ThreeDfvwm)
		{
			XDrawLine (dpy, wn, hilite,  x+1, y+h-2, x+w-2, y+h-2);
			XDrawLine (dpy, wn, hilite,  x+w-2, y+h-2, x+w-2, y+1);
		}
		XDrawLine (dpy, wn, hilite, x, y+h-1, x+w-1, y+h-1);
		XDrawLine (dpy, wn, hilite, x+w-1, y+h-1, x+w-1, y);
		break;
	}
}
Exemple #8
0
static void 
DoStroke(XEvent *event, StrokeStatePtr State)
{
	int i;
	int xtol;
	int ytol;
	int LastBox;
	int BoxWidth;
	int BoxHeight;
	int x0, x1, x2, x3;
	int y0, y1, y2, y3;
	String action;
	StrokeMapPtr *tmp = State->Map;
	int FinalPoints;

	/*
	   fprintf(stderr, "DoStroke(%s) - %i %i %i %i\n",
	   XtName(State->widget),
	   State->xmin, State->ymin,
	   State->xmax, State->ymax);
	 */
	if (State->npoints < 2)
		return;

	BoxWidth = State->xmax - State->xmin;
	BoxHeight = State->ymax - State->ymin;
	x0 = State->xmin;
	x1 = State->xmin + (1 * BoxWidth / 3);
	x2 = State->xmin + (2 * BoxWidth / 3);
	x3 = State->xmin + (3 * BoxWidth / 3);
	xtol = BoxWidth / State->slop;
	y0 = State->ymin;
	y1 = State->ymin + (1 * BoxHeight / 3);
	y2 = State->ymin + (2 * BoxHeight / 3);
	y3 = State->ymin + (3 * BoxHeight / 3);
	ytol = BoxHeight / State->slop;
	if (x3 - x0 < 20)
	{
		x1 = x0 - 1;
		x2 = x3 + 1;
	}
	if (y3 - y0 < 20)
	{
		y1 = y0 - 1;
		y2 = y3 + 1;
	}

	if (State->Debug)
	{
		XDrawRectangle(XtDisplay(State->widget),
			       event->xbutton.root,
			       State->gc,
			       x0, y0,
			       BoxWidth,
			       BoxHeight);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x1, y0,
			  x1, y3);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x1 - xtol, y0,
			  x1 - xtol, y3);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x1 + xtol, y0,
			  x1 + xtol, y3);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x2, y0,
			  x2, y3);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x2 - xtol, y0,
			  x2 - xtol, y3);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x2 + xtol, y0,
			  x2 + xtol, y3);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x0, y1,
			  x3, y1);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x0, y1 - ytol,
			  x3, y1 - ytol);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x0, y1 + ytol,
			  x3, y1 + ytol);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x0, y2,
			  x3, y2);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x0, y2 - ytol,
			  x3, y2 - ytol);
		XDrawLine(XtDisplay(State->widget),
			  event->xbutton.root,
			  State->gc,
			  x0, y2 + ytol,
			  x3, y2 + ytol);
	}
	for (i = 1; i < State->npoints; i++)
	{
		int dx = State->points[i - 1].x - State->points[i].x;
		int dy = State->points[i - 1].y - State->points[i].y;
		int maxx = (x2 - xtol) - (x1 + xtol);
		int maxy = (y2 - ytol) - (y1 + ytol);

		if (((dx * dx) >= (maxx * maxx)) || ((dy * dy) >= (maxy * maxy)))
		{
			int j;

			AllocatePoints(State);
			for (j = State->npoints; j > i; j--)
			{
				State->points[j].x = State->points[j - 1].x;
				State->points[j].y = State->points[j - 1].y;
			}
			State->npoints++;
			State->points[i].x = State->points[i - 1].x + (State->points[i].x - State->points[i - 1].x) / 2;
			State->points[i].y = State->points[i - 1].y + (State->points[i].y - State->points[i - 1].y) / 2;
			/*
			   XDrawRectangle(XtDisplay(State->widget),
			   XtWindow(State->widget),
			   State->gc,
			   State->points[i].x - 4,
			   State->points[i].y - 4,
			   8,
			   8);
			 */
			i--;
		}
	}
	for (i = 0; i < State->npoints; i++)
	{
		if ((State->points[i].x >= x0 && State->points[i].x < x1 - xtol) &&
		  (State->points[i].y >= y0 && State->points[i].y < y1 - ytol))
		{
			State->box[i] = 1;
		}
		else if ((State->points[i].x >= x1 + xtol && State->points[i].x < x2 - xtol) &&
		  (State->points[i].y >= y0 && State->points[i].y < y1 - ytol))
		{
			State->box[i] = 2;
		}
		else if ((State->points[i].x >= x2 + xtol && State->points[i].x <= x3) &&
		  (State->points[i].y >= y0 && State->points[i].y < y1 - ytol))
		{
			State->box[i] = 3;
		}
		else if ((State->points[i].x >= x0 && State->points[i].x < x1 - xtol) &&
			 (State->points[i].y >= y1 + ytol && State->points[i].y < y2 - ytol))
		{
			State->box[i] = 4;
		}
		else if ((State->points[i].x >= x1 + xtol && State->points[i].x < x2 - xtol) &&
			 (State->points[i].y >= y1 + ytol && State->points[i].y < y2 - ytol))
		{
			State->box[i] = 5;
		}
		else if ((State->points[i].x >= x2 + xtol && State->points[i].x <= x3) &&
			 (State->points[i].y >= y1 + ytol && State->points[i].y < y2 - ytol))
		{
			State->box[i] = 6;
		}
		else if ((State->points[i].x >= x0 && State->points[i].x < x1 - xtol) &&
		 (State->points[i].y >= y2 + ytol && State->points[i].y <= y3))
		{
			State->box[i] = 7;
		}
		else if ((State->points[i].x >= x1 + xtol && State->points[i].x < x2 - xtol) &&
		 (State->points[i].y >= y2 + ytol && State->points[i].y <= y3))
		{
			State->box[i] = 8;
		}
		else if ((State->points[i].x >= x2 + xtol && State->points[i].x <= x3) &&
		 (State->points[i].y >= y2 + ytol && State->points[i].y <= y3))
		{
			State->box[i] = 9;
		}
		else
		{
			State->box[i] = 0;
		}
	}
	LastBox = 0;
	FinalPoints = 0;
	action = XtNewString("Stroke-");
	for (i = 0; i < State->npoints; i++)
	{
		if ((State->box[i] != 0) && (State->box[i] != LastBox))
		{
			action = XtRealloc(action, 2 + strlen(action));
			sprintf(&action[strlen(action)], "%i", State->box[i]);
			LastBox = State->box[i];
			FinalPoints++;
		}
	}
	{
		StrokeStatePtr WidgetState;

		WidgetState = StrokeGetMap(State->widget);
		tmp = WidgetState->Map;
	}
	while (tmp != NULL && (*tmp) != NULL && FinalPoints > 2)
	{
		if (strcmp(&action[7], (*tmp)->Stroke) == 0)
		{
			if (State->Debug)
			{
				fprintf(stderr, "%s(%i) - %s Calling action >%s<\n",
					__FILE__, __LINE__,
					XtName(State->widget),
					(*tmp)->Action);
			}
			if (State->Sound != NULL)
			{
				XtCallActionProc(State->widget, "PlaySound", NULL, &State->Sound, 1);
			}
			XtCallActionProc(State->widget, (*tmp)->Action, event, NULL, 0);
			break;
		}
		tmp++;
	}
	if (((tmp == NULL) || ((*tmp) == NULL)) && FinalPoints > 2)
	{
		if (State->Debug)
		{
			fprintf(stderr, "%s(%i) - %s Calling action >%s<\n",
				__FILE__,
				__LINE__,
				XtName(State->widget),
				action);
		}
		XtCallActionProc(State->widget, action, event, NULL, 0);
	}
	XtFree(action);
}
Exemple #9
0
static void Input (Widget W, StrokeStatePtr State, XEvent *event)
{
	/*
	   fprintf(stderr, "Input(%s,%i) - %s %i %i %i %i\n",
	   XtName(State->widget),
	   event->xany.type,
	   XtName(W),
	   event->xbutton.x,
	   event->xbutton.y,
	   event->xbutton.x_root,
	   event->xbutton.y_root);
	 */
	switch (event->xany.type)
	{
	case KeyRelease:
	case ButtonRelease:
		if (State->InStroke)
		{
			int i;

			if (!State->Debug)
			{
				for (i = 1; i < State->npoints; i++)
				{
					XDrawLine(XtDisplay(W),
						  event->xbutton.root,
						  State->gc,
						  State->points[i - 1].x,
						  State->points[i - 1].y,
						  State->points[i].x,
						  State->points[i].y);
					/*
					   XDrawRectangle(XtDisplay(State->widget),
					   XtWindow(State->widget),
					   State->gc,
					   State->points[State->npoints].x - 2,
					   State->points[State->npoints].y - 2,
					   4,
					   4);
					 */
				}
			}
			XtUngrabPointer(W, event->xbutton.time);
			XUngrabServer(XtDisplay(W));
			DoStroke(event, State);
			State->InStroke = False;
			State->npoints = 0;
		}
		break;
	case KeyPress:
	case ButtonPress:
		if (!State->InStroke)
		{
			State->widget = W;
			State->npoints = 0;
			AllocatePoints(State);
			/*
			   TranslateCoords(W, State->widget,
			   &((XButtonPressedEvent *)event)->x,
			   &((XButtonPressedEvent *)event)->y);
			 */
			State->points[State->npoints].x = event->xbutton.x_root;
			State->points[State->npoints].y = event->xbutton.y_root;
			State->xmin = State->points[State->npoints].x;
			State->ymin = State->points[State->npoints].y;
			State->xmax = State->points[State->npoints].x;
			State->ymax = State->points[State->npoints].y;
			State->npoints++;
			State->InStroke = True;
			XGrabServer(XtDisplay(W));
			XtGrabPointer(W, 
				False,
				ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
				GrabModeAsync, GrabModeAsync, None, None, event->xbutton.time);
		}
		break;
	case MotionNotify:
		if (State->gc == (GC)NULL)
		{
			Pixel Background;

			State->gc = XCreateGC(XtDisplay(State->widget),
					      XtWindow(State->widget),
					      0, NULL);
			XtVaGetValues(State->widget,
				      XtNbackground, &Background,
				      NULL);
			XSetForeground(XtDisplay(State->widget),
				       State->gc,
				       Background);
			XSetFunction(XtDisplay(State->widget), State->gc, GXxor);
			XSetSubwindowMode(XtDisplay(State->widget), State->gc, IncludeInferiors);
		}
		if (State->InStroke)
		{
			int dx = State->points[State->npoints - 1].x - event->xmotion.x_root;
			int dy = State->points[State->npoints - 1].y - event->xmotion.y_root;

			if (dx * dx + dy * dy > State->slop)
			{
				AllocatePoints(State);
				State->points[State->npoints].x = event->xmotion.x_root;
				State->points[State->npoints].y = event->xmotion.y_root;
				XDrawLine(XtDisplay(State->widget),
					  event->xmotion.root,
					  State->gc,
					  State->points[State->npoints - 1].x,
					  State->points[State->npoints - 1].y,
					  State->points[State->npoints].x,
					  State->points[State->npoints].y);
				State->xmin = State->xmin < State->points[State->npoints].x ? State->xmin : State->points[State->npoints].x;
				State->xmax = State->xmax > State->points[State->npoints].x ? State->xmax : State->points[State->npoints].x;
				State->ymin = State->ymin < State->points[State->npoints].y ? State->ymin : State->points[State->npoints].y;
				State->ymax = State->ymax > State->points[State->npoints].y ? State->ymax : State->points[State->npoints].y;
				State->npoints++;
			}
		}
		break;
	default:
		fprintf(stderr, "%s(%i): Input(%s) - %s Unknown event type %i\n",
			__FILE__,
			__LINE__,
			XtName(State->widget),
			XtName(W),
			event->type);
	}
}
Exemple #10
0
void
drawswarm(Window win)
{
	swarmstruct *sp = &swarms[screen];
	int         b;

	/* <=- Wasp -=> */
	/* Age the arrays. */
	sp->wx[2] = sp->wx[1];
	sp->wx[1] = sp->wx[0];
	sp->wy[2] = sp->wy[1];
	sp->wy[1] = sp->wy[0];
	/* Accelerate */
	sp->wxv += balance_rand(WASPACC);
	sp->wyv += balance_rand(WASPACC);

	/* Speed Limit Checks */
	if (sp->wxv > WASPVEL)
		sp->wxv = WASPVEL;
	if (sp->wxv < -WASPVEL)
		sp->wxv = -WASPVEL;
	if (sp->wyv > WASPVEL)
		sp->wyv = WASPVEL;
	if (sp->wyv < -WASPVEL)
		sp->wyv = -WASPVEL;

	/* Move */
	sp->wx[0] = sp->wx[1] + sp->wxv;
	sp->wy[0] = sp->wy[1] + sp->wyv;

	/* Bounce Checks */
	if ((sp->wx[0] < sp->border) || (sp->wx[0] > sp->width - sp->border - 1)) {
		sp->wxv = -sp->wxv;
		sp->wx[0] += sp->wxv;
	}
	if ((sp->wy[0] < sp->border) || (sp->wy[0] > sp->height - sp->border - 1)) {
		sp->wyv = -sp->wyv;
		sp->wy[0] += sp->wyv;
	}
	/* Don't let things settle down. */
	sp->xv[LRAND() % sp->beecount] += balance_rand(3);
	sp->yv[LRAND() % sp->beecount] += balance_rand(3);

	/* <=- Bees -=> */
	for (b = 0; b < sp->beecount; b++) {
		int         distance, dx, dy;

		/* Age the arrays. */
		X(2, b) = X(1, b);
		X(1, b) = X(0, b);
		Y(2, b) = Y(1, b);
		Y(1, b) = Y(0, b);

		/* Accelerate */
		dx = sp->wx[1] - X(1, b);
		dy = sp->wy[1] - Y(1, b);
		distance = abs(dx) + abs(dy);	/* approximation */
		if (distance == 0)
			distance = 1;
		sp->xv[b] += (dx * BEEACC) / distance;
		sp->yv[b] += (dy * BEEACC) / distance;

		/* Speed Limit Checks */
		if (sp->xv[b] > BEEVEL)
			sp->xv[b] = BEEVEL;
		if (sp->xv[b] < -BEEVEL)
			sp->xv[b] = -BEEVEL;
		if (sp->yv[b] > BEEVEL)
			sp->yv[b] = BEEVEL;
		if (sp->yv[b] < -BEEVEL)
			sp->yv[b] = -BEEVEL;

		/* Move */
		X(0, b) = X(1, b) + sp->xv[b];
		Y(0, b) = Y(1, b) + sp->yv[b];

		/* Fill the segment lists. */
		sp->segs[b].x1 = X(0, b);
		sp->segs[b].y1 = Y(0, b);
		sp->segs[b].x2 = X(1, b);
		sp->segs[b].y2 = Y(1, b);
		sp->old_segs[b].x1 = X(1, b);
		sp->old_segs[b].y1 = Y(1, b);
		sp->old_segs[b].x2 = X(2, b);
		sp->old_segs[b].y2 = Y(2, b);
	}

	XSetForeground(dsp, Scr[screen].gc, BlackPixel(dsp, screen));
	XDrawLine(dsp, win, Scr[screen].gc,
		  sp->wx[1], sp->wy[1], sp->wx[2], sp->wy[2]);
	XDrawSegments(dsp, win, Scr[screen].gc, sp->old_segs, sp->beecount);

	XSetForeground(dsp, Scr[screen].gc, WhitePixel(dsp, screen));
	XDrawLine(dsp, win, Scr[screen].gc,
		  sp->wx[0], sp->wy[0], sp->wx[1], sp->wy[1]);
	if (!mono && Scr[screen].npixels > 2) {
		XSetForeground(dsp, Scr[screen].gc, Scr[screen].pixels[sp->pix]);
		if (++sp->pix >= Scr[screen].npixels)
			sp->pix = 0;
	}
	XDrawSegments(dsp, win, Scr[screen].gc, sp->segs, sp->beecount);
}
void
x11_draw_layout_line_with_colors( Drawable         drawable,
                                  GC               gc,
                                  int              x,
                                  int              y,
                                  PangoLayoutLine  *line,
                                  XColor           *foreground,
                                  XColor           *background)
{
    PangoRectangle overall_rect;
    PangoRectangle logical_rect;
    PangoRectangle ink_rect;
    PangoContext *context;
    gint x_off = 0;
    gint rise = 0;

    context = pango_layout_get_context (line->layout);

    pango_layout_line_get_extents (line,NULL, &overall_rect);

    GSList *tmp_list = line->runs;
    while (tmp_list)
    {
        PangoUnderline uline = PANGO_UNDERLINE_NONE;
        PangoLayoutRun *run = (PangoLayoutRun *) tmp_list->data;
        PangoColor fg_color, bg_color;
        gboolean strike, fg_set, bg_set, shape_set;
        gint risen_y;

        tmp_list = tmp_list->next;

        x11_pango_get_item_properties (run->item, &uline,
            &strike, &rise,  &fg_color, &fg_set, &bg_color, &bg_set,
            &shape_set, &ink_rect, &logical_rect);

        /* we subtract the rise because X coordinates are upside down */
        risen_y = y - rise / PANGO_SCALE;

        if (!shape_set)
        {
            if (uline == PANGO_UNDERLINE_NONE)
                pango_glyph_string_extents (run->glyphs, run->item->analysis.font, NULL, &logical_rect);
            else
                pango_glyph_string_extents (run->glyphs, run->item->analysis.font, &ink_rect, &logical_rect);
        }

#if 0
	    XDrawRectangle( drawable, gc, TRUE,
			      x + (x_off + logical_rect.x) / PANGO_SCALE,
			      risen_y + overall_rect.y / PANGO_SCALE,
			      logical_rect.width / PANGO_SCALE,
			      overall_rect.height / PANGO_SCALE);
#endif

        if (!shape_set)
        {
            int gx = x + x_off / PANGO_SCALE;
            int gy = risen_y;

            x11_draw_glyphs( drawable, gc, run->item->analysis.font, gx, gy, run->glyphs);
        }

        if (uline ==  PANGO_UNDERLINE_SINGLE)
        {
            XDrawLine( wxGlobalDisplay(), drawable, gc,
			  x + (x_off + ink_rect.x) / PANGO_SCALE - 1,
                          risen_y + 1,
			  x + (x_off + ink_rect.x + ink_rect.width) / PANGO_SCALE,
                         risen_y + 1);
        }

        x_off += logical_rect.width;
    }
}
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);
}
Exemple #13
0
/*	draw_recur draws the object associated with zone i and the objects
	associated with all the zones that touch it.
*/
void	draw_recur(int i)
{
	register int	j, tmp;

	if(zones[i].drawn) return;
	for(j=0; j<zones[i].numtouch; j++) {
		draw_recur(zones[i].touch[j]);
	}
	switch(zones[i].type) {
		case ZLINE:
			XDrawLine(display, gamewindow, ctable[CWHITE].smallgc,
						mazelines[zones[i].num].x1 - plx + WINDOWWIDTH / 2,
						mazelines[zones[i].num].y1 - ply + WINDOWHEIGHT / 2,
						mazelines[zones[i].num].x2 - plx + WINDOWWIDTH / 2,
						mazelines[zones[i].num].y2 - ply + WINDOWHEIGHT / 2);
			break;
		case ZPLAYER:
			if(!dead && (exploded == -1)) {
				XCopyArea(display, playerpix[playerphase], gamewindow,
							ctable[CWHITE].smallgc, 0, 0, PLAYERWIDTH,
							PLAYERHEIGHT, WINDOWWIDTH / 2 - PLAYERWIDTH / 2,
							WINDOWHEIGHT / 2 - PLAYERHEIGHT / 2);
			}
			break;
		case ZBURN:
			if(!dead && (exploded == -1) && burn) {
				XCopyArea(display, burnpix[playerphase / FACEFRONT],
							gamewindow, ctable[CWHITE].smallgc, 0, 0,
							PLAYERWIDTH, PLAYERHEIGHT, WINDOWWIDTH / 2 -
							PLAYERWIDTH / 2, WINDOWHEIGHT / 2 - PLAYERHEIGHT
							/ 2);
			}
			break;
		case ZEXPLODE:
			if(!dead && (exploded > -1)) {
				XCopyArea(display, explodepix[exploded], gamewindow,
							ctable[CWHITE].smallgc, 0, 0, EXPLODEWIDTH,
							EXPLODEHEIGHT, WINDOWWIDTH / 2 - EXPLODEWIDTH / 2,
							WINDOWHEIGHT / 2 - EXPLODEHEIGHT / 2);
			}
			break;
		case ZFIRE:
			XCopyArea(display, firepix[firephase[zones[i].num]],
						gamewindow, ctable[CWHITE].smallgc, 0, 0,
						FIREWIDTH, FIREHEIGHT, transx(firex[zones[i].num],
						FIREWIDTH), transy(firey[zones[i].num],
						FIREHEIGHT));
			break;
		case ZGUARD:
			XCopyArea(display,
				guardpix[guarddir[zones[i].num]][guardphase[zones[i].num]],
						gamewindow, ctable[CWHITE].smallgc, 0, 0,
						GUARDWIDTH, GUARDHEIGHT, transx(guardx[zones[i].num],
						GUARDWIDTH), transy(guardy[zones[i].num],
						GUARDHEIGHT));
			break;
		case ZSWEEP:
			XCopyArea(display, sweeperpix[sweepphase[zones[i].num]],
						gamewindow, ctable[CWHITE].smallgc, 0, 0,
						SWEEPERWIDTH, SWEEPERHEIGHT,
						transx(sweepx[zones[i].num], SWEEPERWIDTH),
						transy(sweepy[zones[i].num], SWEEPERHEIGHT));
			break;
		case ZFUEL:
			if(fuelalive[zones[i].num]) {
				XCopyArea(display, fuelpix, gamewindow,
							ctable[CWHITE].smallgc, 0, 0, FUELWIDTH,
							FUELHEIGHT, transx(fuelx[zones[i].num],
							FUELWIDTH), transy(fuely[zones[i].num],
							FUELHEIGHT));
			} else if(fueltimer[zones[i].num]) {
				tmp = XTextWidth(fontinfo, "100", 3) / 2;
				XDrawString(display, gamewindow, ctable[CGREEN].smallgc,
							fuelx[zones[i].num] - plx + WINDOWWIDTH / 2 -
							tmp, fuely[zones[i].num] - ply +
							WINDOWHEIGHT / 2, "100", 3);
			}
			break;
		case ZKEY:
			if(keyalive) {
				XCopyArea(display, keypix, gamewindow,
							ctable[CWHITE].smallgc, 0, 0, KEYWIDTH,
							KEYHEIGHT, transx(keyx, KEYWIDTH),
							transy(keyy, KEYHEIGHT));
			} else if(keytimer) {
				tmp = XTextWidth(fontinfo, "500", 3) / 2;
				XDrawString(display, gamewindow, ctable[CGREEN].smallgc,
							keyx - plx + WINDOWWIDTH / 2 - tmp, keyy -
							ply + WINDOWHEIGHT / 2, "500", 3);
			}
			break;
		case ZDOOR:
			tmp = indoor;
			if(indoor && (exploded > -1))  tmp = 0;
			XCopyArea(display, doorpix[tmp], gamewindow,
						ctable[CWHITE].smallgc, 0, 0, DOORWIDTH,
						DOORHEIGHT, transx(doorx, DOORWIDTH),
						transy(doory, DOORHEIGHT) - (DOORHEIGHT -
						PLAYERHEIGHT) / 2);
			break;
		case ZSMESS:
			if(messagetime != 0) {
				if(messagecolor == CBLACK) tmp = random() % (NCOLORS-1) + 1;
				else tmp = messagecolor;
				XDrawString(display, gamewindow, ctable[tmp].smallgc,
							messagex, messagey, messagestring, messagelength);
			}
			break;
		case ZBMESS:
			if(bigmessagetime != 0) {
				if(bigmessagecolor == CBLACK) tmp = random() % (NCOLORS-1) + 1;
				else tmp = bigmessagecolor;
				XDrawString(display, gamewindow, ctable[tmp].biggc,
							bigmessagex, bigmessagey, bigmessagestring, 
							bigmessagelength);
			}
			break;
	}
	zones[i].drawn = 1;
}
static void redraw_marker( LUI_COLORBAR *cb )
{
   Window win;
   int x, y0, y1;
   char str[50];
   int dir,ascent, descent;
   XCharStruct overall;
   int xpos;
   float val;

   win = cb->window;

   y0 = cb->marker_y;
   y1 = cb->height - cb->framewidth - 1;
   XFillRectangle( LUI_Display, win, LUI_GC_black,
                   cb->framewidth, y0,
                   cb->width-cb->framewidth*2, y1-y0+1 );

   /* draw marker below color wedge at ctable[pos] */
   x = index_to_x( cb, cb->markerpos );
   XDrawLine( LUI_Display, win, LUI_GC_white,
              x, cb->marker_y, x, cb->marker_y+MARKER_HEIGHT );
   XDrawLine( LUI_Display, win, LUI_GC_white,
              x, cb->marker_y, x-3, cb->marker_y+6 );
   XDrawLine( LUI_Display, win, LUI_GC_white,
              x, cb->marker_y, x+3, cb->marker_y+6 );

   /* draw min value */
   sprintf( str, "%.2f", cb->minval );
   XDrawString( LUI_Display, win, LUI_GC_white,
                cb->framewidth+2, cb->label_y, str, strlen(str) );

   /* draw variable name and marker value */
   val = cb->minval + (cb->maxval-cb->minval)
                  * ( (float) cb->markerpos / (float) (cb->table_size-1));
   sprintf(str,"%s= %.2f", cb->label, val );
   XTextExtents( LUI_Font, str, strlen(str), &dir,&ascent,&descent,&overall );
   xpos = (cb->width - overall.width) / 2;
   XDrawString( LUI_Display, win, LUI_GC_white,
                xpos, cb->label_y, str, strlen(str) );

   /* draw max value */
   sprintf( str, "%.2f", cb->maxval );
   XTextExtents( LUI_Font, str, strlen(str), &dir,&ascent,&descent,&overall );
   xpos = cb->width - overall.width - cb->framewidth - 2;
   XDrawString( LUI_Display, win, LUI_GC_white,
                xpos, cb->label_y, str, strlen(str) );

   /* draw new compression & rotation factors */
/*  This can be un-commented if you want to see these values superimposed
   over the color curves.
   fprintf(stderr,"redraw_marker(): Curve=%.1f\n",cb->curve);
   sprintf(str,"comp=%.1f",cb->curve);
   XDrawString( LUI_Display, win, LUI_GC_white, 15, 75, str, strlen(str) );
   fprintf(stderr,"redraw_marker(): Bias =%.3f\n\n",cb->params[BIAS]);
   sprintf(str,"rot =%.3f",cb->params[BIAS]);
   XDrawString( LUI_Display, win, LUI_GC_white, 15, 90, str, strlen(str) );
*/

   LUI_DrawFrame( win, 1, 1, cb->width-2, cb->height-2, cb->framewidth-1, 1 );
   XDrawRectangle( LUI_Display, win, LUI_GC_black,
                   0, 0, cb->width-1, cb->height-1 );
}
Exemple #15
0
/* To call from C, use the routine below - without the extra underscore */
void draw_wave(double * results) {

/* Note extra underscore in draw_wave routine - needed for Fortran */

float 	scale, point, coloratio = 65535.0 / 255.0;
int 	i,j,k,y, zeroaxis, done, myscreen, points[WIDTH];

MYWINDOW base, quit;
Font 	font,font2;   
GC 		itemgc,textgc,pointgc,linegc; 
XColor 	red,yellow,blue,green,black,white;
XEvent 	myevent;
Colormap cmap;
KeySym 	mykey;
Display *mydisp;


/* Set rgb values for colors */
red.red= (int) (255 * coloratio);
red.green= (int) (0 * coloratio);
red.blue = (int) (0 * coloratio);

yellow.red= (int) (255 * coloratio);
yellow.green= (int) (255 * coloratio);
yellow.blue= (int) (0 * coloratio);

blue.red= (int) (0 * coloratio);
blue.green= (int) (0 * coloratio);
blue.blue= (int) (255 * coloratio);

green.red= (int) (0 * coloratio);
green.green= (int) (255 * coloratio);
green.blue= (int) (0 * coloratio);

black.red= (int) (0 * coloratio);
black.green= (int) (0 * coloratio);
black.blue= (int) (0 * coloratio);

white.red= (int) (255 * coloratio);
white.green= (int) (255 * coloratio);
white.blue= (int) (255 * coloratio);

mydisp = XOpenDisplay("");
if (!mydisp) {
   fprintf (stderr, "Hey! Either you don't have X or something's not right.\n");
   fprintf (stderr, "Guess I won't be showing the graph.  No big deal.\n");
   exit(1);
   }
myscreen = DefaultScreen(mydisp);
cmap = DefaultColormap (mydisp, myscreen);
XAllocColor (mydisp, cmap, &red); 
XAllocColor (mydisp, cmap, &yellow);
XAllocColor (mydisp, cmap, &blue);
XAllocColor (mydisp, cmap, &black); 
XAllocColor (mydisp, cmap, &green); 
XAllocColor (mydisp, cmap, &white); 

/* Set up for creating the windows */
/* XCreateSimpleWindow uses defaults for many attributes,   */
/* thereby simplifying the programmer's work in many cases. */

/* base window position and size */
base.hints.x = 50;
base.hints.y = 50;
base.hints.width = WIDTH;
base.hints.height = HEIGHT;
base.hints.flags = PPosition | PSize;
base.bordwidth = 5;

/* window Creation */
/* base window */
base.window = XCreateSimpleWindow (mydisp, DefaultRootWindow (mydisp), 
              base.hints.x, base.hints.y, base.hints.width, 
              base.hints.height, base.bordwidth, black.pixel,
              black.pixel);
XSetStandardProperties (mydisp, base.window, baseword, baseword, None,
                        NULL, 0, &base.hints);

/* quit window position and size (subwindow of base) */
quit.hints.x = 5;
quit.hints.y = 450;
quit.hints.width = 70;
quit.hints.height = 30;
quit.hints.flags = PPosition | PSize;
quit.bordwidth = 5;

quit.window = XCreateSimpleWindow (mydisp, base.window, quit.hints.x, 
              quit.hints.y, quit.hints.width, quit.hints.height,
              quit.bordwidth, green.pixel, yellow.pixel);
XSetStandardProperties (mydisp, quit.window, exitword, exitword, None,
             NULL, 0, &quit.hints);

/* Load fonts */
/*
font = XLoadFont (mydisp, "Rom28");
font2 = XLoadFont (mydisp, "Rom17.500");
*/
font = XLoadFont (mydisp, "fixed");
font2 = XLoadFont (mydisp, "fixed");

/* GC creation and initialization */
textgc = XCreateGC (mydisp, base.window, 0,0);
XSetFont (mydisp, textgc, font);
XSetForeground (mydisp, textgc, white.pixel);

linegc = XCreateGC (mydisp, base.window, 0,0);
XSetForeground (mydisp, linegc, white.pixel);

itemgc = XCreateGC (mydisp, quit.window, 0,0);
XSetFont (mydisp, itemgc, font2);
XSetForeground (mydisp, itemgc, black.pixel);

pointgc = XCreateGC (mydisp, base.window, 0,0);
XSetForeground (mydisp, pointgc, green.pixel);

/* The program is event driven; the XSelectInput call sets which */
/* kinds of interrupts are desired for each window.              */
/* These aren't all used. */
XSelectInput (mydisp, base.window,
              ButtonPressMask | KeyPressMask | ExposureMask);
XSelectInput (mydisp, quit.window,
              ButtonPressMask | KeyPressMask | ExposureMask);

/* window mapping -- this lets windows be displayed */
XMapRaised (mydisp, base.window);
XMapSubwindows (mydisp, base.window);

/* Scale each data point  */
zeroaxis = HEIGHT/2;
scale = (float)zeroaxis;
for(j=0;j<WIDTH;j++) 
   points[j]  = zeroaxis - (int)(results[j] * scale);

/* Main event loop  --  exits when user clicks on "exit" */
done = 0;
while (! done) {
   XNextEvent (mydisp, &myevent);   /* Read next event */
   switch (myevent.type) {
   case Expose:
      if (myevent.xexpose.count == 0) {
         if (myevent.xexpose.window == base.window) {
            XDrawString (mydisp, base.window, textgc, 775, 30, "Wave",4);
            XDrawLine (mydisp, base.window, linegc, 1,zeroaxis,WIDTH,
                       zeroaxis);
            for (j=1; j<WIDTH; j++) 
               XDrawPoint (mydisp, base.window, pointgc, j, points[j-1]);
            }

         else if (myevent.xexpose.window == quit.window) {
            XDrawString (mydisp, quit.window, itemgc, 12,20, exitword, 
                         strlen(exitword));
            }
      }   /* case Expose */
      break;

   case ButtonPress:
      if (myevent.xbutton.window == quit.window)
         done = 1;
      break;

   case KeyPress:
/*
      i = XLookupString (&myevent, text, 10, &mykey, 0);
      if (i == 1 && text[0] == 'q')
         done = 1;
*/
      break;

   case MappingNotify:
/*
      XRefreshKeyboardMapping (&myevent);
*/
      break;

      }  /* switch (myevent.type) */

   }   /* while (! done) */

XDestroyWindow (mydisp, base.window);
XCloseDisplay (mydisp);
}
Exemple #16
0
/*
 * Draw a line in the view subwindow. Don't show it right away if possible.
 */
void
DrawViewLine(int x1, int y1, int x2, int y2)
{
	XDrawLine(dpy, mwWindow, copyGC, x1+VIEW_X_ORIGIN, y1+VIEW_Y_ORIGIN,
		  x2+VIEW_X_ORIGIN, y2+VIEW_Y_ORIGIN);
}
Exemple #17
0
int UISymbolEdit (DBObjTable *symbols,int symbolType)

	{
	int symNum;
	static int changed, save;
	static Widget dShell = NULL;
	XmString string;
	UISymbol **editSymbols;
	DBObjRecord *symRecord;

	if (dShell == NULL)
		{
		char symString [20];
		int depth;
		Pixel foreground, background;
		XGCValues xgcv;
		GC gc;
		Widget mainForm, scrolledW, list, label, button, text, foreMenu, backMenu, rowCol, symMenu;
		Pixmap markerPixmap, labelPixmap;

		dShell = UIDialogForm ((char *) "Symbol Edit");
		mainForm = UIDialogFormGetMainForm (dShell);
		scrolledW = XtVaCreateManagedWidget ("UISymScrolledWindow",xmScrolledWindowWidgetClass,mainForm,
													XmNtopAttachment,		XmATTACH_FORM,
													XmNleftAttachment,	XmATTACH_FORM,
													XmNrightAttachment,	XmATTACH_FORM,
													NULL);
		list = XtVaCreateManagedWidget (UISymListName + 1,xmListWidgetClass,scrolledW,
													XmNvisibleItemCount,	6,
													XmNselectionPolicy,	XmBROWSE_SELECT,
													XmNscrollBarDisplayPolicy,	XmSTATIC,
													NULL);
		XtAddCallback (list,XmNbrowseSelectionCallback,(XtCallbackProc) _UISymbolListSelectCBK,dShell);
		string = XmStringCreate ((char *) "Symbol",UICharSetNormal);
		label = XtVaCreateManagedWidget ("UISymbolLabel",xmLabelWidgetClass,mainForm,
													XmNtopAttachment,		XmATTACH_WIDGET,
													XmNtopWidget,			scrolledW,
													XmNleftAttachment,	XmATTACH_FORM,
													XmNlabelString,		string,
													NULL);
		XmStringFree (string);
		string = XmStringCreate ((char *) "Load Names",UICharSetNormal);
		button = XtVaCreateManagedWidget (UISymLoadNamesButtonName + 1,xmPushButtonWidgetClass,mainForm,
													XmNtopAttachment,		XmATTACH_WIDGET,
													XmNtopWidget,			label,
													XmNrightAttachment,	XmATTACH_FORM,
													XmNlabelString,		string,
													NULL);
		XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _UISymbolLoadNamesCBK,list);
		XmStringFree (string);
		text = XtVaCreateManagedWidget (UISymTextFieldName + 1,xmTextFieldWidgetClass,mainForm,
													XmNtopAttachment,		XmATTACH_WIDGET,
													XmNtopWidget,			label,
													XmNleftAttachment,	XmATTACH_FORM,
													XmNrightAttachment,	XmATTACH_WIDGET,
													XmNrightWidget,		button,
													XmNrightOffset,		5,
													NULL);
		XtAddCallback (text,XmNvalueChangedCallback,(XtCallbackProc) _UISymbolTextValueChangedCBK,list);
		XtAddCallback (text,XmNvalueChangedCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&changed);

		foreMenu = XmCreatePulldownMenu (mainForm,(char *) "UISymForegroundMenuPane",NULL,0);
		backMenu = XmCreatePulldownMenu (mainForm,(char *) "UISymBackgroundMenuPane",NULL,0);

		for (symNum = 0;symNum <  UIColorNum (UIColorStandard);symNum++)
			{
			foreground = UIColor (UIColorStandard,symNum);
			_UISymSetButtonString (symString,symNum);
			string = XmStringCreate (UIStandardColorName(symNum),UICharSetNormal);
			button =  XtVaCreateManagedWidget (symString + 1,xmPushButtonWidgetClass,foreMenu,
													XmNuserData,			symNum,
													XmNforeground,			foreground,
													XmNlabelString,		string,
													NULL);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _UISymbolSetForegroundCBK,text);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&changed);
			button =  XtVaCreateManagedWidget (symString + 1,xmPushButtonWidgetClass,backMenu,
													XmNuserData,			symNum,
													XmNforeground,			foreground,
													XmNlabelString,		string,
													NULL);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _UISymbolSetBackgroundCBK,text);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&changed);
			XmStringFree (string);
			}

		string = XmStringCreate ((char *) "Foreground:",UICharSetNormal);
		foreMenu = XtVaCreateManagedWidget (UISymForegroundMenuName + 1,xmRowColumnWidgetClass,mainForm,
													XmNtopAttachment,			XmATTACH_WIDGET,
													XmNtopWidget,				text,
													XmNrightAttachment,		XmATTACH_FORM,
													XmNsubMenuId,				foreMenu,
													XmNlabelString,			string,
													XmNrowColumnType,			XmMENU_OPTION,
													XmNtraversalOn,			false,
													NULL);
		XmStringFree (string);
		string = XmStringCreate ((char *) "Background:",UICharSetNormal);
		backMenu = XtVaCreateManagedWidget (UISymBackgroundMenuName + 1,xmRowColumnWidgetClass,mainForm,
													XmNtopAttachment,			XmATTACH_WIDGET,
													XmNtopWidget,				foreMenu,
													XmNrightAttachment,		XmATTACH_FORM,
													XmNsubMenuId,				backMenu,
													XmNlabelString,			string,
													XmNrowColumnType,			XmMENU_OPTION,
													XmNtraversalOn,			false,
													NULL);
		rowCol = XtVaCreateManagedWidget ("UISymbolRowCol",xmRowColumnWidgetClass,mainForm,
													XmNtopAttachment,			XmATTACH_WIDGET,
													XmNtopWidget,				backMenu,
													XmNrightAttachment,		XmATTACH_FORM,
													XmNbottomAttachment,		XmATTACH_FORM,
													NULL);
		XtVaGetValues (mainForm,XmNforeground,	&foreground,XmNbackground,	&background,NULL);
		xgcv.foreground = foreground;
		xgcv.background = background;
		xgcv.fill_style = FillTiled;
		gc = XCreateGC (XtDisplay (UITopLevel ()),XtWindow (UITopLevel ()),GCForeground | GCBackground | GCFillStyle,&xgcv);

		symMenu = XmCreatePulldownMenu (rowCol,(char *) "UISymShadeMenuPane",NULL,0);
		depth = DefaultDepth (XtDisplay (UITopLevel ()),DefaultScreen (XtDisplay (UITopLevel ())));
		for (symNum = 0;(xgcv.tile = UIPattern (symNum,foreground,background)) != (Pixmap) NULL;symNum++)
			{
			labelPixmap = XCreatePixmap (XtDisplay (UITopLevel ()),XtWindow (UITopLevel ()),96,24,depth);
			XChangeGC (XtDisplay (UITopLevel ()),gc,GCTile,&xgcv);
			XFillRectangle (XtDisplay (UITopLevel ()),labelPixmap,gc,0,0,96,24);
			XFreePixmap (XtDisplay (UITopLevel ()),xgcv.tile);

			_UISymSetButtonString(symString,symNum);
			button = XtVaCreateManagedWidget (symString + 1,xmPushButtonGadgetClass,symMenu,
													XmNuserData,				symNum,
													XmNlabelType,				XmPIXMAP,
													XmNlabelPixmap,			labelPixmap,
													NULL);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _UISymbolSetStyleCBK,text);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&changed);
			}
		string = XmStringCreate ((char *) "Shade:",UICharSetNormal);
		symMenu = XtVaCreateWidget (UISymShadeMenuName + 1,xmRowColumnWidgetClass,rowCol,
													XmNsubMenuId,				symMenu,
													XmNlabelString,			string,
													XmNrowColumnType,			XmMENU_OPTION,
													XmNtraversalOn,			false,
													NULL);
		XmStringFree (string);

		xgcv.foreground = background;
		xgcv.fill_style = FillSolid;
		XChangeGC (XtDisplay (UITopLevel ()),gc,GCForeground | GCFillStyle,&xgcv);
		symMenu = XmCreatePulldownMenu (rowCol,(char *) "UISymMarkerMenuPane",NULL,0);
		depth = DefaultDepth (XtDisplay (UITopLevel ()),DefaultScreen (XtDisplay (UITopLevel ())));
		for (symNum = 0;(markerPixmap = UIMarker (symNum,foreground,background)) != (Pixmap) NULL;symNum++)
			{
			labelPixmap = XCreatePixmap (XtDisplay (UITopLevel ()),XtWindow (UITopLevel ()),96,24,depth);
			XFillRectangle (XtDisplay (UITopLevel ()),labelPixmap,gc,0,0,96,24);
			XCopyArea (XtDisplay (UITopLevel ()),markerPixmap,labelPixmap,gc,0,0,11,11,42,6);
			XFreePixmap (XtDisplay (UITopLevel ()),markerPixmap);
			_UISymSetButtonString(symString,symNum);
			button = XtVaCreateManagedWidget (symString + 1,xmPushButtonGadgetClass,symMenu,
													XmNuserData,				symNum,
													XmNlabelType,				XmPIXMAP,
													XmNlabelPixmap,			labelPixmap,
													NULL);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _UISymbolSetStyleCBK,text);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&changed);
			}
		string = XmStringCreate ((char *) "Marker:",UICharSetNormal);
		symMenu = XtVaCreateWidget (UISymMarkerMenuName + 1,xmRowColumnWidgetClass,rowCol,
													XmNsubMenuId,				symMenu,
													XmNlabelString,			string,
													XmNrowColumnType,			XmMENU_OPTION,
													XmNtraversalOn,			false,
													NULL);
		XmStringFree (string);

		symMenu = XmCreatePulldownMenu (rowCol,(char *) "UISymLineMenuPane",NULL,0);
		depth = DefaultDepth (XtDisplay (UITopLevel ()),DefaultScreen (XtDisplay (UITopLevel ())));
		for (symNum = 0;symNum < 12;symNum++)
			{
			labelPixmap = XCreatePixmap (XtDisplay (UITopLevel ()),XtWindow (UITopLevel ()),96,24,depth);
			xgcv.foreground = background;
			xgcv.fill_style = FillSolid;
			XChangeGC (XtDisplay (UITopLevel ()),gc,GCForeground | GCFillStyle,&xgcv);
			XFillRectangle (XtDisplay (UITopLevel ()),labelPixmap,gc,0,0,96,24);
			xgcv.line_width = symNum & 0x03;
			switch (symNum >> 0x02)
				{
				case 0:	xgcv.line_style = LineSolid;		break;
				case 1:	xgcv.line_style = LineOnOffDash;	break;
				case 2:	xgcv.line_style = LineDoubleDash;	break;
				}
			xgcv.foreground = foreground;
			xgcv.background = UIColor (UIColorStandard,0);
			XChangeGC (XtDisplay (UITopLevel ()),gc,GCForeground | GCBackground | GCLineWidth | GCLineStyle,&xgcv);
			XDrawLine (XtDisplay (UITopLevel ()),labelPixmap,gc,0,12,96,12);
			_UISymSetButtonString(symString,symNum);
			button = XtVaCreateManagedWidget (symString + 1,xmPushButtonGadgetClass,symMenu,
													XmNuserData,				symNum,
													XmNlabelType,				XmPIXMAP,
													XmNlabelPixmap,			labelPixmap,
													NULL);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _UISymbolSetStyleCBK,text);
			XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&changed);
			}
		string = XmStringCreate ((char *) "Line:",UICharSetNormal);
		symMenu = XtVaCreateWidget (UISymLineMenuName + 1,xmRowColumnWidgetClass,rowCol,
													XmNsubMenuId,				symMenu,
													XmNlabelString,			string,
													XmNrowColumnType,			XmMENU_OPTION,
													XmNtraversalOn,			false,
													NULL);
		XmStringFree (string);
		XtAddCallback (UIDialogFormGetOkButton (dShell),XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&save);
		}
Exemple #18
0
static gmx_bool LogoCallBack(t_x11 *x11, XEvent *event, Window w, void *data)
{
    /* Assume window is 100x110 */
    static gmx_bool bFirst = TRUE;
#define CSIZE 9
#define NSIZE 8
#define OSIZE 9
#define HSIZE 7
#define YOFFS 30
    static t_circle c[] = {
        { 10, YOFFS+12, CSIZE, &LIGHTGREEN },
        { 20, YOFFS+22, CSIZE, &LIGHTGREEN },
        { 20, YOFFS+34, OSIZE, &LIGHTRED   },
        { 30, YOFFS+12, NSIZE, &LIGHTCYAN  },
        { 30, YOFFS+ 2, HSIZE, &WHITE     },
        { 40, YOFFS+22, CSIZE, &LIGHTGREEN },
        { 40, YOFFS+34, CSIZE, &LIGHTGREEN },
        { 50, YOFFS+12, CSIZE, &LIGHTGREEN },
        { 50, YOFFS, OSIZE, &LIGHTRED   },
        { 60, YOFFS+22, NSIZE, &LIGHTCYAN  },
        { 60, YOFFS+32, HSIZE, &WHITE     },
        { 70, YOFFS+12, CSIZE, &LIGHTGREEN },
        { 80, YOFFS+22, CSIZE, &LIGHTGREEN },
        { 80, YOFFS+34, OSIZE, &LIGHTRED   },
        { 90, YOFFS+12, NSIZE, &LIGHTCYAN  },
        { 90, YOFFS+ 2, HSIZE, &WHITE      },
        {100, YOFFS+22, CSIZE, &LIGHTGREEN }
    };
    static int      lines[] = {
        0, 1, 1, 2, 1, 3, 3, 4, 3, 5, 5, 6, 5, 7, 7, 8, 7, 9,
        9, 10, 9, 11, 11, 12, 12, 13, 12, 14, 14, 15, 14, 16
    };
#define COFFS 70
    static t_mess   Mess[] = {
        { "GROMACS",                         0,       20, NULL },
        { NULL,                             16,        9, NULL },
        { "Copyright (c) 1991-2010",        COFFS+ 2,  9, NULL },
        { "D.v.d.Spoel, E.Lindahl, B.Hess", COFFS+11,  9, NULL },
        { "& Groningen University ",        COFFS+20,  9, NULL },
        { "click to dismiss",               COFFS+31,  8, NULL }
    };
#define NMESS asize(Mess)
    int             i;
    real            wfac, hfac;
    t_logo         *logo;
    t_windata      *wd;

    logo = (t_logo *)data;
    wd   = &(logo->wd);
    if (bFirst)
    {
        wfac = wd->width/110.0;
        hfac = wd->height/110.0;
        for (i = 0; (i < asize(c)); i++)
        {
            c[i].x *= wfac;
            c[i].y *= hfac;
        }
        Mess[1].text = GromacsVersion();
        for (i = 0; (i < NMESS); i++)
        {
            Mess[i].y  *= hfac;
            Mess[i].h  *= hfac;
            Mess[i].fnt = (i == 0) ? logo->bigfont : (i == NMESS-1) ? x11->font :
                          logo->smallfont;
        }
        bFirst = FALSE;
    }
    switch (event->type)
    {
    case Expose:
        XSetForeground(x11->disp, x11->gc, WHITE);
        XSetLineAttributes(x11->disp, x11->gc, 3, LineSolid, CapNotLast, JoinRound);
        for (i = 0; (i < asize(lines)); i += 2)
        {
            XDrawLine(x11->disp, wd->self, x11->gc,
                      c[lines[i]].x, c[lines[i]].y, c[lines[i+1]].x, c[lines[i+1]].y);
        }
        XSetLineAttributes(x11->disp, x11->gc, 1, LineSolid, CapNotLast, JoinRound);
        for (i = 0; (i < asize(c)); i++)
        {
            XSetForeground(x11->disp, x11->gc, *(c[i].col));
            XFillCircle(x11->disp, wd->self, x11->gc, c[i].x, c[i].y, c[i].rad);
        }
        XSetForeground(x11->disp, x11->gc, BLACK);
        XDrawRectangle(x11->disp, wd->self, x11->gc, 2, 2, wd->width-5, wd->height-5);
        for (i = 0; (i < asize(Mess)); i++)
        {
            SpecialTextInRect(x11, Mess[i].fnt, wd->self, Mess[i].text,
                              0, Mess[i].y, wd->width, Mess[i].h,
                              eXCenter, eYCenter);
        }
        XSetForeground(x11->disp, x11->gc, x11->fg);
        break;
    case ButtonPress:
        hide_logo(x11, logo);
        return logo->bQuitOnClick;
        break;
    default:
        break;
    }

    return FALSE;
}
Exemple #19
0
static Bool
self_similar_normalized (struct state *st,
			 int       iterations,
			 double    x1,
			 double    y1,
			 double    x2,
			 double    y2,
			 double    maximum_x,
			 double    maximum_y,
			 double    minimum_x,
			 double    minimum_y,
			 int       segment_count,
			 Position* points)
{
    if (iterations == 0)
    {
	double delta_x = maximum_x - minimum_x;
	double delta_y = maximum_y - minimum_y;
	st->color_index = (int)(((double)(st->line_count * st->color_count))
			    / ((double)st->total_lines));
	++st->line_count;
	XSetForeground (st->dpy, st->context, st->colors [st->color_index].pixel);
	if (st->plot_maximum_x < x1) st->plot_maximum_x = x1;
	if (st->plot_maximum_x < x2) st->plot_maximum_x = x2;
	if (st->plot_maximum_y < y1) st->plot_maximum_y = y1;
	if (st->plot_maximum_y < y2) st->plot_maximum_y = y2;
	if (st->plot_minimum_x > x1) st->plot_minimum_x = x1;
	if (st->plot_minimum_x > x2) st->plot_minimum_x = x2;
	if (st->plot_minimum_y > y1) st->plot_minimum_y = y1;
	if (st->plot_minimum_y > y2) st->plot_minimum_y = y2;
	XDrawLine (st->dpy, st->pixmap, st->context,
		   (int)(((x1 - minimum_x) / delta_x) * st->width),
		   (int)(((maximum_y - y1) / delta_y) * st->height),
		   (int)(((x2 - minimum_x) / delta_x) * st->width),
		   (int)(((maximum_y - y2) / delta_y) * st->height));
    }
    else
    {
	int       index = 0;
	double    next_x = 0.0;
	double    next_y = 0.0;
	Position* replacement = (Position*)NULL;
	double    x = 0.0;
	double    y = 0.0;

	replacement = (Position*)(malloc (segment_count * sizeof (Segment)));
	copy_points (segment_count, points, replacement);
	assert (fabs ((replacement [segment_count - 1].x) - 1.0) < EPSILON);
	assert (fabs (replacement [segment_count - 1].y) < EPSILON);
	realign (x1, y1, x2, y2, segment_count, replacement);
        /* jwz: I don't understand what these assertions are supposed to
           be detecting, but let's just bail on the fractal instead of
           crashing. */
/*	assert (fabs (x2 - (replacement [segment_count - 1].x)) < EPSILON);
	assert (fabs (y2 - (replacement [segment_count - 1].y)) < EPSILON);*/
        if (fabs (x2 - (replacement [segment_count - 1].x)) >= EPSILON ||
            fabs (y2 - (replacement [segment_count - 1].y)) >= EPSILON) {
          free (replacement);
          return False;
        }
	x = x1;
	y = y1;
	for (index = 0; index < segment_count; ++index)
	{
	    next_x = replacement [index].x;
	    next_y = replacement [index].y;
	    if (!self_similar_normalized (st, 
				     iterations - 1, x, y, next_x, next_y,
				     maximum_x, maximum_y,
				     minimum_x, minimum_y,
				     segment_count, points)) {
              free(replacement);
              return False;
            }
	    x = next_x;
	    y = next_y;
	}
        free(replacement);
    }
    return True;
}
Exemple #20
0
int set_full_screen(Display *dpy) {
    signal(SIGUSR1, fake_right_button);
    fulldisplay = dpy;
    Window curwin, rootw;
    Cursor hand_cursor;
    int x1, y1, winx, winy;
    unsigned int mask;
    XEvent ev;
    int screen_num;

    if (!dpy) {
        fprintf(stderr, "WTPEN : cannot get default display\n");
        exit(1);
    }

    /* style for line */
    unsigned int line_width = 8;
    int line_style = LineSolid;
    int cap_style  = CapRound;
    int join_style = JoinRound;

    screen_num = DefaultScreen(dpy);
    rootw = DefaultRootWindow(dpy);

    if (rootw == None) {
        fprintf(stderr, "WTPEN : full screen mode cannot get root window\n");
        exit(1);
    }

    hand_cursor = XCreateFontCursor(dpy, XC_hand2);

    drawgc = XCreateGC(dpy, rootw, 0, NULL);			// hier wordt getekend (met xor)
    XSetSubwindowMode(dpy, drawgc, IncludeInferiors);
    XSetForeground(dpy, drawgc,
                   WhitePixel(dpy, screen_num)
                   ^ BlackPixel(dpy, screen_num));
    XSetLineAttributes(dpy, drawgc, line_width, line_style,
                       cap_style, join_style);
    XSetFunction(dpy, drawgc, GXandInverted);
    //XSetFunction(dpy, drawgc, GXxor);

    fprintf(stderr, "full screen mode grab button\n");
    XGrabButton(dpy, AnyButton, 0, rootw, False,
                ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | OwnerGrabButtonMask,
                GrabModeSync, GrabModeAsync, None, hand_cursor);

	while (1) {
		fprintf (stderr, "fullscreen\n");	// wordt bij tekenen aangeroepen
        XAllowEvents(dpy, SyncPointer, CurrentTime);
        XWindowEvent(dpy, rootw, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask, &ev);

        switch(ev.type) {
        case ButtonPress:
            kill(getppid(), SIGUSR2);
            if(ev.xbutton.button != Button1) {
                int num;
                XUngrabButton(dpy, AnyButton, 0, rootw);
                XFlush(dpy);
                record_coordinate(0xff, 0xff);
                clear_draw_area(dpy, rootw, drawgc);
                num = get_coordinates_num();
                return num;
            }
            XQueryPointer(dpy, rootw,
                          &rootw, &curwin,
                          &x1, &y1,	//root x, root y
                          &winx, &winy,
                          &mask);
            record_coordinate(x1, y1);
            break;
        case ButtonRelease:
            if (ev.xbutton.button == Button1) {
                if (get_coordinates_num() == 2) {
                    free_coordinates();
                    XUngrabButton(dpy, AnyButton, 0, rootw);
                    forward_click_event(dpy, &ev);
                    XFlush(dpy);
                    return 0;
                }
                record_coordinate(0xff, 0x00);
                kill(getppid(), SIGALRM);
            }
            break;
        case MotionNotify:
            if (ev.xmotion.state & Button1MotionMask) {
                CoordinateList *cl_end;
                XQueryPointer(dpy, rootw,
                              &rootw, &curwin,
                              &x1, &y1,	//root x, root y
                              &winx, &winy,
                              &mask);
                cl_end = coordinate_list_end();
                if (cl_end) {
                    if (!(cl_end->x == 0xff && cl_end->y == 0x00)) {
                        XDrawLine(dpy, rootw,
                                  drawgc,
                                  x1,
                                  y1,
                                  cl_end->x,
                                  cl_end->y);
                        record_coordinate(x1, y1);
                    }
                } else {
                    record_coordinate(x1, y1);
                }
            }
            break;
        default:
            break;
        }
    }
    fprintf(stderr, "exit fullscreen\n");		// wordt nooit bereikt
    return 1;
}
Exemple #21
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);

}
Exemple #22
0
ENTRYPOINT void
draw_rotor (ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	GC          gc = MI_GC(mi);
	register elem *pelem;
	int         thisx, thisy;
	int         i;
	int         x_1, y_1, x_2, y_2;
	rotorstruct *rp;

	if (rotors == NULL)
		return;
	rp = &rotors[MI_SCREEN(mi)];
	if (rp->elements == NULL)
		return;

	MI_IS_DRAWN(mi) = True;
	if (!rp->iconifiedscreen) {
		thisx = rp->centerx;
		thisy = rp->centery;
	} else {
		thisx = rp->prevcenterx;
		thisy = rp->prevcentery;
	}
	XSetLineAttributes(MI_DISPLAY(mi), MI_GC(mi), rp->linewidth,
			   LineSolid, CapButt, JoinMiter);
	for (i = rp->num, pelem = rp->elements; --i >= 0; pelem++) {
		if (pelem->radius_drift_max <= pelem->radius_drift_now) {
			pelem->start_radius = pelem->end_radius;
			pelem->end_radius = (float) NRAND(40000) / 100.0 - 200.0;
			pelem->radius_drift_max = (float) NRAND(100000) + 10000.0;
			pelem->radius_drift_now = 0.0;
		}
		if (pelem->ratio_drift_max <= pelem->ratio_drift_now) {
			pelem->start_ratio = pelem->end_ratio;
			pelem->end_ratio = (float) NRAND(2000) / 100.0 - 10.0;
			pelem->ratio_drift_max = (float) NRAND(100000) + 10000.0;
			pelem->ratio_drift_now = 0.0;
		}
		pelem->ratio = pelem->start_ratio +
			(pelem->end_ratio - pelem->start_ratio) /
			pelem->ratio_drift_max * pelem->ratio_drift_now;
		pelem->angle = rp->angle * pelem->ratio;
		pelem->radius = pelem->start_radius +
			(pelem->end_radius - pelem->start_radius) /
			pelem->radius_drift_max * pelem->radius_drift_now;

		thisx += (int) (COSF(pelem->angle) * pelem->radius);
		thisy += (int) (SINF(pelem->angle) * pelem->radius);

		pelem->ratio_drift_now += 1.0;
		pelem->radius_drift_now += 1.0;
	}
	if (rp->firsttime)
		rp->firsttime = False;
	else {
		XSetForeground(display, gc, MI_BLACK_PIXEL(mi));

		x_1 = (int) rp->save[rp->rotor].x;
		y_1 = (int) rp->save[rp->rotor].y;
		x_2 = (int) rp->save[rp->prev].x;
		y_2 = (int) rp->save[rp->prev].y;

		if (rp->iconifiedscreen) {
			x_1 = x_1 * rp->centerx / rp->prevcenterx;
			x_2 = x_2 * rp->centerx / rp->prevcenterx;
			y_1 = y_1 * rp->centery / rp->prevcentery;
			y_2 = y_2 * rp->centery / rp->prevcentery;
		}
		XDrawLine(display, MI_WINDOW(mi), gc, x_1, y_1, x_2, y_2);

		if (MI_NPIXELS(mi) > 2) {
			XSetForeground(display, gc, MI_PIXEL(mi, rp->pix));
			if (++rp->pix >= MI_NPIXELS(mi))
				rp->pix = 0;
		} else
			XSetForeground(display, gc, MI_WHITE_PIXEL(mi));

		x_1 = rp->lastx;
		y_1 = rp->lasty;
		x_2 = thisx;
		y_2 = thisy;

		if (rp->iconifiedscreen) {
			x_1 = x_1 * rp->centerx / rp->prevcenterx;
			x_2 = x_2 * rp->centerx / rp->prevcenterx;
			y_1 = y_1 * rp->centery / rp->prevcentery;
			y_2 = y_2 * rp->centery / rp->prevcentery;
		}
		XDrawLine(display, MI_WINDOW(mi), gc, x_1, y_1, x_2, y_2);
	}
	rp->save[rp->rotor].x = rp->lastx = thisx;
	rp->save[rp->rotor].y = rp->lasty = thisy;

	++rp->rotor;
	rp->rotor %= rp->nsave;
	++rp->prev;
	rp->prev %= rp->nsave;
	if (rp->forward) {
		rp->angle += 0.01;
		if (rp->angle >= MAXANGLE) {
			rp->angle = MAXANGLE;
			rp->forward = False;
		}
	} else {
		rp->angle -= 0.1;
		if (rp->angle <= 0) {
			rp->angle = 0.0;
			rp->forward = True;
		}
	}
	if (rp->redrawing) {
		int         j;

		for (i = 0; i < REDRAWSTEP; i++) {
			j = (rp->rotor - rp->redrawpos + rp->nsave) % rp->nsave;

			x_1 = (int) rp->save[j].x;
			y_1 = (int) rp->save[j].y;
			x_2 = (int) rp->save[(j - 1 + rp->nsave) % rp->nsave].x;
			y_2 = (int) rp->save[(j - 1 + rp->nsave) % rp->nsave].y;

			if (rp->iconifiedscreen) {
				x_1 = x_1 * rp->centerx / rp->prevcenterx;
				x_2 = x_2 * rp->centerx / rp->prevcenterx;
				y_1 = y_1 * rp->centery / rp->prevcentery;
				y_2 = y_2 * rp->centery / rp->prevcentery;
			}
			XDrawLine(display, MI_WINDOW(mi), gc, x_1, y_1, x_2, y_2);

			if (++(rp->redrawpos) >= rp->nsave) {
				rp->redrawing = 0;
				break;
			}
		}
	}
	XSetLineAttributes(MI_DISPLAY(mi), MI_GC(mi), 1,
			   LineSolid, CapButt, JoinMiter);
}
Exemple #23
0
void write_other(int x,int y,int c)
{
   switch (c) {
      case 24:     /* up arrow */
         XDrawLine(dpy, pm, gctext, x+3,y+10,x+3,y+2);
         XDrawLine(dpy, pm, gctext, x+3,y+2,x+1,y+4);
         XDrawLine(dpy, pm, gctext, x+3,y+2,x+5,y+4);
         break;
      case 25:     /* down arrow */
         XDrawLine(dpy, pm, gctext, x+3,y+2,x+3,y+10);
         XDrawLine(dpy, pm, gctext, x+3,y+10,x+1,y+8);
         XDrawLine(dpy, pm, gctext, x+3,y+10,x+5,y+8);
         break;
      case 26:     /* right arrow */
         XDrawLine(dpy, pm, gctext, x+1,y+6,x+6,y+6);
         XDrawLine(dpy, pm, gctext, x+4,y+4,x+6,y+6);
         XDrawLine(dpy, pm, gctext, x+4,y+8,x+6,y+6);
         break;
      case 27:     /* left arrow */
         XDrawLine(dpy, pm, gctext, x+1,y+6,x+6,y+6);
         XDrawLine(dpy, pm, gctext, x+3,y+4,x+1,y+6);
         XDrawLine(dpy, pm, gctext, x+3,y+8,x+1,y+6);
         break;
      case 132:    /* ground; although the definition has been commented out in pfun1_21.pas, it is still used in pfmsc_21.pas (and displayed incorrectly under DOS, it seems) */
         y+=6; x+=3;
         XDrawLine(dpy, pm, gctext, x-3,y,x+3,y);
         y+=2; XDrawLine(dpy, pm, gctext, x-2,y,x+2,y);
         y+=2; XDrawLine(dpy, pm, gctext, x-1,y,x+1,y);
         break;
      case 179:    /* single vertical bar */
         XDrawLine(dpy, pm, gctext, x+3,y,x+3,y+13);
         break;
      case 184:    /* =, */
         XDrawLine(dpy, pm, gctext, x+3,y+5,x+3,y+13);
         XDrawLine(dpy, pm, gctext, x,y+7,x+3,y+7);
         XDrawLine(dpy, pm, gctext, x,y+5,x+3,y+5);
         break;
      case 186:    /* double vertical bar */
         XDrawLine(dpy, pm, gctext, x+2,y,x+2,y+13);
         XDrawLine(dpy, pm, gctext, x+4,y,x+4,y+13);
         break;
      case 187:    /* =,, */
         XDrawLine(dpy, pm, gctext, x+4,y+5,x+4,y+13);
         XDrawLine(dpy, pm, gctext, x+2,y+7,x+2,y+13);
         XDrawLine(dpy, pm, gctext, x,y+7,x+2,y+7);
         XDrawLine(dpy, pm, gctext, x,y+5,x+4,y+5);
         break;
      case 188:    /* ='' */
         XDrawLine(dpy, pm, gctext, x+2,y+5,x+2,y);
         XDrawLine(dpy, pm, gctext, x+4,y+7,x+4,y);
         XDrawLine(dpy, pm, gctext, x,y+7,x+4,y+7);
         XDrawLine(dpy, pm, gctext, x,y+5,x+2,y+5);
         break;
      case 190:    /* =' */
         XDrawLine(dpy, pm, gctext, x+3,y+7,x+3,y);
         XDrawLine(dpy, pm, gctext, x,y+7,x+3,y+7);
         XDrawLine(dpy, pm, gctext, x,y+5,x+3,y+5);
         break;
      case 200:    /* ``= */
         XDrawLine(dpy, pm, gctext, x+2,y+7,x+2,y);
         XDrawLine(dpy, pm, gctext, x+4,y+5,x+4,y);
         XDrawLine(dpy, pm, gctext, x+7,y+7,x+2,y+7);
         XDrawLine(dpy, pm, gctext, x+7,y+5,x+4,y+5);
         break;
      case 201:    /* ,,= */
         XDrawLine(dpy, pm, gctext, x+2,y+5,x+2,y+13);
         XDrawLine(dpy, pm, gctext, x+4,y+7,x+4,y+13);
         XDrawLine(dpy, pm, gctext, x+7,y+7,x+4,y+7);
         XDrawLine(dpy, pm, gctext, x+7,y+5,x+2,y+5);
         break;
      case 205:    /* double horizontal bar */
         XDrawLine(dpy, pm, gctext, x,y+5,x+7,y+5);
         XDrawLine(dpy, pm, gctext, x,y+7,x+7,y+7);
         break;
      case 212:    /* `= */
         XDrawLine(dpy, pm, gctext, x+3,y+7,x+3,y);
         XDrawLine(dpy, pm, gctext, x+7,y+7,x+3,y+7);
         XDrawLine(dpy, pm, gctext, x+7,y+5,x+3,y+5);
         break;
      case 213:    /* ,= */
         XDrawLine(dpy, pm, gctext, x+3,y+5,x+3,y+13);
         XDrawLine(dpy, pm, gctext, x+7,y+7,x+3,y+7);
         XDrawLine(dpy, pm, gctext, x+7,y+5,x+3,y+5);
         break;
      case 234:    /* Omega */
         x++; y+=10; XDrawPoint(dpy, pm, gctext, x,y);
         x++; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         x--; y--; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y--; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y--; XDrawPoint(dpy, pm, gctext, x,y);
         x++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y++; XDrawPoint(dpy, pm, gctext, x,y);
         y++; XDrawPoint(dpy, pm, gctext, x,y);
         y++; XDrawPoint(dpy, pm, gctext, x,y);
         x--; y++; XDrawPoint(dpy, pm, gctext, x,y);
         y++; XDrawPoint(dpy, pm, gctext, x,y);
         y++; XDrawPoint(dpy, pm, gctext, x,y);
         y++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; XDrawPoint(dpy, pm, gctext, x,y);
         break;
      case 235:    /* delta */
         y+=5; x+=3;
         XDrawPoint(dpy, pm, gctext, x,y);
         y++; XDrawPoint(dpy, pm, gctext, x+1,y); XDrawPoint(dpy, pm, gctext, x-1,y);
         y++; XDrawPoint(dpy, pm, gctext, x+2,y); XDrawPoint(dpy, pm, gctext, x-2,y);
         y++; XDrawPoint(dpy, pm, gctext, x+3,y); XDrawPoint(dpy, pm, gctext, x-3,y);
         y++; XDrawLine(dpy, pm, gctext, x-3,y,x+3,y);
         break;
      case 236:   /* infinity */
         y+=8; x+=3; 
         XDrawPoint(dpy, pm, gctext, x,y);
         x--; y++; XDrawPoint(dpy, pm, gctext, x,y);
         x--; XDrawPoint(dpy, pm, gctext, x,y);
         x--; y--; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y--; XDrawPoint(dpy, pm, gctext, x,y);
         x++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; XDrawPoint(dpy, pm, gctext, x,y);
         x++; y--; XDrawPoint(dpy, pm, gctext, x,y);
         y--; XDrawPoint(dpy, pm, gctext, x,y);
         x--; y--; XDrawPoint(dpy, pm, gctext, x,y);
         x--; XDrawPoint(dpy, pm, gctext, x,y);
         x--; y++; XDrawPoint(dpy, pm, gctext, x,y);
         break;
      default:
         fprintf(stderr,"NOT IMPLEMENTED: write_other(%i,%i,%i)\n",c,x,y);
   }
}
Exemple #24
0
/* puts up azimuth lines every 45 degrees */
void draw_az_lines(int screen)
{
int x_ctr_offset=0,  y_ctr_offset=0;  /*  CVG 8.3 */

int retval;

screen_data *azsd=NULL;
    
    
 
    if(screen == SCREEN_1) {
        azsd = sd1;
        
    } else if(screen == SCREEN_2) {
        azsd = sd2;
        
    } else if(screen == SCREEN_3) {
        azsd = sd3;
    }
    
    
if(azsd->icd_product != NULL) { 
    x_ctr_offset = - (int) (azsd->x_center_offset * azsd->scale_factor);
    y_ctr_offset = - (int) (azsd->y_center_offset * azsd->scale_factor); 
}     
    


/*  EXISTING BUG:  When the product is zoomed and offset so that the radar is     */
/*           offthe drawing area, the drawing of azimuth lines labels breaks down.*/
/*  CVG 8.5 WORKAROUND: Stop display if center_pixel AND center_scanl are negative*/
/*                      or exceed the dwawing area.                               */
    if( (x_ctr_offset < -pwidth)/2 || (x_ctr_offset > pwidth/2) || 
        (y_ctr_offset < -pheight/2) || (y_ctr_offset > pheight/2) )
        return; 

    /* CVG 9.0 */
    /*  setup azimuth line palette file here */
    /*  text_1.plt     */
    /* 0-black 1-white */

    retval = open_default_palette(AZIMUTH_LINE_RANGE_RING);
    
    if(retval==FALSE) {
        use_cvg_colors = TRUE;
        fprintf(stderr,"Using internal colors for azimuth line display");
    }

    if(use_cvg_colors == TRUE) 
         XSetForeground(display, gc, white_color);
    else
         XSetForeground(display, gc, display_colors[1].pixel);
    XSetLineAttributes (display, gc, 1, LineSolid, 
                                 CapButt, JoinMiter); 



/*  VERSION 2 AVOID GAB AND DESCRIPTION AREAS */
/*     XDrawLine(display, azsd->pixmap, gc, 0.09*pwidth,  */
/*                                       0.09*pheight, */
/*                                 pwidth-0.09*pwidth,  */
/*                               pheight-0.09*pheight);  */
/*     XDrawLine(display, azsd->pixmap, gc, 0.09*pwidth,  */
/*                               pheight-0.09*pheight,  */
/*                                 pwidth-0.09*pwidth,  */
/*                                       0.09*pheight);  */
/*  */

/*  VERSION 3 OFF CENTER DISPLAY */
    /* diagonal lines (could use a better fudge factor than 460) */
    XDrawLine(display, azsd->pixmap, gc, (pwidth + x_ctr_offset) + 460, 
                                      (pheight + y_ctr_offset) + 460,
                                       (0 + x_ctr_offset) - 460, 
                                      (0 + y_ctr_offset)  - 460); 
    XDrawLine(display, azsd->pixmap, gc, (pwidth + x_ctr_offset) + 460 , 
                                      (0 + y_ctr_offset) - 460, 
                                       (0 + x_ctr_offset) - 460, 
                                      (pheight + y_ctr_offset) + 460); 



    /* horizontal lines */
    XDrawLine(display, azsd->pixmap, gc, pwidth/2 + x_ctr_offset, 
                                              0, 
                                       pwidth/2 + x_ctr_offset, 
                                        pheight);
    XDrawLine(display, azsd->pixmap, gc, 0, 
                               pheight/2 + y_ctr_offset, 
                                  pwidth, 
                               pheight/2 + y_ctr_offset);
    
    /* we want white lines */
    XSetForeground(display, gc, white_color);
    XSetLineAttributes(display, gc, 1, LineSolid, CapButt, JoinMiter);
    
    
} /* end draw_az_lines */
Exemple #25
0
static unsigned long
cwaves_draw (Display *dpy, Window window, void *closure)
{
  state *st = (state *) closure;
  int i, x;

  for (i = 0; i < st->nwaves; i++)
    st->waves[i].offset += st->waves[i].delta;

  for (x = 0; x < st->xgwa.width; x += st->scale)
    {
      double v = 0;
      int j;
      for (i = 0; i < st->nwaves; i++)
        v += cos ((x * st->waves[i].scale) - st->waves[i].offset);
      v /= st->nwaves;

      j = st->ncolors * (v/2 + 0.5);
      if (j < 0 || j >= st->ncolors) abort();
      XSetForeground (st->dpy, st->gc, st->colors[j].pixel);
      XFillRectangle (st->dpy, st->window, st->gc, 
                      x, 0, st->scale, st->xgwa.height);
    }

  if (st->debug_p)
    {
      int wh = (st->xgwa.height / (st->nwaves + 1)) * 0.9;
      int i;
      XSetLineAttributes (st->dpy, st->gc, 2, LineSolid, CapRound, JoinRound);
      XSetForeground (st->dpy, st->gc, BlackPixelOfScreen (st->xgwa.screen));
      for (i = 0; i < st->nwaves; i++)
        {
          int y = st->xgwa.height * i / (st->nwaves + 1);
          int ox = -1, oy = -1;

          for (x = 0; x < st->xgwa.width; x += st->scale)
            {
              int yy;
              double v = 0;
              v = cos ((x * st->waves[i].scale) - st->waves[i].offset);
              v /= 2;

              yy = y + wh/2 + (wh * v);
              if (ox == -1)
                ox = x, oy = yy;
              XDrawLine (st->dpy, st->window, st->gc, ox, oy, x, yy);
              ox = x;
              oy = yy;
            }
        }

      {
        int y = st->xgwa.height * i / (st->nwaves + 1);
        int ox = -1, oy = -1;

        for (x = 0; x < st->xgwa.width; x += st->scale)
          {
            int yy;
            double v = 0;
            for (i = 0; i < st->nwaves; i++)
              v += cos ((x * st->waves[i].scale) - st->waves[i].offset);
            v /= st->nwaves;
            v /= 2;

            yy = y + wh/2 + (wh * v);
            if (ox == -1)
              ox = x, oy = yy;
            XDrawLine (st->dpy, st->window, st->gc, ox, oy, x, yy);
            ox = x;
            oy = yy;
          }
      }
    }

  return st->delay;
}
Exemple #26
0
void display_packet_7(int packet,int offset) 
{
    short length, i_start, i_end, j_start, j_end;
    int i,num_vectors,count=1;
    float   x_scale, y_scale;
    /* CVG 9.0 */
    int center_pixel, center_scanl;

    /* CVG 9.0 - added for GEOGRAPHIC_PRODUCT support */
    int  *type_ptr, msg_type;
    Prod_header *hdr;
    int *prod_res_ind;    
    float base_res, prod_res;




    /* CVG 9.0 - added for GEOGRAPHIC_PRODUCT support */
    /* get the type of product we have here */
    hdr = (Prod_header *)(sd->icd_product);
    type_ptr = assoc_access_i(msg_type_list, hdr->g.prod_id);
    if(type_ptr == NULL) {
        msg_type = NON_GEOGRAPHIC_PRODUCT; /* default */
    } else {
        msg_type = *type_ptr;
    }


    /* CVG 9.0 - added GEOGRAPHIC_PRODUCT support */
    if(msg_type == GEOGRAPHIC_PRODUCT) {
        /* configured resolution of this product */
        prod_res_ind = assoc_access_i(product_res, hdr->g.prod_id);
        prod_res = res_index_to_res(*prod_res_ind);
        /* CVG 9.0 - added for GEOGRAPHIC_PRODUCT support */
        /* resolution of the base image displayed */
        base_res = res_index_to_res(sd->resolution);   
        
        geo_scale_and_center(pwidth, pheight, sd->scale_factor, 
                         sd->x_center_offset, sd->y_center_offset, 
                         base_res, prod_res, &x_scale, &y_scale,
                                      &center_pixel, &center_scanl);
        
    } else { /* a NON_GEOGRAPHIC_PRODUCT */
       /* CVG 9.0 - calculates x_scale, y_scale, center_pixel, center_scanl */
       non_geo_scale_and_center((float)pwidth, (float)pheight, 
                          &x_scale, &y_scale, &center_pixel, &center_scanl);
                                                  
    }



    offset += 2;
    length = read_half(sd->icd_product, &offset);

    if(verbose_flag) {
        printf("\nPacket 7: Unlinked Vector Packet (no value)\n");
        printf("Packet 7 Length of Data Block (in bytes) = %hd\n", length);
    }

    num_vectors=length/8;
    if(verbose_flag)
        printf("Number of Vectors: %i\n", num_vectors);


    XSetForeground(display, gc, display_colors[1].pixel);
     
    for(i=0; i<num_vectors; i++) {
        /* CVG 9.0 - added centering factor for large screens */
        i_start = read_half(sd->icd_product, &offset) * x_scale + center_pixel;
        j_start = read_half(sd->icd_product, &offset) * y_scale + center_scanl;
        if(verbose_flag)
            printf("I Starting Point: %hd   J Starting Point: %hd\n", i_start, j_start);
        /* CVG 9.0 - added centering factor for large screens */
        i_end = read_half(sd->icd_product, &offset) * x_scale + center_pixel;
        j_end = read_half(sd->icd_product, &offset) * y_scale + center_scanl;
        if(verbose_flag)
            printf("End Vector Number %4d   I=%5hd  J=%5hd\n",count,i_end,j_end);
        XDrawLine(display, sd->pixmap, gc, i_start, j_start, i_end, j_end);
        count++;
        
    }  /* end for num_vectors */
    
} /* end display_packet_7 */
Exemple #27
0
static gmx_bool xhwCallBack(struct t_x11 *x11, XEvent *event, Window wd, void *data)
{
    t_xhighway     *xhw;
    t_windata      *win;
    float           sx;
    int             i;
    static     int  nyy = 0;
    static     int *yy;

    xhw = (t_xhighway *)data;
    win = &(xhw->win);

    if (nyy == 0)
    {
        nyy = 2*xhw->ir.nlane+1;
        snew(yy, nyy);
    }
    for (i = 0; (i < nyy); i++)
    {
        yy[i] = ((float) i*win->height)/(nyy-1);
    }

    switch (event->type)
    {
        case Expose:
        {
            if (wd == win->self)
            {
                sx = (float)win->width  / xhw->ir.metres;

                XClearWindow(x11->disp, win->self);
                XSetForeground(x11->disp, x11->gc, WHITE);

                for (i = 2; (i < nyy-1); i += 2)
                {
                    XDrawLine(x11->disp, win->self, x11->gc, 0, yy[i], win->width-1, yy[i]);
                }

                for (i = 0; (i < xhw->ncars); i++)
                {
                    t_car *car = &(xhw->cars[i]);
                    int    w1  = car->x*sx;
                    int    h1  = yy[1+2*(xhw->ir.nlane-1-car->lane)];

                    draw_car(x11->disp, win->self, x11->gc, car, w1, h1);
                }
                if (xhw->bDriving)
                {
                    simulate(x11, xhw, xhw->ncars, xhw->cars, &xhw->ir);
                }
            }
            break;
        }
        case ConfigureNotify:
            if (wd == xhw->main.self)
            {
                xhw->main.width  = event->xconfigure.width;
                xhw->main.height = event->xconfigure.height;
                Configure(xhw);
                for (i = 0; (i < NBUT); i++)
                {
                    XMoveResizeWindow(x11->disp, xhw->but[i].self,
                                      xhw->but[i].x, xhw->but[i].y,
                                      xhw->but[i].width, xhw->but[i].height);
                }
                XMoveResizeWindow(x11->disp, win->self,
                                  win->x, win->y, win->width, win->height);
            }
            else if (wd == win->self)
            {
                win->width  = event->xconfigure.width;
                win->height = event->xconfigure.height;
            }
            break;
        case ButtonPress:
            return TRUE;
        default:
            break;
    }
    return FALSE;
}
Exemple #28
0
int
main(int argc, char **argv) {
    char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
    char buf[32], passwd[256], passdisp[256];
    int num, screen, width, height, update, sleepmode, term, pid;

#ifndef HAVE_BSD_AUTH
    const char *pws;
#endif
    unsigned int len;
    Bool running = True;
    Cursor invisible;
    Display *dpy;
    KeySym ksym;
    Pixmap pmap;
    Window root, w;
    XColor black, red, dummy;
    XEvent ev;
    XSetWindowAttributes wa;
    XFontStruct* font;
    GC gc;
    XGCValues values;

    // defaults
    char* passchar = "*";
    char* fontname = "-*-dejavu sans-bold-r-*-*-*-420-100-100-*-*-iso8859-1";
    char* username = "";
    int showline = 1;
    int xshift = 0;

    for (int i = 0; i < argc; i++) {
        if (!strcmp(argv[i], "-c")) {
            if (i + 1 < argc)
                passchar = argv[i + 1];
            else
                die("error: no password character given.\n");
        } else if (!strcmp(argv[i], "-f")) {
            if (i + 1 < argc)
                fontname = argv[i + 1];
            else
                die("error: font not specified.\n");
        }
        else if (!strcmp(argv[i], "-v"))
            die("sflock-"VERSION", © 2015 Ben Ruijl\n");
        else if (!strcmp(argv[i], "-h"))
            showline = 0;
        else if (!strcmp(argv[i], "-xshift"))
            xshift = atoi(argv[i + 1]);
        else if (!strcmp(argv[i], "?"))
            die("usage: sflock [-v] [-c passchars] [-f fontname] [-xshift horizontal shift]\n");
    }

    // fill with password characters
    for (int i = 0; i < sizeof passdisp; i+= strlen(passchar))
        for (int j = 0; j < strlen(passchar) && i + j < sizeof passdisp; j++)
            passdisp[i + j] = passchar[j];


    /* disable tty switching */
    if ((term = open("/dev/console", O_RDWR)) == -1) {
        perror("error opening console");
    }

    if ((ioctl(term, VT_LOCKSWITCH)) == -1) {
        perror("error locking console");
    }

    /* deamonize */
    pid = fork();
    if (pid < 0)
        die("Could not fork sflock.");
    if (pid > 0)
        exit(0); // exit parent

#ifndef HAVE_BSD_AUTH
    pws = get_password();
    username = getpwuid(geteuid())->pw_name;
#else
    username = getlogin();
#endif

    if(!(dpy = XOpenDisplay(0)))
        die("sflock: cannot open dpy\n");

    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    width = DisplayWidth(dpy, screen);
    height = DisplayHeight(dpy, screen);

    wa.override_redirect = 1;
    wa.background_pixel = XBlackPixel(dpy, screen);
    w = XCreateWindow(dpy, root, 0, 0, width, height,
                      0, DefaultDepth(dpy, screen), CopyFromParent,
                      DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa);

    XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "orange red", &red, &dummy);
    XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy);
    pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8);
    invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0);
    XDefineCursor(dpy, w, invisible);
    XMapRaised(dpy, w);

    font = XLoadQueryFont(dpy, fontname);

    if (font == 0) {
        die("error: could not find font. Try using a full description.\n");
    }

    gc = XCreateGC(dpy, w, (unsigned long)0, &values);
    XSetFont(dpy, gc, font->fid);
    XSetForeground(dpy, gc, XWhitePixel(dpy, screen));

    for(len = 1000; len; len--) {
        if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
                        GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
            break;
        usleep(1000);
    }
    if((running = running && (len > 0))) {
        for(len = 1000; len; len--) {
            if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
                    == GrabSuccess)
                break;
            usleep(1000);
        }
        running = (len > 0);
    }

    len = 0;
    XSync(dpy, False);
    update = True;
    sleepmode = False;

    /* main event loop */
    while(running && !XNextEvent(dpy, &ev)) {
        if (sleepmode) {
            DPMSEnable(dpy);
            DPMSForceLevel(dpy, DPMSModeOff);
            XFlush(dpy);
        }

        if (update) {
            int x, y, dir, ascent, descent;
            XCharStruct overall;

            XClearWindow(dpy, w);
            XTextExtents (font, passdisp, len, &dir, &ascent, &descent, &overall);
            x = (width - overall.width) / 2;
            y = (height + ascent - descent) / 2;

            XDrawString(dpy,w,gc, (width - XTextWidth(font, username, strlen(username))) / 2 + xshift, y - ascent - 20, username, strlen(username));

            if (showline)
                XDrawLine(dpy, w, gc, width * 3 / 8 + xshift, y - ascent - 10, width * 5 / 8 + xshift, y - ascent - 10);

            XDrawString(dpy,w,gc, x + xshift, y, passdisp, len);
            update = False;
        }

        if (ev.type == MotionNotify) {
            sleepmode = False;
        }

        if(ev.type == KeyPress) {
            sleepmode = False;

            buf[0] = 0;
            num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
            if(IsKeypadKey(ksym)) {
                if(ksym == XK_KP_Enter)
                    ksym = XK_Return;
                else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
                    ksym = (ksym - XK_KP_0) + XK_0;
            }
            if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
                    || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
                    || IsPrivateKeypadKey(ksym))
                continue;

            switch(ksym) {
            case XK_Return:
                passwd[len] = 0;
#ifdef HAVE_BSD_AUTH
                running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
                running = strcmp(crypt(passwd, pws), pws);
#endif
                if (running != 0)
                    // change background on wrong password
                    XSetWindowBackground(dpy, w, red.pixel);
                len = 0;
                break;
            case XK_Escape:
                len = 0;

                if (DPMSCapable(dpy)) {
                    sleepmode = True;
                }

                break;
            case XK_BackSpace:
                if(len)
                    --len;
                break;
            default:
                if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) {
                    memcpy(passwd + len, buf, num);
                    len += num;
                }

                break;
            }

            update = True; // show changes
        }
    }

    /* free and unlock */
    setreuid(geteuid(), 0);
    if ((ioctl(term, VT_UNLOCKSWITCH)) == -1) {
        perror("error unlocking console");
    }

    close(term);
    setuid(getuid()); // drop rights permanently


    XUngrabPointer(dpy, CurrentTime);
    XFreePixmap(dpy, pmap);
    XFreeFont(dpy, font);
    XFreeGC(dpy, gc);
    XDestroyWindow(dpy, w);
    XCloseDisplay(dpy);
    return 0;
}
Exemple #29
0
void
_DtTermPrimRefreshText(Widget w, short startColumn, short startRow,
	short endColumn, short endRow)
{
    DtTermPrimitiveWidget tw = (DtTermPrimitiveWidget) w;
    struct termData *tpd = tw->term.tpd;
    TermBuffer tBuffer = tpd->termBuffer;
    int lineWidth;
    unsigned char *linePtr;
    TermFont termFont;
    int currentColorPair = 0;
    int currentVideo = 0;
    short chunkStartColumn;
    short chunkWidth;
    enhValues enhancements;
    int i;
    int lineNum;
    unsigned long valueMask;
    GC gc;
    XGCValues values;
    TermEnhInfoRec enhInfo;
    Boolean checkSelection = False;
    int selectionEnd;
    Pixel tmpPixel;
    XmTextPosition  begin, end;
    
    DebugF('t', 0, fprintf(stderr, ">>_DtTermPrimRefreshText() starting\n"));
    DebugF('t', 0, fprintf(stderr,
	    ">>_DtTermPrimRefreshText() startCol=%hd  startRow=%hd  endCol=%hd  endRow=%hd\n",
	    startColumn, startRow, endColumn, endRow));

    if (tpd->mbCurMax > 1)
    {
        _DtTermPrimRefreshTextWc(w, startColumn, startRow, endColumn, endRow);
        return;
    }

    /* clip start/end x/y... */
    if (startColumn <= 0)
	startColumn = 0;
    if (startRow <= 0)
	startRow = 0;
    if (endColumn >= tw->term.columns)
	endColumn = tw->term.columns - 1;
    if (endRow >= tw->term.rows)
	endRow = tw->term.rows - 1;

    /*
    ** don't display if we are in jump scroll and in the process
    ** of scrolling and inside the scroll region...
    */
    if (tw->term.jumpScroll && tpd->scroll.jump.scrolled) {
	/* set all the scrollRefreshRows flags... */
	for (; startRow <= endRow; startRow++) {
	    tpd->scrollRefreshRows[startRow] = True;
	}

	DebugF('t', 0,
		fprintf(stderr,
		">>_DtTermPrimRefreshText() jump scroll in progress, no render\n"));
        return;
    }

    if (!tpd->renderGC.gc) {
	/* get a drawImageString GC... */
	int i;
	XGCValues values;

	/***********************************************************
	 * renderGC...
	 */
	/* set the GC fg and bg... */
	values.foreground = tw->term.reverseVideo ?
		tw->core.background_pixel : tw->primitive.foreground;
	values.background = tw->term.reverseVideo ?
		tw->primitive.foreground : tw->core.background_pixel;

	tpd->renderGC.gc = XCreateGC(XtDisplay(w), XtWindow(w),
		GCForeground | GCBackground, &values);

	/* set the GC cache values... */
	tpd->renderGC.foreground = values.foreground;
	tpd->renderGC.background = values.background;
	tpd->renderGC.fid = (Font) 0;

	/***********************************************************
	 * renderReverseGC...
	 */
	values.foreground = tw->term.reverseVideo ?
		tw->primitive.foreground : tw->core.background_pixel;
	values.background = tw->term.reverseVideo ?
		tw->core.background_pixel : tw->primitive.foreground;

	tpd->renderReverseGC.gc = XCreateGC(XtDisplay(w), XtWindow(w),
		GCForeground | GCBackground, &values);

	/* set the GC cache values... */
	tpd->renderReverseGC.foreground = values.foreground;
	tpd->renderReverseGC.background = values.background;
	tpd->renderReverseGC.fid = (Font) 0;

	/***********************************************************
	 * clearGC...
	 */
	values.foreground = tw->term.reverseVideo ?
		tw->primitive.foreground : tw->core.background_pixel;
	values.background = tw->term.reverseVideo ?
		tw->core.background_pixel : tw->primitive.foreground;

	tpd->clearGC.gc = XCreateGC(XtDisplay(w), XtWindow(w),
		GCForeground | GCBackground, &values);

	/* set the GC cache values... */
	tpd->clearGC.foreground = values.foreground;
	tpd->clearGC.background = values.background;
	tpd->clearGC.fid = (Font) 0;
    }

#ifdef SUN_MOTIF_PERF
    /* use the clear GC... */
    gc = tpd->clearGC.gc;

    valueMask = (unsigned long) 0;
    if (tpd->clearGC.foreground !=
	    tw->term.reverseVideo ?
	    tw->core.background_pixel : tw->primitive.foreground) {
        values.foreground =
	        tw->term.reverseVideo ?
	        tw->primitive.foreground :
	        tw->core.background_pixel;
        tpd->clearGC.foreground = values.foreground;
        valueMask |= GCForeground;
    }
    if (tpd->clearGC.background !=
	    tw->term.reverseVideo ?
	    tw->primitive.foreground :
	    tw->core.background_pixel) {
        values.background =
	        tw->term.reverseVideo ?
	        tw->core.background_pixel :
	        tw->primitive.foreground;
        tpd->clearGC.background = values.background;
        valueMask |= GCBackground;
    }
    if (valueMask) {
        (void) XChangeGC(XtDisplay(w), tpd->clearGC.gc,
	        valueMask, &values);
    }
    (void) XFillRectangle(XtDisplay(w),         /* Display		*/
		    XtWindow(w),		/* Drawable		*/
		    gc,				/* GC			*/
		    startColumn * tpd->cellWidth + tpd->offsetX,
						/* x			*/
		    startRow * tpd->cellHeight + tpd->offsetY,
						/* y			*/
		    (endColumn - startColumn + 1) * tpd->cellWidth,
						/* width		*/
		    (endRow - startRow + 1) * tpd->cellHeight);		
						/* height		*/
#endif /* SUN_MOTIF_PERF */

    for (; startRow <= endRow; startRow++) {
	/* if we are refreshing a full line, then we can clear the
	 * scrollRefreshRows flag for this line...
	 */
	if ((startColumn == 0) && (endColumn >= tw->term.columns - 1)) {
	    tpd->scrollRefreshRows[startRow] = False;
	}

	lineNum = startRow + tpd->topRow;
	if (!tw->term.jumpScroll && tpd->scroll.nojump.pendingScroll) {
            if (lineNum != tpd->scrollLockBottomRow)
            {
                lineNum -= tpd->scroll.nojump.pendingScrollLines;
            }
    	}

	/* are we in the selected area?... */
        if (tpd->useHistoryBuffer)
        {
            if (_DtTermPrimSelectGetSelection(w, &begin, &end) &&
                (begin < end) &&
                (lineNum >= (begin / (tpd->selectInfo->columns + 1)) - 
                            tpd->lastUsedHistoryRow) &&
                (lineNum <= (end   / (tpd->selectInfo->columns + 1)) - 
                            tpd->lastUsedHistoryRow)) {
                checkSelection = True;
            } else {
                checkSelection = False;
            }
        }
        else
        {
            if (_DtTermPrimSelectGetSelection(w, &begin, &end) &&
                (begin < end) &&
                (lineNum >= (begin / (tpd->selectInfo->columns + 1))) &&
                (lineNum <= (end   / (tpd->selectInfo->columns + 1))))  {
                checkSelection = True;
            } else {
                checkSelection = False;
            }
        }

	chunkStartColumn = startColumn;
	if (startColumn > endColumn) {
	    /* nothing to render on this line... */
	    continue;
	}

	if (lineNum >= tpd->lastUsedRow) {
	    /* we are pointing to empty screen space below the last used
	     * line of the display...
	     */
	    lineWidth = 0;
	    linePtr = NULL;
	} else if (lineNum < 0) {
	    if ((tpd->useHistoryBuffer) &&
		    (-lineNum <= tpd->lastUsedHistoryRow)) {
		/* get a line out of the history buffer... */
		lineWidth = MAX(0, MIN(endColumn - startColumn + 1,
		    _DtTermPrimBufferGetLineWidth(tpd->historyBuffer,
		    tpd->lastUsedHistoryRow + lineNum) - startColumn));
		linePtr =
		    _DtTermPrimBufferGetCharacterPointer(tpd->historyBuffer,
		    tpd->lastUsedHistoryRow + lineNum, startColumn);
	    } else {
		/* we are above the history buffer.  Should not happen, but...
		 */
		lineWidth = 0;
		linePtr = NULL;
	    }
	} else {
	    /* get the line width and a pointer to the data... */
	    lineWidth = MAX(0, MIN(endColumn - startColumn + 1,
		    _DtTermPrimBufferGetLineWidth(tBuffer, lineNum) -
		    startColumn));
	    linePtr = _DtTermPrimBufferGetCharacterPointer(tBuffer, lineNum,
		    startColumn);
	}

	while (lineWidth > 0) {
	    /* get the enhancement values for the first chunk of the
	     * string...
	     */
	    if (lineNum >= 0) {
		(void) _DtTermPrimBufferGetEnhancement(tBuffer,
						/* TermBuffer		*/
			lineNum,		/* row			*/
			chunkStartColumn,	/* col			*/
			&enhancements,		/* enhancements		*/
			&chunkWidth,		/* width        	*/
			countAll);		/* countWhich		*/
	    } else {
		/* get it from the history buffer... */
		(void) _DtTermPrimBufferGetEnhancement(tpd->historyBuffer,
						/* TermBuffer		*/
			tpd->lastUsedHistoryRow + lineNum,
						/* row			*/
			chunkStartColumn,	/* col			*/
			&enhancements,		/* enhancements		*/
			&chunkWidth,		/* width		*/
			countAll);		/* countWhich		*/
	    }

	    /* clip chunkWidth... */
	    if (chunkWidth > lineWidth)
		chunkWidth = lineWidth;

	    /* set reasonable defaults for our render info... */
	    enhInfo.fg = tw->primitive.foreground;
	    enhInfo.bg = tw->core.background_pixel;
	    enhInfo.font = tpd->defaultTermFont;
	    enhInfo.flags = (unsigned long) 0;

	    /* set our font and color from the enhancements... */
	    if (ENH_PROC(tBuffer)) {
                (void) (*(ENH_PROC(tBuffer)))(w, enhancements, &enhInfo);
	    }

	    /* if we are in reverse video mode... */
	    if (tw->term.reverseVideo) {
		/* flip fg and bg... */
		tmpPixel = enhInfo.fg;
		enhInfo.fg = enhInfo.bg;
		enhInfo.bg = tmpPixel;
	    }

	    /* are we in the selection area?... */
	    if (checkSelection && 
                _DtTermPrimSelectIsInSelection(w, lineNum, chunkStartColumn,
		                         chunkWidth, &chunkWidth)) {

		/* flip fg and bg... */
		tmpPixel = enhInfo.fg;
		enhInfo.fg = enhInfo.bg;
		enhInfo.bg = tmpPixel;
	    }
			
	    /* if secure, we will use a XFillRectangle, and we need
	     * foreground set to the background...
	     */

	    if (TermIS_SECURE(enhInfo.flags)) {
		/* render secure video locally...
		 */
		/* set the renderReverseGC... */
		valueMask = (unsigned long) 0;
		if (tpd->renderReverseGC.foreground != enhInfo.bg) {
		    tpd->renderReverseGC.foreground = enhInfo.bg;
		    values.foreground = enhInfo.bg;
		    valueMask |= GCForeground;
		}
		if (valueMask) {
		    (void) XChangeGC(XtDisplay(w), tpd->renderReverseGC.gc,
			    valueMask, &values);
		}
		(void) XFillRectangle(XtDisplay(w),
			XtWindow(w),
			tpd->renderReverseGC.gc,
			chunkStartColumn * tpd->cellWidth + tpd->offsetX,
			startRow * tpd->cellHeight + tpd->offsetY,
			tpd->cellWidth *  chunkWidth,
			tpd->cellHeight);

		/* underline as well... */
		if (TermIS_UNDERLINE(enhInfo.flags)) {
		    valueMask = (unsigned long) 0;
		    if (tpd->renderGC.foreground != enhInfo.fg) {
			tpd->renderGC.foreground = enhInfo.fg;
			values.foreground = enhInfo.fg;
			valueMask |= GCForeground;
		    }
		    if (valueMask) {
			(void) XChangeGC(XtDisplay(w), tpd->renderGC.gc,
				valueMask, &values);
		    }
		    (void) XDrawLine(XtDisplay(w),
						/* Display		*/
			    XtWindow(w),	/* Drawable		*/
			    tpd->renderGC.gc,	/* GC			*/
			    chunkStartColumn * tpd->cellWidth + tpd->offsetX,
						/* X1			*/
			    startRow * tpd->cellHeight + tpd->offsetY +
			    tpd->cellHeight - 1,
						/* Y1			*/
			    (chunkStartColumn + chunkWidth) * tpd->cellWidth +
			    tpd->offsetX,	/* X2			*/
			    startRow * tpd->cellHeight + tpd->offsetY +
			    tpd->cellHeight - 1);
						/* Y2			*/
		}
	    } else {
		(void) _DtTermPrimRenderText(
		    w,				/* Widget		*/
		    enhInfo.font,		/* TermFont		*/
		    enhInfo.fg,			/* fg Pixel		*/
		    enhInfo.bg,			/* bg Pixel		*/
		    enhInfo.flags,		/* flags		*/
		    chunkStartColumn * tpd->cellWidth + tpd->offsetX,
						/* x			*/
		    startRow * tpd->cellHeight + tpd->offsetY,
						/* y			*/
		    linePtr,			/* string		*/
		    chunkWidth);		/* width		*/
	    }
	    chunkStartColumn += chunkWidth;
	    lineWidth -= chunkWidth;
	    linePtr += chunkWidth;
	}

	/* clear any extra space in the line.  chunkStartColumn now points to
	 * the end of the line, and lineWidth == 0...
	 */
	while (endColumn - chunkStartColumn >= 0) {
	    chunkWidth = endColumn - chunkStartColumn + 1;
	    if (checkSelection && 
                _DtTermPrimSelectIsInSelection(w, lineNum, chunkStartColumn,
		                         chunkWidth, &chunkWidth)) {
		/* use the render gc set to the fg color... */
		gc = tpd->renderReverseGC.gc;

		valueMask = (unsigned long) 0;
		if (tpd->renderReverseGC.foreground !=
			tw->term.reverseVideo ?
			tw->core.background_pixel : tw->primitive.foreground) {
		    values.foreground =
			    tw->term.reverseVideo ?
			    tw->core.background_pixel :
			    tw->primitive.foreground;
		    tpd->renderReverseGC.foreground = values.foreground;
		    valueMask |= GCForeground;
		}
		if (valueMask) {
		    (void) XChangeGC(XtDisplay(w), tpd->renderReverseGC.gc,
			    valueMask, &values);
		}
#ifndef SUN_MOTIF_PERF
	    } else {
		/* use the clear GC... */
		gc = tpd->clearGC.gc;

		valueMask = (unsigned long) 0;
		if (tpd->clearGC.foreground !=
			tw->term.reverseVideo ?
			tw->core.background_pixel : tw->primitive.foreground) {
		    values.foreground =
			    tw->term.reverseVideo ?
			    tw->primitive.foreground :
			    tw->core.background_pixel;
		    tpd->clearGC.foreground = values.foreground;
		    valueMask |= GCForeground;
		}
		if (tpd->clearGC.background !=
			tw->term.reverseVideo ?
			tw->primitive.foreground :
			tw->core.background_pixel) {
		    values.background =
			    tw->term.reverseVideo ?
			    tw->core.background_pixel :
			    tw->primitive.foreground;
		    tpd->clearGC.background = values.background;
		    valueMask |= GCBackground;
		}
		if (valueMask) {
		    (void) XChangeGC(XtDisplay(w), tpd->clearGC.gc,
			    valueMask, &values);
		}
	    }
#endif /* not SUN_MOTIF_PERF */

	    if (isDebugFSet('t', 1)) {
#ifdef	BBA
#pragma BBA_IGNORE
#endif	/*BBA*/
		/* Fill in the clear area so we can see what is going to
		 * be displayed...
		 */
		(void) XFillRectangle(XtDisplay(w),
			XtWindow(w),
			tpd->renderGC.gc,
			chunkStartColumn * tpd->cellWidth + tpd->offsetX,
			startRow * tpd->cellHeight + tpd->offsetY,
			chunkWidth * tpd->cellWidth,
			tpd->cellHeight);
		(void) XSync(XtDisplay(w), False);
		(void) shortSleep(100000);
	    }
	    (void) XFillRectangle(XtDisplay(w),
						/* Display		*/
		    XtWindow(w),		/* Drawable		*/
		    gc,				/* GC			*/
		    chunkStartColumn * tpd->cellWidth + tpd->offsetX,
						/* x			*/
		    startRow * tpd->cellHeight + tpd->offsetY,
						/* y			*/
		    chunkWidth * tpd->cellWidth,
						/* width		*/
		    tpd->cellHeight);		/* height		*/
#ifdef SUN_MOTIF_PERF
	    }
#endif /* SUN_MOTIF_PERF */
	    chunkStartColumn += chunkWidth;
	}
    }
Exemple #30
0
static void
draw_laser_once(ModeInfo * mi)
{
    Display    *display = MI_DISPLAY(mi);
    lasersstruct *lp = &lasers[MI_SCREEN(mi)];
    int         i;

    for (i = 0; i < lp->ln; i++) {
        laserstruct *l = &lp->laser[i];

        if (lp->sw >= lp->lw) {
            XChangeGC(display, lp->stippledGC, GCForeground, &(lp->gcv_black));
            XDrawLine(display, MI_WINDOW(mi), lp->stippledGC,
                      lp->cx, lp->cy,
                      l->sx[lp->so], l->sy[lp->so]);
        }
        if (l->dir) {
            switch (l->bn) {
            case TOP:
                l->bx -= l->speed;
                if (l->bx < 0) {
                    l->by = -l->bx;
                    l->bx = 0;
                    l->bn = LEFT;
                }
                break;
            case RIGHT:
                l->by -= l->speed;
                if (l->by < 0) {
                    l->bx = lp->width + l->by;
                    l->by = 0;
                    l->bn = TOP;
                }
                break;
            case BOTTOM:
                l->bx += l->speed;
                if (l->bx >= lp->width) {
                    l->by = lp->height - l->bx % lp->width;
                    l->bx = lp->width;
                    l->bn = RIGHT;
                }
                break;
            case LEFT:
                l->by += l->speed;
                if (l->by >= lp->height) {
                    l->bx = l->by % lp->height;
                    l->by = lp->height;
                    l->bn = BOTTOM;
                }
            }
        } else {
            switch (l->bn) {
            case TOP:
                l->bx += l->speed;
                if (l->bx >= lp->width) {
                    l->by = l->bx % lp->width;
                    l->bx = lp->width;
                    l->bn = RIGHT;
                }
                break;
            case RIGHT:
                l->by += l->speed;
                if (l->by >= lp->height) {
                    l->bx = lp->width - l->by % lp->height;
                    l->by = lp->height;
                    l->bn = BOTTOM;
                }
                break;
            case BOTTOM:
                l->bx -= l->speed;
                if (l->bx < 0) {
                    l->by = lp->height + l->bx;
                    l->bx = 0;
                    l->bn = LEFT;
                }
                break;
            case LEFT:
                l->by -= l->speed;
                if (l->by < 0) {
                    l->bx = -l->bx;
                    l->by = 0;
                    l->bn = TOP;
                }
            }
        }

        XChangeGC(display, lp->stippledGC, GCForeground, &l->gcv);
        XDrawLine(display, MI_WINDOW(mi), lp->stippledGC,
                  lp->cx, lp->cy, l->bx, l->by);

        l->sx[lp->so] = l->bx;
        l->sy[lp->so] = l->by;

    }

    if (lp->sw < lp->lw)
        ++lp->sw;

    lp->so = (lp->so + 1) % lp->lw;
}