Example #1
0
int main(int argc, char *argv[]){
	FILE *fp;
	char buff[1000];
	int ch, i, j, x, y;
	int line_count = 0;

	count = -1;
	count_intersect = 0;
	k = 0;
	
	fp = fopen(argv[1], "r");

	if (fp == NULL){
		printf("There's no input file.\n");
		exit(0);
	}
	else{
		if( (display = XOpenDisplay(display_name)) == NULL ){ 
			printf("Could not open display. \n"); 
			exit(-1);
		}
		printf("Connected to X server  %s\n", XDisplayName(display_name) );
		
		screen_num = DefaultScreen(display);
		screen = DefaultScreenOfDisplay(display);
		colormap = XDefaultColormap(display, screen_num);
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);

		//obtaining line count
		while(!feof(fp)){
			ch = fgetc(fp);
			if (ch == '\n'){
				line_count++;
			}
		}
		rewind(fp);
	}

	//int m[line_count][6];
	int m[line_count+1][6];

	//Creating window
	border_width = 10;
	win_x = 0; win_y = 0;
	win_width = display_width/2;
	win_height = display_height * 0.8;
	//win_height = (int)(win_width/1.7); //rectangular window

	printf("window width: %d\n window height: %d\n", display_width, display_height);

	//win = XCreateSimpleWindow(display, RootWindow(display, 0), 1, 1, win_width, win_height, 10, WhitePixel (display, 0), WhitePixel (display, 0));
	win = XCreateSimpleWindow(display, RootWindow(display, screen_num), 
		win_x, win_y, win_width, win_height, border_width,
		BlackPixel(display, screen_num), WhitePixel(display, screen_num));
	

	//Maps window on screen
	size_hints = XAllocSizeHints();
	wm_hints = XAllocWMHints();
	class_hints = XAllocClassHint();
	if (size_hints == NULL || wm_hints == NULL || class_hints == NULL){
		printf("Error allocating memory for hints\n");
		exit(-1);
	}

	size_hints -> flags = PPosition | PSize | PMinSize;
	size_hints -> min_width = 60;
	size_hints -> min_height = 60;

	XStringListToTextProperty(&win_name_string, 1, &win_name);
	XStringListToTextProperty(&icon_name_string, 1, &icon_name);

	wm_hints -> flags = StateHint | InputHint;
	wm_hints -> initial_state = NormalState;
	wm_hints -> input = False;

	class_hints -> res_name = "x_use_example";
	class_hints -> res_class = "homework1";
	
	XSetWMProperties(display, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints );
	XSelectInput(display, win, ExposureMask | KeyPressMask | ButtonPressMask);

	// put on screen
	XMapWindow(display, win);
	XFlush(display);

	//graphics setup
	green_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, green, &green_col);
	if (XAllocColor(display, colormap, &green_col) == 0){
		printf("Failed to get color green\n");
		exit(-1);
	}
	else{
		printf("Success green!\n");
		XSetForeground(display, green_gc, green_col.pixel);

	}

	red_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, red, &red_col);
	if (XAllocColor(display, colormap, &red_col) == 0){
		printf("Failed to get color red\n");
		exit(-1);
	}
	else{
		printf("Success red!\n");
		XSetForeground(display, red_gc, red_col.pixel);
	}


	black_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, black, &black_col);
	if (XAllocColor(display, colormap, &black_col) == 0){
		printf("Failed to get color black\n");
		exit(-1);
	}
	else{
		printf("Success black!\n");
		XSetForeground(display, black_gc, black_col.pixel);
	}


	light_purple_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, light_purple, &light_purple_col);
	if (XAllocColor(display, colormap, &light_purple_col) == 0){
		printf("Failed to get color light purple\n");
		exit(-1);
	}
	else{
		printf("Success light purple!\n");
		XSetForeground(display, light_purple_gc, light_purple_col.pixel);
	}


	white_gc = XCreateGC(display, win, 0, 0);
	XParseColor(display, colormap, white, &white_col);	
	if (XAllocColor(display, colormap, &white_col) == 0){
		printf("Failed to get color white\n");
		exit(-1);
	}
	else{
		printf("Success white!\n");
		XSetForeground(display, white_gc, white_col.pixel);	
	}
	

	
	while(1){
		XNextEvent(display, &report);
		switch(report.type){
			case Expose:
			{	
				
				for (i = 0; i <= line_count; i++){
					fscanf(fp, "%*s ( %d, %d) ( %d, %d) (%d, %d)", &m[i][0], &m[i][1], &m[i][2], &m[i][3], &m[i][4], &m[i][5]);
				}

				m[line_count+1][0] = -5;

				for (i = 0; i <= line_count ; i++){
					for (j=0; j<6; j+=2){
						m[i][j] = m[i][j] + 100;
						m[i][j+1] = m[i][j+1] + 100;
					}
				}

				for (i = 0; i <=line_count; i++){
					//Draw the triangles
					XDrawLine(display, win, green_gc, m[i][0], m[i][1], m[i][2], m[i][3]);
					XDrawLine(display, win, green_gc, m[i][2], m[i][3], m[i][4], m[i][5]);
					XDrawLine(display, win, green_gc, m[i][4], m[i][5], m[i][0], m[i][1]);
				}

				rewind(fp);

				if (valid_vertex[0][0] != 0.0){
					for (i= 0; i<k; i++){
						if  (valid_vertex[i][6] == 0.0 || valid_vertex[i][6] == -4.0){
							printf("from (%d, %d) to (%d, %d) length: %f and path length: %f\n", (int)valid_vertex[i][0], (int)valid_vertex[i][1], (int)valid_vertex[i][2], (int)valid_vertex[i][3], valid_vertex[i][4], valid_vertex[i][5]);
							XDrawLine(display, win, light_purple_gc, valid_vertex[i][0], valid_vertex[i][1], valid_vertex[i][2], valid_vertex[i][3]);
						}
					}

					XFillArc( display, win, black_gc, start_x, start_y, win_width/200, win_width/200, 0, 360*64);
					XFillArc( display, win, black_gc, target_x, target_y, win_width/200, win_width/200, 0, 360*64);
				}
				else{}
				//printf("exposed\n");
				XFlush(display);
				break;
			}
			case ButtonPress:
			{
				//printf("Button press %d, %d.\n",report.xbutton.x, report.xbutton.y);
				double distance1;
				x = report.xbutton.x;
				y = report.xbutton.y;
				int inTriangle;

				if (report.xbutton.button == Button1){
					/* left click */
					count++;
					
					inTriangle = check_if_in_triangle(line_count, m, x, y);

					if (inTriangle == 0){
						XFillArc( display, win, black_gc, x, y, win_width/200, win_width/200, 0, 360*64);
					}
					

				}
				else{
					printf("Closing Window.\n");
					XDestroyWindow(display, win);
					XCloseDisplay(display);
					exit(1);
				}

				//printf("count: %d\n", count);

				if (count == 0){
					reset(m, line_count);
					start_x = x;
					start_y = y;

					if (inTriangle == 1){
						count = -1;
					}
				}
				else if (count == 1){

					if (inTriangle == 0){
						target_x = x;
						target_y = y;

						printf("\n\nStarting point: (%d, %d)\nTarget point: (%d, %d)\n", start_x, start_y, target_x, target_y);

						int vertex[line_count][6];
						int * nearest_triangles;
						int * result_line_seg;

						for(i=0;i<=line_count;i++){
							//store formatted input file in array m
							fscanf(fp, "%*s ( %d, %d) ( %d, %d) (%d, %d)", &vertex[i][0], &vertex[i][1], &vertex[i][2], &vertex[i][3], &vertex[i][4], &vertex[i][5]);					
						}
						rewind(fp);
						
						printf("Total triangles: %d\n", line_count+1);

						for (i = 0; i <= line_count ; i++){
							for (j=0; j<6; j+=2){
								vertex[i][j] = vertex[i][j] + 100;
								vertex[i][j+1] = vertex[i][j+1] + 100;
							}
						}

						start_graph(line_count, vertex, start_x, start_y, target_x, target_y);

						printf("Applied start_graph()\n");
						
						shortest_path();

						printf("Applied shortest_path()\n");

						organize();

						printf("The shortest path: \n");

						for (i= 0; i<k; i++){
							if  (valid_vertex[i][6] == 0.0 || valid_vertex[i][6] == -4.0){
								printf("from (%d, %d) to (%d, %d) length: %f and path length: %f\n", (int)valid_vertex[i][0], (int)valid_vertex[i][1], (int)valid_vertex[i][2], (int)valid_vertex[i][3], valid_vertex[i][4], valid_vertex[i][5]);
								XDrawLine(display, win, light_purple_gc, valid_vertex[i][0], valid_vertex[i][1], valid_vertex[i][2], valid_vertex[i][3]);
							}
						}
						
						printf("DONE\n");
						
						count = -1;
						
					}
				}

				XFlush(display);
				break;
			}
			default:
				break;
		}
	}
	fclose(fp);
	return 0;
}
Example #2
0
// Create the X11 window (and its colormap)
//
static GLboolean createWindow(_GLFWwindow* window,
                              const _GLFWwndconfig* wndconfig)
{
    unsigned long wamask;
    XSetWindowAttributes wa;
    XVisualInfo* visual = _GLFW_X11_CONTEXT_VISUAL;

    // Every window needs a colormap
    // Create one based on the visual used by the current context
    // TODO: Decouple this from context creation

    window->x11.colormap = XCreateColormap(_glfw.x11.display,
                                           _glfw.x11.root,
                                           visual->visual,
                                           AllocNone);

    // Create the actual window
    {
        wamask = CWBorderPixel | CWColormap | CWEventMask;

        wa.colormap = window->x11.colormap;
        wa.border_pixel = 0;
        wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
                        PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
                        ExposureMask | FocusChangeMask | VisibilityChangeMask |
                        EnterWindowMask | LeaveWindowMask | PropertyChangeMask;

        if (wndconfig->monitor == NULL)
        {
            // HACK: This is a workaround for windows without a background pixel
            //       not getting any decorations on certain older versions of
            //       Compiz running on Intel hardware
            wa.background_pixel = BlackPixel(_glfw.x11.display,
                                             _glfw.x11.screen);
            wamask |= CWBackPixel;
        }

        _glfwGrabXErrorHandler();

        window->x11.handle = XCreateWindow(_glfw.x11.display,
                                           _glfw.x11.root,
                                           0, 0,
                                           wndconfig->width, wndconfig->height,
                                           0,              // Border width
                                           visual->depth,  // Color depth
                                           InputOutput,
                                           visual->visual,
                                           wamask,
                                           &wa);

        _glfwReleaseXErrorHandler();

        if (!window->x11.handle)
        {
            _glfwInputXError(GLFW_PLATFORM_ERROR,
                             "X11: Failed to create window");
            return GL_FALSE;
        }

        if (!wndconfig->decorated)
        {
            MotifWmHints hints;
            hints.flags = MWM_HINTS_DECORATIONS;
            hints.decorations = 0;

            XChangeProperty(_glfw.x11.display, window->x11.handle,
                            _glfw.x11.MOTIF_WM_HINTS,
                            _glfw.x11.MOTIF_WM_HINTS, 32,
                            PropModeReplace,
                            (unsigned char*) &hints,
                            sizeof(MotifWmHints) / sizeof(long));
        }

        XSaveContext(_glfw.x11.display,
                     window->x11.handle,
                     _glfw.x11.context,
                     (XPointer) window);
    }

    if (window->monitor && !_glfw.x11.hasEWMH)
    {
        // This is the butcher's way of removing window decorations
        // Setting the override-redirect attribute on a window makes the window
        // manager ignore the window completely (ICCCM, section 4)
        // The good thing is that this makes undecorated fullscreen windows
        // easy to do; the bad thing is that we have to do everything manually
        // and some things (like iconify/restore) won't work at all, as those
        // are tasks usually performed by the window manager

        XSetWindowAttributes attributes;
        attributes.override_redirect = True;
        XChangeWindowAttributes(_glfw.x11.display,
                                window->x11.handle,
                                CWOverrideRedirect,
                                &attributes);

        window->x11.overrideRedirect = GL_TRUE;
    }

    // Declare the WM protocols supported by GLFW
    {
        int count = 0;
        Atom protocols[2];

        // The WM_DELETE_WINDOW ICCCM protocol
        // Basic window close notification protocol
        if (_glfw.x11.WM_DELETE_WINDOW)
            protocols[count++] = _glfw.x11.WM_DELETE_WINDOW;

        // The _NET_WM_PING EWMH protocol
        // Tells the WM to ping the GLFW window and flag the application as
        // unresponsive if the WM doesn't get a reply within a few seconds
        if (_glfw.x11.NET_WM_PING)
            protocols[count++] = _glfw.x11.NET_WM_PING;

        if (count > 0)
        {
            XSetWMProtocols(_glfw.x11.display, window->x11.handle,
                            protocols, count);
        }
    }

    if (_glfw.x11.NET_WM_PID)
    {
        const pid_t pid = getpid();

        XChangeProperty(_glfw.x11.display,  window->x11.handle,
                        _glfw.x11.NET_WM_PID, XA_CARDINAL, 32,
                        PropModeReplace,
                        (unsigned char*) &pid, 1);
    }

    // Set ICCCM WM_HINTS property
    {
        XWMHints* hints = XAllocWMHints();
        if (!hints)
        {
            _glfwInputError(GLFW_OUT_OF_MEMORY,
                            "X11: Failed to allocate WM hints");
            return GL_FALSE;
        }

        hints->flags = StateHint;
        hints->initial_state = NormalState;

        XSetWMHints(_glfw.x11.display, window->x11.handle, hints);
        XFree(hints);
    }

    // Set ICCCM WM_NORMAL_HINTS property (even if no parts are set)
    {
        XSizeHints* hints = XAllocSizeHints();
        hints->flags = 0;

        if (wndconfig->monitor)
        {
            hints->flags |= PPosition;
            _glfwPlatformGetMonitorPos(wndconfig->monitor, &hints->x, &hints->y);
        }
        else
        {
            // HACK: Explicitly setting PPosition to any value causes some WMs,
            //       notably Compiz and Metacity, to honor the position of
            //       unmapped windows set by XMoveWindow
            hints->flags |= PPosition;
            hints->x = hints->y = 0;
        }

        if (!wndconfig->resizable)
        {
            hints->flags |= (PMinSize | PMaxSize);
            hints->min_width  = hints->max_width  = wndconfig->width;
            hints->min_height = hints->max_height = wndconfig->height;
        }

        XSetWMNormalHints(_glfw.x11.display, window->x11.handle, hints);
        XFree(hints);
    }

    // Set ICCCM WM_CLASS property
    // HACK: Until a mechanism for specifying the application name is added, the
    //       initial window title is used as the window class name
    if (strlen(wndconfig->title))
    {
        XClassHint* hint = XAllocClassHint();
        hint->res_name = (char*) wndconfig->title;
        hint->res_class = (char*) wndconfig->title;

        XSetClassHint(_glfw.x11.display, window->x11.handle, hint);
        XFree(hint);
    }

    if (_glfw.x11.xi.available)
    {
        // Select for XInput2 events

        XIEventMask eventmask;
        unsigned char mask[] = { 0 };

        eventmask.deviceid = 2;
        eventmask.mask_len = sizeof(mask);
        eventmask.mask = mask;
        XISetMask(mask, XI_Motion);

        XISelectEvents(_glfw.x11.display, window->x11.handle, &eventmask, 1);
    }

    _glfwPlatformSetWindowTitle(window, wndconfig->title);

    XRRSelectInput(_glfw.x11.display, window->x11.handle,
                   RRScreenChangeNotifyMask);

    _glfwPlatformGetWindowPos(window, &window->x11.xpos, &window->x11.ypos);
    _glfwPlatformGetWindowSize(window, &window->x11.width, &window->x11.height);

    return GL_TRUE;
}
Example #3
0
/* Ouvre une fenetre pour l'affichage du GUI */
void OpenWindow ()
{
 XTextProperty Name;
 XWMHints *IndicWM;
 XSizeHints *IndicNorm;
 unsigned long mask;
 XSetWindowAttributes Attr;

 /* Allocation des couleurs */
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->forecolor,&x11base->TabColor[fore]);
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->backcolor,&x11base->TabColor[back]);
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->shadcolor,&x11base->TabColor[shad]);
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->licolor,&x11base->TabColor[li]);
 MyAllocNamedColor(x11base->display,x11base->colormap,"#000000",&x11base->TabColor[black]);
 MyAllocNamedColor(x11base->display,x11base->colormap,"#FFFFFF",&x11base->TabColor[white]);

 /* Definition des caracteristiques de la fentre */
 mask=0;
 mask|=CWBackPixel;
 Attr.background_pixel=x11base->TabColor[back].pixel;
 
 x11base->win=XCreateWindow(x11base->display,
			DefaultRootWindow(x11base->display),
			x11base->size.x,
			x11base->size.y,
			x11base->size.width,
			x11base->size.height,0,
			CopyFromParent,
			InputOutput,
			CopyFromParent,
			mask,&Attr);

 XSetWindowColormap(x11base->display,x11base->win,x11base->colormap);
 x11base->gc=XCreateGC(x11base->display,x11base->win,0,NULL);

 /* Choix des evts recus par la fenetre */
 XSelectInput(x11base->display,x11base->win,KeyPressMask|ButtonPressMask|
	ExposureMask|ButtonReleaseMask|EnterWindowMask|LeaveWindowMask|ButtonMotionMask);
 XSelectInput(x11base->display,x11base->root,PropertyChangeMask);
 
 /* Specification des parametres utilises par le gestionnaire de fenetre */
 if (XStringListToTextProperty(&x11base->title,1,&Name)==0)
  fprintf(stderr,"Can't use icon name\n");
 IndicNorm=XAllocSizeHints();
 if (x11base->size.x!=-1)
 {
  IndicNorm->x=x11base->size.x;
  IndicNorm->y=x11base->size.y;
  IndicNorm->flags=PSize|PMinSize|PMaxSize|PResizeInc|PBaseSize|PPosition;
 }
 else
  IndicNorm->flags=PSize|PMinSize|PMaxSize|PResizeInc|PBaseSize;
 IndicNorm->width=x11base->size.width;
 IndicNorm->height=x11base->size.height;
 IndicNorm->min_width=x11base->size.width;
 IndicNorm->min_height=x11base->size.height;
 IndicNorm->max_width=x11base->size.width;
 IndicNorm->max_height=x11base->size.height;
 IndicWM=XAllocWMHints();
 IndicWM->input=True;
 IndicWM->initial_state=NormalState;
 IndicWM->flags=InputHint|StateHint;
 XSetWMProperties(x11base->display,x11base->win,&Name,
       &Name,NULL,0,IndicNorm,IndicWM,NULL);
 Scrapt=(char*)calloc(sizeof(char),1);
 
 /* Construction des atomes pour la communication inter-application */
 propriete=XInternAtom(x11base->display,"Prop_selection",False);
 wm_del_win = XInternAtom(x11base->display,"WM_DELETE_WINDOW",False);
 XSetWMProtocols(x11base->display,x11base->win,&wm_del_win,1);

}
Example #4
0
/* create the X11 window for DAZZLER display */
static void open_display(void)
{
	Window rootwindow;
	XSizeHints *size_hints = XAllocSizeHints();
	Atom wm_delete_window;

	display = XOpenDisplay(NULL);
	XLockDisplay(display);
	screen = DefaultScreen(display);
	rootwindow = RootWindow(display, screen);
	XGetWindowAttributes(display, rootwindow, &wa);
	window = XCreateSimpleWindow(display, rootwindow, 0, 0,
					size, size, 1, 0, 0);
	XStoreName(display, window, "Cromemco DAzzLER");
	size_hints->flags = PSize | PMinSize | PMaxSize;
	size_hints->min_width = size;
	size_hints->min_height = size;
	size_hints->base_width = size;
	size_hints->base_height = size;
	size_hints->max_width = size;
	size_hints->max_height = size;
	XSetWMNormalHints(display, window, size_hints);
	XFree(size_hints);
	wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
	XSetWMProtocols(display, window, &wm_delete_window, 1);
	colormap = DefaultColormap(display, 0);
	gc = XCreateGC(display, window, 0, NULL);
	XSetFillStyle(display, gc, FillSolid);
	pixmap = XCreatePixmap(display, rootwindow, size, size,
		 wa.depth);

	XParseColor(display, colormap, color0, &colors[0]);
	XAllocColor(display, colormap, &colors[0]);
	XParseColor(display, colormap, color1, &colors[1]);
	XAllocColor(display, colormap, &colors[1]);
	XParseColor(display, colormap, color2, &colors[2]);
	XAllocColor(display, colormap, &colors[2]);
	XParseColor(display, colormap, color3, &colors[3]);
	XAllocColor(display, colormap, &colors[3]);
	XParseColor(display, colormap, color4, &colors[4]);
	XAllocColor(display, colormap, &colors[4]);
	XParseColor(display, colormap, color5, &colors[5]);
	XAllocColor(display, colormap, &colors[5]);
	XParseColor(display, colormap, color6, &colors[6]);
	XAllocColor(display, colormap, &colors[6]);
	XParseColor(display, colormap, color7, &colors[7]);
	XAllocColor(display, colormap, &colors[7]);
	XParseColor(display, colormap, color8, &colors[8]);
	XAllocColor(display, colormap, &colors[8]);
	XParseColor(display, colormap, color9, &colors[9]);
	XAllocColor(display, colormap, &colors[9]);
	XParseColor(display, colormap, color10, &colors[10]);
	XAllocColor(display, colormap, &colors[10]);
	XParseColor(display, colormap, color11, &colors[11]);
	XAllocColor(display, colormap, &colors[11]);
	XParseColor(display, colormap, color12, &colors[12]);
	XAllocColor(display, colormap, &colors[12]);
	XParseColor(display, colormap, color13, &colors[13]);
	XAllocColor(display, colormap, &colors[13]);
	XParseColor(display, colormap, color14, &colors[14]);
	XAllocColor(display, colormap, &colors[14]);
	XParseColor(display, colormap, color15, &colors[15]);
	XAllocColor(display, colormap, &colors[15]);

	XParseColor(display, colormap, gray0, &grays[0]);
	XAllocColor(display, colormap, &grays[0]);
	XParseColor(display, colormap, gray1, &grays[1]);
	XAllocColor(display, colormap, &grays[1]);
	XParseColor(display, colormap, gray2, &grays[2]);
	XAllocColor(display, colormap, &grays[2]);
	XParseColor(display, colormap, gray3, &grays[3]);
	XAllocColor(display, colormap, &grays[3]);
	XParseColor(display, colormap, gray4, &grays[4]);
	XAllocColor(display, colormap, &grays[4]);
	XParseColor(display, colormap, gray5, &grays[5]);
	XAllocColor(display, colormap, &grays[5]);
	XParseColor(display, colormap, gray6, &grays[6]);
	XAllocColor(display, colormap, &grays[6]);
	XParseColor(display, colormap, gray7, &grays[7]);
	XAllocColor(display, colormap, &grays[7]);
	XParseColor(display, colormap, gray8, &grays[8]);
	XAllocColor(display, colormap, &grays[8]);
	XParseColor(display, colormap, gray9, &grays[9]);
	XAllocColor(display, colormap, &grays[9]);
	XParseColor(display, colormap, gray10, &grays[10]);
	XAllocColor(display, colormap, &grays[10]);
	XParseColor(display, colormap, gray11, &grays[11]);
	XAllocColor(display, colormap, &grays[11]);
	XParseColor(display, colormap, gray12, &grays[12]);
	XAllocColor(display, colormap, &grays[12]);
	XParseColor(display, colormap, gray13, &grays[13]);
	XAllocColor(display, colormap, &grays[13]);
	XParseColor(display, colormap, gray14, &grays[14]);
	XAllocColor(display, colormap, &grays[14]);
	XParseColor(display, colormap, gray15, &grays[15]);
	XAllocColor(display, colormap, &grays[15]);

	XMapWindow(display, window);
	XUnlockDisplay(display);
}
Example #5
0
void OGLwin_Open_Window(int x, int y, int width, int height, char *name,
			WINTYPE t, Window parent_win)
{
    XSetWindowAttributes swa;
    XEvent event;
    unsigned long attr_mask;
    Window parent;
    Window root_win;

    if (!Dsp) {
	if (global_display != NULL) {
	    Dsp = global_display;
	} else {
	    Dsp = XOpenDisplay(0);
	}
    }

    if (getenv("OGLWIN_USE12")) {
	attributes[RGBA_SINGLE] = rgba12_att;
	attributes[RGBA_DOUBLE] = rgba12_datt;
    }

    Vi = glXChooseVisual(Dsp, DefaultScreen(Dsp), attributes[t]);
    Cmap = getColormap(Dsp, Vi, t);

    swa.border_pixel = 0;
    swa.colormap = Cmap;
    swa.event_mask =
	ExposureMask | StructureNotifyMask | VisibilityChangeMask |
	PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
	KeyPressMask | KeyReleaseMask;
    swa.override_redirect = OGLwin_override_redirect;
    attr_mask =
	CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

    parent = parent_win;
    root_win = RootWindow(Dsp, Vi->screen);

    if (!parent)
	parent = root_win;

    if (parent_border) {
	parent = XCreateSimpleWindow(Dsp, parent, x, y, width, height,
				     0, 0, 0);
	XSelectInput(Dsp, parent, StructureNotifyMask);
	x = y = parent_border;
	width -= parent_border;
	height -= parent_border;
    }

    XWindow = XCreateWindow(Dsp, parent, x, y,
			    width, height,
			    0, Vi->depth, InputOutput, Vi->visual,
			    attr_mask, &swa);

    if (parent_win == root_win) {
	Window top_win = (parent_border ? parent : XWindow);

	/*
	 * fix size/position/aspect of new swWindow  
	 */
	{
	    XSizeHints *size_hints;

	    size_hints = XAllocSizeHints();
	    size_hints->flags = USSize | PSize | USPosition | PPosition;
	    XSetWMNormalHints(Dsp, top_win, size_hints);
	    XFree(size_hints);
	}

	XSetWMColormapWindows(Dsp, XWindow, &XWindow, 1);
	XStoreName(Dsp, top_win, name);
	XMapSubwindows(Dsp, top_win);
	XMapWindow(Dsp, top_win);
	XIfEvent(Dsp, &event, WaitForMapNotify, (char *) top_win);
    } else {
	XMapWindow(Dsp, XWindow);
	XIfEvent(Dsp, &event, WaitForMapNotify, (char *) XWindow);
    }

    Cxt = glXCreateContext(Dsp, Vi, 0, direct_context);

    //SetWin();

    fontBase = -1;
}
Example #6
0
/*
 * Vytvoøit a namapovat top-level okno, vytvoøit dal¹í zdroje (napø. GC)
 */
static void create_resources(int argc, char *argv[])
{
    XWMHints *wm_hints; /* Doporuèení pro window manager */
    XSizeHints *size_hints; /* Doporuèená velikost okna */
    XClassHint *class_hint; /* Jméno a tøída pro resource manager */
    XTextProperty window_name, icon_name; /* Jména pro window manager */
    XGCValues gc_values; /* Hodnoty pro nastavení GC */
    char *str_window_name = (char *)"Hello Window"; /* Titulek okna */
    char *str_icon_name = (char *)"Hello Icon"; /* Titulek ikony */
    XColor exact_bg, screen_bg; /* Barva pozadí pro GC */
   
    /* Vytvoøit top-level okno */
    topwin_x = topwin_y = 0; /* Okno umístí window manager */
    topwin_w = screen_width / 2;
    topwin_h = screen_height / 2;
    topwin_b = 0;
    topwin = XCreateSimpleWindow(display, root, topwin_x, topwin_y, topwin_w,
				 topwin_h, topwin_b, black, white);
    debug("Created top-level window ID %#lx\n", topwin);

    /* Vytvoøit ikonu pro top-level okno */
    topwin_icon = XCreateBitmapFromData(display, topwin, Xlib_icon_bits,
					Xlib_icon_width, Xlib_icon_height);
    debug("Created icon %#lx for top-level window\n", topwin_icon);

    /* Nastavit properties pro window manager */
    if(!(size_hints = XAllocSizeHints()) ||
       !(wm_hints = XAllocWMHints()) ||
       !(class_hint = XAllocClassHint())) {
	fprintf(stderr, "Cannot allocate memory\n");
	exit(1);
    }
    
    /*  Poloha a velikost se bere ze skuteèných hodnot okna v oka¾iku
     * namapování. PPosition | PSize øíká, ¾e hodnoty nastavil program (a
     * window manager je mù¾e mìnit podle potøeby). USSize | USPosition by
     * znamenalo, ¾e hodnoty zadal u¾ivatel (napø. na pøíkazové øádce) a
     * window manager by je nemìl mìnit. */
    size_hints->flags = PPosition | PSize | PMinSize;
    /* Window manager by nemìl okno nikdy zmen¹it na ménì ne¾
     * min_width x min_height pixelù. */
    size_hints->min_width = 200;
    size_hints->min_height = 100;
    
    wm_hints->initial_state = NormalState;/* Na zaèátku má být zobrazeno
                                             normální okno (ne ikona) */
    wm_hints->input = True; /* Aplikace potøebuje vstup z klávesnice */
    wm_hints->icon_pixmap = topwin_icon;
    wm_hints->flags = StateHint | InputHint | IconPixmapHint;
    
    /* Ulo¾ení jména okna a ikony */
    if(!XStringListToTextProperty(&str_window_name, 1, &window_name) ||
       !XStringListToTextProperty(&str_icon_name, 1, &icon_name)) {
        fprintf(stderr, "XStringListToTextProperty() for failed\n");
        exit(1);
    }

    /* Jméno programu a tøídy pro hledání v resource databázi */
    class_hint->res_name = progname;
    class_hint->res_class = (char *) "HelloWorld";

    /* Nastavit v¹echny properties */
    XSetWMProperties(display, topwin, &window_name, &icon_name, argv, argc,
                     size_hints, wm_hints, class_hint);

    /* Vybrat události pro top-level okno */
    XSelectInput(display, topwin, ExposureMask | KeyPressMask |
		 ButtonPressMask | StructureNotifyMask);
    
    /* Vytvoøit GC */
    if(!XAllocNamedColor(display, cmap, "RGBi:0.5/0.5/0.5", &exact_bg,
			 &screen_bg)) {
	fprintf(stderr, "Cannot allocate color\n");
	exit(1);
    }
    gc_values.background = screen_bg.pixel;
    gc_values.foreground = black;
    my_gc = XCreateGC(display, topwin, GCBackground | GCForeground, &gc_values);
    XCopyGC(display, def_gc, GCFont, my_gc); /* default font */
    
    /* Namapovat top-level okno */
    XMapWindow(display, topwin);
}
Example #7
0
int main(int argc, char** argv)
{  
   // The usual X overhead...
   unsigned int width, height;   // window size
   unsigned int border_width = 4;

   char* window_name = argv[0];
   char* icon_name = "GCT";

   Pixmap icon_pixmap;
   XSizeHints* size_hints;
   XWMHints* wm_hints;
   XClassHint* class_hints;
   XTextProperty windowName;
   XTextProperty iconName;
   XEvent report;
   int window_size_ok = 1;
   char* display_name = 0;
   char* progname = argv[0];
   Window win; 
   Display* display;
   int screen_num;

   // check allocation of hints
   if (!(size_hints = XAllocSizeHints())
      || !(wm_hints = XAllocWMHints())
      || !(class_hints = XAllocClassHint()))
   {  
      cerr << progname << " error: failure allocating memory" << endl;
      exit(-1);
   }

   progname = argv[0];

   // connect to X server
   display = XOpenDisplay(display_name);
   if (display == NULL)
   {  
      cerr << progname << " error: can't connect to server " <<
         XDisplayName(display_name) << endl;
      exit(-1);
   }

   // get screen size from display structure macro
   screen_num = DefaultScreen(display);

   win = XCreateSimpleWindow(display, RootWindow(display, screen_num),
      0, 0, DEF_WIDTH, DEF_HEIGHT, border_width, BlackPixel(display,
      screen_num), WhitePixel(display, screen_num));

   if (XStringListToTextProperty(&window_name, 1, &windowName) == 0)
   {  
      cerr << progname
         << " error: structure allocation for windowName failed."
         << endl;
      exit(-1);
   }

   if (XStringListToTextProperty(&icon_name, 1, &iconName) == 0) 
   {  
      cerr << progname
         << " error: structure allocation for iconName failed."
         << endl;
      exit(-1);
   }

   size_hints->flags = PPosition | PSize | PMinSize;
   size_hints->min_width = DEF_WIDTH;
   size_hints->min_height = DEF_HEIGHT;

   wm_hints->initial_state = NormalState;
   wm_hints->input = True;
   wm_hints->icon_pixmap = icon_pixmap;
   wm_hints->flags = StateHint | IconPixmapHint | InputHint;

   class_hints->res_name = progname;
   class_hints->res_class = "chigcx";

   XSetWMProperties(display, win, &windowName, &iconName, argv, argc,
      size_hints, wm_hints, class_hints);

   // Select desired event types
   XSelectInput(display, win, ExposureMask | KeyPressMask
      | ButtonPressMask);

   // Highly intuitive way to state that we can process "delete window"
   Atom delete_atom = XInternAtom(display, "WM_DELETE_WINDOW", false);
   XSetWMProtocols(display, win, &delete_atom, 1);

   XMapWindow(display, win);

   cwin.open(display, win);

   // Event loop
   int draw_flag = 1;
   while (true)
   {  
      XNextEvent(display, &report);
      switch ((int)report.type)
      {  
         case Expose:
            if (report.xexpose.count == 0)
            {  
               if (window_size_ok)
               {  
                  if (draw_flag)
                  {  
                     ccc_win_main();
                     draw_flag = 0;
                  }
                  else
                     cwin.repaint();
               }
            }
            break;

         case ConfigureNotify:
            /* 
               window has been resized, change width and
               height to send to draw_text and draw_graphics
               in next Expose 
            */
            width = report.xconfigure.width;
            height = report.xconfigure.height;
            window_size_ok = (width >= size_hints->min_width)
               && (height >= size_hints->min_height);
            break;

         case ClientMessage:
            if (report.xclient.data.l[0] == delete_atom)
            {
               cwin.close();
               exit(0);
            }
            break;
         case ButtonPress:
         case KeyPress:
         default:
            break;
      }
   }
   return 0;
}
Example #8
0
GL_Window::GL_Window(int w, int h)
{
    int width = w;
    int height = h;
    XSetWindowAttributes swa;
    x_display = XOpenDisplay(NULL);
    DefaultScreen(x_display);
    root = DefaultRootWindow(x_display);
    swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask | ButtonPressMask |
                     MotionNotify | ButtonReleaseMask | StructureNotifyMask;

    win = XCreateWindow(x_display, root, 0, 0, width, height, 0,
                        CopyFromParent, InputOutput, CopyFromParent, CWEventMask, &swa);

    // handle window close correctly

    XMapWindow(x_display, win);
    Atom delmsg = XInternAtom(x_display, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(x_display, win, &delmsg, 1);

    // limit resize to 16:9 ratio

    XSizeHints *hints = XAllocSizeHints();
    hints->flags |= PAspect;
    hints->min_aspect.x = 16;
    hints->min_aspect.y = 9;
    hints->max_aspect.x = 16;
    hints->max_aspect.y = 9;
    XSetWMNormalHints(x_display, win, hints);
    XFree(hints);


    // EGL stuff

    EGLint major, minor;
    EGLint numConfigs;
    EGLConfig config;
    const EGLint configAttribs[] = {
            EGL_RENDERABLE_TYPE, EGL_WINDOW_BIT,
            EGL_RED_SIZE, 8,
            EGL_GREEN_SIZE, 8,
            EGL_BLUE_SIZE, 8,
            EGL_DEPTH_SIZE, 24,
            EGL_NONE
    };
    const EGLint contextAttribs[] = {
            EGL_CONTEXT_CLIENT_VERSION, 2,
            EGL_NONE
    };
    display = eglGetDisplay((EGLNativeDisplayType)x_display);
    eglInitialize(display, &major, &minor);
    eglChooseConfig(display, configAttribs, &config, 1, &numConfigs);
    surface = eglCreateWindowSurface(display, config,
                    (EGLNativeWindowType)win, NULL);
    context = eglCreateContext(display, config,
                    EGL_NO_CONTEXT, contextAttribs);
    eglMakeCurrent(display, surface, surface, context);



}
void createDialogWindow(AppInfo *app)
{
   XSetWindowAttributes attr;
   unsigned long attrMask = 0;
   DialogInfo *d = app->dialog;
   
   attr.background_pixel = d->w3.w.background;
   attrMask |= CWBackPixel;
   attr.border_pixel = d->w3.borderColor;
   attrMask |= CWBorderPixel;
   attr.cursor = None;
   attrMask |= CWCursor;
   attr.event_mask = app->eventMask;
   attrMask |= CWEventMask;

   d->dialogWindow = XCreateWindow(app->dpy, app->rootWindow,
				   d->w3.w.x, d->w3.w.y,
				   d->w3.w.width, d->w3.w.height,
				   d->w3.borderWidth,
				   DefaultDepthOfScreen(app->screen),
				   InputOutput,
				   DefaultVisualOfScreen(app->screen),
				   attrMask, &attr);
   
   d->sizeHints = XAllocSizeHints();
   if (!(d->sizeHints)) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   d->sizeHints->flags = 0;
   d->sizeHints->flags |= PPosition;
   d->sizeHints->flags |= PSize;
   d->sizeHints->min_width = d->w3.w.width;
   d->sizeHints->min_height = d->w3.w.height;
   d->sizeHints->flags |= PMinSize;
   d->sizeHints->max_width = d->w3.w.width;
   d->sizeHints->max_height = d->w3.w.height;
   d->sizeHints->flags |= PMaxSize;
   d->sizeHints->base_width = d->w3.w.width;
   d->sizeHints->base_height = d->w3.w.height;
   d->sizeHints->flags |= PBaseSize;
   
   d->wmHints = XAllocWMHints();
   if (!(d->wmHints)) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   d->wmHints->flags = 0;
   d->wmHints->input = True;
   d->wmHints->flags |= InputHint;
   d->wmHints->initial_state = NormalState;
   d->wmHints->flags |= StateHint;

   d->classHints = XAllocClassHint();
   if (!(d->classHints)) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   d->classHints->res_name = app->appName;
   d->classHints->res_class = app->appClass;

   if (!XStringListToTextProperty(&(d->title), 1, &(d->windowName))) {
      destroyDialog(app);
      outOfMemory(app, __LINE__);
   }
   XSetWMProperties(app->dpy, d->dialogWindow, &(d->windowName), NULL,
		    app->argv, app->argc, d->sizeHints,
		    d->wmHints, d->classHints);
   XSetTransientForHint(app->dpy, d->dialogWindow, d->dialogWindow);
   
   app->wmDeleteWindowAtom = XInternAtom(app->dpy, "WM_DELETE_WINDOW", False);
   XSetWMProtocols(app->dpy, d->dialogWindow, &(app->wmDeleteWindowAtom), 1);
}
Example #10
0
File: x11_out.c Project: erelh/gpac
/*
 * Setup X11 wnd System
 */
void
X11_SetupWindow (GF_VideoOutput * vout)
{
	X11VID ();
	const char *sOpt;
        Bool autorepeat, supported;

	xWindow->display = XOpenDisplay (NULL);
	xWindow->screennum = DefaultScreen (xWindow->display);
	xWindow->screenptr = DefaultScreenOfDisplay (xWindow->display);
	xWindow->visual = DefaultVisualOfScreen (xWindow->screenptr);
	xWindow->depth = DefaultDepth (xWindow->display, xWindow->screennum);

	{
		Float screenWidth = (Float)XWidthOfScreen(xWindow->screenptr);
		Float screenWidthIn = (Float)XWidthMMOfScreen(xWindow->screenptr) / 25.4f;
		Float screenHeight = (Float)XHeightOfScreen(xWindow->screenptr);
		Float screenHeightIn = (Float)XHeightMMOfScreen(xWindow->screenptr) / 25.4f;
		vout->dpi_x = (u32)(screenWidth / screenWidthIn);
		vout->dpi_y = (u32)(screenHeight / screenHeightIn);
	}

	switch (xWindow->depth) {
	case 8:
		xWindow->pixel_format = GF_PIXEL_GREYSCALE;
		break;
	case 16:
		xWindow->pixel_format = GF_PIXEL_RGB_565;
		break;
	case 24:
		xWindow->pixel_format = GF_PIXEL_RGB_32;
		break;
	default:
		xWindow->pixel_format = GF_PIXEL_GREYSCALE;
		break;
	}
	xWindow->bpp = xWindow->depth / 8;
	xWindow->bpp = xWindow->bpp == 3 ? 4 : xWindow->bpp;

xWindow->screennum=0;
	vout->max_screen_width = DisplayWidth(xWindow->display, xWindow->screennum);
	vout->max_screen_height = DisplayHeight(xWindow->display, xWindow->screennum);
	/*
	 * Full screen wnd
	 */
	xWindow->full_wnd = XCreateWindow (xWindow->display,
								   RootWindowOfScreen (xWindow->screenptr),
								   0, 0,
								   vout->max_screen_width,
								   vout->max_screen_height, 0,
								   xWindow->depth, InputOutput,
								   xWindow->visual, 0, NULL);

	XSelectInput(xWindow->display, xWindow->full_wnd,
					FocusChangeMask | ExposureMask | PointerMotionMask | ButtonReleaseMask | ButtonPressMask | KeyPressMask | KeyReleaseMask);

	if (!xWindow->par_wnd) {
		xWindow->w_width = 320;
		xWindow->w_height = 240;
		xWindow->wnd = XCreateWindow (xWindow->display,
					   RootWindowOfScreen(xWindow->screenptr), 0, 0,
					   xWindow->w_width, xWindow->w_height, 0,
					   xWindow->depth, InputOutput,
					   xWindow->visual, 0, NULL);
		XMapWindow (xWindow->display, (Window) xWindow->wnd);
	} else {
		XWindowAttributes pwa;
		XGetWindowAttributes(xWindow->display, xWindow->par_wnd, &pwa);
		xWindow->w_width = pwa.width;
		xWindow->w_height = pwa.height;
		xWindow->wnd = XCreateWindow (xWindow->display, xWindow->par_wnd, pwa.x, pwa.y,
					xWindow->w_width, xWindow->w_height, 0,
					   xWindow->depth, InputOutput,
					   xWindow->visual, 0, NULL);
		XMapWindow (xWindow->display, (Window) xWindow->wnd);
	}

	XSync(xWindow->display, False);
	XUnmapWindow (xWindow->display, (Window) xWindow->wnd);
	XSync(xWindow->display, False);
	old_handler = XSetErrorHandler(X11_BadAccess_ByPass);
	selectinput_err = 0;
	XSelectInput(xWindow->display, xWindow->wnd,
		FocusChangeMask | StructureNotifyMask | PropertyChangeMask | ExposureMask |
		PointerMotionMask | ButtonReleaseMask | ButtonPressMask |
		KeyPressMask | KeyReleaseMask);
	XSync(xWindow->display, False);
	XSetErrorHandler(old_handler);
	if (selectinput_err) {
	       	XSelectInput(xWindow->display, xWindow->wnd,
			StructureNotifyMask | PropertyChangeMask | ExposureMask |
			KeyPressMask | KeyReleaseMask);

		GF_LOG(GF_LOG_ERROR, GF_LOG_MMIO, ("[X11] Cannot select input focus\n"));
	}
	XSync(xWindow->display, False);
	XMapWindow (xWindow->display, (Window) xWindow->wnd);

	XSizeHints *Hints = XAllocSizeHints ();
	Hints->flags = PSize | PMinSize;
	Hints->min_width = 64;
	Hints->min_height = 64;
	Hints->max_height = 4096;
	Hints->max_width = 4096;
	if (!xWindow->par_wnd) {
		XSetWMNormalHints (xWindow->display, xWindow->wnd, Hints);
		XStoreName (xWindow->display, xWindow->wnd, "GPAC X11 Output");
	}
	Hints->x = 0;
	Hints->y = 0;
	Hints->flags |= USPosition;
	XSetWMNormalHints (xWindow->display, xWindow->full_wnd, Hints);

	autorepeat = 1;
	XkbSetDetectableAutoRepeat(xWindow->display, autorepeat, &supported);


	if (xWindow->init_flags & GF_TERM_WINDOW_NO_DECORATION) {
#define PROP_MOTIF_WM_HINTS_ELEMENTS 5
#define MWM_HINTS_DECORATIONS (1L << 1)
	  struct {
	    unsigned long flags;
	    unsigned long functions;
	    unsigned long decorations;
	    long inputMode;
	    unsigned long status;
	  } hints = {2, 0, 0, 0, 0};

	  hints.flags = MWM_HINTS_DECORATIONS;
	  hints.decorations = 0;

	  XChangeProperty(xWindow->display, xWindow->wnd, XInternAtom(xWindow->display,"_MOTIF_WM_HINTS", False), XInternAtom(xWindow->display, "_MOTIF_WM_HINTS", False), 32, PropModeReplace, (unsigned char *)&hints, PROP_MOTIF_WM_HINTS_ELEMENTS);

	}

	xWindow->the_gc = XCreateGC (xWindow->display, xWindow->wnd, 0, NULL);
	xWindow->use_shared_memory = 0;

#ifdef GPAC_HAS_X11_SHM
	sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "UseHardwareMemory");
        if (sOpt && !strcmp(sOpt, "yes")) {
	  int XShmMajor, XShmMinor;
	  Bool XShmPixmaps;
	  if (XShmQueryVersion(xWindow->display, &XShmMajor, &XShmMinor, &XShmPixmaps)) {
		xWindow->use_shared_memory = 1;
		GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using X11 Shared Memory\n"));
		if ((XShmPixmaps==True) && (XShmPixmapFormat(xWindow->display)==ZPixmap)) {
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] X11 Shared Memory Pixmaps available\n"));
		}
	  }
	}

#endif

#ifdef GPAC_HAS_X11_XV
	sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "DisableColorKeying");
	if (sOpt && !strcmp(sOpt, "yes")) {
		xWindow->xvport = X11_GetXVideoPort(vout, GF_PIXEL_I420, 0);
	} else {
		xWindow->xvport = X11_GetXVideoPort(vout, GF_PIXEL_I420, 1);
		if (xWindow->xvport<0) {
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Hardware has no color keying\n"));
			vout->overlay_color_key = 0;
			xWindow->xvport = X11_GetXVideoPort(vout, GF_PIXEL_I420, 0);
		} else {
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Hardware uses color key %08x\n", vout->overlay_color_key));
		}
	}
	if (xWindow->xvport>=0) {
		XvUngrabPort(xWindow->display, xWindow->xvport, CurrentTime );
		xWindow->xvport = -1;
		vout->yuv_pixel_format = X11_GetPixelFormat(xWindow->xv_pf_format);
		vout->Blit = X11_Blit;
		vout->hw_caps |= GF_VIDEO_HW_HAS_YUV_OVERLAY;
		GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using XV YUV Overlays\n"));

#ifdef GPAC_HAS_X11_SHM
		/*if user asked for YUV->RGB on offscreen, do it (it may crash the system)*/
		sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "EnableOffscreenYUV");
		if (sOpt && !strcmp(sOpt, "yes")) {
			vout->hw_caps |= GF_VIDEO_HW_HAS_YUV;
			GF_LOG(GF_LOG_INFO, GF_LOG_MMIO, ("[X11] Using XV Offscreen YUV2RGB acceleration\n"));
		}
#endif
	}
#endif

	XSetWindowAttributes xsw;
	xsw.border_pixel = WhitePixel (xWindow->display, xWindow->screennum);
	xsw.background_pixel = BlackPixel (xWindow->display, xWindow->screennum);
	xsw.win_gravity = NorthWestGravity;
	XChangeWindowAttributes (xWindow->display, xWindow->wnd, CWBackPixel | CWWinGravity, &xsw);

	xsw.override_redirect = True;
	XChangeWindowAttributes(xWindow->display, xWindow->full_wnd,
				CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWWinGravity, &xsw);

	if (!xWindow->par_wnd) {
		xWindow->WM_DELETE_WINDOW = XInternAtom (xWindow->display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(xWindow->display, xWindow->wnd, &xWindow->WM_DELETE_WINDOW, 1);
	}


	{
		XEvent ev;
		long mask;

		memset (&ev, 0, sizeof (ev));
		ev.xclient.type = ClientMessage;
		ev.xclient.window = RootWindowOfScreen (xWindow->screenptr);
		ev.xclient.message_type = XInternAtom (xWindow->display, "KWM_KEEP_ON_TOP", False);
		ev.xclient.format = 32;
		ev.xclient.data.l[0] = xWindow->full_wnd;
		ev.xclient.data.l[1] = CurrentTime;
		mask = SubstructureRedirectMask;
		XSendEvent (xWindow->display,RootWindowOfScreen (xWindow->screenptr), False,
			    mask, &ev);
	}

	/*openGL setup*/
#ifdef GPAC_HAS_OPENGL
	{
	  int attribs[64];
	  int i, nb_bits;

	  sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "GLNbBitsPerComponent");
	  /* Most outputs are 24/32 bits these days, use 8 bits per channel instead of 5, works better on MacOS X */
	  nb_bits = sOpt ? atoi(sOpt) : 8;
          if (!sOpt){
             gf_modules_set_option((GF_BaseInterface *)vout, "Video", "GLNbBitsPerComponent", "8");
          }
	  i=0;
	  attribs[i++] = GLX_RGBA;
	  attribs[i++] = GLX_RED_SIZE;
	  attribs[i++] = nb_bits;
	  attribs[i++] = GLX_GREEN_SIZE;
	  attribs[i++] = nb_bits;
	  attribs[i++] = GLX_BLUE_SIZE;
	  attribs[i++] = nb_bits;
	  sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "GLNbBitsDepth");
	  nb_bits = sOpt ? atoi(sOpt) : 16;
          if (!sOpt){
             gf_modules_set_option((GF_BaseInterface *)vout, "Video", "GLNbBitsDepth", "16");
          }
	  if (nb_bits) {
		  attribs[i++] = GLX_DEPTH_SIZE;
		  attribs[i++] = nb_bits;
	  }
	  sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "UseGLDoubleBuffering");
          if (!sOpt){
             gf_modules_set_option((GF_BaseInterface *)vout, "Video", "UseGLDoubleBuffering", "yes");
          }
	  if (!sOpt || !strcmp(sOpt, "yes")) attribs[i++] = GLX_DOUBLEBUFFER;
	  attribs[i++] = None;
	  xWindow->glx_visualinfo = glXChooseVisual(xWindow->display, xWindow->screennum, attribs);
	  if (!xWindow->glx_visualinfo) {
		  GF_LOG(GF_LOG_ERROR, GF_LOG_MMIO, ("[X11] Error selecting GL display\n"));
	  }
	}

	xWindow->gl_wnd = XCreateWindow (xWindow->display, RootWindowOfScreen (xWindow->screenptr),
								   0,
								   0,
								   200,
								   200, 0,
								   xWindow->depth, InputOutput,
								   xWindow->visual, 0, NULL);

	XSync(xWindow->display, False);
	XUnmapWindow(xWindow->display, (Window) xWindow->gl_wnd);
	XSync(xWindow->display, False);

	sOpt = gf_modules_get_option((GF_BaseInterface *)vout, "Video", "X113DOffscreenMode");
	if (!sOpt)
		gf_modules_set_option((GF_BaseInterface *)vout, "Video", "X113DOffscreenMode", "Pixmap");
        if (sOpt && !strcmp(sOpt, "Window")) {
		xWindow->offscreen_type = 1;
        } else if (sOpt && !strcmp(sOpt, "VisibleWindow")) {
		xWindow->offscreen_type = 2;
		XSetWMNormalHints (xWindow->display, xWindow->gl_wnd, Hints);
       } else if (sOpt && !strcmp(sOpt, "Pixmap")) {
		xWindow->offscreen_type = 0;
	} else {
		xWindow->offscreen_type = 0;
	}
#endif


	/*turn off xscreensaver*/
	X11_XScreenSaverState(xWindow, 0);

	xWindow->setup_done = 1;
	XFree (Hints);
}
Example #11
0
int main(int argc, char **argv)
{
  /* code add by andrew GONG for reading file from command line argument */
    
    point p[N];
    point q[N];
    point array[V];
    unsigned int G[V][V];

    point s = {0, 0};
    point t = {0, 0};
    int i, j, k;
    int press;
    i = j = k = 0;
    press = 0;

    for (i = 0; i < N; i++) {
      p[i].x = p[i].y = 0;
      q[i].x = q[i].y = 0;
    }
    
    if(argc != 2) {
      printf("usage:%s filename", argv[0]);
    }
    else {
      FILE *file = fopen(argv[1], "r");
      if(file == 0) {
        printf("Could not open file!\n");
      }
      else {
        i = 0;
        printf("%s\n", argv[1]);
        while(!feof(file)) {
          if(fscanf(file, "S (%d, %d) (%d, %d)\n",
		    &p[i].x, &p[i].y, &q[i].x, &q[i].y) != 4) {
            break;
          }
          else {
            i++;
          }
        }
      }
      
      fclose(file);
    }
    
    
    


  /* opening display: basic connection to X Server */
  if( (display_ptr = XOpenDisplay(display_name)) == NULL )
    { printf("Could not open display. \n"); exit(-1); }
  printf("Connected to X server  %s\n", XDisplayName(display_name));
  screen_num = DefaultScreen(display_ptr);
  screen_ptr = DefaultScreenOfDisplay(display_ptr);
  color_map  = XDefaultColormap(display_ptr, screen_num);
  display_width  = DisplayWidth(display_ptr, screen_num);
  display_height = DisplayHeight(display_ptr, screen_num);

  printf("Width %d, Height %d, Screen Number %d\n", 
           display_width, display_height, screen_num);

  /* creating the window */
  border_width = 10;
  win_x = 0; win_y = 0;
  win_width = display_width/2; 
  win_height = (unsigned int) (win_width / 1.7); /* rectangular window */
  win= XCreateSimpleWindow(display_ptr, RootWindow(display_ptr, screen_num), win_x, win_y, win_width, win_height, border_width, BlackPixel(display_ptr, screen_num), WhitePixel(display_ptr, screen_num));

/* now try to put it on screen, this needs cooperation of window manager */
  size_hints = XAllocSizeHints();
  wm_hints = XAllocWMHints(); 
  class_hints = XAllocClassHint(); 
  if( size_hints == NULL || wm_hints == NULL || class_hints == NULL ) {
    printf("Error allocating memory for hints. \n"); exit(-1); }
  size_hints -> flags = PPosition | PSize | PMinSize  ; 
  size_hints -> min_width = 60; 
  size_hints -> min_height = 60; 
  XStringListToTextProperty(&win_name_string, 1, &win_name);
  XStringListToTextProperty(&icon_name_string, 1, &icon_name);
  wm_hints -> flags = StateHint | InputHint ; 
  wm_hints -> initial_state = NormalState; 
  wm_hints -> input = False; 
  class_hints -> res_name = "x_use_example"; 
  class_hints -> res_class = "examples"; 
  XSetWMProperties(display_ptr, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints);

  /* what events do we want to receive */
  XSelectInput(display_ptr, win,
            ExposureMask | StructureNotifyMask | ButtonPressMask);
  
  /* finally: put window on screen */
  XMapWindow(display_ptr, win);

  XFlush(display_ptr);
  /* create graphics context, so that we may draw in this window */
  gc = XCreateGC(display_ptr, win, valuemask, &gc_values);
  XSetForeground(display_ptr, gc, BlackPixel(display_ptr, screen_num));
  XSetLineAttributes(display_ptr, gc, 2, LineSolid, CapRound, JoinRound);

  /* and three other graphics contexts, to draw in yellow and red and grey */
  gc_yellow = XCreateGC( display_ptr, win, valuemask, &gc_yellow_values);
  XSetLineAttributes(display_ptr, gc_yellow, 2, LineSolid, CapRound, JoinRound);
  if(XAllocNamedColor(display_ptr, color_map, "yellow",
			&tmp_color1, &tmp_color2 ) == 0)
    {printf("failed to get color yellow\n"); exit(-1); } 
  else
    XSetForeground(display_ptr, gc_yellow, tmp_color1.pixel);
  gc_red = XCreateGC(display_ptr, win, valuemask, &gc_red_values);
 /* XSetLineAttributes(display_ptr, gc_red, 6, LineSolid, CapRound, JoinRound); */
  if( XAllocNamedColor(display_ptr, color_map, "red",
			&tmp_color1, &tmp_color2) == 0 )
    {printf("failed to get color red\n"); exit(-1);} 
  else
    XSetForeground(display_ptr, gc_red, tmp_color1.pixel);
  gc_grey = XCreateGC(display_ptr, win, valuemask, &gc_grey_values);
  if( XAllocNamedColor(display_ptr, color_map, "light grey",
			&tmp_color1, &tmp_color2) == 0)
    {printf("failed to get color grey\n"); exit(-1);} 
  else
    XSetForeground(display_ptr, gc_grey, tmp_color1.pixel);

  /* and now it starts: the event loop */
  while(1) { 
    XNextEvent( display_ptr, &report );
    switch(report.type)
    {
      case Expose:
      /* (re-)draw the example figure. This event happens
       * each time some part ofthe window gets exposed (becomes visible) */
      
      /* print all the obstacles */
      for (i = 0; i < N; i++) {
        if (p[i].x != 0 && p[i].y != 0 && q[i].x != 0 && q[i].y !=0) {
          XDrawLine(display_ptr, win, gc, p[i].x, p[i].y, q[i].x, q[i].y);
        }
      }
      break;
      case ConfigureNotify:
      /* This event happens when the user changes the size of the window */
      win_width = report.xconfigure.width;
      win_height = report.xconfigure.height;
      break;

      /* This event happens when the user pushes a mouse button. I draw
       * a circle to show the point where it happened, but do not save 
       * the position; so when the next redraw event comes, these circles
       * disappear again. */
      case ButtonPress: {
      int x, y;
      x = report.xbutton.x;
      y = report.xbutton.y;
      /* read point s, t */
      if (press == 0) {
	    s.x = report.xbutton.x;
	    s.y = report.xbutton.y;
      }
      else if (press == 1) {
	    t.x = report.xbutton.x;
	    t.y = report.xbutton.y;
      }
      
      press += 1;
      
      if (report.xbutton.button == Button1)
	    XFillArc(display_ptr, win, gc_red,
        x - win_height/40, y - win_height/40,
        win_height / 20, win_height / 20, 0, 360*64);
      else
	    XFillArc(display_ptr, win, gc_yellow,
        x - win_height / 40, y - win_height / 40,
        win_height / 20, win_height / 20, 0, 360*64);
      
      
      printf("%d, %d, %d, %d\n", s.x, s.y, t.x, t.y);
      printf("press = %d\n", press);
      
      if (press == 2) {
        XFlush(display_ptr);
          /* construction graph G
           *s is the first point and t is the last point */
	
        array[0].x = s.x;
        array[0].y = s.y;
        array[V-1].x = t.x;
        array[V-1].y = t.y;
	  
        for (i = 1; i < V-1; i++) {
          if ( i <= N ) {
            array[i].x = p[i-1].x;
            array[i].y = p[i-1].y;
          }
          else if (i > N) {
            array[i].x = q[i-N-1].x;
            array[i].y = q[i-N-1].y;
          }
        }
	
        for (i = 0; i < V; i++) {
          int j;
          for(j = 0; j < V; j++) {
            if (( array[i].x == 0 && array[i].y == 0 ) || ( array[j].x == 0 && array[j].y == 0)) {
              G[i][j] = INT_MAX;
            }
            else {
              G[i][j] = distant(array[i],array[j]);
            }
            for (k = 0; k < N; k++) {
              if (p[k].x != 0 && p[k].y != 0 && q[k].x != 0 &&
                  q[k].y != 0 && array[i].x !=0 && array[i].y !=0 &&
                  intersect( array[i], array[j], p[k], q[k])) {
                G[i][j] = INT_MAX;
              }
            }
          }
        }
	    
        dijkstra(G, 0, array);
      }
    }
      break;
    default:
      /* this is a catch-all for other events; it does not do anything.
       *One could look at the report type to see what the event was */ 
      break;
    }
    
  }
  
  exit(0);
}
Example #12
0
Window mume_x11_create_window(
    Display *display, int type, Window parent,
    int x, int y, unsigned int width, unsigned int height,
    unsigned int clazz, int eventmask)
{
    int screen;
    int depth;
    Visual *visual;
    unsigned long valuemask;
    XSetWindowAttributes attributes;
    XSizeHints *size_hints;
    XWMHints *wm_hints;
    XClassHint *class_hints;
    Window window;

    screen = DefaultScreen(display);
    visual = DefaultVisual(display, screen);

    if (clazz != InputOnly) {
        depth = DefaultDepth(display, screen);
        valuemask = CWBackPixel | CWBorderPixel;
        attributes.background_pixel = WhitePixel(display, screen);
        attributes.border_pixel = BlackPixel(display, screen);

        if (MUME_BACKWIN_MENU == type) {
            assert(RootWindow(display, screen) == parent);

            valuemask |= CWSaveUnder | CWOverrideRedirect;
            attributes.save_under = True;
            attributes.override_redirect = True;
        }
    }
    else {
        depth = 0;
        valuemask = 0;
    }

    if (None == parent)
        parent = RootWindow(display, screen);

    window = XCreateWindow(
        display, parent, x, y, width, height, 0, depth,
        clazz, visual, valuemask, &attributes);

    if (clazz != InputOnly) {
        /* Setup standard properties. */
        if (!(size_hints = XAllocSizeHints()))
            mume_abort(("allocating memory failed!\n"));

        if (!(wm_hints = XAllocWMHints()))
            mume_abort(("allocating memory failed!\n"));

        if (!(class_hints = XAllocClassHint()))
            mume_abort(("allocating memory failed!\n"));

        size_hints->flags = PPosition | PSize | PMinSize;
        size_hints->min_width = 0;
        size_hints->min_height = 0;
        wm_hints->initial_state = NormalState;
        wm_hints->input = True;
        /* wm_hints->icon_pixmap = icon_pixmap; */
        wm_hints->flags = StateHint/* | IconPixmapHint*/ | InputHint;
        class_hints->res_name = "mume";
        class_hints->res_class = "mume";

        /* or use XSizeHints, XSetClassHint, XSetWMHints */
        XmbSetWMProperties(display, window, "mume", "mume",
                           NULL, 0, size_hints, wm_hints, class_hints);

        XFree(wm_hints);
        XFree(class_hints);
        XFree(size_hints);
    }

    /* Select event */
    XSelectInput(display, window, eventmask);

    return window;
}
Example #13
0
void make_window()
{
 Window                rootwindow;
 XpmAttributes         xpmattributes;
 XSetWindowAttributes  windowattributes;
 int                   shapeevent, shapeerror;
 XWMHints             *wmhints;
 XClassHint           *classhint;
 XSizeHints           *sizehints;
 XGCValues             gcvalues;
 unsigned int          depth;
 struct
 {
  long flags;
  long functions;
  long decorations;
  long input_mode;
  long unknown;
 } mwmhints;
 

 display = XOpenDisplay(opt_display);
 if(!display)
 {
  fprintf(stderr, "Could not open display %s\n", opt_display);
  exit(1);
 }
 screen = DefaultScreen(display);
 screenwidth = DisplayWidth(display, screen);
 screenheight = DisplayHeight(display, screen);
 rootwindow = RootWindow(display, screen);
 colormap = DefaultColormap(display, screen);
 depth = DefaultDepth(display, screen);
 xpmattributes.valuemask = XpmColormap | XpmCloseness;
 xpmattributes.colormap = colormap;
 xpmattributes.closeness = 40000;
 XpmCreatePixmapFromData(display, rootwindow, bg_xpm,
                         &background, &backgroundmask, &xpmattributes);
 XpmCreatePixmapFromData(display, rootwindow, on_xpm,
                         &on, None, &xpmattributes);
 XpmCreatePixmapFromData(display, rootwindow, off_xpm,
                         &off, None, &xpmattributes);
 XpmCreatePixmapFromData(display, rootwindow, numbers_xpm,
                         &numbers, None, &xpmattributes);
 buffer = XCreatePixmap(display, rootwindow,
                        WINDOW_WIDTH, WINDOW_HEIGHT, depth);
 windowattributes.background_pixmap = background;
 windowattributes.event_mask = ExposureMask |
                               ButtonPressMask |
			       ButtonReleaseMask |
			       PointerMotionMask |
			       PropertyChangeMask;
 windowattributes.colormap = colormap;
 window = XCreateWindow(display, rootwindow,
                        0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
			CopyFromParent,
			InputOutput,
			CopyFromParent,
			CWBackPixmap | CWEventMask | CWColormap,
			&windowattributes);
 iconwindow = XCreateWindow(display, rootwindow,
                            0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
			    CopyFromParent,
			    InputOutput,
			    CopyFromParent,
			    CWBackPixmap | CWEventMask,
			    &windowattributes);
 fleur = XCreateFontCursor(display, XC_fleur);
 if(XShapeQueryExtension(display, &shapeevent, &shapeerror) && opt_shape)
 {
  XShapeCombineMask(display, window, ShapeBounding,
                    0, 0, backgroundmask, ShapeSet);
  XShapeCombineMask(display, iconwindow, ShapeBounding,
                    0, 0, backgroundmask, ShapeSet);
 }
 else
 {  
  XpmCreatePixmapFromData(display, rootwindow, panel_xpm,
                          &panel, None, &xpmattributes);
  gcvalues.function = GXcopy;
  gcvalues.graphics_exposures = False;
  gcvalues.clip_mask = backgroundmask;
  gcvalues.clip_x_origin = 0;
  gcvalues.clip_y_origin = 0;
  gc = XCreateGC(display, rootwindow,
                 GCFunction |
                 GCGraphicsExposures |
                 GCClipMask |
		 GCClipXOrigin |
		 GCClipYOrigin,
		 &gcvalues);
  XCopyArea(display, background, panel, gc, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0);
  gcvalues.clip_mask = None;
  XChangeGC(display, gc, GCClipMask, &gcvalues);
  XCopyArea(display, panel, background, gc, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0);
  XFreeGC(display, gc);
  XFreePixmap(display, panel);
 }

 mapwindow = opt_window ? iconwindow : window;
 wmhints = XAllocWMHints();
 wmhints -> flags = InputHint | WindowGroupHint | IconWindowHint | StateHint;
 wmhints -> input = True;
 wmhints -> window_group = window;
 wmhints -> icon_window = iconwindow;
 wmhints -> initial_state = WithdrawnState;
 XSetWMHints(display, window, wmhints);
 XFree(wmhints);

 classhint = XAllocClassHint();
 classhint -> res_name = OPT_CLASS_NAME;
 classhint -> res_class = OPT_CLASS_CLASS;
 XSetClassHint(display, mapwindow, classhint);
 XFree(classhint);

 sizehints = XAllocSizeHints();
 sizehints -> flags = USSize | PSize | PMinSize | PMaxSize | PBaseSize;
 sizehints -> width = WINDOW_WIDTH;
 sizehints -> height = WINDOW_HEIGHT;
 sizehints -> min_width = WINDOW_WIDTH;
 sizehints -> min_height = WINDOW_HEIGHT;
 sizehints -> max_width = WINDOW_WIDTH;
 sizehints -> max_height = WINDOW_HEIGHT;
 sizehints -> base_width = WINDOW_WIDTH;
 sizehints -> base_height = WINDOW_HEIGHT;
 XSetWMNormalHints(display, mapwindow, sizehints);
 XFree(sizehints);

 XStoreName(display, window, OPT_WINDOW_NAME);
 XStoreName(display, iconwindow, OPT_WINDOW_NAME); /* For other wms */

 gcvalues.graphics_exposures = False;
 gcvalues.function = GXcopy;
 gc = XCreateGC(display, rootwindow,
                GCGraphicsExposures | GCFunction,
		&gcvalues);
 XCopyArea(display, background, buffer, gc, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0);
 XSetCommand(display, window, argv, argc);
 wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0);
 XSetWMProtocols(display, mapwindow, &wm_delete_window, 1);
 if(opt_window)
 {
  _motif_wm_hints = XInternAtom(display, "_MOTIF_WM_HINTS", 0);
  mwmhints.flags = 2;
  mwmhints.functions = 0x71; /* WTF IS THIS ? */
  mwmhints.decorations = 0;
  XChangeProperty(display, mapwindow,
                  _motif_wm_hints, _motif_wm_hints,
                  32, PropModeReplace, (unsigned char *)&mwmhints, 5);
 }
 XMapWindow(display, mapwindow);
 signal(SIGINT, handle_signal);
 signal(SIGQUIT, handle_signal);
 signal(SIGTERM, handle_signal);
}
Example #14
0
int main( int argc, char * argv[] )
{
    Window       win;
    int          x, y;
    unsigned int width, height;
    unsigned int border_width;
    char *       window_name = "Hello, X Window System!";
    char *       icon_name   = "HelloX";

    char *       display_name = NULL;
    unsigned int display_width, display_height;

    XSizeHints *  size_hints;
    XWMHints   *  wm_hints;
    XClassHint *  class_hints;
    XTextProperty windowName, iconName;
    XEvent        report;
    XFontStruct * font_info;
    XGCValues     values;
    GC            gc;

    appname = argv[0];

    if ( !( size_hints  = XAllocSizeHints() ) ||
         !( wm_hints    = XAllocWMHints()   ) ||
         !( class_hints = XAllocClassHint() )    ) {
        fprintf(stderr, "%s: couldn't allocate memory.\n", appname);
        exit(EXIT_FAILURE);
    }

    if ( (display = XOpenDisplay(display_name)) == NULL ) {
        fprintf(stderr, "%s: couldn't connect to X server %s\n",
                appname, display_name);
        exit(EXIT_FAILURE);
    }

    screen_num     = DefaultScreen(display);
    display_width  = DisplayWidth(display, screen_num);
    display_height = DisplayHeight(display, screen_num);

    x = y = 0;
    width  = display_width / 3;
    height = display_width / 3;

    win = XCreateSimpleWindow(display, RootWindow(display, screen_num),
                              x, y, width, height, border_width,
                              BlackPixel(display, screen_num),
                              WhitePixel(display, screen_num));

    if ( XStringListToTextProperty(&window_name, 1, &windowName) == 0 ) {
        fprintf(stderr, "%s: structure allocation for windowName failed.\n",
                appname);
        exit(EXIT_FAILURE);
    }

    if ( XStringListToTextProperty(&icon_name, 1, &iconName) == 0 ) {
        fprintf(stderr, "%s: structure allocation for iconName failed.\n",
                appname);
        exit(EXIT_FAILURE);
    }

    size_hints->flags       = PPosition | PSize | PMinSize;
    size_hints->min_width   = 200;
    size_hints->min_height  = 100;

    wm_hints->flags         = StateHint | InputHint;
    wm_hints->initial_state = NormalState;
    wm_hints->input         = True;

    class_hints->res_name   = appname;
    class_hints->res_class  = "hellox";

    XSetWMProperties(display, win, &windowName, &iconName, argv, argc,
                     size_hints, wm_hints, class_hints);

    XSelectInput(display, win, ExposureMask | KeyPressMask |
                 ButtonPressMask | StructureNotifyMask);

    if ( (font_info = XLoadQueryFont(display, "9x15")) == NULL ) {
        fprintf(stderr, "%s: cannot open 9x15 font.\n", appname);
        exit(EXIT_FAILURE);
    }

    gc = XCreateGC(display, win, 0, &values);

    XSetFont(display, gc, font_info->fid);
    XSetForeground(display, gc, BlackPixel(display, screen_num));

    XMapWindow(display, win);


    while ( 1 ) {
        static char * message = "Hello, X Window System!";
        //static int    length;
        static int    font_height;
        //static int    msg_x, msg_y;
        static int    msg_y = 0;

        XNextEvent(display, &report);

        switch ( report.type ) {

        case Expose:

            if ( report.xexpose.count != 0 )
                break;

        {
            /*length = XTextWidth(font_info, message, strlen(message));
            msg_x  = (width - length) / 2;*/

            msg_y = 0;
            QStringList list = stat();

            for (int i = 0; i < list.size(); i++)
            {
                font_height = font_info->ascent + font_info->descent;
                msg_y  += font_height + 2;

                XDrawString(display, win, gc, 10, msg_y,
                            list.at(i).toStdString().c_str(), list.at(i).length());
            }
        }
            break;


        case ConfigureNotify:
            width  = report.xconfigure.width;
            height = report.xconfigure.height;

            break;


        case DestroyNotify:
            XUnloadFont(display, font_info->fid);
            XFreeGC(display, gc);
            XCloseDisplay(display);
            exit(EXIT_SUCCESS);

        }
    }

    return 0;
}
Example #15
0
/*
 * Initialize a term_data
 */
static errr term_data_init(term_data *td, int i)
{
	term *t = &td->t;

	cptr name = angband_term_name[i];

	cptr font;

	int x = 0;
	int y = 0;

	int cols = 80;
	int rows = 24;

	int ox = 1;
	int oy = 1;

	int wid, hgt, num;

	char buf[80];

	cptr str;

	int val;

	XClassHint *ch;

	char res_name[20];
	char res_class[20];

	XSizeHints *sh;

	/* Get default font for this term */
	font = get_default_font(i);

	/* Window specific location (x) */
	sprintf(buf, "ANGBAND_X11_AT_X_%d", i);
	str = getenv(buf);
	x = (str != NULL) ? atoi(str) : -1;

	/* Window specific location (y) */
	sprintf(buf, "ANGBAND_X11_AT_Y_%d", i);
	str = getenv(buf);
	y = (str != NULL) ? atoi(str) : -1;

	/* Window specific cols */
	sprintf(buf, "ANGBAND_X11_COLS_%d", i);
	str = getenv(buf);
	val = (str != NULL) ? atoi(str) : -1;
	if (val > 0) cols = val;

	/* Window specific rows */
	sprintf(buf, "ANGBAND_X11_ROWS_%d", i);
	str = getenv(buf);
	val = (str != NULL) ? atoi(str) : -1;
	if (val > 0) rows = val;

	/* Hack the main window must be at least 80x24 */
	if (!i)
	{
		if (cols < 80) cols = 80;
		if (rows < 24) rows = 24;
	}

	/* Window specific inner border offset (ox) */
	sprintf(buf, "ANGBAND_X11_IBOX_%d", i);
	str = getenv(buf);
	val = (str != NULL) ? atoi(str) : -1;
	if (val > 0) ox = val;

	/* Window specific inner border offset (oy) */
	sprintf(buf, "ANGBAND_X11_IBOY_%d", i);
	str = getenv(buf);
	val = (str != NULL) ? atoi(str) : -1;
	if (val > 0) oy = val;


	/* Prepare the standard font */
	MAKE(td->fnt, infofnt);
	Infofnt_set(td->fnt);
	if (Infofnt_init_data(font)) quit_fmt("Couldn't load the requested font. (%s)", font);

	/* Hack -- key buffer size */
	num = ((i == 0) ? 1024 : 16);

	/* Assume full size windows */
	wid = cols * td->fnt->wid + (ox + ox);
	hgt = rows * td->fnt->hgt + (oy + oy);

	/* Create a top-window */
	MAKE(td->win, infowin);
	Infowin_set(td->win);
	Infowin_init_top(x, y, wid, hgt, 0,
	                 Metadpy->fg, Metadpy->bg);

	/* Ask for certain events */
	Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask);

	/* Set the window name */
	Infowin_set_name(name);

	/* Save the inner border */
	Infowin->ox = ox;
	Infowin->oy = oy;

	/* Make Class Hints */
	ch = XAllocClassHint();

	if (ch == NULL) quit("XAllocClassHint failed");

	my_strcpy(res_name, name, sizeof(res_name));
	res_name[0] = FORCELOWER(res_name[0]);
	ch->res_name = res_name;

	strcpy(res_class, "Angband");
	ch->res_class = res_class;

	XSetClassHint(Metadpy->dpy, Infowin->win, ch);

	/* Make Size Hints */
	sh = XAllocSizeHints();

	/* Oops */
	if (sh == NULL) quit("XAllocSizeHints failed");

	/* Main window has a differing minimum size */
	if (i == 0)
	{
		/* Main window min size is 80x24 */
		sh->flags = PMinSize | PMaxSize;
		sh->min_width = 80 * td->fnt->wid + (ox + ox);
		sh->min_height = 24 * td->fnt->hgt + (oy + oy);
		sh->max_width = 255 * td->fnt->wid + (ox + ox);
		sh->max_height = 255 * td->fnt->hgt + (oy + oy);
	}

	/* Other windows can be shrunk to 1x1 */
	else
	{
		/* Other windows */
		sh->flags = PMinSize | PMaxSize;
		sh->min_width = td->fnt->wid + (ox + ox);
		sh->min_height = td->fnt->hgt + (oy + oy);
		sh->max_width = 255 * td->fnt->wid + (ox + ox);
		sh->max_height = 255 * td->fnt->hgt + (oy + oy);
	}

	/* Resize increment */
	sh->flags |= PResizeInc;
	sh->width_inc = td->fnt->wid;
	sh->height_inc = td->fnt->hgt;

	/* Base window size */
	sh->flags |= PBaseSize;
	sh->base_width = (ox + ox);
	sh->base_height = (oy + oy);

	/* Use the size hints */
	XSetWMNormalHints(Metadpy->dpy, Infowin->win, sh);

	/* Map the window */
	Infowin_map();


	/* Move the window to requested location */
	if ((x >= 0) && (y >= 0)) Infowin_impell(x, y);


	/* Initialize the term */
	term_init(t, cols, rows, num);

	/* Use a "soft" cursor */
	t->soft_cursor = TRUE;

	/* Erase with "white space" */
	t->attr_blank = TERM_WHITE;
	t->char_blank = ' ';

	/* Hooks */
	t->xtra_hook = Term_xtra_x11;
	t->curs_hook = Term_curs_x11;
	t->bigcurs_hook = Term_bigcurs_x11;
	t->wipe_hook = Term_wipe_x11;
	t->text_hook = Term_text_x11;

	/* Save the data */
	t->data = td;

	/* Activate (important) */
	Term_activate(t);

	/* Success */
	return (0);
}
int main(int argc, char **argv)
{
    /* opening display: basic connection to X Server */
    if( (display_ptr = XOpenDisplay(display_name)) == NULL )
    {
        printf("Could not open display. \n");
        exit(-1);
    }
    printf("Connected to X server  %s\n", XDisplayName(display_name) );
    screen_num = DefaultScreen( display_ptr );
    screen_ptr = DefaultScreenOfDisplay( display_ptr );
    color_map  = XDefaultColormap( display_ptr, screen_num );
    display_width  = DisplayWidth( display_ptr, screen_num );
    display_height = DisplayHeight( display_ptr, screen_num );

    printf("Width %d, Height %d, Screen Number %d\n",
           display_width, display_height, screen_num);
    /* creating the window */
    border_width = 10;
    win_x = 0;
    win_y = 0;
    win_width = display_width/2;
    win_height = (int) (win_width / 1.7); /*rectangular window*/

    win= XCreateSimpleWindow( display_ptr, RootWindow( display_ptr, screen_num),
                              win_x, win_y, win_width, win_height, border_width,
                              BlackPixel(display_ptr, screen_num),
                              WhitePixel(display_ptr, screen_num) );
    /* now try to put it on screen, this needs cooperation of window manager */
    size_hints = XAllocSizeHints();
    wm_hints = XAllocWMHints();
    class_hints = XAllocClassHint();
    if( size_hints == NULL || wm_hints == NULL || class_hints == NULL )
    {
        printf("Error allocating memory for hints. \n");
        exit(-1);
    }

    size_hints -> flags = PPosition | PSize | PMinSize  ;
    size_hints -> min_width = 60;
    size_hints -> min_height = 60;

    XStringListToTextProperty( &win_name_string,1,&win_name);
    XStringListToTextProperty( &icon_name_string,1,&icon_name);

    wm_hints -> flags = StateHint | InputHint ;
    wm_hints -> initial_state = NormalState;
    wm_hints -> input = False;

    class_hints -> res_name = "x_use_example";
    class_hints -> res_class = "examples";

    XSetWMProperties( display_ptr, win, &win_name, &icon_name, argv, argc,
                      size_hints, wm_hints, class_hints );

    /* what events do we want to receive */
    XSelectInput( display_ptr, win,
                  ExposureMask | StructureNotifyMask | ButtonPressMask );

    /* finally: put window on screen */
    XMapWindow( display_ptr, win );

    XFlush(display_ptr);

    /* create graphics context, so that we may draw in this window */
    gc = XCreateGC( display_ptr, win, valuemask, &gc_values);
    XSetForeground( display_ptr, gc, BlackPixel( display_ptr, screen_num ) );
    XSetLineAttributes( display_ptr, gc, 4, LineSolid, CapRound, JoinRound);
    /* and three other graphics contexts, to draw in yellow and red and grey*/
    gc_yellow = XCreateGC( display_ptr, win, valuemask, &gc_yellow_values);
    XSetLineAttributes(display_ptr, gc_yellow, 6, LineSolid,CapRound, JoinRound);
    if( XAllocNamedColor( display_ptr, color_map, "yellow",
                          &tmp_color1, &tmp_color2 ) == 0 )
    {
        printf("failed to get color yellow\n");
        exit(-1);
    }
    else
        XSetForeground( display_ptr, gc_yellow, tmp_color1.pixel );
    gc_red = XCreateGC( display_ptr, win, valuemask, &gc_red_values);
    XSetLineAttributes( display_ptr, gc_red, 6, LineSolid, CapRound, JoinRound);
    if( XAllocNamedColor( display_ptr, color_map, "red",
                          &tmp_color1, &tmp_color2 ) == 0 )
    {
        printf("failed to get color red\n");
        exit(-1);
    }
    else
        XSetForeground( display_ptr, gc_red, tmp_color1.pixel );
    gc_grey = XCreateGC( display_ptr, win, valuemask, &gc_grey_values);
    if( XAllocNamedColor( display_ptr, color_map, "light grey",
                          &tmp_color1, &tmp_color2 ) == 0 )
    {
        printf("failed to get color grey\n");
        exit(-1);
    }
    else
        XSetForeground( display_ptr, gc_grey, tmp_color1.pixel );

    /* and now it starts: the event loop */
    while(1)
    {   XNextEvent( display_ptr, &report );
        switch( report.type )
        {
        case Expose:
            /* (re-)draw the example figure. This event happens
               each time some part ofthe window gets exposed (becomes visible) */
            XDrawLine(display_ptr, win, gc, win_width /4, win_height/ 3,
                      3*win_width/4, win_height/3 );
            XDrawLine(display_ptr, win, gc_red, win_width /4, 2*win_height/ 3,
                      3*win_width/4, 2*win_height/3 );
            XFillArc( display_ptr, win, gc_grey, win_width/2-win_height/6,
                      win_height/3,
                      win_height/3, win_height/3, 0, 360*64);
            XDrawArc( display_ptr, win, gc_yellow, win_width/4, win_height/3,
                      win_height/6, win_height/3, 90*64, 180*64);

            break;
        case ConfigureNotify:
            /* This event happens when the user changes the size of the window*/
            win_width = report.xconfigure.width;
            win_height = report.xconfigure.height;
            break;
        case ButtonPress:
            /* This event happens when the user pushes a mouse button. I draw
              a circle to show the point where it happened, but do not save
              the position; so when the next redraw event comes, these circles
            disappear again. */
        {
            int x, y;
            x = report.xbutton.x;
            y = report.xbutton.y;
            if (report.xbutton.button == Button1 )
                XFillArc( display_ptr, win, gc_red,
                          x -win_height/40, y- win_height/40,
                          win_height/20, win_height/20, 0, 360*64);
            else
                XFillArc( display_ptr, win, gc_yellow,
                          x - win_height/40, y - win_height/40,
                          win_height/20, win_height/20, 0, 360*64);

        }
        break;
        default:
            /* this is a catch-all for other events; it does not do anything.
                   One could look at the report type to see what the event was */
            break;
        }

    }
    exit(0);
}
Example #17
0
/*
 * Vstupní bod programu
 */
int main(int argc, char *argv[])
{
    XWMHints *wm_hints; /* Doporuèení pro window manager */
    XClassHint *class_hints; /* Jméno tøídy pro resource management */
    XTextProperty window_name, icon_name; /* Jména zobrazovaná window
                                               managerem */
    XSizeHints *size_hints; /* Doporuèená velikost okna */
    char *str_window_name = (char *) "Hello World";
    char *str_icon_name = (char *) "Hello Icon";
    XEvent event; /* Pro zpracování pøijatých událostí */
    static Bool window_too_small = False;
                        
    /* Inicializace */
    progname = argv[0];
    
    /* Pøipojení k X serveru */
    if(!(display = XOpenDisplay(display_name))) {
        fprintf(stderr, "%s: cannot connect to X server %s\n",
                progname, XDisplayName(display_name));
        exit(-1);
    }
    printf("Connected to X server %s\n", XDisplayName(display_name));
    screen_num = DefaultScreen(display);
    printf("Default screen number is %d\n", screen_num);
    screen_ptr = DefaultScreenOfDisplay(display);

    display_width = DisplayWidth(display, screen_num);
    display_height = DisplayHeight(display, screen_num);
    printf("Display is %u x %u pixels\n", display_width, display_height);

    /* Vytvoøení okna */
    x = y = 0; /* Okno umístí window manager */
    width = display_width/2;
    height = display_height/2;
    win = XCreateSimpleWindow(display, RootWindow(display, screen_num),
                              x, y, width, height, border_width,
                              BlackPixel(display, screen_num),
                              WhitePixel(display, screen_num));
    printf("Created window with ID %#lx\n", win);
    
    /* Pixmapa ikony */
    icon_pixmap = XCreateBitmapFromData(display, win, hello_icon_bits,
                                        hello_icon_width, hello_icon_height);
    printf("Created pixmap with ID %#lx\n", icon_pixmap);
    
    /* Nastavení properties pro window manager */
    if(!(size_hints = XAllocSizeHints())) {
        fprintf(stderr, "Cannot allocate memory\n");
        exit(-1);
    }
    if(!(wm_hints = XAllocWMHints())) {
        fprintf(stderr, "Cannot allocate memory\n");
        exit(-1);
    }
    if(!(class_hints = XAllocClassHint())) {
        fprintf(stderr, "Cannot allocate memory\n");
        exit(-1);
    }
    /* Poloha a velikost se bere ze skuteèných hodnot okna v oka¾iku
     * namapování. PPosition | PSize øíká, ¾e hodnoty nastavil program (a
     * window manager je mù¾e mìnit podle potøeby). USSize | USPosition by
     * znamenalo, ¾e hodnoty zadal u¾ivatel (napø. na pøíkazové øádce) a
     * window manager by je nemìl mìnit. */
    size_hints->flags = PPosition | PSize | PMinSize;
    /* Window manager by nemìl okno nikdy zmen¹it na ménì ne¾
     * min_width x min_height pixelù. */
    size_hints->min_width = 300;
    size_hints->min_height = 200;
    /* Ulo¾ení jména okna a ikony */
    if(!XStringListToTextProperty(&str_window_name, 1, &window_name)) {
        fprintf(stderr, "XStringListToTextProperty() for window_name"
                " failed\n");
        exit(-1);
    }
    if(!XStringListToTextProperty(&str_icon_name, 1, &icon_name)) {
        fprintf(stderr, "XStringListToTextProperty() for icon_name"
                " failed\n");
        exit(-1);
    }
    wm_hints->initial_state = NormalState;/* Na zaèátku má být zobrazeno
                                             normální okno (ne ikona) */
    wm_hints->input = True; /* Aplikace potøebuje vstup z klávesnice */
    wm_hints->icon_pixmap = icon_pixmap;
    wm_hints->flags = StateHint | InputHint | IconPixmapHint;
    /* Jméno programu a tøídy pro hledání v resource databázi */
    class_hints->res_name = progname;
    class_hints->res_class = (char *) "HelloWorld";
    XSetWMProperties(display, win, &window_name, &icon_name, argv, argc,
                     size_hints, wm_hints, class_hints);
    
    /* Výbìr typù událostí ke zpracování */
    XSelectInput(display, win, ExposureMask | KeyPressMask |
                 ButtonPressMask | StructureNotifyMask);

    /* Nahrát font */
    load_font(&font_info);

    /* Vytvoøit graphics context pro kreslení */
    getGC(win, &gc, font_info);

    /* Namapovat okno na obrazovku (zobrazit) */
    XMapWindow(display, win);

    /* Smyèka pro pøíjem a zpracování událostí */
    while(1) {
        XNextEvent(display, &event); /* Èeká na pøíchod dal¹í události */
        switch(event.type) { /* Zpracování události */
            case Expose:
                printf("Drawing (serial=%lu send=%d count=%d x=%d y=%d "
                       "w=%d h=%d)\n",
                       event.xexpose.serial,
                       event.xexpose.send_event,
                       event.xexpose.count,
                       event.xexpose.x,
                       event.xexpose.y,
                       event.xexpose.width,
                       event.xexpose.height);
                if(event.xexpose.count == 0) {
                    if(window_too_small) { /* Pøíli¹ zmen¹ené okno */
                        printf("Drawing small\n");
                        draw_too_small(win, gc, font_info);
                    } else { /* Nakreslit obsah okna */
                        printf("Drawing normal (w=%d h=%d)\n", width, height);
                        draw_text(win, gc, font_info, width, height);
                        draw_graphics(win, gc, width, height);
                    }
                }
                break;
            case ConfigureNotify:
                /* Kdybychom nevolali XClearWindow(), tak pøi rychlé zmìnì
                 * velikosti okna my¹í postupnì window manager mìní velikost
                 * okna, co¾ má za následek smazání pøedchozího obsahu okna a
                 * vygenerování událostí ConfigureNotify a Expose. Jen¾e
                 * jestli¾e program nestihne pøekreslit okno pøed dal¹í
                 * zmìnou velikosti okna, tak X server jednou sma¾e okno, pak
                 * program nìkolikrát pøeète ConfigureNotify a Expose a
                 * nìkolikrát nakreslí obsah okna pro rùzné velikosti
                 * zji¹tìné z ConfigureNotify. Takto se pøekryje nìkolik rùznì
                 * velkých kreseb a obsah okna je ¹patný. */
		if(width != event.xconfigure.width || height != event.xconfigure.height)
		    XClearWindow(display, win);
                width = event.xconfigure.width;
                height = event.xconfigure.height;
                window_too_small = (int) width < size_hints->min_width+10 ||
                    (int) height < size_hints->min_height+10;
                printf("ConfigureNotify (serial=%lu send=%d w=%d h=%d)\n",
                       event.xconfigure.serial,
                       event.xconfigure.send_event,
                       event.xconfigure.width,
                       event.xconfigure.height);
                break;
            case ButtonPress:
            case KeyPress:
                /* Libovolná klávesa nebo tlaèítko my¹i ukonèí program */
                /* Následující dvì volání nejsou nezbytná, XCloseDisplay()
                 * uklidí v¹echny server resources alokované tímto klientem */
                XUnloadFont(display, font_info->fid);
                XFreeGC(display, gc);
                /* Odpojení od X serveru */
                XCloseDisplay(display);
                return 0;
                break;
            default:
                /* Sem se dostanou události vybrané maskou StructureNotifyMask
                 * kromì ConfigureNotify. */
                break;
        }
    }

    /* Sem se program nikdy nedostane */
    return 0;
}
Example #18
0
void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {

	last_button_state=0;
	dpad_last[0]=0;
	dpad_last[1]=0;

	xmbstring=NULL;
	event_id=0;
	x11_window=0;
	last_click_ms=0;
	args=OS::get_singleton()->get_cmdline_args();
	current_videomode=p_desired;
	main_loop=NULL;
	last_timestamp=0;
	last_mouse_pos_valid=false;
	last_keyrelease_time=0;

	if (get_render_thread_mode()==RENDER_SEPARATE_THREAD) {
		XInitThreads();
	}
	
	/** XLIB INITIALIZATION **/
	x11_display = XOpenDisplay(NULL);
	
	char * modifiers = XSetLocaleModifiers ("@im=none");
	ERR_FAIL_COND( modifiers == NULL );
	
	xim = XOpenIM (x11_display, NULL, NULL, NULL);
	

	if (xim == NULL) {
		WARN_PRINT("XOpenIM failed");
		xim_style=NULL;
	} else {
		::XIMStyles *xim_styles=NULL;
		xim_style=0;
		char *imvalret=NULL;
		imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
		if (imvalret != NULL || xim_styles == NULL) {
			fprintf (stderr, "Input method doesn't support any styles\n");
		}
		
		if (xim_styles) {
			xim_style = 0;
			for (int i=0;i<xim_styles->count_styles;i++) {
				
				if (xim_styles->supported_styles[i] ==
				    (XIMPreeditNothing | XIMStatusNothing)) {
					    
					    xim_style = xim_styles->supported_styles[i];
					    break;
				    }
			}
			
			XFree (xim_styles);
		}
	}

	/*
	char* windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

		//freopen("/home/punto/stdout", "w", stdout);
		//reopen("/home/punto/stderr", "w", stderr);
		x11_window = atol(windowid);

		XWindowAttributes xwa;
		XGetWindowAttributes(x11_display,x11_window,&xwa);

		current_videomode.width = xwa.width;
		current_videomode.height = xwa.height;
	};
	*/

	// maybe contextgl wants to be in charge of creating the window
	//print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height));
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
	context_gl = memnew( ContextGL_X11( x11_display, x11_window,current_videomode, false ) );
	context_gl->initialize();

	if (p_video_driver == 0) {
		rasterizer = memnew( RasterizerGLES2 );
	} else {
		rasterizer = memnew( RasterizerGLES1 );
	};

#endif
	visual_server = memnew( VisualServerRaster(rasterizer) );

	if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {

		visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD));
	}

	// borderless fullscreen window mode
	if (current_videomode.fullscreen) {
		// needed for lxde/openbox, possibly others
		Hints hints;
		Atom property;
		hints.flags = 2;
		hints.decorations = 0;
		property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
		XChangeProperty(x11_display, x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
		XMapRaised(x11_display, x11_window);
		XWindowAttributes xwa;
		XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa);
		XMoveResizeWindow(x11_display, x11_window, 0, 0, xwa.width, xwa.height);

		// code for netwm-compliants
		XEvent xev;
		Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
		Atom fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);

		memset(&xev, 0, sizeof(xev));
		xev.type = ClientMessage;
		xev.xclient.window = x11_window;
		xev.xclient.message_type = wm_state;
		xev.xclient.format = 32;
		xev.xclient.data.l[0] = 1;
		xev.xclient.data.l[1] = fullscreen;
		xev.xclient.data.l[2] = 0;

		XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureNotifyMask, &xev);
	}

	// disable resizeable window
	if (!current_videomode.resizable) {
		XSizeHints *xsh;
		xsh = XAllocSizeHints();
		xsh->flags = PMinSize | PMaxSize;
		XWindowAttributes xwa;
		if (current_videomode.fullscreen) {
			XGetWindowAttributes(x11_display,DefaultRootWindow(x11_display),&xwa);
		} else {
			XGetWindowAttributes(x11_display,x11_window,&xwa);
		}
		xsh->min_width = xwa.width; 
		xsh->max_width = xwa.width;
		xsh->min_height = xwa.height;
		xsh->max_height = xwa.height;
		XSetWMNormalHints(x11_display, x11_window, xsh);
	}

	AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton();

	if (AudioDriverManagerSW::get_driver(p_audio_driver)->init()!=OK) {

		ERR_PRINT("Initializing audio failed.");
	}

	sample_manager = memnew( SampleManagerMallocSW );
	audio_server = memnew( AudioServerSW(sample_manager) );
	audio_server->init();
	spatial_sound_server = memnew( SpatialSoundServerSW );
	spatial_sound_server->init();
	spatial_sound_2d_server = memnew( SpatialSound2DServerSW );
	spatial_sound_2d_server->init();

	
	ERR_FAIL_COND(!visual_server);
	ERR_FAIL_COND(x11_window==0);

	XSetWindowAttributes new_attr;

	new_attr.event_mask=KeyPressMask | KeyReleaseMask | ButtonPressMask |
			   ButtonReleaseMask | EnterWindowMask |
			   LeaveWindowMask | PointerMotionMask |
			   Button1MotionMask |
			   Button2MotionMask | Button3MotionMask |
			   Button4MotionMask | Button5MotionMask |
			   ButtonMotionMask | KeymapStateMask |
			   ExposureMask | VisibilityChangeMask |
			   StructureNotifyMask |
			   SubstructureNotifyMask | SubstructureRedirectMask |
			   FocusChangeMask | PropertyChangeMask |
			   ColormapChangeMask | OwnerGrabButtonMask;

	XChangeWindowAttributes(x11_display, x11_window,CWEventMask,&new_attr);
	
    XClassHint* classHint;

    /* set the titlebar name */
    XStoreName(x11_display, x11_window, "Godot");

    /* set the name and class hints for the window manager to use */
    classHint = XAllocClassHint();
    if (classHint) {
        classHint->res_name = "Godot";
        classHint->res_class = "Godot";
    }
    XSetClassHint(x11_display, x11_window, classHint);
    XFree(classHint);

	wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);	
	XSetWMProtocols(x11_display, x11_window, &wm_delete, 1);
		

	if (xim && xim_style) {
		
		xic = XCreateIC (xim,XNInputStyle, xim_style,XNClientWindow,x11_window,XNFocusWindow, x11_window, (char*)NULL);
	} else {
		
		xic=NULL;
		WARN_PRINT("XCreateIC couldn't create xic");

	}	

	XcursorSetTheme(x11_display,"default");
	cursor_size = XcursorGetDefaultSize(x11_display);
	cursor_theme = XcursorGetTheme(x11_display);

	if (!cursor_theme) {
		print_line("not found theme");
		cursor_theme="default";
	}

	for(int i=0;i<CURSOR_MAX;i++) {

		cursors[i]=None;
	}

	current_cursor=CURSOR_ARROW;

	if (cursor_theme) {
		//print_line("cursor theme: "+String(cursor_theme));
		for(int i=0;i<CURSOR_MAX;i++) {

			static const char *cursor_file[]={
				"left_ptr",
				"xterm",
				"hand2",
				"cross",
				"watch",
				"left_ptr_watch",
				"fleur",
				"hand1",
				"X_cursor",
				"sb_v_double_arrow",
				"sb_h_double_arrow",
				"size_bdiag",
				"size_fdiag",
				"hand1",
				"sb_v_double_arrow",
				"sb_h_double_arrow",
				"question_arrow"
			};

			XcursorImage *img = XcursorLibraryLoadImage(cursor_file[i],cursor_theme,cursor_size);
			if (img) {
				cursors[i]=XcursorImageLoadCursor(x11_display,img);
				//print_line("found cursor: "+String(cursor_file[i])+" id "+itos(cursors[i]));
			} else {
				if (OS::is_stdout_verbose())
					print_line("failed cursor: "+String(cursor_file[i]));
			}
		}

	}


	{
		Pixmap cursormask;
		 XGCValues xgc;
		 GC gc;
		 XColor col;
		 Cursor cursor;

		 cursormask = XCreatePixmap(x11_display, RootWindow(x11_display,DefaultScreen(x11_display)), 1, 1, 1);
		 xgc.function = GXclear;
		 gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
		XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
		col.pixel = 0;
		col.red = 0;
		col.flags = 4;
		cursor = XCreatePixmapCursor(x11_display,
			      cursormask, cursormask,
			      &col, &col, 0, 0);
		 XFreePixmap(x11_display, cursormask);
		 XFreeGC(x11_display, gc);



		 if (cursor == None)
		 {
			 ERR_PRINT("FAILED CREATING CURSOR");
		 }

		 null_cursor=cursor;
	}
	set_cursor_shape(CURSOR_BUSY);


	visual_server->init();
	//
	physics_server = memnew( PhysicsServerSW );
	physics_server->init();
	physics_2d_server = memnew( Physics2DServerSW );
	physics_2d_server->init();

	input = memnew( InputDefault );

	probe_joystick();

	_ensure_data_dir();

	net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);


	//printf("got map notify\n");
		
}
Example #19
0
// Create the X11 window (and its colormap)
//
static GLboolean createWindow(_GLFWwindow* window,
                              const _GLFWwndconfig* wndconfig)
{
    unsigned long wamask;
    XSetWindowAttributes wa;
    XVisualInfo* visual = _GLFW_X11_CONTEXT_VISUAL;

    // Every window needs a colormap
    // Create one based on the visual used by the current context
    // TODO: Decouple this from context creation

    window->x11.colormap = XCreateColormap(_glfw.x11.display,
                                           _glfw.x11.root,
                                           visual->visual,
                                           AllocNone);

    // Create the actual window
    {
        wamask = CWBorderPixel | CWColormap | CWEventMask;

        wa.colormap = window->x11.colormap;
        wa.border_pixel = 0;
        wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
                        PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
                        ExposureMask | FocusChangeMask | VisibilityChangeMask |
                        EnterWindowMask | LeaveWindowMask | PropertyChangeMask;

        if (wndconfig->monitor == NULL)
        {
            // HACK: This is a workaround for windows without a background pixel
            // not getting any decorations on certain older versions of Compiz
            // running on Intel hardware
            wa.background_pixel = BlackPixel(_glfw.x11.display,
                                             _glfw.x11.screen);
            wamask |= CWBackPixel;
        }

        window->x11.handle = XCreateWindow(_glfw.x11.display,
                                           _glfw.x11.root,
                                           0, 0,
                                           wndconfig->width, wndconfig->height,
                                           0,              // Border width
                                           visual->depth,  // Color depth
                                           InputOutput,
                                           visual->visual,
                                           wamask,
                                           &wa);

        if (!window->x11.handle)
        {
            // TODO: Handle all the various error codes here and translate them
            // to GLFW errors

            _glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to create window");
            return GL_FALSE;
        }
    }

    if (window->monitor && !_glfw.x11.hasEWMH)
    {
        // This is the butcher's way of removing window decorations
        // Setting the override-redirect attribute on a window makes the window
        // manager ignore the window completely (ICCCM, section 4)
        // The good thing is that this makes undecorated fullscreen windows
        // easy to do; the bad thing is that we have to do everything manually
        // and some things (like iconify/restore) won't work at all, as those
        // are tasks usually performed by the window manager

        XSetWindowAttributes attributes;
        attributes.override_redirect = True;
        XChangeWindowAttributes(_glfw.x11.display,
                                window->x11.handle,
                                CWOverrideRedirect,
                                &attributes);

        window->x11.overrideRedirect = GL_TRUE;
    }

    // Declare the WM protocols supported by GLFW
    {
        int count = 0;
        Atom protocols[2];

        // The WM_DELETE_WINDOW ICCCM protocol
        // Basic window close notification protocol
        if (_glfw.x11.WM_DELETE_WINDOW != None)
            protocols[count++] = _glfw.x11.WM_DELETE_WINDOW;

        // The _NET_WM_PING EWMH protocol
        // Tells the WM to ping the GLFW window and flag the application as
        // unresponsive if the WM doesn't get a reply within a few seconds
        if (_glfw.x11.NET_WM_PING != None)
            protocols[count++] = _glfw.x11.NET_WM_PING;

        if (count > 0)
        {
            XSetWMProtocols(_glfw.x11.display, window->x11.handle,
                            protocols, count);
        }
    }

    // Set ICCCM WM_HINTS property
    {
        XWMHints* hints = XAllocWMHints();
        if (!hints)
        {
            _glfwInputError(GLFW_OUT_OF_MEMORY,
                            "X11: Failed to allocate WM hints");
            return GL_FALSE;
        }

        hints->flags = StateHint;
        hints->initial_state = NormalState;

        XSetWMHints(_glfw.x11.display, window->x11.handle, hints);
        XFree(hints);
    }

    // Set ICCCM WM_NORMAL_HINTS property (even if no parts are set)
    {
        XSizeHints* hints = XAllocSizeHints();
        hints->flags = 0;

        if (wndconfig->monitor)
        {
            hints->flags |= PPosition;
            _glfwPlatformGetMonitorPos(wndconfig->monitor, &hints->x, &hints->y);
        }

        if (!wndconfig->resizable)
        {
            hints->flags |= (PMinSize | PMaxSize);
            hints->min_width  = hints->max_width  = wndconfig->width;
            hints->min_height = hints->max_height = wndconfig->height;
        }

        XSetWMNormalHints(_glfw.x11.display, window->x11.handle, hints);
        XFree(hints);
    }

    _glfwPlatformSetWindowTitle(window, wndconfig->title);

    XRRSelectInput(_glfw.x11.display, window->x11.handle,
                   RRScreenChangeNotifyMask);

    return GL_TRUE;
}
Example #20
0
File: gui.c Project: NgoHuy/unikey
//------------------------------------------------------
int main(int argc, char **argv)
{
  XSizeHints *sizeHints;
  XWMHints *wmHints;
  XClassHint *classHints;
  XTextProperty windowNameP, iconNameP;
  char *windowName = "UniKey GUI";
  char *iconName = "UniKey";
  XSetWindowAttributes attrs;
  Bool setXim = False;
  int i;
  pid_t pid;

  progname = argv[0];

  for (i = 1; i < argc; i++) {
    if (!strcmp(argv[i], "-display")) {
      DisplayName = argv[++i];
    }
    else if (!strcmp(argv[i], "-xim")) {
      setXim = True;
      strcpy(XimPath, argv[++i]);
    }
    else if (!strcmp(argv[i], "-macro")) {
      MacroFile = argv[++i];
    }
    else if (!strcmp(argv[i], "-config")) {
      ConfigFile = argv[++i];
    }
    else if (!strcmp(argv[i], "-locales") || !strcmp(argv[i], "-l")) {
      XimLocales = argv[++i];
    }
    else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h")) {
      usage();
      exit(0);
    }
    else if (!strcmp(argv[i], "-version") || !strcmp(argv[i], "-v")) {
      showVersion();
      exit(0);
    }
    else {
      puts("Wrong options! Run \"unikey -h\" for help\n");
      exit(-1);
    }
  }

  if (!setXim)
    getXimPath();
  
  pid = fork();
  if (pid > 0)
    exit(0);
  else if (pid < 0) {
    fputs("failed to launch new child process\n", stderr);
    exit(-1);
  }

  getOptions();

  if (!(sizeHints = XAllocSizeHints())) {
    fprintf(stderr, "%s: failure allocating memory\n", progname);
    exit(0);
  }

  if (!(wmHints = XAllocWMHints())) {
    fprintf(stderr, "%s: failure allocating memory\n", progname);
    exit(0);
  }
  
  if (!(classHints = XAllocClassHint())) {
    fprintf(stderr, "%s: failure allocating memory\n", progname);
    exit(0);
  }

  if ((display = XOpenDisplay(DisplayName)) == NULL) {
    fprintf(stderr, "Can't Open Display: %s\n", XDisplayName(DisplayName));
    XCloseDisplay(display);
    exit(1);
  }

  StartTime = time(0);
  RootWindow = DefaultRootWindow(display);
  setRootPropMask();
  getSyncAtoms();

  if (!singleLaunch()) {
    //check if previous instance is hidden
    if (!UkGetPropValue(AGUIVisible, 0)) {
      //wake up
      UkSetPropValue(AGUIVisible, 1);
      XFlush(display);
    }
    else {
      UkSetPropValue(ARaiseWindow, 1);
      XFlush(display);
      fputs("An instance of unikey has already started!\n", stderr);
    }
    exit(1);
  }

  UkSetPropValue(AGUIVisible, 1);
  UkGUIVisible = 1;

  /* get screen size from display structure macro */
  ScreenNum = DefaultScreen(display);
  displayWidth = DisplayWidth(display, ScreenNum);
  displayHeight = DisplayHeight(display, ScreenNum);
  MainColormap = DefaultColormap(display, ScreenNum);

  // MainWinX = displayWidth-MainWinWidth-50;
  // MainWinY = displayHeight-MainWinHeight-50;
  getInitPos();

  MainWindow = XCreateSimpleWindow(display, DefaultRootWindow(display),
				   MainWinX,
				   MainWinY,
				   MainWinWidth, MainWinHeight,
				   0, WhitePixel(display, ScreenNum),
				   WhitePixel(display, ScreenNum));
  attrs.override_redirect = True;
  XChangeWindowAttributes(display, MainWindow, CWOverrideRedirect, &attrs);

  if (MainWindow == (Window)NULL) {
    fprintf(stderr, "Can't Create Window\n");
    exit(1);
  }

  // Setup window properties
  sizeHints->flags = PPosition | PSize | PMinSize;
  sizeHints->min_width = MainWinWidth;
  sizeHints->min_height = MainWinHeight;

  if (XStringListToTextProperty(&windowName, 1, &windowNameP) == 0) {
    fprintf( stderr, "Structure allocation for windowName failed.\n"); 
    exit(-1);
  }

  if (XStringListToTextProperty(&iconName, 1, &iconNameP) == 0) {
    fprintf( stderr, "Structure allocation for iconName failed.\n"); 
    exit(-1);
  }

  wmHints->initial_state = NormalState;
  wmHints->input = True;
  wmHints->flags = StateHint | InputHint;

  classHints->res_name = progname;
  classHints->res_class = "UnikeyWindow";

  XSetWMProperties(display, MainWindow, &windowNameP, &iconNameP, 
		   argv, argc, sizeHints, wmHints, 
		   classHints);

  XChangeProperty(display, MainWindow, 
		  _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, 
		  (unsigned char *)&_NET_WM_WINDOW_TYPE_DOCK, 1);

  //  XStoreName(display, im_window, "Unikey");
  XSetTransientForHint(display, MainWindow, MainWindow);
  XSelectInput(display, MainWindow, 
     StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask |
     VisibilityChangeMask | PointerMotionMask | PropertyChangeMask);
  
  allocXResources();
  getInitSettings();

  XMapWindow(display, MainWindow);
  UkSetPropValue(AGUIPosX, MainWinX);
  UkSetPropValue(AGUIPosY, MainWinY);

  signalSetup();
  ChildPid = childProcess();

  UkLoopContinue = 1;
  while (UkLoopContinue) {
    XEvent event;
    XNextEvent(display, &event);
    /*
      if (XFilterEvent(&event, None) == True) {
      continue;
      }
    */
    MyXEventHandler(MainWindow, &event);
  }
  cleanup();
  return 0;
}
Example #21
0
static byte X11_InitHW(void) {
    char *arg = HW->Name;
    int xscreen;
    unsigned int xdepth;
    XSetWindowAttributes xattr;
    XColor xcolor;
    XSizeHints *xhints;
    XEvent event;
    Visual *xvisual;
    Colormap colormap;
    byte *s, *xdisplay_ = NULL, *xdisplay0 = NULL,
        *fontname = NULL, *fontname0 = NULL,
        *charset = NULL, *charset0 = NULL,
        title[X11_TITLE_MAXLEN];
    int i, nskip;
    udat fontwidth = 8, fontheight = 16;
    byte drag = tfalse, noinput = tfalse;
    unsigned long xcreategc_mask = GCForeground|GCBackground|GCGraphicsExposures;
    
    if (!(HW->Private = (struct x11_data *)AllocMem(sizeof(struct x11_data)))) {
	printk("      X11_InitHW(): Out of memory!\n");
	return tfalse;
    }
    WriteMem(HW->Private, 0, sizeof(struct x11_data));

    /* default: show the whole screen */
    xhw_view = xhw_startx = xhw_starty = xhw_endx = xhw_endy = 0;

    /* not yet opened */
    xdisplay = NULL;
    
    if (arg && *arg && ((nskip = check_hw_name(arg)) > 0)) {
        arg += nskip;

	if (*arg == '@') {
	    if ((s = strchr(xdisplay_ = ++arg, ','))) {
		*(xdisplay0 = s) = '\0';
		arg = s + 1;
	    } else
		arg = NULL;
	}

	while (arg && *arg) {
	    /* parse options */
	    if (*arg == ',') {
		arg++;
		continue;
	    }
	    if (!strncmp(arg, "font=", 5)) {
		fontname = arg += 5;
		s = strchr(arg, ',');
		if (s) *(fontname0 = s++) = '\0';
		arg = s;
            } else if (!strncmp(arg, "fontsize=", 9)) {
                int n1 = atoi(arg += 9), n2 = 0;
                byte ch;
                if (n1 > 0) {
                    while ((ch = (byte)*++arg) && ch != ',') {
                        if (ch == 'x') {
                            n2 = atoi(arg+1);
                            break;
                        }
                    }
                    fontwidth  = Min2(TW_MAXUDAT, n2 > 0 ? n1 : n1 / 2);
                    fontheight = Min2(TW_MAXUDAT, n2 > 0 ? n2 : n1);
                }
	    } else if (!strncmp(arg, "charset=", 8)) {
		charset = arg += 8;
		s = strchr(arg, ',');
		if (s) *(charset0 = s++) = '\0';
		arg = s;
	    } else if (!strncmp(arg, "view=", 5)) {
		xhw_view = 1;
		xhw_endx = strtol(arg+5, &arg, 0);
		xhw_endy = strtol(arg+1, &arg, 0);
		xhw_startx = strtol(arg+1, &arg, 0);
		xhw_starty = strtol(arg+1, &arg, 0);
		xhw_endx += xhw_startx;
		xhw_endy += xhw_starty;
	    } else if (!strncmp(arg, "drag", 4)) {
		arg += 4;
		drag = ttrue;
	    } else if (!strncmp(arg, "noinput", 7)) {
		arg += 7;
		noinput = ttrue;
	    } else
		arg = strchr(arg, ',');
	}
    }

    xsfont = NULL; xhints = NULL;
    xwindow = None; xgc = None;
    xReqCount = XReqCount = 0;
    HW->keyboard_slot = NOSLOT;
    
    if ((xdisplay = XOpenDisplay(xdisplay_))) do {
	
	(void)XSetIOErrorHandler(X11_Die);

	if (!X11_CheckRemapKeys())
	    break;

	xscreen = DefaultScreen(xdisplay);
	xdepth  = DefaultDepth(xdisplay, xscreen);
        xvisual = DefaultVisual(xdisplay, xscreen);
        colormap = DefaultColormap(xdisplay, xscreen);
	
	for (i = 0; i <= MAXCOL; i++) {
	    xcolor.red   = 257 * (udat)Palette[i].Red;
	    xcolor.green = 257 * (udat)Palette[i].Green;
	    xcolor.blue  = 257 * (udat)Palette[i].Blue;
            if (!X11_AllocColor(xdisplay, xvisual, colormap, &xcolor, &xcol[i], i)) {
                printk("      X11_InitHW() failed to allocate colors\n");
                break;
            }
	}
	if (i <= MAXCOL)
	    break;
	
	xattr.background_pixel = xcol[0];
	xattr.event_mask = ExposureMask | VisibilityChangeMask |
	    StructureNotifyMask | SubstructureNotifyMask |
	    KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;

	if (!X11_LoadFont(fontname, fontwidth, fontheight))
	    break;
	
	if (xhw_view && xhw_startx >= 0 && xhw_starty >= 0 && xhw_endx > xhw_startx && xhw_endy > xhw_starty) {
	    /* a valid view was specified */
	    
	    xwidth  = xwfont * (ldat)(xhw_endx - xhw_startx);
	    xheight = xhfont * (ldat)(xhw_endy - xhw_starty);
	} else {
	    xhw_view = xhw_startx = xhw_starty = 0;
	    xhw_endx = HW->X;
	    xhw_endy = HW->Y;
	}
	
	if ((xwindow = XCreateWindow(xdisplay, DefaultRootWindow(xdisplay), 0, 0,
				     xwidth, xheight, 0, xdepth, InputOutput,
				     xvisual, CWBackPixel | CWEventMask, &xattr)) &&

	    (xsgc.foreground = xsgc.background = xcol[0],
	     xsgc.graphics_exposures = False,
#if HW_X_DRIVER == HW_X11
	     xsgc.font = xsfont->fid,
             xcreategc_mask = xcreategc_mask|GCFont,
#elif HW_X_DRIVER == HW_XFT
             xforeground = xbackground = xftcolors[0],
#endif
	     xgc = XCreateGC(xdisplay, xwindow, xcreategc_mask, &xsgc)) &&

	    (xhints = XAllocSizeHints()))
        {
	    
            static XComposeStatus static_xcompose;
            xcompose = static_xcompose;

#if HW_X_DRIVER == HW_XFT
            xftdraw = XftDrawCreate(xdisplay,xwindow,xvisual,colormap);
#endif

#ifdef TW_FEATURE_X11_XIM_XIC
            xim = XOpenIM(xdisplay, NULL, NULL, NULL);
            if (xim != NULL) {
                xic = XCreateIC(xim, XNInputStyle, XIMStatusNothing|XIMPreeditNothing,
                                XNClientWindow, xwindow, XNFocusWindow, xwindow, NULL);
                if (xic == NULL) {
                    XCloseIM(xim);
                    xim = NULL;
                }
            } else
                xic = NULL;
#endif
            X11_FillWindowTitle(title, sizeof(title));
	    XStoreName(xdisplay, xwindow, title);


	    if (!(xUTF_32_to_charset = X11_UTF_32_to_charset_function(charset)))
		xUTF_32_to_charset = X11_UTF_32_to_UCS_2;
	    /*
	     * ask ICCCM-compliant window manager to tell us when close window
	     * has been chosen, rather than just killing us
	     */
	    xWM_PROTOCOLS = XInternAtom(xdisplay, "WM_PROTOCOLS", False);
	    xWM_DELETE_WINDOW = XInternAtom(xdisplay, "WM_DELETE_WINDOW", False);
	    xTARGETS = XInternAtom(xdisplay, "TARGETS", False);

	    XChangeProperty(xdisplay, xwindow, xWM_PROTOCOLS, XA_ATOM, 32, PropModeReplace,
			    (unsigned char *) &xWM_DELETE_WINDOW, 1);

	    if (xhw_view) {
		xhints->flags = PMinSize|PMaxSize;
		xhints->min_width = xhints->max_width = xwidth;
		xhints->min_height = xhints->max_height = xheight;
	    } else {
		xhints->flags = PResizeInc;
		xhints->width_inc  = xwfont;
		xhints->height_inc = xhfont;
	    }
	    XSetWMNormalHints(xdisplay, xwindow, xhints);
	    
	    XMapWindow(xdisplay, xwindow);
	    
	    do {
		XNextEvent(xdisplay, &event);
	    } while (event.type != MapNotify);
	    
	    XFree(xhints); xhints = NULL;
	    
	    HW->mouse_slot = NOSLOT;
	    HW->keyboard_slot = RegisterRemote(i = XConnectionNumber(xdisplay), (obj)HW,
					       X11_KeyboardEvent);
	    if (HW->keyboard_slot == NOSLOT)
		break;
	    fcntl(i, F_SETFD, FD_CLOEXEC);
	    
	    HW->FlushVideo = X11_FlushVideo;
	    HW->FlushHW = X11_FlushHW;
	    
	    HW->KeyboardEvent = X11_KeyboardEvent;
	    HW->MouseEvent = (void *)NoOp; /* mouse events handled by X11_KeyboardEvent */
	    
	    HW->XY[0] = HW->XY[1] = 0;
	    HW->TT = NOCURSOR;
	    
	    HW->ShowMouse = NoOp;
	    HW->HideMouse = NoOp;
	    HW->UpdateMouseAndCursor = NoOp;
	    HW->MouseState.x = HW->MouseState.y = HW->MouseState.keys = 0;
	    
	    HW->DetectSize  = X11_DetectSize;
	    HW->CheckResize = X11_CheckResize;
	    HW->Resize      = X11_Resize;
	    
	    HW->HWSelectionImport  = X11_SelectionImport_X11;
	    HW->HWSelectionExport  = X11_SelectionExport_X11;
	    HW->HWSelectionRequest = X11_SelectionRequest_X11;
	    HW->HWSelectionNotify  = X11_SelectionNotify_X11;
	    HW->HWSelectionPrivate = 0;
	    
	    if (drag) {
		HW->CanDragArea = X11_CanDragArea;
		HW->DragArea    = X11_DragArea;
	    } else
		HW->CanDragArea = NULL;
	    
	    HW->Beep = X11_Beep;
	    HW->Configure = X11_Configure;
	    HW->SetPalette = (void *)NoOp;
	    HW->ResetPalette = NoOp;
	    
	    HW->QuitHW = X11_QuitHW;
	    HW->QuitKeyboard  = NoOp;
	    HW->QuitMouse = NoOp;
	    HW->QuitVideo = NoOp;
	    
	    HW->DisplayIsCTTY = tfalse;
	    HW->FlagsHW &= ~FlHWSoftMouse; /* mouse pointer handled by X11 server */
	    
	    HW->FlagsHW |= FlHWNeedOldVideo;
	    HW->FlagsHW |= FlHWExpensiveFlushVideo;
	    if (noinput)
		HW->FlagsHW |= FlHWNoInput;
	    
	    HW->NeedHW = 0;
	    HW->CanResize = ttrue;
	    HW->merge_Threshold = 0;
	    
	    /*
	     * we must draw everything on our new shiny window
	     * without forcing all other displays
	     * to redraw everything too.
	     */
	    HW->RedrawVideo = tfalse;
	    NeedRedrawVideo(0, 0, HW->X - 1, HW->Y - 1);
	    
	    if (xdisplay0) *xdisplay0 = ',';
	    if (fontname0) *fontname0 = ',';
	    if (charset0) *charset0 = ',';
	    
	    return ttrue;
	}
    } while (0); else {
	if (xdisplay_ || (xdisplay_ = getenv("DISPLAY")))
	    printk("      X11_InitHW() failed to open display %."STR(TW_SMALLBUFF)"s\n", HW->Name);
	else
	    printk("      X11_InitHW() failed: DISPLAY is not set\n");
    }

fail:
    if (xdisplay0) *xdisplay0 = ',';
    if (fontname0) *fontname0 = ',';
    if (charset0) *charset0 = ',';
	
    if (xdisplay)
	X11_QuitHW();

    FreeMem(HW->Private);
    HW->Private = NULL;
    
    return tfalse;
}
Example #22
0
int main(int argc, char **argv)
{
  FILE *fp;
  int x_1,y_1,x_2,y_2,x_3,y_3;
  char a;
  int i,j;
  int outside;
  int ButtonPressed = 0;
  int temp_x, temp_y;
  pixel_count = 0;
  for(i=0;i<302;i++)
  {              
    for(j=0;j<302;j++)  
    {          
      cost[i][j] = 9999; 
    } 
  }

  if( (display_ptr = XOpenDisplay(display_name)) == NULL )
    { printf("Could not open display. \n"); exit(-1);}
  printf("Connected to X server  %s\n", XDisplayName(display_name) );
  screen_num = DefaultScreen( display_ptr );
  screen_ptr = DefaultScreenOfDisplay( display_ptr );
  color_map  = XDefaultColormap( display_ptr, screen_num );
  display_width  = DisplayWidth( display_ptr, screen_num );
  display_height = DisplayHeight( display_ptr, screen_num );

  printf("Width %d, Height %d, Screen Number %d\n", 
           display_width, display_height, screen_num);
  border_width = 10;
  win_x = 0; win_y = 0;
  win_width = display_width;
  win_height = display_height; 
  
  win= XCreateSimpleWindow( display_ptr, RootWindow( display_ptr, screen_num),
                            win_x, win_y, win_width, win_height, border_width,
                            BlackPixel(display_ptr, screen_num),
                            WhitePixel(display_ptr, screen_num) );
  size_hints = XAllocSizeHints();
  wm_hints = XAllocWMHints();
  class_hints = XAllocClassHint();
  if( size_hints == NULL || wm_hints == NULL || class_hints == NULL )
    { printf("Error allocating memory for hints. \n"); exit(-1);}

  size_hints -> flags = PPosition | PSize | PMinSize  ;
  size_hints -> min_width = 60;
  size_hints -> min_height = 60;

  XStringListToTextProperty( &win_name_string,1,&win_name);
  XStringListToTextProperty( &icon_name_string,1,&icon_name);
  
  wm_hints -> flags = StateHint | InputHint ;
  wm_hints -> initial_state = NormalState;
  wm_hints -> input = False;

  class_hints -> res_name = "x_use_example";
  class_hints -> res_class = "examples";

  XSetWMProperties( display_ptr, win, &win_name, &icon_name, argv, argc,
                    size_hints, wm_hints, class_hints );

  XSelectInput( display_ptr, win, 
            ExposureMask | StructureNotifyMask | ButtonPressMask );
  
  XMapWindow( display_ptr, win );

  XFlush(display_ptr);
  gc_red = XCreateGC( display_ptr, win, valuemask, &gc_red_values);
  XSetLineAttributes( display_ptr, gc_red, 3, LineSolid, CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "red", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get color red\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_red, tmp_color1.pixel );
  gc_black = XCreateGC( display_ptr, win, valuemask, &gc_black_values);
  XSetLineAttributes(display_ptr, gc_black, 3, LineSolid,CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "black", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get color black\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_black, tmp_color1.pixel );
  gc_blue = XCreateGC( display_ptr, win, valuemask, &gc_blue_values);
  XSetLineAttributes(display_ptr, gc_blue, 3, LineSolid,CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "blue", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get blue yellow\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_blue, tmp_color1.pixel );
  gc_white = XCreateGC( display_ptr, win, valuemask, &gc_white_values);
  XSetLineAttributes(display_ptr, gc_white, 3, LineSolid,CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "white", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get color white\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_white, tmp_color1.pixel );

  if ( argc != 2 ) 
  {
      printf( "Usage: %s filename.extension \n", argv[0] );
      exit(-1);
  }
  fp = fopen(argv[1], "r");
  if (fp == NULL) 
  {
    fprintf(stderr, "Can't open file %s!\n", argv[1]);
    printf( "Usage: %s filename.extension or Check whether file is present or not\n", argv[0] );
    exit(-1);
  } 
  triangle_count = 0;
  while (fscanf(fp, "%c %c%d%c%d%c %c%d%c%d%c %c%d%c%d%c%c", &a,&a,&x_1,&a,&y_1,&a,&a,&x_2,&a,&y_2,&a,&a,&x_3,&a,&y_3,&a,&a) != EOF) 
  {
    if(get_x_min(x_1,x_2,x_3) >= 0 && get_y_min(y_1,y_2,y_3) >= 0 && get_x_max(x_1,x_2,x_3) <= display_width - 300 && get_y_max(y_1,y_2,y_3) <= display_height - 200)
    {
      t[triangle_count].x1 = x_1;
      t[triangle_count].x2 = x_2;
      t[triangle_count].x3 = x_3;
      t[triangle_count].y1 = y_1;
      t[triangle_count].y2 = y_2;
      t[triangle_count].y3 = y_3;
      triangle_count++;
    }   
  }
  
  x_min = t[0].x1;
  x_max = x_min;
  y_min = t[0].y1;
  y_max = y_min;
  for(i=0;i<triangle_count;i++)
  {
    if(x_min > t[i].x1)
      x_min = t[i].x1;
    if(x_min > t[i].x2)
      x_min = t[i].x2;
    if(x_min > t[i].x2)
      x_min = t[i].x3;
    if(y_min > t[i].y1)
      y_min = t[i].y1;
    if(y_min > t[i].y2)
      y_min = t[i].y2;
    if(y_min > t[i].y3)
      y_min = t[i].y3;
    if(x_max < t[i].x1)
      x_max = t[i].x1;
    if(x_max < t[i].x2)
      x_max = t[i].x2;
    if(x_max < t[i].x3)
      x_max = t[i].x3;
    if(y_max < t[i].y1)
      y_max = t[i].y1;
    if(y_max < t[i].y2)
      y_max = t[i].y2;
    if(y_max < t[i].y3)
      y_max = t[i].y3;        
  }
   
  x_center = win_width / 2;
  y_center = win_height / 2;
  x_gap = x_max - x_min;
  y_gap = y_max - y_min;
  x_start = x_center - x_gap/2 - 50;
  y_start = y_center - y_gap/2 - 50;
  x_end = x_start + x_gap + 100;
  y_end = y_start + y_gap + 100;
  rec_width = x_end - x_start;
  rec_height = y_end - y_start;

  for(i=0;i<triangle_count;i++)
  {
    t[i].x1 = t[i].x1 + x_start + 50 - x_min;
    t[i].x2 = t[i].x2 + x_start + 50 - x_min;
    t[i].x3 = t[i].x3 + x_start + 50 - x_min;
    t[i].y1 = t[i].y1 + y_start + 50 - y_min;
    t[i].y2 = t[i].y2 + y_start + 50 - y_min;
    t[i].y3 = t[i].y3 + y_start + 50 - y_min;
  }
  for(i=0;i<triangle_count;i++)
  {
    t[i].point_1_inside_triangle = 0;
    t[i].point_2_inside_triangle = 0;
    t[i].point_3_inside_triangle = 0;       
  }
  for(i=0;i<triangle_count;i++)
  {
    for(j=0;j<triangle_count;j++)
    {
      if(j!=i)
      {
        if(point_in_triangle(t[i].x1,t[i].y1,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1)
        {
          t[i].point_1_inside_triangle = 1;
        }
        if(point_in_triangle(t[i].x2,t[i].y2,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1)
        {
          t[i].point_2_inside_triangle = 1;
        }
        if(point_in_triangle(t[i].x3,t[i].y3,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1)
        {
          t[i].point_3_inside_triangle = 1;
        }
      }
    }
  }
  
  while(1)
  { 
    XNextEvent( display_ptr, &report );
    switch( report.type )
	  {
	    case Expose:
	      for(i=0;i<triangle_count;i++)
        {
          XDrawLine(display_ptr, win, gc_black, t[i].x1, t[i].y1, t[i].x2, t[i].y2);
          XDrawLine(display_ptr, win, gc_black, t[i].x2, t[i].y2, t[i].x3, t[i].y3);
          XDrawLine(display_ptr, win, gc_black, t[i].x3, t[i].y3, t[i].x1, t[i].y1);
        }
        XDrawRectangle(display_ptr, win, gc_black, x_start, y_start, rec_width, rec_height ); 
        break;
        
      case ConfigureNotify:
          win_width = report.xconfigure.width;
          win_height = report.xconfigure.height;
          break;
        
      case ButtonPress:
      {  
        int x, y;
  	    x = report.xbutton.x;
        y = report.xbutton.y;
        if (report.xbutton.button == Button1 )
	      {
          outside = 0;
          if(x <= x_start || y <= y_start || x >= x_end || y >= y_end)
          {
            outside = 1;
          } 
          for(i=0;i<triangle_count;i++)
          {
            if(point_in_triangle(x,y,t[i].x1,t[i].y1,t[i].x2,t[i].y2,t[i].x3,t[i].y3)==1)
            {
              outside = 1;
              break;
            }
          }
          if(outside == 0)
          {
            ButtonPressed++;
            if(ButtonPressed == 1)
            { 
              temp_x = x;
              temp_y = y;
              pixel_count = 0;
              XFillArc( display_ptr, win, gc_red, x - win_height/150, y - win_height/150, win_height/100, win_height/100, 0, 360*64);
              pixel[pixel_count].name = pixel_count;
              pixel[pixel_count].x = x; 
              pixel[pixel_count].y = y;
              pixel_count++;
            }
            else if(ButtonPressed == 2)
            { 
              if(temp_x == x && temp_y == y)
              {
                ButtonPressed = 1;
                break;
              }
              XFillArc( display_ptr, win, gc_red, x - win_height/150, y - win_height/150, win_height/100, win_height/100, 0, 360*64);
              for(i=0;i<triangle_count;i++)
              {
                if(t[i].point_1_inside_triangle != 1)
                {
                  pixel[pixel_count].name = pixel_count;
                  pixel[pixel_count].x = t[i].x1; 
                  pixel[pixel_count].y = t[i].y1;
                  pixel_count++;
                }
                if(t[i].point_2_inside_triangle != 1)
                {
                  pixel[pixel_count].name = pixel_count;
                  pixel[pixel_count].x = t[i].x2; 
                  pixel[pixel_count].y = t[i].y2;
                  pixel_count++;
                }
                if(t[i].point_3_inside_triangle != 1)
                {
                  pixel[pixel_count].name = pixel_count;
                  pixel[pixel_count].x = t[i].x3; 
                  pixel[pixel_count].y = t[i].y3;
                  pixel_count++;
                }
              }
              pixel[pixel_count].name = pixel_count;
              pixel[pixel_count].x = x; 
              pixel[pixel_count].y = y;
              pixel_count++;
              for(i=0;i<pixel_count-1;i++)
              {         
                for(j=i+1;j<pixel_count;j++)
                {
                  if(can_see(pixel[i].x,pixel[i].y,pixel[j].x,pixel[j].y)==1)
                  {
                    cost[pixel[i].name][pixel[j].name] = cost[pixel[j].name][pixel[i].name] = eculidian_dist(pixel[i].x,pixel[i].y,pixel[j].x,pixel[j].y);
                  }
                }
              }
              dijsktra(pixel[0].name, pixel[pixel_count-1].name);
            }
            else
            {
              clear_cost();
              expose();
              ButtonPressed = 0;          
            }
          }
        }
        else
        {
          XFlush(display_ptr);
          XCloseDisplay(display_ptr);
          exit(0);
        }
      }
      break;
      default:
        break;
    }
  }
  exit(0);
}
Example #23
0
GFX_PlatformWindow _gfx_platform_window_create(

		const GFX_PlatformAttributes* attributes)
{
	/* Setup the x11 window */
	GFX_X11_Window window;
	window.monitor = attributes->monitor;
	window.context = NULL;
	window.flags   = 0;

	window.flags |=
		attributes->flags & GFX_WINDOW_RESIZABLE ?
		GFX_X11_RESIZABLE : 0;
	window.flags |=
		attributes->flags & GFX_WINDOW_HIDDEN ?
		GFX_X11_HIDDEN : 0;

	/* Get display mode & position */
	GFXDisplayMode mode;
	int x = window.monitor->x;
	int y = window.monitor->y;

	if(attributes->flags & GFX_WINDOW_FULLSCREEN)
	{
		window.flags |= GFX_X11_FULLSCREEN;

		GFX_X11_Mode* it = gfx_vector_at(
			&_gfx_x11.modes,
			window.monitor->modes[attributes->mode]
		);

		window.mode = it->id;
		mode = it->mode;
	}
	else
	{
		mode.width  = attributes->w;
		mode.height = attributes->h;
		mode.depth  = *attributes->depth;

		x += attributes->x;
		y += attributes->y;
	}

	/* Get FB Config */
	GLXFBConfig* config = _gfx_x11_get_config(
		window.monitor->screen,
		&mode.depth,
		attributes->flags & GFX_WINDOW_DOUBLE_BUFFER
	);

	if(!config) return NULL;

	/* Get visual from config */
	XVisualInfo* visual = glXGetVisualFromFBConfig(
		_gfx_x11.display,
		*config
	);

	window.config = *config;
	XFree(config);

	/* Create the window attributes */
	unsigned long mask = CWColormap | CWEventMask;
	XSetWindowAttributes attr;

	if(
		attributes->flags & GFX_WINDOW_BORDERLESS ||
		attributes->flags & GFX_WINDOW_FULLSCREEN)
	{
		/* Borderless window */
		mask |= CWBorderPixel;
		attr.border_pixel = 0;
	}

	/* Event mask & Color map */
	Window root =
		XRootWindowOfScreen(window.monitor->screen);

	attr.event_mask =
		KeyPressMask |
		KeyReleaseMask |
		PointerMotionMask |
		EnterWindowMask |
		LeaveWindowMask |
		ButtonPressMask |
		ButtonReleaseMask |
		StructureNotifyMask |
		FocusChangeMask;

	attr.colormap = XCreateColormap(
		_gfx_x11.display,
		root,
		visual->visual,
		AllocNone
	);

	/* Create the actual window */
	window.handle = XCreateWindow(
		_gfx_x11.display,
		root,
		x,
		y,
		mode.width,
		mode.height,
		0,
		visual->depth,
		InputOutput,
		visual->visual,
		mask,
		&attr
	);

	XFree(visual);

	if(window.handle)
	{
		/* Get properties to check for events */
		XWindowAttributes get;
		get.x      = 0;
		get.y      = 0;
		get.width  = 0;
		get.height = 0;
		XGetWindowAttributes(_gfx_x11.display, window.handle, &get);

		window.x      = get.x;
		window.y      = get.y;
		window.width  = get.width;
		window.height = get.height;

		/* Delete protocol & name */
		XSetWMProtocols(
			_gfx_x11.display,
			window.handle,
			&_gfx_x11.WM_DELETE_WINDOW,
			1);

		XStoreName(
			_gfx_x11.display,
			window.handle,
			attributes->name);

		/* Disable decorations */
		if(mask & CWBorderPixel)
		{
			unsigned long hints[5];
			hints[0] = MWM_HINTS_DECORATIONS;
			hints[2] = 0;

			XChangeProperty(
				_gfx_x11.display,
				window.handle,
				_gfx_x11.MOTIF_WM_HINTS,
				_gfx_x11.MOTIF_WM_HINTS,
				32,
				PropModeReplace,
				(unsigned char*)hints,
				5);
		}

		/* Bypass compositor */
		if(attributes->flags & GFX_WINDOW_FULLSCREEN)
		{
			unsigned long bypass = 1;

			XChangeProperty(
				_gfx_x11.display,
				window.handle,
				_gfx_x11.NET_WM_BYPASS_COMPOSITOR,
				XA_CARDINAL,
				32,
				PropModeReplace,
				(unsigned char*)&bypass,
				1
			);
		}

		/* Set size hints */
		if(!(attributes->flags & GFX_WINDOW_RESIZABLE))
		{
			XSizeHints* hints = XAllocSizeHints();
			hints->flags = PMinSize | PMaxSize;

			hints->min_width = mode.width;
			hints->max_width = mode.width;
			hints->min_height = mode.height;
			hints->max_height = mode.height;

			XSetWMNormalHints(_gfx_x11.display, window.handle, hints);

			XFree(hints);
		}

		/* Add window to vector */
		GFXVectorIterator it = gfx_vector_insert(
			&_gfx_x11.windows,
			&window,
			_gfx_x11.windows.end
		);

		if(it != _gfx_x11.windows.end)
		{
			/* Make it visible */
			/* Triggers FocusIn event for fullscreen */
			if(!(attributes->flags & GFX_WINDOW_HIDDEN))
				XMapWindow(_gfx_x11.display, window.handle);

			return GFX_UINT_TO_VOID(window.handle);
		}

		XDestroyWindow(_gfx_x11.display, window.handle);
	}

	XFreeColormap(_gfx_x11.display, attr.colormap);

	return NULL;
}
Example #24
0
int
ui_init( int *argc, char ***argv )
{
  char *displayName=NULL;	/* Use default display */
  XWMHints *wmHints;
  XSizeHints *sizeHints;
  XClassHint *classHint;
  char *windowNameList=(char *)"Fuse",*iconNameList=(char *)"Fuse";
  XTextProperty windowName, iconName;
  unsigned long windowFlags;
  XSetWindowAttributes windowAttributes;

  /* Allocate memory for various things */

  if( ui_widget_init() ) return 1;

  if(!(wmHints = XAllocWMHints())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(!(sizeHints = XAllocSizeHints())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(!(classHint = XAllocClassHint())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(XStringListToTextProperty(&windowNameList,1,&windowName) == 0 ) {
    fprintf(stderr,"%s: structure allocation for windowName failed\n",
	    fuse_progname);
    return 1;
  }

  if(XStringListToTextProperty(&iconNameList,1,&iconName) == 0 ) {
    fprintf(stderr,"%s: structure allocation for iconName failed\n",
	    fuse_progname);
    return 1;
  }

  /* Open a connection to the X server */

  if ( ( display=XOpenDisplay(displayName)) == NULL ) {
    fprintf(stderr,"%s: cannot connect to X server %s\n", fuse_progname,
	    XDisplayName(displayName));
    return 1;
  }

  /* Set up our error handler */
  xerror_expecting = xerror_error = 0;
  XSetErrorHandler( xerror_handler );

  xui_screenNum = DefaultScreen(display);

  /* Create the main window */

  xui_mainWindow = XCreateSimpleWindow(
    display, RootWindow( display, xui_screenNum ), 0, 0,
    DISPLAY_ASPECT_WIDTH, DISPLAY_SCREEN_HEIGHT, 0,
    BlackPixel( display, xui_screenNum ), WhitePixel( display, xui_screenNum )
  );

  /* Set standard window properties */

  sizeHints->flags = PBaseSize | PResizeInc | PMaxSize | PMinSize;

  sizeHints->base_width = 0;
  sizeHints->base_height = 0;

  sizeHints->min_width    =     DISPLAY_ASPECT_WIDTH;
  sizeHints->min_height   =     DISPLAY_SCREEN_HEIGHT;
  sizeHints->width_inc    =     DISPLAY_ASPECT_WIDTH;
  sizeHints->height_inc   =     DISPLAY_SCREEN_HEIGHT;
  sizeHints->max_width    = 3 * DISPLAY_ASPECT_WIDTH;
  sizeHints->max_height   = 3 * DISPLAY_SCREEN_HEIGHT;

  if( settings_current.aspect_hint ) {
    sizeHints->flags |= PAspect;
    sizeHints->min_aspect.x = 4;
    sizeHints->min_aspect.y = 3;
    sizeHints->max_aspect.x = 4;
    sizeHints->max_aspect.y = 3;
  }

  wmHints->flags=StateHint | InputHint;
  wmHints->initial_state=NormalState;
  wmHints->input=True;

  classHint->res_name=(char *)fuse_progname;
  classHint->res_class=(char *)"Fuse";

  XSetWMProperties(display, xui_mainWindow, &windowName, &iconName,
		   *argv, *argc, sizeHints, wmHints, classHint);

  XFree( windowName.value );
  XFree( iconName.value );
  XFree( sizeHints );
  XFree( wmHints );
  XFree( classHint );

  /* Ask the server to use its backing store for this window */

  windowFlags=CWBackingStore;
  windowAttributes.backing_store=WhenMapped;

  XChangeWindowAttributes(display, xui_mainWindow, windowFlags,
			  &windowAttributes);

  /* Select which types of event we want to receive */

  XSelectInput(display, xui_mainWindow, ExposureMask | KeyPressMask |
	       KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
	       StructureNotifyMask | FocusChangeMask | PointerMotionMask );

  {
    static XColor dummy = { 0, 0, 0, 0, 4, 0 };
    XGCValues xgc;
    GC gc;

    Pixmap mask =
      XCreatePixmap( display, RootWindow( display, xui_screenNum ), 1, 1, 1 );

    xgc.function = GXclear;
    gc = XCreateGC( display, mask, GCFunction, &xgc );
    XFillRectangle( display, mask, gc, 0, 0, 1, 1 );
    nullpointer = XCreatePixmapCursor( display, mask,mask, &dummy,&dummy, 0,0 );
    XFreePixmap( display, mask );
    XFreeGC( display, gc );
  }

  /* Ask to be notified of window close requests */

  delete_window_atom = XInternAtom( display, "WM_DELETE_WINDOW", 0 );
  XSetWMProtocols( display, xui_mainWindow, &delete_window_atom, 1 );

  if( xdisplay_init() ) return 1;

  /* And finally display the window */
  XMapWindow(display,xui_mainWindow);

  ui_mouse_present = 1;

  return 0;
}
Example #25
0
	void X11EGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )
	{
		mEglDisplay = mGLSupport->getGLDisplay();//todo
		XSetWindowAttributes attr;
		ulong mask;
		XVisualInfo *visualInfo = mGLSupport->getVisualFromFBConfig(mEglConfig);

		attr.background_pixel = 0;
		attr.border_pixel = 0;
		attr.colormap = XCreateColormap((Display*)mNativeDisplay,
			DefaultRootWindow((Display*)mNativeDisplay),
			visualInfo->visual,
			AllocNone);
		attr.event_mask = StructureNotifyMask | VisibilityChangeMask | FocusChangeMask;
		mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

		if(mIsFullScreen && mGLSupport->mAtomFullScreen == None) 
		{
			LogManager::getSingleton().logMessage("EGLWindow::switchFullScreen: Your WM has no fullscreen support");

			// A second best approach for outdated window managers
			attr.backing_store = NotUseful;
			attr.save_under = False;
			attr.override_redirect = True;
			mask |= CWSaveUnder | CWBackingStore | CWOverrideRedirect;
			left = top = 0;
		}

		// Create window on server
		mWindow = (NativeWindowType)XCreateWindow((Display*)mNativeDisplay,
			mParentWindow,
			left, top, width, height,
			0, visualInfo->depth,
			InputOutput,
			visualInfo->visual, mask, &attr);
		XFree(visualInfo);

		if(!mWindow)
		{
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
				"Unable to create an X NativeWindowType",
				"EGLWindow::create");
		}

		if (mIsTopLevel)
		{
			XWMHints *wmHints;
			XSizeHints *sizeHints;

			// Is this really necessary ? Which broken WM might need it?
			if ((wmHints = XAllocWMHints()) != NULL)
			{
				wmHints->initial_state = NormalState;
				wmHints->input = True;
				wmHints->flags = StateHint | InputHint;
			}

			// Is this really necessary ? Which broken WM might need it?
			if ((sizeHints = XAllocSizeHints()) != NULL)
			{
				sizeHints->flags = USPosition;
			}

			XTextProperty titleprop;
			char *lst = (char*)title.c_str();
			XStringListToTextProperty((char **)&lst, 1, &titleprop);
			XSetWMProperties((Display*)mNativeDisplay, (Window)mWindow, &titleprop,
				NULL, NULL, 0, sizeHints, wmHints, NULL);

			XFree(titleprop.value);
			XFree(wmHints);
			XFree(sizeHints);

			XSetWMProtocols((Display*)mNativeDisplay, (Window)mWindow, &mGLSupport->mAtomDeleteWindow, 1);

			XWindowAttributes windowAttrib;

			XGetWindowAttributes((Display*)mNativeDisplay, (Window)mWindow, &windowAttrib);

			left = windowAttrib.x;
			top = windowAttrib.y;
			width = windowAttrib.width;
			height = windowAttrib.height;
		}

		mEglSurface = createSurfaceFromWindow(mGLSupport->getGLDisplay(), mWindow);

		XMapWindow((Display*)mNativeDisplay, (Window)mWindow);

		if (mIsFullScreen)
		{
			switchFullScreen(true);
		}

		XFlush((Display*)mNativeDisplay);

		WindowEventUtilities::_addRenderWindow(this);
	}
Example #26
0
void init_x(void)
{
   XGCValues xgcv;
   XFontStruct *fontinfo;
   int i;

   dpy=XOpenDisplay(NULL);
   if (dpy==NULL) {
      fprintf(stderr,"Could not open display; is the DISPLAY variable set correctly?\n");
      exit(1);
   }
   scr=DefaultScreen(dpy);

   width=900; height=600;
   ScreenWidth=width;
   ScreenHeight=height;
   vp.x2=width-1;
   vp.y2=height-1;

   // create our window
   w=XCreateWindow(dpy,RootWindow(dpy,scr),-1,-1, width, height, 0, CopyFromParent, InputOutput, CopyFromParent, 0, NULL);
   XMapWindow(dpy,w);
   XStoreName(dpy,w,"puff");

   // create a background pixmap, that we're actually going to use for everything, because then the xserver takes care of redrawing the window when it is uncovered
   XGetWindowAttributes(dpy,w,&wa);
   pm=XCreatePixmap(dpy, RootWindow(dpy,scr),wa.width,wa.height,wa.depth);
   XSetWindowBackgroundPixmap(dpy,w,pm);

   // tell the window manager that we don't want to be resized to less than 640x480 (the old VGA resolution)
   XSizeHints* win_size_hints = XAllocSizeHints();
   win_size_hints->flags = PMinSize;
   win_size_hints->min_width = 640;
   win_size_hints->min_height = 480;
   XSetWMNormalHints(dpy, w, win_size_hints);
   XFree(win_size_hints);

   // allocate 16 memory places to temporarily store pieces of the drawing
   for (i=0;i<16;i++) boxes[i]=XCreatePixmap(dpy, RootWindow(dpy,scr),32,32,wa.depth);

   // create several graphics contexts
   xgcv.foreground=WhitePixel(dpy,scr);
   xgcv.background=BlackPixel(dpy,scr);
   xgcv.function=GXcopy;
   gc = XCreateGC(dpy, w, GCForeground|GCBackground|GCFunction, &xgcv);
   XSetLineAttributes(dpy, gc, 1, LineSolid, CapRound, JoinRound);

   xgcv.foreground=BlackPixel(dpy,scr);
   xgcv.background=WhitePixel(dpy,scr);
   xgcv.function=GXcopy;
   gcclear = XCreateGC(dpy, w, GCForeground|GCBackground|GCFunction, &xgcv);

   gcpixel = XCreateGC(dpy, w, 0, &xgcv);

   xgcv.foreground=WhitePixel(dpy,scr);
   xgcv.background=BlackPixel(dpy,scr);
   xgcv.function=GXcopy;
   gctext = XCreateGC(dpy, w, GCForeground|GCBackground|GCFunction, &xgcv);

   xgcv.background=WhitePixel(dpy,scr);
   xgcv.foreground=BlackPixel(dpy,scr);
   xgcv.function=GXcopy;
   gcfill = XCreateGC(dpy, w, GCForeground|GCBackground|GCFunction, &xgcv);
   XSetLineAttributes(dpy, gcfill, 1000, LineSolid, CapRound, JoinRound);    // very thick line, see FloodFill() for explanation

   // clear the screen
   XFillRectangle(dpy, pm, gcfill, 0,0,ScreenWidth,ScreenHeight);
   XClearWindow(dpy,w);

   // load an 8x13 font; the VGA font on which the partitioning of the screen is based is an 8x14 font
   fontinfo=XLoadQueryFont(dpy,"8x13");
   XSetFont(dpy,gctext,fontinfo->fid);
   XSetFont(dpy,gc,fontinfo->fid);
   fontyoffs=fontinfo->ascent;

   // allocate a set of colours corresponding to those of the VGA mode originally used by puff
   getpascalcolours();

   XSelectInput(dpy,w,KeyPressMask|KeyReleaseMask|StructureNotifyMask);

   XFlush(dpy);
}
	//-------------------------------------------------------------------------------------------------//
	void GLXWindow::create(const String& name, uint width, uint height,
			   bool fullScreen, const NameValuePairList *miscParams)
	{
		Display *xDisplay = mGLSupport->getXDisplay();
		String title = name;
		uint samples = 0;
		short frequency = 0;
		bool vsync = false;
		bool hidden = false;
		unsigned int vsyncInterval = 1;
		int gamma = 0;
		::GLXContext glxContext = 0;
		::GLXDrawable glxDrawable = 0;
		Window externalWindow = 0;
		Window parentWindow = DefaultRootWindow(xDisplay);
		int left = DisplayWidth(xDisplay, DefaultScreen(xDisplay))/2 - width/2;
		int top  = DisplayHeight(xDisplay, DefaultScreen(xDisplay))/2 - height/2;
		
		mIsFullScreen = fullScreen;
		
		if(miscParams)
		{
			NameValuePairList::const_iterator opt;
			NameValuePairList::const_iterator end = miscParams->end();
			
			// NB: Do not try to implement the externalGLContext option.
			//
			//	 Accepting a non-current context would expose us to the 
			//	 risk of segfaults when we made it current. Since the
			//	 application programmers would be responsible for these
			//	 segfaults, they are better discovering them in their code.
		
			if ((opt = miscParams->find("currentGLContext")) != end &&
				StringConverter::parseBool(opt->second))
			{
				if (! glXGetCurrentContext())
				{
					OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "GLXWindow::create");
				}
				
				glxContext = glXGetCurrentContext();
				glxDrawable = glXGetCurrentDrawable();
			}
			
			// Note: Some platforms support AA inside ordinary windows
			if((opt = miscParams->find("FSAA")) != end) 
				samples = StringConverter::parseUnsignedInt(opt->second);
			
			if((opt = miscParams->find("displayFrequency")) != end) 
				frequency = (short)StringConverter::parseInt(opt->second);
			
			if((opt = miscParams->find("vsync")) != end) 
				vsync = StringConverter::parseBool(opt->second);

			if((opt = miscParams->find("hidden")) != end)
				hidden = StringConverter::parseBool(opt->second);

			if((opt = miscParams->find("vsyncInterval")) != end) 
				vsyncInterval = StringConverter::parseUnsignedInt(opt->second);

			if ((opt = miscParams->find("gamma")) != end)
				gamma = StringConverter::parseBool(opt->second);

			if((opt = miscParams->find("left")) != end) 
				left = StringConverter::parseInt(opt->second);
			
			if((opt = miscParams->find("top")) != end) 
				top = StringConverter::parseInt(opt->second);
			
			if((opt = miscParams->find("title")) != end) 
				title = opt->second;
			
			if ((opt = miscParams->find("externalGLControl")) != end)
				mIsExternalGLControl = StringConverter::parseBool(opt->second);
			
			if((opt = miscParams->find("parentWindowHandle")) != end) 
			{
				vector<String>::type tokens = StringUtil::split(opt->second, " :");
				
				if (tokens.size() == 3)
				{
					// deprecated display:screen:xid format
					parentWindow = StringConverter::parseUnsignedLong(tokens[2]);
				}
				else
				{
					// xid format
					parentWindow = StringConverter::parseUnsignedLong(tokens[0]);
				}
			}
			else if((opt = miscParams->find("externalWindowHandle")) != end) 
			{
				vector<String>::type tokens = StringUtil::split(opt->second, " :");
				
				LogManager::getSingleton().logMessage(
													  "GLXWindow::create: The externalWindowHandle parameter is deprecated.\n"
													  "Use the parentWindowHandle or currentGLContext parameter instead.");
				
				if (tokens.size() == 3)
				{
					// Old display:screen:xid format
					// The old GLX code always created a "parent" window in this case:
					parentWindow = StringConverter::parseUnsignedLong(tokens[2]);
				}
				else if (tokens.size() == 4)
				{
					// Old display:screen:xid:visualinfo format
					externalWindow = StringConverter::parseUnsignedLong(tokens[2]);
				}
				else
				{
					// xid format
					externalWindow = StringConverter::parseUnsignedLong(tokens[0]);
				}
			}
		}
		
		// Ignore fatal XErrorEvents during parameter validation:
		oldXErrorHandler = XSetErrorHandler(safeXErrorHandler);
		// Validate parentWindowHandle
		
		if (parentWindow != DefaultRootWindow(xDisplay))
		{
			XWindowAttributes windowAttrib;
			
			if (! XGetWindowAttributes(xDisplay, parentWindow, &windowAttrib) ||
				windowAttrib.root != DefaultRootWindow(xDisplay))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid parentWindowHandle (wrong server or screen)", "GLXWindow::create");
			}
		}
		
		// Validate externalWindowHandle
		
		if (externalWindow != 0)
		{
			XWindowAttributes windowAttrib;
			
			if (! XGetWindowAttributes(xDisplay, externalWindow, &windowAttrib) ||
				windowAttrib.root != DefaultRootWindow(xDisplay))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid externalWindowHandle (wrong server or screen)", "GLXWindow::create");
			}
			glxDrawable = externalWindow;
		}

		// Derive fbConfig
		
		::GLXFBConfig fbConfig = 0;
		
		if (glxDrawable)
		{
			fbConfig = mGLSupport->getFBConfigFromDrawable (glxDrawable, &width, &height);
		}

		if (! fbConfig && glxContext)
		{
			fbConfig = mGLSupport->getFBConfigFromContext (glxContext);
		}
			
		mIsExternal = (glxDrawable != 0);
		
		XSetErrorHandler(oldXErrorHandler);
		
		if (! fbConfig)
		{
			int minAttribs[] = {
				GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT,
				GLX_RENDER_TYPE,	GLX_RGBA_BIT,
				GLX_RED_SIZE,	   1,
				GLX_BLUE_SIZE,	  1,
				GLX_GREEN_SIZE,	 1,
				None
			};
			
			int maxAttribs[] = {
				GLX_SAMPLES,		samples,
				GLX_DOUBLEBUFFER,   1,
				GLX_STENCIL_SIZE,   INT_MAX,
				GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, 1,
				None
			};

			fbConfig = mGLSupport->selectFBConfig(minAttribs, maxAttribs);

			if (gamma != 0)
			{
				mGLSupport->getFBConfigAttrib(fbConfig, GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &gamma);
			}

			mHwGamma = (gamma != 0);
		}
		
    if (! fbConfig)
    {
      // This should never happen.
      OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a GLXFBConfig","GLXWindow::create");
    }
		
		mIsTopLevel = (! mIsExternal && parentWindow == DefaultRootWindow(xDisplay));
		
		if (! mIsTopLevel)
		{
			mIsFullScreen = false;
			left = top = 0;
		}
		
		if (mIsFullScreen) 
		{
			mGLSupport->switchMode (width, height, frequency);
		}
		
		if (! mIsExternal)
		{
			XSetWindowAttributes attr;
			ulong mask;
			XVisualInfo *visualInfo = mGLSupport->getVisualFromFBConfig (fbConfig);
			
			attr.background_pixel = 0;
			attr.border_pixel = 0;
			attr.colormap = XCreateColormap(xDisplay, DefaultRootWindow(xDisplay), visualInfo->visual, AllocNone);
			attr.event_mask = StructureNotifyMask | VisibilityChangeMask | FocusChangeMask;
			mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
			
			if(mIsFullScreen && mGLSupport->mAtomFullScreen == None) 
			{
				LogManager::getSingleton().logMessage("GLXWindow::switchFullScreen: Your WM has no fullscreen support");
				
				// A second best approach for outdated window managers
				attr.backing_store = NotUseful;
				attr.save_under = False;
				attr.override_redirect = True;
				mask |= CWSaveUnder | CWBackingStore | CWOverrideRedirect;
				left = top = 0;
			} 
			
			// Create window on server
			mWindow = XCreateWindow(xDisplay, parentWindow, left, top, width, height, 0, visualInfo->depth, InputOutput, visualInfo->visual, mask, &attr);
			
			XFree(visualInfo);
			
			if(!mWindow) 
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to create an X Window", "GLXWindow::create");
			}
			
			if (mIsTopLevel)
			{
				XWMHints *wmHints;
				XSizeHints *sizeHints;
				
				if ((wmHints = XAllocWMHints()) != NULL) 
				{
					wmHints->initial_state = NormalState;
					wmHints->input = True;
					wmHints->flags = StateHint | InputHint;
					
					int depth = DisplayPlanes(xDisplay, DefaultScreen(xDisplay));
					
					// Check if we can give it an icon
					if(depth == 24 || depth == 32) 
					{
						if(mGLSupport->loadIcon("GLX_icon.png", &wmHints->icon_pixmap, &wmHints->icon_mask))
						{
							wmHints->flags |= IconPixmapHint | IconMaskHint;
						}
					}
				}
				
				// Is this really necessary ? Which broken WM might need it?
				if ((sizeHints = XAllocSizeHints()) != NULL)
				{
					sizeHints->flags = USPosition;
				}
				
				XTextProperty titleprop;
				char *lst = (char*)title.c_str();
				XStringListToTextProperty((char **)&lst, 1, &titleprop);
				XSetWMProperties(xDisplay, mWindow, &titleprop, NULL, NULL, 0, sizeHints, wmHints, NULL);
				
				XFree(titleprop.value);
				XFree(wmHints);
				XFree(sizeHints);
				
				XSetWMProtocols(xDisplay, mWindow, &mGLSupport->mAtomDeleteWindow, 1);
				
				XWindowAttributes windowAttrib;
				
				XGetWindowAttributes(xDisplay, mWindow, &windowAttrib);
				
				left = windowAttrib.x;
				top = windowAttrib.y;
				width = windowAttrib.width;
				height = windowAttrib.height;
			}
			
			glxDrawable = mWindow;
			
			// setHidden takes care of mapping or unmapping the window
			// and also calls setFullScreen if appropriate.
			setHidden(hidden);
			XFlush(xDisplay);
			
			WindowEventUtilities::_addRenderWindow(this);
		}
		
		mContext = new GLXContext(mGLSupport, fbConfig, glxDrawable, glxContext);
		
		// apply vsync settings. call setVSyncInterval first to avoid 
		// setting vsync more than once.
		setVSyncInterval(vsyncInterval);
		setVSyncEnabled(vsync);
		
		int fbConfigID;
		
		mGLSupport->getFBConfigAttrib(fbConfig, GLX_FBCONFIG_ID, &fbConfigID);
		
		LogManager::getSingleton().logMessage("GLXWindow::create used FBConfigID = " + StringConverter::toString(fbConfigID));
		
		mName = name;
		mWidth = width;
		mHeight = height;
		mLeft = left;
		mTop = top;
		mActive = true;
		mClosed = false;
	}
Example #28
0
void TestMap()
{

   XSizeHints *hints;
   XWindowAttributes attr;
   Window w;

   /* Create the window. */
   w = XCreateSimpleWindow(display, rootWindow, 100, 100, 200, 100, 0, 0, 0);
   XSelectInput(display, w, StructureNotifyMask | PropertyNotify);

   /* Map the window and wait for it. */
   XMapWindow(display, w);
   Assert(AwaitEvent(MapNotify));

   /* Unmap the window and wait for it. */
   XUnmapWindow(display, w);
   Assert(AwaitEvent(UnmapNotify));

   /* Map the window and wait for it (again). */
   XMapWindow(display, w);
   Assert(AwaitEvent(MapNotify));

   /* Minimize and wait. */
   Minimize(w);
   Assert(AwaitEvent(UnmapNotify));

   /* Restore and wait. */
   Unminimize(w);
   Assert(AwaitEvent(MapNotify));

   /* Maximize and wait. */
   Maximize(w, 1, 1);
   Assert(AwaitEvent(ConfigureNotify));

   /* Unmaximize and wait. */
   Unmaximize(w, 0, 1);
   Assert(AwaitEvent(ConfigureNotify));

   /* Unmaximize and wait. */
   Unmaximize(w, 1, 0);
   Assert(AwaitEvent(ConfigureNotify));

   /* Change the size hints. */
   hints = XAllocSizeHints();
   hints->flags = PMinSize;
   hints->min_width = 300;
   hints->min_height = 200;
   XSetWMNormalHints(display, w, hints);
   XFree(hints);
   XSync(display, False);
   sleep(1);
   IgnoreEvents();
   XGetWindowAttributes(display, w, &attr);
   Assert(attr.width == 300);
   Assert(attr.height == 200);

   /* Shade and wait. */
   Shade(w);
   Assert(AwaitEvent(UnmapNotify));

   /* Maximize and wait. */
   Maximize(w, 0, 1);
   Assert(AwaitEvent(MapNotify));

   /* Shade and wait. */
   Shade(w);
   Assert(AwaitEvent(UnmapNotify));

   /* Unshade and wait. */
   Unshade(w);
   Assert(AwaitEvent(MapNotify));

   /* Destroy the window. */
   XDestroyWindow(display, w);

}
Example #29
0
static GLboolean createWindow(_GLFWwindow* window,
                              const _GLFWwndconfig* wndconfig)
{
    unsigned long wamask;
    XSetWindowAttributes wa;
    XVisualInfo* visual = _glfwGetContextVisual(window);

    // Every window needs a colormap
    // Create one based on the visual used by the current context

    window->X11.colormap = XCreateColormap(_glfwLibrary.X11.display,
                                           _glfwLibrary.X11.root,
                                           visual->visual,
                                           AllocNone);

    // Create the actual window
    {
        wamask = CWBorderPixel | CWColormap | CWEventMask;

        wa.colormap = window->X11.colormap;
        wa.border_pixel = 0;
        wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
            PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
            ExposureMask | FocusChangeMask | VisibilityChangeMask |
            EnterWindowMask | LeaveWindowMask;

        if (wndconfig->mode == GLFW_WINDOWED)
        {
            // The /only/ reason we are setting the background pixel here is
            // that otherwise our window wont get any decorations on systems
            // using Compiz on Intel hardware
            wa.background_pixel = BlackPixel(_glfwLibrary.X11.display,
                                             _glfwLibrary.X11.screen);
            wamask |= CWBackPixel;
        }

        window->X11.handle = XCreateWindow(
            _glfwLibrary.X11.display,
            _glfwLibrary.X11.root,
            0, 0,                            // Upper left corner of this window on root
            window->width, window->height,
            0,                               // Border width
            visual->depth,                   // Color depth
            InputOutput,
            visual->visual,
            wamask,
            &wa
        );

        if (!window->X11.handle)
        {
            // TODO: Handle all the various error codes here

            _glfwSetError(GLFW_PLATFORM_ERROR,
                          "X11/GLX: Failed to create window");
            return GL_FALSE;
        }
    }

    if (window->mode == GLFW_FULLSCREEN && !_glfwLibrary.X11.hasEWMH)
    {
        // This is the butcher's way of removing window decorations
        // Setting the override-redirect attribute on a window makes the window
        // manager ignore the window completely (ICCCM, section 4)
        // The good thing is that this makes undecorated fullscreen windows
        // easy to do; the bad thing is that we have to do everything manually
        // and some things (like iconify/restore) won't work at all, as they're
        // usually performed by the window manager

        XSetWindowAttributes attributes;
        attributes.override_redirect = True;
        XChangeWindowAttributes(_glfwLibrary.X11.display,
                                window->X11.handle,
                                CWOverrideRedirect,
                                &attributes);

        window->X11.overrideRedirect = GL_TRUE;
    }

    // Find or create the protocol atom for window close notifications
    _glfwLibrary.X11.wmDeleteWindow = XInternAtom(_glfwLibrary.X11.display,
                                                  "WM_DELETE_WINDOW",
                                                  False);

    // Declare the WM protocols we support
    {
        int count = 0;
        Atom protocols[2];

        // The WM_DELETE_WINDOW ICCCM protocol
        // Basic window close notification protocol
        if (_glfwLibrary.X11.wmDeleteWindow != None)
            protocols[count++] = _glfwLibrary.X11.wmDeleteWindow;

        // The _NET_WM_PING EWMH protocol
        // Tells the WM to ping our window and flag us as unresponsive if we
        // don't reply within a few seconds
        if (_glfwLibrary.X11.wmPing != None)
            protocols[count++] = _glfwLibrary.X11.wmPing;

        if (count > 0)
        {
            XSetWMProtocols(_glfwLibrary.X11.display, window->X11.handle,
                            protocols, count);
        }
    }

    // Set ICCCM WM_HINTS property
    {
        XWMHints* hints = XAllocWMHints();
        if (!hints)
        {
            _glfwSetError(GLFW_OUT_OF_MEMORY,
                          "X11/GLX: Failed to allocate WM hints");
            return GL_FALSE;
        }

        hints->flags = StateHint;
        hints->initial_state = NormalState;

        XSetWMHints(_glfwLibrary.X11.display, window->X11.handle, hints);
        XFree(hints);
    }

    // Set ICCCM WM_NORMAL_HINTS property (even if no parts are set)
    {
        XSizeHints* hints = XAllocSizeHints();
        if (!hints)
        {
            _glfwSetError(GLFW_OUT_OF_MEMORY,
                          "X11/GLX: Failed to allocate size hints");
            return GL_FALSE;
        }

        hints->flags = 0;

        if (!wndconfig->resizable)
        {
            hints->flags |= (PMinSize | PMaxSize);
            hints->min_width  = hints->max_width  = window->width;
            hints->min_height = hints->max_height = window->height;
        }

        XSetWMNormalHints(_glfwLibrary.X11.display, window->X11.handle, hints);
        XFree(hints);
    }

    _glfwPlatformSetWindowTitle(window, wndconfig->title);

    // Make sure the window is mapped before proceeding
    XMapWindow(_glfwLibrary.X11.display, window->X11.handle);
    XFlush(_glfwLibrary.X11.display);

    return GL_TRUE;
}
Example #30
0
LLDSPEC bool_t gdisp_lld_init(GDisplay *g) {
	XSizeHints				*pSH;
	XSetWindowAttributes	xa;
	XTextProperty			WindowTitle;
	char *					WindowTitleText;
	xPriv					*priv;

	if (!initdone) {
		gfxThreadHandle			hth;

		initdone = TRUE;
		#if GFX_USE_OS_LINUX || GFX_USE_OS_OSX
			XInitThreads();
		#endif

		dis = XOpenDisplay(0);
		scr = DefaultScreen(dis);
		cxt = XUniqueContext();
		wmDelete = XInternAtom(dis, "WM_DELETE_WINDOW", False);
		XSetIOErrorHandler(FatalXIOError);

		#if GDISP_FORCE_24BIT
			if (!XMatchVisualInfo(dis, scr, 24, TrueColor, &vis)) {
				fprintf(stderr, "Your display has no TrueColor mode\n");
				XCloseDisplay(dis);
				return FALSE;
			}
			cmap = XCreateColormap(dis, RootWindow(dis, scr),
					vis.visual, AllocNone);
		#else
			vis.visual = CopyFromParent;
			vis.depth = DefaultDepth(dis, scr);
			cmap = DefaultColormap(dis, scr);
		#endif
		fprintf(stderr, "Running GFX Window in %d bit color\n", vis.depth);

		if (!(hth = gfxThreadCreate(waXThread, sizeof(waXThread), HIGH_PRIORITY, ThreadX, 0))) {
			fprintf(stderr, "Cannot start X Thread\n");
			XCloseDisplay(dis);
			exit(0);
		}
		#if GFX_USE_OS_LINUX || GFX_USE_OS_OSX
			pthread_detach(hth);
		#endif
		gfxThreadClose(hth);
	}

	g->priv = gfxAlloc(sizeof(xPriv));
	priv = (xPriv *)g->priv;
	g->board = 0;					// No board interface for this driver

	xa.colormap = cmap;
	xa.border_pixel = 0xFFFFFF;
	xa.background_pixel = 0x000000;

	priv->win = XCreateWindow(dis, RootWindow(dis, scr), 16, 16,
			GDISP_SCREEN_WIDTH, GDISP_SCREEN_HEIGHT,
			0, vis.depth, InputOutput, vis.visual,
			CWBackPixel|CWColormap|CWBorderPixel, &xa);
	XSync(dis, TRUE);

	XSaveContext(dis, priv->win, cxt, (XPointer)g);
	XSetWMProtocols(dis, priv->win, &wmDelete, 1);

	{
		char					buf[132];
		sprintf(buf, "uGFX - %u", g->systemdisplay+1);
		WindowTitleText = buf;
		XStringListToTextProperty(&WindowTitleText, 1, &WindowTitle);
		XSetWMName(dis, priv->win, &WindowTitle);
		XSetWMIconName(dis, priv->win, &WindowTitle);
		XSync(dis, TRUE);
	}

	pSH = XAllocSizeHints();
	pSH->flags = PSize | PMinSize | PMaxSize;
	pSH->min_width = pSH->max_width = pSH->base_width = GDISP_SCREEN_WIDTH;
	pSH->min_height = pSH->max_height = pSH->base_height = GDISP_SCREEN_HEIGHT;
	XSetWMNormalHints(dis, priv->win, pSH);
	XFree(pSH);
	XSync(dis, TRUE);

	priv->pix = XCreatePixmap(dis, priv->win,
				GDISP_SCREEN_WIDTH, GDISP_SCREEN_HEIGHT, vis.depth);
	XSync(dis, TRUE);

	priv->gc = XCreateGC(dis, priv->win, 0, 0);
	XSetBackground(dis, priv->gc, BlackPixel(dis, scr));
	XSync(dis, TRUE);

	// Create the associated mouse before the map
	#if GINPUT_NEED_MOUSE
		priv->mouse = (GMouse *)gdriverRegister((const GDriverVMT const *)GMOUSE_DRIVER_VMT, g);
	#endif

	XSelectInput(dis, priv->win, StructureNotifyMask);
	XMapWindow(dis, priv->win);

	// Wait for the window creation to complete (for safety)
	while(!(((volatile GDisplay *)g)->flags & GDISP_FLG_READY))
		gfxSleepMilliseconds(100);

	/* Initialise the GDISP structure to match */
    g->g.Orientation = GDISP_ROTATE_0;
    g->g.Powermode = powerOn;
    g->g.Backlight = 100;
    g->g.Contrast = 50;
    g->g.Width = GDISP_SCREEN_WIDTH;
    g->g.Height = GDISP_SCREEN_HEIGHT;

    return TRUE;
}