Example #1
0
	int main(int argc, char **argv)
	{
		static char *string = "Hello World!";
		Display *display;
		int screen_num;
		Window win;			//窗口ID
		unsigned int width, height;	//窗口尺寸
		unsigned int border_width = 4;	//边界空白
		unsigned int display_width, display_height;//屏幕尺寸
		int count;
		XEvent report;
		GC gc;
		unsigned long valuemask = 0;
		XGCValues values;
		char *display_name = NULL;
	
		// 和X 服务器连接
		if ( (display=XOpenDisplay(display_name)) == NULL )
		{
			printf("Cannot connect to X server %s\n", 
					XDisplayName(display_name));
			exit(-1);
		}

		//获得缺省的 screen_num
		screen_num = DefaultScreen(display);

		//获得屏幕的宽度和高度
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);
	
		//指定所建立窗口的宽度和高度
		width = display_width/3;
		height = display_height/4;
	
		//建立窗口
		win = XCreateSimpleWindow(display, 	//display
			RootWindow(display,screen_num), //父窗口
			0, 0, width, height, 		//位置和大小
			border_width, 			//边界宽度
			BlackPixel(display,screen_num), //前景色
			WhitePixel(display,screen_num));//背景色
	
		//选择窗口感兴趣的事件掩码
		XSelectInput(display, win, 
			ExposureMask | KeyPressMask | 
			ButtonPressMask | StructureNotifyMask);

		//建立GC
		gc = XCreateGC(display, win, valuemask, &values);

		//显示窗口
		XMapWindow(display, win);

		//进入事件循环
		while (1)  {

			//取得队列中的事件
			XNextEvent(display, &report);
			switch  (report.type) {

			//曝光事件, 窗口应重绘
			case Expose:
				//取得最后一个曝光事件
				if (report.xexpose.count != 0) break;
	
				//写字符串
				XDrawString(display, win, gc, width/2,height/2,
					string, strlen(string));
	
				break;

			//窗口尺寸改变, 重新取得窗口的宽度和高度
			case ConfigureNotify:
				width = report.xconfigure.width;
				height = report.xconfigure.height;
				break;

			//鼠标点击或有按键, 释放资源则退出
			case ButtonPress:
			case KeyPress:
				XFreeGC(display, gc);
				XCloseDisplay(display);
				exit(1);
			default:
				
				break;
			}
		}
	}
Example #2
0
	int main(int argc, char **argv)
	{
		Display *display;
		int screen_num;
		Window win;			//窗口ID
		unsigned int width, height;	//窗口尺寸
		unsigned int border_width = 4;	//边界空白
		unsigned int display_width, display_height;//屏幕尺寸
		XEvent report;
		GC gc;
		unsigned long valuemask = 0;
		XGCValues values;
		char *display_name = NULL;
		Atom          protocols;

		//edit
		int           len = 127;
		unsigned char string[128], s_tab[ROW][127];
		KeySym        keysym;
		int           row = 0, col = 0;
		int           i, count = 0;
		Status        status;
		//字体集
		XFontSet fontset;
		char **missing_charsets;
		int num_missing_charsets;
		char *default_string;
		XFontSetExtents *fs_ext;
		int dec;    

		//XIM
		XIM im;
		XIC ic;
		//overspot
		XRectangle    spot, s_rect;
		XVaNestedList preedit_attr, status_attr;

		//设置locale	
		if((setlocale(LC_ALL, "")) == NULL){
			printf("cannot set locale\n");
			exit(1);
		}

		//判断X是否支持locale
		if(!XSupportsLocale()){
			printf("X does not support current locale\n");
			exit(1);
		}

		//设置locale修饰
		if(XSetLocaleModifiers(NULL)){
			printf("Cannot set locale modifiers\n");
			exit(1);
		}
	
		// 和X 服务器连接
		if ( (display=XOpenDisplay(display_name)) == NULL )
		{
			printf("Cannot connect to X server %s\n", 
					XDisplayName(display_name));
			exit(-1);
		}

		//获得缺省的 screen_num
		screen_num = DefaultScreen(display);

		//获得屏幕的宽度和高度
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);
	
		//建立字体集
		fontset = XCreateFontSet(display, 
			"8x16,-*-song-medium-r-normal--16-*-*-*-*-*-gb2312.1980-0",
			&missing_charsets, &num_missing_charsets,
			&default_string);

		if(num_missing_charsets > 0){
			int i;
			printf("Following charsets are missing:\n");
			for(i=0; i<num_missing_charsets; i++){
				printf("Missing %d: %s\n", 
					i, missing_charsets[i]);
			}
			printf("\nDefault string:%s\n", default_string);
			XFreeStringList(missing_charsets);
		}
		//字体的Extents
		fs_ext = XExtentsOfFontSet(fontset);
		dec = fs_ext->max_logical_extent.height 
			+ fs_ext->max_logical_extent.y;

		width  = W_WIDTH;
		height = W_HEIGHT + dec;

	
		//建立窗口
		win = XCreateSimpleWindow(display, 	//display
			RootWindow(display,screen_num), //父窗口
			0, 0, width, height, 		//位置和大小
			border_width, 			//边界宽度
			BlackPixel(display,screen_num), //前景色
			WhitePixel(display,screen_num));//背景色
	
		//选择窗口感兴趣的事件掩码
		XSelectInput(display, win, 
			ExposureMask | KeyPressMask | 
			ButtonPressMask | StructureNotifyMask);

		//建立GC
		gc = XCreateGC(display, win, valuemask, &values);

		protocols = XInternAtom(display, "WM_DELETE_WINDOW", True);
		XSetWMProtocols(display, win, &protocols, 1);

		//显示窗口
		XMapWindow(display, win);

		//联接输入服务器
		if((im = XOpenIM(display, NULL, NULL, NULL)) == NULL){
			printf("Error : XOpenIM !\n");
			exit(1);
		}

		//设置输入服务器的位置
		spot.x = F_SIZE / 2 * col;
		spot.y = F_SIZE * (row + 1) - dec; 
		preedit_attr = XVaCreateNestedList(0,
			XNSpotLocation, &spot,
			XNFontSet, fontset, 
			NULL);
		s_rect.x = 0;
		s_rect.y = F_SIZE * ROW + dec + 2;
		s_rect.width = W_WIDTH;
		s_rect.height = F_SIZE;
		status_attr = XVaCreateNestedList(0,
			XNArea, &s_rect,
			XNFontSet, fontset,
			NULL);
		//建立IC
		if((ic = XCreateIC(im, 
			XNInputStyle, XIMPreeditPosition | XIMStatusNothing,
			XNClientWindow, win, 
			XNPreeditAttributes, preedit_attr,
			XNStatusAttributes, status_attr, NULL)) == NULL){
			printf("Error : XCreateIC() ! \n");
			XCloseIM(im);
			exit(0);
		}
		//释放内存
		XFree(preedit_attr);
		XFree(status_attr);


		//写屏缓冲区初始化
		for(i = 0; i < ROW; i++)s_tab[i][0] = 0;

		//进入事件循环
		while (1)  {

			//取得队列中的事件
			XNextEvent(display, &report);

			//过滤事件
			if(XFilterEvent(&report, None) == True) continue;
			switch  (report.type) {

			//聚焦发声变化
			case FocusIn:
				XSetICFocus(ic); 
				break;
			case FocusOut:
				XUnsetICFocus(ic);
				break;

			//曝光事件, 窗口应重绘
			case Expose:
				//取得最后一个曝光事件
				if (report.xexpose.count != 0) break;
				for ( i=0; i < ROW; i++)
					XmbDrawString(display, win, fontset,gc, 
					0, F_SIZE * (i +1), 
					s_tab[i], strlen(s_tab[i]));
				break;

			//窗口尺寸改变, 重新取得窗口的宽度和高度
			case ConfigureNotify:
				width = report.xconfigure.width;
				height = report.xconfigure.height;
				break;

			//鼠标点击或有按键, 释放资源则退出
			case KeyPress:
				count = XmbLookupString(ic, 
					(XKeyPressedEvent *) &report,
					string, len, &keysym, &status);
				string[count] = 0;
				if (status == XLookupBoth&&keysym == XK_Return){
					row = (++row) % ROW;
					col = 0;
					s_tab[row][0] = 0;
					XClearArea(display, win, 
						0, F_SIZE * row + dec,
						W_WIDTH, F_SIZE, False);
				} else if (status = XLookupChars 
					|| status == XLookupBoth){
					XmbDrawString(display, win, fontset, gc,
					F_SIZE / 2 * col, F_SIZE * (row + 1),
					string, count);
					for (i = 0; i < count && col < len && 
						string[i]; i++, col++)
						s_tab[row][col] = string[i];
						s_tab[row][col] = 0;
				}
				//更新输入服务器位置
				spot.x = F_SIZE / 2 * col;
				spot.y = F_SIZE * (row + 1);
				preedit_attr = XVaCreateNestedList(0,
					XNSpotLocation, &spot,
					NULL);
				XSetICValues(ic, 
					XNPreeditAttributes, preedit_attr, 
					NULL);
				XFree(preedit_attr);
				break;
			case ClientMessage:
				if (report.xclient.data.l[0] == protocols) {
					XDestroyIC(ic);
					XCloseIM(im);
					XDestroyWindow(display, win);
					XCloseDisplay(display);
					exit(0);
				}
				break;
			default:
				break;
			}
		}
	}
Example #3
0
EIF_BOOLEAN basic_gui_initialize(EIF_POINTER display_name,
				 EIF_BOOLEAN sync,
				 EIF_BOOLEAN no_xshm,
				 EIF_POINTER name,
				 EIF_POINTER progclass,
				 EIF_POINTER gxid_host,
				 EIF_INTEGER gxid_port) {
  /*
     Called only once at the very beginning to initialize the Window Manager.
  */
  int synchronize = sync;
  XKeyboardState keyboard_state;
  XClassHint *class_hint;
  X_GETTIMEOFDAY (&start);
  gdk_display_name = display_name;
  XSetErrorHandler (gui_x_error);
  XSetIOErrorHandler (gui_x_io_error);
  g_get_prgname = name;
  gdk_display_name = display_name;
  if (no_xshm) gdk_use_xshm = FALSE;
  gdk_progclass = progclass;
#ifdef XINPUT_GXI
  gdk_input_gxid_host = gxid_host;
  gdk_input_gxid_port = gxid_port;
#endif

  gdk_display = XOpenDisplay (gdk_display_name);
  if (!gdk_display)
    return FALSE;

  if (synchronize)
    XSynchronize (gdk_display, True);

  gdk_screen = DefaultScreen (gdk_display);

  gdk_root_window = RootWindow (gdk_display, gdk_screen);

  gdk_leader_window = XCreateSimpleWindow(gdk_display, gdk_root_window,
					  10, 10, 10, 10, 0, 0 , 0);
  class_hint = XAllocClassHint();
  class_hint->res_name = g_get_prgname;
  if (gdk_progclass == NULL) {
    gdk_progclass = g_get_prgname;
  }
  class_hint->res_class = gdk_progclass;
  XmbSetWMProperties (gdk_display, gdk_leader_window,
		      NULL, NULL, se_argv, se_argc,
		      NULL, NULL, class_hint);
  XFree (class_hint);
  gdk_wm_delete_window = XInternAtom (gdk_display, "WM_DELETE_WINDOW", False);
  gdk_wm_take_focus = XInternAtom (gdk_display, "WM_TAKE_FOCUS", False);
  gdk_wm_protocols = XInternAtom (gdk_display, "WM_PROTOCOLS", False);
  gdk_wm_window_protocols[0] = gdk_wm_delete_window;
  gdk_wm_window_protocols[1] = gdk_wm_take_focus;
  gdk_selection_property = XInternAtom (gdk_display, "GDK_SELECTION", False);

  XGetKeyboardControl (gdk_display, &keyboard_state);

  autorepeat = keyboard_state.global_auto_repeat;

  timer.tv_sec = 0;
  timer.tv_usec = 0;
  timerp = NULL;

  /* @@@ Keep This ?:
     gdk_events_init ();
     gdk_visual_init ();
     gdk_window_init ();
     gdk_image_init ();
     gdk_input_init ();
     gdk_dnd_init ();

#ifdef USE_XIM
  gdk_im_open ();
#endif
  */
  return 1;
}
Example #4
0
/*
 * The following function initializes a toplevel window.
 * It returns 0 if the initialization was successful,
 * or -1 if it couldn't initialize the double buffering routine.
 */
int Init_top(void)
{
    int					top_x, top_y;
    int					i;
    int					x, y;
    unsigned				w, h;
    unsigned long			values;
    int					top_flags;
    XGCValues				xgc;
    XSetWindowAttributes		sattr;
    unsigned long			mask;

    if (topWindow)
	fatal("Init_top called twice");

    if (Colors_init() == -1)
	return -1;

    radarDrawRectanglePtr = XFillRectangle;

    /*
     * Get toplevel geometry.
     */
    top_flags = 0;
    if (geometry != NULL && geometry[0] != '\0')
	mask = XParseGeometry(geometry, &x, &y, &w, &h);
    else
	mask = 0;

    if ((mask & WidthValue) != 0) {
	top_width = w;
	top_flags |= USSize;
    } else {
	top_width = DEF_TOP_WIDTH;
	top_flags |= PSize;
    }
    LIMIT(top_width, MIN_TOP_WIDTH, MAX_TOP_WIDTH);
    if ((mask & HeightValue) != 0) {
	top_height = h;
	top_flags |= USSize;
    } else {
	top_height = DEF_TOP_HEIGHT;
	top_flags |= PSize;
    }
    LIMIT(top_height, MIN_TOP_HEIGHT, MAX_TOP_HEIGHT);
    if ((mask & XValue) != 0) {
	if ((mask & XNegative) != 0)
	    top_x = DisplayWidth(dpy, DefaultScreen(dpy)) - top_width + x;
	else
	    top_x = x;
	top_flags |= USPosition;
    } else {
	top_x = (DisplayWidth(dpy, DefaultScreen(dpy)) - top_width) /2;
	top_flags |= PPosition;
    }
    if ((mask & YValue) != 0) {
	if ((mask & YNegative) != 0)
	    top_y = DisplayHeight(dpy, DefaultScreen(dpy)) - top_height + y;
	else
	    top_y = y;
	top_flags |= USPosition;
    } else {
	top_y = (DisplayHeight(dpy, DefaultScreen(dpy)) - top_height) /2;
	top_flags |= PPosition;
    }
    if (geometry != NULL) {
	free(geometry);
	geometry = NULL;
    }

    /*
     * Create toplevel window (we need this first so that we can create GCs)
     */
    mask = 0;
    /*old debug: sattr.background_pixel = colors[WHITE].pixel;*/
    sattr.background_pixel = colors[BLACK].pixel;
    mask |= CWBackPixel;
    sattr.border_pixel = colors[WHITE].pixel;
    mask |= CWBorderPixel;
    if (colormap != 0) {
	sattr.colormap = colormap;
	mask |= CWColormap;
    }
    if (ignoreWindowManager) {
	sattr.override_redirect = True;
	mask |= CWOverrideRedirect;
    }
    topWindow = XCreateWindow(dpy,
			      DefaultRootWindow(dpy),
			      top_x, top_y,
			      top_width, top_height,
			      0, (int)dispDepth,
			      InputOutput, visual,
			      mask, &sattr);
    XSelectInput(dpy, topWindow,
		 KeyPressMask | KeyReleaseMask
		 | FocusChangeMask | StructureNotifyMask);
    Init_disp_prop(dpy, topWindow, top_width, top_height,
		   top_x, top_y, top_flags);
    if (kdpy) {
	int scr = DefaultScreen(kdpy);
	keyboardWindow = XCreateSimpleWindow(kdpy,
					     DefaultRootWindow(kdpy),
					     top_x, top_y,
					     top_width, top_height,
					     0, 0, BlackPixel(dpy, scr));
	XSelectInput(kdpy, keyboardWindow,
		     KeyPressMask | KeyReleaseMask | FocusChangeMask);
	Init_disp_prop(kdpy, keyboardWindow, top_width, top_height,
		       top_x, top_y, top_flags);
    }

    /*
     * Create item bitmaps
     */
    for (i = 0; i < NUM_ITEMS; i++)
	itemBitmaps[i]
	    = XCreateBitmapFromData(dpy, topWindow,
				    (char *)itemBitmapData[i].data,
				    ITEM_SIZE, ITEM_SIZE);

    /*
     * Creates and initializes the graphic contexts.
     */
    xgc.line_width = 0;
    xgc.line_style = LineSolid;
    xgc.cap_style = CapButt;
    xgc.join_style = JoinMiter;		/* I think this is fastest, is it? */
    xgc.graphics_exposures = False;
    values
	= GCLineWidth|GCLineStyle|GCCapStyle|GCJoinStyle|GCGraphicsExposures;

    messageGC	= XCreateGC(dpy, topWindow, values, &xgc);
    radarGC	= XCreateGC(dpy, topWindow, values, &xgc);
    buttonGC	= XCreateGC(dpy, topWindow, values, &xgc);
    scoreListGC	= XCreateGC(dpy, topWindow, values, &xgc);
    textGC	= XCreateGC(dpy, topWindow, values, &xgc);
    talkGC	= XCreateGC(dpy, topWindow, values, &xgc);
    motdGC	= XCreateGC(dpy, topWindow, values, &xgc);
    gameGC	= XCreateGC(dpy, topWindow, values, &xgc);
    XSetBackground(dpy, gameGC, colors[BLACK].pixel);

    /*
     * Set fonts
     */
    gameFont
	= Set_font(dpy, gameGC, gameFontName, "gameFont");
    messageFont
	= Set_font(dpy, messageGC, messageFontName, "messageFont");
    scoreListFont
	= Set_font(dpy, scoreListGC, scoreListFontName, "scoreListFont");
    buttonFont
	= Set_font(dpy, buttonGC, buttonFontName, "buttonFont");
    textFont
	= Set_font(dpy, textGC, textFontName, "textFont");
    talkFont
	= Set_font(dpy, talkGC, talkFontName, "talkFont");
    motdFont
	= Set_font(dpy, motdGC, motdFontName, "motdFont");

    XSetState(dpy, gameGC,
	      WhitePixel(dpy, DefaultScreen(dpy)),
	      BlackPixel(dpy, DefaultScreen(dpy)),
	      GXcopy, AllPlanes);
    XSetState(dpy, radarGC,
	      WhitePixel(dpy, DefaultScreen(dpy)),
	      BlackPixel(dpy, DefaultScreen(dpy)),
	      GXcopy, AllPlanes);
    XSetState(dpy, messageGC,
	      WhitePixel(dpy, DefaultScreen(dpy)),
	      BlackPixel(dpy, DefaultScreen(dpy)),
	      GXcopy, AllPlanes);
    XSetState(dpy, buttonGC,
	      WhitePixel(dpy, DefaultScreen(dpy)),
	      BlackPixel(dpy, DefaultScreen(dpy)),
	      GXcopy, AllPlanes);
    XSetState(dpy, scoreListGC,
	      WhitePixel(dpy, DefaultScreen(dpy)),
	      BlackPixel(dpy, DefaultScreen(dpy)),
	      GXcopy, AllPlanes);

    if (dbuf_state->type == COLOR_SWITCH)
	XSetPlaneMask(dpy, gameGC, dbuf_state->drawing_planes);

    return 0;
}
Example #5
0
int
main() {
    Display *d;
    Window w;
    GC planetGc[NO_OF_PLANETS], rectGc, textGc, sunGc, invGc;
    XColor sunColor, rectColor, planetColor[NO_OF_PLANETS];
    XEvent e;
    KeySym key;
    int rectX = (windowWidth - rectWidth) / 2, rectY = (windowHeight - rectHeight) / 2;
    Point pt[NO_OF_PLANETS], centre = rectX + (rectWidth / 2) + I * (rectY + (rectHeight / 2));
    int prevAngle[NO_OF_PLANETS];
    int s, sunX = creal(centre) - p[0].orbitSemiMajor * p[0].orbitEccentricity - 10, sunY = cimag(centre), i;

    d = XOpenDisplay(NULL);
    s = DefaultScreen(d);
    w = XCreateSimpleWindow(d, RootWindow(d, s), 0, 0, windowWidth, windowHeight, 0, 0, WhitePixel(d, s));

    setPlanetAttributes(p);

    XStoreName(d, w, "Planetary Motion Simulator Window");
    XSelectInput(d, w, ExposureMask | KeyPressMask);
    XMapWindow(d, w);
    XMoveWindow(d, w, (DisplayWidth(d, s) - windowWidth) / 2, (DisplayHeight(d, s) - windowHeight) / 2);

    textGc = XCreateGC(d, w, 0, 0);

    createGC(d, &w, s, 2, &rectGc, rect, &rectColor);
    createGC(d, &w, s, 1, &sunGc, sun, &sunColor);
    for (i = 0; i < NO_OF_PLANETS; i++)
        createGC(d, &w, s, 1, &planetGc[i], planetColour[i], &planetColor[i]);

    invGc = XCreateGC(d, w, 0, 0);
    XSetForeground(d, invGc, WhitePixel(d, s));
    XSetFillStyle(d, invGc, FillSolid);

    for (i = 0; i < NO_OF_PLANETS; i++)
        prevAngle[i] = 90 * i;

    while (true) {
        XNextEvent(d, &e);
        switch (e.type) {
            case Expose:
                drawText(d, s, &w, &textGc, message);
                XDrawRectangle(d, w, rectGc, rectX, rectY, rectWidth, rectHeight);
                XFillArc(d, w, sunGc, sunX - sunRadius, sunY - sunRadius, sunRadius * 2, sunRadius * 2, 0, 360 * 64);
                for (i = 0; i < NO_OF_PLANETS; i++) {
                    pt[i] = pointOnEllipse(p[i].orbitSemiMajor, p[i].orbitSemiMinor, prevAngle[i], centre);
                    XDrawArc(d, w, planetGc[i], creal(centre) - p[i].orbitSemiMajor, cimag(centre) - p[i].orbitSemiMinor,
                            p[i].orbitSemiMajor * 2, p[i].orbitSemiMinor * 2, 0, 360 * 64);
                    XFillArc(d, w, planetGc[i], creal(pt[i]) - p[i].radius, cimag(pt[i]) - p[i].radius,
                            p[i].radius * 2, p[i].radius * 2, 0, 360 * 64);
                }
                break;
            case KeyPress:
                key = XLookupKeysym(&e.xkey, 0);
                if (key == XK_Return) {
                    drawText(d, s, &w, &textGc, message);
                    for (i = 0; i < NO_OF_PLANETS; i++)
                        XFillArc(d, w, invGc, creal(pt[i]) - p[i].radius, cimag(pt[i]) - p[i].radius,
                            p[i].radius * 2, p[i].radius * 2, 0, 360 * 64);
                    XDrawRectangle(d, w, rectGc, rectX, rectY, rectWidth, rectHeight);
                    XFillArc(d, w, sunGc, sunX - sunRadius, sunY - sunRadius, sunRadius * 2, sunRadius * 2, 0, 360 * 64);
                    for (i = 0; i < NO_OF_PLANETS; i++) {
                        pt[i] = pointOnEllipse(p[i].orbitSemiMajor, p[i].orbitSemiMinor, prevAngle[i], centre);
                        XDrawArc(d, w, planetGc[i], creal(centre) - p[i].orbitSemiMajor, cimag(centre) - p[i].orbitSemiMinor,
                                p[i].orbitSemiMajor * 2, p[i].orbitSemiMinor * 2, 0, 360 * 64);
                        XFillArc(d, w, planetGc[i], creal(pt[i]) - p[i].radius, cimag(pt[i]) - p[i].radius,
                                p[i].radius * 2, p[i].radius * 2, 0, 360 * 64);
                        prevAngle[i] += p[i].angVelocity * (i == 1 || i == 6 ? -1 : 1); // venus & uranus rotate clockwise
                        prevAngle[i] %= 360;
                    }
                } else exit(0);
        }
    }
    XDestroyWindow(d, w);
    XCloseDisplay(d);
    return (EXIT_SUCCESS);
}
Example #6
0
se_text_xviewer* se_text_xviewer_create( se_env* env )
{
    se_text_xviewer* viewer = g_malloc0( sizeof(se_text_xviewer) );
    if ( !viewer ) {
        se_error( "can not malloc a viewer obj" );
    }

    viewer->env = env;
    
    int width = 800;
    int height = 600;
    
    viewer->view = XCreateSimpleWindow(
        env->display, env->root, 0, 0, width, height, 0,
        BlackPixel(env->display, env->screen),
        WhitePixel(env->display, env->screen) );
    
    viewer->key_handler = se_text_xviewer_key_event;
    viewer->mouse_handler = se_text_xviewer_mouse_event;
    viewer->configure_change_handler = se_text_xviewer_configure_change_handler;

    viewer->show = se_text_xviewer_show;
    viewer->repaint = se_text_xviewer_repaint;
    viewer->redisplay = se_text_xviewer_redisplay;
    viewer->updateSize = se_text_xviewer_updateSize;
    
    se_text_xviewer_draw_create( viewer );

    viewer->content = g_malloc0( SE_MAX_COLUMNS * SE_MAX_ROWS );

    XIMStyles *im_supported_styles;
    XIMStyle app_supported_styles;
    XIMStyle style;
    XIMStyle best_style;

    XGetIMValues( env->xim, XNQueryInputStyle, &im_supported_styles, NULL );
    app_supported_styles = XIMPreeditNone | XIMPreeditNothing | XIMPreeditArea
        | XIMStatusNone | XIMStatusNothing | XIMStatusArea;
    best_style = 0;
    se_debug( "styles count: %d", im_supported_styles->count_styles );
    for(int i=0; i < im_supported_styles->count_styles; i++) {
        style = im_supported_styles->supported_styles[i];
        dump_style( style );
        if ((style & app_supported_styles) == style) /* if we can handle it */
            best_style = ChooseBetterStyle(style, best_style);
    }

    /* if we couldn't support any of them, print an error and exit */
    if (best_style == 0) {
        se_error("commonly supported interaction style.");
        exit(1);
    }
    XFree(im_supported_styles);
    dump_style( best_style );
    
    viewer->xic = XCreateIC(env->xim, XNInputStyle, best_style,
                            XNClientWindow, viewer->view,
                            NULL);
    if ( viewer->xic == NULL ) {
        se_debug(" create xic failed" );
        exit(1);        
    }
    se_debug( "XLocaleOfIM: %s", XLocaleOfIM( env->xim ) );
    
    return viewer;
}
Example #7
0
void xskin_start_interface( int pipe_in ) {

  int xskin_sc;
  XEvent xskin_e;
  XSetWindowAttributes xskin_attr;

  XSizeHints xskin_hint;
  XClassHint xskin_chint;
  XTextProperty ct;
  char *namlist[2];


  /* setup window */

  xskin_d     = XOpenDisplay( NULL );
  xskin_sc    = DefaultScreen( xskin_d );
  xskin_r     = RootWindow( xskin_d, xskin_sc );
  xskin_gc    = DefaultGC( xskin_d, xskin_sc );
  xskin_vis   = DefaultVisual( xskin_d, xskin_sc );
  xskin_depth = DefaultDepth( xskin_d, xskin_sc );

  xskin_w = XCreateSimpleWindow( xskin_d, xskin_r, 0, 0,
				 skin_width, skin_height, 0,
				 WhitePixel( xskin_d, xskin_sc ),
				 BlackPixel( xskin_d, xskin_sc ) );

  xskin_attr.backing_store = True;
  xskin_attr.override_redirect = False;
  XChangeWindowAttributes( xskin_d, xskin_w,
			   CWBackingStore|CWOverrideRedirect, &xskin_attr );

  XSelectInput( xskin_d, xskin_w,
		KeyPressMask|ExposureMask|
		EnterWindowMask|LeaveWindowMask|
		ButtonPressMask|ButtonReleaseMask|
		Button1MotionMask );

  xskin_hint.flags = USSize | PMinSize | PMaxSize | USPosition;
  xskin_hint.width = xskin_hint.min_width = xskin_hint.max_width
    = skin_width;
  xskin_hint.height = xskin_hint.min_height = xskin_hint.max_height
    = skin_height;
  XSetNormalHints( xskin_d, xskin_w, &xskin_hint );

  xskin_chint.res_name  = XSKIN_RES_NAME;
  xskin_chint.res_class = XSKIN_RES_CLASS;
  XSetClassHint( xskin_d, xskin_w, &xskin_chint );

  namlist[0]=(char *)safe_malloc(strlen(XSKIN_WINDOW_NAME)+1);
  strcpy( namlist[0], XSKIN_WINDOW_NAME );
  XmbTextListToTextProperty( xskin_d, namlist, 1, XCompoundTextStyle, &ct );
  XSetWMName( xskin_d, xskin_w, &ct );
  XSetWMIconName( xskin_d, xskin_w, &ct );
  free(namlist[0]);


  /* setup pixmaps */

  if ( load_skins()!=0 ) goto finish;

  XSetWindowBackgroundPixmap( xskin_d, xskin_w, xskin_back );
  XClearWindow( xskin_d, xskin_w );

  XMapWindow( xskin_d, xskin_w );
  while( 1 ) {
    XNextEvent( xskin_d, &xskin_e );
    if ( xskin_e.type == Expose ) break; 
  }

  fshuf=0;
  frep=0;
  fequ=1;
  fpll=1;
  fplay=0;
  fpause=0;
  fremain=0;
  play_val=1;
  vol_val=50;
  last_current_time=0;
  total_time=0;
  speana_buf = NULL;
  strcpy( last_text, "welcome to timidity" );

  install_sighandler();

  repaint();
  ts_spectrum( -1, speana_buf );

  XFlush(xskin_d);

  xskin_jobs( pipe_in );   /* tskin main jobs */

finish:
  signal_vector(0);  /* finish */
}
Example #8
0
// ===== startSystemTray() =====
WId LX11::startSystemTray(){
  qDebug() << "Starting System Tray";
  //Setup the freedesktop standards compliance
  Display *disp = QX11Info::display();
  Window root = QX11Info::appRootWindow();
  
  //Get the appropriate atom for this screen
  QString str = QString("_NET_SYSTEM_TRAY_S%1").arg(DefaultScreen(disp));
  qDebug() << "Default Screen Atom Name:" << str;
  Atom _NET_SYSTEM_TRAY_S = XInternAtom(disp,str.toAscii(),false);
  //Make sure that there is no other system tray running
  if(XGetSelectionOwner(disp, _NET_SYSTEM_TRAY_S) != None){
    qWarning() << "An alternate system tray is currently in use";
    return 0;
  }
  //Create a simple window to register as the tray (not visible)
  Window LuminaSessionTrayID = XCreateSimpleWindow(disp, root,-1,-1,1,1,0,0,0);
  //register this widget as the system tray
  XSetSelectionOwner(disp, _NET_SYSTEM_TRAY_S, LuminaSessionTrayID, CurrentTime);
  //Make sure that it was registered properly
  if(XGetSelectionOwner(disp, _NET_SYSTEM_TRAY_S) != LuminaSessionTrayID){
    qWarning() << "Could not register the system tray";
    XDestroyWindow(disp, LuminaSessionTrayID);
    return 0;
  }
  //Now register the orientation of the system tray
  //int horz = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
  //XChangeProperty(disp, trayID, XInternAtom(disp,"_NET_SYSTEM_TRAY_ORIENTATION",true),
  	  	//XA_CARDINAL, 32, PropModeReplace, (unsigned char*) &horz, 1);
  //Now get the visual ID for the system tray
  XVisualInfo *XVI = new XVisualInfo;
    XVI->screen = QX11Info::appScreen();
    XVI->depth = 32;
    XVI->c_class = TrueColor;
  int num;
  XVI = XGetVisualInfo(disp, VisualScreenMask | VisualDepthMask | VisualClassMask , XVI, &num);
  VisualID vis = 0;
  if(XVI != 0){
    XRenderPictFormat *fmt;
    for(int i=0; i<num; i++){
      fmt = XRenderFindVisualFormat(disp, XVI[i].visual);
      if( (fmt !=0) && (fmt->type == PictTypeDirect) && (fmt->direct.alphaMask!=0) ){
        vis = XVI[i].visualid;
        break;
      }
    }
  }
  XFree(XVI); //done with this - clean it up
  //Now register the visual ID
  if(vis!=0){
    XChangeProperty(disp, LuminaSessionTrayID, XInternAtom(disp,"_NET_SYSTEM_TRAY_VISUAL",true),
  	  	XA_VISUALID, 32, PropModeReplace, (unsigned char*) &vis, 1);	  
  }
  //Finally, send out an X event letting others know that the system tray is up and running
  XClientMessageEvent msg;
    msg.type = ClientMessage;
    msg.window = root;
    msg.message_type = XInternAtom(disp,"MANAGER",true);
    msg.format = 32;
    msg.data.l[0] = CurrentTime;
    msg.data.l[1] = _NET_SYSTEM_TRAY_S;
    msg.data.l[2] = LuminaSessionTrayID;
    msg.data.l[3] = 0;
    msg.data.l[4] = 0;
  XSendEvent(disp, root, False, StructureNotifyMask, (XEvent*)&msg);
  
  //Success
  return LuminaSessionTrayID;
}
Example #9
0
int
main(int argc, char **argv)
{
   Imlib_Image        *im = NULL;
   char               *file = NULL;
   int                 no = 1;
   const char         *display_name = getenv("DISPLAY");

   if (argc < 2)
      return 1;

   file = argv[no];
   if (display_name == NULL)
      display_name = ":0";
   disp = XOpenDisplay(display_name);
   if (disp == NULL)
     {
        fprintf(stderr, "Can't open display %s\n", display_name);
        return 1;
     }
   vis = DefaultVisual(disp, DefaultScreen(disp));
   depth = DefaultDepth(disp, DefaultScreen(disp));
   cm = DefaultColormap(disp, DefaultScreen(disp));
   win = XCreateSimpleWindow(disp, DefaultRootWindow(disp), 0, 0, 10, 10,
                             0, 0, 0);
   XSelectInput(disp, win, ButtonPressMask | ButtonReleaseMask |
                ButtonMotionMask | PointerMotionMask);
   imlib_context_set_display(disp);
   imlib_context_set_visual(vis);
   imlib_context_set_colormap(cm);
   imlib_context_set_progress_function(progress);
   imlib_context_set_progress_granularity(10);
   imlib_context_set_drawable(win);
   im = imlib_load_image(file);
   while (!im)
     {
        no++;
        if (no == argc)
          {
             fprintf(stderr, "Image format not available\n");
             exit(0);
          }
        file = argv[no];
        image_width = 0;
        im = imlib_load_image(file);
        imlib_context_set_image(im);
     }
   if (!im)
     {
        fprintf(stderr, "Image format not available\n");
        exit(0);
     }
   for (;;)
     {
        int                 x, y, b, count, fdsize, xfd, timeout = 0;
        XEvent              ev;
        static int          zoom_mode = 0, zx, zy;
        static double       zoom = 1.0;
        struct timeval      tval;
        fd_set              fdset;
        double              t1;

        XFlush(disp);
        XNextEvent(disp, &ev);
        switch (ev.type)
          {
          case ButtonPress:
             b = ev.xbutton.button;
             x = ev.xbutton.x;
             y = ev.xbutton.y;
             if (b == 3)
               {
                  zoom_mode = 1;
                  zx = x;
                  zy = y;
                  imlib_context_set_drawable(pm);
                  imlib_context_set_image(bg_im);
                  imlib_context_set_anti_alias(0);
                  imlib_context_set_dither(0);
                  imlib_context_set_blend(0);
                  imlib_render_image_part_on_drawable_at_size
                     (0, 0, image_width, image_height,
                      0, 0, image_width, image_height);
                  XSetWindowBackgroundPixmap(disp, win, pm);
                  XClearWindow(disp, win);
               }
             break;
          case ButtonRelease:
             b = ev.xbutton.button;
             x = ev.xbutton.x;
             y = ev.xbutton.y;
             if (b == 3)
                zoom_mode = 0;
             if (b == 1)
               {
                  no++;
                  if (no == argc)
                     no = argc - 1;
                  file = argv[no];
                  image_width = 0;
                  zoom = 1.0;
                  zoom_mode = 0;
                  imlib_context_set_image(im);
                  imlib_free_image_and_decache();
                  im = imlib_load_image(file);
                  while (!im)
                    {
                       no++;
                       if (no == argc)
                          exit(0);
                       file = argv[no];
                       image_width = 0;
                       im = imlib_load_image(file);
                    }
                  imlib_context_set_image(im);
               }
             if (b == 2)
               {
                  no--;
                  if (no == 0)
                     no = 1;
                  file = argv[no];
                  image_width = 0;
                  zoom = 1.0;
                  zoom_mode = 0;
                  imlib_context_set_image(im);
                  imlib_free_image_and_decache();
                  im = imlib_load_image(file);
                  while (!im)
                    {
                       no--;
                       if (no == 0)
                          no = 1;
                       file = argv[no];
                       image_width = 0;
                       im = imlib_load_image(file);
                    }
                  imlib_context_set_image(im);
               }
             break;
          case MotionNotify:
             while (XCheckTypedWindowEvent(disp, win, MotionNotify, &ev));
             x = ev.xmotion.x;
             y = ev.xmotion.y;
             if (zoom_mode)
               {
                  int                 sx, sy, sw, sh, dx, dy, dw, dh;

                  zoom = ((double)x - (double)zx) / 32.0;
                  if (zoom < 0)
                     zoom = 1.0 + ((zoom * 32.0) / ((double)(zx + 1)));
                  else
                     zoom += 1.0;
                  if (zoom <= 0.0001)
                     zoom = 0.0001;
                  if (zoom > 1.0)
                    {
                       dx = 0;
                       dy = 0;
                       dw = image_width;
                       dh = image_height;

                       sx = zx - (zx / zoom);
                       sy = zy - (zy / zoom);
                       sw = image_width / zoom;
                       sh = image_height / zoom;
                    }
                  else
                    {
                       dx = zx - (zx * zoom);
                       dy = zy - (zy * zoom);
                       dw = image_width * zoom;
                       dh = image_height * zoom;

                       sx = 0;
                       sy = 0;
                       sw = image_width;
                       sh = image_height;
                    }
                  imlib_context_set_anti_alias(0);
                  imlib_context_set_dither(0);
                  imlib_context_set_blend(0);
                  imlib_context_set_image(bg_im);
                  imlib_render_image_part_on_drawable_at_size
                     (sx, sy, sw, sh, dx, dy, dw, dh);
                  XSetWindowBackgroundPixmap(disp, win, pm);
                  XClearWindow(disp, win);
                  XFlush(disp);
                  timeout = 1;
               }
          default:
             break;
          }
        t1 = 0.2;
        tval.tv_sec = (long)t1;
        tval.tv_usec = (long)((t1 - ((double)tval.tv_sec)) * 1000000);
        xfd = ConnectionNumber(disp);
        fdsize = xfd + 1;
        FD_ZERO(&fdset);
        FD_SET(xfd, &fdset);
        if (timeout)
           count = select(fdsize, &fdset, NULL, NULL, &tval);
        else
           count = select(fdsize, &fdset, NULL, NULL, NULL);
        if (count < 0)
          {
             if ((errno == ENOMEM) || (errno == EINVAL) || (errno == EBADF))
                exit(1);
          }
        else
          {
             if ((count == 0) && (timeout))
               {
                  int                 sx, sy, sw, sh, dx, dy, dw, dh;

                  if (zoom > 1.0)
                    {
                       dx = 0;
                       dy = 0;
                       dw = image_width;
                       dh = image_height;

                       sx = zx - (zx / zoom);
                       sy = zy - (zy / zoom);
                       sw = image_width / zoom;
                       sh = image_height / zoom;
                    }
                  else
                    {
                       dx = zx - (zx * zoom);
                       dy = zy - (zy * zoom);
                       dw = image_width * zoom;
                       dh = image_height * zoom;

                       sx = 0;
                       sy = 0;
                       sw = image_width;
                       sh = image_height;
                    }
                  imlib_context_set_anti_alias(1);
                  imlib_context_set_dither(1);
                  imlib_context_set_blend(0);
                  imlib_context_set_image(bg_im);
                  imlib_render_image_part_on_drawable_at_size
                     (sx, sy, sw, sh, dx, dy, dw, dh);
                  XSetWindowBackgroundPixmap(disp, win, pm);
                  XClearWindow(disp, win);
                  XFlush(disp);
                  timeout = 0;
               }
          }
     }
   return 0;
}
Example #10
0
Window Xvars::create_toplevel_window(int argc,char** argv,
                                     int dpyNum,const Size& size,
                                     const char* title,
                                     long eventMask) {
  // Creates with 0 border width.
  Window toplevel = 
    XCreateSimpleWindow(dpy[dpyNum],root[dpyNum],0,0,
                        size.width,size.height,
                        0,windowBorder[dpyNum],
                        windowBg[dpyNum]);

  XSizeHints size_hints;
  size_hints.flags = PPosition | PSize | PMinSize | PMaxSize;
  size_hints.min_width = size.width;
  size_hints.min_height = size.height;
  size_hints.max_width = size.width;
  size_hints.max_height = size.height;

  XTextProperty windowName, iconName;
  // Should be safe to cast away const, XStringListToTextProperty doesn't 
  // mutate the string list argument.
  char *window_name = (char*)title;    // Will appear on window.
  char *icon_name = (char*)title;
  Status stat = XStringListToTextProperty(&window_name,1,&windowName);
  assert(stat);
  stat = XStringListToTextProperty(&icon_name,1,&iconName);
  assert(stat);
  
  // Hints to window manager.
  XWMHints wm_hints;
  wm_hints.initial_state = NormalState;
  wm_hints.input = True;
  wm_hints.flags = StateHint | InputHint;
  
  // Only set IconPixmap and IconMask hints if the pixmaps loaded 
  // correctly.
  if (iconPixmap[dpyNum]) {
    wm_hints.icon_pixmap = iconPixmap[dpyNum];
    wm_hints.flags |= IconPixmapHint;
    if (iconMask[dpyNum]) {
      wm_hints.icon_mask = iconMask[dpyNum];
      wm_hints.flags |= IconMaskHint;
    }
  }

  XClassHint class_hints;
  class_hints.res_name = argv[0];
  class_hints.res_class = "XEvil";

  XSetWMProperties(dpy[dpyNum],toplevel,
                   &windowName,&iconName,argv,argc,
                   &size_hints,&wm_hints,&class_hints);

  XSelectInput(dpy[dpyNum],toplevel,eventMask);

  // Add WM_DELETE_WINDOW protocol
  XChangeProperty(dpy[dpyNum],toplevel,
                  wmProtocols[dpyNum],XA_ATOM,
                  32,PropModePrepend,
                  (unsigned char *)&wmDeleteWindow[dpyNum],
                  1);

  return toplevel;
}
int main(void)
{
	Display *display;
	Window window;      //initialization for a window
	int screen;         //which screen

	/* open connection with the server */
	display = XOpenDisplay(NULL);
	if(display == NULL) {
		fprintf(stderr, "cannot open display\n");
		return 0;
	}

	screen = DefaultScreen(display);

	/* set window size */
	int width = 400;
	int height = 400;

	/* set window position */
	int x = 0;
	int y = 0;

	/* border width in pixels */
	int border_width = 0;

	/* create window */
	window = XCreateSimpleWindow(display, RootWindow(display, screen), x, y, width, height, border_width,
					BlackPixel(display, screen), WhitePixel(display, screen));

	/* create graph */
	GC gc;
	XGCValues values;
	long valuemask = 0;

	gc = XCreateGC(display, window, valuemask, &values);
	//XSetBackground (display, gc, WhitePixel (display, screen));
	XSetForeground (display, gc, BlackPixel (display, screen));
	XSetBackground(display, gc, 0X0000FF00);
	XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);

	/* map(show) the window */
	XMapWindow(display, window);
	XSync(display, 0);

	int* repeatsBuffer;
	repeatsBuffer  = (int*)malloc(sizeof(int) * width * height);
	const int threadNum = 50;
	pthread_t threads[threadNum];
	WorkPara* paras[threadNum];
	WorkPara* para;
	int numPerThread;
	int i;
	struct timespec timeStart, timeEnd;

	clock_gettime(CLOCK_REALTIME, &timeStart);
	numPerThread = width % threadNum == 0 ? width / threadNum : width / threadNum + 1;
	for(i=0;i<threadNum;i++){
		para = paras[i] = (WorkPara*)malloc(sizeof(WorkPara));
		para -> repeatsBuffer = repeatsBuffer;
		para -> width = width;
		para -> height = height;
		para -> start = numPerThread * i;
		para -> end = para -> start + numPerThread;
		if(para -> end > width){
			para -> end = width;
		}
		para -> tid = i;
		pthread_create(&threads[i], NULL, doWork, (void*)para);
	}

	for(i = 0; i < threadNum ; i++){
		pthread_join(threads[i],NULL);
	}
	clock_gettime(CLOCK_REALTIME, &timeEnd);
	
	printf("Time Usage: %lf s\n", (double)(timeEnd.tv_sec - timeStart.tv_sec) + (double)(timeEnd.tv_nsec - timeStart.tv_nsec)/1e9);
	fflush(stdout);
	for(i = 0; i < width * height; i++){
		XSetForeground (display, gc,  1024 * 1024 * (repeatsBuffer[i] % 256));
		//printf("%d\n",repeatsBuffer[i]);
		XDrawPoint (display, window, gc, i/width, i%width);
	}
	XFlush(display);

	for(i = 0; i < threadNum ; i++){
		free(paras[i]);
	}
	free(repeatsBuffer);

	sleep(5);
	return 0;
}
Example #12
0
int
main(int argc, char **argv)
{
   int                 w, h, tw, th;
   Imlib_Image         im_bg = NULL;
   XEvent              ev;
   KeySym              keysym;
   static char         kbuf[20];
   Imlib_Font          font;
   Imlib_Color_Range   range;
   const char         *display_name = getenv("DISPLAY");

   /**
    * First tests to determine which rendering task to perform
    */
   if (display_name == NULL)
       display_name = ":0";
   disp = XOpenDisplay(display_name);
   if (disp == NULL)
     {
       fprintf(stderr, "Can't open display %s\n", display_name);
       return 1;
     }
   vis = DefaultVisual(disp, DefaultScreen(disp));
   depth = DefaultDepth(disp, DefaultScreen(disp));
   cm = DefaultColormap(disp, DefaultScreen(disp));
   win =
       XCreateSimpleWindow(disp, DefaultRootWindow(disp), 0, 0, 100, 100, 0, 0,
                           0);
   XSelectInput(disp, win,
                ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
                PointerMotionMask | ExposureMask | KeyPressMask);
   XMapWindow(disp, win);

   /**
    * Start rendering
    */
   imlib_set_font_cache_size(512 * 1024);
   imlib_add_path_to_font_path(PACKAGE_DATA_DIR"/data/fonts");
   imlib_context_set_display(disp);
   imlib_context_set_visual(vis);
   imlib_context_set_colormap(cm);
   imlib_context_set_drawable(win);
   imlib_context_set_blend(0);
   imlib_context_set_color_modifier(NULL);
   imlib_context_set_blend(0);

   im_bg = imlib_create_image(600, 400);
   imlib_context_set_image(im_bg);
   w = imlib_image_get_width();
   h = imlib_image_get_height();
   imlib_context_set_color(128, 128, 255, 255);
   imlib_image_fill_rectangle(0, 0, w, h);
   XResizeWindow(disp, win, w, h);
   XSync(disp, False);

   while (1)
     {
        do
          {
             XNextEvent(disp, &ev);
             switch (ev.type)
               {
                 case ButtonRelease:
                    exit(0);
                    break;
                 case KeyPress:
                    XLookupString(&ev.xkey, (char *)kbuf, sizeof(kbuf), &keysym,
                                  NULL);
                    switch (*kbuf)
                      {
                        case 'q':
                           exit(0);
                        default:
                           break;
                      }
                    break;
                 default:
                    break;

               }
          }
        while (XPending(disp));

        imlib_context_set_image(im_bg);
        imlib_context_set_color(128, 128, 255, 255);
        imlib_image_fill_rectangle(0, 0, w, h);
        imlib_context_set_color(0, 0, 0, 255);
        imlib_image_draw_rectangle(20, 20, 560, 140);
        imlib_image_draw_rectangle(20, 220, 560, 140);
        font = imlib_load_font("notepad/15");
        if (font)
          {
             char                text[4096];

             imlib_context_set_font(font);
             imlib_context_set_color(0, 0, 0, 255);
             sprintf(text, "RGBA range, 2 points, from red to magenta");
             imlib_get_text_size(text, &tw, &th);
             imlib_text_draw(300 - tw / 2, 180 - th / 2, text);
             sprintf(text, "HSVA range, 2 points, from red to magenta");
             imlib_get_text_size(text, &tw, &th);
             imlib_text_draw(300 - tw / 2, 380 - th / 2, text);
             imlib_free_font();
          }

        /* Draw rectangle w/ RGBA gradient */
        range = imlib_create_color_range();
        imlib_context_set_color_range(range);
        imlib_context_set_color(255, 0, 0, 255);
        imlib_add_color_to_color_range(0);
        imlib_context_set_color(255, 0, 255, 255);
        imlib_add_color_to_color_range(20);
        imlib_image_fill_color_range_rectangle(21, 21, 558, 138, -90.0);
        imlib_free_color_range();

        /* Draw rectangle w/ HSVA gradient */
        range = imlib_create_color_range();
        imlib_context_set_color_range(range);
        imlib_context_set_color_hsva(0, 1, 1, 255);
        imlib_add_color_to_color_range(0);
        imlib_context_set_color_hsva(300, 1, 1, 255);
        imlib_add_color_to_color_range(20);
        imlib_image_fill_hsva_color_range_rectangle(21, 221, 558, 138, -90.0);
        imlib_free_color_range();

        imlib_render_image_on_drawable(0, 0);
     }
   return 0;
}
int main(int argc, char **argv)
{
    threads = atoi(argv[1]);
    
    atof(minX, 2);
    atof(maxX, 3);
    atof(minY, 4);
    atof(maxY, 5);
    width = atoi(argv[6]);
    height = atoi(argv[7]);
    
    std::string in = argv[8];
    if (in == "enable")
        isEnable = true;
    else
        isEnable = false;

/********* MPI MISSION START *********/
    
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    MPI_Comm_size (MPI_COMM_WORLD, &size);
    
    MPI_Status status;
    Display *display;
	Window window;      //initialization for a window
	int screen;         //which screen 

	/* set window position */
	int x = 0;
	int y = 0;
	
    /* create graph */
	GC gc;
	XGCValues values;
	long valuemask = 0;

	/* border width in pixels */
	int border_width = 0;
	/* open connection with the server */
    
	/* draw points */
    int numPerTask = width / (size);
    if (rank == size - 1)
       numPerTask += width % (size);
    
    if (isEnable && rank == 0) {
        display = XOpenDisplay(NULL);
        if(display == NULL) {
            fprintf(stderr, "cannot open display\n");
            return 0;
        }

        screen = DefaultScreen(display);

        /* set window size */
        
        /* create window */
        window = XCreateSimpleWindow(display, 
            RootWindow(display, screen), x, y, 
                width, height, border_width, 
                    BlackPixel(display, screen), 
                        WhitePixel(display, screen));
        
        gc = XCreateGC(display, window, valuemask, &values);
        //XSetBackground (display, gc, WhitePixel (display, screen));
        XSetForeground (display, gc, BlackPixel (display, screen));
        XSetBackground(display, gc, 0X0000FF00);
        XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);
        
        /* map(show) the window */
        XMapWindow(display, window);
        XSync(display, 0);
        if (isEnable)  
             XFlush(display);
        
    }

    Pixel *pixel = new Pixel[numPerTask * height];
    int curIndex = 0;
    int beginPos = rank != size - 1 ?  
        numPerTask * (rank) : (rank) * (numPerTask - (width % (size)));
    
     
    printf("rank %d -> begin = %d, numTasks = %d\n", rank, beginPos, numPerTask);
    int ansK = -1;
    for(int i = beginPos, k = 0; k < numPerTask; i++, k++) {
        ansK = ansK > i ? ansK : i;
        for(int j=0; j<height; j++) {
            // printf("rank %d : (%d, %d)\n", rank, i, j);
            Compl z, c;
            double temp, lengthsq;
            int repeats;
            z.real = 0.0;
            z.imag = 0.0;
            
            double scaleX = width / (maxX - minX);
            double scaleY = height / (maxY - minY);
            
            c.real = ((double)i + scaleX * minX) / scaleX; 
            /* Theorem : If c belongs to M(Mandelbrot set), then |c| <= 2 */
            
            c.imag = ((double)j + scaleY * minY) / scaleY; 
            /* So needs to scale the window */

            repeats = 0;
            lengthsq = 0.0;

            while(repeats < 10000 && lengthsq < 4.0) { 
                /* Theorem : If c belongs to M, then |Zn| <= 2. So Zn^2 <= 4 */
                temp = z.real*z.real - z.imag*z.imag + c.real;
                z.imag = 2*z.real*z.imag + c.imag;
                z.real = temp;
                lengthsq = z.real*z.real + z.imag*z.imag;
                 
                repeats++;
            }
            
            if (!isEnable) continue; 
            pixel[curIndex++] = Pixel(i, j, repeats);
        }
    }

    printf("Rank[%d] ansK = %d\n", rank, ansK);
    
    if (rank != 0) {
        send(&curIndex, 1, MPI_INT, ROOT);
       // printf("rank %d send curIndex %d ...\n", rank, curIndex);
       // sleep(5);
        send(pixel, curIndex * sizeof(Pixel), MPI_CHAR, ROOT);
       // printf("rank %d send pixel...\n", rank);
    }
    else if (isEnable) {
        for (int index = 0; index < curIndex; ++index) {
            XSetForeground (display, gc,  
                        1024 * 1024 * (pixel[index].repeats % 256));	
            XDrawPoint (display, window, gc, pixel[index].i, pixel[index].j);
        }
            
        std::vector <Pixel> drawGraph; 
        for (int threads = 1; threads < size; ++threads) {
            int pixelNum;
            recv(&pixelNum, sizeof(int), MPI_INT, threads);
            // printf("recv pixelNum =  %d\n", pixelNum);   
            Pixel *pixel = new Pixel[pixelNum];
            recv(pixel, pixelNum * sizeof(Pixel), MPI_CHAR, threads);
            for (int i = 0; i < pixelNum; ++i)
                drawGraph.push_back(pixel[i]);
            delete [] pixel;
        }
        int drawTimes = 2;
        while (drawTimes--) {
          for (int k = 0; k < drawGraph.size(); ++k) {
              int i = drawGraph[k].i;
              int j = drawGraph[k].j;
              int repeats = drawGraph[k].repeats;

              XSetForeground (display, gc,  
                          1024 * 1024 * (repeats % 256));	
              XDrawPoint (display, window, gc, i, j);
          }
        }
    }
    delete [] pixel;

    MPI_Finalize();
    if (isEnable) sleep(5);
	return 0;
}
Example #14
0
/* This function handles a GstVdpWindow creation */
static GstVdpWindow *
gst_vdp_sink_window_new (VdpSink * vdp_sink, gint width, gint height)
{
  GstVdpWindow *window = NULL;
  GstVdpDevice *device = vdp_sink->device;

  Window root;
  gint screen_num;
  gulong black;

  VdpStatus status;
  VdpColor color = { 0, };

  g_return_val_if_fail (GST_IS_VDP_SINK (vdp_sink), NULL);

  window = g_new0 (GstVdpWindow, 1);

  window->width = width;
  window->height = height;
  window->internal = TRUE;

  g_mutex_lock (vdp_sink->x_lock);

  screen_num = DefaultScreen (device->display);
  root = DefaultRootWindow (device->display);
  black = XBlackPixel (device->display, screen_num);

  window->win = XCreateSimpleWindow (vdp_sink->device->display,
      root, 0, 0, window->width, window->height, 0, 0, black);

  /* We have to do that to prevent X from redrawing the background on 
     ConfigureNotify. This takes away flickering of video when resizing. */
  XSetWindowBackgroundPixmap (vdp_sink->device->display, window->win, None);

  /* set application name as a title */
  gst_vdp_sink_window_set_title (vdp_sink, window, NULL);

  if (vdp_sink->handle_events) {
    Atom wm_delete;

    XSelectInput (vdp_sink->device->display, window->win, ExposureMask |
        StructureNotifyMask | PointerMotionMask | KeyPressMask |
        KeyReleaseMask | ButtonPressMask | ButtonReleaseMask);

    /* Tell the window manager we'd like delete client messages instead of
     * being killed */
    wm_delete =
        XInternAtom (vdp_sink->device->display, "WM_DELETE_WINDOW", False);
    (void) XSetWMProtocols (vdp_sink->device->display, window->win, &wm_delete,
        1);
  }

  XMapRaised (vdp_sink->device->display, window->win);

  XSync (vdp_sink->device->display, FALSE);

  g_mutex_unlock (vdp_sink->x_lock);

  gst_vdp_sink_window_decorate (vdp_sink, window);

  status = device->vdp_presentation_queue_target_create_x11 (device->device,
      window->win, &window->target);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not create presentation target"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));
  }

  status =
      device->vdp_presentation_queue_create (device->device, window->target,
      &window->queue);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not create presentation queue"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));
  }

  status =
      device->vdp_presentation_queue_set_background_color (window->queue,
      &color);
  if (status != VDP_STATUS_OK) {
    GST_ELEMENT_ERROR (vdp_sink, RESOURCE, READ,
        ("Could not set background color"),
        ("Error returned from vdpau was: %s",
            device->vdp_get_error_string (status)));
  }

  gst_x_overlay_got_xwindow_id (GST_X_OVERLAY (vdp_sink), window->win);

  return window;
}
Example #15
0
Display * x11setup(Window *win, GC *gc, int width, int height)
{

    /* --------------------------- X11 graphics setup ------------------------------ */
    Display 		*display;
    unsigned int 	win_x,win_y, /* window position */
                    border_width, /* border width in pixels */
                    display_width, display_height, /* size of screen */
                    screen; /* which screen */

    char 			window_name[] = "N-Body Simulation", *display_name = NULL;
    unsigned long 	valuemask = 0;
    XGCValues 		values;

    XSizeHints 		size_hints;

    //Pixmap 		bitmap;
    //XPoint 		points[800];
    FILE 			*fopen ();//, *fp;
    //char 			str[100];

    XSetWindowAttributes attr[1];

    if ( (display = XOpenDisplay (display_name)) == NULL ) { /* connect to Xserver */
        fprintf (stderr, "Cannot connect to X server %s\n",XDisplayName (display_name) );
        exit (-1);
    }

    screen = DefaultScreen (display); /* get screen size */
    display_width = DisplayWidth (display, screen);
    display_height = DisplayHeight (display, screen);

    win_x = 0; win_y = 0; /* set window position */

    border_width = 4; /* create opaque window */
    *win = XCreateSimpleWindow (display, RootWindow (display, screen),
            win_x, win_y, width, height, border_width,
            WhitePixel (display, screen), BlackPixel (display, screen));

    size_hints.flags = USPosition|USSize;
    size_hints.x = win_x;
    size_hints.y = win_y;
    size_hints.width = width;
    size_hints.height = height;
    size_hints.min_width = 300;
    size_hints.min_height = 300;

    XSetNormalHints (display, *win, &size_hints);
    XStoreName(display, *win, window_name);

    *gc = XCreateGC (display, *win, valuemask, &values); /* create graphics context */

    XSetBackground (display, *gc, BlackPixel (display, screen));
    XSetForeground (display, *gc, WhitePixel (display, screen));
    XSetLineAttributes (display, *gc, 1, LineSolid, CapRound, JoinRound);

    attr[0].backing_store = Always;
    attr[0].backing_planes = 1;
    attr[0].backing_pixel = BlackPixel(display, screen);

    XChangeWindowAttributes(display, *win, CWBackingStore | CWBackingPlanes | CWBackingPixel, attr);

    XSelectInput(display, *win, KeyPressMask);

    XMapWindow (display, *win);
    XSync(display, 0);

    /* --------------------------- End of X11 graphics setup ------------------------------ */
    return display;
}
Example #16
0
static XIMHandle*
_open_imdkit(const char* _server_name, const char* _locale)
{
    XIMStyle ims_styles_onspot [] = {
        XIMPreeditPosition | XIMStatusArea,        //OverTheSpot
        XIMPreeditPosition | XIMStatusNothing,     //OverTheSpot
        XIMPreeditPosition | XIMStatusNone,        //OverTheSpot
        XIMPreeditNothing  | XIMStatusNothing,     //Root
        XIMPreeditNothing  | XIMStatusNone,        //Root
        0
    };
    XIMEncoding ims_encodings[] = {
        "COMPOUND_TEXT",
        0
    };

    /* this is rarely documentated, the trigger condition is
     *
     * keycode == keysym && (state & modifier_mask) == modifier
     *
     * where keycode and state is the user pressed
     */
    hotkey_t hk;
    settings_get(TRIGGER_KEY, &hk);
    XIMTriggerKey trigger = {
        .keysym = hk.keysym,
        .modifier = hk.modifiers,
        .modifier_mask = STATE_MASK
    };

    XIMTriggerKeys keys;
    XIMStyles styles;
    XIMEncodings encodings;

    styles.count_styles =
        sizeof (ims_styles_onspot)/sizeof (XIMStyle) - 1;
    styles.supported_styles = ims_styles_onspot;

    encodings.count_encodings =
        sizeof (ims_encodings)/sizeof (XIMEncoding) - 1;
    encodings.supported_encodings = ims_encodings;

    keys.count_keys = 1;
    keys.keylist = &trigger;

    Window win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy),
                                     0, 0, 1, 1, 1, 0, 0);
    XSelectInput(dpy, win,
                 ExposureMask | ButtonPressMask | ButtonReleaseMask
                 | ButtonMotionMask | VisibilityChangeMask);

    XIMHandle* handle =
        IMOpenIM(dpy,
                 IMModifiers, "Xi18n",
                 IMServerWindow, win,
                 IMServerName, _server_name,
                 IMLocale, _locale,
                 IMServerTransport, "X/",
                 IMInputStyles, &styles,
                 IMEncodingList, &encodings,
                 IMProtocolHandler, _imdkit_protocol_hanlder,
                 IMFilterEventMask, KeyPressMask | KeyReleaseMask,
                 IMOnKeysList, &keys,
                 NULL);
    if (handle == NULL) {
        fprintf(stderr, "Startup xim server failed.\n");
        fprintf(stderr, "Your locale is %s, please file a bug.", _locale);
    }
    return handle;
}

XIMHandle*
create_xim_server(const char* server_name, const char* locale)
{
    XIMHandle* handle = _open_imdkit(server_name, locale);
    icmgr_init();
    return handle;
}
Example #17
0
gboolean
xfce_xsettings_helper_register (XfceXSettingsHelper *helper,
                                GdkDisplay          *gdkdisplay,
                                gboolean             force_replace)
{
    Display             *xdisplay;
    Window               root_window;
    Window               window;
    gchar                atom_name[64];
    Atom                 selection_atom;
    gint                 n_screens, n;

    XfceXSettingsScreen *screen;
    Time                 timestamp;
    XClientMessageEvent  xev;
    gboolean             succeed;

    g_return_val_if_fail (GDK_IS_DISPLAY (gdkdisplay), FALSE);
    g_return_val_if_fail (XFCE_IS_XSETTINGS_HELPER (helper), FALSE);
    g_return_val_if_fail (helper->screens == NULL, FALSE);

    xdisplay = GDK_DISPLAY_XDISPLAY (gdkdisplay);
    helper->xsettings_atom = XInternAtom (xdisplay, "_XSETTINGS_SETTINGS", False);

    gdk_error_trap_push ();

    n_screens = gdk_display_get_n_screens (gdkdisplay);
    for (n = 0; n < n_screens; n++)
    {
        g_snprintf (atom_name, sizeof (atom_name), "_XSETTINGS_S%d", n);
        selection_atom = XInternAtom (xdisplay, atom_name, False);

        if (!force_replace
            && XGetSelectionOwner (xdisplay, selection_atom) != None)
        {
            g_message ("Skipping screen %d, it already has an xsettings manager...", n);
            continue;
        }

        succeed = FALSE;

        /* create new window */
        root_window = RootWindow (xdisplay, n);
        window = XCreateSimpleWindow (xdisplay, root_window, -1, -1, 1, 1, 0, 0, 0);
        g_assert (window != 0);
        XSelectInput (xdisplay, window, PropertyChangeMask);

        /* get the current xserver timestamp */
        timestamp = xfce_xsettings_get_server_time (xdisplay, window);

        /* request ownership of the xsettings selection on this screen */
        XSetSelectionOwner (xdisplay, selection_atom, window, timestamp);

        /* check if the have the selection */
        if (G_LIKELY (XGetSelectionOwner (xdisplay, selection_atom) == window))
        {
            /* register this xsettings window for this screen */
            xev.type = ClientMessage;
            xev.window = root_window;
            xev.message_type = XInternAtom (xdisplay, "MANAGER", True);
            xev.format = 32;
            xev.data.l[0] = timestamp;
            xev.data.l[1] = selection_atom;
            xev.data.l[2] = window;
            xev.data.l[3] = 0;  /* manager specific data */
            xev.data.l[4] = 0;  /* manager specific data */

            if (XSendEvent (xdisplay, root_window, False,
                            StructureNotifyMask, (XEvent *)&xev) != 0)
            {
                /* the window was successfully registered as the new
                 * xsettings window for this screen */
                succeed = TRUE;
            }
            else
            {
                g_warning ("Failed to register the xsettings window for screen %d", n);
            }
        }
        else
        {
            g_warning ("Unable to get the xsettings selection for screen %d", n);
        }

        if (G_LIKELY (succeed))
        {
            /* add the window to the internal list */
            screen = g_slice_new0 (XfceXSettingsScreen);
            screen->window = window;
            screen->selection_atom = selection_atom;
            screen->xdisplay = xdisplay;
            screen->screen_num = n;

            xfsettings_dbg (XFSD_DEBUG_XSETTINGS, "%s registered on screen %d", atom_name, n);

            helper->screens = g_slist_prepend (helper->screens, screen);
        }
        else
        {
            XDestroyWindow (xdisplay, window);
        }
    }

    if (gdk_error_trap_pop () != 0)
        g_critical ("Failed to initialize screens");

    if (helper->screens != NULL)
    {
        /* watch for selection changes */
        gdk_window_add_filter (NULL, xfce_xsettings_helper_event_filter, helper);

        /* send notifications */
        xfce_xsettings_helper_notify (helper);
        xfce_xsettings_helper_notify_xft (helper);

        /* startup fontconfig monitoring */
        helper->fc_init_id = g_idle_add (xfce_xsettings_helper_fc_init, helper);

        return TRUE;
    }

    return FALSE;
}
Example #18
0
value caml_gr_open_graph(value arg)
{
  char display_name[256], geometry_spec[64];
  char * p, * q;
  XSizeHints hints;
  int ret;
  XEvent event;
  int x, y, w, h;
  XWindowAttributes attributes;

  if (caml_gr_initialized) {
    caml_gr_clear_graph();
  } else {

    /* Parse the argument */
    for (p = String_val(arg), q = display_name; *p != 0 && *p != ' '; p++)
      if (q < display_name + sizeof(display_name) - 1) *q++ = *p;
    *q = 0;
    while (*p == ' ') p++;
    for (q = geometry_spec; *p != 0; p++)
      if (q < geometry_spec + sizeof(geometry_spec) - 1) *q++ = *p;
    *q = 0;

    /* Open the display */
    if (caml_gr_display == NULL) {
      caml_gr_display = XOpenDisplay(display_name);
      if (caml_gr_display == NULL)
        caml_gr_fail("Cannot open display %s", XDisplayName(display_name));
      caml_gr_screen = DefaultScreen(caml_gr_display);
      caml_gr_black = BlackPixel(caml_gr_display, caml_gr_screen);
      caml_gr_white = WhitePixel(caml_gr_display, caml_gr_screen);
      caml_gr_background = caml_gr_white;
      caml_gr_colormap = DefaultColormap(caml_gr_display, caml_gr_screen);
    }

    /* Set up the error handlers */
    XSetErrorHandler(caml_gr_error_handler);
    XSetIOErrorHandler(caml_gr_ioerror_handler);

    /* Parse the geometry specification */
    hints.x = 0;
    hints.y = 0;
    hints.width = DEFAULT_SCREEN_WIDTH;
    hints.height = DEFAULT_SCREEN_HEIGHT;
    hints.flags = PPosition | PSize;
    hints.win_gravity = 0;

    ret = XWMGeometry(caml_gr_display, caml_gr_screen, geometry_spec, "", BORDER_WIDTH,
                      &hints, &x, &y, &w, &h, &hints.win_gravity);
    if (ret & (XValue | YValue)) {
      hints.x = x; hints.y = y; hints.flags |= USPosition;
    }
    if (ret & (WidthValue | HeightValue)) {
      hints.width = w; hints.height = h; hints.flags |= USSize;
    }

    /* Initial drawing color is black */
    caml_gr_color = 0; /* CAML COLOR */

    /* Create the on-screen window */
    caml_gr_window.w = hints.width;
    caml_gr_window.h = hints.height;
    caml_gr_window.win =
      XCreateSimpleWindow(caml_gr_display, DefaultRootWindow(caml_gr_display),
                          hints.x, hints.y, hints.width, hints.height,
                          BORDER_WIDTH, caml_gr_black, caml_gr_background);
    p = window_name;
    if (p == NULL) p = DEFAULT_WINDOW_NAME;
    /* What not use XSetWMProperties? */
    XSetStandardProperties(caml_gr_display, caml_gr_window.win, p, p,
                           None, NULL, 0, &hints);
    caml_gr_window.gc = XCreateGC(caml_gr_display, caml_gr_window.win, 0, NULL);
    XSetBackground(caml_gr_display, caml_gr_window.gc, caml_gr_background);
    XSetForeground(caml_gr_display, caml_gr_window.gc, caml_gr_black);

    /* Require exposure, resize and keyboard events */
    caml_gr_selected_events = DEFAULT_SELECTED_EVENTS;
    XSelectInput(caml_gr_display, caml_gr_window.win, caml_gr_selected_events);

    /* Map the window on the screen and wait for the first Expose event */
    XMapWindow(caml_gr_display, caml_gr_window.win);
    do { XNextEvent(caml_gr_display, &event); } while (event.type != Expose);

    /* Get the actual window dimensions */
    XGetWindowAttributes(caml_gr_display, caml_gr_window.win, &attributes);
    caml_gr_window.w = attributes.width;
    caml_gr_window.h = attributes.height;

    /* Create the pixmap used for backing store */
    caml_gr_bstore.w = caml_gr_window.w;
    caml_gr_bstore.h = caml_gr_window.h;
    caml_gr_bstore.win =
      XCreatePixmap(caml_gr_display, caml_gr_window.win, caml_gr_bstore.w, caml_gr_bstore.h,
                    XDefaultDepth(caml_gr_display, caml_gr_screen));
    caml_gr_bstore.gc = XCreateGC(caml_gr_display, caml_gr_bstore.win, 0, NULL);
    XSetBackground(caml_gr_display, caml_gr_bstore.gc, caml_gr_background);

    /* Clear the pixmap */
    XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_background);
    XFillRectangle(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
                   0, 0, caml_gr_bstore.w, caml_gr_bstore.h);
    XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_black);

    /* Set the display and remember modes on */
    caml_gr_display_modeflag = True ;
    caml_gr_remember_modeflag = True ;

    /* The global data structures are now correctly initialized.
       In particular, caml_gr_sigio_handler can now handle events safely. */
    caml_gr_initialized = True;

    /* If possible, request that system calls be restarted after
       the EVENT_SIGNAL signal. */
#ifdef POSIX_SIGNALS
#ifdef SA_RESTART
    { struct sigaction action;
      sigaction(EVENT_SIGNAL, NULL, &action);
      action.sa_flags |= SA_RESTART;
      sigaction(EVENT_SIGNAL, &action, NULL);
    }
#endif
#endif

#ifdef USE_ASYNC_IO
    /* If BSD-style asynchronous I/O are supported:
       arrange for I/O on the connection to trigger the SIGIO signal */
    ret = fcntl(ConnectionNumber(caml_gr_display), F_GETFL, 0);
    fcntl(ConnectionNumber(caml_gr_display), F_SETFL, ret | FASYNC);
    fcntl(ConnectionNumber(caml_gr_display), F_SETOWN, getpid());
#endif
  }
#ifdef USE_INTERVAL_TIMER
  /* If BSD-style interval timers are provided, use the real-time timer
     to poll events. */
  { struct itimerval it;
    it.it_interval.tv_sec = 0;
    it.it_interval.tv_usec = 250000;
    it.it_value.tv_sec = 0;
    it.it_value.tv_usec = 250000;
    setitimer(ITIMER_REAL, &it, NULL);
  }
#endif
#ifdef USE_ALARM
  /* The poor man's solution: use alarm to poll events. */
  alarm(1);
#endif
  /* Position the current point at origin */
  caml_gr_x = 0;
  caml_gr_y = 0;
  /* Reset the color cache */
  caml_gr_init_color_cache();
  caml_gr_init_direct_rgb_to_pixel();
  return Val_unit;
}
Example #19
0
File: viewer.c Project: jafp/eyebot
int main(int argc, char* argv[])
{
    struct timeval begin, now;
    long counter;

    printf("\n -- EYEBOT Viewer -- \n\n");

    // Allocate buffers
    img_buffer = malloc(SIZE * CHANNELS);
    read_buffer = malloc(SIZE + PADDING);

    scaled_up_img = malloc(UP_S * CHANNELS);
    scaled_up_img_dbl = malloc(UP_S * CHANNELS);

    unsigned char b[4096];

    display = XOpenDisplay(NULL);
    visual = DefaultVisual(display, 0);
    
    window = XCreateSimpleWindow(display, RootWindow(display, 0), 0, 0, 320, 300, 1, 0, 0);
    XMapWindow(display, window);
    XFlush(display);

    if(visual->class!=TrueColor)
    {
        fprintf(stderr, "Cannot handle non true color visual ...\n");
        exit(1);
    }

    //XMapWindow(display, window);
    //XFlush(display);

    image = NULL;

    struct addrinfo hints, *res;
    int socket_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(socket_fd == -1)
    {
        printf("Could not make a socket\n");
        return 1;
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo(SERVER_HOSTNAME, SERVER_PORT, &hints, &res);

    sleep(1);
    memset(b, 0, sizeof(b));
    sprintf(b, "Eyebot Line Follower - LiveEye");
    XSetForeground(display, DefaultGC(display, 0), 0x00ff0000); // red
    XDrawString(display, window, DefaultGC(display, 0), 10, 20, b, strlen(b));
    
    memset(b, 0, sizeof(b));
    sprintf(b, "Copyright (C) 2013 Andre Christensen and Jacob Pedersen");
    XSetForeground(display, DefaultGC(display, 0), 0x000000EF); // red
    XDrawString(display, window, DefaultGC(display, 0), 10, 35, b, strlen(b));

    XFlush(display);

    while (1)
    {
        printf("Connecting to EYEBOT! (%s:%s)\n", SERVER_HOSTNAME, SERVER_PORT);

        // Connect loop
        while (1)
        {
            if (connect(socket_fd, res->ai_addr, res->ai_addrlen) == -1)
            {
                sleep(1);
            } 
            else
            {
                printf("Connected!\n");
                break;
            }
        }

        // Two seconds of timeout. Useful so that recv doesn't wait 
        // forever to receive all its bytes.
        struct timeval tv;
        tv.tv_sec = 2;  
        tv.tv_usec = 0; 
        setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));

        // Measure time at beginning
        counter = 0;
        gettimeofday(&begin, NULL);

        // Frame update loop
        while (1)
        {
            int bytes_read;
            int total = 0;
            unsigned int x = 0, y = 0, error, error_upper, mass;
            int l_x, l_y, u_x, u_y;

            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(socket_fd, &fds);

            struct timeval timeout;
            timeout.tv_sec = 6 * 60;
            timeout.tv_usec = 0;

            if (select(sizeof(fds) * 8, &fds, NULL, NULL, &timeout) < 0)
            {
                exitp("select()");
            }

            if (read(socket_fd, &l_x, sizeof(l_x)) < 0)
            {
                exitp("read() (error x)");
            }

            if (read(socket_fd, &l_y, sizeof(l_y)) < 0)
            {
                exitp("read() (error y)");
            }

            if (read(socket_fd, &u_x, sizeof(u_x)) < 0)
            {
                exitp("read() (error x)");
            }

            if (read(socket_fd, &u_y, sizeof(u_y)) < 0)
            {
                exitp("read() (error y)");
            }

            if (read(socket_fd, &error, sizeof(error)) < 0)
            {
                exitp("read() (error)");
            }

            if (read(socket_fd, &error_upper, sizeof(error_upper)) < 0)
            {
                exitp("read() (error)");
            }


            if (read(socket_fd, &mass, sizeof(mass)) < 0)
            {
                exitp("read() (error mass)");
            }

            // Clear the read buffer
            memset(read_buffer, 0, SIZE);

            //
            // Read the 76800 bytes a frame consist of
            //
            
            bytes_read = recv(socket_fd, read_buffer, SIZE, MSG_WAITALL);
            if (bytes_read < 0)
            {
                perror("recv");
                break;
            }
            else if (bytes_read == SIZE)
            {
                copy_to_x_buffer(read_buffer, bytes_read);
                draw_center_point(l_x, l_y, 0, 0, 255);
                draw_center_point(u_x, u_y, 0, 255, 0);
                draw_center_lines();

                //upscale_image();

                if (image != NULL)
                {
                    XDestroyImage(image);
                }

                //upscale_image();
                //draw_center_point2(l_x, l_y, 0, 0, 255);
                //draw_center_point2(u_x, u_y, 0, 255, 0);
                //draw_center_lines2();

                //scaled_up_img_dbl = malloc(UP_S * CHANNELS);
                //memcpy(scaled_up_img_dbl, scaled_up_img, UP_S * CHANNELS);


                // Allocate a new buffer for next frame. 
                // The old one is freed by XDestroyImage
                img_disp_buffer = (unsigned char *) malloc(SIZE * CHANNELS);
                memcpy(img_disp_buffer, img_buffer, SIZE * CHANNELS);
                
                image = XCreateImage(display, visual, 24, ZPixmap, 0, img_disp_buffer, 320, 240, 32, 0);
                XPutImage(display, window, DefaultGC(display, 0), image, 0, 0, 0, 0, 320, 240);

                //image = XCreateImage(display, visual, 24, ZPixmap, 0, scaled_up_img_dbl, 640, 480, 32, 0);
                //XPutImage(display, window, DefaultGC(display, 0), image, 0, 0, 0, 0, 640, 480);

                // Clear text area
                XSetForeground(display, DefaultGC(display, 0), 0x00ffffff); 
                XFillRectangle(display, window, DefaultGC(display, 0), 0, 240, 320, 60);

                // memset(b, 0, sizeof(b));
                // sprintf(b, "Center: (%d, %d)", x,y);
                XSetForeground(display, DefaultGC(display, 0), 0x00ff0000); // red
                // XDrawString(display, window, DefaultGC(display, 0), 5, 260, b, strlen(b));

                memset(b, 0, sizeof(b));
                sprintf(b, "Error (upper): %d", error_upper);
                XDrawString(display, window, DefaultGC(display, 0), 5, 250, b, strlen(b));

                memset(b, 0, sizeof(b));
                sprintf(b, "Error (lower): %d", error);
                XDrawString(display, window, DefaultGC(display, 0), 5, 280, b, strlen(b));

                memset(b, 0, sizeof(b));
                sprintf(b, "Mass: %d", mass);
                XDrawString(display, window, DefaultGC(display, 0), 150, 250, b, strlen(b));


                // Calculate and display fps
                gettimeofday(&now, NULL);
                double  elapsed = (now.tv_sec - begin.tv_sec) * 1000.0;
                elapsed += (now.tv_usec - begin.tv_usec) / 1000.0;
                elapsed /= 1000.0;
                memset(b, 0, sizeof(b));
                sprintf(b, "FPS: %.2f", ((counter / elapsed) * 3));
                XDrawString(display, window, DefaultGC(display, 0), 150, 280, b, strlen(b));

                counter++;
            }
            else
            {   
                printf("Connection lost - retrying!\n");
                close(socket_fd);
                break;
            }
        }
    }

	printf("Closing the socket\n");
    if(close(socket_fd) == -1)
    {
    	printf("Could not close socket\n");
     	return 0;
    }
}
Example #20
0
void addLayer(Window canvas){
  GC mask_gc;
  GC gc;
  int i;

  unsigned long background = WhitePixel(dis,0);

  if(layer_num>=MAX_LAYER)return;

  //レイヤーの作成
  layer[layer_num].win = XCreateSimpleWindow( dis, canvas,
					      0, 0,
					      CANV_WIDTH, CANV_HEIGHT,
					      0, 0, background );
  XSetWindowBackgroundPixmap( dis, layer[layer_num].win, None );//背景を透明に
    
  XSelectInput( dis, layer[layer_num].win,
		Button1MotionMask
		|ButtonPressMask
		|ButtonReleaseMask
		|ExposureMask );
  //レイヤーマスクの作成
  layer[layer_num].mask = XCreatePixmap(dis, canvas, CANV_WIDTH, CANV_HEIGHT, 1);

  //再描画のための画面保存用ピクスマップの作成
  layer[layer_num].exact = XCreatePixmap(dis, canvas, CANV_WIDTH, CANV_HEIGHT,
					 DefaultDepth(dis,0));

  //マスク用1ビットGC取得&標準設定
  mask_gc = XCreateGC( dis, layer[layer_num].mask, 0, 0 );
  XFillRectangle(dis,layer[layer_num].mask,mask_gc,0,0,CANV_WIDTH,CANV_HEIGHT);//マスクの初期化(すべて0にする)
  XShapeCombineMask( dis, layer[layer_num].win, ShapeBounding, 0, 0,//レイヤーをマスクの
		     layer[layer_num].mask, ShapeSet);              // 1の部分のみの形にする
  XShapeCombineMask( dis, layer[layer_num].win, ShapeClip, 0, 0,    // ShapeBounding :ボーダーの外枠設定
		     layer[layer_num].mask, ShapeSet);              // ShapeClip     :ボーダーの内枠設定
  //通常GC取得&標準設定
  gc = XCreateGC( dis, layer[layer_num].win, 0, 0 );
  XSetForeground( dis, gc, GetColor( dis, "white")  );
  XFillRectangle(dis,layer[layer_num].exact,gc,0,0,CANV_WIDTH,CANV_HEIGHT);//再描画用ピクスマップの初期化


  //名前の設定
  sprintf(layer[layer_num].name,"Layer%d",layer_num);

  //可視、書き込み設定の初期化
  layer[layer_num].visible=1;
  layer[layer_num].writable=1;

  //レイヤーの表示
  XMapWindow( dis, layer[layer_num].win);
  //スタック順をずらして追加
  for(i=layer_num;i>0;i++){
    stack[i+1]=stack[i];
  }
  stack[0]=layer_num;

  //使用レイヤー数を増やす
  layer_num++;
  //使用したGCの解放
  XFreeGC(dis,gc);
  XFreeGC(dis,mask_gc);
}
Example #21
0
void
ndga_process_event(struct ndga_state * sp, XEvent * event)
{
	NRectangle	rectangle;

	if (!sp)
		return;

	if (event->xany.type == Expose) {
#ifdef X_VISIBILITY_BUG
		if (sp->clearOnExpose) {
			NDestroyRegion(sp->region);
			sp->region = NCreateRegion();
			sp->clearOnExpose = 0;
		}
#endif /* X_VISIBILITY_BUG */
		rectangle.x = event->xexpose.x;
		rectangle.y = event->xexpose.y;
		rectangle.width = event->xexpose.width;
		rectangle.height = event->xexpose.height;
		NUnionRectWithRegion(&rectangle, sp->region, sp->region);

		DBG(fprintf(stderr, "Expose: %d,%d %dx%d\n",
			event->xexpose.x,
			event->xexpose.y,
			event->xexpose.width,
			event->xexpose.height));
		if (event->xexpose.count == 0) {
			/*
			 * Handle the last in a sequence of expose events.
			 */
			sp->is_changed = 1;
		}
	} else if (event->xany.type == VisibilityNotify) {
		sp->is_visible =
		    (event->xvisibility.state != VisibilityFullyObscured);
		sp->is_unobscured =
		    (event->xvisibility.state == VisibilityUnobscured);
		sp->is_changed = 1;
		DBG(fprintf(stderr, "Visiblility: %s\n",
			(event->xvisibility.state == VisibilityUnobscured) ?
			"Unobscured" :
			((event->xvisibility.state == VisibilityFullyObscured) ?
			    "FullyObscured" : "PartuallyObscured")));
		if (event->xvisibility.state == VisibilityPartiallyObscured) {
			Window		w;
			DBG(fprintf(stderr, "Request full clip\n"));

			NDestroyRegion(sp->region);
			sp->region = NCreateRegion();

			w = XCreateSimpleWindow(sp->display, sp->window,
			    0, 0, 30000, 30000, 0, 0, 0);
			XMapWindow(sp->display, w);
			XFlush(sp->display);
			XDestroyWindow(sp->display, w);
			XFlush(sp->display);
			/*
			 * sync so we will get expose events all together
			 */ 
			XSync(sp->display, False);
		}
	} else if (event->xany.type == UnmapNotify) {
		DBG(fprintf(stderr, "Unmap\n"));
		sp->is_changed = 1;
		NDestroyRegion(sp->region);
		sp->region = NCreateRegion();
	} else if (event->xany.type == ConfigureNotify) {
		DBG(fprintf(stderr, "Configure\n"));
		sp->is_changed = 1;
	} else if (event->xany.type == CirculateNotify) {
		DBG(fprintf(stderr, "Circulate\n"));
	} else if (event->xany.type == MapNotify) {
		DBG(fprintf(stderr, "Map\n"));
	} else {
		DBG(fprintf(stderr, "Event %d\n", event->xany.type));
	}

	if (XPending(sp->display) != 0)
		return;
	DBG(fprintf(stderr, "Last Event\n\n"));

	if ((sp->on_open || sp->on_close) && sp->is_changed) {
		if (sp->is_open != sp->was_open) {
			if (!sp->is_open) {
				DBG(fprintf(stderr, "I-CLOSED\n"));
				if (sp->on_close)
					(*sp->on_close) ();
			} else {
				DBG(fprintf(stderr, "I-OPEN\n"));
				if (sp->on_open)
					(*sp->on_open) ();
			}

			sp->was_open = sp->is_open;
		}
	}

	if (sp->is_changed) {
		ndga_handle_change(sp);
		if (!sp->busy)
			sp->is_changed = 0;
	}

	if (!sp->busy && sp->new_clip) {
		update_clip(sp);
	}
}
Example #22
0
void dpy_start(void)
{
	display = XOpenDisplay(NULL);
	if (!display)
	{
		fprintf(stderr, "Error: can't open display. Is DISPLAY set?\n");
		exit(1);
	}

	window = XCreateSimpleWindow(display, RootWindow(display, 0),
					  0, 0, 800, 600, 0, 0, BlackPixel(display, 0));
	XStoreName(display, window, "WordGrinder " VERSION);
	XSetClassHint(display, window,
		&((XClassHint) { "WordGrinder", "WordGrinder" }));
	XSelectInput(display, window,
		StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask);
	XMapWindow(display, window);

	glyphcache_init();

	colours[COLOUR_BLACK]  = load_colour("X11_BLACK_COLOUR",  "#000000");
	colours[COLOUR_DIM]    = load_colour("X11_DIM_COLOUR",    "#555555");
	colours[COLOUR_NORMAL] = load_colour("X11_NORMAL_COLOUR", "#888888");
	colours[COLOUR_BRIGHT] = load_colour("X11_BRIGHT_COLOUR", "#ffffff");

	draw = XftDrawCreate(display, window,
		DefaultVisual(display, DefaultScreen(display)),
		DefaultColormap(display, DefaultScreen(display)));

	xim = XOpenIM(display, NULL, NULL, NULL);
	if (xim)
		xic = XCreateIC(xim, XNInputStyle,
			XIMPreeditNothing | XIMStatusNothing, XNClientWindow, window, NULL);
	if (!xim || !xic)
	{
		fprintf(stderr, "Error: couldn't set up input methods\n");
		exit(1);
	}
	XSetICFocus(xic);

	{
		XGCValues gcv =
		{
			.graphics_exposures = false
		};

		gc = XCreateGC(display, window, GCGraphicsExposures, &gcv);
	}

	screenwidth = screenheight = 0;
	cursorx = cursory = 0;
}

void dpy_shutdown(void)
{
}

void dpy_clearscreen(void)
{
	dpy_cleararea(0, 0, screenwidth-1, screenheight-1);
}
Example #23
0
/*
 * Creates the playing windows.
 * Returns 0 on success, -1 on error.
 */
int Init_playing_windows(void)
{
    unsigned			w, h;
    Pixmap			pix;
    GC				cursorGC;

    if (!topWindow) {
	if (Init_top())
	    return -1;
    }

    Scale_dashes();

    draw_width = top_width - (256 + 2);
    draw_height = top_height;
    drawWindow = XCreateSimpleWindow(dpy, topWindow, 258, 0,
				     draw_width, draw_height,
				     0, 0, colors[BLACK].pixel);
    radarWindow = XCreateSimpleWindow(dpy, topWindow, 0, 0,
				      256, RadarHeight, 0, 0,
				      colors[BLACK].pixel);
    radar_score_mapped = true;

    /* Create buttons */
#define BUTTON_WIDTH	84
    ButtonHeight = buttonFont->ascent + buttonFont->descent + 2*BTN_BORDER;

    button_form
	= Widget_create_form(0, topWindow,
			     0, (int)RadarHeight,
			     256, ButtonHeight + 2,
			     0);
    Widget_create_activate(button_form,
			   0 + 0*BUTTON_WIDTH, 0,
			   BUTTON_WIDTH, ButtonHeight,
			   1, "QUIT",
			   Quit_callback, NULL);
    Widget_create_activate(button_form,
			   1 + 1*BUTTON_WIDTH, 0,
			   BUTTON_WIDTH, ButtonHeight,
			   1, "ABOUT",
			   About_callback, NULL);
    menu_button
	= Widget_create_menu(button_form,
			     2 + 2*BUTTON_WIDTH, 0,
			     BUTTON_WIDTH, ButtonHeight,
			     1, "MENU");
    Widget_add_pulldown_entry(menu_button,
			      "KEYS", Keys_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "CONFIG", Config_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "COLORS", Colors_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "SCORE", Score_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "PLAYER", Player_callback, NULL);
    Widget_add_pulldown_entry(menu_button,
			      "MOTD", Motd_callback, NULL);
    Widget_map_sub(button_form);

    /* Create score list window */
    players_width = RadarWidth;
    players_height = top_height - (RadarHeight + ButtonHeight + 2);
    playersWindow
	= XCreateSimpleWindow(dpy, topWindow,
			      0, (int)RadarHeight + ButtonHeight + 2,
			      players_width, players_height,
			      0, 0,
			      colors[windowColor].pixel);

    /*
     * Selecting the events we can handle.
     */
    XSelectInput(dpy, radarWindow, ExposureMask);
    XSelectInput(dpy, playersWindow, ExposureMask);
    XSelectInput(dpy, drawWindow, ButtonPressMask | ButtonReleaseMask);

    /*
     * Initialize misc. pixmaps if we're not color switching.
     * (This could be in dbuff_init_buffer completely IMHO, -- Metalite)
     */
    switch (dbuf_state->type) {

    case PIXMAP_COPY:
	radarPixmap
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	radarPixmap2
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	drawPixmap
	    = XCreatePixmap(dpy, drawWindow, draw_width, draw_height,
			    dispDepth);
	break;

    case MULTIBUFFER:
	radarPixmap
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	radarPixmap2
	    = XCreatePixmap(dpy, radarWindow, 256, RadarHeight, dispDepth);
	dbuff_init_buffer(dbuf_state);
	break;

    case COLOR_SWITCH:
	radarPixmap2 = radarWindow;
	radarPixmap = radarWindow;
	drawPixmap = drawWindow;
	Paint_sliding_radar();
	break;

    default:
	assert(0 && "Init_playing_windows: unknown dbuf state type.");
	break;
    }

    XAutoRepeatOff(dpy);	/* We don't want any autofire, yet! */
    if (kdpy)
	XAutoRepeatOff(kdpy);

    /*
     * Define a blank cursor for use with pointer control
     */
    XQueryBestCursor(dpy, drawWindow, 1, 1, &w, &h);
    pix = XCreatePixmap(dpy, drawWindow, w, h, 1);
    cursorGC = XCreateGC(dpy, pix, 0, NULL);
    XSetForeground(dpy, cursorGC, 0);
    XFillRectangle(dpy, pix, cursorGC, 0, 0, w, h);
    XFreeGC(dpy, cursorGC);
    pointerControlCursor = XCreatePixmapCursor(dpy, pix, pix, &colors[BLACK],
					       &colors[BLACK], 0, 0);
    XFreePixmap(dpy, pix);

    /*
     * Maps the windows, makes the visible. Voila!
     */
    XMapSubwindows(dpy, topWindow);
    XMapWindow(dpy, topWindow);
    XSync(dpy, False);

    if (kdpy) {
	XMapWindow(kdpy, keyboardWindow);
	XSync(kdpy, False);
    }

    Init_spark_colors();

    return 0;
}
Example #24
0
void InitXGraphics(int argc, char **argv, int ny, int nx, int nd, 
		   MET_MAP_PIX *** MetMap)
{
  /* following is for the X11 libraries */

  int i, x, y, screen;		/* screen is an int. */
  int border_width;
  int c1, c2, c3;
  float re, best_re;
  long dy, dx;
  int best_e, best_ndx, best_ndy;
  int el, ndxl, ndyl;
  int buf = 50;

#ifdef HAVE_X11
  Colormap cmap;		/* map from pixel values to colors */
  char *window_name = "DHSVM Realtime Display", *display_name = NULL;
  XSizeHints size_hints;

  /* connect to Xserver */

  if ((display = XOpenDisplay(display_name)) == NULL) {
    fprintf(stderr, "InitXGraphics: cannot connect to X server %s\n",
	    XDisplayName(display_name));
    exit(-1);
  }

  /* get screen size */

  screen = DefaultScreen(display);

  dx = 0.95 * DisplayWidth(display, screen);
  dy = 0.95 * DisplayHeight(display, screen);

  border_width = 4;
  x = 0;
  y = 0;

  /* figure out the actual size of the window and stuff */

  /* now we need to figure out the expansion factor for the number of graphs */
  /* want to maximize the size of each graph while constrained by the
     number of graphs and the screen size */
  /* save top 20 pixels of the display for the date counter */
  /* save 40 pixels for the X11 window title bar- allocated by system */
  /* save left 10 pixels for border */
  dx = dx - 10;
  dy = dy - 60;

  best_e = -10;
  best_ndx = 1;

  for (ndxl = 1; ndxl <= nd; ndxl++) {
    for (el = -10; el <= 10; el++) {

      if (el != 0) {
	if (el < 0)
	  re = 1 / ((float) (-el));
	if (el > 0)
	  re = (float) el;
	ndyl = nd / (ndxl);
	if (ndxl * ndyl < nd)
	  ndyl = ndyl + 1;
	c1 = nd * (nx * re + buf) * (ny * re + buf);
	c2 = ndxl * (nx * re + buf);
	c3 = ndyl * (ny * re + buf);
	if (c1 <= dx * dy && c2 <= dx && c3 <= dy) {
	  /*      printf("ndx %d ndy %d e %d \n",ndxl,ndy,el);
	     printf("nx ny buf re %d %d %d %f\n",nx,ny,buf,re);
	     printf("c1 c2 c3 rh1 rh2 rh3 %d %d %d %d %d %d \n",c1,c2,c3,dx*dy,dx,dy); */
	  if (el > best_e) {
	    best_e = el;
	    best_ndx = ndxl;
	    best_re = re;
	  }
	}
      }
    }
  }

  printf("best use of display for %d images: \n", nd);
  printf("Expand images by factor %f with %d columns\n", best_re, best_ndx);

  e = best_e;
  ndx = best_ndx;

  best_ndy = nd / best_ndx;
  if (best_ndy * best_ndx < nd)
    best_ndy = best_ndy + 1;

  /* now create the window given the new size classes */

  dx = best_ndx * (nx * best_re + buf) + 10;
  dy = best_ndy * (ny * best_re + buf) + 60;

  window = XCreateSimpleWindow(display, RootWindow(display, screen),
			       0, 0, dx, dy, border_width,
			       WhitePixel(display, screen),
			       WhitePixel(display, screen));
  size_hints.flags = PPosition | PSize | PMinSize | PMaxSize;
  size_hints.x = 0;
  size_hints.y = 0;
  size_hints.width = dx;
  size_hints.height = dy;
  size_hints.min_width = 200;
  size_hints.min_height = 200;
  size_hints.max_width = DisplayWidth(display, screen);
  size_hints.max_height = DisplayHeight(display, screen);

  XSetStandardProperties(display, window, window_name,
			 window_name, None, NULL, 0, &size_hints);

  black = XBlackPixel(display, screen);
  white = XWhitePixel(display, screen);

  gc = XCreateGC(display, window, 0, 0);

  XMapWindow(display, window);

  cmap = XDefaultColormap(display, screen);
  /* black to blue */
  for (i = 0; i < 10; i++) {
    my_color[i].red = 0;
    my_color[i].green = 0;
    my_color[i].blue = 65535 * i / 9;
  }
  /* blue to cyan */
  for (i = 10; i < 20; i++) {
    my_color[i].red = 0;
    my_color[i].green = i * 65535 / 19;
    my_color[i].blue = 65535;
  }
  /*cyan to green */
  for (i = 20; i < 25; i++) {
    my_color[i].red = 0;
    my_color[i].green = 65535;
    my_color[i].blue = 65535 - (65535 * (i - 20) / 5);
  }
  /*green to yellow */
  for (i = 25; i < 30; i++) {
    my_color[i].red = (i - 25) * 65535 / 5;
    my_color[i].green = 65535;
    my_color[i].blue = 0;
  }
  /*yellow to magenta */
  for (i = 30; i < 40; i++) {
    my_color[i].red = 65535;
    my_color[i].green = 65535 - (65535 * (i - 30) / 9);
    my_color[i].blue = 65535 * (i - 30) / 9;
  }
  /*magenta to red */
  for (i = 40; i < 50; i++) {
    my_color[i].red = 65335;
    my_color[i].green = 0;
    my_color[i].blue = 65535 - (65535 * (i - 40) / 9);
  }

  for (i = 0; i < 50; i++) {
    if (XAllocColor(display, cmap, &my_color[i]) == 0) {
      printf("Can't do DHSVM colors\n");
      exit(3);
    }
  }

  /* done initializing the X11 Display, available for drawing */

  /* initialize the memory used solely by the drawing functions */

  if (!((*MetMap) = (MET_MAP_PIX **) calloc(ny, sizeof(MET_MAP_PIX *))))
    ReportError("InitXGraphics", 1);

  for (y = 0; y < ny; y++) {
    if (!((*MetMap)[y] = (MET_MAP_PIX *) calloc(nx, sizeof(MET_MAP_PIX))))
      ReportError("InitXGraphics", 1);
  }

  if ((temp_array = (float **) malloc(ny * sizeof(float *))) == NULL) {
    ReportError("draw.c", 1);
  }
  for (y = 0; y < ny; y++) {
    if ((temp_array[y] = (float *) malloc(nx * sizeof(float))) == NULL) {
      ReportError("draw.c", 1);
    }
  }

#endif
}
Example #25
0
File: pcx11e.c Project: cjg/grads
static void
Init (int argc, char **argv)
{
    int background, foreground;
    long event_mask;
    int dw, dh;

    condpy = XOpenDisplay ("");
    if (condpy == NULL)
    {
        fprintf (stderr, "Cannot open display\n");
        exit (1);
    }
    screen = DefaultScreen (condpy);
    dw = DisplayWidth(condpy, screen);
    dh = DisplayHeight(condpy, screen);

    /* cope with PC low res */
    if ( dw < 800 ) {
        font = XLoadQueryFont (condpy, "xm6x10b");
    } else {
        font = XLoadQueryFont (condpy, "8x14");
    }

    ncols = 80;
#if defined(STNDALN)
    nrows = 10;
#else
    nrows = 24;
#endif

    text = (char *) calloc (MAX_NROWS * MAX_NCOLS, 1);

    font_width = font->max_bounds.width;
    font_ascent = font->max_bounds.ascent;
    font_height = font->max_bounds.ascent + font->max_bounds.descent;
    width = ncols * font_width;
    height = nrows * font_height;

    background = WhitePixel (condpy, screen);
    foreground = BlackPixel (condpy, screen);

    hints.flags = 0;
    hints.x = DisplayWidth (condpy, screen) - width - 20;
    hints.y = DisplayHeight (condpy, screen) - height - 40;
    hints.flags |= PPosition;
    hints.width = width;
    hints.height = height;
    hints.flags |= PSize;
    hints.min_width = font_width * 20;
    hints.min_height = font_height * 5;
    hints.flags |= PMinSize;
    hints.max_width = font_width * MAX_NCOLS;
    hints.max_height = font_height * MAX_NROWS;
    hints.flags |= PMaxSize;
    hints.width_inc = font_width;
    hints.height_inc = font_height;
    hints.flags |= PResizeInc;

    win = XCreateSimpleWindow (condpy,
                               DefaultRootWindow (condpy),
                               hints.x, hints.y,
                               hints.width, hints.height, 4,
                               foreground, background);
    event_mask = EnterWindowMask
                 |LeaveWindowMask
                 |ButtonPressMask
                 |KeyPressMask
                 |StructureNotifyMask
                 |ExposureMask;

    XSelectInput (condpy, win, event_mask);

    gc_normal = XCreateGC (condpy, (Drawable) win, 0, 0);
    XSetFont (condpy, gc_normal, font->fid);
    XSetBackground (condpy, gc_normal, background);
    XSetForeground (condpy, gc_normal, foreground);

    gc_cursor = XCreateGC (condpy, (Drawable) win, 0, 0);
    XSetFont (condpy, gc_cursor, font->fid);
    XSetBackground (condpy, gc_cursor, foreground);
    XSetForeground (condpy, gc_cursor, background);

    XSetStandardProperties (condpy, win,
                            program, program,
                            None,
                            argv, argc, &hints);
    XMapWindow (condpy, win);


}
Example #26
0
int xdaemon(int *fds, pid_t *rpid) {
	int fd;
	pid_t pid;
	Window win;
        Display *dpy;
	ssize_t size, rcv_size;
	char rpassword[MAX_PASSWORD_LEN];
	int x11_fd, efd;
	struct epoll_event ee, events[MAX_EVENTS];

	x11_started = 1;

	pipe(fds);
	pid = fork();
	if (pid < 0) {
		close(fds[0]);
		close(fds[1]);
		return 0;
	}

	if (pid) {
		*rpid = pid;		
		close(fds[0]);
		return fds[1];
	}

	fd = fds[0];
	close(fds[1]);

	if (!setup_signals())
		return 0;

	dpy = XOpenDisplay(NULL);
	if (!dpy) {
		syslog(LOG_WARNING, "Can not open display");
		return 0;
	}

	win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, 0, 0);
	if (!win) {
		XCloseDisplay(dpy);
		syslog(LOG_ERR, "Can not create window");
		return 0;
	}
//	XSelectInput(dpy, win, PropertyChangeMask);
	XSetSelectionOwner(dpy, XA_CLIPBOARD(dpy), win, CurrentTime);

	syslog(LOG_INFO, "Started xdaemon on fd%d", fd);
	x11_fd = ConnectionNumber(dpy);


	efd = epoll_create1(0);
	if (efd < 0) {
		syslog(LOG_ERR, "Can not create epoll");
		return 0;
	}

	ee.data.fd = x11_fd;
	ee.events = EPOLLIN;
	if (epoll_ctl(efd, EPOLL_CTL_ADD, x11_fd, &ee) < 0) {
		syslog(LOG_ERR, "Can not add epoll x11: %s", strerror(errno));
		return 0;
	}

	ee.data.fd = fd;
	ee.events = EPOLLIN | EPOLLET;
	if (epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ee) < 0) {
		syslog(LOG_ERR, "Can not add epoll pipe: %s", strerror(errno));
		return 0;
	}
	
	memset(rpassword, 0, MAX_PASSWORD_LEN);
	while (1) {
		int n, i;

		n = epoll_wait (efd, events, MAX_EVENTS, -1);
		for (i = 0; i < n; i++) {
			if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) {
				syslog(LOG_WARNING, "Invalid epoll data");
				continue;
			}

			if (events[i].data.fd == fd) {
				size = read(fd, &rcv_size, sizeof(int));
				if (size != sizeof(int)) {
					syslog(LOG_WARNING, "Communication error size %d", size);
					continue;
				}

				if (rcv_size > MAX_PASSWORD_LEN) {
					syslog(LOG_WARNING, "Corrupter data received");
					continue;
				}

				size = read(fd, rpassword, rcv_size);
				if (size != rcv_size) {
					syslog(LOG_WARNING, "Communication error rcv_size %d", rcv_size);
					continue;
				}
		
				rpassword[rcv_size] = '\0';		

				XSetSelectionOwner(dpy, XA_CLIPBOARD(dpy), win, CurrentTime);
				process_x11_event(dpy, rpassword);
			} else if (events[i].data.fd == x11_fd) {

				if (!rpassword[0])
					continue;

				process_x11_event(dpy, rpassword);
			}
		

		}
	}

	XCloseDisplay(dpy);

	return 1;
}
Example #27
0
int CreeTermGraph(TC *p,unsigned int largeur,unsigned int hauteur,char* titre)
{
  char *display_name = getenv("DISPLAY");
  unsigned long valuemask = 0;
  XGCValues values ;

  p->largeur = largeur;
  p->hauteur = hauteur;

  if ((p->display = XOpenDisplay(display_name)) == NULL)
    return -1;

  p->screen_num = DefaultScreen(p->display);

  p->win = XCreateSimpleWindow(p->display,
                               RootWindow(p->display,p->screen_num),
                               0,0,
                               largeur,hauteur,
                               1,
                               BlackPixel(p->display,p->screen_num),
                               WhitePixel(p->display,p->screen_num));

  XStoreName(p->display,p->win,titre);
  XMapWindow(p->display,p->win);
  XFlush(p->display);

  p->gc = XCreateGC(p->display,p->win,valuemask,&values);

  /***** Allocations des couleurs *****/
  p->cm = DefaultColormap(p->display,DefaultScreen(p->display));

  if (XAllocNamedColor(p->display,p->cm,"black",&(p->Noir),&(p->Noir)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"white",&(p->Blanc),&(p->Blanc)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"red",&(p->Rouge),&(p->Rouge)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"blue",&(p->Bleu),&(p->Bleu)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"green",&(p->Vert),&(p->Vert)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"yellow",&(p->Jaune),&(p->Jaune)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"brown",&(p->Brun),&(p->Brun)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"gray",&(p->Gris),&(p->Gris)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"magenta",&(p->Magenta),&(p->Magenta)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"cyan",&(p->Cyan),&(p->Cyan)) == 0)
    return -1;

  XSetBackground(p->display, p->gc, p->Blanc.pixel);

  XSync(p->display, False);

  sleep(1);

  return 0;
}
Example #28
0
int main(void)
{
	Display *d;
	Window w;
	XEvent e;
	XWindowAttributes attr;

	int s;


	float x_max, y_max;

	int w_, h_,  delt;

	int i;
	int id1, id2, id3;
//	float kx, ky, kx_0, ky_0, kxa, kya, x, y;
	float kx, ky, kxa, kya, x, y;
	int fl =0;
	int fl1=0;
	int fl2=0;

	int flagg=0;
	FILE *file;
    file=fopen("data.txt","r");


	srand(time(NULL));

	

	if(flagg==1)
	{


	}

	if ( (file=fopen("data.txt", "r")) == NULL)
	{

		return -1;
	}

	/*N=0;
	while (fscanf(file, "%d %d", &i, &j) == 2)
		N++;
	fseek(file, 0L, SEEK_SET);
	* */

	 printf("[PIXEL DATA]\n");
	 /*
	point=(Point*)malloc(N*sizeof(Point));
	for (i=0; i<N; i++)
	{
		fscanf(file, "%f %f", &point[i].x, &point[i].y);
		printf("x, y = %f %f\n", point[i].x, point[i].y);
	}*/
	
	while (fscanf(file, "%f %f", &x, &y) ==2)
		AddPoint(x, y);
	
	printf("N=%d\n", N);
	if (N==0)
	{
		printf("N=0\n");
		exit(0);
	}	
	


	fclose(file);
	
	
/*
	x_min=point[0].x;
	y_min=point[0].y;

	x_max=point[0].x;
	y_max=point[0].y;

	for (i=0; i<N; i++)
	{
		if (point[i].x - x_min < eps)
			x_min=point[i].x;

		if (point[i].y - y_min < eps)
			y_min=point[i].y;

		if (point[i].x - x_max > eps)
			x_max=point[i].x;

		if (point[i].y - y_max > eps)
			y_max=point[i].y;
	}


	printf("\nxmin, ymin = %f %f\n", x_min, y_min);
	printf("xmax, ymax = %f %f\n", x_max, y_max);

	kx_0=float(x_max/x_min);
	ky_0=float(y_max/y_min);

	printf("kx_0, ky_0 = %f %f\n\n", kx_0, ky_0);

    int a,b,c;
    int t=0,q=1,g=2;
    float minn;
	id1=id2=id3=0;
	max=cos(point[0], point[1], point[2]);
	for (i=t; i<N; i++)
	{
		for(j=q;j<N; j++)
		{
			for (k=g;k<N; k++)
			{
			    minn=dist(point[i],point[j]);
			    a=i;b=k;c=j;
			    id1=a; id2=b; id3=c;
			    if((minn-dist(point[i],point[k]))>0)
			    {
                    a=i;b=j;c=k;
			    }
			    if((minn-dist(point[k],point[j]))>0)
			    {
                    a=j;b=i;c=k;
			    }

                if (((cos(point[a], point[b], point[c])-max)  > eps) && (cos(point[a], point[b], point[c])-1>eps))
                {
                    max=cos(point[a], point[b], point[c]);
                    id1=a; id2=b; id3=c;
                    printf("cos=%f\n",cos(point[a], point[b], point[c]));
                    printf("i=%d,j=%d,k=%d\n",id1,id2,id3);
                }
                g++;
			}
			printf("i=%d,j=%d,k=%d\n",id1,id2,id3);
			q++;
		}
		i++;
		}*/

	w_=w0;
	h_=h0;
	
	
	
	refresh(&x_max, &y_max, &id1, &id2, &id3);

	kx=float(w_ / x_max);
	ky=float(h_ / y_max);

	printf("kx, ky = %f, %f\n", kx, ky);

	if ((d = XOpenDisplay(getenv("DISPLAY"))) == NULL) {
			exit(1);
	}

	s = DefaultScreen(d);


	w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, w0, h0, 1,
							   BlackPixel(d, s), WhitePixel(d, s));


	XSelectInput(d, w, ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask );


	XMapWindow(d, w);

	kxa=kya=1;
	while (1)
	{
			XGetWindowAttributes(d, w, &attr);
			w_=attr.width;
			h_=attr.height;
			kx=float(w_ / x_max);
			ky=float(h_ / y_max);

		XNextEvent(d, &e);



		if (e.type==ButtonPress)
		{
			printf("Button Press\n");

			ButPress(10,10,e.xbutton.x,e.xbutton.y,&fl);
			ButPress(10,50,e.xbutton.x,e.xbutton.y,&fl1);
			ButPress(10,90,e.xbutton.x,e.xbutton.y,&fl2);
			if(fl==1||fl1==1||fl2==1)
			{
				printf("fl=%d, fl1=%d, fl2=%d\n", fl, fl1, fl2);
				if(fl==1)
				{
					kxa=kxa-0.02;
					printf("KX ----- %f\n", kxa);
					printf("BUTTON 1\n");
				}
				if(fl1==1)
				{
					kxa=kxa+0.02;
					printf("KX +++++ %f\n", kxa);
					printf("BUTTON 2\n");
				}
				if(fl2==1)
				{
					AddPoint(10, 50);
					refresh(&x_max, &y_max, &id1, &id2, &id3);
				}
			}

		}

		if (e.type==ButtonRelease)
		{
			printf("Button Release\n\n");
			fl=fl2=fl1=0;
			XClearArea(d,w,0,0,attr.width,attr.height,1);
			XEvent ev;
			ev.type=Expose;
			XSendEvent(d,w,1,0,&ev);
		}


		if (e.type == Expose)
		{


			if (kx>ky)
				kx=ky;
			else
				ky=kx;

			kx*=kxa;
			ky*=kya;
			
			printf("kx = %f ky = %f\n", kx, ky);

			if (w_ > h_)
				delt=h_;
			else
				delt=w_;


			DrawButton( d,w,DefaultGC(d, s),10,10,s,fl);
    	    DrawButton( d,w,DefaultGC(d, s),10,50,s,fl1);
    	    DrawButton( d,w,DefaultGC(d, s),10,90,s,fl2);


			for (i=0; i<N; i++)
			XFillRectangle(d, w, DefaultGC(d, s), kx*point[i].x - delt/coef, ky*point[i].y - delt/coef, delt/(coef/2), delt/(coef/2));

			XDrawLine(d, w, DefaultGC(d, s), kx*point[id1].x, ky*point[id1].y, kx*point[id2].x, ky*point[id2].y);
			XDrawLine(d, w, DefaultGC(d, s), kx*point[id2].x, ky*point[id2].y, kx*point[id3].x, ky*point[id3].y);
			XDrawLine(d, w, DefaultGC(d, s), kx*point[id3].x, ky*point[id3].y, kx*point[id1].x, ky*point[id1].y);

		}
		if (e.type == KeyPress)
			break;
  }


	XCloseDisplay(d);

	if (point)
		free(point);

	return 0;
}
Example #29
0
main()
{
	float llx,lly,urx,ury;
	int width,height,i;
	char buf[LBUF],string[256];
	char *scalestring="0.88889 1.10769 scale\n"; /* 72/81, 72/65 */
	Display *dpy;
	XEvent ev;
	GC gc;
	Window win;
	DPSContext ctxt;

	/* open display */
	if ((dpy=XOpenDisplay(NULL))==NULL) {
		fprintf(stderr,"Cannot connect to display %s\n",
			XDisplayName(NULL));
		exit(-1);
	}
	
	/* determine window size */
	fgets(buf,LBUF,stdin);
	sscanf(buf,"%*s %s",string);
	string[3] = '\0';
	if (strcmp(string,"EPS")!=0) {
		width = 612;
		height = 792;
	} else {
		while(fgets(buf,LBUF,stdin)!=NULL) { 
			if (buf[0]!='%' || buf[1]!='%') continue;
			sscanf(buf,"%s",string);
			if (strcmp(string,"%%BoundingBox:")==0) {
				sscanf(buf,"%*s %s",string);
				if (strcmp(string,"(atend)")==0) {
					width = 612;
					height = 792;
				} else {
					sscanf(buf,"%*s %f %f %f %f",
						&llx,&lly,&urx,&ury);
					width = urx-llx;
					height = ury-lly;
				}
				break;
			} else if (strcmp(string,"%%EndComments")==0) {
				width = 612;
				height = 792;
				break;
			}
		}
	}
	
	/* create and map window */
	win = XCreateSimpleWindow(dpy,DefaultRootWindow(dpy),
		100,100,width,height,1,
                BlackPixel(dpy,DefaultScreen(dpy)),
		WhitePixel(dpy,DefaultScreen(dpy)));
	XMapWindow(dpy,win);
	
	/* create graphics context */
	gc = XCreateGC(dpy,RootWindow(dpy,DefaultScreen(dpy)),0,NULL);
	XSetForeground(dpy,gc,BlackPixel(dpy,DefaultScreen(dpy)));
	XSetBackground(dpy,gc,WhitePixel(dpy,DefaultScreen(dpy)));

	/* create and set Display PostScript context */
	ctxt = XDPSCreateSimpleContext(dpy,win,gc,0,height,
		DPSDefaultTextBackstop,DPSDefaultErrorProc,NULL);
	if (ctxt==NULL) {
		fprintf(stderr,"Cannot create DPS context\n");
		exit(-1);
	}
	DPSSetContext(ctxt);
	DPSWaitContext(ctxt);
	for (i=0; i<1000000; ++i);  /* KLUDGE synchronization */
	
	/* scale */
	/* no longer necessary, as of AIX Version 3.003? */
	/*
	DPSWriteData(ctxt,scalestring,strlen(scalestring));
	*/

	/* read PostScript from standard input and write to window */
	while (fgets(buf,LBUF,stdin)!=NULL) {
		sscanf(buf,"%s",string);
		if (strcmp(string,"showpage")==0) break;
		DPSWriteData(ctxt,buf,strlen(buf));
	}
	DPSFlushContext(ctxt);

	/* any key press to exit */
	XSelectInput(dpy,win,KeyPressMask);
	while(True) {
            XNextEvent(dpy,&ev);
	    if (ev.type==KeyPress) break;
	}

	/* clean up */
	DPSDestroySpace(DPSSpaceFromContext(ctxt));
	XFlush(dpy);
}
Example #30
0
int
main(int argc, char **argv)
{
	unsigned int x = 1, y = 1;
	Pixmap back;
	DACallbacks eventCallbacks = {
		destroy, /* destroy */
		NULL, /* buttonPress */
		NULL, /* buttonRelease */
		NULL, /* motion (mouse) */
		NULL, /* mouse enters window */
		NULL, /* mouse leaves window */
		moveBall /* timeout */
	};

	/* provide standard command-line options */
	DAParseArguments(
		argc, argv, /* Where the options come from */
		NULL, 0, /* Our list with options - none as you can see */
		"This is the help text for the basic example of how to "
		"use libDockapp.\n",
		"Basic example version 1.1");

	/* Tell libdockapp what version we expect it to be (a date from
	 * NEWS should do).
	 */
	DASetExpectedVersion(20020126);

	DAOpenDisplay(
		NULL /* default display */,
		argc, argv /* needed by libdockapp */
		);
	DACreateIcon(
		"daBasicExample" /* WM_CLASS hint; don't use chars in [.?*: ] */,
		48, 48 /* geometry of dockapp internals */,
		argc, argv      /* needed by libdockapp */
		);

	/* The pixmap that makes up the background of the dockapp */
	back = DAMakePixmap();
	drawRelief(back);
	DASetPixmap(back);
	XFreePixmap(DADisplay, back);

	/* A window(!) for the ball pixmap.
	 * Moving a window is a lot easier then erasing/copying the pixmap all
	 * the time.
	 *
	 * I use a DAShapedPixmap here, which contains all the information
	 * related to the pixmap: pixmap, mask and geometry.
	 */
	ballPix = DAMakeShapedPixmapFromData(ball_red_xpm);
	ballWin = XCreateSimpleWindow(DADisplay, DAWindow,
				      x, y,
				      /* Use the geometry of the shaped pixmap */
				      ballPix->geometry.width, ballPix->geometry.height,
				      0, 0, 0);
	DASPSetPixmapForWindow(ballWin, ballPix);

	/* Respond to destroy and timeout events (the ones not NULL in the
	 * eventCallbacks variable.
	 */
	DASetCallbacks(&eventCallbacks);

	/* Set the time for timeout events (in msec) */
	DASetTimeout(SPEED);

	/* Randomize movement variation.
	 * Run multiple versions of the dockapp simultaneously to see the effect
	 * best.
	 * (which function to use is set from the Imakefile)
	 */
#ifdef HAS_RANDOMDEV
	srandomdev();
#else
	srandom(time(NULL));
#endif

	DAShow(); /* Show the dockapp window. */

	/* Process events and keep the dockapp running */
	DAEventLoop();

	/* not reached */
	exit(EXIT_SUCCESS);
}