Exemplo n.º 1
0
Arquivo: status.c Projeto: awaw/status
int
main(int argc, char *argv[])
{
	XEvent e;
	Atom type;
	XClassHint *h;
	XSetWindowAttributes wa;
	unsigned int desktop;
	struct pollfd pfd[1];
	int nfds;
	char *fontstr = FONT;
	int running = 1;

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

	s = DefaultScreen(d);

	wa.override_redirect = 1;
	wa.background_pixmap = ParentRelative;
	wa.event_mask = ExposureMask | ButtonReleaseMask | ButtonPressMask;

	w = XCreateWindow(d, RootWindow(d, s), 0, BARPOS, BARWIDTH, BARHEIGHT, 0,
	    DefaultDepth(d, s), CopyFromParent, DefaultVisual(d, s),
	    CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);

	h = XAllocClassHint();
	h->res_name  = "status";
	h->res_class = "status";
	XSetClassHint(d, w, h);
	XFree(h);

	XStoreName(d, w, "status");

	type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", False);
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", False),
	    XInternAtom(d, "ATOM", False), 32, PropModeReplace, (unsigned char *)&type, 1);

	type = XInternAtom(d, "_NET_WM_STATE_ABOVE", False);
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", False),
	    XInternAtom(d, "ATOM", False), 32, PropModeReplace, (unsigned char *)&type, 1);

	type = XInternAtom(d, "_NET_WM_STATE_STICKY", False);
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", False),
	    XInternAtom(d, "ATOM", False), 32, PropModeAppend, (unsigned char *)&type, 1); 

	desktop = 0xffffffff;
	XChangeProperty(d, w, XInternAtom(d, "_NET_WM_DESKTOP", False),
	    XInternAtom(d, "CARDINAL", False), 32, PropModeReplace, (unsigned char *)&desktop, 1);

	xftd = XftDrawCreate(d, w, DefaultVisual(d, s), DefaultColormap(d, s));

	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "white",  &white);
	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "black",  &black);
	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "red",  &red);
	XftColorAllocName(d, DefaultVisual(d, s), DefaultColormap(d, s),  "green",  &green);

	xftfont = XftFontOpenXlfd(d, s, fontstr);
	if (!xftfont)
		xftfont = XftFontOpenName(d, s, fontstr);
	if (!xftfont)
		exit(1);

	XSelectInput(d, w, ExposureMask | ButtonPressMask | ButtonReleaseMask | Button1MotionMask);
	XSelectInput(d, RootWindow(d, s), PropertyChangeMask);

	XMapWindow(d, w);
	XFlush(d);

	pfd[0].fd = ConnectionNumber(d);
	pfd[0].events = POLLIN;

	while (running) {
		nfds = poll(pfd, 1, 1000);
		if (nfds == -1 || (pfd[0].revents & (POLLERR|POLLHUP|POLLNVAL)))
			break;
		if (nfds == 0) {
			redraw();
			XFlush(d);
			continue;
		}

		while (XPending(d)) {
			XNextEvent(d, &e);
			if (e.type == PropertyNotify &&
			    e.xproperty.window == RootWindow(d, s) &&
			    e.xproperty.atom == XInternAtom(d, "_NET_CURRENT_DESKTOP", True)) {
				redraw();
			}
			if (e.type == Expose) {
				XftDrawRect(xftd, &black, 0, 0, BARWIDTH, BARHEIGHT);
				redraw();
			}
			if (e.type == ButtonPress) {
				/*running = 0;
				break;*/
				redraw();
			}
		}
	}

	XftColorFree(d, DefaultVisual(d, s), DefaultColormap(d, s), &white);
	XftColorFree(d, DefaultVisual(d, s), DefaultColormap(d, s), &black);
	XftFontClose(d, xftfont);
	XftDrawDestroy(xftd);
	XDestroyWindow(d, w);
	XCloseDisplay(d);
	return 0;
}
Exemplo n.º 2
0
XMenu *
XMenuCreate(Display *display, Window parent, register char const *def_env)
                                /* ID of previously opened display */
                  		/* Window ID of the menu's parent window. */
                           	/* X Defaults program environment name. */
{
  register char *def_val;	/* X Default value temp variable. */

  register XMenu *menu;		/* Pointer to the new menu. */
  XMStyle menu_style;		/* Menu display style. */
  XMMode menu_mode;		/* Menu display mode. */
  XMPane *pane;			/* Pane list header. */
  XAssocTable *assoc_tab;	/* XAssocTable pointer. */

  int freeze;			/* Freeze server mode. */
  int reverse;			/* Reverse video mode. */

  XMStyle p_style;		/* Pane display style. */
  char const *p_fnt_name;	/* Flag font name. */
  XFontStruct *p_fnt_info;	/* Flag font structure */
  int p_fnt_pad;		/* Flag font padding in pixels. */
  double p_spread;		/* Pane spread in flag height fractions. */
  int p_fnt_height;		/* Pane character height. */
  int p_bdr_width;		/* Pane border width. */
  int flag_height;		/* Flag window height. */
  int p_height;			/* Pane window height. */
  int p_x_off;			/* Pane X offset. */
  int p_y_off;			/* Pane Y offset. */
  GC pane_GC;			/* Pane graphics context. */

  XMStyle s_style;		/* Selection display style. */
  char const *s_fnt_name;	/* Selection font name. */
  XFontStruct *s_fnt_info;	/* Selection font structure. */
  int s_fnt_pad;		/* Selection font padding in pixels. */
  int s_fnt_height;		/* Selection font character height */
  double s_spread;		/* Select spread in line height fractions. */
  int s_bdr_width;		/* Highlight border width. */
  int s_height;			/* Selection window height. */
  int s_x_off;			/* Selection window X offset. */
  int s_y_off;			/* Selection window Y offset. */
  GC normal_select_GC;		/* GC used for normal video selection. */
  GC inverse_select_GC;		/* GC used for inverse video selection. */
  GC inact_GC;			/* GC for inactive pane header and */
  /* selections. */

  XColor color_def;		/* Temp color definition holder. */
  XColor p_bdr_color;		/* Color of border. */
  XColor s_bdr_color;		/* Color of highlight. */
  XColor p_frg_color;		/* Color of pane foreground color. */
  XColor s_frg_color;		/* Color of selection foreground. */
  XColor bkgnd_color;		/* Color of background.. */
  XColor mouse_color;		/* Color of mouse cursor. */
  Cursor mouse_cursor;		/* Mouse cursor. */
  Pixmap inact_bitmap;		/* Menu inactive pixmap. */

  int inact_pnum;		/* Inactive background pattern number. */

  Pixmap cursor;		/* Cursor pixmap holder. */
  Pixmap cursor_mask;		/* Cursor mask pixmap holder. */
  Pixmap stipple_pixmap;	/* Stipple mask for half-tone text. */
  unsigned long valuemask;
  XGCValues *values;

  Window root = RootWindow (display, DefaultScreen (display));

  /*
   * Calloc the XMenu structure and the initial pane.
   */
  menu = (XMenu *)calloc(1, sizeof(XMenu));
  if (menu == NULL) {
    _XMErrorCode = XME_CALLOC;
    return(NULL);
  }
  pane = (XMPane *)calloc(1, sizeof(XMPane));
  if (pane == NULL) {
    _XMErrorCode = XME_CALLOC;
    return(NULL);
  }

  /*
   * Create the XAssocTable
   */
  assoc_tab = (XAssocTable *)XCreateAssocTable(XASSOC_TABLE_SIZE);
  if(assoc_tab == NULL) {
    _XMErrorCode= XME_CREATE_ASSOC;
    return(NULL);
  }

  /*
   * Set up the default environment name.
   */
  if (def_env == NULL || *def_env == '\0') def_env = "XMenu";

  /*
   * Set up internal fail-safe defaults.
   */
  freeze = DEF_FREEZE;
  reverse = DEF_REVERSE;
  menu_style = DEF_MENU_STYLE;
  menu_mode = DEF_MENU_MODE;
  inact_pnum = DEF_INACT_PNUM;

  p_style = DEF_P_STYLE;
  p_spread = DEF_P_SPREAD;
  p_fnt_name = DEF_P_FNT_NAME;
  p_bdr_width = DEF_P_BDR_WIDTH;

  s_style = DEF_S_STYLE;
  s_spread = DEF_S_SPREAD;
  s_fnt_name = DEF_S_FNT_NAME;
  s_bdr_width = DEF_S_BDR_WIDTH;

  /*
   * Get default values from X.
   */
  def_val = x_get_resource_string ("menuFreeze", "MenuFreeze");
  if (def_val != NULL) {
    if (strcmp(def_val, "on") == 0) freeze = 1;
    else if (strcmp(def_val, "off") == 0) freeze = 0;
  }

  def_val = x_get_resource_string ("menuReverseVideo", "MenuReverseVideo");
  if (def_val != NULL) {
    if (strcmp(def_val, "on") == 0) reverse = 1;
    else if (strcmp(def_val, "off") == 0) reverse = 0;
  }

  def_val = x_get_resource_string ("menuStyle", "MenuStyle");
  if (def_val != NULL) {
    if (strcmp(def_val, "right_hand") == 0) menu_style = RIGHT;
    else if (strcmp(def_val, "left_hand") == 0) menu_style = LEFT;
    else if (strcmp(def_val, "center") == 0) menu_style = CENTER;
  }

  def_val = x_get_resource_string ("menuMode", "MenuMode");
  if (def_val != NULL) {
    if (strcmp(def_val, "box") == 0) menu_mode = BOX;
    else if (strcmp(def_val, "invert") == 0) menu_mode = INVERT;
  }

  def_val = x_get_resource_string ("menuMouse", "MenuMouse");
  if (
      def_val != NULL &&
      DisplayCells(display, DefaultScreen(display)) > 2 &&
      XAllocDisplayColor(display,
			 DefaultColormap(display, DefaultScreen(display)),
			 def_val,
			 &mouse_color, &color_def)
      );
  else if (reverse &&
	   XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "white",
			      &mouse_color, &color_def)
	   );

  else if (XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "black",
			      &mouse_color, &color_def)
	   );

  else {}

  def_val = x_get_resource_string ("menuBackground", "MenuBackground");
  if (
      def_val != NULL &&
      DisplayCells(display, DefaultScreen(display)) > 2 &&
      XAllocDisplayColor(display,
			 DefaultColormap(display, DefaultScreen(display)),
			 def_val,
			 &bkgnd_color, &color_def)
      );
  else if (reverse &&
	   XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "black",
			      &bkgnd_color, &color_def)
	   );
  else if (XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "white",
			      &bkgnd_color, &color_def)
	   );
  else {}

  def_val = x_get_resource_string ("menuInactivePattern", "MenuInactivePattern");
  if (def_val != NULL) {
    if (strcmp(def_val, "dimple1") == 0) inact_pnum = 0;
    else if (strcmp(def_val, "dimple3") == 0) inact_pnum = 1;
    else if (strcmp(def_val, "gray1") == 0) inact_pnum = 2;
    else if (strcmp(def_val, "gray3") == 0) inact_pnum = 3;
    else if (strcmp(def_val, "cross_weave") == 0) inact_pnum = 4;
  }

  def_val = x_get_resource_string ("paneStyle", "PaneStyle");
  if (def_val != NULL) {
    if (strcmp(def_val, "flush_left") == 0) p_style = LEFT;
    else if (strcmp(def_val, "flush_right") == 0) p_style = RIGHT;
    else if (strcmp(def_val, "center") == 0) p_style = CENTER;
  }

  def_val = x_get_resource_string ("paneFont", "PaneFont");
  if (def_val != NULL) p_fnt_name = def_val;

  def_val = x_get_resource_string ("paneForeground", "PaneForeground");
  if (
      def_val != NULL &&
      DisplayCells(display, DefaultScreen(display)) > 2
      )
    XAllocDisplayColor(display, DefaultColormap(display,
						DefaultScreen(display)),
		       def_val,
		       &p_frg_color, &color_def);

  else if (reverse) XAllocDisplayColor(display,
				       DefaultColormap(display,
						       DefaultScreen(display)),
				       "white",
				       &p_frg_color, &color_def);
  else XAllocDisplayColor(display,
			  DefaultColormap(display, DefaultScreen(display)),
			  "black",
			  &p_frg_color, &color_def);

  def_val = x_get_resource_string ("paneBorder", "PaneBorder");
  if (
      def_val != NULL &&
      DisplayCells(display, DefaultScreen(display)) > 2 &&
      XAllocDisplayColor(display,
			 DefaultColormap(display, DefaultScreen(display)),
			 def_val,
			 &p_bdr_color, &color_def)
      );
  else if (reverse &&
	   XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "white",
			      &p_bdr_color, &color_def)
	   );
  else XAllocDisplayColor(display,
			  DefaultColormap(display, DefaultScreen(display)),
			  "black",
			  &p_bdr_color, &color_def);

  def_val = x_get_resource_string ("paneBorderWidth", "PaneBorderWidth");
  if (def_val != NULL) p_bdr_width = atoi(def_val);

  def_val = x_get_resource_string ("paneSpread", "PaneSpread");
  if (def_val != NULL) p_spread = atof(def_val);

  def_val = x_get_resource_string ("selectionStyle", "SelectionStyle");
  if (def_val != NULL) {
    if (strcmp(def_val, "flush_left") == 0) s_style = LEFT;
    else if (strcmp(def_val, "flush_right") == 0) s_style = RIGHT;
    else if (strcmp(def_val, "center") == 0) s_style = CENTER;
  }

  def_val = x_get_resource_string ("selectionFont", "SelectionFont");
  if (def_val != NULL) s_fnt_name = def_val;

  def_val = x_get_resource_string ("selectionForeground", "SelectionForeground");
  if (
      def_val != NULL &&
      DisplayCells(display, DefaultScreen(display)) > 2 &&
      XAllocDisplayColor(display,
			 DefaultColormap(display, DefaultScreen(display)),
			 def_val,
			 &s_frg_color, &color_def)
      );
  else if (reverse &&
	   XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "white",
			      &s_frg_color, &color_def)
	   ) ;
  else if (XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "black",
			      &s_frg_color, &color_def)
	   ) ;
  else {}


  def_val = x_get_resource_string ("selectionBorder", "SelectionBorder");
  if (
      def_val != NULL &&
      DisplayCells(display, DefaultScreen(display)) > 2 &&
      XAllocDisplayColor(display,
			 DefaultColormap(display, DefaultScreen(display)),
			 def_val,
			 &s_bdr_color, &color_def)
      ) ;
  else if (reverse &&
	   XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "white",
			      &s_bdr_color, &color_def)
	   ) ;
  else if (XAllocDisplayColor(display,
			      DefaultColormap(display, DefaultScreen(display)),
			      "black",
			      &s_bdr_color, &color_def)
	   ) ;
  else {}

  def_val = x_get_resource_string ("selectionBorderWidth", "SelectionBorderWidth");
  if (def_val != NULL) s_bdr_width = atoi(def_val);

  def_val = x_get_resource_string ("selectionSpread", "SelectionSpread");
  if (def_val != NULL) s_spread = atof(def_val);

  /*
   * Create and store the inactive pattern pixmap.
   */
  {
    char *data = NULL;
    int width, height;

    switch (inact_pnum)
      {
      case 0:
	data = (char *)dimple1_bits;
	width = dimple1_width;
	height = dimple1_height;
	break;

      case 1:
	data = (char *)dimple3_bits;
	width = dimple3_width;
	height = dimple3_height;
	break;

      case 2:
	data = (char *)gray1_bits;
	width = gray1_width;
	height = gray1_height;
	break;

      case 3:
	data = (char *)gray3_bits;
	width = gray3_width;
	height = gray3_height;
	break;

      case 4:
	data = (char *)cross_weave_bits;
	width = cross_weave_width;
	height = cross_weave_height;
	break;
      }

    if (! data)
      {
	_XMErrorCode = XME_STORE_BITMAP;
	return(NULL);
      }

    inact_bitmap =
      XCreatePixmapFromBitmapData
	(display, root, data, width, height,
	 p_frg_color.pixel, bkgnd_color.pixel,
	 DisplayPlanes (display, DefaultScreen (display)));
  }

  /*
   * Load the mouse cursor.
   */

  switch (menu_style) {
  case LEFT:
    cursor = XCreateBitmapFromData(display,
				   root,
				   left_ptr_bits,
				   left_ptr_width,
				   left_ptr_height);
    cursor_mask = XCreateBitmapFromData(display,
					root,
					left_ptrmsk_bits,
					left_ptrmsk_width,
					left_ptrmsk_height);
    mouse_cursor = XCreatePixmapCursor(
				       display,
				       cursor, cursor_mask,
				       &mouse_color, &bkgnd_color,
				       left_ptr_x_hot,
				       left_ptr_y_hot
				       );
    XFreePixmap(display, cursor);
    XFreePixmap(display, cursor_mask);
    break;
  case RIGHT:
    cursor = XCreateBitmapFromData(display,
				   root,
				   right_ptr_bits,
				   right_ptr_width,
				   right_ptr_height);
    cursor_mask = XCreateBitmapFromData(display,
					root,
					right_ptrmsk_bits,
					right_ptrmsk_width,
					right_ptrmsk_height);
    mouse_cursor = XCreatePixmapCursor(
				       display,
				       cursor, cursor_mask,
				       &mouse_color, &bkgnd_color,
				       right_ptr_x_hot,
				       right_ptr_y_hot
				       );
    XFreePixmap(display, cursor);
    XFreePixmap(display, cursor_mask);
    break;
  case CENTER:
    cursor = XCreateBitmapFromData(display,
				   root,
				   cntr_ptr_bits,
				   cntr_ptr_width,
				   cntr_ptr_height);
    cursor_mask = XCreateBitmapFromData(display,
					root,
					cntr_ptrmsk_bits,
					cntr_ptrmsk_width,
					cntr_ptrmsk_height);
    mouse_cursor = XCreatePixmapCursor(
				       display,
				       cursor, cursor_mask,
				       &mouse_color, &bkgnd_color,
				       cntr_ptr_x_hot,
				       cntr_ptr_y_hot
				       );
    XFreePixmap(display, cursor);
    XFreePixmap(display, cursor_mask);
    break;
  default:
    /* Error! Invalid style parameter. */
    _XMErrorCode = XME_STYLE_PARAM;
    return(NULL);
  }
  if (mouse_cursor == _X_FAILURE) {
    _XMErrorCode = XME_CREATE_CURSOR;
    return(NULL);
  }

  /*
   * Open the pane and selection fonts.
   */

  p_fnt_info = XLoadQueryFont(display, p_fnt_name);
  if (p_fnt_info == NULL) {
    _XMErrorCode = XME_OPEN_FONT;
    return(NULL);

  }

  s_fnt_info = XLoadQueryFont(display, s_fnt_name);
  if (s_fnt_info == NULL) {
    _XMErrorCode = XME_OPEN_FONT;
    return(NULL);
  }
  /*
   * Calculate the fixed padding value in pixels for each font.
   */
  p_fnt_height = p_fnt_info->max_bounds.ascent + p_fnt_info->max_bounds.descent;
  s_fnt_height = s_fnt_info->max_bounds.ascent + s_fnt_info->max_bounds.descent;
  p_fnt_pad = s_spread * p_fnt_height;
  s_fnt_pad = s_spread * s_fnt_height;

  /*
   * Calculate fixed height and offset requirements.
   */
  flag_height = p_fnt_height + (p_fnt_pad << 1);

  p_height = 0;
  p_y_off = flag_height + p_bdr_width;
  p_x_off = p_y_off * p_spread;

  s_height = s_fnt_height + (s_fnt_pad << 1) + (s_bdr_width << 1);
  s_y_off = s_height;
  s_x_off = p_x_off;

  /*
   * Set up the pane list header.
   */
  pane->next = pane;
  pane->prev = pane;
  pane->type = PL_HEADER;
  pane->serial = -1;

  /*
   * Initialize the internal pane and selection creation queues.
   */
  _XMWinQueInit();

  /*
   * Create pane, active, and inactive GC's.
   */
  values = (XGCValues *)malloc(sizeof(XGCValues));
  valuemask = (GCForeground | GCBackground | GCFont | GCLineWidth);

  /*
   * First, pane.
   */

  values->foreground = p_frg_color.pixel;
  values->background = bkgnd_color.pixel;
  values->font = p_fnt_info->fid;
  values->line_width = p_bdr_width;

  pane_GC = XCreateGC(
		      display,
		      root,
		      valuemask,
		      values);
  /*
   * Then normal video selection.
   */

  values->foreground = s_frg_color.pixel;
  values->background = bkgnd_color.pixel;
  values->font = s_fnt_info->fid;
  values->line_width = s_bdr_width;
  normal_select_GC = XCreateGC(display,
			       root,
			       valuemask,
			       values);
  /*
   * Inverse video selection.
   */

  values->foreground = bkgnd_color.pixel;
  values->background = s_frg_color.pixel;
  values->font = s_fnt_info->fid;
  values->line_width = s_bdr_width;
  inverse_select_GC = XCreateGC(display,
				root,
				valuemask,
				values);
  stipple_pixmap = XCreateBitmapFromData(display,
					 root,
					 stipple_bits,
					 stipple_width,
					 stipple_height);

  /*
   * Finally, inactive pane header and selections
   */
  valuemask |= (GCFillStyle | GCStipple);
  values->foreground = s_frg_color.pixel;
  values->background = bkgnd_color.pixel;
  values->font = s_fnt_info->fid;
  values->line_width = s_bdr_width;
  values->fill_style = FillStippled;
  values->stipple = stipple_pixmap;

  inact_GC = XCreateGC(display,
		       root,
		       valuemask,
		       values);

  valuemask |= (GCGraphicsExposures);
  values->graphics_exposures = False;


  /*
   * Construct the XMenu object.
   */
  /* -------------------- Menu data -------------------- */
  menu->menu_style = menu_style;
  menu->menu_mode = menu_mode;
  menu->freeze = freeze;
  menu->aeq = 0;
  menu->recompute = 1;
  menu->parent = parent;
  menu->height = 0;
  menu->width = 0;
  menu->mouse_cursor = mouse_cursor;
  menu->assoc_tab = assoc_tab;
  menu->p_list = pane;
  /* -------------------- Pane window data -------------------- */
  menu->p_style = p_style;
  menu->p_events = DEF_P_EVENTS;
  menu->p_fnt_info = p_fnt_info;
  menu->p_fnt_pad = p_fnt_pad;
  menu->p_spread = p_spread;
  menu->p_bdr_width = p_bdr_width;
  menu->flag_height = flag_height;
  menu->p_width = 0;
  menu->p_height = p_height;
  menu->p_x_off = p_x_off;
  menu->p_y_off = p_y_off;
  menu->p_count = 0;
  menu->pane_GC = pane_GC;
  menu->x_pos = 0;
  menu->y_pos = 0;
  /* -------------------- Selection window data -------------------- */
  menu->s_style = s_style;
  menu->s_events = DEF_S_EVENTS;
  menu->s_fnt_info = s_fnt_info;
  menu->s_fnt_pad = s_fnt_pad;
  menu->s_spread = s_spread;
  menu->s_bdr_width = s_bdr_width; /* unnecessary */
  menu->s_width = 0;
  menu->s_height = s_height;
  menu->s_x_off = s_x_off;
  menu->s_y_off = s_y_off;
  menu->s_count = 0;
  menu->normal_select_GC = normal_select_GC;
  menu->inverse_select_GC = inverse_select_GC;
  menu->inact_GC = inact_GC;
  /* -------------------- Color data -------------------- */
  menu->p_bdr_color = p_bdr_color.pixel;
  menu->s_bdr_color = s_bdr_color.pixel;
  menu->p_frg_color = p_frg_color.pixel;
  menu->s_frg_color = s_frg_color.pixel;
  menu->bkgnd_color = bkgnd_color.pixel;
  /* -------------------- Pixmap data -------------------- */
  menu->p_bdr_pixmap = None;
  menu->s_bdr_pixmap = None;
  menu->p_frg_pixmap = None;
  menu->s_frg_pixmap = None;
  menu->bkgnd_pixmap = None;
  menu->inact_pixmap = inact_bitmap;

  /*
   * Return the completed XMenu.
   */
  _XMErrorCode = XME_NO_ERROR;
  return(menu);
}
Exemplo n.º 3
0
static void _find_color(Widget w, XColor *target, char *dontuse)
{
Colormap		cm;
XColor			cell_def[256];
double 			cur_dist;
int 			cur_red_dist_index=0;
int 			cur_green_dist_index=0;
int 			cur_blue_dist_index=0;
double 			cur_red_dist;
double 			cur_green_dist;
double 			cur_blue_dist;
double 			dist;
double 			red_dist;
double 			green_dist;
double 			blue_dist;
int    			i;
XColor 			tmp = {0,0,0,0,0,0};
int    			screen;
int    			ncells;
Display 		*d = XtDisplay(w);
XWindowAttributes 	win_att;
int			depth;
Pixel			pix;
unsigned long		red_mask=0;
unsigned long		green_mask=0;
unsigned long		blue_mask=0;
unsigned long		red_mult=0;
unsigned long		green_mult=0;
unsigned long		blue_mult=0;

    screen = XScreenNumberOfScreen(XtScreen(w));
    XtVaGetValues(w, XmNdepth, &depth, NULL);
    if(depth == 8) 
	    ncells = 255;
    else if(depth == 12) 
	    ncells = 16; 
    else
	    ncells = 256;
    if(XtIsRealized(w))
    {
	    XGetWindowAttributes(d, XtWindow(w), &win_att);
	    if(win_att.colormap != 
	        DefaultColormap(XtDisplay(w), screen))
	    {
	        cm = win_att.colormap;
	        red_mask = win_att.visual->red_mask;
	        green_mask = win_att.visual->green_mask;
	        blue_mask = win_att.visual->blue_mask;

	        red_mult = red_mask & (~red_mask+1);
	        green_mult = green_mask & (~green_mask+1);
	        blue_mult = blue_mask & (~blue_mask+1);
	    }
	    else
	    {
	        cm = DefaultColormap(XtDisplay(w), screen);
	    }
    }
    else
    {
	    cm = DefaultColormap(XtDisplay(w), screen);
    }

    for (i = 0; i < ncells; i++)
	{
	    switch(depth)
	        {
	        case 8:
		    cell_def[i].pixel = i;
		    break;
	        case 12:
		    pix = i;
		    cell_def[i].pixel = 
		        (pix * red_mult) + 
		        (pix * green_mult) + 
		        (pix * blue_mult);
		    break;
	        default:
		    pix = i;
		    cell_def[i].pixel = 
		        (pix * red_mult) | 
		        (pix * green_mult) | 
		        (pix * blue_mult);
		    break;
	        }
	    cell_def[i].flags = DoRed | DoGreen | DoBlue;
	}

    XQueryColors(d, cm, cell_def, ncells);

    cur_dist = sqrt((double)((double)65535*(double)65535*(double)65535));
    cur_red_dist = cur_green_dist = cur_blue_dist = 65535.0*65535.0;
    for (i = 0; i < ncells; i++)
	{
	red_dist = (double)(target->red - cell_def[i].red) * 
	      	   (double)(target->red - cell_def[i].red);
	green_dist = (double)(target->green - cell_def[i].green) * 
	      	     (double)(target->green - cell_def[i].green);
	blue_dist = (double)(target->blue - cell_def[i].blue) * 
	      	    (double)(target->blue - cell_def[i].blue);
		    
	switch(depth)
	    {
	    Boolean ok2use;
	    case 8:
		dist = sqrt(red_dist + green_dist + blue_dist);
		if (!dontuse) ok2use = True;
		else ok2use = (dontuse[cell_def[i].pixel] == 0);
		if ((dist < cur_dist) && (ok2use))
		    {
		    cur_dist = dist;
		    tmp.red = cell_def[i].red;
		    tmp.green = cell_def[i].green;
		    tmp.blue = cell_def[i].blue;
		    tmp.pixel = cell_def[i].pixel;
		    }
		break;
	    default:
		if(red_dist < cur_red_dist)
		    {
		    cur_red_dist = red_dist;
		    cur_red_dist_index = i;
		    }
		if(green_dist < cur_green_dist)
		    {
		    cur_green_dist = green_dist;
		    cur_green_dist_index = i;
		    }
		if(blue_dist < cur_blue_dist)
		    {
		    cur_blue_dist = blue_dist;
		    cur_blue_dist_index = i;
		    }
		break;
	    }
	}
    switch(depth)
	{
	case 8:
	    target->red = tmp.red;
        target->green = tmp.green;
        target->blue = tmp.blue;
        target->pixel = tmp.pixel;
        target->flags = tmp.flags;
        target->pad = tmp.pad;
	    break;
	default:
	    pix = (cell_def[cur_red_dist_index].pixel & red_mask) |
		  (cell_def[cur_green_dist_index].pixel & green_mask) |
		  (cell_def[cur_blue_dist_index].pixel & blue_mask);
	    target->pixel = pix;
	    target->red = cell_def[cur_red_dist_index].red; 
	    target->green = cell_def[cur_green_dist_index].green; 
	    target->blue = cell_def[cur_blue_dist_index].blue; 
	    break;
	}
}
Exemplo n.º 4
0
static Status
lookup(Display *dpy, int screen, VisualID visualid, Atom property,
       XStandardColormap *cnew, Bool replace)
     /*
      * dpy		- specifies display connection
      * screen		- specifies screen number
      * visualid	- specifies visualid for std map
      * property	- specifies colormap property name
      * cnew		- specifies a standard colormap
      * replace		- specifies whether to replace
      */
{
    register int	i;
    int			count;
    XStandardColormap	*stdcmaps, *s;
    Window		win = RootWindow(dpy, screen);

    /* The property does not already exist */

    if (! XGetRGBColormaps(dpy, win, &stdcmaps, &count, property)) {
	if (cnew)
	    XSetRGBColormaps(dpy, win, cnew, 1, property);
	return 0;
    }

    /* The property exists and is not describing the RGB_DEFAULT_MAP */

    if (property != XA_RGB_DEFAULT_MAP) {
	if (replace) {
	    XmuDeleteStandardColormap(dpy, screen, property);
	    if (cnew)
		XSetRGBColormaps(dpy, win, cnew, 1, property);
	}
	XFree((char *)stdcmaps);
	return 1;
    }

    /* The property exists and is RGB_DEFAULT_MAP */

    for (i=0, s=stdcmaps; (i < count) && (s->visualid != visualid); i++, s++)
	;

    /* No RGB_DEFAULT_MAP property matches the given visualid */

    if (i == count) {
	if (cnew) {
	    XStandardColormap	*m, *maps;

	    s = (XStandardColormap *) malloc((unsigned) ((count+1) * sizeof
					      (XStandardColormap)));

	    for (i = 0, m = s, maps = stdcmaps; i < count; i++, m++, maps++) {
		m->colormap   = maps->colormap;
		m->red_max    = maps->red_max;
		m->red_mult   = maps->red_mult;
		m->green_max  = maps->green_max;
		m->green_mult = maps->green_mult;
		m->blue_max   = maps->blue_max;
		m->blue_mult  = maps->blue_mult;
		m->base_pixel = maps->base_pixel;
		m->visualid   = maps->visualid;
		m->killid     = maps->killid;
	    }
	    m->colormap   = cnew->colormap;
	    m->red_max    = cnew->red_max;
	    m->red_mult   = cnew->red_mult;
	    m->green_max  = cnew->green_max;
	    m->green_mult = cnew->green_mult;
	    m->blue_max   = cnew->blue_max;
	    m->blue_mult  = cnew->blue_mult;
	    m->base_pixel = cnew->base_pixel;
	    m->visualid   = cnew->visualid;
	    m->killid     = cnew->killid;

	    XSetRGBColormaps(dpy, win, s, ++count, property);
	    free((char *) s);
	}
	XFree((char *) stdcmaps);
	return 0;
    }

    /* Found an RGB_DEFAULT_MAP property with a matching visualid */

    if (replace) {
	/* Free old resources first - we may need them, particularly in
	 * the default colormap of the screen.  However, because of this,
	 * it is possible that we will destroy the old resource and fail
	 * to create a new one if XmuStandardColormap() fails.
	 */

	if (count == 1) {
	    XmuDeleteStandardColormap(dpy, screen, property);
	    if (cnew)
		XSetRGBColormaps(dpy, win, cnew, 1, property);
	}
	else {
	    XStandardColormap	*map;

	    /* s still points to the matching standard colormap */

	    if (s->killid == ReleaseByFreeingColormap) {
		if ((s->colormap != None) &&
		    (s->colormap != DefaultColormap(dpy, screen)))
		    XFreeColormap(dpy, s->colormap);
	    }
	    else if (s->killid != None)
		XKillClient(dpy, s->killid);

	    map = (cnew) ? cnew : stdcmaps + --count;

	    s->colormap   = map->colormap;
	    s->red_max    = map->red_max;
	    s->red_mult   = map->red_mult;
	    s->green_max  = map->green_max;
	    s->green_mult = map->green_mult;
	    s->blue_max   = map->blue_max;
	    s->blue_mult  = map->blue_mult;
	    s->visualid   = map->visualid;
	    s->killid     = map->killid;

	    XSetRGBColormaps(dpy, win, stdcmaps, count, property);
	}
    }
    XFree((char *) stdcmaps);
    return 1;
}
Exemplo n.º 5
0
int XAbstractGui::SetColors(Display *dpy)
{
    int screen;
    XcmsColor xcolor;
    XcmsColor exact;
    int i, scale;
    int rw_color;   /* is it a read/write color ?*/
    int visualClass;
    unsigned long pixels[1 << COLOR_PLANES];

    screen = DefaultScreen(dpy);
    visual = GetBestVisual(dpy, &visualClass, &depth);

    if (!visual)
    {
        fprintf(stderr, "Unable to find an appropriate visual\n");
        return 0;
    }

    rw_color = (visualClass == DirectColor || visualClass == PseudoColor ||
                visualClass == GrayScale);
    cmap = DefaultColormap(dpy, screen);

    if (rw_color)
    {
        /* on visuals with read/write color cells
           first allocate them */
        if (!XAllocColorCells(dpy, cmap, False, nullptr, 0, pixels,
                              1 << COLOR_PLANES))
        {
            /* try again with a own colormap */
            cmap = XCreateColormap(dpy,
                                   RootWindow(dpy, screen),
                                   visual, AllocNone);
            own_cmap = 1;

            if (!XAllocColorCells(dpy, cmap, False, nullptr, 0,
                                  pixels, 1 << COLOR_PLANES))
            {
                fprintf(stderr, "Unable to allocate %d colors\n",
                        1 << COLOR_PLANES);
                return 0; /* failed even with own colormap */
            }
        }
    }

    if (!XcmsLookupColor(dpy, cmap, color.c_str(), &xcolor, &exact,
                         XcmsRGBiFormat))
    {
        exact.spec.RGBi.blue  = 1.0;
        exact.spec.RGBi.red   = 1.0;
        exact.spec.RGBi.green = 1.0;
    }

    xcolor.format = XcmsRGBiFormat;

    for (i = 0; i < (1 << COLOR_PLANES); i++)
    {
        if (withColorScale)
        {
            // DEPENDANCIES:
            // the color plane masks used here depend on
            // the same masks used in CopyToZPixmap
            scale  = i & 0x20 ? 2 : 0;
            scale |= i & 0x04 ? 1 : 0;
            xcolor.spec.RGBi.green = 1.0 * scale / 3;
            scale  = i & 0x10 ? 2 : 0;
            scale |= i & 0x02 ? 1 : 0;
            xcolor.spec.RGBi.red   = 1.0 * scale / 3;
            scale  = i & 0x08 ? 2 : 0;
            scale |= i & 0x01 ? 1 : 0;
            xcolor.spec.RGBi.blue  = 1.0 * scale / 3;
        }
        else
        {
            xcolor.spec.RGBi.blue  =
                exact.spec.RGBi.blue  * i / (1 << COLOR_PLANES);
            xcolor.spec.RGBi.red   =
                exact.spec.RGBi.red   * i / (1 << COLOR_PLANES);
            xcolor.spec.RGBi.green =
                exact.spec.RGBi.green * i / (1 << COLOR_PLANES);
        }

        if (rw_color)
        {
            xcolor.pixel = pixels[i];

            if (XcmsStoreColor(dpy, cmap,
                               &xcolor) == XcmsFailure)
            {
                fprintf(stderr, "Error storing a color\n");
                return 0;
            }
        }
        else
        {
            if (XcmsAllocColor(dpy, cmap,
                               &xcolor, XcmsRGBiFormat) == XcmsFailure)
            {
                fprintf(stderr, "Error allocating a color\n");
                return 0;
            }
        }

        pens[i] = xcolor.pixel;
    }

    //gcVal.plane_mask = 0xFFFFFFFF;

    return 1;
}
Exemplo n.º 6
0
void
Tk_DrawChars(
    Display *display,		/* Display on which to draw. */
    Drawable drawable,		/* Window or pixmap in which to draw. */
    GC gc,			/* Graphics context for drawing characters. */
    Tk_Font tkfont,		/* Font in which characters will be drawn;
				 * must be the same as font used in GC. */
    CONST char *source,		/* UTF-8 string to be displayed. Need not be
				 * '\0' terminated. All Tk meta-characters
				 * (tabs, control characters, and newlines)
				 * should be stripped out of the string that
				 * is passed to this function. If they are not
				 * stripped out, they will be displayed as
				 * regular printing characters. */
    int numBytes,		/* Number of bytes in string. */
    int x, int y)		/* Coordinates at which to place origin of
				 * string when drawing. */
{
    const int maxCoord = 0x7FFF;/* Xft coordinates are 16 bit values */
    UnixFtFont *fontPtr = (UnixFtFont *) tkfont;
    XGCValues values;
    XColor xcolor;
    int clen, nspec;
    XftGlyphFontSpec specs[NUM_SPEC];
    XGlyphInfo metrics;

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

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

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

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

	ftFont = GetFont(fontPtr, c);
	if (ftFont) {
	    specs[nspec].font = ftFont;
	    specs[nspec].glyph = XftCharIndex(fontPtr->display, ftFont, c);
	    specs[nspec].x = x;
	    specs[nspec].y = y;
	    XftGlyphExtents(fontPtr->display, ftFont, &specs[nspec].glyph, 1,
		    &metrics);
	    x += metrics.xOff;
	    y += metrics.yOff;
	    nspec++;
	    if (nspec == NUM_SPEC) {
		XftDrawGlyphFontSpec(fontPtr->ftDraw, &fontPtr->color,
			specs, nspec);
		nspec = 0;
	    }
	}
    }
    if (nspec) {
	XftDrawGlyphFontSpec(fontPtr->ftDraw, &fontPtr->color, specs, nspec);
    }
}
Exemplo n.º 7
0
void
initializeWindowSystem(void)
{
    char *display_name = NULL;
    XColor fg, bg;
#if 0
    XColor rgbdef;
#endif
    Colormap cmap;
    Pixmap  mousebits, mousemask;
/*    fprintf(stderr,"initx:initializeWindowSystem:entered\n");*/
    /* Try to open the display */
/*    fprintf(stderr,"initx:initializeWindowSystem:XOpenDisplay\n");*/
    if ((gXDisplay = XOpenDisplay(display_name)) == NULL) {
        fprintf(stderr, "(HyperDoc) Cannot connect to the X11 server!\n");
        exit(-1);
    }

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

    /* Get the cursors we need. */

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

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

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

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

    /* Now initialize all the colors and fonts */

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

}
Exemplo n.º 8
0
int main()
{
#ifdef TEST_FOR_X
	Display		*display;
	Window		window;
	GC		gc;
	XGCValues	gcValues;
	Colormap	colormap;
	Pixmap		src_pixmap;
	unsigned long	fgColor, bgColor;
	int		screenNum;
	XPoint		points[NUM_POINTS];
#else
	GR_WINDOW_ID 	window;
	GR_WINDOW_ID	src_pixmap;
	unsigned char*	src_pixmap_buf[320*240*2];
	GR_GC_ID        gc;
	GR_POINT	points[NUM_POINTS];
#endif
	
	int		c, c1,  count=4500;
	int		x, y, x1, y1, x2, y2;

#ifdef TEST_FOR_X
	if(!(display=XOpenDisplay(""))) {
		printf("Cannot connect to X.\n");
	}
	screenNum = DefaultScreen(display);
	colormap = DefaultColormap(display, screenNum);

	bgColor = BlackPixel(display, screenNum);
	fgColor = WhitePixel(display, screenNum);
	window = XCreateSimpleWindow(display, RootWindow(display, screenNum),
		0, 0 , 639, 479, 0,
		fgColor, bgColor);
	src_pixmap = XCreatePixmap(display, window, 320, 240, 16);
	XMapRaised(display, window);
	gcValues.background = bgColor;
	gcValues.foreground = fgColor;
	gcValues.line_width = 1;
	gcValues.line_style = LineSolid;
	gcValues.fill_style = FillSolid;
	gcValues.fill_rule = WindingRule;
	gcValues.arc_mode = ArcPieSlice;
	gc = XCreateGC(display, window,
		GCForeground  | GCBackground | GCLineWidth | GCLineStyle |
		GCFillStyle,
		&gcValues);

#else	
	GrOpen();
	window = GrNewWindow(GR_ROOT_WINDOW_ID, 0, 0, 639, 479, 0, BLACK, BLUE);
	src_pixmap = GrNewPixmap(640, 480, src_pixmap_buf);
	GrMapWindow(window);
	gc = GrNewGC();
        GrSetGCForeground(gc, WHITE);
	GrSetGCBackground(gc, BLACK);
	GrSetGCMode(gc, GR_MODE_COPY);
#endif




	
	// Horizontal Line
	////////////////////////////////////////////////
	printf("Horizontal Line(XDrawLine)\n");
	start_timer();
	for(c=0; c<count*20; c++)
	{
		y1=random()%480;
#ifdef TEST_FOR_X
		XDrawLine(display, window, gc, 0, y1, 639, y1);
		XFlush(display);
#else
		GrLine(window, gc, 0, y1, 639, y1);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X
	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif
	
	// Vertical Line
	/////////////////////////////////////////////////
	printf("Vertical Line(XDrawLine)\n");
	start_timer();
	for(c=0; c<count*19; c++)
	{
		x1=random()%640;
#ifdef TEST_FOR_X
		XDrawLine(display, window, gc, x1, 0, x1, 479);
		XFlush(display);
#else
		GrLine(window, gc, x1, 0, x1, 479);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X
	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif

	// General Line
	/////////////////////////////////////////////////
	printf("General Line(XDrawLine)\n");
	start_timer();
	for(c=0; c<count*22; c++)
	{
		x1 = random()%640;
		x2 = random()%640;
		y1 = random()%480;
		y2 = random()%480;
#ifdef TEST_FOR_X
		XDrawLine(display, window, gc, x1, y1, x2, y2);
		XFlush(display);
#else
		GrLine(window, gc, x1, y1, x2, y2);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X
	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif

	// Point
	//////////////////////////////////////////////////
	printf("XPoint\n");
	start_timer();
	for(c=0; c<count*25; c++)
	{
		x1 = random()%640;
		y1 = random()%480;
#ifdef TEST_FOR_X
		XDrawPoint(display, window, gc, x1, y1);
		XFlush(display);
#else
		GrPoint(window, gc, x1, y1);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X
	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif

	// Rectangle
	//////////////////////////////////////////////////
	printf("XRectangle\n");
	start_timer();
	for(c=0; c<count*20; c++)
	{
		x1=random()%639;
		y1=random()%479;
		x2=random()%(639-x1)+1;
		y2=random()%(479-y1)+1;
#ifdef TEST_FOR_X
		XDrawRectangle(display, window, gc, x1, y1, x2, y2);
		XFlush(display);
#else
		GrRect(window, gc, x1, y1, x2, y2);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X
	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif

	// FillRectangle
	//////////////////////////////////////////////////
	printf("XFillRectangle\n");
	start_timer();
	for(c=0; c<count*18; c++)
	{
		x1=random()%639;
		y1=random()%479;
		x2=random()%(639-x1)+1;
		y2=random()%(479-y1)+1;	
#ifdef TEST_FOR_X
		XFillRectangle(display, window, gc, x1, y1, x2, y2);
		XFlush(display);
#else
		GrFillRect(window, gc, x1, y1, x2, y2);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X

	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif

	// FillPolygon
	//////////////////////////////////////////////////
	printf("XFillPolygon\n");
	start_timer();
	for(c=0; c<count; c++)
	{
		for(c1=0; c1<NUM_POINTS; c1++)
		{
			points[c1].x = random()%640;
			points[c1].y = random()%480;
		}	
#ifdef TEST_FOR_X
		XFillPolygon(display, window, gc, points, NUM_POINTS,
			0, 0);
		XFlush(display);
#else
		GrFillPoly(window, gc, NUM_POINTS, points);
		GrFlush();
#endif
	}
	end_timer();
#ifdef TEST_FOR_X
	XClearWindow(display, window);
#else
	GrClearWindow(window, GR_TRUE);
#endif


	// CopyArea
	/////////////////////////////////////////////////
	printf("XCopyArea\n");
	start_timer();
	for(c=0; c<count*5; c++)
	{
		x1=random()%320;
		y1=random()%240;
		x2=random()%319+1;
		y2=random()%239+1;
		
#ifdef TEST_FOR_X
		XCopyArea(display, src_pixmap, window, gc,
			0, 0, x2, y2, x1, y1);
		XFlush(display);
#else
		GrCopyArea(window, gc, x1, y1, x2 ,y2, src_pixmap,
			0, 0, 0);
		GrFlush();
#endif
	}
	end_timer();	

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

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

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

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

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

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

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

    // Setup timer for animation
    signal(SIGALRM, sigalarm_handler);
    struct itimerval timer;
    timer.it_value.tv_sec = time_step/1000;
    timer.it_value.tv_usec = (time_step % 1000) * 1000;
    timer.it_interval = timer.it_value;
    setitimer(ITIMER_REAL, &timer, NULL);
}
Exemplo n.º 10
0
int main (int argc, char **argv) {
	Cursor cursor;
	Display *display;
	Window root, blub, *blubs = NULL;
	unsigned clients;
	unsigned long pixel;
	char *cname;
	XColor color;
	int cnt;
	Atom prop;
	Pixmap save_pixmap = (Pixmap)None;

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

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

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

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

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

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

		display = XOpenDisplay(NULL);

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

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

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

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

	RunWindowManager();
	return 0;
}
Exemplo n.º 11
0
int Init_X (int swidth, int sheight)
{
    XGCValues vals;
    Colormap TheColormap;
    XColor TheColor;
    int i;

    TheWidth = swidth ;
    TheHeight = sheight ;


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

    if (!TheWindow) return 0 ;

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

    if (!ThePixmap) return 0 ;

    TheDrawable = ThePixmap;

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




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




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

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


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


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

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




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


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

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

    Copy_Buffer_X() ;
    XFlush(TheDisplay);  

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

    Set_Color_Rgb_X (0,0,0) ; // black pencil
    return 1 ;
}
Exemplo n.º 12
0
XImage *
read_ppm_file(Display *disp, Colormap cmap, int depth, IOSTREAM *fd)
{ XImage *img;
  long here = Stell(fd);
  int c;
  int fmt, encoding;
  int width, height, bytes_per_line, scale=0;
  char *data;
  int allocdepth;
  int pad = XBitmapPad(disp);
  Visual *v = DefaultVisual(disp, DefaultScreen(disp));

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

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

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

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

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

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

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

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

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

  switch(encoding)
  { int x, y;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	  break;
	}
      }
    }
  }

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

  return img;

errout:
  DEBUG(NAME_ppm,
	Cprintf("PNM: Format error, index = %d\n", Stell(fd)));
  Sseek(fd, here, SEEK_SET);
  return NULL;
}
Exemplo n.º 13
0
stk_widget *stk_progress_bar_new(stk_widget *parent_win, int x, int y, uint w, uint h, char *label)
{
    stk_widget *new_pb  = (stk_widget*) malloc(sizeof(stk_widget));
    stk_progress_bar *pb  = (stk_progress_bar*) malloc(sizeof(stk_progress_bar));
    int screen;

    XGCValues gcval;
    long fg, bg;
    
    memset(new_pb, 0, sizeof(stk_widget));
    
    new_pb->dsp = display;
    new_pb->fontname = "7x13";

    screen = DefaultScreen(new_pb->dsp);
    fg = BlackPixel(new_pb->dsp, screen);
    bg = WhitePixel(new_pb->dsp, screen);
    
    gcval.foreground = fg;
    gcval.background = bg;

    new_pb->gc2 = XCreateGC(new_pb->dsp, parent_win->win, GCForeground |
                                                  GCBackground, &gcval);

    if(new_pb->dsp)
    {
        new_pb->win = XCreateSimpleWindow(new_pb->dsp, parent_win->win, x, y, w,
                                                                  h, 1, fg, bg);
        new_pb->gc = XCreateGC(new_pb->dsp, new_pb->win, 0, 0);
        new_pb->font_info = XLoadQueryFont(new_pb->dsp, new_pb->fontname);

        if(new_pb->fontname != NULL)
            XSetFont(display, new_pb->gc2, new_pb->font_info->fid);
        else
            perror("XLoadQueryFont");

        new_pb->mask =  ExposureMask | EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask;

        XSelectInput(new_pb->dsp, new_pb->win, new_pb->mask);
        


        if(DisplayPlanes(new_pb->dsp, screen) != 1)
        {
            pb->cmap = DefaultColormap(new_pb->dsp, screen);
            if(XAllocNamedColor(new_pb->dsp, pb->cmap, "red", &pb->color, &pb->colorrgb))
                    XSetForeground(new_pb->dsp, new_pb->gc, pb->color.pixel);
        }

        XMapWindow(new_pb->dsp, new_pb->win);

        memset(pb, 0, sizeof(stk_progress_bar));

        new_pb->x = x;
        new_pb->y = y;
        new_pb->w = w;
        new_pb->h = h;

        new_pb->handler = &stk_progress_bar_handle;
        pb->pct = 0;
        new_pb->ext_struct = (void*)pb;


        if(label)
            strcpy(pb->label, label);
        else
            new_pb->label = NULL;

        stk_widget_insert((void*)new_pb); 

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

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

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

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

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

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

    /* getopt */
    int c = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	if (incr) {
	    float avg;
	    avg = (float)(to[0]+to[1]+to[2])/3;
	    rv = avg + (float)(to[0]/2);
	    gv = avg + (float)(to[1]/2);
	    bv = avg + (float)(to[2]/2);
	} else {
            float avg;
	    avg = (float)(from[0]+from[1]+from[2])/3;
	    rv = avg + (float)(from[0]/2);
	    gv = avg + (float)(from[1]/2);
	    bv = avg + (float)(from[2]/2);
	}
	color.red = (unsigned short)(rv>65535.0 ? 65535.0:rv);
    color.green = (unsigned short)(gv>65535.0 ? 65535.0:gv);
	color.blue = (unsigned short)(bv>65535.0 ? 65535.0:bv);
	if (XAllocColor(dpy, DefaultColormap(dpy, DefaultScreen(dpy)),
			&color))
	  *light = color.pixel;
	else
	  *light = colors[incr ? maxcols-1 : 0];
    } else {
	*light = colors[incr ? maxcols-1 : 0];
	*dark = colors[incr ? 0 : maxcols-1];
    }
    return 1;
}
Exemplo n.º 16
0
Pixmap
Tk_GetPixmap(
    Display *display,
    Drawable d,
    int width,
    int height,
    int depth)
{
    TkWinDrawable *newTwdPtr, *twdPtr;
    int planes;
    Screen *screen;

    display->request++;

    newTwdPtr = ckalloc(sizeof(TkWinDrawable));
    newTwdPtr->type = TWD_BITMAP;
    newTwdPtr->bitmap.depth = depth;
    twdPtr = (TkWinDrawable *) d;
    if (twdPtr->type != TWD_BITMAP) {
	if (twdPtr->window.winPtr == NULL) {
	    newTwdPtr->bitmap.colormap = DefaultColormap(display,
		    DefaultScreen(display));
	} else {
	    newTwdPtr->bitmap.colormap = twdPtr->window.winPtr->atts.colormap;
	}
    } else {
	newTwdPtr->bitmap.colormap = twdPtr->bitmap.colormap;
    }
    screen = &display->screens[0];
    planes = 1;
    if (depth == screen->root_depth) {
	planes = PTR2INT(screen->ext_data);
	depth /= planes;
    }
    newTwdPtr->bitmap.handle =
	    CreateBitmap(width, height, (DWORD) planes, (DWORD) depth, NULL);

    /*
     * CreateBitmap tries to use memory on the graphics card. If it fails,
     * call CreateDIBSection which uses real memory; slower, but at least
     * still works. [Bug 2080533]
     */

    if (newTwdPtr->bitmap.handle == NULL) {
	static int repeatError = 0;
	void *bits = NULL;
	BITMAPINFO bitmapInfo;
	HDC dc;

	memset(&bitmapInfo, 0, sizeof(bitmapInfo));
	bitmapInfo.bmiHeader.biSize = sizeof(bitmapInfo.bmiHeader);
	bitmapInfo.bmiHeader.biWidth = width;
	bitmapInfo.bmiHeader.biHeight = height;
	bitmapInfo.bmiHeader.biPlanes = planes;
	bitmapInfo.bmiHeader.biBitCount = depth;
	bitmapInfo.bmiHeader.biCompression = BI_RGB;
	bitmapInfo.bmiHeader.biSizeImage = 0;
	dc = GetDC(NULL);
	newTwdPtr->bitmap.handle = CreateDIBSection(dc, &bitmapInfo,
		DIB_RGB_COLORS, &bits, 0, 0);
	ReleaseDC(NULL, dc);

	/*
	 * Oh no! Things are still going wrong. Pop up a warning message here
	 * (because things will probably crash soon) which will encourage
	 * people to report this as a bug...
	 */

	if (newTwdPtr->bitmap.handle == NULL && !repeatError) {
	    LPVOID lpMsgBuf;

	    repeatError = 1;
	    if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		    FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
		    NULL, GetLastError(),
		    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		    (LPSTR) &lpMsgBuf, 0, NULL)) {
		MessageBoxA(NULL, (LPCSTR) lpMsgBuf,
			"Tk_GetPixmap: Error from CreateDIBSection",
			MB_OK | MB_ICONINFORMATION);
		LocalFree(lpMsgBuf);
	    }
	}
    }

    if (newTwdPtr->bitmap.handle == NULL) {
	ckfree(newTwdPtr);
	return None;
    }

    return (Pixmap) newTwdPtr;
}
Exemplo n.º 17
0
int InitX() {
  XColor    xColor;
  Colormap  colormap;

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

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

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

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

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

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

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

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

  XGCValues    values;
  XFontStruct *font;

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

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

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

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

  return 0;
}
Exemplo n.º 18
0
Colormap InitColorTableFixed(Colormap cmap)
{
    int n_colors = xwa.visual->map_entries;
    int r, g, b, y, i;

    switch (xwa.visual->class) {
    case StaticGray:
    case GrayScale:
	/* determine how many levels of gray we can actually get */
	y = try_get_grays(cmap, n_colors);
	if (y > 2 && y < n_colors)
	    y = try_get_grays(cmap, y);
	if (y < 2)
	    G_fatal_error(_("Unable to get sufficient gray shades."));

	NCOLORS = y;

	for (i = 0; i < 256; i++)
	    Gray[i] = i * y / 256;

	break;

    case StaticColor:
    case PseudoColor:
	/* determine how many levels of r, g, and b are possible */
	get_max_levels(n_colors, &r, &g, &b);

	/* now see how many we can actually get */
	while (!try_get_colors(cmap, r, g, b))
	    if (!get_fewer_levels(&r, &g, &b))
		G_fatal_error(_("Unable to get sufficient colors."));

	NCOLORS = r * g * b;

	for (i = 0; i < 256; i++) {
	    Red[i] = (i * r / 256) * g * b;
	    Grn[i] = (i * g / 256) * b;
	    Blu[i] = (i * b / 256);
	}

	break;

    case DirectColor:
	G_warning(_("Using private colormap for DirectColor visual."));

	/* free any previously-allocated Colormap */
	if (cmap != DefaultColormap(dpy, scrn))
	    XFreeColormap(dpy, cmap);

	/* get shift factors for R,G,B masks */
	NCOLORS = get_rgb_shifts();

	/* create colormap (emulates TrueColor visual) */
	cmap = ramp_colormap();
	break;

    case TrueColor:
	/* get shift factors for R,G,B masks */
	NCOLORS = get_rgb_shifts();
	break;

    default:
	G_fatal_error(_("Unknown visual class [%d]."), xwa.visual->class);
	break;
    }

    return cmap;
}
Exemplo n.º 19
0
void setup_gui_colors() 
{
  XColor kolor,unused;
  int *depths, num_depths;

  display = XtDisplay(shell);
  window = XtWindow(shell);

  if((depths = XListDepths(display, XScreenNumberOfScreen(XtScreen(shell)), 
               &num_depths))==NULL) {
      printf("XListDepths() failed.\n");
      exit(0);
  }

  cmap = DefaultColormap(display, 0); 

  XAllocNamedColor(display,cmap,"black",&kolor,&unused);
  black_color = kolor.pixel;

  XAllocNamedColor(display,cmap,"white",&kolor,&unused);
  white_color = kolor.pixel;

  XAllocNamedColor(display,cmap,"lawngreen",&kolor,&unused);
  green_color = kolor.pixel;

  XAllocNamedColor(display,cmap,"red",&kolor,&unused);
  red_color = kolor.pixel;

  XAllocNamedColor(display,cmap,"blue",&kolor,&unused);
  blue_color = kolor.pixel;

  XAllocNamedColor(display,cmap,"grey",&kolor,&unused);
  grey_color = kolor.pixel;

  XAllocNamedColor(display,cmap,"yellow",&kolor,&unused);
  yellow_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"orange",&kolor,&unused);
  orange_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"magenta",&kolor,&unused);
  magenta_color = kolor.pixel;  
  
  XAllocNamedColor(display,cmap,"cyan",&kolor,&unused);
  cyan_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"brown",&kolor,&unused);
  brown_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"light grey",&kolor,&unused);
  light_grey_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"snow",&kolor,&unused);
  snow_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"indian red",&kolor,&unused);
  indian_red_color = kolor.pixel;
  
  XAllocNamedColor(display,cmap,"ghost white",&kolor,&unused);
  ghost_white_color = kolor.pixel;
  
  gcv.foreground = white_color;
  gcv.background = black_color;
  gcv.graphics_exposures = FALSE;
  gc = XCreateGC(display, window, GCBackground|GCForeground|GCGraphicsExposures, &gcv);
  
}
Exemplo n.º 20
0
XSilChessWindow::XSilChessWindow(XtAppContext app, Widget toplevel,
                                 Visual * vsl, int vsldepth, Colormap cmap)
{
	char tmp[512];
	Arg al[10];
	int i;
	XmString xms;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// Update all
	UpdateStatusBar();
	UpdateMovesList();
	UpdateView();
	UpdateDepthMenu();
}
Exemplo n.º 21
0
static void
ingItColors_and_fonts(void)
{
    char property[256];
    char *prop = &property[0];
    char *str_type[50];
    XrmValue value;
    Colormap cmap;
    int ts;

    /** get the color map for the display **/
/*    fprintf(stderr,"initx:ingItColors_and_fonts:entered\n");*/

/*    fprintf(stderr,"initx:ingItColors_and_fonts:DefaultColorMap\n");*/
    cmap = DefaultColormap(gXDisplay, gXScreenNumber);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:init_group_stack\n");*/
    init_group_stack();


    /** then start getting the fonts **/

/*    fprintf(stderr,"initx:ingItColors_and_fonts:mergeDatabases\n");*/
    mergeDatabases();

/*    fprintf(stderr,"initx:ingItColors_and_fonts:XrmGetResource\n");*/
    if (XrmGetResource(rDB, "Axiom.hyperdoc.RmFont",
                            "Axiom.hyperdoc.Font", str_type, &value) == True)
        (void) strncpy(prop, value.addr, (int) value.size);
    else
        (void) strcpy(prop, RmFontDefault);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 1\n");*/
    load_font(&gRmFont, prop);
/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 2\n");*/
    load_font(&gInputFont, prop);


/*    fprintf(stderr,"initx:ingItColors_and_fonts:XrmGetResource 2\n");*/
    if (XrmGetResource(rDB, "Axiom.hyperdoc.TtFont",
                            "Axiom.hyperdoc.Font", str_type, &value) == True)
        (void) strncpy(prop, value.addr, (int) value.size);
    else
        (void) strcpy(prop, TtFontDefault);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 3\n");*/
    load_font(&gTtFont, prop);
/*    fprintf(stderr,"initx:ingItColors_and_fonts:is_it_850\n");*/
    gTtFontIs850=is_it_850(gTtFont);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:XrmGetResource 5\n");*/
    if (XrmGetResource(rDB, "Axiom.hyperdoc.ActiveFont",
                            "Axiom.hyperdoc.Font", str_type, &value) == True)
        (void) strncpy(prop, value.addr, (int) value.size);
    else
        (void) strcpy(prop, ActiveFontDefault);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 4\n");*/
    load_font(&gActiveFont, prop);

    /* maintain backwards compatibility */

/*    fprintf(stderr,"initx:ingItColors_and_fonts:XrmGetResource 6\n");*/
    if (XrmGetResource(rDB, "Axiom.hyperdoc.AxiomFont",
                            "Axiom.hyperdoc.Font", str_type, &value) == True)
        (void) strncpy(prop, value.addr, (int) value.size);
    else {
        if (XrmGetResource(rDB, "Axiom.hyperdoc.SpadFont",
                           "Axiom.hyperdoc.Font", str_type, &value) == True)
        {
            (void) strncpy(prop, value.addr, (int) value.size);
        }
        else {
            (void) strcpy(prop, fricas_font_default);
        }
    }

/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 5\n");*/
    load_font(&fricas_font, prop);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:XrmGetResource 7\n");*/
    if (XrmGetResource(rDB, "Axiom.hyperdoc.EmphasizeFont",
                            "Axiom.hyperdoc.Font", str_type, &value) == True)
    {
        (void) strncpy(prop, value.addr, (int) value.size);
    }
    else {
        (void) strcpy(prop, EmphasizeFontDefault);
    }
/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 6\n");*/
    load_font(&gEmFont, prop);

/*    fprintf(stderr,"initx:ingItColors_and_fonts:XrmGetResource 8\n");*/
    if (XrmGetResource(rDB, "Axiom.hyperdoc.BoldFont",
                            "Axiom.hyperdoc.Font", str_type, &value) == True)
    {
        (void) strncpy(prop, value.addr, (int) value.size);
    }
    else {
        (void) strcpy(prop, BoldFontDefault);
    }
/*    fprintf(stderr,"initx:ingItColors_and_fonts:load_font 7\n");*/
    load_font(&gBfFont, prop);


    /*
     * If we are on a monochrome screen, then we ignore user preferences, and
     * set the foreground and background as I wish
     */

/*    fprintf(stderr,"initx:ingItColors_and_fonts:DisplayPlanes\n");*/
    if (DisplayPlanes(gXDisplay, gXScreenNumber) == 1) {
        gActiveColor       = fricas_color
                            = gControlBackgroundColor
                            = gInputBackgroundColor
                            = gBfColor
                            = gEmColor
                            = gRmColor
                            = gSlColor
                            = gTtColor
                            = BlackPixel(gXDisplay, gXScreenNumber);

        gBackgroundColor   = gInputForegroundColor
                            = gControlForegroundColor
                            = WhitePixel(gXDisplay, gXScreenNumber);
    }
    else {

        /*
         * If I have gotten here, then we must be on a color screen, so see
         * what the user likes, and set it up
         */

/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 1\n");*/
        gRmColor =
            get_color("RmColor", "Foreground",
                      BlackPixel(gXDisplay, gXScreenNumber), &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 2\n");*/
        gBackgroundColor =
            get_color("Background", "Background",
                      WhitePixel(gXDisplay, gXScreenNumber), &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 3\n");*/
        gActiveColor =
            get_color("ActiveColor", "Foreground",
                       BlackPixel(gXDisplay, gXScreenNumber), &cmap);

        /*
         * for next two, I want name arg = class arg, ie do not want
         * Background and Foreground.
         */

/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 4\n");*/
        gControlBackgroundColor = get_color("ControlBackground",
            "ControlBackground", WhitePixel(gXDisplay, gXScreenNumber), &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 5\n");*/
        gControlForegroundColor = get_color("ControlForeground",
            "ControlForeground", BlackPixel(gXDisplay, gXScreenNumber), &cmap);

        /* maintain backwards compatibility */

/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 6\n");*/
        fricas_color = get_color("AxiomColor", "Foreground", 0, &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 7\n");*/
        if (fricas_color == 0)
            fricas_color = get_color("SpadColor", "Foreground",
                BlackPixel(gXDisplay, gXScreenNumber), &cmap);

/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 8\n");*/
        gInputBackgroundColor =
            get_color("InputBackground", "Foreground", gRmColor, &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 9\n");*/
        gInputForegroundColor =
           get_color("InputForeground", "Background", gBackgroundColor, &cmap);

/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 10\n");*/
        gEmColor =
            get_color("EmphasizeColor", "Foreground", gRmColor, &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 11\n");*/
        gTtColor =
            get_color("TtColor", "Foreground", gRmColor, &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 12\n");*/
        gSlColor =
            get_color("EmphasizeColor", "Foreground", gRmColor, &cmap);
/*        fprintf(stderr,"initx:ingItColors_and_fonts:get_color 13\n");*/
        gBfColor =
            get_color("BoldColor", "Foreground", gRmColor, &cmap);
    }

/*    fprintf(stderr,"initx:ingItColors_and_fonts:makeColors\n");*/
    makeColors(gXDisplay, gXScreenNumber, &cmap, &spadColors, &ts);
    /*
     * Now set the current color and font, so I never have to do it again
     */

    gTopOfGroupStack->cur_color = gRmColor;
    gTopOfGroupStack->cur_font = gRmFont;
/*    fprintf(stderr,"initx:ingItColors_and_fonts:exited\n");*/
}
Exemplo n.º 22
0
Arquivo: slock.c Projeto: eepp/slock
static Lock *
lockscreen(Display *dpy, int screen) {
	char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
	unsigned int len;
	Lock *lock;
	XColor color;
	XSetWindowAttributes wa;
	Cursor invisible;
	int hue1, hue2;

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

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

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

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

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

	return lock;
}
Exemplo n.º 23
0
Status
XmuLookupStandardColormap(Display *dpy, int screen, VisualID visualid,
			  unsigned int depth, Atom property,
			  Bool replace, Bool retain)
     /*
      * dpy		- specifies X server connection
      * screen 		- specifies screen of display
      * visualid	- specifies the visual type
      * depth		- specifies  the visual type
      * property	- a standard colormap property
      * replace		- specifies whether to replace
      * retain		- specifies whether to retain
      */
{
    Display		*odpy;		/* original display connection */
    XStandardColormap	*colormap;
    XVisualInfo		vinfo_template, *vinfo;	/* visual */
    long		vinfo_mask;
    unsigned long	r_max, g_max, b_max;	/* allocation */
    int			count;
    Colormap		cmap;			/* colormap ID */
    Status		status = 0;


    /* Match the requested visual */

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

    /* Monochrome visuals have no standard maps */

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

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

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

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

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

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

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

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

    /* Create the standard colormap */

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

    /* Set the standard colormap property */

    if (colormap) {
	XGrabServer(dpy);

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

    if (retain)
	XCloseDisplay(dpy);
    XFree((char *) vinfo);
    return status;
}
Exemplo n.º 24
0
/*
 * Set the cursor image to be used for the current window
 */
void FGAPIENTRY glutSetCursor( int cursorID )
{
    freeglut_assert_ready;  /* XXX WHY do we need the timer active for this? */
    freeglut_assert_window;

#if TARGET_HOST_UNIX_X11
    /*
     * Open issues:
     * (a) Partial error checking.  Is that a problem?
     *     Is fgGetCursorError() correct?  Should we abort on errors?
     *     Should there be a freeglut-wide X error handler?  Should
     *     we use the X error-handler mechanism?
     * (b) FULL_CROSSHAIR demotes to plain CROSSHAIR.  Old GLUT allows
     *     for this, but if there is a system that easily supports a full-
     *     window (or full-screen) crosshair, we might consider it.
     * (c) Out-of-range cursor-types generate warnings.  Should we abort?
     */
    {
        Cursor cursor = None;
        Pixmap no_cursor = None ;  /* Used for GLUT_CURSOR_NONE */
        int error = 0;

#define MAP_CURSOR(a,b)                                     \
    case a:                                                 \
        cursor = XCreateFontCursor( fgDisplay.Display, b ); \
        break;

        if( GLUT_CURSOR_FULL_CROSSHAIR == cursorID )
            cursorID = GLUT_CURSOR_CROSSHAIR;

        switch( cursorID )
        {
            MAP_CURSOR( GLUT_CURSOR_RIGHT_ARROW, XC_right_ptr);
            MAP_CURSOR( GLUT_CURSOR_LEFT_ARROW,  XC_left_ptr);
            MAP_CURSOR( GLUT_CURSOR_INFO,        XC_hand1);
            MAP_CURSOR( GLUT_CURSOR_DESTROY,     XC_pirate);
            MAP_CURSOR( GLUT_CURSOR_HELP,        XC_question_arrow);
            MAP_CURSOR( GLUT_CURSOR_CYCLE,       XC_exchange);
            MAP_CURSOR( GLUT_CURSOR_SPRAY,       XC_spraycan);
            MAP_CURSOR( GLUT_CURSOR_WAIT,        XC_watch);
            MAP_CURSOR( GLUT_CURSOR_TEXT,        XC_xterm);
            MAP_CURSOR( GLUT_CURSOR_CROSSHAIR,   XC_crosshair);
            MAP_CURSOR( GLUT_CURSOR_UP_DOWN,     XC_sb_v_double_arrow);
            MAP_CURSOR( GLUT_CURSOR_LEFT_RIGHT,  XC_sb_h_double_arrow);
            MAP_CURSOR( GLUT_CURSOR_TOP_SIDE,    XC_top_side);
            MAP_CURSOR( GLUT_CURSOR_BOTTOM_SIDE, XC_bottom_side);
            MAP_CURSOR( GLUT_CURSOR_LEFT_SIDE,   XC_left_side);
            MAP_CURSOR( GLUT_CURSOR_RIGHT_SIDE,  XC_right_side);
            MAP_CURSOR( GLUT_CURSOR_TOP_LEFT_CORNER,     XC_top_left_corner);
            MAP_CURSOR( GLUT_CURSOR_TOP_RIGHT_CORNER,    XC_top_right_corner);
            MAP_CURSOR( GLUT_CURSOR_BOTTOM_RIGHT_CORNER,
                        XC_bottom_right_corner);
            MAP_CURSOR( GLUT_CURSOR_BOTTOM_LEFT_CORNER, XC_bottom_left_corner);
            /* MAP_CURSOR( GLUT_CURSOR_NONE,        XC_bogosity); */

        case GLUT_CURSOR_NONE:
        {
            /*
             * Note that we *never* change {no_cursor_bits} from anything
             * but all-zeros.  It is our image and mask.  We also apparently
             * need to pick a color for foreground/background---but what
             * one we pick doesn't matter for GLUT_CURSOR_NONE.
             */
            static char no_cursor_bits[ 32 ];
            XColor black;
            no_cursor = XCreatePixmapFromBitmapData( fgDisplay.Display,
                                                     fgDisplay.RootWindow,
                                                     no_cursor_bits,
                                                     16, 16,
                                                     1, 0, 1 );
            XParseColor( fgDisplay.Display,
                         DefaultColormap( fgDisplay.Display,
                                          DefaultScreen( fgDisplay.Display ) ),
                         "black",
                         &black );
            cursor = XCreatePixmapCursor( fgDisplay.Display,
                                          no_cursor, no_cursor,
                                          &black, &black,
                                          0, 0 );
            break;
        }

        case GLUT_CURSOR_INHERIT:
            break;

        default:
            fgWarning( "Unknown cursor type: %d\n", cursorID );
            return;
        }

        error = fgGetCursorError( cursor );

        if( GLUT_CURSOR_INHERIT == cursorID )
            XUndefineCursor( fgDisplay.Display,
                             fgStructure.Window->Window.Handle );
        else
        {
            XDefineCursor( fgDisplay.Display,
                           fgStructure.Window->Window.Handle, cursor );
            XFreeCursor( fgDisplay.Display, cursor );
            if( GLUT_CURSOR_NONE == cursorID )
                XFreePixmap( fgDisplay.Display, no_cursor );
        }
    }

#elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE

    /*
     * This is a temporary solution only...
     */
    /* Set the cursor AND change it for this window class. */
#       define MAP_CURSOR(a,b)                                   \
        case a:                                                  \
            SetCursor( LoadCursor( NULL, b ) );                  \
            SetClassLong( fgStructure.Window->Window.Handle,     \
                          GCL_HCURSOR,                           \
                          ( LONG )LoadCursor( NULL, b ) );       \
        break;

    /* Nuke the cursor AND change it for this window class. */
#       define ZAP_CURSOR(a,b)                                   \
        case a:                                                  \
            SetCursor( NULL );                                   \
            SetClassLong( fgStructure.Window->Window.Handle,     \
                          GCL_HCURSOR, ( LONG )NULL );           \
        break;

    switch( cursorID )
    {
        MAP_CURSOR( GLUT_CURSOR_RIGHT_ARROW, IDC_ARROW     );
        MAP_CURSOR( GLUT_CURSOR_LEFT_ARROW,  IDC_ARROW     );
        MAP_CURSOR( GLUT_CURSOR_INFO,        IDC_HELP      );
        MAP_CURSOR( GLUT_CURSOR_DESTROY,     IDC_CROSS     );
        MAP_CURSOR( GLUT_CURSOR_HELP,        IDC_HELP      );
        MAP_CURSOR( GLUT_CURSOR_CYCLE,       IDC_SIZEALL   );
        MAP_CURSOR( GLUT_CURSOR_SPRAY,       IDC_CROSS     );
        MAP_CURSOR( GLUT_CURSOR_WAIT,        IDC_WAIT      );
        MAP_CURSOR( GLUT_CURSOR_TEXT,        IDC_UPARROW   );
        MAP_CURSOR( GLUT_CURSOR_CROSSHAIR,   IDC_CROSS     );
        /* MAP_CURSOR( GLUT_CURSOR_NONE,        IDC_NO        ); */
        ZAP_CURSOR( GLUT_CURSOR_NONE,        NULL           );

    default:
        MAP_CURSOR( GLUT_CURSOR_UP_DOWN,     IDC_ARROW     );
    }
#endif

    fgStructure.Window->State.Cursor = cursorID;
}
int main(int argc, char *argv[]) {
	int rank, nprocs, x, y;
	Window win; // initialization for a window
	GC gc; // graphics context
	Display *display = NULL;
	Colormap screenColourmap;
	XColor colours[15];
	unsigned int width = X_RESN, height = Y_RESN; /* window size */
	clock_t start, end, elapsed;
	int pixelToDraw[3];
	MPI_Init(&argc, &argv); 
	MPI_Comm_size(MPI_COMM_WORLD, &nprocs); 
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	ComplexNumber c;
	ComplexNumber z;
	int depth = 1000;
	int cSize = 4;
	double cX = -2;
	double cY = -2;
	double cMinR = cX;
	double cMinI = cY;
	double cMaxR = cMinR + cSize;
	double cMaxI = cMinI + cSize;
	double increaseX = (cMaxR - cMinR) / X_RESN;
	double increaseY = (cMaxI - cMinI) / Y_RESN;
	int drawable[X_RESN][Y_RESN];
        
	if(rank==0)
	{
		display = x11setup(&win, &gc, width, height);
		screenColourmap = DefaultColormap(display, DefaultScreen(display));
		setupColours(display, colours, screenColourmap);
		int probeFlag = 0;
		MPI_Status status;
		int count = 0;
		int start = 1;
		for (int i = 1; i < nprocs; i++) {
			MPI_Send(&start, 1, MPI_INT, i, 98, MPI_COMM_WORLD);
		}
		for (int y = 0; y < Y_RESN; y++) {
			for (int x = 0; x < X_RESN; x++) {
				while (!probeFlag) {
					MPI_Iprobe(MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, &probeFlag, &status);
					if (probeFlag) {
						int coords[2] = {x, y};
						int slave = status.MPI_SOURCE;
						MPI_Recv(&pixelToDraw, 3, MPI_INT, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
						MPI_Send(&coords, 2, MPI_INT, slave, 99, MPI_COMM_WORLD); 
						drawable[pixelToDraw[0]][pixelToDraw[1]] = pixelToDraw[2];
						count++;
					} else {
						MPI_Iprobe(MPI_ANY_SOURCE, 98, MPI_COMM_WORLD, &probeFlag, &status);
						if (probeFlag) {
							int slave = status.MPI_SOURCE;
							int coords[2] = {x, y};
							MPI_Recv(&start, 1, MPI_INT, MPI_ANY_SOURCE, 98, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
							MPI_Send(&coords, 2, MPI_INT, slave, 99, MPI_COMM_WORLD); 
						}
					}
				}
				probeFlag = 0;
			}
		}
		MPI_Recv(&pixelToDraw, 3, MPI_INT, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
		drawable[pixelToDraw[0]][pixelToDraw[1]] = pixelToDraw[2];
		for (int y = 0; y < Y_RESN; y++) {
			for (int x = 0; x < X_RESN; x++) {
				drawPoint(display, win, gc, colours, x, y, depth, drawable[x][y]);
			}
		}
	} else {
		int flag = 1;
		int coords[2];
		MPI_Recv(&start, 1, MPI_INT, 0, 98, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
		MPI_Send(&start, 1, MPI_INT, 0, 98, MPI_COMM_WORLD);
		while (flag) {
			MPI_Recv(&coords, 2, MPI_INT, 0, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
			c.r = coords[0] * increaseX - 2;
			c.i = coords[1] * increaseY - 2;
			resetComplexNumber(&z);
			int limit = seriesDiverges(depth, &z, &c);
			pixelToDraw[0] = coords[0];
			pixelToDraw[1] = coords[1];
			pixelToDraw[2] = limit;
			MPI_Send(&pixelToDraw, 3, MPI_INT, 0, 99, MPI_COMM_WORLD);
		}
	}
	
	// main loop
	int running = 1; // loop variable
	start = clock();
	while(running) {
	
		// checks to see if there have been any events,
		// will exit the main loop if any key is pressed
		if(rank==0) {
			if(XPending(display)) {
				XEvent ev;
				XNextEvent(display, &ev);
				switch(ev.type) {
					case KeyPress:
						running = 0;
						break;
				}
			}
		}
		
		end = clock();
		elapsed = end - start;
		// only update the display if > 1 millisecond has passed since the last update
		if(elapsed / (CLOCKS_PER_SEC/1000) > 1 && rank==0) {
			//XClearWindow(display, win);
			start = end;
			XFlush(display);
		}
	}

	if(rank==0 && display) {
		XCloseDisplay(display); // close the display window
		printf("Display closed\n");
	} else {
		MPI_Finalize();
		return 0;
	}
	
	MPI_Finalize();
	return 0;
}
Exemplo n.º 26
0
static BackgroundTexture *parseTexture(RContext * rc, char *text)
{
	BackgroundTexture *texture = NULL;
	WMPropList *texarray;
	WMPropList *val;
	int count;
	char *tmp;
	char *type;

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

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

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

	texture = wmalloc(sizeof(BackgroundTexture));

	GETSTRORGOTO(val, type, 0, error);

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

		texture->solid = 1;

		GETSTRORGOTO(val, tmp, 1, error);

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

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

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

		GETSTRORGOTO(val, tmp, 1, error);

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

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

		GETSTRORGOTO(val, tmp, 2, error);

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

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

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

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

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

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

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

		texture->pixmap = pixmap;
	} else if (strcasecmp(type, "mvgradient") == 0
Exemplo n.º 27
0
// #includ ur #life
int main(int argc, char *argv[]) {
  bool q = false;
  if(argv[1] != NULL && strcmp(argv[1], "-q") == 0) q=true;
  Display *disp;
  Window win;
  XEvent e;
  int screen;
  int winy = 0;
  int winx = 0;
  int winheight = 300;
  int winwidth = 500;
  int borderwidth = 10;
  int stdcposx = 20;
  int stdcposy = 20;
  int cposx = stdcposx;
  int cposy = stdcposy;
  int lastdeltime = 0;
  int lastrowlength = 0;
  int lastkeysym = 0;
  char *msg = "Clear";
  int bwidth=strlen(msg)*6;
  int bheight=15;
  int btop=20;
  int bmargin = 2;
  int bleft=winwidth - bwidth - 20;
  GC white;
  XColor white_color;
  Colormap colormap;
  char whiteidk[] = "#FFFFFF";
  GC red;
  XColor red_color;
  Colormap rcolormap;
  char redidk[] = "#FF0000";

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

  screen = DefaultScreen(disp);
  win = XCreateSimpleWindow(disp, RootWindow(disp, screen), winx, winy, winwidth, winheight, borderwidth,
  BlackPixel(disp, screen), WhitePixel(disp, screen));
  XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask);
  // Window XCreateWindow(display, parent, x, y, width, height, border_width, depth,
  //                    class, visual, valuemask, attributes)
  XMapWindow(disp, win);
  colormap = DefaultColormap(disp, 0);
  white = XCreateGC(disp, win, 0, 0);
  XParseColor(disp, colormap, whiteidk, &white_color);
  XAllocColor(disp, colormap, &white_color);
  XSetForeground(disp, white, white_color.pixel);
  rcolormap = DefaultColormap(disp, 0);
  red = XCreateGC(disp, win, 0, 0);
  XParseColor(disp, colormap, redidk, &red_color);
  XAllocColor(disp, colormap, &red_color);
  XSetForeground(disp, red, red_color.pixel);
  while (1) {
    XNextEvent(disp, &e);
    if (e.type == Expose)
      {
        XFillRectangle(disp, win, red, bleft, btop, bwidth, bheight);
        XDrawString(disp, win, white, bleft+bmargin, btop+bmargin+9, msg, strlen(msg));
        //http://tronche.com/gui/x/xlib/graphics/drawing-text/XDrawString.html
      }
      if(e.type == 4) // button press
        {
          int x=e.xbutton.x;
          int y=e.xbutton.y;
          int button = e.xbutton.button;
          if(!q) printf("Button pressed. X: %d, Y: %d Button: %d\n",x,y,button);
          if(button == 1)
            {
              if(y < bheight+btop && x < bwidth+bleft)
                {
                  if(y > btop && x > bleft)
                    {
                      if(!q) printf("You've hitten the button!!\nClearing...\n");
                      XFillRectangle(disp, win, white, 0, 0, winwidth, winheight);
                      cposx = stdcposx;
                      cposy = stdcposy;
                      if(!q) printf("Repainting clearbutton...\n");
                      XFillRectangle(disp, win, red, bleft, btop, bwidth, bheight);
                      XDrawString(disp, win, white, bleft+bmargin, btop+bmargin+9, msg, strlen(msg));
                    }
                  }
                }
              }
              if (e.type == KeyPress)
                {
                  if(!q) printf("Keycode: %d\n", e.xkey.keycode);
                  unsigned long keysym = XLookupKeysym(&e.xkey, 0);
                  if(!q) printf("Keysym: %lu\n",keysym);
                  char *ascii = XKeysymToString(keysym);
                  if(!q) printf("ASCII: %s\n",ascii);
                  if(keysym == 65307 && lastkeysym == 65406) // alt+ESC
                    {
                      printf("Exiting...\n");
                      return 0;
                    }
                    else if(keysym == 65293) // line break
                    {
                      cposy+=10;
                      lastrowlength = cposx;
                      cposx = stdcposx;
                    }
                    else if(keysym == 32) // " "
                    {
                      cposx+=6;
                    }
                    else if(keysym == 65288) // delete
                    {
                      time_t now = time(0);
                      if(!q) printf("Time: %ld\n",now);
                      int diff = now-lastdeltime;
                      if(!q) printf("Time since last deletion: %d\n",diff);
                      XFillRectangle(disp, win, white, cposx-6, cposy-9, 6, 11);
                      if(diff == 0)
                        {
                          XFillRectangle(disp, win, white, cposx-12, cposy-9, 6, 11);
                        }
                        lastdeltime = now;
                        if(cposx <= stdcposx)
                          {
                            if(cposy != stdcposy)
                              {
                                cposy-=10;
                                cposx = lastrowlength;
                              }
                            }
                            else
                              {
                                cposx-=6;
                                if(diff == 0 && cposx-6 > stdcposx)
                                  {
                                    cposx-=6;
                                  }
                                }
                              }
                              else if(keysym == 43) // plus
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "+", 1);
                                cposx+=6;
                              }
                              else if(keysym == 44) // comma
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ",", 1);
                                cposx+=6;
                              }
                              else if(keysym == 45) // minus
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "-", 1);
                                cposx+=6;
                              }
                              else if(keysym == 46) // period
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ".", 1);
                                cposx+=6;
                              }
                              else if(keysym == 65289) // tab
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "   ", 3);
                                cposx+=18;
                              }
                              else
                                {
                                  if(lastkeysym != 65506 || lastkeysym != 65505)
                                    {
                                      if(keysym == 49)
                                        {
                                          ascii = "!";
                                        }
                                        else if(keysym == 43)
                                        {
                                          ascii = "?";
                                        }
                                      }
                                      if(keysym != 65506 && keysym != 65505)
                                        {
                                          XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ascii, strlen(ascii));
                                          cposx+=strlen(ascii)*6;
                                        }
                                      }
                                      lastkeysym = keysym;
                                    }
                                  }
                                  XCloseDisplay(disp);
                                  return 0;
                                }
Exemplo n.º 28
0
Colormap XDefaultColormap(Display *dpy, int scr)
{
    return (DefaultColormap(dpy, scr));
}
Exemplo n.º 29
0
  int main (void)
  {
    int i;
  
    int allocateOK;
  
    ximg = NULL;
  
  	
    d = XOpenDisplay (NULL);
  
    if (!d)
      fputs ("Couldn't open display\n", stderr), exit (1);
  
    screen = DefaultScreen (d);
    gc = DefaultGC (d, screen);
  
    /* Find a visual */
  
    vis.screen = screen;
    vlist = XGetVisualInfo (d, VisualScreenMask, &vis, &match);
  
    if (!vlist)
      fputs ("No matched visuals\n", stderr), exit (1);
  
    vis = vlist[0];
    XFree (vlist);
		
  	// That's not a fair comparison colormap_size is depth in bits!
    // if (vis.colormap_size < COLORS)
      // printf("Colormap is too small: %i.\n",vis.colormap_size); // , exit (1);
		// printf("Colour depth: %i\n",vis.colormap_size);
		// No way this number means nothing!  It is 64 for 16-bit truecolour and 256 for 8-bit!
  
    win = XCreateSimpleWindow (d, DefaultRootWindow (d),
			       0, 0, WIN_W, WIN_H, 0,
			       WhitePixel (d, screen), BlackPixel (d, screen));
  
	  int xclass=get_xvisinfo_class(vis);
		// printf("class = %i\n",xclass);
	  stylee = ( vis.depth > 8 ? styleeTrueColor : styleePrivate );
	  // printf("stylee=%i\n",stylee);
  
    if ( get_xvisinfo_class(vis) % 2 == 1) {	/* The odd numbers can redefine colors */
  
			  // printf("%i\n",get_xvisinfo_class(vis));
	  	
      colormap = DefaultColormap (d, screen);
		  Visual *defaultVisual=DefaultVisual(d,screen);
	  	
      /* Allocate cells */
      allocateOK = (XAllocColorCells (d, colormap, 1,
							      NULL, 0, color, COLORS) != 0);

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

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

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


  
      // XNextEvent (d, &ev);
      // switch (ev.type) {
      // case ButtonPress:
        // should_quit = 1;
        // break;
      // case Expose:
        // if (can_use_mitshm)
				  // XShmPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H, True);
        // else
				  // XPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H);
        // break;
      // default:
			  // break;
      // }
  
  
  
    if (get_xvisinfo_class(vis) % 2 == 1 || get_xvisinfo_class(vis) == TrueColor) {
      unsigned long color[COLORS];
  
      if (allocateOK) {
        for (i = 0; i < COLORS; i++)
				  color[i] = xrgb[i].pixel;
        XFreeColors (d, colormap, color, COLORS, 0);
      }				/* Allocated colors freed */
    } else {
      XUninstallColormap (d, colormap);
    }
  
    if (can_use_mitshm) {
      XShmDetach (d, &shminfo);	/* Server detached */
      XDestroyImage (ximg);	/* Image struct freed */
      shmdt (shminfo.shmaddr);	/* We're detached */
    } else
      XDestroyImage (ximg);	/* Image struct freed */
  
    XDestroyWindow (d, win);	/* Window removed */
    XCloseDisplay (d);		/* Display disconnected */
  
    /* So you can see how your computer compares to your friend's */
    getrusage (RUSAGE_SELF, &resource_utilization);
		float seconds=(float)resource_utilization.ru_utime.tv_sec
						     +(float)resource_utilization.ru_utime.tv_usec*0.000000001;
		printf("CPU seconds per frame: %f\n",seconds/(float)frameno);
    // printf ("CPU seconds consumed: %ds and %dµs\n",
	    // (int) resource_utilization.ru_utime.tv_sec,
	    // (int) resource_utilization.ru_utime.tv_usec);
  
    return 0;
  }
Exemplo n.º 30
0
int main () {
	printf ("X11 demo\n");

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

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

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

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

	return 0;
}