Exemple #1
0
int
puglCreateWindow(PuglView* view, const char* title)
{
	PuglInternals* const impl = view->impl;

	impl->display = XOpenDisplay(NULL);
	impl->screen  = DefaultScreen(impl->display);

	XVisualInfo* const vi = getVisual(view);
	if (!vi) {
		XCloseDisplay(impl->display);
		impl->display = NULL;
		return 1;
	}

#ifdef PUGL_HAVE_GL
	int glxMajor, glxMinor;
	glXQueryVersion(impl->display, &glxMajor, &glxMinor);
	PUGL_LOGF("GLX Version %d.%d\n", glxMajor, glxMinor);
#endif

	Window xParent = view->parent
		? (Window)view->parent
		: RootWindow(impl->display, impl->screen);

	Colormap cmap = XCreateColormap(
		impl->display, xParent, vi->visual, AllocNone);

	XSetWindowAttributes attr;
	memset(&attr, 0, sizeof(XSetWindowAttributes));
	attr.background_pixel = BlackPixel(impl->display, impl->screen);
	attr.border_pixel     = BlackPixel(impl->display, impl->screen);
	attr.colormap         = cmap;
	attr.event_mask       = (ExposureMask | StructureNotifyMask |
	                         EnterWindowMask | LeaveWindowMask |
	                         KeyPressMask | KeyReleaseMask |
	                         ButtonPressMask | ButtonReleaseMask |
	                         PointerMotionMask | FocusChangeMask);

	impl->win = XCreateWindow(
		impl->display, xParent,
		0, 0, view->width, view->height, 0, vi->depth, InputOutput, vi->visual,
		CWBackPixel | CWBorderPixel | CWColormap | CWEventMask, &attr);

	if (!createContext(view, vi)) {
		XDestroyWindow(impl->display, impl->win);
		impl->win = 0;

		XCloseDisplay(impl->display);
		impl->display = NULL;

		return 1;
	}

	XSizeHints sizeHints;
	memset(&sizeHints, 0, sizeof(sizeHints));
	if (!view->resizable) {
		sizeHints.flags      = PMinSize|PMaxSize;
		sizeHints.min_width  = view->width;
		sizeHints.min_height = view->height;
		sizeHints.max_width  = view->width;
		sizeHints.max_height = view->height;
		XSetNormalHints(impl->display, impl->win, &sizeHints);
	} else if (view->min_width > 0 && view->min_height > 0) {
		sizeHints.flags      = PMinSize;
		sizeHints.min_width  = view->min_width;
		sizeHints.min_height = view->min_height;
		XSetNormalHints(impl->display, impl->win, &sizeHints);
	}

	if (title) {
		XStoreName(impl->display, impl->win, title);
	}

	if (!view->parent) {
		Atom wmDelete = XInternAtom(impl->display, "WM_DELETE_WINDOW", True);
		XSetWMProtocols(impl->display, impl->win, &wmDelete, 1);
	}

	if (glXIsDirect(impl->display, impl->ctx)) {
		PUGL_LOG("DRI enabled (to disable, set LIBGL_ALWAYS_INDIRECT=1\n");
	} else {
		PUGL_LOG("No DRI available\n");
	}

	XFree(vi);

	return PUGL_SUCCESS;
}
Exemple #2
0
/* To call from C, use the routine below - without the extra underscore */
void draw_wave(double * results) {

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      }  /* switch (myevent.type) */

   }   /* while (! done) */

XDestroyWindow (mydisp, base.window);
XCloseDisplay (mydisp);
}
Exemple #3
0
  int main (void)
  {
    int i;
  
    int allocateOK;
  
    ximg = NULL;
  
  	
    d = XOpenDisplay (NULL);
  
    if (!d)
      fputs ("Couldn't open display\n", stderr), exit (1);
  
    screen = DefaultScreen (d);
    gc = DefaultGC (d, screen);
  
    /* Find a visual */
  
    vis.screen = screen;
    vlist = XGetVisualInfo (d, VisualScreenMask, &vis, &match);
  
    if (!vlist)
      fputs ("No matched visuals\n", stderr), exit (1);
  
    vis = vlist[0];
    XFree (vlist);
		
  	// That's not a fair comparison colormap_size is depth in bits!
    // if (vis.colormap_size < COLORS)
      // printf("Colormap is too small: %i.\n",vis.colormap_size); // , exit (1);
		printf("Colour depth: %i\n",vis.colormap_size);
  
    win = XCreateSimpleWindow (d, DefaultRootWindow (d),
			       0, 0, WIN_W, WIN_H, 0,
			       WhitePixel (d, screen), BlackPixel (d, screen));
  
	  int xclass=get_xvisinfo_class(vis);
		// printf("class = %i\n",xclass);
	  stylee = ( vis.depth > 8 ? styleeTrueColor : styleePrivate );
	  // printf("stylee=%i\n",stylee);
  
    if ( get_xvisinfo_class(vis) % 2 == 1) {	/* The odd numbers can redefine colors */
  
			  // printf("%i\n",get_xvisinfo_class(vis));
	  	
      colormap = DefaultColormap (d, screen);
		  Visual *defaultVisual=DefaultVisual(d,screen);
	  	
      /* Allocate cells */
      allocateOK = (XAllocColorCells (d, colormap, 1,
							      NULL, 0, color, COLORS) != 0);

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

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


  
      // XNextEvent (d, &ev);
      // switch (ev.type) {
      // case ButtonPress:
        // should_quit = 1;
        // break;
      // case Expose:
        // if (can_use_mitshm)
				  // XShmPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H, True);
        // else
				  // XPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H);
        // break;
      // default:
			  // break;
      // }
  
  
  
    if (get_xvisinfo_class(vis) % 2 == 1 || get_xvisinfo_class(vis) == TrueColor) {
      unsigned long color[COLORS];
  
      if (allocateOK) {
        for (i = 0; i < COLORS; i++)
				  color[i] = xrgb[i].pixel;
        XFreeColors (d, colormap, color, COLORS, 0);
      }				/* Allocated colors freed */
    } else {
      XUninstallColormap (d, colormap);
    }
  
    if (can_use_mitshm) {
      XShmDetach (d, &shminfo);	/* Server detached */
      XDestroyImage (ximg);	/* Image struct freed */
      shmdt (shminfo.shmaddr);	/* We're detached */
    } else
      XDestroyImage (ximg);	/* Image struct freed */
  
    XDestroyWindow (d, win);	/* Window removed */
    XCloseDisplay (d);		/* Display disconnected */
  
    /* So you can see how your computer compares to your friend's */
    getrusage (RUSAGE_SELF, &resource_utilization);
		float seconds=(float)resource_utilization.ru_utime.tv_sec
						     +(float)resource_utilization.ru_utime.tv_usec*0.000000001;
		printf("CPU seconds per frame: %f\n",seconds/(float)frameno);
    // printf ("CPU seconds consumed: %ds and %dµs\n",
	    // (int) resource_utilization.ru_utime.tv_sec,
	    // (int) resource_utilization.ru_utime.tv_usec);
  
    return 0;
  }
static gboolean
skype_connect()
{
	Window root;
	Atom skype_inst;
	Atom type_ret;
	int format_ret;
	unsigned long nitems_ret;
	unsigned long bytes_after_ret;
	unsigned char *prop;
	int status;
	
	x11_error_code = 0;
	XSetErrorHandler(x11_error_handler);
	skype_debug_info("skype_x11", "Set the XErrorHandler\n");
#ifdef USE_XVFB_SERVER	
	if (!getenv("SKYPEDISPLAY"))
		setenv("SKYPEDISPLAY", ":25", 0);
#endif
	if (getenv("SKYPEDISPLAY"))
		disp = XOpenDisplay(getenv("SKYPEDISPLAY"));
	else
		disp = XOpenDisplay(getenv("DISPLAY"));
	if (disp == NULL)
	{
		skype_debug_info("skype_x11", "Couldn't open display\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Opened display\n");
	message_start = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE_BEGIN", False );
	message_continue = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE", False );
	root = DefaultRootWindow( disp );
	win = XCreateSimpleWindow( disp, root, 0, 0, 1, 1,
		0, BlackPixel( disp, DefaultScreen( disp ) ),
		BlackPixel( disp, DefaultScreen( disp ) ));
	XFlush(disp);
	if (win == None)
	{
		XCloseDisplay(disp);
		disp = NULL;
		skype_debug_info("skype_x11", "Could not create X11 messaging window\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Created X11 messaging window\n");
	skype_inst = XInternAtom(disp, "_SKYPE_INSTANCE", True);
	if (skype_inst == None)
	{
		XDestroyWindow(disp, win);
		XCloseDisplay(disp);
		win = (Window)None;
		disp = NULL;
		skype_debug_info("skype_x11", "Could not create skype Atom\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Created skype Atom\n");
	status = XGetWindowProperty(disp, root, skype_inst, 0, 1, False, XA_WINDOW, &type_ret, &format_ret, &nitems_ret, &bytes_after_ret, &prop);
	if(status != Success || format_ret != 32 || nitems_ret < 1)
	{
		XDestroyWindow(disp, win);
		XCloseDisplay(disp);
		win = (Window)None;
		XFree(prop);
		disp = NULL;
		skype_debug_info("skype", "Skype instance not found\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Skype instance found\n");
	skype_win = * (const unsigned long *) prop & 0xffffffff;
	XFree(prop);
	run_loop = TRUE;
	
	skype_debug_info("skype_x11", "Charging lasers...\n");
	receiving_thread = g_thread_create((GThreadFunc)receive_message_loop, NULL, FALSE, NULL);
	
	return TRUE;
}
Exemple #5
0
int main(int argc, char **argv)
{
    XClassHint classhint;

    dpy = XOpenDisplay("");
    if (!dpy) {
        puts("could not open display!");
        exit(1);
    }
    delete_win = XInternAtom(dpy, "WM_DELETE_WINDOW", False);

    leader = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 10, 10, 10, 10,
                                 0, 0, 0);
    /* set class hint */
    classhint.res_name = "notest";
    classhint.res_class = "Notest";
    XSetClassHint(dpy, leader, &classhint);

    /* set window group leader to self */
    hints = XAllocWMHints();
    hints->window_group = leader;
    hints->flags = WindowGroupHint;
    XSetWMHints(dpy, leader, hints);

    /* create app context */
    app = WMAppCreateWithMain(dpy, DefaultScreen(dpy), leader);
    menu = WMMenuCreate(app, "Notify Test Menu");
    WMMenuAddItem(menu, "Hide", (WMMenuAction)hide, NULL, NULL, NULL);
    WMMenuAddItem(menu, "Quit", (WMMenuAction)quit, NULL, NULL, NULL);

    WMAppSetMainMenu(app, menu);
    WMRealizeMenus(app);

    /* Get some WindowMaker notifications */
    WMNotifySet( app, WMN_APP_START, notify_print, (void *) "App start" );
    WMNotifySet( app, WMN_APP_EXIT,  notify_print, (void *) "App end" );
    WMNotifySet( app, WMN_WIN_FOCUS,  notify_print, (void *) "Focus in" );
    WMNotifySet( app, WMN_WIN_UNFOCUS,  notify_print, (void *) "Focus out" );
    WMNotifySet( app, WMN_NOTIFY_ALL,  notify_print, (void *) "Unknown type" );
    WMNotifyMaskUpdate( app );	/* Mask isn't actually set till we do this */

    /* set command to use to startup this */
    XSetCommand(dpy, leader, argv, argc);

    /* create first window */
    newwin(NULL, 0, 0);


    XFlush(dpy);
    while( 1 ) {
        XEvent ev;
        XNextEvent(dpy, &ev);
        if (ev.type==ClientMessage) {
            if (ev.xclient.data.l[0]==delete_win) {
                XDestroyWindow(dpy,ev.xclient.window);
                break;
            }
        }
        WMProcessEvent(app, &ev);
    }
    exit(0);
}
Exemple #6
0
void *
winClipboardProc(void *pvNotUsed)
{
    Atom atomClipboard, atomClipboardManager;
    int iReturn;
    HWND hwnd = NULL;
    int iConnectionNumber = 0;

#ifdef HAS_DEVWINDOWS
    int fdMessageQueue = 0;
#else
    struct timeval tvTimeout;
#endif
    fd_set fdsRead;
    int iMaxDescriptor;
    Display *pDisplay = NULL;
    Window iWindow = None;
    int iRetries;
    Bool fUseUnicode;
    char szDisplay[512];
    int iSelectError;

    ErrorF("winClipboardProc - Hello\n");
    ++clipboardRestarts;

    /* Do we have Unicode support? */
    g_fUnicodeSupport = winClipboardDetectUnicodeSupport();

    /* Do we use Unicode clipboard? */
    fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;

    /* Save the Unicode support flag in a global */
    g_fUseUnicode = fUseUnicode;

    /* Allow multiple threads to access Xlib */
    if (XInitThreads() == 0) {
        ErrorF("winClipboardProc - XInitThreads failed.\n");
        goto winClipboardProc_Exit;
    }

    /* See if X supports the current locale */
    if (XSupportsLocale() == False) {
        ErrorF("winClipboardProc - Warning: Locale not supported by X.\n");
    }

    /* Set error handler */
    XSetErrorHandler(winClipboardErrorHandler);
    g_winClipboardProcThread = pthread_self();
    g_winClipboardOldIOErrorHandler =
        XSetIOErrorHandler(winClipboardIOErrorHandler);

    /* Set jump point for Error exits */
    iReturn = setjmp(g_jmpEntry);

    /* Check if we should continue operations */
    if (iReturn != WIN_JMP_ERROR_IO && iReturn != WIN_JMP_OKAY) {
        /* setjmp returned an unknown value, exit */
        ErrorF("winClipboardProc - setjmp returned: %d exiting\n", iReturn);
        goto winClipboardProc_Exit;
    }
    else if (iReturn == WIN_JMP_ERROR_IO) {
        /* TODO: Cleanup the Win32 window and free any allocated memory */
        ErrorF("winClipboardProc - setjmp returned for IO Error Handler.\n");
        pthread_exit(NULL);
    }

    /* Use our generated cookie for authentication */
    winSetAuthorization();

    /* Initialize retry count */
    iRetries = 0;

    /* Setup the display connection string x */
    /*
     * NOTE: Always connect to screen 0 since we require that screen
     * numbers start at 0 and increase without gaps.  We only need
     * to connect to one screen on the display to get events
     * for all screens on the display.  That is why there is only
     * one clipboard client thread.
     */
    snprintf(szDisplay, 512, "127.0.0.1:%s.0", display);

    /* Print the display connection string */
    ErrorF("winClipboardProc - DISPLAY=%s\n", szDisplay);

    /* Open the X display */
    do {
        pDisplay = XOpenDisplay(szDisplay);
        if (pDisplay == NULL) {
            ErrorF("winClipboardProc - Could not open display, "
                   "try: %d, sleeping: %d\n", iRetries + 1, WIN_CONNECT_DELAY);
            ++iRetries;
            sleep(WIN_CONNECT_DELAY);
            continue;
        }
        else
            break;
    }
    while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);

    /* Make sure that the display opened */
    if (pDisplay == NULL) {
        ErrorF("winClipboardProc - Failed opening the display, giving up\n");
        goto winClipboardProc_Done;
    }

    /* Save the display in the screen privates */
    g_pClipboardDisplay = pDisplay;

    ErrorF("winClipboardProc - XOpenDisplay () returned and "
           "successfully opened the display.\n");

    /* Get our connection number */
    iConnectionNumber = ConnectionNumber(pDisplay);

#ifdef HAS_DEVWINDOWS
    /* Open a file descriptor for the windows message queue */
    fdMessageQueue = open(WIN_MSG_QUEUE_FNAME, O_RDONLY);
    if (fdMessageQueue == -1) {
        ErrorF("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
        goto winClipboardProc_Done;
    }

    /* Find max of our file descriptors */
    iMaxDescriptor = max(fdMessageQueue, iConnectionNumber) + 1;
#else
    iMaxDescriptor = iConnectionNumber + 1;
#endif

    /* Create atoms */
    atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False);
    atomClipboardManager = XInternAtom(pDisplay, "CLIPBOARD_MANAGER", False);

    /* Create a messaging window */
    iWindow = XCreateSimpleWindow(pDisplay,
                                  DefaultRootWindow(pDisplay),
                                  1, 1,
                                  500, 500,
                                  0,
                                  BlackPixel(pDisplay, 0),
                                  BlackPixel(pDisplay, 0));
    if (iWindow == 0) {
        ErrorF("winClipboardProc - Could not create an X window.\n");
        goto winClipboardProc_Done;
    }

    XStoreName(pDisplay, iWindow, "xwinclip");

    /* Select event types to watch */
    if (XSelectInput(pDisplay, iWindow, PropertyChangeMask) == BadWindow)
        ErrorF("winClipboardProc - XSelectInput generated BadWindow "
               "on messaging window\n");

    /* Save the window in the screen privates */
    g_iClipboardWindow = iWindow;

    /* Create Windows messaging window */
    hwnd = winClipboardCreateMessagingWindow();

    /* Save copy of HWND in screen privates */
    g_hwndClipboard = hwnd;

    /* Assert ownership of selections if Win32 clipboard is owned */
    if (NULL != GetClipboardOwner()) {
        /* PRIMARY */
        iReturn = XSetSelectionOwner(pDisplay, XA_PRIMARY,
                                     iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, XA_PRIMARY) != iWindow) {
            ErrorF("winClipboardProc - Could not set PRIMARY owner\n");
            goto winClipboardProc_Done;
        }

        /* CLIPBOARD */
        iReturn = XSetSelectionOwner(pDisplay, atomClipboard,
                                     iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, atomClipboard) != iWindow) {
            ErrorF("winClipboardProc - Could not set CLIPBOARD owner\n");
            goto winClipboardProc_Done;
        }
    }

    /* Pre-flush X events */
    /* 
     * NOTE: Apparently you'll freeze if you don't do this,
     *       because there may be events in local data structures
     *       already.
     */
    winClipboardFlushXEvents(hwnd, iWindow, pDisplay, fUseUnicode);

    /* Pre-flush Windows messages */
    if (!winClipboardFlushWindowsMessageQueue(hwnd))
        return 0;

    /* Signal that the clipboard client has started */
    g_fClipboardStarted = TRUE;

    /* Loop for X events */
    while (1) {
        /* Setup the file descriptor set */
        /*
         * NOTE: You have to do this before every call to select
         *       because select modifies the mask to indicate
         *       which descriptors are ready.
         */
        FD_ZERO(&fdsRead);
        FD_SET(iConnectionNumber, &fdsRead);
#ifdef HAS_DEVWINDOWS
        FD_SET(fdMessageQueue, &fdsRead);
#else
        tvTimeout.tv_sec = 0;
        tvTimeout.tv_usec = 100;
#endif

        /* Wait for a Windows event or an X event */
        iReturn = select(iMaxDescriptor,        /* Highest fds number */
                         &fdsRead,      /* Read mask */
                         NULL,  /* No write mask */
                         NULL,  /* No exception mask */
#ifdef HAS_DEVWINDOWS
                         NULL   /* No timeout */
#else
                         &tvTimeout     /* Set timeout */
#endif
            );

#ifndef HAS_WINSOCK
        iSelectError = errno;
#else
        iSelectError = WSAGetLastError();
#endif

        if (iReturn < 0) {
#ifndef HAS_WINSOCK
            if (iSelectError == EINTR)
#else
            if (iSelectError == WSAEINTR)
#endif
                continue;

            ErrorF("winClipboardProc - Call to select () failed: %d.  "
                   "Bailing.\n", iReturn);
            break;
        }

        /* Branch on which descriptor became active */
        if (FD_ISSET(iConnectionNumber, &fdsRead)) {
            /* Process X events */
            /* Exit when we see that server is shutting down */
            iReturn = winClipboardFlushXEvents(hwnd,
                                               iWindow, pDisplay, fUseUnicode);
            if (WIN_XEVENTS_SHUTDOWN == iReturn) {
                ErrorF("winClipboardProc - winClipboardFlushXEvents "
                       "trapped shutdown event, exiting main loop.\n");
                break;
            }
        }

#ifdef HAS_DEVWINDOWS
        /* Check for Windows event ready */
        if (FD_ISSET(fdMessageQueue, &fdsRead))
#else
        if (1)
#endif
        {
            /* Process Windows messages */
            if (!winClipboardFlushWindowsMessageQueue(hwnd)) {
                ErrorF("winClipboardProc - "
                       "winClipboardFlushWindowsMessageQueue trapped "
                       "WM_QUIT message, exiting main loop.\n");
                break;
            }
        }
    }

 winClipboardProc_Exit:
    /* disable the clipboard, which means the thread will die */
    g_fClipboard = FALSE;

 winClipboardProc_Done:
    /* Close our Windows window */
    if (g_hwndClipboard) {
        /* Destroy the Window window (hwnd) */
        winDebug("winClipboardProc - Destroy Windows window\n");
        PostMessage(g_hwndClipboard, WM_DESTROY, 0, 0);
        winClipboardFlushWindowsMessageQueue(g_hwndClipboard);
    }

    /* Close our X window */
    if (pDisplay && iWindow) {
        iReturn = XDestroyWindow(pDisplay, iWindow);
        if (iReturn == BadWindow)
            ErrorF("winClipboardProc - XDestroyWindow returned BadWindow.\n");
        else
            ErrorF("winClipboardProc - XDestroyWindow succeeded.\n");
    }

#ifdef HAS_DEVWINDOWS
    /* Close our Win32 message handle */
    if (fdMessageQueue)
        close(fdMessageQueue);
#endif

#if 0
    /*
     * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26.  The
     * XSync and XSelectInput calls did not help.
     */

    /* Discard any remaining events */
    XSync(pDisplay, TRUE);

    /* Select event types to watch */
    XSelectInput(pDisplay, DefaultRootWindow(pDisplay), None);

    /* Close our X display */
    if (pDisplay) {
        XCloseDisplay(pDisplay);
    }
#endif

    /* global clipboard variable reset */
    g_fClipboardLaunched = FALSE;
    g_fClipboardStarted = FALSE;
    g_iClipboardWindow = None;
    g_pClipboardDisplay = NULL;
    g_hwndClipboard = NULL;

    /* checking if we need to restart */
    if (clipboardRestarts >= WIN_CLIPBOARD_RETRIES) {
        /* terminates clipboard thread but the main server still lives */
        ErrorF
            ("winClipboardProc - the clipboard thread has restarted %d times and seems to be unstable, disabling clipboard integration\n",
             clipboardRestarts);
        g_fClipboard = FALSE;
        return;
    }

    if (g_fClipboard) {
        sleep(WIN_CLIPBOARD_DELAY);
        ErrorF("winClipboardProc - trying to restart clipboard thread \n");
        /* Create the clipboard client thread */
        if (!winInitClipboard()) {
            ErrorF("winClipboardProc - winClipboardInit failed.\n");
            return;
        }

        winDebug("winClipboardProc - winInitClipboard returned.\n");
        /* Flag that clipboard client has been launched */
        g_fClipboardLaunched = TRUE;
    }
    else {
        ErrorF("winClipboardProc - Clipboard disabled  - Exit from server \n");
        /* clipboard thread has exited, stop server as well */
        kill(getpid(), SIGTERM);
    }

    return NULL;
}
Exemple #7
0
/**
* @brief Destructor. Call this to clean up after you're ready with S3D.
*/
Simple3D::~Simple3D()
{
	delete zbuffer;
	XFreePixmap(disp,backbuffer);
	XDestroyWindow(disp,window);
}
Exemple #8
0
Bool
dfb_x11_open_window( DFBX11 *x11, XWindow** ppXW, int iXPos, int iYPos, int iWidth, int iHeight, DFBSurfacePixelFormat format )
{
     XWindow              *xw;
     XSetWindowAttributes  attr = { .background_pixmap = 0 };
     void                 *old_error_handler = 0;
     unsigned int          cw_mask = CWEventMask;

     D_DEBUG_AT( X11_Window, "Creating %4dx%4d %s window...\n", iWidth, iHeight, dfb_pixelformat_name(format) );

     xw = D_CALLOC( 1, sizeof(XWindow) );
     if (!xw)
          return D_OOM();

     /* We set the structure as needed for our window */
     xw->width   = iWidth;
     xw->height  = iHeight;
     xw->display = x11->display;

     xw->screenptr = DefaultScreenOfDisplay(xw->display);
     xw->screennum = DefaultScreen(xw->display);
     xw->depth     = DefaultDepthOfScreen( xw->screenptr );
     xw->visual    = DefaultVisualOfScreen( xw->screenptr );

     attr.event_mask =
            ButtonPressMask
          | ButtonReleaseMask
          | PointerMotionMask
          | KeyPressMask
          | KeyReleaseMask
          | ExposureMask
          | StructureNotifyMask;

     if (dfb_config->x11_borderless) {
          attr.override_redirect = True;

          cw_mask |= CWOverrideRedirect;
     }

     XLockDisplay( x11->display );

     old_error_handler = XSetErrorHandler( error_handler );

     error_code = 0;

     xw->window = XCreateWindow( xw->display,
                                 RootWindowOfScreen(xw->screenptr),
                                 iXPos, iYPos, iWidth, iHeight, 0, xw->depth, InputOutput,
                                 xw->visual, cw_mask, &attr );
     XSync( xw->display, False );
     if (!xw->window || error_code) {
          D_FREE( xw );
          XUnlockDisplay( x11->display );
          return False;
     }


     XSizeHints Hints;

     /*
      * Here we inform the function of what we are going to change for the
      * window (there's also PPosition but it's obsolete)
      */
     Hints.flags    =    PSize | PMinSize | PMaxSize;

     /*
      * Now we set the structure to the values we need for width & height.
      * For esthetic reasons we set Width=MinWidth=MaxWidth.
      * The same goes for Height. You can try whith differents values, or
      * let's use Hints.flags=Psize; and resize your window..
      */
     Hints.min_width          =    Hints.max_width          =    Hints.base_width    =    xw->width;
     Hints.min_height    =    Hints.max_height    =    Hints.base_height   =    xw->height;

     /* Now we can set the size hints for the specified window */
     XSetWMNormalHints(xw->display,xw->window,&Hints);

     /* We change the title of the window (default:Untitled) */
     XStoreName(xw->display,xw->window,"DFB X11 system window");

     xw->gc = XCreateGC(xw->display, xw->window, 0, NULL);

#if 0
     // Create a null cursor
     Pixmap  pixmp1;
     Pixmap  pixmp2;
     XColor  fore;
     XColor  back;
     char    zero = 0;

     pixmp1 = XCreateBitmapFromData( xw->display, xw->window, &zero, 1, 1 );
     pixmp2 = XCreateBitmapFromData( xw->display, xw->window, &zero, 1, 1 );

     xw->NullCursor = XCreatePixmapCursor( xw->display, pixmp1, pixmp2, &fore, &back, 0, 0 );

     XFreePixmap ( xw->display, pixmp1 );
     XFreePixmap ( xw->display, pixmp2 );

     XDefineCursor( xw->display, xw->window, xw->NullCursor );
#endif

     /* maps the window and raises it to the top of the stack */
     XMapRaised( xw->display, xw->window );


     if (x11->use_shm) {
          // Shared memory
          xw->shmseginfo=(XShmSegmentInfo *)D_CALLOC(1, sizeof(XShmSegmentInfo));
          if (!xw->shmseginfo) {
               x11->use_shm = false;
               goto no_shm;
          }

          xw->ximage=XShmCreateImage(xw->display, xw->visual, xw->depth, ZPixmap,
                                     NULL,xw->shmseginfo, xw->width, xw->height * 2);
          XSync( xw->display, False );
          if (!xw->ximage || error_code) {
               D_ERROR("X11: Error creating shared image (XShmCreateImage) \n");
               x11->use_shm = false;
               D_FREE(xw->shmseginfo);
               error_code = 0;
               goto no_shm;
          }

          xw->bpp = (xw->ximage->bits_per_pixel + 7) / 8;

          /* we firstly create our shared memory segment with the size we need, and
          correct permissions for the owner, the group and the world --> 0777 */
          xw->shmseginfo->shmid=shmget(IPC_PRIVATE,
                                       xw->ximage->bytes_per_line * xw->ximage->height * 2,
                                       IPC_CREAT|0777);

          if (xw->shmseginfo->shmid<0) {
               x11->use_shm = false;
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
               goto no_shm;
          }

          /* Then, we have to attach the segment to our process, and we let the
          function search the correct memory place --> NULL. It's safest ! */
          xw->shmseginfo->shmaddr = shmat( xw->shmseginfo->shmid, NULL, 0 );
          if (!xw->shmseginfo->shmaddr) {
               x11->use_shm = false;
               shmctl(xw->shmseginfo->shmid,IPC_RMID,NULL);
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
               goto no_shm;
          }

          /* We set the buffer in Read and Write mode */
          xw->shmseginfo->readOnly=False;

          xw->virtualscreen= xw->ximage->data = xw->shmseginfo->shmaddr;


          XSetErrorHandler( error_handler_shm );

          XShmAttach(x11->display,xw->shmseginfo);

          XShmPutImage(x11->display, xw->window, xw->gc, xw->ximage,
                       0, 0, 0, 0, 1, 1, False);

          XSync(x11->display, False);

          XSetErrorHandler( error_handler );

          if (!x11->use_shm) {
               shmdt(xw->shmseginfo->shmaddr);
               shmctl(xw->shmseginfo->shmid,IPC_RMID,NULL);
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
          }
     }

no_shm:
     if (!x11->use_shm) {
          int pitch;

          xw->bpp = (xw->depth > 16) ? 4 :
                    (xw->depth >  8) ? 2 : 1;

          pitch = (xw->bpp * xw->width + 3) & ~3;

          /* Use malloc(), not D_MALLOC() here, because XCreateImage()
           * will call free() on this data.
           */
          xw->virtualscreen = malloc ( 2 * xw->height * pitch );

          xw->ximage = XCreateImage( xw->display, xw->visual, xw->depth, ZPixmap, 0,
                                     xw->virtualscreen, xw->width, xw->height * 2, 32, pitch );
          XSync( xw->display, False );
          if (!xw->ximage || error_code) {
               D_ERROR( "X11/Window: XCreateImage( Visual %02lu, depth %d, size %dx%d, buffer %p [%d] ) failed!\n",
                        xw->visual->visualid, xw->depth, xw->width, xw->height * 2, xw->virtualscreen, pitch );
               XFreeGC(xw->display,xw->gc);
               XDestroyWindow(xw->display,xw->window);
               XSetErrorHandler( old_error_handler );
               XUnlockDisplay( x11->display );
               D_FREE( xw );
               return False;
          }
     }

     XSetErrorHandler( old_error_handler );

     XUnlockDisplay( x11->display );

     D_INFO( "X11/Display: %ssing XShm.\n", x11->use_shm ? "U" : "Not u" );

     (*ppXW) = xw;

     return True;
}

void
dfb_x11_close_window( DFBX11 *x11, XWindow* xw )
{
     if (x11->use_shm) {
          XShmDetach( xw->display, xw->shmseginfo );
          shmdt( xw->shmseginfo->shmaddr );
          shmctl( xw->shmseginfo->shmid, IPC_RMID, NULL );
          D_FREE( xw->shmseginfo );
     }

     XDestroyImage( xw->ximage );

     XFreeGC( xw->display, xw->gc );
     XDestroyWindow( xw->display, xw->window );
#if 0
     XFreeCursor( xw->display, xw->NullCursor );
#endif

     D_FREE( xw );
}
Exemple #9
0
static void closewin() {
        unmap();
        XDestroyIC(g_xic); g_xic = 0;
        XDestroyWindow(g_dpy, g_win); g_win = 0;
}
Exemple #10
0
int glx_init( int fullscreen )
{
    int vi_attr[] =
    {
        GLX_RGBA,
        GLX_DOUBLEBUFFER,
        GLX_RED_SIZE,       4,
        GLX_GREEN_SIZE,     4,
        GLX_BLUE_SIZE,      4,
        GLX_DEPTH_SIZE,    16,
        None
    };

    XVisualInfo *vi;
    Window root_win;
    XWindowAttributes win_attr;
    XSetWindowAttributes set_attr;
    XFontStruct *fixed;
    XColor black =
    {
        0, 0, 0, 0, 0, 0
    };

    if( ( dpy = XOpenDisplay( NULL ) ) == NULL )
    {
        fprintf( stderr, "XOpenDisplay failed\n" );
        return( 1 );
    }

    if( ( vi = glXChooseVisual( dpy, DefaultScreen( dpy ),
                                vi_attr ) ) == NULL )
    {
        fprintf( stderr, "glXChooseVisual failed\n" );
        XCloseDisplay( dpy );
        return( 1 );
    }

    root_win = RootWindow( dpy, vi->screen );

    XGetWindowAttributes( dpy, root_win, &win_attr );

    width  = ( fullscreen ) ? win_attr.width  : 640;
    height = ( fullscreen ) ? win_attr.height : 480;

    set_attr.border_pixel = 0;

    set_attr.colormap =
        XCreateColormap( dpy, root_win, vi->visual, AllocNone );

    set_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
                          ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;

    set_attr.override_redirect = ( ( fullscreen ) ? True : False );

    win =
        XCreateWindow(
            dpy, root_win, 0, 0, width, height, 0, vi->depth,
            InputOutput, vi->visual, CWBorderPixel | CWColormap |
            CWEventMask | CWOverrideRedirect, &set_attr );

    XStoreName( dpy, win, AppTitle );
    XMapWindow( dpy, win );

    if( fullscreen )
    {
        XGrabKeyboard(  dpy, win, True, GrabModeAsync,
                        GrabModeAsync, CurrentTime );
    }
    else
    {
        wmDelete = XInternAtom( dpy, "WM_DELETE_WINDOW", True );
        XSetWMProtocols( dpy, win, &wmDelete, 1 );
    }

    if( ( ctx = glXCreateContext( dpy, vi, NULL, True ) ) == NULL )
    {
        fprintf( stderr, "glXCreateContext failed\n" );
        XDestroyWindow( dpy, win );
        XCloseDisplay( dpy );
        return( 1 );
    }

    if( glXMakeCurrent( dpy, win, ctx ) == False )
    {
        fprintf( stderr, "glXMakeCurrent failed\n" );
        glXDestroyContext( dpy, ctx );
        XDestroyWindow( dpy, win );
        XCloseDisplay( dpy );
        return( 1 );
    }

    font = glGenLists( 256 );

    fixed = XLoadQueryFont(
                dpy, "-misc-fixed-medium-r-*-*-20-*-*-*-*-*-*-*" );

    null_cursor = XCreateGlyphCursor(
                      dpy, fixed->fid, fixed->fid, ' ', ' ', &black, &black );

    glXUseXFont( fixed->fid, 0, 256, font );

    XFreeFont( dpy, fixed );

    return( 0 );
}
Exemple #11
0
int main( void )
{
    int fullscreen;
    XEvent event;

    if( gl_data() )
    {
        fprintf( stderr, "gl_data failed\n" );
        return( 1 );
    }

    fullscreen = 0;

    do
    {
        modeswitch  = 0;
        fullscreen ^= 1;

        if( glx_init( fullscreen ) )
        {
            fprintf( stderr, "glx_init failed\n" );
            return( 1 );
        }

        if( gl_init() )
        {
            fprintf( stderr, "gl_init failed\n" );
            return( 1 );
        }

        gl_resize();

        run = 1;

        while( run )
        {
            if( active )
            {
                gl_draw();
                glXSwapBuffers( dpy, win );
            }
            else
            {
                XPeekEvent( dpy, &event );
            }

            while( XPending( dpy ) )
            {
                XNextEvent( dpy, &event );

                switch( event.type )
                {
                case ButtonPress:
                {
                    int x = event.xmotion.x,
                        y = event.xmotion.y;

                    switch( event.xbutton.button )
                    {
                    case Button1:
                        gl_event( 0, 0, x, y );
                        break;
                    case Button3:
                        gl_event( 0, 1, x, y );
                        break;
                    }

                    break;
                }

                case ButtonRelease:
                {
                    int x = event.xmotion.x,
                        y = event.xmotion.y;

                    switch( event.xbutton.button )
                    {
                    case Button1:
                        gl_event( 1, 0, x, y );
                        break;
                    case Button3:
                        gl_event( 1, 1, x, y );
                        break;
                    }

                    break;
                }

                case MotionNotify:
                {
                    int x = event.xmotion.x,
                        y = event.xmotion.y;

                    switch( event.xbutton.button )
                    {
                    case Button1:
                        gl_event( 2,  0, x, y );
                        break;
                    case Button3:
                        gl_event( 2,  1, x, y );
                        break;
                    default:
                        gl_event( 2, -1, x, y );
                        break;
                    }

                    break;
                }

                case KeyPress:
                {
                    break;
                }

                case KeyRelease:
                {
                    int key = XLookupKeysym( &event.xkey, 0 );

                    switch( key )
                    {
                    case XK_Tab:

                        modeswitch = 1;

                    case XK_Escape:

                        run = 0;
                        break;

                    default:

                        gl_event( 4, key, -1, -1 );
                        break;
                    }

                    break;
                }

                case UnmapNotify:
                    active = 0;
                    break;
                case   MapNotify:
                    active = 1;
                    break;

                case ConfigureNotify:
                {
                    width  = event.xconfigure.width;
                    height = event.xconfigure.height;
                    gl_resize();
                    break;
                }

                case ClientMessage:
                {
                    if( event.xclient.data.l[0] == (int) wmDelete )
                    {
                        active = run = 0;
                    }
                    break;
                }

                case ReparentNotify:
                    break;

                default:
                {
                    printf( "caught unknown event, type %d\n",
                            event.type );
                    break;
                }
                }
            }
        }

        glXMakeCurrent( dpy, None, NULL );
        glXDestroyContext( dpy, ctx );
        XDestroyWindow( dpy, win );
        XCloseDisplay( dpy );
    }
    while( modeswitch );

    return( 0 );
}
Exemple #12
0
void
WindowDevice::WINOPEN(const char *_title, int _xLoc, int _yLoc, int _width, int _height)
{
    // set the WindowDevices title, height, wdth, xLoc and yLoc
    strcpy(title, _title);

    height = _height;
    width = _width;  
    xLoc = _xLoc;
    yLoc = _yLoc;

#ifdef _UNIX
    if (winOpen == 0) { // we must close the old window
	XFreeGC(theDisplay, theGC);
	XDestroyWindow(theDisplay, theWindow); 
    }

    // define the position and size of the window - only hints
    hints.x = _xLoc;
    hints.y = _yLoc;
    hints.width = _width;
    hints.height = _height;
    hints.flags = PPosition | PSize;

    // set the defualt foreground and background colors
    XVisualInfo visual; 
    visual.visual = 0;
    int depth = DefaultDepth(theDisplay, theScreen);

    if (background == 0) {
      if (XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual) == 0) {
	  foreground = BlackPixel(theDisplay, theScreen);
	  background = WhitePixel(theDisplay, theScreen);    

      } else {
	foreground = 0;
	background = 255;
      }
    }

    // now open a window
    theWindow = XCreateSimpleWindow(theDisplay,RootWindow(theDisplay,0),
				    hints.x, hints.y,
				    hints.width,hints.height,4,
				    foreground, background);

    if (theWindow == 0) {
	opserr << "WindowDevice::WINOPEN() - could not open a window\n";
	exit(-1);
    }	
    
    XSetStandardProperties(theDisplay, theWindow, title, title, None, 0, 0, &hints);
    
    // create a graphical context
    theGC = XCreateGC(theDisplay, theWindow, 0, 0);

    // if we were unable to get space for our colors
    // we must create and use our own colormap
    if (colorFlag == 3 ) {

      // create the colormap if the 1st window
      if (numWindowDevice == 1) {
	int fail = false;
	//	XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual);
	if (XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual) == 0) {
	  opserr << "WindowDevice::initX11() - could not get a visual for PseudoColor\n";
	  opserr << "Colors diplayed will be all over the place\n";
	  cmap = DefaultColormap(theDisplay, theScreen);
	  fail = true;
        } else {
	  opserr << "WindowDevice::WINOPEN have created our own colormap, \n";
	  opserr << "windows may change color as move mouse from one window to\n";
	  opserr << "another - depends on your video card to use another colormap\n\n";	

	  cmap = XCreateColormap(theDisplay,theWindow,
				 visual.visual, AllocAll);
	}


	/*
	cmap = XCreateColormap(theDisplay,theWindow,
			   DefaultVisual(theDisplay,0),AllocAll);
	*/

	if (cmap == 0) {
	    opserr << "WindowDevice::initX11() - could not get a new color table\n";
	    exit(-1);
	}	    

	// we are going to try to allocate 256 new colors -- need 8 planes for this
	depth = DefaultDepth(theDisplay, theScreen);
	if (depth < 8) {
	    opserr << "WindowDevice::initX11() - needed at least 8 planes\n";
	    exit(-1);
	}	    
	if (fail == false) {
	  int cnt = 0;
	  for (int red = 0; red < 8; red++) {
	    for (int green = 0; green < 8; green++) {
		for (int blue = 0; blue < 4; blue++) {
		  pixels[32*red + 4*green + blue] = cnt;
		  colors[cnt].pixel = pixels[32*red + 4*green + blue];
		  colors[cnt].red = (65536/7)*red;
		  colors[cnt].green = (65536/7)*green;
		  colors[cnt].blue = (65536/3)*blue;
		  colors[cnt].flags = DoRed | DoGreen | DoBlue;
		  cnt++;
		}			
	    }
	  }
	  background = 0; //pixels[0];
	  foreground = 255; // pixels[255];
	  XStoreColors(theDisplay, cmap, colors, cnt);			    
	}
      }

      // now set the windows to use the colormap
      XSetWindowColormap(theDisplay, theWindow, cmap);    
    
    }

    XSetBackground(theDisplay, theGC, background);
    XSetForeground(theDisplay, theGC, foreground);

    XMapWindow(theDisplay,theWindow);
    XClearWindow(theDisplay, theWindow);      
    XFlush(theDisplay);

#else
    //    auxInitDisplayMode(AUX_SINGLE | AUX_RGBA);
    //    auxInitPosition(100,100,_width,_height);
    //    auxInitWindow("G3");

    if (winOpen == 0)
      oglDestroyWindow(title,theWND, theHRC, theHDC);      

    theWND = oglCreateWindow(title, xLoc, yLoc, width, height, &theHRC, &theHDC);
    if (theWND == NULL)
      exit(1);
    winOpen = 0;

    wglMakeCurrent(theHDC, theHRC);
    glClearColor(1.0f,1.0f,1.0f,1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
//    gluOrtho2D(0.0, (GLdouble)width, 0.0, (GLdouble)height);
    glFlush();

#endif

    winOpen = 0;
}
void LUI_ColorBarDestroy( LUI_COLORBAR *cb )
{
   XDestroyWindow( LUI_Display, cb->window );
   free(cb);
}
Exemple #14
0
		int32_t run(int _argc, char** _argv)
		{
			XInitThreads();
			m_display = XOpenDisplay(0);

			int32_t screen = DefaultScreen(m_display);
			int32_t depth = DefaultDepth(m_display, screen);
			Visual* visual = DefaultVisual(m_display, screen);
			Window root = RootWindow(m_display, screen);

			XSetWindowAttributes windowAttrs;
			memset(&windowAttrs, 0, sizeof(windowAttrs) );
			windowAttrs.background_pixmap = 0;
			windowAttrs.border_pixel = 0;
			windowAttrs.event_mask = 0
					| ButtonPressMask
					| ButtonReleaseMask
					| ExposureMask
					| KeyPressMask
					| KeyReleaseMask
					| PointerMotionMask
					| ResizeRedirectMask
					| StructureNotifyMask
					;

			m_window = XCreateWindow(m_display
									, root
									, 0, 0
									, ENTRY_DEFAULT_WIDTH, ENTRY_DEFAULT_HEIGHT, 0, depth
									, InputOutput
									, visual
									, CWBorderPixel|CWEventMask
									, &windowAttrs
									);

			XMapWindow(m_display, m_window);
			XStoreName(m_display, m_window, "BGFX");

			bgfx::x11SetDisplayWindow(m_display, m_window);

			MainThreadEntry mte;
			mte.m_argc = _argc;
			mte.m_argv = _argv;

			bx::Thread thread;
			thread.init(mte.threadFunc, &mte);

			while (!m_exit)
			{
				if (XPending(m_display) )
				{
					XEvent event;
					XNextEvent(m_display, &event);

					switch (event.type)
					{
						case Expose:
							break;

						case ConfigureNotify:
							break;

						case ButtonPress:
						case ButtonRelease:
							{
								const XButtonEvent& xbutton = event.xbutton;
								MouseButton::Enum mb;
								switch (xbutton.button)
								{
									case Button1: mb = MouseButton::Left;   break;
									case Button2: mb = MouseButton::Middle; break;
									case Button3: mb = MouseButton::Right;  break;
									default:      mb = MouseButton::None;   break;
								}

								if (MouseButton::None != mb)
								{
									m_eventQueue.postMouseEvent(xbutton.x
										, xbutton.y
										, mb
										, event.type == ButtonPress
										);
								}
							}
							break;

						case MotionNotify:
							{
								const XMotionEvent& xmotion = event.xmotion;
								m_eventQueue.postMouseEvent(xmotion.x
										, xmotion.y
										);
							}
							break;

						case KeyPress:
						case KeyRelease:
							{
								XKeyEvent& xkey = event.xkey;
								KeySym keysym = XLookupKeysym(&xkey, 0);
								switch (keysym)
								{
								case XK_Meta_L:    setModifier(Modifier::LeftMeta,   KeyPress == event.type); break;
								case XK_Meta_R:    setModifier(Modifier::RightMeta,  KeyPress == event.type); break;
								case XK_Control_L: setModifier(Modifier::LeftCtrl,   KeyPress == event.type); break;
								case XK_Control_R: setModifier(Modifier::RightCtrl,  KeyPress == event.type); break;
								case XK_Shift_L:   setModifier(Modifier::LeftShift,  KeyPress == event.type); break;
								case XK_Shift_R:   setModifier(Modifier::RightShift, KeyPress == event.type); break;
								case XK_Alt_L:     setModifier(Modifier::LeftAlt,    KeyPress == event.type); break;
								case XK_Alt_R:     setModifier(Modifier::RightAlt,   KeyPress == event.type); break;

								default:
									{
										Key::Enum key = fromXk(keysym);
										if (Key::None != key)
										{
											m_eventQueue.postKeyEvent(key, m_modifiers, KeyPress == event.type);
										}
									}
									break;
								}
							}
							break;

						case ResizeRequest:
							{
								const XResizeRequestEvent& xresize = event.xresizerequest;
								XResizeWindow(m_display, m_window, xresize.width, xresize.height);
							}
							break;
					}
				}
			}

			thread.shutdown();

			XUnmapWindow(m_display, m_window);
			XDestroyWindow(m_display, m_window);

			return EXIT_SUCCESS;
		}
int XMessageBox::show()
{
   if (mDisplay == NULL)
      return -1;

   int retVal = 0;
   retVal = loadFont();
   if (retVal < 0)
      return retVal;

   // set the maximum window dimensions
   mScreenWidth = DisplayWidth(mDisplay, DefaultScreen(mDisplay));
   mScreenHeight = DisplayHeight(mDisplay, DefaultScreen(mDisplay));
   mMaxWindowWidth = min(mScreenWidth, MessageBox_MaxWinWidth);
   mMaxWindowHeight = min(mScreenHeight, MessageBox_MaxWinHeight);

   // split the message into a vector of lines
   splitMessage();

   // set the dialog dimensions
   setDimensions();

   mWin = XCreateSimpleWindow(
      mDisplay,
      DefaultRootWindow(mDisplay),
      (mScreenWidth - mMBWidth) / 2,  (mScreenHeight - mMBHeight) / 2,
      mMBWidth, mMBHeight,
      1, 
      BlackPixel(mDisplay, DefaultScreen(mDisplay)),
      WhitePixel(mDisplay, DefaultScreen(mDisplay)));

   mGC = XCreateGC(mDisplay, mWin, 0, 0);

   XSetFont(mDisplay, mGC, mFS->fid);

   // set input mask
   XSelectInput(mDisplay, mWin, 
      ExposureMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask);

   // set wm protocols in case they hit X
   Atom wm_delete_window = 
      XInternAtom(mDisplay, "WM_DELETE_WINDOW", False);
   Atom wm_protocols = 
      XInternAtom(mDisplay, "WM_PROTOCOLS", False);
   XSetWMProtocols (mDisplay, mWin, &wm_delete_window, 1);
   // set pop up dialog hint
   XSetTransientForHint(mDisplay, mWin, mWin);
   
   // set title
   XTextProperty wtitle;
   wtitle.value = (unsigned char *)mTitle;
   wtitle.encoding = XA_STRING;
   wtitle.format = 8;
   wtitle.nitems = strlen(mTitle);
   XSetWMName(mDisplay, mWin, &wtitle);

   // show window
   XMapWindow(mDisplay, mWin);
   // move it in case some bozo window manager repositioned it
   XMoveWindow(mDisplay, mWin, 
      (mScreenWidth - mMBWidth) / 2,  (mScreenHeight - mMBHeight) / 2);
   // raise it to top
   XRaiseWindow(mDisplay, mWin);

   XMessageBoxButton* clickedButton = NULL;
   XEvent event;
   Vector<XMessageBoxButton>::iterator iter;
   bool done = false;
   while (!done)
   {
      XNextEvent(mDisplay, &event);
      switch (event.type)
      {
         case Expose:
            repaint();
            break;
         case MotionNotify:
            for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
               iter->setMouseCoordinates(event.xmotion.x, event.xmotion.y);
            break;
         case ButtonPress:
            for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
            {
               if (iter->pointInRect(event.xbutton.x, event.xbutton.y))
               {
                  iter->setMouseDown(true);
                  iter->setMouseCoordinates(event.xbutton.x, event.xbutton.y);
                  break;
               }
            }
            break;
         case ButtonRelease:
            for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
            {
               if (iter->pointInRect(event.xbutton.x, event.xbutton.y) &&
                  iter->isMouseDown())
               {
                  // we got a winner!
                  clickedButton = iter;
                  done = true;
                  break;
               }
            }
            if (clickedButton == NULL)
            {
               // user released outside a button.  clear the button states
               for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
                  iter->setMouseDown(false);
            }
            break;
         case ClientMessage:
            if (event.xclient.message_type == wm_protocols &&
               event.xclient.data.l[0] == static_cast<long>(wm_delete_window))
               done = true;
            break;
      }
      repaint();
   }

   XUnmapWindow(mDisplay, mWin);
   XDestroyWindow(mDisplay, mWin);
   XFreeGC(mDisplay, mGC);
   XFreeFont(mDisplay, mFS);

   if (clickedButton != NULL)
      return clickedButton->getClickVal();
   else
      return -1;
}
Exemple #16
0
int main(int i_iArg_Count, const char * i_lpszArg_Values[])
{
	bool	bWindow_Debugging_Mode = false;
	bool	bCtrl_Key = false;
	bool	bShift_Key = false;
	bool	bF12_Key = false;
	std::vector<std::thread> vThread_List;

	if (!g_lpMain)
	{
		std::cerr << "No main class instantiated.  Exiting." << std::endl;
		exit(1);
	}
	Initialize_Circle_Vectors();
	XInitThreads();
	//printf("%i %i %i %i %i %i %i\n",MAIN::MB_LEFT, MAIN::MB_CTR, MAIN::MB_RGT, MAIN::MB_SCROLL_V, MAIN::MB_SCROLL_H, MAIN::MB_X1, MAIN::MB_X2);
	// Open the display

	g_lpMain->init();

	g_lpdpyDisplay = XOpenDisplay(NIL);
	assert(g_lpdpyDisplay);


	bool	bFirst_Draw = true;
	GLint                   iAttributeList[] = { GLX_RGBA, GLX_RED_SIZE,8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8, GLX_DOUBLEBUFFER, None };
//	GLint                   iAttributeList[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8, GLX_DOUBLEBUFFER, None };
//	GLint                   iAttributeList[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
//	printf("root\n");
	g_wRoot = DefaultRootWindow(g_lpdpyDisplay);
	XVisualInfo * lpXVisual = glXChooseVisual(g_lpdpyDisplay, DefaultScreen(g_lpdpyDisplay),iAttributeList);
	GLint uiAttribs_Test[] = {GLX_USE_GL, GLX_RGBA, GLX_DOUBLEBUFFER, GLX_DEPTH_SIZE, GLX_STENCIL_SIZE, GLX_RED_SIZE, GLX_GREEN_SIZE, GLX_BLUE_SIZE, GLX_ALPHA_SIZE, None};
	
//	for (unsigned int uiI = 0; uiAttribs_Test[uiI] != None; uiI++)
//	{
//		int uiVal;
//		glXGetConfig(g_lpdpyDisplay,lpXVisual,uiAttribs_Test[uiI],&uiVal);
//		printf("%i: %i\n",uiI,uiVal);
//	}

	Colormap cmap = XCreateColormap(g_lpdpyDisplay, g_wRoot, lpXVisual->visual, AllocNone);
	XSetWindowAttributes    swa;
	swa.colormap = cmap;
	swa.event_mask = StructureNotifyMask|ExposureMask|PointerMotionMask|ButtonPressMask|ButtonReleaseMask|KeyPressMask|KeyReleaseMask|EnterWindowMask|LeaveWindowMask;
//	printf("window\n");

	Window wRoot;
	int iX,iY;
	unsigned int uiWidth,uiHeight,uiBorder_Width,uiDepth;
	XGetGeometry(g_lpdpyDisplay, g_wRoot, &wRoot, &iX, &iY, &uiWidth, &uiHeight, &uiBorder_Width, &uiDepth);

	g_wWindow = XCreateWindow(g_lpdpyDisplay, g_wRoot, 0, 0, uiWidth - 2*uiBorder_Width, uiHeight - 2*uiBorder_Width, 0, lpXVisual->depth, InputOutput, lpXVisual->visual, CWColormap | CWEventMask, &swa);

	// capture WM_DELETE_WINDOW messages from the server - we want to shut down cleanly
	Atom aWM_Delete_Window = XInternAtom(g_lpdpyDisplay, "WM_DELETE_WINDOW", False);
	XSetWMProtocols(g_lpdpyDisplay, g_wWindow, &aWM_Delete_Window, 1);

	XMapWindow(g_lpdpyDisplay,g_wWindow);
	if (g_lpMain && g_lpMain->Get_Window_Name().size() > 0)
		XStoreName(g_lpdpyDisplay, g_wWindow, g_lpMain->Get_Window_Name().c_str());
//	printf("glx\n");
	g_glc = glXCreateContext(g_lpdpyDisplay, lpXVisual, 0, GL_TRUE);
	 glXMakeCurrent(g_lpdpyDisplay, g_wWindow, g_glc);

		printf("Vendor: %s\n",glGetString(GL_VENDOR));
		printf("Renderer: %s\n",glGetString(GL_RENDERER));
		printf("Version: %s\n",glGetString(GL_VERSION));
		printf("SL Version: %s\n",glGetString(GL_SHADING_LANGUAGE_VERSION));

	std::map<std::string,int> vstrGL_Extensions_list;

	std::string szExtensions = glXQueryExtensionsString(g_lpdpyDisplay,0);
	GLint iNum_Ext;
	PFNGLGETSTRINGIPROC glGetStringi = (PFNGLGETSTRINGIPROC)glXGetProcAddress((GLubyte *)"glGetStringi");
	if (glGetStringi)
	{
		glGetIntegerv(GL_NUM_EXTENSIONS,&iNum_Ext);
		unsigned int uiMax = iNum_Ext - 1;
		for (unsigned int uiI = 0; uiI < uiMax; uiI++)
		{
			if (glGetStringi(GL_EXTENSIONS,uiI))
			{
				vstrGL_Extensions_list[std::string((char *)glGetStringi(GL_EXTENSIONS,uiI))] = 1;
			}
		}
	}
	if (!szExtensions.empty())
	{
		size_t sEnd = szExtensions.find_first_of(' ');
		size_t sLast = 0;
		while (sEnd != std::string::npos)
		{
			vstrGL_Extensions_list[szExtensions.substr(sLast,(sEnd - sLast))] = 1;
			sLast = sEnd + 1;
			sEnd = szExtensions.find_first_of(' ',sLast);
		}
		vstrGL_Extensions_list[szExtensions.substr(sLast,(szExtensions.size() - sLast))] = 1;
	}
//	for (std::vector<std::string>::iterator cI = vstrGL_Extensions_list.begin(); cI != vstrGL_Extensions_list.end(); cI++)
//	{
//		printf("%s\n",cI->c_str());
//	}
	if (vstrGL_Extensions_list.count("GLX_EXT_swap_control") > 0)
	{
		PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
		glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) glXGetProcAddress((GLubyte *)"glXSwapIntervalEXT");
		GLXDrawable drawable = glXGetCurrentDrawable();
		if (glXSwapIntervalEXT)
			glXSwapIntervalEXT(g_lpdpyDisplay,drawable,0);
	}
	else if (vstrGL_Extensions_list.count("GLX_SGI_swap_control") > 0)
	{
		PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI;
		glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress((GLubyte *)"glXSwapIntervalSGI");
		glXSwapIntervalSGI(1);
	}
	else if (vstrGL_Extensions_list.count("MESA_swap_control") > 0)
	{
		PFNGLXSWAPINTERVALMESAPROC glXSwapIntervalMESA;
		glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC) glXGetProcAddress((GLubyte *)"glXSwapIntervalMESA");
		glXSwapIntervalMESA(1);
	}


	// We want to get MapNotify events
//	XSelectInput(g_lpdpyDisplay, g_wWindow, StructureNotifyMask|ExposureMask|PointerMotionMask|ButtonPressMask|ButtonReleaseMask||KeyPressMask|KeyReleaseMask|EnterWindowMask|LeaveWindowMask);


	vThread_List.push_back(std::thread(Main_Timer_Loop));
	vThread_List.push_back(std::thread(Gfx_Loop));

	std::vector<XButtonEvent> veButton_Events;
	bool	bReady_To_Process_Buttons = true;
	do
	{
		while (XEventsQueued(g_lpdpyDisplay,QueuedAfterFlush) > 0)
		{
			XEvent	evEvent;
			XNextEvent(g_lpdpyDisplay,&evEvent);
			switch (evEvent.type)
			{
			case KeyRelease:
				if (bWindow_Debugging_Mode)
					printf("Event loop Key %i \n",evEvent.xkey.keycode);
				switch (Key_Map(XLookupKeysym(&evEvent.xkey,0)))
				{
				case MAIN::KEY_RCTRL:
					bCtrl_Key = false;
					break;
				case MAIN::KEY_RSHIFT:
					bShift_Key = false;
					break;
				case MAIN::KEY_F12:
					bF12_Key = false;
					break;
				}
				g_lpMain->On_Key_Up(Key_Map(XLookupKeysym(&evEvent.xkey,0)),0,0, 0, 1);
				break;
			case KeyPress:
				switch (Key_Map(XLookupKeysym(&evEvent.xkey,0)))
				{
				case MAIN::KEY_RCTRL:
					bCtrl_Key = true;
					break;
				case MAIN::KEY_RSHIFT:
					bShift_Key = true;
					break;
				case MAIN::KEY_F12:
					bF12_Key = true;
					break;
				}
				if (bCtrl_Key && bShift_Key && bF12_Key)
				{
					bWindow_Debugging_Mode = !bWindow_Debugging_Mode;
					printf("Debugging mode %s\n",bWindow_Debugging_Mode ? "Enabled" : "Disabled");
				}

				if (bWindow_Debugging_Mode)
					printf("Event loop Key %i \n",evEvent.xkey.keycode);
				g_lpMain->On_Key_Down(Key_Map(XLookupKeysym(&evEvent.xkey,0)),0,0, 0, 0);
				break;
		// Mouse operations
			case ButtonPress:
			case ButtonRelease:
				if (bWindow_Debugging_Mode)
					printf("Event loop Button %i (%i,%i)\n",Mouse_Button_Map(evEvent.xbutton.button), Fix_Coordinate_Window(PAIR<unsigned int>(evEvent.xbutton.x, evEvent.xbutton.y)).m_tX,Fix_Coordinate_Window(PAIR<unsigned int>(evEvent.xbutton.x, evEvent.xbutton.y)).m_tY);
				bReady_To_Process_Buttons = (XEventsQueued(g_lpdpyDisplay,QueuedAfterFlush) == 0);
				if (!bReady_To_Process_Buttons)
				{
				
					XEvent evNext;
					// peek at the next event; if it is a button
					XPeekEvent(g_lpdpyDisplay,&evNext); 
					bReady_To_Process_Buttons = ((evNext.type != ButtonPress && evNext.type != ButtonRelease) || ((evNext.type == ButtonPress || evNext.type == ButtonRelease) && evEvent.xbutton.button != evNext.xbutton.button) || ((evNext.type == ButtonPress || evNext.type == ButtonRelease) && (evEvent.xbutton.button == Button4 || evEvent.xbutton.button == Button5 || evEvent.xbutton.button == 6 || evEvent.xbutton.button == 7))); // process immediately if different buttons are pressed or if button 4,5,6, or 7 is pressed
					if (!bReady_To_Process_Buttons)
					{
						veButton_Events.push_back(evEvent.xbutton);
					}
				}
				if (bReady_To_Process_Buttons)
				{
					if (veButton_Events.size() > 0)
					{
						if (veButton_Events.size() == 4 &&
							veButton_Events[0].type == ButtonPress && 
							veButton_Events[1].type == ButtonRelease &&
							veButton_Events[2].type == ButtonPress &&
							veButton_Events[3].type == ButtonRelease &&
							veButton_Events[0].button == veButton_Events[1].button &&
							veButton_Events[0].button == veButton_Events[2].button &&
							veButton_Events[0].button == veButton_Events[3].button &&
							(veButton_Events[3].time - veButton_Events[0].time) < 500) //@@TODO make this user selectable
						{ // double click detected
							g_lpMain->On_Mouse_Button_Double_Click(Mouse_Button_Map(veButton_Events[0].button), Fix_Coordinate_Window(PAIR<unsigned int>(veButton_Events[0].x, veButton_Events[0].y)));
						}
						else
						{
							for (std::vector<XButtonEvent>::const_iterator cI = veButton_Events.begin(); cI != veButton_Events.end(); cI++)
							{
								if (cI->type == ButtonPress)
								{
									g_lpMain->On_Mouse_Button_Down(Mouse_Button_Map(cI->button), Fix_Coordinate_Window(PAIR<unsigned int>(cI->x, cI->y)));
								}
								else
								{
									g_lpMain->On_Mouse_Button_Up(Mouse_Button_Map(cI->button), Fix_Coordinate_Window(PAIR<unsigned int>(cI->x, cI->y)));
								}
							}
						}
						veButton_Events.clear();
					}
					else if (evEvent.type == ButtonPress)
					{
						g_lpMain->On_Mouse_Button_Down(Mouse_Button_Map(evEvent.xbutton.button), Fix_Coordinate_Window(PAIR<unsigned int>(evEvent.xbutton.x, evEvent.xbutton.y)));
					}
					else
					{
						g_lpMain->On_Mouse_Button_Up(Mouse_Button_Map(evEvent.xbutton.button), Fix_Coordinate_Window(PAIR<unsigned int>(evEvent.xbutton.x, evEvent.xbutton.y)));
					}
				}
				break;
			case MotionNotify:
				if (bWindow_Debugging_Mode)
					printf("Event loop Motion\n");
				g_lpMain->On_Mousemove(Fix_Coordinate_Window(PAIR<unsigned int>(evEvent.xmotion.x, evEvent.xmotion.y)));
				break;
	// Mouse wheel events not supported under X windows
	//		case WM_MOUSEWHEEL:
	//			g_lpMain->on_mouse_wheel(MAIN::MB_SCROLL_V, (short)(wParam >> 16), GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
	//			break;
	//		case WM_MOUSEHWHEEL:
	//			g_lpMain->on_mouse_wheel(MAIN::MB_SCROLL_V, (short)(wParam >> 16), GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
	//			break;
			case Expose:
			case GraphicsExpose:
				if (bWindow_Debugging_Mode)
					printf("Event loop Expose\n");
				g_lpMain->On_Window_Move(Fix_Coordinate_Global(PAIR<unsigned int>(evEvent.xexpose.x,evEvent.xexpose.y)));
				g_lpMain->On_Window_Resize(PAIR<unsigned int>(evEvent.xexpose.width,evEvent.xexpose.height));
				if (!bFirst_Draw)
					g_lpMain->gfx_reshape(g_lpMain->Get_Window_Size());
				g_lpMain->Request_Refresh();
				break;
		    case ConfigureNotify:
				if (bWindow_Debugging_Mode)
					printf("Event loop Configure %i %i\n",evEvent.xconfigure.event, evEvent.xconfigure.window);
				g_lpMain->On_Window_Move(Fix_Coordinate_Global(PAIR<unsigned int>(evEvent.xconfigure.x,evEvent.xconfigure.y)));
				g_lpMain->On_Window_Resize(PAIR<unsigned int>(evEvent.xconfigure.width,evEvent.xconfigure.height));
				if (!bFirst_Draw)
					g_lpMain->gfx_reshape(g_lpMain->Get_Window_Size());
				g_lpMain->Request_Refresh();
		        break;
	 		case DestroyNotify:
				if (bWindow_Debugging_Mode)
					printf("Event loop Destroy\n");
				g_lpMain->Request_Quit();
				break;
			case MapNotify:
				if (bWindow_Debugging_Mode)
					printf("Event loop Map Notify\n");
				g_lpMain->Request_Refresh();
				break;
			case ReparentNotify:
				// don't care
				break;
			case PropertyNotify:
				// may care - ignore for now...
				//printf("Property %i %i\n",evEvent.xproperty.atom,evEvent.xproperty.state);
				break;
			case KeymapNotify:
				// may care - ignore for now...
				//printf("Keymap %i %i\n",evEvent.xkeymap.key_vector[0],evEvent.xkeymap.key_vector[1]);
				break;
			case ClientMessage:
				if (bWindow_Debugging_Mode)
					printf("Event loop Client Message\n");
				if ((Atom)evEvent.xclient.data.l[0] == aWM_Delete_Window)
					g_lpMain->Request_Quit();
				break;
			case EnterNotify:
				g_lpMain->Gain_Focus();
				break;
			case LeaveNotify:
				g_lpMain->Lose_Focus();
				break;
			default:
				if (bWindow_Debugging_Mode)
					printf("Event %i\n",evEvent.type);
				break;
			}
		}
	}
	while (!g_lpMain->Pending_Quit());
	for (std::vector<std::thread>::iterator cI = vThread_List.begin(); cI != vThread_List.end(); cI++)
	{
		cI->join();
	}
	
	glXDestroyContext(g_lpdpyDisplay, g_glc);

	//XFreeGC(g_lpdpyDisplay, gc);
	XDestroyWindow(g_lpdpyDisplay,g_wWindow);
	XCloseDisplay(g_lpdpyDisplay);	
	return 0;
}
Exemple #17
0
int main(int argc, char** argv)
{
   if (argc==1)
   {
      printf("Error need 1 argument\n");
   }
   else if (argc > 1) {
      FILE* f=fopen(argv[1],"rb");
      unsigned size=0;
      char* b=NULL;
      fseek(f,0,SEEK_END);
      size=ftell(f);
      fseek(f,0,SEEK_SET);
      b=(char*)malloc(size);
      size=fread((void*)b,1,size,f);
      printf("Buffering %u bytes\n",size);
      fclose(f);
      test_gif=load_gif_from_stream((int8_t*)b,size);
      
      free(b);
      
      if (test_gif)
      {
         #if defined(GIF_WINAPI)
         MSG msg;
         BOOL quit=FALSE;
         const int mode=GIF_MODE_BITMAP;
         registerTestGifWin(GetModuleHandle(NULL));
         gifWnd=CreateWindow("TestGifWin",
                              argv[1],
                              WS_OVERLAPPEDWINDOW,100,100,
                              test_gif->screen_descriptor.width + 16,
                              test_gif->screen_descriptor.height + 32,
                              NULL,NULL,
                              NULL,NULL);
         
         gif_init_screen(test_gif,mode,(void*)GetDC(gifWnd));        
         #elif defined(GIF_X11)
         /*XImage* ximg=NULL;*/
         const int mode=GIF_MODE_RGBA;
         int quit=0;
         Atom wm_delete_window;
         XEvent report;
         gif_init_screen(test_gif,mode,NULL); 
         dis = XOpenDisplay(NULL);
         win = XCreateSimpleWindow(dis, 
                                   RootWindow(dis, 0), 
                                   100, 
                                   100, 
                                   test_gif->screen_descriptor.width, 
                                   test_gif->screen_descriptor.height,
                                   0, 
                                   0xFFFFFF, 
                                   0x2A2A2A);
         XMapWindow(dis, win);
         XFlush(dis);
         XSelectInput (dis, win, ExposureMask | KeyPressMask | ButtonPressMask);
         XStoreName(dis, win, argv[1]);
         wm_delete_window = XInternAtom (dis, "WM_DELETE_WINDOW", False);
         /*ximg = XCreateImage(dis,
                             NULL,
                             0,
                             XYPixmap,
                             0,
                             (char*) test_gif->screen,
                             test_gif->screen_descriptor.width,
                             test_gif->screen_descriptor.height,
                             32,
                             test_gif->screen_descriptor.width*test_gif->screen_descriptor.height*4);*/
         
         #endif  
         switch (gif_draw_frame(test_gif->screen,test_gif, 0,test_gif->previous,mode))
         {
            case GIF_ERROR_NULL:
               printf("Gif draw error : GIF NULL\n");
               break;
            case GIF_ERROR_BAD_INDEX:
               printf("Gif draw error : GIF BAD INDEX\n");
               break;
         }

         
         printf("Load %s success !\n",argv[1]);
         
         #if defined(GIF_WINAPI)
         ShowWindow(gifWnd,SW_SHOW);
         while ( !quit )
         {
            while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
            {
               if ( msg.message == WM_QUIT )
               {
                  quit = TRUE;
               }
               TranslateMessage(&msg);
               DispatchMessage(&msg);
            }
            Sleep(20);
         }

         DestroyWindow(gifWnd);
         #elif defined(GIF_X11)
         while ( !quit )  {
           XNextEvent(dis, &report);
           switch  (report.type) {
             case ClientMessage :
                if ((Atom) report.xclient.data.l[0] == wm_delete_window)
                  quit = 1;
                break;
             case Expose:
                XClearWindow (dis, win);
                
                break;
             }
         }
         XDestroyWindow(dis,win);
         #endif
         delete_gif(test_gif);
        
      }
      else
      {
         printf("Load %s error %d !\n",argv[1],gif_get_last_error());
         switch (gif_get_last_error())
         {
            case GIF_ERROR_SIGNATURE:
               printf("GIF_ERROR_SIGNATURE\n");
               break;
            case GIF_ERROR_BAD_BLOCK:
               printf("GIF_ERROR_BAD_BLOCK\n");
               break;
            case GIF_ERROR_SIZE:
               printf("GIF_ERROR_SIZE\n");
               break;
            case GIF_ERROR_BAD_COMPRESSION:
               printf("GIF_ERROR_BAD_COMPRESSION\n");
               break;
            case GIF_ERROR_BAD_INDEX:
               printf("GIF_ERROR_BAD_INDEX\n");
               break;
            case GIF_ERROR_NULL:
               printf("GIF_ERROR_NULL\n");
               break;
            case GIF_ERROR_UNKNOW_EXTENSION:
               printf("GIF_ERROR_UNKNOW_EXTENSION\n");
               break;
            default:
               break;
         }
      }
      
   }
   return 0;
}
Exemple #18
0
void
free_node(TextNode *node, short int des)
{

  if (node == NULL)
    return;

  switch (node->type) {
  case Paste:
    free_pastearea(node, des);
    free_node(node->next, des);
    break;
  case Pastebutton:
    free_pastebutton(node, des);
    free_node(node->next, des);
    break;
  case Ifcond:
    free_node(node->data.ifnode->cond, des);
    free_node(node->data.ifnode->thennode, des);
    free_node(node->data.ifnode->elsenode, des);
    break;
  case Dash:
  case Lsquarebrace:
  case Word:
  case WindowId:
  case Punctuation:
  case Lbrace:
  case Rbrace:
  case SimpleBox:
  case Verbatim:
  case Math:
  case Spadsrctxt:
  case Spadsrc:
    free_if_non_NULL(node->data.text);
    free_node(node->next, des);
    break;
  case Inputstring:
    if (des)
      delete_item(node->data.text);
    free_if_non_NULL(node->data.text);
    free_node(node->next, des);
    break;
  case It:
  case Sl:
  case Tt:
  case Rm:
  case Emphasize:
  case Beep:
  case BoldFace:
  case Par:
  case Newline:
  case Horizontalline:
  case Item:
  case Beginscroll:
  case Endscroll:
  case Group:
  case Table:
  case Macro:
  case Pound:
  case Center:
  case Box:
  case Mbox:
  case Tableitem:
  case Scrollingnode:
  case Headernode:
  case Titlenode:
  case Footernode:
  case Controlbitmap:
  case Fi:
  case Description:
  case Rsquarebrace:
  case Endpaste:
  case Endpastebutton:
    free_node(node->next, des);
    break;
  case Inputbitmap:
  case Inputpixmap:
    free_if_non_NULL(node->data.text);
    free_node(node->next, des);
    break;
  case Quitbutton:
  case Helpbutton:
  case Upbutton:
  case Returnbutton:
    if (des && node->link->win) {
      hash_delete(gWindow->page->fLinkHashTable,(char *) &node->link->win);
      XDestroyWindow(gXDisplay, node->link->win);
    }
    free_if_non_NULL(node->link);
    free_node(node->next, des);
    break;
  case Memolink:
  case Downlink:
  case Windowlink:
  case Link:
  case Lisplink:
  case Lispwindowlink:
  case Spadcall:
  case Spadcallquit:
  case LispMemoLink:
  case Lispcommand:
  case Lispcommandquit:
  case LispDownLink:
  case Unixlink:
  case Spadlink:
  case Spadmemolink:
  case Spaddownlink:
  case Unixcommand:
  case Spadcommand:
  case Spadgraph:
    if (des && node->link->win) {
      hash_delete(gWindow->page->fLinkHashTable,(char *) &node->link->win);
      XDestroyWindow(gXDisplay, node->link->win);
    }
    /* TTT don't free the link before freeing nodes off it */
    /*  free_node(node->link->reference.node);*/
    free_if_non_NULL(node->link);
    free_node(node->next, des);
    break;
  case Free:
  case Indent:
  case Indentrel:
  case HSpace:
  case Space:
  case VSpace:
  case Button:
  case Bound:
  case Tab:
    free_node(node->next, des);
    free_node(node->data.node, des);
    break;
  case End:
  case Endcenter:
  case Endlink:
  case Endgroup:
  case Endbox:
  case Endmbox:
  case Endspadcommand:
  case Endpix:
  case Endmacro:
  case Endparameter:
  case Endtable:
  case Endtableitem:
  case Noop:
  case Endinputbox:
  case Enddescription:
  case Endif:
  case Endtitems:
  case Enditems:
  case Endverbatim:
  case Endmath:
  case Endspadsrc:
    free_node(node->next, des);
    break;
  case Endheader:
  case Endtitle:
  case Endfooter:
  case Endscrolling:
  case Endarg:
    break;
  case Endbutton:
  case Beginitems:
    free_if_non_NULL(node->data.text);
    free_node(node->next, des);
    break;

  default:

    /*        printf("don't know how to free type %d\n", node->type); */
    return;
  }
  free(node);
}
Exemple #19
0
 ~EglDrawable() {
     eglDestroySurface(eglDisplay, surface);
     eglWaitClient();
     XDestroyWindow(display, window);
     eglWaitNative(EGL_CORE_NATIVE_ENGINE);
 }
Exemple #20
0
/** Documented at declaration */
int
view_glx(struct view* view)
{    
    // Open display
    view->glx_display = XOpenDisplay(0);
    if ( view->glx_display == NULL ) {
        fprintf(stderr, "Failed to open X display!\n");
        pthread_exit(0);
    }

    // Choose visual
    static int attributes[] = {
        GLX_RGBA,
        GLX_DOUBLEBUFFER,
        GLX_RED_SIZE,   1,
        GLX_GREEN_SIZE, 1,
        GLX_BLUE_SIZE,  1,
        None
    };
    XVisualInfo* visual = glXChooseVisual(view->glx_display, DefaultScreen(view->glx_display), attributes);
    if ( visual == NULL ) {
        fprintf(stderr, "Failed to choose visual!\n");
        pthread_exit(0);
    }

    // Create OpenGL context
    view->glx_context = glXCreateContext(view->glx_display, visual, 0, GL_TRUE);
    if ( view->glx_context == NULL ) {
        fprintf(stderr, "Failed to create OpenGL context!\n");
        pthread_exit(0);
    }

    // Create window
    Colormap colormap = XCreateColormap(view->glx_display, RootWindow(view->glx_display, visual->screen), visual->visual, AllocNone);
    XSetWindowAttributes swa;
    swa.colormap = colormap;
    swa.border_pixel = 0;
    swa.event_mask = KeyPressMask;
    view->glx_window = XCreateWindow(
        view->glx_display, 
        RootWindow(view->glx_display, visual->screen), 
        0, 0, view->window_width, view->window_height,
        0, visual->depth, InputOutput, visual->visual,
        CWBorderPixel | CWColormap | CWEventMask, 
        &swa
    );
    XStoreName(view->glx_display, view->glx_window, "OpenGL and CUDA interoperability");
    XMapWindow(view->glx_display, view->glx_window);
    
    view_opengl_attach(view);
    view_init(view);
    
    while ( 1 ) {
        view_glx_render(view);
        
        XEvent event;
        if ( XCheckWindowEvent(view->glx_display, view->glx_window, KeyPressMask, &event)) {
            int keycode = (int)event.xkey.keycode;
            char* key = XKeysymToString(XKeycodeToKeysym(view->glx_display, keycode, 0));
            if ( view_glx_keyboard(keycode, key) != 0 )
                break;
        }
    }
    
    view_opengl_detach(view);
    
    // Cleanup
    glXDestroyContext(view->glx_display, view->glx_context);
    XDestroyWindow(view->glx_display, view->glx_window);
    XCloseDisplay(view->glx_display);

    return 0;
}
Exemple #21
0
int main(int argc, char** argv)
{
    Display* dpy = XOpenDisplay(NULL);
    if (dpy == NULL)
    {
        fprintf(stderr, "Cannot open display\n");
        exit(1);
    }

    int s = DefaultScreen(dpy);
    Window win = XCreateSimpleWindow(dpy, RootWindow(dpy, s), 10, 10, 660, 200, 1,
                                     BlackPixel(dpy, s), WhitePixel(dpy, s));
    XSelectInput(dpy, win, ExposureMask | KeyPressMask);
    XMapWindow(dpy, win);

#if defined(__APPLE_CC__)
    XStoreName(dpy, win, "Geeks3D.com - X11 window under Mac OS X (Lion)");
#else
    XStoreName(dpy, win, "Geeks3D.com - X11 window under Linux (Mint 10)");
#endif

    Atom WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);

    bool uname_ok = false;
    struct utsname sname;
    int ret = uname(&sname);
    if (ret != -1)
    {
        uname_ok = true;
    }

    XEvent e;
    while (1)
    {
        XNextEvent(dpy, &e);
        if (e.type == Expose)
        {
            int y_offset = 20;

#if defined(__APPLE_CC__)
            const char* s1 = "X11 test app under Mac OS X Lion";
#else
            const char* s1 = "X11 test app under Linux";
#endif

            const char* s2 = "(C)2012 Geeks3D.com";
            XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, s1, strlen(s1));
            y_offset += 20;
            XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, s2, strlen(s2));
            y_offset += 20;

            if (uname_ok)
            {
                char buf[256] = {0};

                sprintf(buf, "System information:");
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- System: %s", sname.sysname);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- Release: %s", sname.release);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- Version: %s", sname.version);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- Machine: %s", sname.machine);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 20;
            }


            XWindowAttributes  wa;
            XGetWindowAttributes(dpy, win, &wa);
            int width = wa.width;
            int height = wa.height;
            char buf[128]= {0};
            sprintf(buf, "Current window size: %dx%d", width, height);
            XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
            y_offset += 20;
        }

        if (e.type == KeyPress)
        {
            char buf[128] = {0};
            KeySym keysym;
            int len = XLookupString(&e.xkey, buf, sizeof buf, &keysym, NULL);
            if (keysym == XK_Escape)
                break;
        }

        if ((e.type == ClientMessage) &&
                (static_cast<unsigned int>(e.xclient.data.l[0]) == WM_DELETE_WINDOW))
        {
            break;
        }
    }

    XDestroyWindow(dpy, win);
    XCloseDisplay(dpy);
    return 0;
}
Exemple #22
0
void Wind::localoff()
  {
  XDeleteContext(dsp,gtwin(),wins);
  XDestroyWindow(dsp,gtwin());
  }
Exemple #23
0
static void gfx_ctx_xegl_destroy(void *data)
{
   (void)data;

   x11_destroy_input_context(&g_xim, &g_xic);

   if (g_egl_dpy)
   {
      if (g_egl_ctx)
      {
         eglMakeCurrent(g_egl_dpy, EGL_NO_SURFACE,
               EGL_NO_SURFACE, EGL_NO_CONTEXT);
         eglDestroyContext(g_egl_dpy, g_egl_ctx);
      }

      if (g_egl_hw_ctx)
         eglDestroyContext(g_egl_dpy, g_egl_hw_ctx);

      if (g_egl_surf)
         eglDestroySurface(g_egl_dpy, g_egl_surf);
      eglTerminate(g_egl_dpy);
   }

   g_egl_ctx     = NULL;
   g_egl_hw_ctx  = NULL;
   g_egl_surf    = NULL;
   g_egl_dpy     = NULL;
   g_egl_config  = 0;

   if (g_win)
   {
      /* Save last used monitor for later. */
#ifdef HAVE_XINERAMA
      XWindowAttributes target;
      Window child;

      int x = 0, y = 0;
      XGetWindowAttributes(g_dpy, g_win, &target);
      XTranslateCoordinates(g_dpy, g_win, RootWindow(g_dpy, DefaultScreen(g_dpy)),
            target.x, target.y, &x, &y, &child);

      g_screen = x11_get_xinerama_monitor(g_dpy, x, y,
            target.width, target.height);

      RARCH_LOG("[X/EGL]: Saved monitor #%u.\n", g_screen);
#endif

      XUnmapWindow(g_dpy, g_win);
      XDestroyWindow(g_dpy, g_win);
      g_win = None;
   }

   if (g_cmap)
   {
      XFreeColormap(g_dpy, g_cmap);
      g_cmap = None;
   }

   if (g_should_reset_mode)
   {
      x11_exit_fullscreen(g_dpy, &g_desktop_mode);
      g_should_reset_mode = false;
   }

   /* Do not close g_dpy. We'll keep one for the entire application 
    * lifecycle to work-around nVidia EGL limitations.
    */
   g_inited = false;
}
bool
NativeStateX11::create_window(WindowProperties const& properties)
{
    static const char *win_name("glmark2 "GLMARK_VERSION);

    if (!xdpy_) {
        Log::error("Error: X11 Display has not been initialized!\n");
        return false;
    }

    /* Recreate an existing window only if it has actually been resized */
    if (xwin_) {
        if (properties_.fullscreen != properties.fullscreen ||
            (properties.fullscreen == false &&
             (properties_.width != properties.width ||
              properties_.height != properties.height)))
        {
            XDestroyWindow(xdpy_, xwin_);
            xwin_ = 0;
        }
        else
        {
            return true;
        }
    }

    /* Set desired attributes */
    properties_.fullscreen = properties.fullscreen;
    properties_.visual_id = properties.visual_id;

    if (properties_.fullscreen) {
        /* Get the screen (root window) size */
        XWindowAttributes window_attr;
        XGetWindowAttributes(xdpy_, RootWindow(xdpy_, DefaultScreen(xdpy_)), 
                             &window_attr);
        properties_.width = window_attr.width;
        properties_.height = window_attr.height;
    }
    else {
        properties_.width = properties.width;
        properties_.height = properties.height;
    }

    XVisualInfo vis_tmpl;
    XVisualInfo *vis_info = 0;
    int num_visuals;

    /* The X window visual must match the supplied visual id */
    vis_tmpl.visualid = properties_.visual_id;
    vis_info = XGetVisualInfo(xdpy_, VisualIDMask, &vis_tmpl,
                             &num_visuals);
    if (!vis_info) {
        Log::error("Error: Could not get a valid XVisualInfo!\n");
        return false;
    }

    Log::debug("Creating XWindow W: %d H: %d VisualID: 0x%x\n",
               properties_.width, properties_.height, vis_info->visualid);

    /* window attributes */
    XSetWindowAttributes attr;
    unsigned long mask;
    Window root = RootWindow(xdpy_, DefaultScreen(xdpy_));

    attr.background_pixel = 0;
    attr.border_pixel = 0;
    attr.colormap = XCreateColormap(xdpy_, root, vis_info->visual, AllocNone);
    attr.event_mask = KeyPressMask;
    mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

    xwin_ = XCreateWindow(xdpy_, root, 0, 0, properties_.width, properties_.height,
                          0, vis_info->depth, InputOutput,
                          vis_info->visual, mask, &attr);

    XFree(vis_info);

    if (!xwin_) {
        Log::error("Error: XCreateWindow() failed!\n");
        return false;
    }

    /* set hints and properties */
    Atom fs_atom = None;
    if (properties_.fullscreen) {
        fs_atom = XInternAtom(xdpy_, "_NET_WM_STATE_FULLSCREEN", True);
        if (fs_atom == None)
            Log::debug("Warning: Could not set EWMH Fullscreen hint.\n");
    }
    if (fs_atom != None) {
        XChangeProperty(xdpy_, xwin_,
                        XInternAtom(xdpy_, "_NET_WM_STATE", True),
                        XA_ATOM, 32, PropModeReplace,
                        reinterpret_cast<unsigned char*>(&fs_atom),  1);
    }
    else {
        XSizeHints sizehints;
        sizehints.min_width  = properties_.width;
        sizehints.min_height = properties_.height;
        sizehints.max_width  = properties_.width;
        sizehints.max_height = properties_.height;
        sizehints.flags = PMaxSize | PMinSize;

        XSetWMProperties(xdpy_, xwin_, NULL, NULL,
                         NULL, 0, &sizehints, NULL, NULL);
    }

    /* Set the window name */
    XStoreName(xdpy_ , xwin_,  win_name);

    /* Gracefully handle Window Delete event from window manager */
    Atom wmDelete = XInternAtom(xdpy_, "WM_DELETE_WINDOW", True);
    XSetWMProtocols(xdpy_, xwin_, &wmDelete, 1);

    return true;
}
Exemple #25
0
int
main(int argc, char **argv) {
    char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
    char buf[32], passwd[256], passdisp[256];
    int num, screen, width, height, update, sleepmode, term, pid;

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

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

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

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


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

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

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

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

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

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

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

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

    font = XLoadQueryFont(dpy, fontname);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                break;
            }

            update = True; // show changes
        }
    }

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

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


    XUngrabPointer(dpy, CurrentTime);
    XFreePixmap(dpy, pmap);
    XFreeFont(dpy, font);
    XFreeGC(dpy, gc);
    XDestroyWindow(dpy, w);
    XCloseDisplay(dpy);
    return 0;
}
Exemple #26
0
int main(int argc, char **argv)
{
    XEvent          evt;
    Colormap        colormap;
    struct timeval  tv;
    int             screenNumber;
    long            eventMask;
    unsigned long   white;
    unsigned long   black;
    Status          rc;
    int             iters;
    int             opt;
    int             draw_lines;
    int             draw_rects;
    int             draw_stipples;
    int             draw_fonts;
    int             draw_image;
    int             zero_counters;
    int             scroll_type;
    char            image_file[256];
    char            proxy_app[256];
    char            msg[4096];

    // set some defaults
    g_winWidth = 640;
    g_winHeight = 480;
    iters = 5000;
    draw_lines = 1;
    draw_rects = 1;
    draw_stipples = 1;
    draw_fonts = 1;
    draw_image = 1;
    g_delay_dur = 1000;
    scroll_type = SCROLL_SMOOTH1;
    zero_counters = 0;
    strcpy(image_file, "yosemite.bmp");
    strcpy(msg, "To be or not to be!");

    // process cmd line args
    opterr = 0;
    while ((opt = getopt(argc, argv, "lrsg:c:f:i:d:o:z:")) != -1)
    {
        switch (opt)
        {
        case 'g':
            if (sscanf(optarg, "%dx%d", &g_winWidth, &g_winHeight) != 2) {
                fprintf(stderr, "\nerror: invalid geometry specified\n\n");
                usage();
                return -1;
            }
            break;

        case 'c':
            if (sscanf(optarg, "%d", &iters) != 1) {
                fprintf(stderr, "\nerror: invalid count specified\n\n");
                usage();
                return -1;
            }
            break;

        case 'l':
            draw_lines = 1;
            draw_rects = 0;
            draw_stipples = 0;
            draw_fonts = 0;
            draw_image = 0;
            break;

        case 'r':
            draw_rects = 1;
            draw_lines = 0;
            draw_stipples = 0;
            draw_fonts = 0;
            draw_image = 0;
            break;

        case 's':
            draw_stipples = 1;
            draw_lines = 0;
            draw_rects = 0;
            draw_fonts = 0;
            draw_image = 0;
            break;

        case 'f':
            if (strlen(optarg) <= 0) {
                fprintf(stderr, "\nerror: -f option requires an argument\n\n");
                usage();
                return -1;
            }
            draw_fonts = 1;
            strncpy(msg, optarg, 4096);
            draw_lines = 0;
            draw_rects = 0;
            draw_stipples = 0;
            draw_image = 0;
            break;

        case 'i':
            if (strlen(optarg) <= 0) {
                fprintf(stderr, "\nerror: -i option requires an argument\n\n");
                usage();
                return -1;
            }
            draw_image = 1;
            strncpy(image_file, optarg, 255);
            draw_lines = 0;
            draw_rects = 0;
            draw_stipples = 0;
            draw_fonts = 0;
            break;

        case 'h':
            usage();
            return 0;
            break;

        case 'v':
            printf("xdemo Ver 1.0\n");
            return 0;
            break;

        case 'd':
            if (sscanf(optarg, "%d", &g_delay_dur) != 1) {
                fprintf(stderr, "\nerror: -d option requires an argument\n\n");
                usage();
                return -1;
            }
            break;

        case 'z':
            if (strlen(optarg) <= 0) {
                fprintf(stderr, "\nerror: invalid proxy application specified\n\n");
                usage();
                return -1;
            }
            strcpy(proxy_app, optarg);
	    printf("##### LK_TODO: proxy_app=%s\n", proxy_app);
            zero_counters = 1;
            break;

        case 'o':
            if (strcmp(optarg, "jump") == 0) {
                scroll_type = SCROLL_JUMP;
            }
            else if (strcmp(optarg, "smooth1") == 0) {
                scroll_type = SCROLL_SMOOTH1;
            }
            else if (strcmp(optarg, "smooth2") == 0) {
                scroll_type = SCROLL_SMOOTH2;
            }
            else if (strcmp(optarg, "smooth3") == 0) {
                scroll_type = SCROLL_SMOOTH3;
            }
            else if (strcmp(optarg, "smooth4") == 0) {
                scroll_type = SCROLL_SMOOTH4;
            }
            else {
                fprintf(stderr, "\ninvalid scroll type specified\n\n");
                usage();
                return -1;
            }
            break;

        default:
            usage();
            return -1;
        }
    }

    // must have at least one operation
    if ((!draw_lines) && (!draw_rects) && (!draw_stipples) &&
        (!draw_fonts) && (!draw_image)) {
        usage();
        return -1;
    }

    g_disp = XOpenDisplay(NULL);
    if (!g_disp) {
        dprint("error opening X display\n");
        exit(-1);
    }

    screenNumber = DefaultScreen(g_disp);
    white = WhitePixel(g_disp, screenNumber);
    black = BlackPixel(g_disp, screenNumber);

    g_win = XCreateSimpleWindow(g_disp,
                                DefaultRootWindow(g_disp),
                                50, 50,                  // origin
                                g_winWidth, g_winHeight, // size
                                0, black,                // border
                                white );                 // backgd

    XMapWindow(g_disp, g_win);
    //eventMask = StructureNotifyMask | MapNotify | VisibilityChangeMask;
    eventMask = StructureNotifyMask | VisibilityChangeMask;
    XSelectInput(g_disp, g_win, eventMask);

    g_gc = XCreateGC(g_disp, g_win,
        0,                       // mask of values
        NULL );                  // array of values
    #if 0
    do
    {
        dprint("about to call XNextEvent(...)\n");
        XNextEvent(g_disp, &evt);// calls XFlush
        dprint("returned from XNextEvent(...)\n");
    }
    //while(evt.type != MapNotify);
    while(evt.type != VisibilityNotify);
    #endif

    // get access to the screen's color map
    colormap = DefaultColormap(g_disp, screenNumber);

    // alloc red color
    rc = XAllocNamedColor(g_disp, colormap, "red", &g_colors[0], &g_colors[0]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'red' color.\n");
        exit(1);
    }

    rc = XAllocNamedColor(g_disp, colormap, "green", &g_colors[1], &g_colors[1]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'green' color.\n");
        exit(1);
    }

    rc = XAllocNamedColor(g_disp, colormap, "blue", &g_colors[2], &g_colors[2]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'blue' color.\n");
        exit(1);
    }
    rc = XAllocNamedColor(g_disp, colormap, "yellow", &g_colors[3], &g_colors[3]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'yellow' color.\n");
        exit(1);
    }
    rc = XAllocNamedColor(g_disp, colormap, "orange", &g_colors[4], &g_colors[4]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'orange' color.\n");
        exit(1);
    }

    if (zero_counters) {
        signal_tcp_proxy(proxy_app);
    }

    if (draw_lines) {
        start_timer(&tv);
        drawLines(iters);
        printf("drew %d lines in %d ms\n", iters, time_elapsed_ms(tv));
    }

    if (draw_rects) {
        start_timer(&tv);
        drawRectangles(iters);
        printf("drew %d rects in %d ms\n", iters, time_elapsed_ms(tv));
    }

    if (draw_stipples) {
        start_timer(&tv);
        // LK_TODO
    }

    if (draw_fonts) {
        start_timer(&tv);
    	drawFont(iters, msg);
        printf("drew %d strings in %d ms\n", iters, time_elapsed_ms(tv));
    }

    if (draw_image) {
        start_timer(&tv);
        drawBMP(image_file, scroll_type);
        printf("drew BMP in %d ms\n", time_elapsed_ms(tv));
    }

    if (zero_counters) {
        signal_tcp_proxy(proxy_app);
    }

    eventMask = ButtonPressMask|ButtonReleaseMask;

    XSelectInput(g_disp, g_win, eventMask);

    do
    {
        XNextEvent(g_disp, &evt); // calls XFlush()
    }
    while(evt.type != ButtonRelease);

    XDestroyWindow(g_disp, g_win);
    XCloseDisplay(g_disp);

    return 0;
}
Exemple #27
0
/*--------------------------------------------------------------------------
**  Purpose:        Windows thread.
**
**  Parameters:     Name        Description.
**
**  Returns:        Nothing.
**
**------------------------------------------------------------------------*/
void *windowThread(void *param)
    {
    GC gc;
    KeySym key;
    KeySym modList[2];
    Pixmap pixmap;
    XEvent event;
    XWMHints wmhints;
    int screen, depth;
    char text[30];
    unsigned long fg, bg;
    int len;
    XWindowAttributes a;
    XColor b,c;
    static int refreshCount = 0;
    char str[2] = " ";
    DispList *curr;
    DispList *end;
    u8 oldFont = 0;
    Atom targetProperty;
    Atom retAtom;
    Atom wmDeleteWindow;
    int retFormat;
    int retStatus;
    unsigned long retRemaining;
    unsigned long retLength; 
    int usageDisplayCount = 0;

    /*
    **  Open the X11 display.
    */
    disp = XOpenDisplay(0);
    if (disp == (Display *) NULL)
        {
        fprintf(stderr, "Could not open display\n");
        exit(1);
        }

    screen = DefaultScreen(disp);

    /*
    **  Create a window using the following hints.
    */
    width = 1100;
    height = 750;

    bg = BlackPixel(disp, screen);
    fg = WhitePixel(disp, screen);

    window = XCreateSimpleWindow (disp, DefaultRootWindow(disp),
        10, 10, width, height, 5, fg, bg);

    /*
    **  Create a pixmap for background image generation.
    */
    depth = DefaultDepth (disp, screen);
    pixmap = XCreatePixmap (disp, window, width, height, depth);

    /*
    **  Set window and icon titles.
    */
    XSetStandardProperties (disp, window, DtCyberVersion " - " DtCyberCopyright " - " DtCyberLicense,
        DtCyberVersion, None, NULL, 0, NULL);

    /*
    **  Create the graphics contexts for window and pixmap.
    */
    gc = XCreateGC (disp, window, 0, 0);

    /*
    **  We don't want to get Expose events, otherwise every XCopyArea will generate one,
    **  and the event queue will fill up. This application will discard them anyway, but
    **  it is better not to generate them in the first place.
    */
    XSetGraphicsExposures(disp, gc, FALSE);

    /*
    **  Load three Cyber fonts.
    */
    hSmallFont = XLoadFont(disp, "-*-lucidatypewriter-medium-*-*-*-10-*-*-*-*-*-*-*\0");
    hMediumFont = XLoadFont(disp, "-*-lucidatypewriter-medium-*-*-*-14-*-*-*-*-*-*-*\0");
    hLargeFont = XLoadFont(disp, "-*-lucidatypewriter-medium-*-*-*-24-*-*-*-*-*-*-*\0");

    /*
    **  Setup fore- and back-ground colors.
    */
    XGetWindowAttributes(disp,window,&a);
    XAllocNamedColor(disp, a.colormap,"green",&b,&c);
    fg=b.pixel;
    bg = BlackPixel(disp, screen);
    XSetBackground(disp, gc, bg);
    XSetForeground(disp, gc, fg);

    /*
    **  Create mappings of some ALT-key combinations to strings.
    */
    modList[0] = XK_Meta_L;
    XRebindKeysym(disp, '0', modList, 1, (u8 *)"$0", 2);
    XRebindKeysym(disp, '1', modList, 1, (u8 *)"$1", 2);
    XRebindKeysym(disp, '2', modList, 1, (u8 *)"$2", 2);
    XRebindKeysym(disp, '3', modList, 1, (u8 *)"$3", 2);
    XRebindKeysym(disp, '4', modList, 1, (u8 *)"$4", 2);
    XRebindKeysym(disp, '5', modList, 1, (u8 *)"$5", 2);
    XRebindKeysym(disp, '6', modList, 1, (u8 *)"$6", 2);
    XRebindKeysym(disp, '7', modList, 1, (u8 *)"$7", 2);
    XRebindKeysym(disp, '8', modList, 1, (u8 *)"$8", 2);
    XRebindKeysym(disp, '9', modList, 1, (u8 *)"$9", 2);
    XRebindKeysym(disp, 'c', modList, 1, (u8 *)"$c", 2);
    XRebindKeysym(disp, 'C', modList, 1, (u8 *)"$c", 2);
    XRebindKeysym(disp, 'e', modList, 1, (u8 *)"$e", 2);
    XRebindKeysym(disp, 'E', modList, 1, (u8 *)"$e", 2);
    XRebindKeysym(disp, 'x', modList, 1, (u8 *)"$x", 2);
    XRebindKeysym(disp, 'X', modList, 1, (u8 *)"$x", 2);
    XRebindKeysym(disp, 'p', modList, 1, (u8 *)"$p", 2);
    XRebindKeysym(disp, 'P', modList, 1, (u8 *)"$p", 2);

    /*
    **  Initialise input.
    */
    wmhints.flags = InputHint;
    wmhints.input = True;
    XSetWMHints(disp, window, &wmhints);
    XSelectInput (disp, window, KeyPressMask | KeyReleaseMask | StructureNotifyMask);

    /*
    **  We like to be on top.
    */
    XMapRaised (disp, window);

    /*
    **  Create atom for paste operations,
    */
    targetProperty = XInternAtom(disp, "DtCYBER", False);

    /*
    **  Create atom for delete message and set window manager.
    */
    wmDeleteWindow = XInternAtom(disp, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(disp, window, &wmDeleteWindow, 1);

    /*
    **  Window thread loop.
    */
    displayActive = TRUE;
    while(displayActive)
        {
        /*
        **  Process paste buffer one character a time.
        */
        if (lpClipToKeyboardPtr != NULL)
            {
            if (clipToKeyboardDelay != 0)
                {
                /*
                **  Delay after CR.
                */
                clipToKeyboardDelay -= 1;
                }
            else
                {
                ppKeyIn = *lpClipToKeyboardPtr++;
                if (ppKeyIn == 0)
                    {
                    /*
                    **  All paste data has been processed - clean up.
                    */
                    XFree(lpClipToKeyboard);
                    lpClipToKeyboard = NULL;
                    lpClipToKeyboardPtr = NULL;
                    }
                else if (ppKeyIn == '\n')
                    {
                    /*
                    **  Substitute to a CR to be able to handle DOS/Windows or UNIX style
                    **  line terminators.
                    */
                    ppKeyIn = '\r';

                    /*
                    **  Short delay to allow PP program to process the line. This may
                    **  require customisation.
                    */
                    clipToKeyboardDelay = 30;
                    }
                else if (ppKeyIn == '\r')
                    {
                    /*
                    **  Ignore CR.
                    */
                    ppKeyIn = 0;
                    }
                }
            }

        /*
        **  Process any X11 events.
        */
        while (XEventsQueued(disp, QueuedAfterReading))
            {
            XNextEvent(disp, &event);

            switch (event.type)
                {
            case ClientMessage:
                if (event.xclient.data.l[0] == wmDeleteWindow)
                    {
                    /*
                    **  Initiate display of usage note because user attempts to close the window.
                    */
                    usageDisplayCount = 5 * FramesPerSecond;
                    }

                break;

            case MappingNotify:
                XRefreshKeyboardMapping ((XMappingEvent *)&event);
                refresh = TRUE;
                break;

            case ConfigureNotify:
                if (event.xconfigure.width > width || event.xconfigure.height > height)
                    {
                    /*
                    **  Reallocate pixmap only if it has grown.
                    */
                    width = event.xconfigure.width;
                    height = event.xconfigure.height;
                    XFreePixmap (disp, pixmap);
                    pixmap = XCreatePixmap (disp, window, width, height, depth);
                    }

                XFillRectangle (disp, pixmap, gc, 0, 0, width, height);
                refresh = TRUE;
                break;

            case KeyPress:
                len = XLookupString ((XKeyEvent *)&event, text, 10, &key, 0);
                if (len == 1)
                    {
                    ppKeyIn = text[0];
                    usleep(5000);
                    }
                else if (len == 2 && text[0] == '$')
                    {
                    switch (text[1])
                        {
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        traceMask ^= (1 << (text[1] - '0'));
                        break;

                    case 'c':
                        traceMask ^= (1 << 14);
                        break;

                    case 'e':
                        traceMask ^= (1 << 15);
                        break;

                    case 'x':
                        if (traceMask == 0)
                            {
                            traceMask = ~0;
                            }
                        else
                            {
                            traceMask = 0;
                            }
                        break;

                    case 'p':
                        if (lpClipToKeyboardPtr != NULL)
                            {
                            /*
                            **  Ignore paste request when a previous one is still executing.
                            */
                            break;
                            }

                        if (targetProperty == None)
                            {
                            /*
                            **  The paste operation atom has not been created. This is bad, but
                            **  not fatal, so we silently ignore paste requests.
                            */
                            break;
                            }
    
                        /*
                        **  Request the server to send an event to the present owner of the selection,
                        **  asking the owner to convert the data in the selection to the required type.
                        */
                        XConvertSelection(disp, XA_PRIMARY, XA_STRING, targetProperty, window, event.xbutton.time);
                        break;
                        }
                    }
                break;

            case KeyRelease:
                len = XLookupString((XKeyEvent *)&event, text, 10, &key, 0);
                if (len == 1)
                    {
                    switch (text[0])
                        {
                    default:
                        break;
                        }
                    }

                break;

            case SelectionNotify:
                /*
                **  The present owner of the selection has replied.
                */
                if (event.xselection.property != targetProperty)
                    {
                    /*
                    **  The current selection is not a string, so we ignore it.
                    */
                    break;
                    }

                /*
                **  Fetch up to 1 kb from the selection.
                */
                retStatus = XGetWindowProperty(disp, window, event.xselection.property,
                    0L, 1024, False, AnyPropertyType, &retAtom, &retFormat, 
                    &retLength, &retRemaining, &lpClipToKeyboard);

                if (retStatus == Success)
                    {
                    lpClipToKeyboardPtr = lpClipToKeyboard;
                    }
                else
                    {
                    lpClipToKeyboard = NULL;
                    lpClipToKeyboardPtr = NULL;
                    }

                break;
                }
            }

        /*
        **  Process any refresh request.
        */
        XSetForeground (disp, gc, fg);

        XSetFont(disp, gc, hSmallFont);
        oldFont = FontSmall;

#if CcCycleTime
        {
        extern double cycleTime;
        char buf[80];

        sprintf(buf, "Cycle time: %.3f", cycleTime);
        XDrawString(disp, pixmap, gc, 0, 10, buf, strlen(buf));
        }
#endif

#if CcDebug == 1
        {
        char buf[160];

        /*
        **  Display P registers of PPUs and CPU and current trace mask.
        */
        sprintf(buf, "Refresh: %-10d  PP P-reg: %04o %04o %04o %04o %04o %04o %04o %04o %04o %04o   CPU P-reg: %06o",
            refreshCount++,
            ppu[0].regP, ppu[1].regP, ppu[2].regP, ppu[3].regP, ppu[4].regP,
            ppu[5].regP, ppu[6].regP, ppu[7].regP, ppu[8].regP, ppu[9].regP,
            cpu.regP); 

        sprintf(buf + strlen(buf), "   Trace: %c%c%c%c%c%c%c%c%c%c%c%c",
            (traceMask >> 0) & 1 ? '0' : '_',
            (traceMask >> 1) & 1 ? '1' : '_',
            (traceMask >> 2) & 1 ? '2' : '_',
            (traceMask >> 3) & 1 ? '3' : '_',
            (traceMask >> 4) & 1 ? '4' : '_',
            (traceMask >> 5) & 1 ? '5' : '_',
            (traceMask >> 6) & 1 ? '6' : '_',
            (traceMask >> 7) & 1 ? '7' : '_',
            (traceMask >> 8) & 1 ? '8' : '_',
            (traceMask >> 9) & 1 ? '9' : '_',
            (traceMask >> 14) & 1 ? 'C' : '_',
            (traceMask >> 15) & 1 ? 'E' : '_');

        XDrawString(disp, pixmap, gc, 0, 10, buf, strlen(buf));
        }
#endif

        if (opActive)
            {
            /*
            **  Display pause message.
            */
            static char opMessage[] = "Emulation paused";
            XSetFont(disp, gc, hLargeFont);
            oldFont = FontLarge;
            XDrawString(disp, pixmap, gc, 20, 256, opMessage, strlen(opMessage));
            }

        /*
        **  Protect display list.
        */
        pthread_mutex_lock(&mutexDisplay);

        if (usageDisplayCount != 0)
            {
            /*
            **  Display usage note when user attempts to close window.
            */
            static char usageMessage1[] = "Please don't just close the window, but instead first cleanly halt the operating system and";
            static char usageMessage2[] = "then use the 'shutdown' command in the operator interface to terminate the emulation.";
            XSetFont(disp, gc, hMediumFont);
            oldFont = FontMedium;
            XDrawString(disp, pixmap, gc, 20, 256, usageMessage1, strlen(usageMessage1));
            XDrawString(disp, pixmap, gc, 20, 275, usageMessage2, strlen(usageMessage2));
            listEnd = 0;
            usageDisplayCount -= 1;
            }

        /*
        **  Draw display list in pixmap.
        */
        curr = display;
        end = display + listEnd;

        for (curr = display; curr < end; curr++)
            {
            /*
            **  Setup new font if necessary.
            */
            if (oldFont != curr->fontSize)
                {
                oldFont = curr->fontSize;

                switch (oldFont)
                    {
                case FontSmall:
                    XSetFont(disp, gc, hSmallFont);
                    break;

                case FontMedium:
                    XSetFont(disp, gc, hMediumFont);
                    break;

                case FontLarge:
                    XSetFont(disp, gc, hLargeFont);
                    break;
                    }
                }

            /*
            **  Draw dot or character.
            */
            if (curr->fontSize == FontDot)
                {
                XDrawPoint(disp, pixmap, gc, curr->xPos, (curr->yPos * 14) / 10 + 20);
                }
            else
                {
                str[0] = curr->ch;
                XDrawString(disp, pixmap, gc, curr->xPos, (curr->yPos * 14) / 10 + 20, str, 1);
                }
            }

        listEnd = 0;
        currentX = -1;
        currentY = -1;
        refresh = FALSE;

        /*
        **  Release display list.
        */
        pthread_mutex_unlock (&mutexDisplay);

        /*
        **  Update display from pixmap.
        */
        XCopyArea(disp, pixmap, window, gc, 0, 0, width, height, 0, 0);

        /*
        **  Erase pixmap for next round.
        */
        XSetForeground (disp, gc, bg);
        XFillRectangle (disp, pixmap, gc, 0, 0, width, height);

        /*
        **  Make sure the updates make it to the X11 server.
        */
        XSync(disp, 0);

        /*
        **  Give other threads a chance to run. This may require customisation.
        */
        usleep(FrameTime); 
        }

    XSync(disp, 0);
    XFreeGC (disp, gc);
    XFreePixmap (disp, pixmap);
    XDestroyWindow (disp, window);
    XCloseDisplay (disp);
    pthread_exit(NULL);
    }
Exemple #28
0
int main()
{
    Display *dpy;
    Window root;
    int att[]= {GLX_RGBA,GLX_DEPTH_SIZE,24,GLX_DOUBLEBUFFER,None};
    XVisualInfo *vi;
    Colormap cmap;
    XSetWindowAttributes swa;
    Window win;
    GLXContext glc;
    XWindowAttributes gwa;
    XEvent xev;

    int viewport[4],i;
    char *buf;
    buf=malloc(1500);
    dpy = XOpenDisplay(0);
    if(!dpy) {
        printf("XOpenDisplay failed\n");
        return -1;
    }
    root=DefaultRootWindow(dpy);
    vi=glXChooseVisual(dpy,0,att);
    if(!vi) {
        printf("glXChooseVisual failed\n");
    }

    for(i=0; i<NUM_TRAINS; i++) {
        speed[i]=speedc;
        state[i]=0;
    }

    cmap=XCreateColormap(dpy,root,vi->visual,AllocNone);
    swa.colormap=cmap;
    swa.event_mask=ExposureMask|KeyPressMask|PointerMotionMask;
    win=XCreateWindow(dpy,root,0,0,width,height,0,vi->depth,InputOutput,vi->visual,CWColormap|CWEventMask,&swa);
    XMapWindow(dpy,win);
    glc=glXCreateContext(dpy,vi,NULL,GL_TRUE);
    glXMakeCurrent(dpy,win,glc);
    sprintf(buf,"%s",glGetString(GL_VENDOR));
    XStoreName(dpy,win,buf);
    glEnable(GL_DEPTH_TEST);
    XGetWindowAttributes(dpy,win,&gwa);
    glViewport(0,0,gwa.width,gwa.height);
    glGetIntegerv(GL_VIEWPORT,viewport);
    glColor3ub(255,255,255);
    while(1) {
        while (XPending(dpy) > 0)
        {
            XNextEvent(dpy,&xev);
//		if(xev.type == Expose){
            /*			glMatrixMode(GL_PROJECTION);
            			glLoadIdentity();
            			glMatrixMode(GL_MODELVIEW);
            			glLoadIdentity();*/
//		}else
            if(xev.type == KeyPress) {
                if(xev.xkey.type==KeyPress) {
                    switch(xev.xkey.keycode) {
                    case 9:
                        glXMakeCurrent(dpy,None,0);
                        glXDestroyContext(dpy,glc);
                        XDestroyWindow(dpy,win);
                        XCloseDisplay(dpy);
                        free(buf);
                        return 0;
                    case 0x41: //spacebar

                        break;
                    default:
                        sprintf(buf,"%04X",xev.xkey.keycode);
                    }
                } else {
                    switch(xev.xkey.keycode) {
                    default:
                        sprintf(buf,"%04X",xev.xkey.keycode);
                    }
                }
            } else if(xev.type == MotionNotify) { //mousebutton
                x=(xev.xmotion.x*2.0)/width-1;
                y=1-(xev.xmotion.y*2.0)/height;
            }
        }
//sprintf(buf,"%.2f:%.2f %u",train[0][0],train[0][1],state[0]);
//	XStoreName(dpy,win,buf);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        draw(GL_RENDER);
        glFinish();
        glXSwapBuffers(dpy, win);
    }
    return 0;
}
Exemple #29
0
Eina_Bool
engine_software_16_x11_args(const char *engine, int width, int height)
{
   XSetWindowAttributes attr;
   XClassHint chint;
   XSizeHints szhints;
   Evas_Engine_Info_Software_16_X11 *einfo;
   int i;

   disp = XOpenDisplay(NULL);
   if (!disp) return EINA_FALSE;

   evas_output_method_set(evas, evas_render_method_lookup("software_16_x11"));
   einfo = (Evas_Engine_Info_Software_16_X11 *)evas_engine_info_get(evas);
   if (!einfo)
     {
	printf("Evas does not support the Software 16bit X11 Engine\n");
	goto close_display;
     }

   einfo->info.display = disp;
   attr.backing_store = NotUseful;
   attr.colormap = DefaultColormap(disp, DefaultScreen(disp));
   attr.border_pixel = 0;
   attr.background_pixmap = None;
   attr.event_mask =
     ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
     StructureNotifyMask | EnterWindowMask | LeaveWindowMask |
     KeyPressMask | KeyReleaseMask;
   attr.bit_gravity = ForgetGravity;
   win = XCreateWindow(disp, DefaultRootWindow(disp),
		       0, 0, width, height, 0,
		       DefaultDepth(disp, DefaultScreen(disp)), InputOutput,
		       DefaultVisual(disp, DefaultScreen(disp)),
		       CWBackingStore | CWColormap |
		       CWBackPixmap | CWBorderPixel |
		       CWBitGravity | CWEventMask,
		       &attr);
   if (!win)
     goto close_display;

   einfo->info.drawable = win;
   if (!evas_engine_info_set(evas, (Evas_Engine_Info *) einfo))
     {
	printf("Evas can not setup the informations of the Software 16bit X11 Engine\n");
	goto destroy_window;
     }

   if (fullscreen)
     {
        Atom prop  = XInternAtom(disp, "_NET_WM_STATE", False);
        Atom state = XInternAtom(disp, "_NET_WM_STATE_FULLSCREEN", False);
        unsigned long data = state;
        XChangeProperty(disp, win, prop, XA_ATOM, 32, PropModeReplace, 
                        &data, 1);
     }
   
   XStoreName(disp, win, "Expedite - Evas Test Suite");
   chint.res_name = "expedite";
   chint.res_class = "Expedite";
   XSetClassHint(disp, win, &chint);
   szhints.flags = PMinSize | PMaxSize | PSize | USSize;
   szhints.min_width = szhints.max_width = width;
   szhints.min_height = szhints.max_height = height;
   XSetWMNormalHints(disp, win, &szhints);
   XMapWindow(disp, win);
   XSync(disp, False);
   while (!first_expose)
     engine_software_16_x11_loop();
   return EINA_TRUE;

 destroy_window:
   XDestroyWindow(disp, win);
 close_display:
   XCloseDisplay(disp);

   return EINA_FALSE;
}
Exemple #30
0
void DestroyVScrollBar(struct XObj *xobj)
{
  XFreeFont(dpy,xobj->xfont);
  XFreeGC(dpy,xobj->gc);
  XDestroyWindow(dpy,xobj->win);
}