Setting the line endings and keywords on a bunch of new text files
[freeglut] / src / mswin / freeglut_window_mswin.c
1 /*
2  * freeglut_window_mswin.c
3  *
4  * The Windows-specific mouse cursor related stuff.
5  *
6  * Copyright (c) 2012 Stephen J. Baker. All Rights Reserved.
7  * Written by John F. Fay, <fayjf@sourceforge.net>
8  * Creation date: Sun Jan 22, 2012
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included
18  * in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  */
27
28 #define FREEGLUT_BUILDING_LIB
29 #include <GL/freeglut.h>
30 #include "../Common/freeglut_internal.h"
31
32
33 /* The following include file is available from SGI but is not standard:
34  *   #include <GL/wglext.h>
35  * So we copy the necessary parts out of it.
36  * XXX: should local definitions for extensions be put in a separate include file?
37  */
38 typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
39
40 typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
41
42 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
43 #define WGL_ACCELERATION_ARB           0x2003
44 #define WGL_SUPPORT_OPENGL_ARB         0x2010
45 #define WGL_DOUBLE_BUFFER_ARB          0x2011
46 #define WGL_COLOR_BITS_ARB             0x2014
47 #define WGL_ALPHA_BITS_ARB             0x201B
48 #define WGL_DEPTH_BITS_ARB             0x2022
49 #define WGL_STENCIL_BITS_ARB           0x2023
50 #define WGL_FULL_ACCELERATION_ARB      0x2027
51
52 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
53 #define WGL_SAMPLES_ARB                0x2042
54
55 #define WGL_TYPE_RGBA_FLOAT_ARB        0x21A0
56
57 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
58
59 #ifndef WGL_ARB_create_context
60 #define WGL_ARB_create_context 1
61 #ifdef WGL_WGLEXT_PROTOTYPES
62 extern HGLRC WINAPI wglCreateContextAttribsARB (HDC, HGLRC, const int *);
63 #endif /* WGL_WGLEXT_PROTOTYPES */
64 typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
65
66 #define WGL_CONTEXT_MAJOR_VERSION_ARB  0x2091
67 #define WGL_CONTEXT_MINOR_VERSION_ARB  0x2092
68 #define WGL_CONTEXT_LAYER_PLANE_ARB    0x2093
69 #define WGL_CONTEXT_FLAGS_ARB          0x2094
70 #define WGL_CONTEXT_PROFILE_MASK_ARB   0x9126
71
72 #define WGL_CONTEXT_DEBUG_BIT_ARB      0x0001
73 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
74
75 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
76 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
77
78 #define ERROR_INVALID_VERSION_ARB      0x2095
79 #define ERROR_INVALID_PROFILE_ARB      0x2096
80 #endif
81 /* End of copying the necessary parts out of it. */
82
83 #ifdef WM_TOUCH
84 typedef BOOL (WINAPI *pRegisterTouchWindow)(HWND,ULONG);
85 static pRegisterTouchWindow fghRegisterTouchWindow = (pRegisterTouchWindow)0xDEADBEEF;
86 #endif
87
88 /* 
89  * Helper functions for getting client area from the window rect
90  * and the window rect from the client area given the style of the window
91  * (or a valid window pointer from which the style can be queried).
92  */
93 extern void fghGetBorderWidth(const DWORD windowStyle, int* xBorderWidth, int* yBorderWidth);
94
95
96 /*
97  * Setup the pixel format for a Win32 window
98  */
99
100 #if defined(_WIN32_WCE)
101 static wchar_t* fghWstrFromStr(const char* str)
102 {
103     int i,len=strlen(str);
104     wchar_t* wstr = (wchar_t*)malloc(2*len+2);
105     for(i=0; i<len; i++)
106         wstr[i] = str[i];
107     wstr[len] = 0;
108     return wstr;
109 }
110 #endif /* defined(_WIN32_WCE) */
111
112
113 static void fghFillContextAttributes( int *attributes ) {
114   int where = 0, contextFlags, contextProfile;
115
116   if ( !fghIsLegacyContextVersionRequested() ) {
117     ATTRIB_VAL( WGL_CONTEXT_MAJOR_VERSION_ARB, fgState.MajorVersion );
118     ATTRIB_VAL( WGL_CONTEXT_MINOR_VERSION_ARB, fgState.MinorVersion );
119   }
120
121   contextFlags =
122     fghMapBit( fgState.ContextFlags, GLUT_DEBUG, WGL_CONTEXT_DEBUG_BIT_ARB ) |
123     fghMapBit( fgState.ContextFlags, GLUT_FORWARD_COMPATIBLE, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB );
124   if ( contextFlags != 0 ) {
125     ATTRIB_VAL( WGL_CONTEXT_FLAGS_ARB, contextFlags );
126   }
127
128   contextProfile =
129     fghMapBit( fgState.ContextProfile, GLUT_CORE_PROFILE, WGL_CONTEXT_CORE_PROFILE_BIT_ARB ) |
130     fghMapBit( fgState.ContextProfile, GLUT_COMPATIBILITY_PROFILE, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB );
131   if ( contextProfile != 0 ) {
132     ATTRIB_VAL( WGL_CONTEXT_PROFILE_MASK_ARB, contextProfile );
133   }
134
135   ATTRIB( 0 );
136 }
137
138 static int fghIsExtensionSupported( HDC hdc, const char *extension ) {
139     const char *pWglExtString;
140     PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetEntensionsStringARB =
141       (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
142     if ( wglGetEntensionsStringARB == NULL )
143     {
144       return FALSE;
145     }
146     pWglExtString = wglGetEntensionsStringARB( hdc );
147     return ( pWglExtString != NULL ) && ( strstr(pWglExtString, extension) != NULL );
148 }
149
150 void fgNewWGLCreateContext( SFG_Window* window )
151 {
152     HGLRC context;
153     int attributes[9];
154     PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
155
156     /* If nothing fancy has been required, leave the context as it is */
157     if ( fghIsLegacyContextRequested() )
158     {
159         return;
160     }
161
162     wglMakeCurrent( window->Window.pContext.Device, window->Window.Context );
163
164     if ( !fghIsExtensionSupported( window->Window.pContext.Device, "WGL_ARB_create_context" ) )
165     {
166         return;
167     }
168
169     /* new context creation */
170     fghFillContextAttributes( attributes );
171
172     wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress( "wglCreateContextAttribsARB" );
173     if ( wglCreateContextAttribsARB == NULL )
174     {
175         fgError( "wglCreateContextAttribsARB not found" );
176     }
177
178     context = wglCreateContextAttribsARB( window->Window.pContext.Device, 0, attributes );
179     if ( context == NULL )
180     {
181         fghContextCreationError();
182     }
183
184     wglMakeCurrent( NULL, NULL );
185     wglDeleteContext( window->Window.Context );
186     window->Window.Context = context;
187 }
188
189 #if !defined(_WIN32_WCE)
190
191 static void fghFillPFD( PIXELFORMATDESCRIPTOR *ppfd, HDC hdc, unsigned char layer_type )
192 {
193   int flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
194   if ( fgState.DisplayMode & GLUT_DOUBLE ) {
195         flags |= PFD_DOUBLEBUFFER;
196   }
197   if ( fgState.DisplayMode & GLUT_STEREO ) {
198     flags |= PFD_STEREO;
199   }
200
201 #if defined(_MSC_VER)
202 #pragma message( "fgSetupPixelFormat(): there is still some work to do here!" )
203 #endif
204
205   /* Specify which pixel format do we opt for... */
206   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
207   ppfd->nVersion = 1;
208   ppfd->dwFlags = flags;
209
210   if( fgState.DisplayMode & GLUT_INDEX ) {
211     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
212     ppfd->cRedBits = 0;
213     ppfd->cGreenBits = 0;
214     ppfd->cBlueBits = 0;
215     ppfd->cAlphaBits = 0;
216   } else {
217     ppfd->iPixelType = PFD_TYPE_RGBA;
218     ppfd->cRedBits = 8;
219     ppfd->cGreenBits = 8;
220     ppfd->cBlueBits = 8;
221     ppfd->cAlphaBits = ( fgState.DisplayMode & GLUT_ALPHA ) ? 8 : 0;
222   }
223
224   ppfd->cColorBits = 24;
225   ppfd->cRedShift = 0;
226   ppfd->cGreenShift = 0;
227   ppfd->cBlueShift = 0;
228   ppfd->cAlphaShift = 0;
229   ppfd->cAccumBits = ( fgState.DisplayMode & GLUT_ACCUM ) ? 1 : 0;
230   ppfd->cAccumRedBits = 0;
231   ppfd->cAccumGreenBits = 0;
232   ppfd->cAccumBlueBits = 0;
233   ppfd->cAccumAlphaBits = 0;
234
235   /* Hmmm, or 32/0 instead of 24/8? */
236   ppfd->cDepthBits = 24;
237   ppfd->cStencilBits = 8;
238
239   ppfd->cAuxBuffers = fghNumberOfAuxBuffersRequested();
240   ppfd->iLayerType = layer_type;
241   ppfd->bReserved = 0;
242   ppfd->dwLayerMask = 0;
243   ppfd->dwVisibleMask = 0;
244   ppfd->dwDamageMask = 0;
245   
246   ppfd->cColorBits = (BYTE) GetDeviceCaps( hdc, BITSPIXEL );
247 }
248
249 static void fghFillPixelFormatAttributes( int *attributes, const PIXELFORMATDESCRIPTOR *ppfd )
250 {
251   int where = 0;
252
253   ATTRIB_VAL( WGL_DRAW_TO_WINDOW_ARB, GL_TRUE );
254   ATTRIB_VAL( WGL_SUPPORT_OPENGL_ARB, GL_TRUE );
255   ATTRIB_VAL( WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB );
256
257   ATTRIB_VAL( WGL_COLOR_BITS_ARB, ppfd->cColorBits );
258   ATTRIB_VAL( WGL_ALPHA_BITS_ARB, ppfd->cAlphaBits );
259   ATTRIB_VAL( WGL_DEPTH_BITS_ARB, ppfd->cDepthBits );
260   ATTRIB_VAL( WGL_STENCIL_BITS_ARB, ppfd->cStencilBits );
261
262   ATTRIB_VAL( WGL_DOUBLE_BUFFER_ARB, ( fgState.DisplayMode & GLUT_DOUBLE ) != 0 );
263
264   if ( fgState.DisplayMode & GLUT_SRGB ) {
265     ATTRIB_VAL( WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, TRUE );
266   }
267
268   ATTRIB_VAL( WGL_SAMPLE_BUFFERS_ARB, GL_TRUE );
269   ATTRIB_VAL( WGL_SAMPLES_ARB, fgState.SampleNumber );
270   ATTRIB( 0 );
271 }
272 #endif
273
274 GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
275                               unsigned char layer_type )
276 {
277 #if defined(_WIN32_WCE)
278     return GL_TRUE;
279 #else
280     PIXELFORMATDESCRIPTOR pfd;
281     PIXELFORMATDESCRIPTOR* ppfd = &pfd;
282     int pixelformat;
283     HDC current_hDC;
284     GLboolean success;
285
286     if (checkOnly)
287       current_hDC = CreateDC(TEXT("DISPLAY"), NULL ,NULL ,NULL);
288     else
289       current_hDC = window->Window.pContext.Device;
290
291     fghFillPFD( ppfd, current_hDC, layer_type );
292     pixelformat = ChoosePixelFormat( current_hDC, ppfd );
293
294     /* windows hack for multismapling/sRGB */
295     if ( ( fgState.DisplayMode & GLUT_MULTISAMPLE ) ||
296          ( fgState.DisplayMode & GLUT_SRGB ) )
297     {        
298         HGLRC rc, rc_before=wglGetCurrentContext();
299         HWND hWnd;
300         HDC hDC, hDC_before=wglGetCurrentDC();
301         WNDCLASS wndCls;
302
303         /* create a dummy window */
304         ZeroMemory(&wndCls, sizeof(wndCls));
305         wndCls.lpfnWndProc = DefWindowProc;
306         wndCls.hInstance = fgDisplay.pDisplay.Instance;
307         wndCls.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
308         wndCls.lpszClassName = _T("FREEGLUT_dummy");
309         RegisterClass( &wndCls );
310
311         hWnd=CreateWindow(_T("FREEGLUT_dummy"), _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.pDisplay.Instance, 0 );
312         hDC=GetDC(hWnd);
313         SetPixelFormat( hDC, pixelformat, ppfd );
314
315         rc = wglCreateContext( hDC );
316         wglMakeCurrent(hDC, rc);
317
318         if ( fghIsExtensionSupported( hDC, "WGL_ARB_multisample" ) )
319         {
320             PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc =
321               (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
322             if ( wglChoosePixelFormatARBProc )
323             {
324                 int attributes[100];
325                 int iPixelFormat;
326                 BOOL bValid;
327                 float fAttributes[] = { 0, 0 };
328                 UINT numFormats;
329                 fghFillPixelFormatAttributes( attributes, ppfd );
330                 bValid = wglChoosePixelFormatARBProc(hDC, attributes, fAttributes, 1, &iPixelFormat, &numFormats);
331
332                 if ( bValid && numFormats > 0 )
333                 {
334                     pixelformat = iPixelFormat;
335                 }
336             }
337         }
338
339         wglMakeCurrent( hDC_before, rc_before);
340         wglDeleteContext(rc);
341         ReleaseDC(hWnd, hDC);
342         DestroyWindow(hWnd);
343         UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.pDisplay.Instance);
344     }
345
346     success = ( pixelformat != 0 ) && ( checkOnly || SetPixelFormat( current_hDC, pixelformat, ppfd ) );
347
348     if (checkOnly)
349         DeleteDC(current_hDC);
350
351     return success;
352 #endif /* defined(_WIN32_WCE) */
353 }
354
355
356
357 void fgPlatformSetWindow ( SFG_Window *window )
358 {
359     if ( window != fgStructure.CurrentWindow )
360     {
361         if( fgStructure.CurrentWindow )
362             ReleaseDC( fgStructure.CurrentWindow->Window.Handle,
363                        fgStructure.CurrentWindow->Window.pContext.Device );
364
365         if ( window )
366         {
367             window->Window.pContext.Device = GetDC( window->Window.Handle );
368             wglMakeCurrent(
369                 window->Window.pContext.Device,
370                 window->Window.Context
371             );
372         }
373     }
374 }
375
376
377
378 /* Computes position of corners of window Rect (outer position including
379  * decorations) based on the provided client rect and based on the style
380  * of the window in question.
381  * If posIsOutside is set to true, the input client Rect is taken to follow
382  * freeGLUT's window specification convention in which the top-left corner
383  * is at the outside of the window, while the size
384  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
385  * area.
386  */
387 void fghComputeWindowRectFromClientArea_UseStyle( const DWORD windowStyle, RECT *clientRect, BOOL posIsOutside )
388 {
389     int xBorderWidth = 0, yBorderWidth = 0;
390
391     /* If window has title bar, correct rect for it */
392     if (windowStyle & WS_MAXIMIZEBOX) /* Need to query for WS_MAXIMIZEBOX to see if we have a title bar, the WS_CAPTION query is also true for a WS_DLGFRAME only... */
393         if (posIsOutside)
394             clientRect->bottom += GetSystemMetrics( SM_CYCAPTION );
395         else
396             clientRect->top -= GetSystemMetrics( SM_CYCAPTION );
397
398     /* get width of window's borders (frame), correct rect for it.
399      * Note, borders can be of zero width if style does not specify borders
400      */
401     fghGetBorderWidth(windowStyle, &xBorderWidth, &yBorderWidth);
402     if (posIsOutside)
403     {
404         clientRect->right  += xBorderWidth * 2;
405         clientRect->bottom += yBorderWidth * 2;
406     }
407     else
408     {
409         clientRect->left   -= xBorderWidth;
410         clientRect->right  += xBorderWidth;
411         clientRect->top    -= yBorderWidth;
412         clientRect->bottom += yBorderWidth;
413     }
414 }
415
416 /* Computes position of corners of window Rect (outer position including
417  * decorations) based on the provided client rect and based on the style
418  * of the window in question. If the window pointer or the window handle
419  * is NULL, a fully decorated window (caption and border) is assumed.
420  * Furthermore, if posIsOutside is set to true, the input client Rect is
421  * taken to follow freeGLUT's window specification convention in which the
422  * top-left corner is at the outside of the window, while the size
423  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
424  * area.
425 */
426 void fghComputeWindowRectFromClientArea_QueryWindow( const SFG_Window *window, RECT *clientRect, BOOL posIsOutside )
427 {
428     DWORD windowStyle = 0;
429
430     if (window && window->Window.Handle)
431         windowStyle = GetWindowLong(window->Window.Handle, GWL_STYLE);
432     else
433         windowStyle = WS_OVERLAPPEDWINDOW;
434
435     fghComputeWindowRectFromClientArea_UseStyle(windowStyle, clientRect, posIsOutside);
436 }
437
438 /* Computes position of corners of client area (drawable area) of a window
439  * based on the provided window Rect (outer position including decorations)
440  * and based on the style of the window in question. If the window pointer
441  * or the window handle is NULL, a fully decorated window (caption and
442  * border) is assumed.
443  * Furthermore, if wantPosOutside is set to true, the output client Rect
444  * will follow freeGLUT's window specification convention in which the
445  * top-left corner is at the outside of the window, the size
446  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
447  * area.
448  */
449 void fghComputeClientAreaFromWindowRect( const SFG_Window *window, RECT *windowRect, BOOL wantPosOutside )
450 {
451     DWORD windowStyle = 0;
452     int xBorderWidth = 0, yBorderWidth = 0;
453
454     if (window && window->Window.Handle)
455         windowStyle = GetWindowLong(window->Window.Handle, GWL_STYLE);
456     else
457         windowStyle = WS_OVERLAPPEDWINDOW;
458
459     /* If window has title bar, correct rect for it */
460     if (windowStyle & WS_MAXIMIZEBOX) /* Need to query for WS_MAXIMIZEBOX to see if we have a title bar, the WS_CAPTION query is also true for a WS_DLGFRAME only... */
461         if (wantPosOutside)
462             windowRect->bottom -= GetSystemMetrics( SM_CYCAPTION );
463         else
464             windowRect->top    += GetSystemMetrics( SM_CYCAPTION );
465
466     /* get width of window's borders (frame), correct rect for it.
467      * Note, borders can be of zero width if style does not specify borders
468      */
469     fghGetBorderWidth(windowStyle, &xBorderWidth, &yBorderWidth);
470     if (wantPosOutside)
471     {
472         windowRect->right  -= xBorderWidth * 2;
473         windowRect->bottom -= yBorderWidth * 2;
474     }
475     else
476     {
477         windowRect->left   += xBorderWidth;
478         windowRect->right  -= xBorderWidth;
479         windowRect->top    += yBorderWidth;
480         windowRect->bottom -= yBorderWidth;
481     }
482 }
483
484 /* Gets the rect describing the client area (drawable area) of the
485  * specified window.
486  * Returns an empty rect if window pointer or window handle is NULL.
487  * If wantPosOutside is set to true, the output client Rect
488  * will follow freeGLUT's window specification convention in which the
489  * top-left corner is at the outside of the window, while the size
490  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
491  * area.
492  */
493 RECT fghGetClientArea( const SFG_Window *window, BOOL wantPosOutside )
494 {
495     RECT windowRect = {0,0,0,0};
496
497     freeglut_return_val_if_fail((window && window->Window.Handle),windowRect);
498     
499     /*
500      * call GetWindowRect()
501      * (this returns the pixel coordinates of the outside of the window)
502      */
503     GetWindowRect( window->Window.Handle, &windowRect );
504
505     /* Then correct the results */
506     fghComputeClientAreaFromWindowRect(window, &windowRect, wantPosOutside);
507
508     return windowRect;
509 }
510
511 /* Returns the width of the window borders based on the window's style.
512  */
513 void fghGetBorderWidth(const DWORD windowStyle, int* xBorderWidth, int* yBorderWidth)
514 {
515     if (windowStyle & WS_THICKFRAME)
516     {
517         *xBorderWidth = GetSystemMetrics(SM_CXSIZEFRAME);
518         *yBorderWidth = GetSystemMetrics(SM_CYSIZEFRAME);
519     }
520     else if (windowStyle & WS_DLGFRAME)
521     {
522         *xBorderWidth = GetSystemMetrics(SM_CXFIXEDFRAME);
523         *yBorderWidth = GetSystemMetrics(SM_CYFIXEDFRAME);
524     }
525     else
526     {
527         *xBorderWidth = 0;
528         *yBorderWidth = 0;
529     }
530 }
531
532 #if(WINVER >= 0x500)
533 typedef struct
534 {
535       int *x;
536       int *y;
537       const char *name;
538 } m_proc_t;
539
540 static BOOL CALLBACK m_proc(HMONITOR mon,
541                             HDC hdc,
542                             LPRECT rect,
543                             LPARAM data)
544 {
545       m_proc_t *dp=(m_proc_t *)data;
546       MONITORINFOEX info;
547       BOOL res;
548       info.cbSize=sizeof(info);
549       res=GetMonitorInfo(mon,(LPMONITORINFO)&info);
550       if( res )
551       {
552           if( strcmp(dp->name,info.szDevice)==0 )
553           {
554               *(dp->x)=info.rcMonitor.left;
555               *(dp->y)=info.rcMonitor.top;
556               return FALSE;
557           }
558       }
559       return TRUE;
560 }
561
562 /* 
563  * this function returns the origin of the screen identified by
564  * fgDisplay.pDisplay.DisplayName, and 0 otherwise.
565  * This is used in fgOpenWindow to open the gamemode window on the screen
566  * identified by the -display command line argument. The function should
567  * not be called otherwise.
568  */
569
570 static void get_display_origin(int *xp,int *yp)
571 {
572     *xp = 0;
573     *yp = 0;
574
575     if( fgDisplay.pDisplay.DisplayName )
576     {
577         m_proc_t st;
578         st.x=xp;
579         st.y=yp;
580         st.name=fgDisplay.pDisplay.DisplayName;
581         EnumDisplayMonitors(0,0,m_proc,(LPARAM)&st);
582     }
583 }
584 #else
585 #pragma message( "-display parameter only works if compiled with WINVER >= 0x0500")
586
587 static void get_display_origin(int *xp,int *yp)
588 {
589     *xp = 0;
590     *yp = 0;
591
592     if( fgDisplay.pDisplay.DisplayName )
593     {
594         fgWarning( "for working -display support FreeGLUT must be compiled with WINVER >= 0x0500");
595     }
596 }
597 #endif
598
599
600
601 /*
602  * Opens a window. Requires a SFG_Window object created and attached
603  * to the freeglut structure. OpenGL context is created here.
604  */
605 void fgPlatformOpenWindow( SFG_Window* window, const char* title,
606                            GLboolean positionUse, int x, int y,
607                            GLboolean sizeUse, int w, int h,
608                            GLboolean gameMode, GLboolean isSubWindow )
609 {
610
611     WNDCLASS wc;
612     DWORD flags   = 0;
613     DWORD exFlags = 0;
614     ATOM atom;
615
616     /* Grab the window class we have registered on glutInit(): */
617     atom = GetClassInfo( fgDisplay.pDisplay.Instance, _T("FREEGLUT"), &wc );
618     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
619                                    "fgOpenWindow" );
620
621     /* Determine window style flags*/
622     if( gameMode )
623     {
624         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
625                                        "Game mode being invoked on a subwindow",
626                                        "fgOpenWindow" );
627
628         /*
629          * Set the window creation flags appropriately to make the window
630          * entirely visible:
631          */
632         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
633     }
634     else
635     {
636         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
637
638         /*
639          * There's a small difference between creating the top, child and
640          * menu windows
641          */
642         if ( window->IsMenu )
643         {
644             flags |= WS_POPUP;
645             exFlags |= WS_EX_TOOLWINDOW;
646         }
647 #if defined(_WIN32_WCE)
648         /* no decorations for windows CE */
649 #else
650         /* if this is not a subwindow (child), set its style based on the requested display mode */
651         else if( window->Parent == NULL )
652             if ( fgState.DisplayMode & GLUT_BORDERLESS )
653             {
654                 /* no window decorations needed */
655             }
656             else if ( fgState.DisplayMode & GLUT_CAPTIONLESS )
657                 /* only window decoration is a border, no title bar or buttons */
658                 flags |= WS_DLGFRAME;
659             else
660                 /* window decoration are a border, title bar and buttons.
661                  * NB: we later query whether the window has a title bar or
662                  * not by testing for the maximize button, as the test for
663                  * WS_CAPTION can be true without the window having a title
664                  * bar. This style WS_OVERLAPPEDWINDOW gives you a maximize
665                  * button. */
666                 flags |= WS_OVERLAPPEDWINDOW;
667 #endif
668         else
669             /* subwindows always have no decoration, but are marked as a child window to the OS */
670             flags |= WS_CHILD;
671     }
672
673     /* determine window size and position */
674     if( gameMode )
675     {
676         /* if in gamemode, query the origin of specified by the -display
677          * command line parameter (if any) and offset the upper-left corner
678          * of the window so we create the window on that screen.
679          * The -display argument doesn't do anything if not trying to enter
680          * gamemode.
681          */
682         int xoff=0, yoff=0;
683         get_display_origin(&xoff,&yoff);
684         x += xoff;
685         y += yoff;
686     }
687     if( !positionUse )
688     {
689         x = CW_USEDEFAULT;
690         y = CW_USEDEFAULT;
691     }
692     if( !sizeUse )
693     {
694         if( ! window->IsMenu )
695         {
696             w = CW_USEDEFAULT;
697             h = CW_USEDEFAULT;
698         }
699         else /* fail safe - Windows can make a window of size (0, 0) */
700             w = h = 300; /* default window size */
701     }
702     /* store requested client area width and height */
703     window->State.Width = w;
704     window->State.Height = h;
705
706 #if !defined(_WIN32_WCE)    /* no decorations for windows CE */
707     if( sizeUse )
708     {
709         RECT windowRect;
710         /*
711          * Update the window dimensions, taking the window decorations
712          * into account.  FreeGLUT is to create the window with the
713          * topleft outside corner at (x,y) and with client area
714          * dimensions (w,h).
715          * note: don't need to do this when w=h=CW_USEDEFAULT, so in the
716          * if( sizeUse ) here is convenient.
717          */
718         windowRect.left     = x;
719         windowRect.top      = y;
720         windowRect.right    = x+w;
721         windowRect.bottom   = y+h;
722
723         fghComputeWindowRectFromClientArea_UseStyle(flags,&windowRect,TRUE);
724
725         w = windowRect.right - windowRect.left;
726         h = windowRect.bottom- windowRect.top;
727     }
728 #endif /* !defined(_WIN32_WCE) */
729
730 #if defined(_WIN32_WCE)
731     {
732         wchar_t* wstr = fghWstrFromStr(title);
733
734         window->Window.Handle = CreateWindow(
735             _T("FREEGLUT"),
736             wstr,
737             WS_VISIBLE | WS_POPUP,
738             0,0, 240,320,
739             NULL,
740             NULL,
741             fgDisplay.pDisplay.Instance,
742             (LPVOID) window
743         );
744
745         free(wstr);
746
747         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
748         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
749         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
750         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
751         ShowWindow(window->Window.Handle, SW_SHOW);
752         UpdateWindow(window->Window.Handle);
753     }
754 #else
755     window->Window.Handle = CreateWindowEx(
756         exFlags,
757         _T("FREEGLUT"),
758         title,
759         flags,
760         x, y, w, h,
761         (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
762         (HMENU) NULL,
763         fgDisplay.pDisplay.Instance,
764         (LPVOID) window
765     );
766 #endif /* defined(_WIN32_WCE) */
767
768     if( !( window->Window.Handle ) )
769         fgError( "Failed to create a window (%s)!", title );
770
771 #if !defined(_WIN32_WCE)
772     /* Need to set requested style again, apparently Windows doesn't listen when requesting windows without title bar or borders */
773     SetWindowLong(window->Window.Handle, GWL_STYLE, flags);
774     SetWindowPos(window->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
775 #endif /* defined(_WIN32_WCE) */
776
777     /* Make a menu window always on top - fix Feature Request 947118 */
778     if( window->IsMenu || gameMode )
779         SetWindowPos(
780                         window->Window.Handle,
781                         HWND_TOPMOST,
782                         0, 0, 0, 0,
783                         SWP_NOMOVE | SWP_NOSIZE
784                     );
785
786     /* Enable multitouch: additional flag TWF_FINETOUCH, TWF_WANTPALM */
787     #ifdef WM_TOUCH
788         if (fghRegisterTouchWindow == (pRegisterTouchWindow)0xDEADBEEF) 
789                         fghRegisterTouchWindow = (pRegisterTouchWindow)GetProcAddress(GetModuleHandle("user32"),"RegisterTouchWindow");
790                 if (fghRegisterTouchWindow)
791              fghRegisterTouchWindow( window->Window.Handle, TWF_FINETOUCH | TWF_WANTPALM );
792     #endif
793
794 #if defined(_WIN32_WCE)
795     ShowWindow( window->Window.Handle, SW_SHOW );
796 #else
797     ShowWindow( window->Window.Handle,
798                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOW );
799 #endif /* defined(_WIN32_WCE) */
800
801     UpdateWindow( window->Window.Handle );
802     ShowCursor( TRUE );  /* XXX Old comments say "hide cursor"! */
803
804 }
805
806
807 /*
808  * Closes a window, destroying the frame and OpenGL context
809  */
810 void fgPlatformCloseWindow( SFG_Window* window )
811 {
812     /* Make sure we don't close a window with current context active */
813     if( fgStructure.CurrentWindow == window )
814         wglMakeCurrent( NULL, NULL );
815
816     /*
817      * Step through the list of windows.  If the rendering context
818      * is not being used by another window, then we delete it.
819      */
820     {
821         int used = FALSE ;
822         SFG_Window *iter ;
823
824         for( iter = (SFG_Window *)fgStructure.Windows.First;
825              iter;
826              iter = (SFG_Window *)iter->Node.Next )
827         {
828             if( ( iter->Window.Context == window->Window.Context ) &&
829                 ( iter != window ) )
830                 used = TRUE;
831         }
832
833         if( ! used )
834             wglDeleteContext( window->Window.Context );
835     }
836
837     DestroyWindow( window->Window.Handle );
838 }
839
840
841
842 /*
843  * This function makes the current window visible
844  */
845 void fgPlatformGlutShowWindow( void )
846 {
847     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
848 }
849
850 /*
851  * This function hides the current window
852  */
853 void fgPlatformGlutHideWindow( void )
854 {
855     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
856 }
857
858 /*
859  * Iconify the current window (top-level windows only)
860  */
861 void fgPlatformGlutIconifyWindow( void )
862 {
863     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_MINIMIZE );
864 }
865
866 /*
867  * Set the current window's title
868  */
869 void fgPlatformGlutSetWindowTitle( const char* title )
870 {
871 #ifdef _WIN32_WCE
872     {
873         wchar_t* wstr = fghWstrFromStr(title);
874         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
875         free(wstr);
876     }
877 #else
878     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
879 #endif
880 }
881
882 /*
883  * Set the current window's iconified title
884  */
885 void fgPlatformGlutSetIconTitle( const char* title )
886 {
887 #ifdef _WIN32_WCE
888     {
889         wchar_t* wstr = fghWstrFromStr(title);
890         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
891         free(wstr);
892     }
893 #else
894     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
895 #endif
896 }
897
898 /*
899  * Change the current window's position
900  */
901 void fgPlatformGlutPositionWindow( int x, int y )
902 {
903     RECT winRect;
904
905     /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
906     GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
907     MoveWindow(
908         fgStructure.CurrentWindow->Window.Handle,
909         x,
910         y,
911         winRect.right - winRect.left,
912         winRect.bottom - winRect.top,
913         TRUE
914     );
915 }
916
917 /*
918  * Lowers the current window (by Z order change)
919  */
920 void fgPlatformGlutPushWindow( void )
921 {
922     SetWindowPos(
923         fgStructure.CurrentWindow->Window.Handle,
924         HWND_BOTTOM,
925         0, 0, 0, 0,
926         SWP_NOSIZE | SWP_NOMOVE
927     );
928 }
929
930 /*
931  * Raises the current window (by Z order change)
932  */
933 void fgPlatformGlutPopWindow( void )
934 {
935     SetWindowPos(
936         fgStructure.CurrentWindow->Window.Handle,
937         HWND_TOP,
938         0, 0, 0, 0,
939         SWP_NOSIZE | SWP_NOMOVE
940     );
941 }
942
943 /*
944  * Resize the current window so that it fits the whole screen
945  */
946 void fgPlatformGlutFullScreen( SFG_Window *win )
947 {
948 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
949
950     if (glutGet(GLUT_FULL_SCREEN))
951     {
952         /*  Leave full screen state before entering fullscreen again (resizing?) */
953         glutLeaveFullScreen();
954     }
955
956     {
957 #if(WINVER >= 0x0500) /* Windows 2000 or later */
958         DWORD s;
959         RECT rect;
960         HMONITOR hMonitor;
961         MONITORINFO mi;
962
963         /* For fullscreen mode, first remove all window decoration
964          * and set style to popup so it will overlap the taskbar
965          * then force to maximize on the screen on which it has the most
966          * overlap.
967          */
968
969         
970         /* store current window rect */
971         GetWindowRect( win->Window.Handle, &win->State.pWState.OldRect );
972
973         /* store current window style */
974         win->State.pWState.OldStyle = s = GetWindowLong(win->Window.Handle, GWL_STYLE);
975
976         /* remove decorations from style and add popup style*/
977         s &= ~WS_OVERLAPPEDWINDOW;
978         s |= WS_POPUP;
979         SetWindowLong(win->Window.Handle, GWL_STYLE, s);
980         SetWindowPos(win->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
981
982         /* For fullscreen mode, find the monitor that is covered the most
983          * by the window and get its rect as the resize target.
984              */
985         hMonitor= MonitorFromRect(&win->State.pWState.OldRect, MONITOR_DEFAULTTONEAREST);
986         mi.cbSize = sizeof(mi);
987         GetMonitorInfo(hMonitor, &mi);
988         rect = mi.rcMonitor;
989 #else   /* if (WINVER >= 0x0500) */
990         RECT rect;
991
992         /* For fullscreen mode, force the top-left corner to 0,0
993          * and adjust the window rectangle so that the client area
994          * covers the whole screen.
995          */
996
997         rect.left   = 0;
998         rect.top    = 0;
999         rect.right  = fgDisplay.ScreenWidth;
1000         rect.bottom = fgDisplay.ScreenHeight;
1001
1002         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
1003                                   WS_CLIPCHILDREN, FALSE );
1004 #endif  /* (WINVER >= 0x0500) */
1005
1006         /*
1007          * then resize window
1008          * SWP_NOACTIVATE     Do not activate the window
1009          * SWP_NOOWNERZORDER  Do not change position in z-order
1010          * SWP_NOSENDCHANGING Suppress WM_WINDOWPOSCHANGING message
1011          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
1012          */
1013         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
1014                       HWND_TOP,
1015                       rect.left,
1016                       rect.top,
1017                       rect.right  - rect.left,
1018                       rect.bottom - rect.top,
1019                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1020                       SWP_NOZORDER
1021                     );
1022
1023         win->State.IsFullscreen = GL_TRUE;
1024     }
1025 #endif
1026 }
1027
1028 /*
1029  * If we are fullscreen, resize the current window back to its original size
1030  */
1031 void fgPlatformGlutLeaveFullScreen( SFG_Window *win )
1032 {
1033 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
1034     if (!glutGet(GLUT_FULL_SCREEN))
1035     {
1036         /* nothing to do */
1037         return;
1038     }
1039
1040     /* restore style of window before making it fullscreen */
1041     SetWindowLong(win->Window.Handle, GWL_STYLE, win->State.pWState.OldStyle);
1042     SetWindowPos(win->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
1043
1044     /* Then resize */
1045     SetWindowPos(win->Window.Handle,
1046         HWND_TOP,
1047         win->State.pWState.OldRect.left,
1048         win->State.pWState.OldRect.top,
1049         win->State.pWState.OldRect.right  - win->State.pWState.OldRect.left,
1050         win->State.pWState.OldRect.bottom - win->State.pWState.OldRect.top,
1051         SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1052         SWP_NOZORDER
1053         );
1054
1055     win->State.IsFullscreen = GL_FALSE;
1056 #endif
1057 }
1058
1059 /*
1060  * Toggle the window's full screen state.
1061  */
1062 void fgPlatformGlutFullScreenToggle( SFG_Window *win )
1063 {
1064     if (!win->State.IsFullscreen)
1065         glutFullScreen();
1066     else
1067         glutLeaveFullScreen();
1068 }
1069
1070
1071 /* -- PLATFORM-SPECIFIC INTERFACE FUNCTION -------------------------------------------------- */
1072
1073 int FGAPIENTRY __glutCreateWindowWithExit( const char *title, void (__cdecl *exit_function)(int) )
1074 {
1075   __glutExitFunc = exit_function;
1076   return glutCreateWindow( title );
1077 }
1078