Fix more compiler warnings
[freeglut] / src / x11 / fg_window_x11.c
1 /*
2  * freeglut_window_x11.c
3  *
4  * Window management methods for X11
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Copied for Platform code by Evan Felix <karcaw at gmail.com>
9  * Creation date: Thur Feb 2 2012
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included
19  * in all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
25  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28
29 #define FREEGLUT_BUILDING_LIB
30 #include <GL/freeglut.h>
31 #include <limits.h>  /* LONG_MAX */
32 #include <unistd.h>  /* usleep */
33 #include "../fg_internal.h"
34
35 #ifdef EGL_VERSION_1_0
36 #include "egl/fg_window_egl.h"
37 #define fghCreateNewContext fghCreateNewContextEGL
38 #else
39 #include "x11/fg_window_x11_glx.h"
40 #endif
41
42 static int fghResizeFullscrToggle(void)
43 {
44     XWindowAttributes attributes;
45
46     if(glutGet(GLUT_FULL_SCREEN)) {
47         /* restore original window size */
48         SFG_Window *win = fgStructure.CurrentWindow;
49         fgStructure.CurrentWindow->State.NeedToResize = GL_TRUE;
50         fgStructure.CurrentWindow->State.Width  = win->State.pWState.OldWidth;
51         fgStructure.CurrentWindow->State.Height = win->State.pWState.OldHeight;
52
53     } else {
54         /* resize the window to cover the entire screen */
55         XGetWindowAttributes(fgDisplay.pDisplay.Display,
56                 fgStructure.CurrentWindow->Window.Handle,
57                 &attributes);
58         
59         /*
60          * The "x" and "y" members of "attributes" are the window's coordinates
61          * relative to its parent, i.e. to the decoration window.
62          */
63         XMoveResizeWindow(fgDisplay.pDisplay.Display,
64                 fgStructure.CurrentWindow->Window.Handle,
65                 -attributes.x,
66                 -attributes.y,
67                 fgDisplay.ScreenWidth,
68                 fgDisplay.ScreenHeight);
69     }
70     return 0;
71 }
72
73 #define _NET_WM_STATE_TOGGLE    2
74 static int fghEwmhFullscrToggle(void)
75 {
76     XEvent xev;
77     long evmask = SubstructureRedirectMask | SubstructureNotifyMask;
78
79     if(!fgDisplay.pDisplay.State || !fgDisplay.pDisplay.StateFullScreen) {
80         return -1;
81     }
82
83     xev.type = ClientMessage;
84     xev.xclient.window = fgStructure.CurrentWindow->Window.Handle;
85     xev.xclient.message_type = fgDisplay.pDisplay.State;
86     xev.xclient.format = 32;
87     xev.xclient.data.l[0] = _NET_WM_STATE_TOGGLE;
88     xev.xclient.data.l[1] = fgDisplay.pDisplay.StateFullScreen;
89     xev.xclient.data.l[2] = 0;  /* no second property to toggle */
90     xev.xclient.data.l[3] = 1;  /* source indication: application */
91     xev.xclient.data.l[4] = 0;  /* unused */
92
93     if(!XSendEvent(fgDisplay.pDisplay.Display, fgDisplay.pDisplay.RootWindow, 0, evmask, &xev)) {
94         return -1;
95     }
96     return 0;
97 }
98
99 static int fghToggleFullscreen(void)
100 {
101     /* first try the EWMH (_NET_WM_STATE) method ... */
102     if(fghEwmhFullscrToggle() != -1) {
103         return 0;
104     }
105
106     /* fall back to resizing the window */
107     if(fghResizeFullscrToggle() != -1) {
108         return 0;
109     }
110     return -1;
111 }
112
113 static Bool fghWindowIsVisible( Display *display, XEvent *event, XPointer arg)
114 {
115     Window window = (Window)arg;
116     return (event->type == MapNotify) && (event->xmap.window == window);
117 }
118
119 /*
120  * Opens a window. Requires a SFG_Window object created and attached
121  * to the freeglut structure. OpenGL context is created here.
122  */
123 void fgPlatformOpenWindow( SFG_Window* window, const char* title,
124                            GLboolean positionUse, int x, int y,
125                            GLboolean sizeUse, int w, int h,
126                            GLboolean gameMode, GLboolean isSubWindow )
127 {
128     XVisualInfo * visualInfo = NULL;
129     XSetWindowAttributes winAttr;
130     XTextProperty textProperty;
131     XSizeHints sizeHints;
132     XWMHints wmHints;
133     XEvent eventReturnBuffer; /* return buffer required for a call */
134     unsigned long mask;
135     unsigned int current_DisplayMode = fgState.DisplayMode ;
136
137     /* Save the display mode if we are creating a menu window */
138     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
139         fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB ;
140
141 #ifdef EGL_VERSION_1_0
142 #define WINDOW_CONFIG window->Window.pContext.egl.Config
143 #else
144 #define WINDOW_CONFIG window->Window.pContext.FBConfig
145 #endif
146     fghChooseConfig(&WINDOW_CONFIG);
147
148     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
149         fgState.DisplayMode = current_DisplayMode ;
150
151     if( ! WINDOW_CONFIG )
152     {
153         /*
154          * The "fghChooseConfig" returned a null meaning that the visual
155          * context is not available.
156          * Try a couple of variations to see if they will work.
157          */
158 #ifndef EGL_VERSION_1_0
159         if( !( fgState.DisplayMode & GLUT_DOUBLE ) )
160         {
161             fgState.DisplayMode |= GLUT_DOUBLE ;
162             fghChooseConfig(&WINDOW_CONFIG);
163             fgState.DisplayMode &= ~GLUT_DOUBLE;
164         }
165 #endif
166
167         if( fgState.DisplayMode & GLUT_MULTISAMPLE )
168         {
169             fgState.DisplayMode &= ~GLUT_MULTISAMPLE ;
170             fghChooseConfig(&WINDOW_CONFIG);
171             fgState.DisplayMode |= GLUT_MULTISAMPLE;
172         }
173     }
174
175     FREEGLUT_INTERNAL_ERROR_EXIT( WINDOW_CONFIG != NULL,
176                                   "FBConfig with necessary capabilities not found", "fgOpenWindow" );
177
178     /*  Get the X visual.  */
179 #ifdef EGL_VERSION_1_0
180     EGLint vid = 0;
181     XVisualInfo visualTemplate;
182     int num_visuals;
183     if (!eglGetConfigAttrib(fgDisplay.pDisplay.egl.Display, window->Window.pContext.egl.Config, EGL_NATIVE_VISUAL_ID, &vid))
184       fgError("eglGetConfigAttrib(EGL_NATIVE_VISUAL_ID) failed");
185     visualTemplate.visualid = vid;
186     visualInfo = XGetVisualInfo(fgDisplay.pDisplay.Display, VisualIDMask, &visualTemplate, &num_visuals);
187 #else
188     visualInfo = glXGetVisualFromFBConfig( fgDisplay.pDisplay.Display,
189                                            window->Window.pContext.FBConfig );
190 #endif
191
192     FREEGLUT_INTERNAL_ERROR_EXIT( visualInfo != NULL,
193                                   "visualInfo could not be retrieved from FBConfig", "fgOpenWindow" );
194
195     /*
196      * XXX HINT: the masks should be updated when adding/removing callbacks.
197      * XXX       This might speed up message processing. Is that true?
198      * XXX
199      * XXX A: Not appreciably, but it WILL make it easier to debug.
200      * XXX    Try tracing old GLUT and try tracing freeglut.  Old GLUT
201      * XXX    turns off events that it doesn't need and is a whole lot
202      * XXX    more pleasant to trace.  (Think mouse-motion!  Tons of
203      * XXX    ``bonus'' GUI events stream in.)
204      */
205     winAttr.event_mask        =
206         StructureNotifyMask | SubstructureNotifyMask | ExposureMask |
207         ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
208         VisibilityChangeMask | EnterWindowMask | LeaveWindowMask |
209         PointerMotionMask | ButtonMotionMask;
210     winAttr.background_pixmap = None;
211     winAttr.background_pixel  = 0;
212     winAttr.border_pixel      = 0;
213
214     winAttr.colormap = XCreateColormap(
215         fgDisplay.pDisplay.Display, fgDisplay.pDisplay.RootWindow,
216         visualInfo->visual, AllocNone
217     );
218
219     mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
220
221     if( window->IsMenu || ( gameMode == GL_TRUE ) )
222     {
223         winAttr.override_redirect = True;
224         mask |= CWOverrideRedirect;
225     }
226
227     if( ! positionUse )
228         x = y = -1; /* default window position */
229     if( ! sizeUse )
230         w = h = 300; /* default window size */
231
232     window->Window.Handle = XCreateWindow(
233         fgDisplay.pDisplay.Display,
234         window->Parent == NULL ? fgDisplay.pDisplay.RootWindow :
235         window->Parent->Window.Handle,
236         x, y, w, h, 0,
237         visualInfo->depth, InputOutput,
238         visualInfo->visual, mask,
239         &winAttr
240     );
241
242     /*
243      * The GLX context creation, possibly trying the direct context rendering
244      *  or else use the current context if the user has so specified
245      */
246
247     if( window->IsMenu )
248     {
249         /*
250          * If there isn't already an OpenGL rendering context for menu
251          * windows, make one
252          */
253         if( !fgStructure.MenuContext )
254         {
255             fgStructure.MenuContext =
256                 (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
257             fgStructure.MenuContext->MContext = fghCreateNewContext( window );
258         }
259
260         /* window->Window.Context = fgStructure.MenuContext->MContext; */
261         window->Window.Context = fghCreateNewContext( window );
262     }
263     else if( fgState.UseCurrentContext )
264     {
265
266 #ifdef EGL_VERSION_1_0
267         window->Window.Context = eglGetCurrentContext( );
268 #else
269         window->Window.Context = glXGetCurrentContext( );
270 #endif
271
272         if( ! window->Window.Context )
273             window->Window.Context = fghCreateNewContext( window );
274     }
275     else
276         window->Window.Context = fghCreateNewContext( window );
277
278 #if !defined( __FreeBSD__ ) && !defined( __NetBSD__ ) && !defined(EGL_VERSION_1_0)
279     if(  !glXIsDirect( fgDisplay.pDisplay.Display, window->Window.Context ) )
280     {
281       if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
282         fgError( "Unable to force direct context rendering for window '%s'",
283                  title );
284     }
285 #endif
286
287     /*
288      * XXX Assume the new window is visible by default
289      * XXX Is this a  safe assumption?
290      */
291     window->State.Visible = GL_TRUE;
292
293     sizeHints.flags = 0;
294     if ( positionUse )
295         sizeHints.flags |= USPosition;
296     if ( sizeUse )
297         sizeHints.flags |= USSize;
298
299     /*
300      * Fill in the size hints values now (the x, y, width and height
301      * settings are obsolete, are there any more WMs that support them?)
302      * Unless the X servers actually stop supporting these, we should
303      * continue to fill them in.  It is *not* our place to tell the user
304      * that they should replace a window manager that they like, and which
305      * works, just because *we* think that it's not "modern" enough.
306      */
307     sizeHints.x      = x;
308     sizeHints.y      = y;
309     sizeHints.width  = w;
310     sizeHints.height = h;
311
312     wmHints.flags = StateHint;
313     wmHints.initial_state = fgState.ForceIconic ? IconicState : NormalState;
314     /* Prepare the window and iconified window names... */
315     XStringListToTextProperty( (char **) &title, 1, &textProperty );
316
317     XSetWMProperties(
318         fgDisplay.pDisplay.Display,
319         window->Window.Handle,
320         &textProperty,
321         &textProperty,
322         0,
323         0,
324         &sizeHints,
325         &wmHints,
326         NULL
327     );
328     XFree( textProperty.value );
329
330     XSetWMProtocols( fgDisplay.pDisplay.Display, window->Window.Handle,
331                      &fgDisplay.pDisplay.DeleteWindow, 1 );
332
333 #ifdef EGL_VERSION_1_0
334     fghPlatformOpenWindowEGL(window);
335 #else
336     glXMakeContextCurrent(
337         fgDisplay.pDisplay.Display,
338         window->Window.Handle,
339         window->Window.Handle,
340         window->Window.Context
341     );
342 #endif
343
344     /* register extension events _before_ window is mapped */
345     #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
346        fgRegisterDevices( fgDisplay.pDisplay.Display, &(window->Window.Handle) );
347     #endif
348
349     XMapWindow( fgDisplay.pDisplay.Display, window->Window.Handle );
350
351     XFree(visualInfo);
352
353     if( !isSubWindow)
354         XPeekIfEvent( fgDisplay.pDisplay.Display, &eventReturnBuffer, &fghWindowIsVisible, (XPointer)(window->Window.Handle) );
355 #undef WINDOW_CONFIG
356 }
357
358
359 /*
360  * Closes a window, destroying the frame and OpenGL context
361  */
362 void fgPlatformCloseWindow( SFG_Window* window )
363 {
364 #ifdef EGL_VERSION_1_0
365     fghPlatformCloseWindowEGL(window);
366 #else
367     if( window->Window.Context )
368         glXDestroyContext( fgDisplay.pDisplay.Display, window->Window.Context );
369     window->Window.pContext.FBConfig = NULL;
370 #endif
371
372     if( window->Window.Handle ) {
373         XDestroyWindow( fgDisplay.pDisplay.Display, window->Window.Handle );
374     }
375     /* XFlush( fgDisplay.pDisplay.Display ); */ /* XXX Shouldn't need this */
376 }
377
378
379 /*
380  * This function makes the current window visible
381  */
382 void fgPlatformGlutShowWindow( void )
383 {
384     XMapWindow( fgDisplay.pDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
385     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
386 }
387
388 /*
389  * This function hides the current window
390  */
391 void fgPlatformGlutHideWindow( void )
392 {
393     if( fgStructure.CurrentWindow->Parent == NULL )
394         XWithdrawWindow( fgDisplay.pDisplay.Display,
395                          fgStructure.CurrentWindow->Window.Handle,
396                          fgDisplay.pDisplay.Screen );
397     else
398         XUnmapWindow( fgDisplay.pDisplay.Display,
399                       fgStructure.CurrentWindow->Window.Handle );
400     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
401 }
402
403 /*
404  * Iconify the current window (top-level windows only)
405  */
406 void fgPlatformGlutIconifyWindow( void )
407 {
408     XIconifyWindow( fgDisplay.pDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
409                     fgDisplay.pDisplay.Screen );
410     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
411 }
412
413 /*
414  * Set the current window's title
415  */
416 void fgPlatformGlutSetWindowTitle( const char* title )
417 {
418     XTextProperty text;
419
420     text.value = (unsigned char *) title;
421     text.encoding = XA_STRING;
422     text.format = 8;
423     text.nitems = strlen( title );
424
425     XSetWMName(
426         fgDisplay.pDisplay.Display,
427         fgStructure.CurrentWindow->Window.Handle,
428         &text
429     );
430
431     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
432 }
433
434 /*
435  * Set the current window's iconified title
436  */
437 void fgPlatformGlutSetIconTitle( const char* title )
438 {
439     XTextProperty text;
440
441     text.value = (unsigned char *) title;
442     text.encoding = XA_STRING;
443     text.format = 8;
444     text.nitems = strlen( title );
445
446     XSetWMIconName(
447         fgDisplay.pDisplay.Display,
448         fgStructure.CurrentWindow->Window.Handle,
449         &text
450     );
451
452     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
453 }
454
455 /*
456  * Change the current window's position
457  */
458 void fgPlatformGlutPositionWindow( int x, int y )
459 {
460     XMoveWindow( fgDisplay.pDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
461                  x, y );
462     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
463 }
464
465 /*
466  * Lowers the current window (by Z order change)
467  */
468 void fgPlatformGlutPushWindow( void )
469 {
470     XLowerWindow( fgDisplay.pDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
471 }
472
473 /*
474  * Raises the current window (by Z order change)
475  */
476 void fgPlatformGlutPopWindow( void )
477 {
478     XRaiseWindow( fgDisplay.pDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
479 }
480
481 /*
482  * Resize the current window so that it fits the whole screen
483  */
484 void fgPlatformGlutFullScreen( SFG_Window *win )
485 {
486     if(!glutGet(GLUT_FULL_SCREEN)) {
487         if(fghToggleFullscreen() != -1) {
488             win->State.IsFullscreen = GL_TRUE;
489         }
490     }
491 }
492
493 /*
494  * If we are fullscreen, resize the current window back to its original size
495  */
496 void fgPlatformGlutLeaveFullScreen( SFG_Window *win )
497 {
498     if(glutGet(GLUT_FULL_SCREEN)) {
499         if(fghToggleFullscreen() != -1) {
500             win->State.IsFullscreen = GL_FALSE;
501         }
502     }
503 }
504
505 /*
506  * Toggle the window's full screen state.
507  */
508 void fgPlatformGlutFullScreenToggle( SFG_Window *win )
509 {
510     if(fghToggleFullscreen() != -1) {
511         win->State.IsFullscreen = !win->State.IsFullscreen;
512     }
513 }
514