/* ===============================================================
 *
 *                          DEMO
 *
 * ===============================================================*/
int
main(void)
{
    long dt;
    long started;
    int running = 1;
    int status;
    XWindow xw;
    struct rawfb_context *rawfb;
    void *fb = NULL;
    unsigned char tex_scratch[512 * 512];

    /* X11 */
    memset(&xw, 0, sizeof xw);
    xw.dpy = XOpenDisplay(NULL);
    if (!xw.dpy) die("Could not open a display; perhaps $DISPLAY is not set?");

    xw.root = DefaultRootWindow(xw.dpy);
    xw.screen = XDefaultScreen(xw.dpy);
    xw.vis = XDefaultVisual(xw.dpy, xw.screen);
    xw.cmap = XCreateColormap(xw.dpy,xw.root,xw.vis,AllocNone);
    xw.swa.colormap = xw.cmap;
    xw.swa.event_mask =
        ExposureMask | KeyPressMask | KeyReleaseMask |
        ButtonPress | ButtonReleaseMask| ButtonMotionMask |
        Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
        PointerMotionMask | KeymapStateMask | EnterWindowMask | LeaveWindowMask;
    xw.win = XCreateWindow(xw.dpy, xw.root, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
        XDefaultDepth(xw.dpy, xw.screen), InputOutput,
        xw.vis, CWEventMask | CWColormap, &xw.swa);

    XStoreName(xw.dpy, xw.win, "X11");
    XMapWindow(xw.dpy, xw.win);
    XGetWindowAttributes(xw.dpy, xw.win, &xw.attr);
    xw.width = (unsigned int)xw.attr.width;
    xw.height = (unsigned int)xw.attr.height;

    /* Framebuffer emulator */
    status = nk_xlib_init(xw.dpy, xw.vis, xw.screen, xw.win, xw.width, xw.height, &fb);
    if (!status || !fb)
        return 0;

    /* GUI */
    rawfb = nk_rawfb_init(fb, tex_scratch, xw.width, xw.height, xw.width * 4);
    if (!rawfb) running = 0;

    #ifdef INCLUDE_STYLE
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/
    #endif

    while (running) {
        /* Input */
        XEvent evt;
        started = timestamp();
        nk_input_begin(&rawfb->ctx);
        while (XCheckWindowEvent(xw.dpy, xw.win, xw.swa.event_mask, &evt)) {
            if (XFilterEvent(&evt, xw.win)) continue;
            nk_xlib_handle_event(xw.dpy, xw.screen, xw.win, &evt, rawfb);
        }
        nk_input_end(&rawfb->ctx);

        /* GUI */
        if (nk_begin(&rawfb->ctx, "Demo", nk_rect(50, 50, 200, 200),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|
            NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE)) {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;

            nk_layout_row_static(&rawfb->ctx, 30, 80, 1);
            if (nk_button_label(&rawfb->ctx, "button"))
                fprintf(stdout, "button pressed\n");
            nk_layout_row_dynamic(&rawfb->ctx, 30, 2);
            if (nk_option_label(&rawfb->ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(&rawfb->ctx, "hard", op == HARD)) op = HARD;
            nk_layout_row_dynamic(&rawfb->ctx, 25, 1);
            nk_property_int(&rawfb->ctx, "Compression:", 0, &property, 100, 10, 1);
        }
        nk_end(&rawfb->ctx);
        if (nk_window_is_closed(&rawfb->ctx, "Demo")) break;

        /* -------------- EXAMPLES ---------------- */
        #ifdef INCLUDE_CALCULATOR
          calculator(ctx);
        #endif
        #ifdef INCLUDE_OVERVIEW
          overview(ctx);
        #endif
        #ifdef INCLUDE_NODE_EDITOR
          node_editor(ctx);
        #endif
        /* ----------------------------------------- */

        /* Draw framebuffer */
        nk_rawfb_render(rawfb, nk_rgb(30,30,30), 1);

        /* Emulate framebuffer */
        XClearWindow(xw.dpy, xw.win);
        nk_xlib_render(xw.win);
        XFlush(xw.dpy);

        /* Timing */
        dt = timestamp() - started;
        if (dt < DTIME)
            sleep_for(DTIME - dt);
    }

    nk_rawfb_shutdown(rawfb);
    nk_xlib_shutdown();
    XUnmapWindow(xw.dpy, xw.win);
    XFreeColormap(xw.dpy, xw.cmap);
    XDestroyWindow(xw.dpy, xw.win);
    XCloseDisplay(xw.dpy);
    return 0;
}
Exemple #2
0
void wsCreateWindow( wsTWindow * win,int X,int Y,int wX,int hY,int bW,int cV,unsigned char D,char * label )
{
 int depth;

 win->Property=D;
 if ( D & wsShowFrame ) win->Decorations=1;
 wsHGC=DefaultGC( wsDisplay,wsScreen );
// The window position and size.
 switch ( X )
  {
   case -1: win->X=( wsMaxX / 2 ) - ( wX / 2 ) + wsOrgX; break;
   case -2: win->X=wsMaxX - wX - 1 + wsOrgX; break;
   default: win->X=X; break;
  }
 switch ( Y )
  {
   case -1: win->Y=( wsMaxY / 2 ) - ( hY / 2 ) + wsOrgY; break;
   case -2: win->Y=wsMaxY - hY - 1 + wsOrgY; break;
   default: win->Y=Y; break;
  }
 win->Width=wX;
 win->Height=hY;
 win->OldX=win->X;
 win->OldY=win->Y;
 win->OldWidth=win->Width;
 win->OldHeight=win->Height;

// Border size for window.
 win->BorderWidth=bW;
// Hide Mouse Cursor
 win->wsCursor=None;
 win->wsMouseEventType=cV;
 win->wsCursorData[0]=0;
 win->wsCursorPixmap=XCreateBitmapFromData( wsDisplay,wsRootWin,win->wsCursorData,1,1 );
 if ( !(cV & wsShowMouseCursor) ) win->wsCursor=XCreatePixmapCursor( wsDisplay,win->wsCursorPixmap,win->wsCursorPixmap,&win->wsColor,&win->wsColor,0,0 );

 depth = vo_find_depth_from_visuals( wsDisplay,wsScreen,NULL );
 if ( depth < 15 )
  {
   mp_msg( MSGT_GPLAYER,MSGL_FATAL,MSGTR_WS_ColorDepthTooLow );
   exit( 0 );
  }
 XMatchVisualInfo( wsDisplay,wsScreen,depth,TrueColor,&win->VisualInfo );

// ---
 win->AtomLeaderClient=XInternAtom( wsDisplay,"WM_CLIENT_LEADER",False );
 win->AtomDeleteWindow=XInternAtom( wsDisplay,"WM_DELETE_WINDOW",False );
 win->AtomTakeFocus=XInternAtom( wsDisplay,"WM_TAKE_FOCUS",False );
 win->AtomRolle=XInternAtom( wsDisplay,"WM_WINDOW_ROLE",False );
 win->AtomWMSizeHint=XInternAtom( wsDisplay,"WM_SIZE_HINT",False );
 win->AtomWMNormalHint=XInternAtom( wsDisplay,"WM_NORMAL_HINT",False );
 win->AtomProtocols=XInternAtom( wsDisplay,"WM_PROTOCOLS",False );
 win->AtomsProtocols[0]=win->AtomDeleteWindow;
 win->AtomsProtocols[1]=win->AtomTakeFocus;
 win->AtomsProtocols[2]=win->AtomRolle;
// ---

 win->WindowAttrib.background_pixel=BlackPixel( wsDisplay,wsScreen );
 win->WindowAttrib.border_pixel=WhitePixel( wsDisplay,wsScreen );
 win->WindowAttrib.colormap=XCreateColormap( wsDisplay,wsRootWin,win->VisualInfo.visual,AllocNone );
 win->WindowAttrib.event_mask=StructureNotifyMask | FocusChangeMask |
                              ExposureMask | PropertyChangeMask |
                              EnterWindowMask | LeaveWindowMask |
                              VisibilityChangeMask |
                              KeyPressMask | KeyReleaseMask;
 if ( ( cV & wsHandleMouseButton ) ) win->WindowAttrib.event_mask|=ButtonPressMask | ButtonReleaseMask;
 if ( ( cV & wsHandleMouseMove ) ) win->WindowAttrib.event_mask|=PointerMotionMask;
 win->WindowAttrib.cursor=win->wsCursor;
 win->WindowAttrib.override_redirect=False;
 if ( D & wsOverredirect ) win->WindowAttrib.override_redirect=True;

 win->WindowMask=CWBackPixel | CWBorderPixel |
                 CWColormap | CWEventMask | CWCursor |
                 CWOverrideRedirect;

 win->WindowID=XCreateWindow( wsDisplay,
  (win->Parent != 0?win->Parent:wsRootWin),
  win->X,win->Y,win->Width,win->Height,win->BorderWidth,
  win->VisualInfo.depth,
  InputOutput,
  win->VisualInfo.visual,
  win->WindowMask,&win->WindowAttrib );

 wsClassHint.res_name="MPlayer";

 wsClassHint.res_class="MPlayer";
 XSetClassHint( wsDisplay,win->WindowID,&wsClassHint );

 win->SizeHint.flags=PPosition | PSize | PResizeInc | PWinGravity;// | PBaseSize;
 win->SizeHint.x=win->X;
 win->SizeHint.y=win->Y;
 win->SizeHint.width=win->Width;
 win->SizeHint.height=win->Height;

 if ( D & wsMinSize )
  {
   win->SizeHint.flags|=PMinSize;
   win->SizeHint.min_width=win->Width;
   win->SizeHint.min_height=win->Height;
  }
 if ( D & wsMaxSize )
  {
   win->SizeHint.flags|=PMaxSize;
   win->SizeHint.max_width=win->Width;
   win->SizeHint.max_height=win->Height;
  }

 win->SizeHint.height_inc=1;
 win->SizeHint.width_inc=1;
 win->SizeHint.base_width=win->Width;
 win->SizeHint.base_height=win->Height;
 win->SizeHint.win_gravity=StaticGravity;
 XSetWMNormalHints( wsDisplay,win->WindowID,&win->SizeHint );

 win->WMHints.flags=InputHint | StateHint;
 win->WMHints.input=True;
 win->WMHints.initial_state=NormalState;
 XSetWMHints( wsDisplay,win->WindowID,&win->WMHints );

 wsWindowDecoration( win,win->Decorations );
 XStoreName( wsDisplay,win->WindowID,label );
 XmbSetWMProperties( wsDisplay,win->WindowID,label,label,NULL,0,NULL,NULL,NULL );

 XSetWMProtocols( wsDisplay,win->WindowID,win->AtomsProtocols,3 );
 XChangeProperty( wsDisplay,win->WindowID,
                  win->AtomLeaderClient,
                  XA_WINDOW,32,PropModeReplace,
                  (unsigned char *)&LeaderWindow,1 );

 wsTextProperty.value=label;
 wsTextProperty.encoding=XA_STRING;
 wsTextProperty.format=8;
 wsTextProperty.nitems=strlen( label );
 XSetWMIconName( wsDisplay,win->WindowID,&wsTextProperty );

 win->wGC=XCreateGC( wsDisplay,win->WindowID,
  GCForeground | GCBackground,
  &win->wGCV );

 win->Visible=0;
 win->Focused=0;
 win->Mapped=0;
 win->Rolled=0;
 if ( D & wsShowWindow ) XMapWindow( wsDisplay,win->WindowID );

 wsCreateImage( win,win->Width,win->Height );
// --- End of creating --------------------------------------------------------------------------

 {
  int i;
  for ( i=0;i < wsWLCount;i++ )
   if ( wsWindowList[i] == NULL ) break;
  if ( i == wsWLCount )
   {  mp_msg( MSGT_GPLAYER,MSGL_FATAL,MSGTR_WS_TooManyOpenWindows ); exit( 0 ); }
  wsWindowList[i]=win;
 }

 XFlush( wsDisplay );
 XSync( wsDisplay,False );

 win->ReDraw=NULL;
 win->ReSize=NULL;
 win->Idle=NULL;
 win->MouseHandler=NULL;
 win->KeyHandler=NULL;
 mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"[ws] window is created. ( %s ).\n",label );
}
Exemple #3
0
//! Change window title
void video::show_title()
{
    if(vidtype < 3)
        XStoreName(dpy, win, title);
}
Exemple #4
0
void setWindowTitle()
{
	XStoreName(Xdpy, Xwin, getWindowTitle());
	XSetIconName(Xdpy, Xwin, getWindowTitle());
}
Exemple #5
0
void glutSetWindowTitle(char *title)
{
	XStoreName(dpy, win, title);
}
Exemple #6
0
void set_title(void)
{
    //Set the window title bar.
    XMapWindow(dpy, win);
    XStoreName(dpy, win, "CS335 Lab1 - Sunny Day ");
}
Exemple #7
0
Window::Window(ui::WindowBase & window, Application & application, ui::Pixel width, ui::Pixel height)
:
	application_{&application}
{
	auto display = application_->display_;
	auto & config = application_->configs_[0];

	auto visual_info = glXGetVisualFromFBConfig(display, config);
	if (visual_info == nullptr) throw std::runtime_error{"Unable to obtain VisualInfo"};
	auto && visual_info_guard = data::MakeScopeGuard([&] { XFree(visual_info); });

	colormap_ = XCreateColormap(
		display,
		RootWindow(display, visual_info->screen),
		visual_info->visual, AllocNone);
	auto && colormap_guard = data::MakeScopeGuard([&] { XFreeColormap(display, colormap_); });

	XSetWindowAttributes window_attributes;
	window_attributes.colormap = colormap_;
	window_attributes.background_pixmap = None;
	window_attributes.border_pixel = 0;
	window_attributes.event_mask =
		EnterWindowMask |
		LeaveWindowMask |
		PointerMotionMask |
		ButtonPressMask |
		ButtonReleaseMask |
		KeyPressMask |
		KeyReleaseMask |
		StructureNotifyMask |
		ExposureMask;

	id_ = XCreateWindow(
		display,
		RootWindow(display, visual_info->screen),
		0, 0, width, height, 0, visual_info->depth, InputOutput,
		visual_info->visual,
		CWBorderPixel | CWColormap | CWEventMask, &window_attributes);
	auto && window_guard = data::MakeScopeGuard([&] { XDestroyWindow(display, id_); });

	XSaveContext(display, id_, application_->context_, reinterpret_cast<XPointer>(&window));
	auto && save_context_guard = data::MakeScopeGuard([&] { XDeleteContext(display, id_, application_->context_); });

	XSetWMProtocols(display, id_, &application_->wm_delete_window_, 1);
	XStoreName(display, id_, "Twil Window");
	XMapWindow(display, id_);

	int ContextAttribs[] = {
		GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
		GLX_CONTEXT_MINOR_VERSION_ARB, 3,
#ifndef NDEBUG
		GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB,
#endif
		GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
		None};

	context_ = glXCreateContextAttribsARB(display, config, 0, True, ContextAttribs);
	if (context_ == 0) throw std::runtime_error{"Unable to create OpenGL context"};
	auto && context_guard = data::MakeScopeGuard([&] { glXDestroyContext(display, context_); });

	glXMakeCurrent(display, id_, context_);
	SymbolLoader loader;
	gl::context::Initialize(loader);

#ifndef NDEBUG
	glDebugMessageCallbackARB(HandleDebug, nullptr);
#endif

	save_context_guard.Dismiss();
	context_guard.Dismiss();
	window_guard.Dismiss();
	colormap_guard.Dismiss();
}
Exemple #8
0
int MFDisplay_CreateDisplay(int width, int height, int bpp, int rate, bool vsync, bool triplebuffer, bool wide, bool progressive)
{
	MFCALLSTACK;

	MFZeroMemory(gXKeys, sizeof(gXKeys));
	MFZeroMemory(&gXMouse, sizeof(gXMouse));
	gXMouse.x = -1;

	gDisplay.fullscreenWidth = gDisplay.width = width;
	gDisplay.fullscreenHeight = gDisplay.height = height;
	gDisplay.refreshRate = 0;
	gDisplay.colourDepth = 0; /* Use default.  Chances are, it's something sane */
	gDisplay.windowed = true;
	gDisplay.wide = false;
	gDisplay.progressive = true;

	if(!(xdisplay = XOpenDisplay(NULL)))
	{
		MFDebug_Error("Unable to open display");
		MFDisplay_DestroyDisplay();
		return 1;
	}

	screen = DefaultScreen(xdisplay);
	rootWindow = RootWindow(xdisplay, screen);

	// build our internal list of available video modes
	GetModes(&modes, !gDisplay.windowed);
	while(!FindMode(modes, width, height))
	{
		if(!gDisplay.windowed)
		{
			// no fullscreen mode, try windowed mode instead
			MFDebug_Warn(1, "No suitable modes for fullscreen mode, trying windowed mode");

			gDisplay.windowed = true;

			FreeModes();
			GetModes(&modes, false);
		}
		else
		{
			// default is some sort of custom mode that doesn't appear in the windowed mode list
			// HACK: we'll add it to the end..
			modes[numModes].width = width;
			modes[numModes].height = height;
			currentMode = numModes;
			++numModes;
			break;
		}
	}

	DebugMenu_AddItem("Resolution", "Display Options", &resSelect, ChangeResCallback);
	DebugMenu_AddItem("Apply", "Display Options", &applyDisplayMode, ApplyDisplayModeCallback);

	// Set full screen mode, if necessary
	if(!gDisplay.windowed && numModes > 1)
	{
		if(!XF86VidModeSwitchToMode(xdisplay, screen, vidModes[currentMode]))
		{
			MFDebug_Error("Unable to switch screenmodes, defaulting to windowed mode");
			MFDisplay_DestroyDisplay();
			return 1;
		}
	}

	XVisualInfo *MFRenderer_GetVisualInfo();
	XVisualInfo *visualInfo = MFRenderer_GetVisualInfo();
	if(!visualInfo)
		return 1;

	if(!(colorMap = XCreateColormap(xdisplay, rootWindow, visualInfo->visual, AllocNone)))
	{
		MFDebug_Error("Unable to create colourmap");
		XFree(visualInfo);
		MFDisplay_DestroyDisplay();
		return 1;
	}

	XSetWindowAttributes windowAttrs;
	windowAttrs.colormap = colorMap;
	windowAttrs.cursor = None;
	windowAttrs.event_mask = StructureNotifyMask;
	windowAttrs.border_pixel = BlackPixel(xdisplay, screen);
	windowAttrs.background_pixel = BlackPixel(xdisplay, screen);

	if(!(window = XCreateWindow(xdisplay, rootWindow, 0, 0, width, height, 0, visualInfo->depth, InputOutput, visualInfo->visual, CWBackPixel | CWBorderPixel | CWCursor | CWColormap | CWEventMask, &windowAttrs)))
	{
		MFDebug_Error("Unable to create X Window");
		XFree(visualInfo);
		MFDisplay_DestroyDisplay();
		return 1;
	}

	// Tell the window manager not to allow our window to be resized.  But some window managers can ignore me and do it anyway.  Typical X-Windows.
	if((sizeHints = XAllocSizeHints()) == NULL)
	{
		MFDebug_Error("Unable to alloc XSizeHints structure, out of memory?");
		XFree(visualInfo);
		MFDisplay_DestroyDisplay();
		return 1;
	}

	sizeHints->flags = PSize | PMinSize | PMaxSize;
    sizeHints->min_width = sizeHints->max_width = sizeHints->base_width = width;
    sizeHints->min_height = sizeHints->max_height = sizeHints->base_height = height;

	XSetWMNormalHints(xdisplay, window, sizeHints);

	// Window title
	XStoreName(xdisplay, window, gDefaults.display.pWindowTitle);

	XWMHints *wmHints;
	if((wmHints = XAllocWMHints()) == NULL)
	{
		MFDebug_Error("Unable to alloc XWMHints structure, out of memory?");
		XFree(visualInfo);
		MFDisplay_DestroyDisplay();
		return 1;
	}

	wmHints->flags = InputHint | StateHint;
	wmHints->input = true;
	wmHints->initial_state = NormalState;
	if(!XSetWMHints(xdisplay, window, wmHints))
	{
		MFDebug_Error("Unable to set WM hints for window");
		XFree(visualInfo);
		MFDisplay_DestroyDisplay();
		return 1;
	}

	XFree(wmHints);
	XFree(visualInfo);

	// Tell the window manager that I want to be notified if the window's closed
	wm_delete_window = XInternAtom(xdisplay, "WM_DELETE_WINDOW", false);
	if(!XSetWMProtocols(xdisplay, window, &wm_delete_window, 1))
	{
		MFDebug_Error("Unable to set Window Manager protocols");
		MFDisplay_DestroyDisplay();
		return 1;
	}

	XSelectInput(xdisplay, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | ExposureMask);

	if(!XMapRaised(xdisplay, window))
	{
		MFDebug_Error("Unable to map new window");
		MFDisplay_DestroyDisplay();
		return 1;
	}

	// Wait for the window to be mapped, etc. The documentation doesn't indicate that this is necessary, but every GLX program I've ever seen does it, so I assume it is.
	XEvent event;
	XIfEvent(xdisplay, &event, WaitForNotify, (char *)window);

	MFRenderer_CreateDisplay();

	if(!gDisplay.windowed && numModes > 1)
	{
		if(!XF86VidModeSwitchToMode(xdisplay, screen, vidModes[currentMode]))
		{
			MFDebug_Error("Unable to set screen mode");
			MFDisplay_DestroyDisplay();
			return 1;
		}

		XGrabPointer(xdisplay, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, None, CurrentTime);

		XFlush(xdisplay);
		// A little trick to make sure the entire window is on the screen
		XWarpPointer(xdisplay, None, window, 0, 0, 0, 0, width - 1, height - 1);
		XWarpPointer(xdisplay, None, window, 0, 0, 0, 0, 0, 0);
		XFlush(xdisplay);
	}

	return 0;
}
Exemple #9
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Error code
///
////////////////////////////////////////////////////////////
int main()
{
    // Open a connection with the X server
    Display* display = XOpenDisplay(NULL);
    if (!display)
        return EXIT_FAILURE;

    // Get the default screen
    int screen = DefaultScreen(display);

    // Let's create the main window
    XSetWindowAttributes attributes;
    attributes.background_pixel = BlackPixel(display, screen);
    attributes.event_mask       = KeyPressMask;
    Window window = XCreateWindow(display, RootWindow(display, screen),
                               0, 0, 650, 330, 0,
                               DefaultDepth(display, screen),
                               InputOutput,
                               DefaultVisual(display, screen),
                               CWBackPixel | CWEventMask, &attributes);
    if (!window)
        return EXIT_FAILURE;

    // Set the window's name
    XStoreName(display, window , "SFML Window");

    // Let's create the windows which will serve as containers for our SFML views
    Window view1 = XCreateWindow(display, window,
                                 10, 10, 310, 310, 0,
                                 DefaultDepth(display, screen),
                                 InputOutput,
                                 DefaultVisual(display, screen),
                                 0, NULL);
    Window view2 = XCreateWindow(display, window,
                                 330, 10, 310, 310, 0,
                                 DefaultDepth(display, screen),
                                 InputOutput,
                                 DefaultVisual(display, screen),
                                 0, NULL);

    // Show our windows
    XMapWindow(display, window);
    XFlush(display);

    // Create our SFML views
    sf::Window SFMLView1(view1);
    sf::Window SFMLView2(view2);

    // Create a clock for measuring elapsed time
    sf::Clock clock;

    // Initialize our views
    initialize(SFMLView1);
    initialize(SFMLView2);

    // Start the event loop
    bool running = true;
    while (running)
    {
        while (XPending(display))
        {
            // Get the next pending event
            XEvent event;
            XNextEvent(display, &event);

            // Process it
            switch (event.type)
            {
                // Any key is pressed: quit
                case KeyPress:
                    running = false;
                    break;
            }
        }

        // Draw something into our views
        draw(SFMLView1, clock.getElapsedTime().asSeconds());
        draw(SFMLView2, clock.getElapsedTime().asSeconds() * 0.3f);

        // Display the views on screen
        SFMLView1.display();
        SFMLView2.display();
    }

    // Close the display
    XCloseDisplay(display);

    return EXIT_SUCCESS;
}
Exemple #10
0
ne_status
window_create(
	char *title,
	uint16_t w,
	uint16_t h)
{
	int pos_x = 0, pos_y = 0;
	Window root;
	XSetWindowAttributes swa, xattr;
	Atom wm_state,
		cardinal,
		_NET_WM_ICON,
		_NET_WM_PID,
		_NET_WM_WINDOW_TYPE,
		_NET_WM_WINDOW_TYPE_NORMAL,
		_NET_WM_BYPASS_COMPOSITOR;
	XEvent xev;
	XWMHints wm_hints;
	XClassHint class_hint;
	XSizeHints size_hints;
	Screen *screen;
	pid_t pid;
	long compositor = 1;

	x_display = XOpenDisplay(NULL);
	if (!x_display)
		return NE_NO_DISPLAY;

	screen = XDefaultScreenOfDisplay(x_display);
	root = DefaultRootWindow(x_display);

	swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask |
		KeyReleaseMask | StructureNotifyMask | PropertyChangeMask |
		FocusChangeMask | ButtonPressMask | ButtonReleaseMask |
		ButtonMotionMask | EnterWindowMask | LeaveWindowMask |
		PointerMotionMask;

	x11_active_window = XCreateWindow(x_display, root, pos_x, pos_y, w, h,
			0, CopyFromParent, InputOutput, CopyFromParent,
			CWEventMask, &swa);

	xattr.override_redirect = False;
	XChangeWindowAttributes(x_display, x11_active_window,
		CWOverrideRedirect, &xattr);

	/*hints.input = True;
	hints.flags = InputHint;
	XSetWMHints(x_display, x11_active_window, &hints);*/

	XMapWindow(x_display, x11_active_window);
	XStoreName(x_display, x11_active_window, title);

	wm_state = XInternAtom(x_display, "_NET_WM_STATE", False);

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

	XSendEvent(x_display, DefaultRootWindow(x_display), False,
				SubstructureNotifyMask, &xev);

	_NET_WM_ICON = XInternAtom(x_display, "_NET_WM_ICON", False);
	cardinal = XInternAtom(x_display, "CARDINAL", False);

	x11_wnd_width = w;
	x11_wnd_height = h;
	_own_window = true;

	// Set WM hints

	memset(&class_hint, 0x0, sizeof(class_hint));
	memset(&size_hints, 0x0, sizeof(size_hints));
	memset(&wm_hints, 0x0, sizeof(wm_hints));

	class_hint.res_name = "NekoEngine";
	class_hint.res_class = "NekoEngine";

	size_hints.x = pos_x;
	size_hints.y = pos_y;
	size_hints.flags |= USPosition;

	wm_hints.input = True;
	wm_hints.flags = InputHint;

	XSetWMProperties(x_display, x11_active_window, NULL, NULL, NULL, 0,
		&size_hints, &wm_hints, &class_hint);

	_NET_WM_PID = XInternAtom(x_display, "_NET_WM_PID", False);
	if (_NET_WM_PID) {
		pid = getpid();
		XChangeProperty(x_display, x11_active_window,
			_NET_WM_PID, XA_CARDINAL, 32, PropModeReplace,
			(const unsigned char *)&pid, 1);
	}

	_NET_WM_WINDOW_TYPE =
		XInternAtom(x_display, "_NET_WM_WINDOW_TYPE", False);
	_NET_WM_WINDOW_TYPE_NORMAL =
		XInternAtom(x_display, "_NET_WM_WINDOW_TYPE_NORMAL", False);

	if (_NET_WM_WINDOW_TYPE && _NET_WM_WINDOW_TYPE_NORMAL)
		XChangeProperty(x_display, x11_active_window,
			_NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace,
			(const unsigned char *)&_NET_WM_WINDOW_TYPE_NORMAL, 1);

	// bypass compositor
	_NET_WM_BYPASS_COMPOSITOR =
		XInternAtom(x_display, "_NET_WM_BYPASS_COMPOSITOR", False);
	if (_NET_WM_BYPASS_COMPOSITOR)
		XChangeProperty(x_display, x11_active_window,
			_NET_WM_BYPASS_COMPOSITOR, XA_CARDINAL, 32,
			PropModeReplace, (const unsigned char *)&compositor, 1);

	XSync(x_display, False);

	return NE_OK;
}
void
InitWindow(int argc, char **argv)
{
	XGCValues gc_values;
	XWMHints wmhints;
	Widget	w;
	XClassHint	classHint;
	GC	iconGC;

	progName = (char *)rindex(argv[0], '/');
	if (progName)
		progName++;
	else
		progName = argv[0];

	/*
	 * We cheat here by using the Toolkit to do the initialization work.
	 * We just ignore the top-level widget that gets created.
	 */

	w = XtAppInitialize(&app_con, progName, opTable, XtNumber(opTable),
			&argc, argv, default_resources, NULL, ZERO);

	if ((argc > 1) && (strcmp("-robot", argv[1]) == 0))
	  { argc--;
	    app_resources.robotic = TRUE;
	  }
	else {app_resources.robotic = FALSE;}

	printf("set robot. ");
	dpy = XtDisplay(w);
	screen = DefaultScreen(dpy);

	printf("set Xscreen. ");

	XtGetApplicationResources(w, (caddr_t) &app_resources, resources,
				XtNumber(resources), NULL, (Cardinal) 0);

	printf("set XResource. ");

	if (!app_resources.scoreFont)
		MWError("cannot open font");
	scoreFontInfo = XQueryFont(dpy, app_resources.scoreFont);

	printf("set XQueue. ");

        cur_width = MIN_X_DIM;
        cur_height = MIN_Y_DIM + (MAX_RATS+1) *
	             (scoreFontInfo->max_bounds.ascent +
		      scoreFontInfo->max_bounds.descent);

	mwWindow = XCreateSimpleWindow(dpy,
					RootWindow(dpy, screen),
					0, 0,
					cur_width, cur_height,
					app_resources.borderWidth, 0,
				       app_resources.bg_pixel);
	XStoreName(dpy, mwWindow, "MazeWar");
	XSetIconName(dpy, mwWindow, "MazeWar");
	classHint.res_name = "cs244Bmazewar";
	classHint.res_class = "cs244Bmazewar";
	XSetClassHint(dpy, mwWindow, &classHint);

	gc_values.function = GXcopy;
	gc_values.foreground = app_resources.fg_pixel;
	gc_values.background = app_resources.bg_pixel;
	gc_values.font = app_resources.scoreFont;
	gc_values.line_width = 0;
	copyGC = XCreateGC(dpy, mwWindow,
		       GCFunction | GCForeground | GCBackground
		       | GCLineWidth | GCFont,
		       &gc_values);

	gc_values.function = GXxor;
	gc_values.plane_mask = AllPlanes;
	gc_values.foreground = app_resources.fg_pixel ^ app_resources.bg_pixel;
	gc_values.background = 0;
	xorGC = XCreateGC(dpy, mwWindow,
		       GCFunction | GCForeground | GCBackground | GCPlaneMask,
		       &gc_values);

	icon_pixmap = XCreatePixmapFromBitmapData(
			dpy, mwWindow,
			(char *)icon_bits,
			icon_width, icon_height,
			app_resources.fg_pixel, app_resources.bg_pixel,
			XDefaultDepth(dpy, screen));

	/* is this even used? */
	gc_values.function = GXclear;
	gc_values.plane_mask = AllPlanes;
	iconGC = XCreateGC(dpy, mwWindow,
			GCFunction | GCPlaneMask,
			&gc_values);
	iconmask_pixmap = XCreatePixmap(dpy, mwWindow,
					icon_width, icon_height,
					XDefaultDepth(dpy, screen));
	XFillRectangle(dpy, iconmask_pixmap, iconGC, 0, 0,
			icon_width, icon_height);

	icon_reverse_pixmap = XCreatePixmapFromBitmapData(dpy, mwWindow,
						  (char *)icon_bits,
						  icon_width, icon_height,
						  app_resources.bg_pixel,
						  app_resources.fg_pixel,
						  XDefaultDepth(dpy, screen));

	wmhints.input = TRUE;
        wmhints.flags = IconPixmapHint | IconMaskHint | InputHint;
        wmhints.icon_pixmap = icon_pixmap;
        wmhints.icon_mask = iconmask_pixmap;
        XSetWMHints(dpy, mwWindow, &wmhints);

	initCursors();
	arrowImage = XCreateImage(dpy, DefaultVisual(dpy, DefaultScreen(dpy)),
				1, XYBitmap, 0, NULL,
				16, 16, 8, 2);
	arrowImage->byte_order = MSBFirst;
	arrowImage->bitmap_bit_order = MSBFirst;
}
Exemple #12
0
ne_status
window_set_title(char *title)
{
	return XStoreName(x_display, x11_active_window, title);
}
Exemple #13
0
void set_title(void)
{
    //Set the window title bar.
    XMapWindow(dpy, win);
    XStoreName(dpy, win, "335 Lab1   LMB for particle");
}
Exemple #14
0
static int X_init(__AA_CONST struct aa_hardware_params *p, __AA_CONST void *none,struct aa_hardware_params *dest, void **driverdata)
{
    const char *font = "8x13bold";
    static int registered;
    static aa_font aafont;
    __AA_CONST static struct aa_hardware_params def=
    {&aa_fontX13B, AA_DIM_MASK | AA_REVERSE_MASK | AA_NORMAL_MASK | AA_BOLD_MASK | AA_BOLDFONT_MASK | AA_EXTENDED,
     0, 0,
     0, 0,
     80, 32,
     0, 0};
    struct xdriverdata *d;
    *dest=def;
    *driverdata=d=calloc(1,sizeof(*d));
    d->previoust=NULL;
    d->previousa=NULL;
    d->cvisible=1;
    d->width=80;
    d->height=32;
    if ((d->dp = XOpenDisplay(NULL)) == NULL)
	return 0;
    d->screen = DefaultScreen(d->dp);
    if (getenv ("AAFont"))
      font = getenv ("AAFont");
    d->font = XLoadFont(d->dp, font);
    if (!d->font) {
	XCloseDisplay(d->dp);
	return 0;
    }
    d->font_s = XQueryFont(d->dp, d->font);
    if (!d->font_s) {
	XCloseDisplay(d->dp);
	return 0;
    }
    d->fontheight = d->font_s->max_bounds.ascent + d->font_s->max_bounds.descent;
    d->fontwidth = d->font_s->max_bounds.rbearing - d->font_s->min_bounds.lbearing;
    d->realfontwidth = d->font_s->max_bounds.width;
    d->cmap = DefaultColormap(d->dp, d->screen);
    /*c.flags=DoRed | DoGreen | DoBlue; */

    X_AllocColors (d);
    if (d->bold == d->normal)
      dest->supported &= ~AA_BOLD_MASK;
    if (d->dim == d->normal)
      dest->supported &= ~AA_DIM_MASK;

    d->attr.event_mask = ExposureMask;
    d->attr.override_redirect = False;
    if (p->width)
	d->width = p->width;
    if (p->height)
	d->height = p->height;
    if (p->maxwidth && d->width > p->maxwidth)
	d->width = p->maxwidth;
    if (p->minwidth && d->width < p->minwidth)
	d->width = p->minwidth;
    if (p->maxheight && d->height > p->maxheight)
	d->height = p->maxheight;
    if (p->minheight && d->height < p->minheight)
	d->height = p->minheight;
    d->wi = XCreateWindow(d->dp, RootWindow(d->dp, d->screen), 0, 0, d->width * d->realfontwidth, d->height * d->fontheight, 0, DefaultDepth(d->dp, d->screen), InputOutput, DefaultVisual(d->dp, d->screen), CWBackPixel | CWBorderPixel | CWEventMask, &d->attr);
    if (!registered) {
	d->pi = XCreatePixmap(d->dp, d->wi, d->fontwidth, d->fontheight * 256, 1);
	if (d->pi) {
	    int i;
	    unsigned char c;
	    unsigned char *data;
	    XImage *image;
	    registered = 1;
	    d->specialGC = XCreateGC(d->dp, d->pi, 0L, NULL);
	    XSetForeground(d->dp, d->specialGC, 0);
	    XSetBackground(d->dp, d->specialGC, 0);
	    XFillRectangle(d->dp, d->pi, d->specialGC, 0, 0, d->fontwidth, 256 * d->fontheight);
	    XSetForeground(d->dp, d->specialGC, 1);
	    XSetFont(d->dp, d->specialGC, d->font);
	    for (i = 0; i < 256; i++) {
		c = i;
		XDrawString(d->dp, d->pi, d->specialGC, 0, (i + 1) * d->fontheight - d->font_s->descent, (char *)&c, 1);
	    }
	    image = XGetImage(d->dp, d->pi, 0, 0, d->fontwidth, 256 * d->fontheight, 1, XYPixmap);
	    if (image != NULL) {
		data = malloc(256 * d->fontheight);
		for (i = 0; i < 256; i++) {
		    int y;
		    font_error = 0;
		    for (y = 0; y < d->fontheight; y++) {
			int o;
			o = ((mygetpixel(image, 0, i * d->fontheight + y) != 0) << 7) +
			    ((mygetpixel(image, 1, i * d->fontheight + y) != 0) << 6) +
			    ((mygetpixel(image, 2, i * d->fontheight + y) != 0) << 5) +
			    ((mygetpixel(image, 3, i * d->fontheight + y) != 0) << 4) +
			    ((mygetpixel(image, 4, i * d->fontheight + y) != 0) << 3) +
			    ((mygetpixel(image, 5, i * d->fontheight + y) != 0) << 2) +
			    ((mygetpixel(image, 6, i * d->fontheight + y) != 0) << 1) +
			    ((mygetpixel(image, 7, i * d->fontheight + y) != 0) << 0);
			data[i * d->fontheight + y] = o;
		    }
		}
		aafont.name = "Font used by X server";
		aafont.shortname = "current";
		aafont.height = d->fontheight;
		aafont.data = data;
		aa_registerfont(&aafont);
		dest->font = &aafont;
	    }
	}
    }
    XStoreName(d->dp, d->wi, "aa for X");
    XMapWindow(d->dp, d->wi);
    X_setinversionmode (getenv ("AAInverted") != NULL, d);
    d->pixelwidth = -1;
    d->pixelheight = -1;
    XSync(d->dp, 0);
    aa_recommendlowkbd("X11");
    return 1;
}
int main(void)
{
    /* Platform */
    int running = 1;
    struct XWindow win;
    GLXContext glContext;
    struct nk_context *ctx;
    struct nk_colorf bg;

    memset(&win, 0, sizeof(win));
    win.dpy = XOpenDisplay(NULL);
    if (!win.dpy) die("Failed to open X display\n");
    {
        /* check glx version */
        int glx_major, glx_minor;
        if (!glXQueryVersion(win.dpy, &glx_major, &glx_minor))
            die("[X11]: Error: Failed to query OpenGL version\n");
        if ((glx_major == 1 && glx_minor < 3) || (glx_major < 1))
            die("[X11]: Error: Invalid GLX version!\n");
    }
    {
        /* find and pick matching framebuffer visual */
        int fb_count;
        static GLint attr[] = {
            GLX_X_RENDERABLE,   True,
            GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT,
            GLX_RENDER_TYPE,    GLX_RGBA_BIT,
            GLX_X_VISUAL_TYPE,  GLX_TRUE_COLOR,
            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,   True,
            None
        };
        GLXFBConfig *fbc;
        fbc = glXChooseFBConfig(win.dpy, DefaultScreen(win.dpy), attr, &fb_count);
        if (!fbc) die("[X11]: Error: failed to retrieve framebuffer configuration\n");
        {
            /* pick framebuffer with most samples per pixel */
            int i;
            int fb_best = -1, best_num_samples = -1;
            for (i = 0; i < fb_count; ++i) {
                XVisualInfo *vi = glXGetVisualFromFBConfig(win.dpy, fbc[i]);
                if (vi) {
                    int sample_buffer, samples;
                    glXGetFBConfigAttrib(win.dpy, fbc[i], GLX_SAMPLE_BUFFERS, &sample_buffer);
                    glXGetFBConfigAttrib(win.dpy, fbc[i], GLX_SAMPLES, &samples);
                    if ((fb_best < 0) || (sample_buffer && samples > best_num_samples))
                        fb_best = i, best_num_samples = samples;
                }
            }
            win.fbc = fbc[fb_best];
            XFree(fbc);
            win.vis = glXGetVisualFromFBConfig(win.dpy, win.fbc);
        }
    }
    {
        /* create window */
        win.cmap = XCreateColormap(win.dpy, RootWindow(win.dpy, win.vis->screen), win.vis->visual, AllocNone);
        win.swa.colormap =  win.cmap;
        win.swa.background_pixmap = None;
        win.swa.border_pixel = 0;
        win.swa.event_mask =
            ExposureMask | KeyPressMask | KeyReleaseMask |
            ButtonPress | ButtonReleaseMask| ButtonMotionMask |
            Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
            PointerMotionMask| StructureNotifyMask;
        win.win = XCreateWindow(win.dpy, RootWindow(win.dpy, win.vis->screen), 0, 0,
            WINDOW_WIDTH, WINDOW_HEIGHT, 0, win.vis->depth, InputOutput,
            win.vis->visual, CWBorderPixel|CWColormap|CWEventMask, &win.swa);
        if (!win.win) die("[X11]: Failed to create window\n");
        XFree(win.vis);
        XStoreName(win.dpy, win.win, "Demo");
        XMapWindow(win.dpy, win.win);
        win.wm_delete_window = XInternAtom(win.dpy, "WM_DELETE_WINDOW", False);
        XSetWMProtocols(win.dpy, win.win, &win.wm_delete_window, 1);
    }
    {
        /* create opengl context */
        typedef GLXContext(*glxCreateContext)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
        int(*old_handler)(Display*, XErrorEvent*) = XSetErrorHandler(gl_error_handler);
        const char *extensions_str = glXQueryExtensionsString(win.dpy, DefaultScreen(win.dpy));
        glxCreateContext create_context = (glxCreateContext)
            glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");

        gl_err = nk_false;
        if (!has_extension(extensions_str, "GLX_ARB_create_context") || !create_context) {
            fprintf(stdout, "[X11]: glXCreateContextAttribARB() not found...\n");
            fprintf(stdout, "[X11]: ... using old-style GLX context\n");
            glContext = glXCreateNewContext(win.dpy, win.fbc, GLX_RGBA_TYPE, 0, True);
        } else {
            GLint attr[] = {
                GLX_CONTEXT_MAJOR_VERSION_ARB, 2,
                GLX_CONTEXT_MINOR_VERSION_ARB, 2,
                None
            };
            glContext = create_context(win.dpy, win.fbc, 0, True, attr);
            XSync(win.dpy, False);
            if (gl_err || !glContext) {
                /* Could not create GL 3.0 context. Fallback to old 2.x context.
                 * If a version below 3.0 is requested, implementations will
                 * return the newest context version compatible with OpenGL
                 * version less than version 3.0.*/
                attr[1] = 1; attr[3] = 0;
                gl_err = nk_false;
                fprintf(stdout, "[X11] Failed to create OpenGL 3.0 context\n");
                fprintf(stdout, "[X11] ... using old-style GLX context!\n");
                glContext = create_context(win.dpy, win.fbc, 0, True, attr);
            }
        }
        XSync(win.dpy, False);
        XSetErrorHandler(old_handler);
        if (gl_err || !glContext)
            die("[X11]: Failed to create an OpenGL context\n");
        glXMakeCurrent(win.dpy, win.win, glContext);
    }

    ctx = nk_x11_init(win.dpy, win.win);
    /* Load Fonts: if none of these are loaded a default font will be used  */
    /* Load Cursor: if you uncomment cursor loading please hide the cursor */
    {struct nk_font_atlas *atlas;
    nk_x11_font_stash_begin(&atlas);
    /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/
    /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
    /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
    /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/
    /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
    /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/
    nk_x11_font_stash_end();
    /*nk_style_load_all_cursors(ctx, atlas->cursors);*/
    /*nk_style_set_font(ctx, &droid->handle);*/}

    #ifdef INCLUDE_STYLE
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/
    #endif

    bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f;
    while (running)
    {
        /* Input */
        XEvent evt;
        nk_input_begin(ctx);
        while (XPending(win.dpy)) {
            XNextEvent(win.dpy, &evt);
            if (evt.type == ClientMessage) goto cleanup;
            if (XFilterEvent(&evt, win.win)) continue;
            nk_x11_handle_event(&evt);
        }
        nk_input_end(ctx);

        /* GUI */
        if (nk_begin(ctx, "Demo", nk_rect(50, 50, 200, 200),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
            NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
        {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;

            nk_layout_row_static(ctx, 30, 80, 1);
            if (nk_button_label(ctx, "button"))
                fprintf(stdout, "button pressed\n");
            nk_layout_row_dynamic(ctx, 30, 2);
            if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
            nk_layout_row_dynamic(ctx, 25, 1);
            nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);

            nk_layout_row_dynamic(ctx, 20, 1);
            nk_label(ctx, "background:", NK_TEXT_LEFT);
            nk_layout_row_dynamic(ctx, 25, 1);
            if (nk_combo_begin_color(ctx, nk_rgb_cf(bg), nk_vec2(nk_widget_width(ctx),400))) {
                nk_layout_row_dynamic(ctx, 120, 1);
                bg = nk_color_picker(ctx, bg, NK_RGBA);
                nk_layout_row_dynamic(ctx, 25, 1);
                bg.r = nk_propertyf(ctx, "#R:", 0, bg.r, 1.0f, 0.01f,0.005f);
                bg.g = nk_propertyf(ctx, "#G:", 0, bg.g, 1.0f, 0.01f,0.005f);
                bg.b = nk_propertyf(ctx, "#B:", 0, bg.b, 1.0f, 0.01f,0.005f);
                bg.a = nk_propertyf(ctx, "#A:", 0, bg.a, 1.0f, 0.01f,0.005f);
                nk_combo_end(ctx);
            }
        }
        nk_end(ctx);

        /* -------------- EXAMPLES ---------------- */
        #ifdef INCLUDE_CALCULATOR
          calculator(ctx);
        #endif
        #ifdef INCLUDE_OVERVIEW
          overview(ctx);
        #endif
        #ifdef INCLUDE_NODE_EDITOR
          node_editor(ctx);
        #endif
        /* ----------------------------------------- */

        /* Draw */
        XGetWindowAttributes(win.dpy, win.win, &win.attr);
        glViewport(0, 0, win.width, win.height);
        glClear(GL_COLOR_BUFFER_BIT);
        glClearColor(bg.r, bg.g, bg.b, bg.a);
        /* IMPORTANT: `nk_x11_render` modifies some global OpenGL state
         * with blending, scissor, face culling, depth test and viewport and
         * defaults everything back into a default state.
         * Make sure to either a.) save and restore or b.) reset your own state after
         * rendering the UI. */
        nk_x11_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
        glXSwapBuffers(win.dpy, win.win);
    }

cleanup:
    nk_x11_shutdown();
    glXMakeCurrent(win.dpy, 0, 0);
    glXDestroyContext(win.dpy, glContext);
    XUnmapWindow(win.dpy, win.win);
    XFreeColormap(win.dpy, win.cmap);
    XDestroyWindow(win.dpy, win.win);
    XCloseDisplay(win.dpy);
    return 0;

}
/*--------------------------------------------------------*/
void open_gwindow_( )
{
/*
 * create new graphics window on first entry....
 */
  int                          font,black,white;
  int                          scr_width,scr_height;
  int                          j;
  unsigned long                valuemask;
  static int                   depth;    /* number of planes  */
  static Visual               *visual;   /*VISUAL TYPE       */
  static XSizeHints            win_position;   /*position and size for
                                            window manager.*/

/*
 * initialize display id and screen id....
 */
      disp_id = XOpenDisplay(0);
      if (!disp_id) {
         printf("Display not opened!\n");
         exit(-1);
      }
/*
 * next instruction for debugging only....
 */
/*      XSynchronize(disp_id, 1); */
  
  screen_id  =  XDefaultScreenOfDisplay(disp_id);
  root_win_id = XRootWindowOfScreen(screen_id);
  black =       XBlackPixelOfScreen(screen_id);
  white =       XWhitePixelOfScreen(screen_id);
  scr_width =   XWidthOfScreen(screen_id);
  scr_height =  XHeightOfScreen(screen_id);
  depth  =      XDefaultDepthOfScreen(screen_id);
  visual =      XDefaultVisualOfScreen(screen_id);


/*
 * set up backing store....
 */
      valuemask = CWBitGravity | CWBackingStore | CWBackPixel;
      setwinattr.bit_gravity = SouthWestGravity;
      setwinattr.backing_store = Always;
      setwinattr.background_pixel = white;
/*
 * create the window....
 */
      win_id  = XCreateWindow(disp_id,
			      root_win_id,
			      scr_width - win_width - 15,
			      scr_height - win_height - 35,
			      win_width, 
			      win_height, 
			      10,
			      depth,
			      InputOutput,
			      visual,
			      valuemask,
			      &setwinattr);
/* WMHints structure */
  win_position.x = scr_width - win_width - 15;
  win_position.y = scr_height - win_height - 35;
  win_position.width = win_width;
  win_position.height = win_height;
  win_position.flags=USPosition|USSize;
  
  XSetWMNormalHints(disp_id, win_id, &win_position); 

      XStoreName(disp_id, win_id, WINDNAME);
/*
 * get named color values....
 */

      color[1]   = define_color_("BLUE");
      color[2]   = define_color_("DEEP SKY BLUE");
      color[3]   = define_color_("LIGHT SKY BLUE");

      color[4]   = define_color_("SEA GREEN");
      color[5]  = define_color_("MEDIUM SEA GREEN");
      color[6]  = define_color_("GREEN");

      color[7]  = define_color_("BROWN");
      color[8]  = define_color_("CHOCOLATE");
      color[9]  = define_color_("SANDY BROWN");

      color[10]   = define_color_("RED");
      color[11]   = define_color_("CORAL");
      color[12]   = define_color_("ORANGE");

      color[13]  = define_color_("YELLOW3");
      color[14]  = define_color_("YELLOW2");
      color[15]  = define_color_("YELLOW");

      color[16]  = define_color_("PEACH PUFF");
      color[17]  = define_color_("PAPAYA WHIP");
      color[18]  = define_color_("OLD LACE");

      color[19]   = white;
      color[20]   = black;
      color[21]   = black;


/*
 * create graphics context....
 */
      xgcvl.background = color[19];
      xgcvl.foreground = color[20];
      gc_id = XCreateGC(disp_id, win_id, GCForeground | GCBackground, &xgcvl);
      xgcvl.function = GXinvert;
      gc_comp_id = XCreateGC(disp_id, win_id, GCFunction, &xgcvl);
/*
 * load the font for text writing....
 */
      font = XLoadFont(disp_id, FONTNAME);
      XSetFont(disp_id, gc_id, font);

  /* Map the window.... */
  XSelectInput(disp_id,win_id,ExposureMask|VisibilityChangeMask);
  XMapRaised(disp_id,win_id);

  /*
   * Wait for the window to be raised. Some X servers do not 
   * generate an initial expose event, so also check the visibility
   * event.
   */
  XMaskEvent(disp_id,ExposureMask|VisibilityChangeMask,&event);
  XSelectInput(disp_id,win_id,0);
  XSync(disp_id,1);
}
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
                      X11Display &rDisplay, bool dragDrop, bool playOnDrop,
                      X11Window *pParentWindow, GenericWindow::WindowType_t type ):
    OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
    m_dragDrop( dragDrop ), m_pDropTarget( NULL ), m_type ( type )
{
    XSetWindowAttributes attr;
    unsigned long valuemask;
    string name_type;

    if( type == GenericWindow::FullscreenWindow )
    {
        m_wnd_parent = DefaultRootWindow( XDISPLAY );

        int i_screen = DefaultScreen( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
        attr.backing_store = Always;
        valuemask = CWBackingStore | CWBackPixel | CWEventMask;

        if( NET_WM_STATE_FULLSCREEN == None )
        {
            attr.override_redirect = True;
            valuemask = valuemask | CWOverrideRedirect;
        }

        name_type = "Fullscreen";
    }
    else if( type == GenericWindow::VoutWindow )
    {
        m_wnd_parent = pParentWindow->m_wnd;

        int i_screen = DefaultScreen( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        attr.backing_store = Always;
        attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
        valuemask = CWBackingStore | CWBackPixel | CWEventMask;

        name_type = "VoutWindow";
    }
    else if( type == GenericWindow::FscWindow )
    {
        m_wnd_parent = DefaultRootWindow( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        valuemask = CWEventMask;

        name_type = "FscWindow";
    }
    else
    {
        m_wnd_parent = DefaultRootWindow( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        valuemask = CWEventMask;

        name_type = "TopWindow";
    }

    // Create the window
    m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 10, 10, 0, 0,
                           InputOutput, CopyFromParent, valuemask, &attr );

    // wait for X server to process the previous commands
    XSync( XDISPLAY, false );

    // Set the colormap for 8bpp mode
    if( XPIXELSIZE == 1 )
    {
        XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
    }

    // Select events received by the window
    long event_mask;
    if( type == GenericWindow::VoutWindow )
    {
        event_mask =  ExposureMask|KeyPressMask|
                      LeaveWindowMask|FocusChangeMask;
    }
    else
    {
        event_mask =  ExposureMask|KeyPressMask|
                      PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
                      LeaveWindowMask|FocusChangeMask;
    }
    XSelectInput( XDISPLAY, m_wnd, event_mask );

    // Store a pointer on the generic window in a map
    X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
    pFactory->m_windowMap[m_wnd] = &rWindow;

    // Changing decorations
    struct {
        unsigned long flags;
        unsigned long functions;
        unsigned long decorations;
        signed   long input_mode;
        unsigned long status;
    } motifWmHints;
    Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False );
    motifWmHints.flags = 2;    // MWM_HINTS_DECORATIONS;
    motifWmHints.decorations = 0;
    XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32,
                     PropModeReplace, (unsigned char *)&motifWmHints,
                     sizeof( motifWmHints ) / sizeof( uint32_t ) );

    // Drag & drop
    if( m_dragDrop )
    {
        // Create a Dnd object for this window
        m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd,
                                         playOnDrop, &rWindow );

        // Register the window as a drop target
        Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False );
        char xdndVersion = 4;
        XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32,
                         PropModeReplace, (unsigned char *)&xdndVersion, 1 );

        // Store a pointer to be used in X11Loop
        pFactory->m_dndMap[m_wnd] = m_pDropTarget;
    }

    // Change the window title
    string name_window = "VLC (" + name_type + ")";
    XStoreName( XDISPLAY, m_wnd, name_window.c_str() );

    // Set the WM_TRANSIENT_FOR property
    if( type == GenericWindow::FscWindow )
    {
        // Associate the fsc window to the fullscreen window
        VoutManager* pVoutManager = VoutManager::instance( getIntf() );
        GenericWindow* pWin = pVoutManager->getVoutMainWindow();
        Window wnd = (Window) pWin->getOSHandle();
        XSetTransientForHint( XDISPLAY, m_wnd, wnd );
    }
    else
    {
        // Associate the regular top-level window to the offscren main window
        XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() );
    }

    // initialize Class Hint
    XClassHint classhint;
    classhint.res_name = (char*) "vlc";
    classhint.res_class = (char*) "Vlc";
    XSetClassHint( XDISPLAY, m_wnd, &classhint );

    // copies WM_HINTS from the main window
    XWMHints *wm = XGetWMHints( XDISPLAY, m_rDisplay.getMainWindow() );
    if( wm )
    {
        XSetWMHints( XDISPLAY, m_wnd, wm );
        XFree( wm );
    }

    // initialize WM_CLIENT_MACHINE
    char* hostname = NULL;
    long host_name_max = sysconf( _SC_HOST_NAME_MAX );
    if( host_name_max <= 0 )
        host_name_max = _POSIX_HOST_NAME_MAX;
    hostname = new char[host_name_max];
    if( hostname && gethostname( hostname, host_name_max ) == 0 )
    {
        hostname[host_name_max - 1] = '\0';

        XTextProperty textprop;
        textprop.value = (unsigned char *) hostname;
        textprop.encoding = XA_STRING;
        textprop.format = 8;
        textprop.nitems = strlen( hostname );
        XSetWMClientMachine( XDISPLAY, m_wnd, &textprop);
    }
    delete[] hostname;

    // initialize EWMH pid
    pid_t pid = getpid();
    assert(  NET_WM_PID != None );
    XChangeProperty( XDISPLAY, m_wnd, NET_WM_PID, XA_CARDINAL, 32,
                     PropModeReplace, (unsigned char *)&pid, 1 );

}
Exemple #18
0
int main(int argc, char *argv[])
{
	XSetErrorHandler(handler);
	XWindowAttributes attr;

	Display *dpy = XOpenDisplay(NULL);
	if(!(dpy = XOpenDisplay(0x0))) return 1;

	int scr = XDefaultScreen(dpy);
	int display_width = DisplayWidth(dpy, scr);
	int display_height = DisplayHeight(dpy, scr);

	XColor col = color(dpy, "green");
	Window win = XCreateSimpleWindow(dpy,
		XRootWindow(dpy, scr),
		0, 0, display_width + 10, display_height + 10, 2,
		XBlackPixel(dpy, scr), XBlackPixel(dpy, scr));

	XGetWindowAttributes(dpy, win, &attr);
	XStoreName(dpy, win, "xx");
 
	XSelectInput(dpy, win, 
		ExposureMask | KeyPressMask | ButtonPressMask | SubstructureNotifyMask);

	GC gc = XDefaultGC(dpy, scr);
 
	col = color(dpy, "green");
	XSetForeground(dpy, gc, col.pixel);

	col = color(dpy, "black");
	XSetBackground(dpy, gc, col.pixel);

	XFontStruct *font = get_font(dpy);

	XTextItem item;
	item.delta = 10;
	item.font = font -> fid; 
	XMapWindow(dpy, win);
	XEvent ev;
	int pid_about = 0;
	int loop = 1;
	while (loop) {
		XNextEvent(dpy, &ev);
		switch (ev.type)
		{
			case Expose:
			{
				XGetWindowAttributes(dpy, win, &attr);
				draw_text(dpy, gc, win, attr.width, attr.height, font);
				draw_lines(dpy, gc, win, attr.width, attr.height);
				draw_icons(dpy, gc, win, attr.width, 
						load_bitmap(dpy, "icon.bmp"));
				pixmap_ *cen = load_bitmap(dpy, "background.bmp");
				int h = cen -> height;
				int w = cen -> width;
				XCopyPlane(dpy, cen -> px, win, gc, 0, 0, w, h,
								attr.width/2 - w/2, attr.height/2 - h/2, 1);
			}
			break;
 
			case ButtonPress:
			{
				
				if(ev.xbutton.y_root - attr.y > attr.height - 80 &&
				   ev.xbutton.y_root - attr.y < attr.height - 30){
					if(ev.xbutton.x_root - attr.x >  5 * attr.width / 16 &&
				 	   ev.xbutton.x_root - attr.x < 11 * attr.width / 16){
						kill(0, SIGHUP);
						loop = 0;
					}
				}else if(ev.xbutton.y_root - attr.y > attr.height - 40 &&
				   	    ev.xbutton.y_root - attr.y < attr.height - 20){
					if(ev.xbutton.x_root - attr.x > 15 * attr.width / 16 &&
				 	   ev.xbutton.x_root - attr.x < 16 * attr.width / 16){
						if(pid_about == 0){
							pid_about = fork();
							if(!pid_about){
								about();
								exit(0);						
							}
						}else{
							kill(pid_about, SIGKILL);
							pid_about = 0;
						}
					}
				}else if(ev.xbutton.y_root - attr.y < 100){
					XGetWindowAttributes(dpy, win, &attr);
					int index = (ev.xbutton.x_root-attr.x)/
								(attr.width/4);		
					run(get_command(index));		
				}
			}
			break;
		}
	}
	XDestroyWindow(dpy, win);
	XCloseDisplay(dpy);
	return 1;
}
Exemple #19
0
void Window::SetTitle(char const * string)
{
	XStoreName(application_->display_, id_, string);
}
Exemple #20
0
/* ===============================================================
 *
 *                          DEMO
 *
 * ===============================================================*/
int
main(void)
{
    long dt;
    long started;
    int running = 1;
    XWindow xw;
    struct nk_context *ctx;

    /* X11 */
    memset(&xw, 0, sizeof xw);
    xw.dpy = XOpenDisplay(NULL);
    if (!xw.dpy) die("Could not open a display; perhaps $DISPLAY is not set?");

    xw.root = DefaultRootWindow(xw.dpy);
    xw.screen = XDefaultScreen(xw.dpy);
    xw.vis = XDefaultVisual(xw.dpy, xw.screen);
    xw.cmap = XCreateColormap(xw.dpy,xw.root,xw.vis,AllocNone);
    xw.swa.colormap = xw.cmap;
    xw.swa.event_mask =
        ExposureMask | KeyPressMask | KeyReleaseMask |
        ButtonPress | ButtonReleaseMask| ButtonMotionMask |
        Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
        PointerMotionMask | KeymapStateMask;
    xw.win = XCreateWindow(xw.dpy, xw.root, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0,
        XDefaultDepth(xw.dpy, xw.screen), InputOutput,
        xw.vis, CWEventMask | CWColormap, &xw.swa);
    XStoreName(xw.dpy, xw.win, "X11");
    XMapWindow(xw.dpy, xw.win);
    XGetWindowAttributes(xw.dpy, xw.win, &xw.attr);
    xw.width = (unsigned int)xw.attr.width;
    xw.height = (unsigned int)xw.attr.height;

    /* GUI */
    xw.font = nk_xfont_create(xw.dpy, "fixed");
    ctx = nk_xlib_init(xw.font, xw.dpy, xw.screen, xw.win, xw.width, xw.height);

    /* style.c */
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/

    while (running)
    {
        /* Input */
        XEvent evt;
        started = timestamp();
        nk_input_begin(ctx);
        while (XCheckWindowEvent(xw.dpy, xw.win, xw.swa.event_mask, &evt)){
            if (XFilterEvent(&evt, xw.win)) continue;
            nk_xlib_handle_event(xw.dpy, xw.screen, xw.win, &evt);
        }
        nk_input_end(ctx);

        /* GUI */
        {struct nk_panel layout;
        if (nk_begin(ctx, &layout, "Demo", nk_rect(50, 50, 200, 200),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
            NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
        {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;

            nk_layout_row_static(ctx, 30, 80, 1);
            if (nk_button_label(ctx, "button"))
                fprintf(stdout, "button pressed\n");
            nk_layout_row_dynamic(ctx, 30, 2);
            if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
            nk_layout_row_dynamic(ctx, 25, 1);
            nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);
        }
        nk_end(ctx);}
        if (nk_window_is_closed(ctx, "Demo")) break;

        /* -------------- EXAMPLES ---------------- */
        /*calculator(ctx);*/
        /*overview(ctx);*/
        /*node_editor(ctx);*/
        /* ----------------------------------------- */

        /* Draw */
        XClearWindow(xw.dpy, xw.win);
        nk_xlib_render(xw.win, nk_rgb(30,30,30));
        XFlush(xw.dpy);

        /* Timing */
        dt = timestamp() - started;
        if (dt < DTIME)
            sleep_for(DTIME - dt);
    }

    nk_xfont_del(xw.dpy, xw.font);
    nk_xlib_shutdown();
    XUnmapWindow(xw.dpy, xw.win);
    XFreeColormap(xw.dpy, xw.cmap);
    XDestroyWindow(xw.dpy, xw.win);
    XCloseDisplay(xw.dpy);
    return 0;
}
Exemple #21
0
void set_title(void)
{
	//Set the window title bar.
	XMapWindow(dpy, win);
	XStoreName(dpy, win, "Waterfall Model");
}
Exemple #22
0
void sSetWindowName(const sChar *name)
{
  WindowName = name;
  if(sXWnd) XStoreName(sXDisplay(),sXWnd,sLinuxFromWide(name));
}
Exemple #23
0
void
setstatus(char *str)
{
	XStoreName(dpy, DefaultRootWindow(dpy), str);
	XSync(dpy, False);
}
Exemple #24
0
int
main()
{
	GLXFBConfig fbconfig;
	Vec2u screen_dim { 1200, 900 };

	// create window
	{
		int buffer_attribs[] = {
			GLX_X_RENDERABLE    , True,
			GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
			GLX_RENDER_TYPE     , GLX_RGBA_BIT,
			GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
			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    , True,
			//GLX_SAMPLE_BUFFERS  , 1,
			//GLX_SAMPLES         , 4,
			None
		};

		g_pctx.display = XOpenDisplay(NULL);
		if (!g_pctx.display)
			zabort("failed to create display");
		int xscreen = XDefaultScreen(g_pctx.display), num_fbconfigs;
		GLXFBConfig *fbconfigs = glXChooseFBConfig(g_pctx.display, xscreen, buffer_attribs, &num_fbconfigs);
		if (!fbconfigs)
			zabort("Failed to retrieve frame buffer configs");
		int best_fbc = -1, best_num_samp = -1;
		for (int i = 0; i < num_fbconfigs; ++i) {
			XVisualInfo *visual = glXGetVisualFromFBConfig(g_pctx.display, fbconfigs[i]);
			if (visual) {
				int samp_buf, samples;
				glXGetFBConfigAttrib(g_pctx.display, fbconfigs[i], GLX_SAMPLE_BUFFERS, &samp_buf);
				glXGetFBConfigAttrib(g_pctx.display, fbconfigs[i], GLX_SAMPLES, &samples);

				if (best_fbc < 0 || (samp_buf && samples > best_num_samp))
					best_fbc = i, best_num_samp = samples;
				//if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp)
					//worst_fbc = i, worst_num_samp = samples;
			}
			XFree(visual);
		}
		if (best_fbc < 0)
			zabort("failed to get a frame buffer");
		fbconfig = fbconfigs[0];
		XFree(fbconfigs);

		XVisualInfo *visual = glXGetVisualFromFBConfig(g_pctx.display, fbconfig);
		Window root = DefaultRootWindow(g_pctx.display);
		XSetWindowAttributes win_attribs;
		win_attribs.colormap = XCreateColormap(g_pctx.display, root, visual->visual, AllocNone);
		win_attribs.background_pixmap = None;
		win_attribs.border_pixmap = None;
		win_attribs.border_pixel = 0;
		win_attribs.event_mask =
			StructureNotifyMask |
			FocusChangeMask |
			EnterWindowMask |
			LeaveWindowMask |
			ExposureMask |
			ButtonPressMask |
			ButtonReleaseMask |
			OwnerGrabButtonMask |
			KeyPressMask |
			KeyReleaseMask;

		int win_attribs_mask = 
			CWBackPixmap|
			CWColormap|
			CWBorderPixel|
			CWEventMask;

		assert(visual->c_class == TrueColor);
		g_pctx.window = XCreateWindow(g_pctx.display, root, 0, 0, screen_dim.x, screen_dim.y, 0, visual->depth, InputOutput, visual->visual, win_attribs_mask, &win_attribs);
		if (!g_pctx.window)
			zabort("Failed to create a window.\n");
		XFree(visual);
		XStoreName(g_pctx.display, g_pctx.window, "cge");
		XMapWindow(g_pctx.display, g_pctx.window);
		if ((g_pctx.wm_delete_window = XInternAtom(g_pctx.display, "WM_DELETE_WINDOW", 1)))
			XSetWMProtocols(g_pctx.display, g_pctx.window, &g_pctx.wm_delete_window, 1);
		else
			zerror("Unable to register WM_DELETE_WINDOW atom");
	}

	// Create OpenGL context.
	{
		int major_ver, minor_ver;
		if (!glXQueryVersion(g_pctx.display, &major_ver, &minor_ver))
			zabort("Unable to query GLX version");
		if ((major_ver == 1 && minor_ver < 3) || major_ver < 1)
			zabort("GLX version is too old");

		// Install a new error handler so that the program doesn't just exit if we fail to get a 3.1 context.
		// Note this error handler is global.  All display connections in all threads of a process use the same error handler.
		ctx_error_occured = false;
		int (*old_handler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctx_error_handler);

		const char *gl_exts = glXQueryExtensionsString(g_pctx.display, XDefaultScreen(g_pctx.display));
		if (!is_ext_supported(gl_exts, "GLX_ARB_create_context"))
			zabort("OpenGL does not support glXCreateContextAttribsARB extension");

		int context_attribs[] = {
			GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
			GLX_CONTEXT_MINOR_VERSION_ARB, 1,
			//GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
			None
		};
		typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
		glXCreateContextAttribsARBProc glXCreateContextAttribsARB = NULL;
		glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte *)"glXCreateContextAttribsARB");
		if (!glXCreateContextAttribsARB)
			zabort("Could not load glXCreateContextAttribsARB");
		g_pctx.gl_context = NULL;
		g_pctx.gl_context = glXCreateContextAttribsARB(g_pctx.display, fbconfig, 0, True, context_attribs);
		XSync(g_pctx.display, False);
		if (ctx_error_occured || !g_pctx.gl_context)
			zabort("Failed to create OpenGL context");
		XSetErrorHandler(old_handler);
		glXMakeCurrent(g_pctx.display, g_pctx.window, g_pctx.gl_context);
	}

	// Load OpenGL functions.
	#define LOADPROC
	#include "glprocs.h"
	#undef LOADPROC

	main_loop(screen_dim);
	platform_exit();
	return 0;
}
Exemple #25
0
void wsSetTitle( wsTWindow * win,char * name )
{ XStoreName( wsDisplay,win->WindowID,name ); }
Exemple #26
0
void X11Window::setTitle(const std::string& title)
{
    XStoreName(m_display, m_window, title.c_str());
    XSetIconName(m_display, m_window, title.c_str());
}
Exemple #27
0
// ---------------------------------------------------------------------------
void X11WindowImpl::setTitle(const char* title)
{
  XStoreName(factory->xdisplay,xwindow,title);
  factory->flushX();
}
Exemple #28
0
Error ContextGL_X11::initialize() {

	//const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");

	ERR_FAIL_COND_V(!glXCreateContextAttribsARB, ERR_UNCONFIGURED);

	static int visual_attribs[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 24,
		None
	};

	static int visual_attribs_layered[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 8,
		GLX_GREEN_SIZE, 8,
		GLX_BLUE_SIZE, 8,
		GLX_ALPHA_SIZE, 8,
		GLX_DEPTH_SIZE, 24,
		None
	};

	int fbcount;
	GLXFBConfig fbconfig = 0;
	XVisualInfo *vi = NULL;

	XSetWindowAttributes swa;
	swa.event_mask = StructureNotifyMask;
	swa.border_pixel = 0;
	unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;

	if (OS::get_singleton()->is_layered_allowed()) {
		GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs_layered, &fbcount);
		ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED);

		for (int i = 0; i < fbcount; i++) {
			vi = (XVisualInfo *)glXGetVisualFromFBConfig(x11_display, fbc[i]);
			if (!vi)
				continue;

			XRenderPictFormat *pict_format = XRenderFindVisualFormat(x11_display, vi->visual);
			if (!pict_format) {
				XFree(vi);
				vi = NULL;
				continue;
			}

			fbconfig = fbc[i];
			if (pict_format->direct.alphaMask > 0) {
				break;
			}
		}
		ERR_FAIL_COND_V(!fbconfig, ERR_UNCONFIGURED);

		swa.background_pixmap = None;
		swa.background_pixel = 0;
		swa.border_pixmap = None;
		valuemask |= CWBackPixel;

	} else {
		GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
		ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED);

		vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

		fbconfig = fbc[0];
	}

	int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&ctxErrorHandler);

	switch (context_type) {
		case OLDSTYLE: {

			p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE);
			ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED);
		} break;
		case GLES_2_0_COMPATIBLE: {

			p->glx_context = glXCreateNewContext(x11_display, fbconfig, GLX_RGBA_TYPE, 0, true);
			ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED);
		} break;
		case GLES_3_0_COMPATIBLE: {

			static int context_attribs[] = {
				GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
				GLX_CONTEXT_MINOR_VERSION_ARB, 3,
				GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
				GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB /*|GLX_CONTEXT_DEBUG_BIT_ARB*/,
				None
			};

			p->glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs);
			ERR_FAIL_COND_V(ctxErrorOccurred || !p->glx_context, ERR_UNCONFIGURED);
		} break;
	}

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa);
	XStoreName(x11_display, x11_window, "Godot Engine");

	ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED);
	set_class_hint(x11_display, x11_window);
	XMapWindow(x11_display, x11_window);

	XSync(x11_display, False);
	XSetErrorHandler(oldHandler);

	glXMakeCurrent(x11_display, x11_window, p->glx_context);

	XFree(vi);

	return OK;
}
Exemple #29
0
void* mfb_open(const char* title, int width, int height, unsigned int flags, int scale)
{
	XSetWindowAttributes windowAttributes;
	XSizeHints sizeHints;
	XImage* image;
	Window window;
	WindowInfo* window_info;

	if (!setup_display()) {
		return 0;
	}

	//TODO: Handle no title/borderless 
	(void)flags;

	width *= scale;
	height *= scale;

	Window defaultRootWindow = DefaultRootWindow(s_display);

	windowAttributes.border_pixel = BlackPixel(s_display, s_screen);
	windowAttributes.background_pixel = BlackPixel(s_display, s_screen);
	windowAttributes.backing_store = NotUseful;

	window = XCreateWindow(s_display, defaultRootWindow, (s_screen_width - width) / 2,
					(s_screen_height - height) / 2, width, height, 0, s_depth, InputOutput,
					s_visual, CWBackPixel | CWBorderPixel | CWBackingStore,
					&windowAttributes);
	if (!window) {
		printf("Unable to create X11 Window\n");
		return 0;
	}

	//XSelectInput(s_display, s_window, KeyPressMask | KeyReleaseMask);
	XStoreName(s_display, window, title);

	XSelectInput(s_display, window, ButtonPressMask | KeyPressMask | KeyReleaseMask | ButtonReleaseMask);

	if (!(flags & WINDOW_RESIZE)) {
		sizeHints.flags = PPosition | PMinSize | PMaxSize;
		sizeHints.x = 0;
		sizeHints.y = 0;
		sizeHints.min_width = width;
		sizeHints.max_width = width;
		sizeHints.min_height = height;
		sizeHints.max_height = height;
  		XSetWMNormalHints(s_display, window, &sizeHints);
	}

  	XClearWindow(s_display, window);
  	XMapRaised(s_display, window);
	XFlush(s_display);

	image = XCreateImage(s_display, CopyFromParent, s_depth, ZPixmap, 0, NULL, width, height, 32, width * 4);

	if (!image) {
		XDestroyWindow(s_display, window);
		printf("Unable to create XImage\n");
		return 0;
	}

	window_info = (WindowInfo*)malloc(sizeof(WindowInfo));
	window_info->key_callback = 0;
	window_info->rust_data = 0;
	window_info->window = window;
	window_info->ximage = image;
	window_info->scale = scale;
	window_info->width = width;
	window_info->height = height;
	window_info->draw_buffer = malloc(width * height * 4);
	window_info->update = 1;

	XSetWMProtocols(s_display, window, &s_wm_delete_window, 1);

	XSaveContext(s_display, window, s_context, (XPointer) window_info);

	image->data = (char*)window_info->draw_buffer;

	s_window_count += 1;

	return (void*)window_info;
}
Exemple #30
0
void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {

	last_button_state=0;

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

	if (get_render_thread_mode()==RENDER_SEPARATE_THREAD) {
		XInitThreads();
	}

	/** XLIB INITIALIZATION **/
	x11_display = XOpenDisplay(NULL);

	char * modifiers = XSetLocaleModifiers ("@im=none");
	ERR_FAIL_COND( modifiers == NULL );

	xim = XOpenIM (x11_display, NULL, NULL, NULL);


	if (xim == NULL) {
		WARN_PRINT("XOpenIM failed");
		xim_style=0L;
	} else {
		::XIMStyles *xim_styles=NULL;
		xim_style=0L;
		char *imvalret=NULL;
		imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
		if (imvalret != NULL || xim_styles == NULL) {
			fprintf (stderr, "Input method doesn't support any styles\n");
		}

		if (xim_styles) {
			xim_style = 0L;
			for (int i=0;i<xim_styles->count_styles;i++) {

				if (xim_styles->supported_styles[i] ==
				    (XIMPreeditNothing | XIMStatusNothing)) {

					    xim_style = xim_styles->supported_styles[i];
					    break;
				    }
			}

			XFree (xim_styles);
		}
		XFree( imvalret );
	}

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

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

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

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

	// maybe contextgl wants to be in charge of creating the window
	//print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height));
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)

	context_gl = memnew( ContextGL_X11( x11_display, x11_window,current_videomode, false ) );
	context_gl->initialize();

	rasterizer = memnew( RasterizerGLES2 );

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

	if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {

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

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

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

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

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

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

	if (current_videomode.fullscreen) {
		//set_wm_border(false);
		set_wm_fullscreen(true);
	}
	if (!current_videomode.resizable) {
		int screen = get_current_screen();
		Size2i screen_size = get_screen_size(screen);
		set_window_size(screen_size);
		set_window_resizable(false);
	}
#endif

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

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

		bool success=false;
		audio_driver_index=-1;
		for(int i=0;i<AudioDriverManagerSW::get_driver_count();i++) {
			if (i==p_audio_driver)
				continue;
			AudioDriverManagerSW::get_driver(i)->set_singleton();
			if (AudioDriverManagerSW::get_driver(i)->init()==OK) {
				success=true;
				print_line("Audio Driver Failed: "+String(AudioDriverManagerSW::get_driver(p_audio_driver)->get_name()));
				print_line("Using alternate audio driver: "+String(AudioDriverManagerSW::get_driver(i)->get_name()));
				audio_driver_index=i;
				break;
			}
		}
		if (!success) {
			ERR_PRINT("Initializing audio failed.");
		}

	}

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


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

	XSetWindowAttributes new_attr;

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

	XChangeWindowAttributes(x11_display, x11_window,CWEventMask,&new_attr);

	XClassHint* classHint;

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

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

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


	if (xim && xim_style) {

		xic = XCreateIC (xim,XNInputStyle, xim_style,XNClientWindow,x11_window,XNFocusWindow, x11_window, (char*)NULL);
	} else {

		xic=NULL;
		WARN_PRINT("XCreateIC couldn't create xic");

	}

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

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

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

		cursors[i]=None;
		img[i]=NULL;
	}

	current_cursor=CURSOR_ARROW;

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

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

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


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

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



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

		 null_cursor=cursor;
	}
	set_cursor_shape(CURSOR_BUSY);


	visual_server->init();
	//
	physics_server = memnew( PhysicsServerSW );
	physics_server->init();
	//physics_2d_server = memnew( Physics2DServerSW );
	physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
	physics_2d_server->init();

	input = memnew( InputDefault );
#ifdef JOYDEV_ENABLED
	joystick = memnew( joystick_linux(input));
#endif
	_ensure_data_dir();
}