3a6e646de11bc99e2816a3cf5922eafceee5789b
[blender.git] / intern / ghost / intern / GHOST_WindowWin32.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file ghost/intern/GHOST_WindowWin32.cpp
29  *  \ingroup GHOST
30  */
31
32
33 /**
34  * Copyright (C) 2001 NaN Technologies B.V.
35  * @author      Maarten Gribnau
36  * @date        May 10, 2001
37  */
38
39 #include <string.h>
40 #include "GHOST_WindowWin32.h"
41 #include "GHOST_SystemWin32.h"
42 #include "GHOST_DropTargetWin32.h"
43 #include "utfconv.h"
44 #include "utf_winfunc.h"
45
46 // Need glew for some defines
47 #include <GL/glew.h>
48 #include <GL/wglew.h>
49 #include <math.h>
50
51 // MSVC6 still doesn't define M_PI
52 #ifndef M_PI
53 #define M_PI 3.1415926536
54 #endif
55
56 // Some more multisample defines
57 #define WGL_SAMPLE_BUFFERS_ARB  0x2041
58 #define WGL_SAMPLES_ARB         0x2042
59
60 // win64 doesn't define GWL_USERDATA
61 #ifdef WIN32
62 #ifndef GWL_USERDATA
63 #define GWL_USERDATA GWLP_USERDATA
64 #define GWL_WNDPROC GWLP_WNDPROC
65 #endif
66 #endif
67
68 wchar_t *GHOST_WindowWin32::s_windowClassName = L"GHOST_WindowClass";
69 const int GHOST_WindowWin32::s_maxTitleLength = 128;
70 HGLRC GHOST_WindowWin32::s_firsthGLRc = NULL;
71 HDC GHOST_WindowWin32::s_firstHDC = NULL;
72
73 static int WeightPixelFormat(PIXELFORMATDESCRIPTOR& pfd);
74 static int EnumPixelFormats(HDC hdc);
75
76 /*
77  * Color and depth bit values are not to be trusted.
78  * For instance, on TNT2:
79  * When the screen color depth is set to 16 bit, we get 5 color bits
80  * and 16 depth bits.
81  * When the screen color depth is set to 32 bit, we get 8 color bits
82  * and 24 depth bits.
83  * Just to be safe, we request high waulity settings.
84  */
85 static PIXELFORMATDESCRIPTOR sPreferredFormat = {
86         sizeof(PIXELFORMATDESCRIPTOR),  /* size */
87         1,                              /* version */
88         PFD_SUPPORT_OPENGL |
89         PFD_DRAW_TO_WINDOW |
90         PFD_SWAP_COPY |                 /* support swap copy */
91         PFD_DOUBLEBUFFER,               /* support double-buffering */
92         PFD_TYPE_RGBA,                  /* color type */
93         32,                             /* prefered color depth */
94         0, 0, 0, 0, 0, 0,               /* color bits (ignored) */
95         0,                              /* no alpha buffer */
96         0,                              /* alpha bits (ignored) */
97         0,                              /* no accumulation buffer */
98         0, 0, 0, 0,                     /* accum bits (ignored) */
99         32,                             /* depth buffer */
100         0,                              /* no stencil buffer */
101         0,                              /* no auxiliary buffers */
102         PFD_MAIN_PLANE,                 /* main layer */
103         0,                              /* reserved */
104         0, 0, 0                         /* no layer, visible, damage masks */
105 };
106
107 /* Intel videocards don't work fine with multiple contexts and
108  * have to share the same context for all windows.
109  * But if we just share context for all windows it could work incorrect
110  * with multiple videocards configuration. Suppose, that Intel videocards
111  * can't be in multiple-devices configuration. */
112 static int is_crappy_intel_card(void)
113 {
114         int crappy = 0;
115         const char *vendor = (const char *)glGetString(GL_VENDOR);
116
117         if (strstr(vendor, "Intel"))
118                 crappy = 1;
119
120         return crappy;
121 }
122
123 GHOST_WindowWin32::GHOST_WindowWin32(
124     GHOST_SystemWin32 *system,
125     const STR_String& title,
126     GHOST_TInt32 left,
127     GHOST_TInt32 top,
128     GHOST_TUns32 width,
129     GHOST_TUns32 height,
130     GHOST_TWindowState state,
131     GHOST_TDrawingContextType type,
132     const bool stereoVisual,
133     const GHOST_TUns16 numOfAASamples,
134     GHOST_TEmbedderWindowID parentwindowhwnd,
135     GHOST_TSuccess msEnabled,
136     int msPixelFormat)
137         :
138         GHOST_Window(width, height, state, GHOST_kDrawingContextTypeNone,
139                      stereoVisual, numOfAASamples),
140         m_system(system),
141         m_hDC(0),
142         m_hGlRc(0),
143         m_hasMouseCaptured(false),
144         m_hasGrabMouse(false),
145         m_nPressedButtons(0),
146         m_customCursor(0),
147         m_wintab(NULL),
148         m_tabletData(NULL),
149         m_tablet(0),
150         m_maxPressure(0),
151         m_multisample(numOfAASamples),
152         m_parentWindowHwnd(parentwindowhwnd),
153         m_multisampleEnabled(msEnabled),
154         m_msPixelFormat(msPixelFormat),
155         //For recreation
156         m_title(title),
157         m_left(left),
158         m_top(top),
159         m_width(width),
160         m_height(height),
161         m_normal_state(GHOST_kWindowStateNormal),
162         m_stereo(stereoVisual),
163         m_nextWindow(NULL)
164 {
165         OSVERSIONINFOEX versionInfo;
166         bool hasMinVersionForTaskbar = false;
167         
168         ZeroMemory(&versionInfo, sizeof(OSVERSIONINFOEX));
169         
170         versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
171         
172         if (!GetVersionEx((OSVERSIONINFO *)&versionInfo)) {
173                 versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
174                 if (GetVersionEx((OSVERSIONINFO *)&versionInfo)) {
175                         if ((versionInfo.dwMajorVersion == 6 && versionInfo.dwMinorVersion >= 1) || versionInfo.dwMajorVersion >= 7) {
176                                 hasMinVersionForTaskbar = true;
177                         }
178                 }
179         }
180         else {
181                 if ((versionInfo.dwMajorVersion == 6 && versionInfo.dwMinorVersion >= 1) || versionInfo.dwMajorVersion >= 7) {
182                         hasMinVersionForTaskbar = true;
183                 }
184         }
185
186         if (state != GHOST_kWindowStateFullScreen) {
187                 RECT rect;
188                 MONITORINFO monitor;
189                 GHOST_TUns32 tw, th; 
190
191                 width += GetSystemMetrics(SM_CXSIZEFRAME) * 2;
192                 height += GetSystemMetrics(SM_CYSIZEFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION);
193
194                 rect.left = left;
195                 rect.right = left + width;
196                 rect.top = top;
197                 rect.bottom = top + height;
198
199                 monitor.cbSize = sizeof(monitor);
200                 monitor.dwFlags = 0;
201
202                 // take taskbar into account
203                 GetMonitorInfo(MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST), &monitor);
204
205                 th = monitor.rcWork.bottom - monitor.rcWork.top;
206                 tw = monitor.rcWork.right - monitor.rcWork.left;
207
208                 if (tw < width)
209                 {
210                         width = tw;
211                         left = monitor.rcWork.left;
212                 }
213                 else if (monitor.rcWork.right < left + (int)width)
214                         left = monitor.rcWork.right - width;
215                 else if (left < monitor.rcWork.left)
216                         left = monitor.rcWork.left;
217
218                 if (th < height)
219                 {
220                         height = th;
221                         top = monitor.rcWork.top;
222                 }
223                 else if (monitor.rcWork.bottom < top + (int)height)
224                         top = monitor.rcWork.bottom - height;
225                 else if (top < monitor.rcWork.top)
226                         top = monitor.rcWork.top;
227
228                 int wintype = WS_OVERLAPPEDWINDOW;
229                 if (m_parentWindowHwnd != 0)
230                 {
231                         wintype = WS_CHILD;
232                         GetWindowRect((HWND)m_parentWindowHwnd, &rect);
233                         left = 0;
234                         top = 0;
235                         width = rect.right - rect.left;
236                         height = rect.bottom - rect.top;
237                 }
238                 
239                 wchar_t *title_16 = alloc_utf16_from_8((char *)(const char *)title, 0);
240                 m_hWnd = ::CreateWindowW(
241                     s_windowClassName,          // pointer to registered class name
242                     title_16,                   // pointer to window name
243                     wintype,                    // window style
244                     left,                       // horizontal position of window
245                     top,                        // vertical position of window
246                     width,                      // window width
247                     height,                     // window height
248                     (HWND) m_parentWindowHwnd,  // handle to parent or owner window
249                     0,                          // handle to menu or child-window identifier
250                     ::GetModuleHandle(0),       // handle to application instance
251                     0);                         // pointer to window-creation data
252                 free(title_16);
253         }
254         else {
255                 wchar_t *title_16 = alloc_utf16_from_8((char *)(const char *)title, 0);
256                 m_hWnd = ::CreateWindowW(
257                     s_windowClassName,          // pointer to registered class name
258                     title_16,                   // pointer to window name
259                     WS_POPUP | WS_MAXIMIZE,     // window style
260                     left,                       // horizontal position of window
261                     top,                        // vertical position of window
262                     width,                      // window width
263                     height,                     // window height
264                     HWND_DESKTOP,               // handle to parent or owner window
265                     0,                          // handle to menu or child-window identifier
266                     ::GetModuleHandle(0),       // handle to application instance
267                     0);                         // pointer to window-creation data
268                 free(title_16);
269         }
270         if (m_hWnd) {
271                 // Register this window as a droptarget. Requires m_hWnd to be valid.
272                 // Note that OleInitialize(0) has to be called prior to this. Done in GHOST_SystemWin32.
273                 m_dropTarget = new GHOST_DropTargetWin32(this, m_system);
274                 // Store a pointer to this class in the window structure
275                 ::SetWindowLongPtr(m_hWnd, GWL_USERDATA, (LONG_PTR) this);
276
277                 // Store the device context
278                 m_hDC = ::GetDC(m_hWnd);
279
280                 if (!s_firstHDC) {
281                         s_firstHDC = m_hDC;
282                 }
283
284                 // Show the window
285                 int nCmdShow;
286                 switch (state) {
287                         case GHOST_kWindowStateMaximized:
288                                 nCmdShow = SW_SHOWMAXIMIZED;
289                                 break;
290                         case GHOST_kWindowStateMinimized:
291                                 nCmdShow = SW_SHOWMINIMIZED;
292                                 break;
293                         case GHOST_kWindowStateNormal:
294                         default:
295                                 nCmdShow = SW_SHOWNORMAL;
296                                 break;
297                 }
298                 GHOST_TSuccess success;
299                 success = setDrawingContextType(type);
300
301                 if (success)
302                 {
303                         ::ShowWindow(m_hWnd, nCmdShow);
304                         // Force an initial paint of the window
305                         ::UpdateWindow(m_hWnd);
306                 }
307                 else {
308                         //invalidate the window
309                         m_hWnd = 0;
310                 }
311         }
312
313         if (parentwindowhwnd != 0) {
314                 RAWINPUTDEVICE device = {0};
315                 device.usUsagePage  = 0x01; /* usUsagePage & usUsage for keyboard*/
316                 device.usUsage      = 0x06; /* http://msdn.microsoft.com/en-us/windows/hardware/gg487473.aspx */
317                 device.dwFlags |= RIDEV_INPUTSINK; // makes WM_INPUT is visible for ghost when has parent window
318                 device.hwndTarget = m_hWnd;
319                 RegisterRawInputDevices(&device, 1, sizeof(device));
320         }
321
322         m_wintab = ::LoadLibrary("Wintab32.dll");
323         if (m_wintab) {
324                 GHOST_WIN32_WTInfo fpWTInfo = (GHOST_WIN32_WTInfo) ::GetProcAddress(m_wintab, "WTInfoA");
325                 GHOST_WIN32_WTOpen fpWTOpen = (GHOST_WIN32_WTOpen) ::GetProcAddress(m_wintab, "WTOpenA");
326
327                 // let's see if we can initialize tablet here
328                 /* check if WinTab available. */
329                 if (fpWTInfo && fpWTInfo(0, 0, NULL)) {
330                         // Now init the tablet
331                         LOGCONTEXT lc;
332                         AXIS TabletX, TabletY, Pressure, Orientation[3]; /* The maximum tablet size, pressure and orientation (tilt) */
333
334                         // Open a Wintab context
335
336                         // Get default context information
337                         fpWTInfo(WTI_DEFCONTEXT, 0, &lc);
338
339                         // Open the context
340                         lc.lcPktData = PACKETDATA;
341                         lc.lcPktMode = PACKETMODE;
342                         lc.lcOptions |= CXO_MESSAGES | CXO_SYSTEM;
343
344                         /* Set the entire tablet as active */
345                         fpWTInfo(WTI_DEVICES, DVC_X, &TabletX);
346                         fpWTInfo(WTI_DEVICES, DVC_Y, &TabletY);
347
348                         /* get the max pressure, to divide into a float */
349                         BOOL pressureSupport = fpWTInfo(WTI_DEVICES, DVC_NPRESSURE, &Pressure);
350                         if (pressureSupport)
351                                 m_maxPressure = Pressure.axMax;
352                         else
353                                 m_maxPressure = 0;
354
355                         /* get the max tilt axes, to divide into floats */
356                         BOOL tiltSupport = fpWTInfo(WTI_DEVICES, DVC_ORIENTATION, &Orientation);
357                         if (tiltSupport) {
358                                 /* does the tablet support azimuth ([0]) and altitude ([1]) */
359                                 if (Orientation[0].axResolution && Orientation[1].axResolution) {
360                                         /* all this assumes the minimum is 0 */
361                                         m_maxAzimuth = Orientation[0].axMax;
362                                         m_maxAltitude = Orientation[1].axMax;
363                                 }
364                                 else {  /* no so dont do tilt stuff */
365                                         m_maxAzimuth = m_maxAltitude = 0;
366                                 }
367                         }
368
369                         if (fpWTOpen) {
370                                 m_tablet = fpWTOpen(m_hWnd, &lc, TRUE);
371                                 if (m_tablet) {
372                                         m_tabletData = new GHOST_TabletData();
373                                         m_tabletData->Active = GHOST_kTabletModeNone;
374                                 }
375                         }
376                 }
377         }
378
379         if (hasMinVersionForTaskbar)
380                 CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList, (LPVOID *)&m_Bar);
381         else
382                 m_Bar = NULL;
383 }
384
385
386 GHOST_WindowWin32::~GHOST_WindowWin32()
387 {
388         if (m_Bar)
389         {
390                 m_Bar->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
391                 m_Bar->Release();
392         };
393
394         if (m_wintab) {
395                 GHOST_WIN32_WTClose fpWTClose = (GHOST_WIN32_WTClose) ::GetProcAddress(m_wintab, "WTClose");
396                 if (fpWTClose) {
397                         if (m_tablet)
398                                 fpWTClose(m_tablet);
399                         if (m_tabletData)
400                                 delete m_tabletData;
401                         m_tabletData = NULL;
402                 }
403         }
404         if (m_customCursor) {
405                 DestroyCursor(m_customCursor);
406                 m_customCursor = NULL;
407         }
408
409         ::wglMakeCurrent(NULL, NULL);
410         m_multisampleEnabled = GHOST_kFailure;
411         m_multisample = 0;
412         setDrawingContextType(GHOST_kDrawingContextTypeNone);
413         if (m_hDC && m_hDC != s_firstHDC) {
414                 ::ReleaseDC(m_hWnd, m_hDC);
415                 m_hDC = 0;
416         }
417         if (m_hWnd) {
418                 m_dropTarget->Release(); // frees itself.
419                 ::DestroyWindow(m_hWnd);
420                 m_hWnd = 0;
421         }
422 }
423
424 GHOST_Window *GHOST_WindowWin32::getNextWindow()
425 {
426         return m_nextWindow;
427 }
428
429 bool GHOST_WindowWin32::getValid() const
430 {
431         return m_hWnd != 0;
432 }
433
434 HWND GHOST_WindowWin32::getHWND() const
435 {
436         return m_hWnd;
437 }
438
439 void GHOST_WindowWin32::setTitle(const STR_String& title)
440 {
441         wchar_t *title_16 = alloc_utf16_from_8((char *)(const char *)title, 0);
442         ::SetWindowTextW(m_hWnd, (wchar_t *)title_16);
443         free(title_16);
444 }
445
446
447 void GHOST_WindowWin32::getTitle(STR_String& title) const
448 {
449         char buf[s_maxTitleLength]; /*CHANGE + never used yet*/
450         ::GetWindowText(m_hWnd, buf, s_maxTitleLength);
451         STR_String temp(buf);
452         title = buf;
453 }
454
455
456 void GHOST_WindowWin32::getWindowBounds(GHOST_Rect& bounds) const
457 {
458         RECT rect;
459         ::GetWindowRect(m_hWnd, &rect);
460         bounds.m_b = rect.bottom;
461         bounds.m_l = rect.left;
462         bounds.m_r = rect.right;
463         bounds.m_t = rect.top;
464 }
465
466
467 void GHOST_WindowWin32::getClientBounds(GHOST_Rect& bounds) const
468 {
469         RECT rect;
470         GHOST_TWindowState state = this->getState();
471         LONG_PTR result = ::GetWindowLongPtr(m_hWnd, GWL_STYLE);
472         int sm_cysizeframe = GetSystemMetrics(SM_CYSIZEFRAME);
473         ::GetWindowRect(m_hWnd, &rect);
474
475         if ((result & (WS_POPUP | WS_MAXIMIZE)) != (WS_POPUP | WS_MAXIMIZE)) {
476                 if (state == GHOST_kWindowStateMaximized) {
477                         // in maximized state we don't have borders on the window
478                         bounds.m_b = rect.bottom - GetSystemMetrics(SM_CYCAPTION) - sm_cysizeframe * 2;
479                         bounds.m_l = rect.left + sm_cysizeframe;
480                         bounds.m_r = rect.right - sm_cysizeframe;
481                         bounds.m_t = rect.top;
482                 }
483                 else if (state == GHOST_kWindowStateEmbedded) {
484                         bounds.m_b = rect.bottom;
485                         bounds.m_l = rect.left;
486                         bounds.m_r = rect.right;
487                         bounds.m_t = rect.top;
488                 }
489                 else {
490                         bounds.m_b = rect.bottom - GetSystemMetrics(SM_CYCAPTION) - sm_cysizeframe * 2;
491                         bounds.m_l = rect.left;
492                         bounds.m_r = rect.right - sm_cysizeframe * 2;
493                         bounds.m_t = rect.top;
494                 }
495         }
496         else {
497                 bounds.m_b = rect.bottom;
498                 bounds.m_l = rect.left;
499                 bounds.m_r = rect.right;
500                 bounds.m_t = rect.top;
501         }
502 }
503
504
505 GHOST_TSuccess GHOST_WindowWin32::setClientWidth(GHOST_TUns32 width)
506 {
507         GHOST_TSuccess success;
508         GHOST_Rect cBnds, wBnds;
509         getClientBounds(cBnds);
510         if (cBnds.getWidth() != (GHOST_TInt32)width) {
511                 getWindowBounds(wBnds);
512                 int cx = wBnds.getWidth() + width - cBnds.getWidth();
513                 int cy = wBnds.getHeight();
514                 success =  ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
515                           GHOST_kSuccess : GHOST_kFailure;
516         }
517         else {
518                 success = GHOST_kSuccess;
519         }
520         return success;
521 }
522
523
524 GHOST_TSuccess GHOST_WindowWin32::setClientHeight(GHOST_TUns32 height)
525 {
526         GHOST_TSuccess success;
527         GHOST_Rect cBnds, wBnds;
528         getClientBounds(cBnds);
529         if (cBnds.getHeight() != (GHOST_TInt32)height) {
530                 getWindowBounds(wBnds);
531                 int cx = wBnds.getWidth();
532                 int cy = wBnds.getHeight() + height - cBnds.getHeight();
533                 success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
534                           GHOST_kSuccess : GHOST_kFailure;
535         }
536         else {
537                 success = GHOST_kSuccess;
538         }
539         return success;
540 }
541
542
543 GHOST_TSuccess GHOST_WindowWin32::setClientSize(GHOST_TUns32 width, GHOST_TUns32 height)
544 {
545         GHOST_TSuccess success;
546         GHOST_Rect cBnds, wBnds;
547         getClientBounds(cBnds);
548         if ((cBnds.getWidth() != (GHOST_TInt32)width) || (cBnds.getHeight() != (GHOST_TInt32)height)) {
549                 getWindowBounds(wBnds);
550                 int cx = wBnds.getWidth() + width - cBnds.getWidth();
551                 int cy = wBnds.getHeight() + height - cBnds.getHeight();
552                 success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
553                           GHOST_kSuccess : GHOST_kFailure;
554         }
555         else {
556                 success = GHOST_kSuccess;
557         }
558         return success;
559 }
560
561
562 GHOST_TWindowState GHOST_WindowWin32::getState() const
563 {
564         GHOST_TWindowState state;
565
566         // XXX 27.04.2011
567         // we need to find a way to combine parented windows + resizing if we simply set the
568         // state as GHOST_kWindowStateEmbedded we will need to check for them somewhere else.
569         // It's also strange that in Windows is the only platform we need to make this separation.
570         if (m_parentWindowHwnd != 0) {
571                 state = GHOST_kWindowStateEmbedded;
572                 return state;
573         }
574         if (::IsIconic(m_hWnd)) {
575                 state = GHOST_kWindowStateMinimized;
576         }
577         else if (::IsZoomed(m_hWnd)) {
578                 LONG_PTR result = ::GetWindowLongPtr(m_hWnd, GWL_STYLE);
579                 if ((result & (WS_POPUP | WS_MAXIMIZE)) != (WS_POPUP | WS_MAXIMIZE))
580                         state = GHOST_kWindowStateMaximized;
581                 else
582                         state = GHOST_kWindowStateFullScreen;
583         }
584         else {
585                 state = GHOST_kWindowStateNormal;
586         }
587         return state;
588 }
589
590
591 void GHOST_WindowWin32::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
592 {
593         POINT point = { inX, inY };
594         ::ScreenToClient(m_hWnd, &point);
595         outX = point.x;
596         outY = point.y;
597 }
598
599
600 void GHOST_WindowWin32::clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
601 {
602         POINT point = { inX, inY };
603         ::ClientToScreen(m_hWnd, &point);
604         outX = point.x;
605         outY = point.y;
606 }
607
608
609 GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state)
610 {
611         GHOST_TWindowState curstate = getState();
612         WINDOWPLACEMENT wp;
613         wp.length = sizeof(WINDOWPLACEMENT);
614         ::GetWindowPlacement(m_hWnd, &wp);
615
616         if (state == GHOST_kWindowStateNormal)
617                 state = m_normal_state;
618         switch (state) {
619                 case GHOST_kWindowStateMinimized:
620                         wp.showCmd = SW_SHOWMINIMIZED;
621                         break;
622                 case GHOST_kWindowStateMaximized:
623                         wp.showCmd = SW_SHOWMAXIMIZED;
624                         SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
625                         break;
626                 case GHOST_kWindowStateFullScreen:
627                         if (curstate != state && curstate != GHOST_kWindowStateMinimized)
628                                 m_normal_state = curstate;
629                         wp.showCmd = SW_SHOWMAXIMIZED;
630                         wp.ptMaxPosition.x = 0;
631                         wp.ptMaxPosition.y = 0;
632                         SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_POPUP | WS_MAXIMIZE);
633                         break;
634                 case GHOST_kWindowStateEmbedded:
635                         SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_CHILD);
636                         break;
637                 case GHOST_kWindowStateNormal:
638                 default:
639                         wp.showCmd = SW_SHOWNORMAL;
640                         SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
641                         break;
642         }
643         SetWindowPos(m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); /*Clears window cache for SetWindowLongPtr */
644         return ::SetWindowPlacement(m_hWnd, &wp) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
645 }
646
647
648 GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
649 {
650         HWND hWndInsertAfter = order == GHOST_kWindowOrderTop ? HWND_TOP : HWND_BOTTOM;
651         return ::SetWindowPos(m_hWnd, hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
652 }
653
654
655 GHOST_TSuccess GHOST_WindowWin32::swapBuffers()
656 {
657         HDC hDC = m_hDC;
658
659         if (is_crappy_intel_card())
660                 hDC = ::wglGetCurrentDC();
661
662         return ::SwapBuffers(hDC) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
663 }
664
665
666 GHOST_TSuccess GHOST_WindowWin32::activateDrawingContext()
667 {
668         GHOST_TSuccess success;
669         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
670                 if (m_hDC && m_hGlRc) {
671                         success = ::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
672                 }
673                 else {
674                         success = GHOST_kFailure;
675                 }
676         }
677         else {
678                 success = GHOST_kSuccess;
679         }
680         return success;
681 }
682
683
684 GHOST_TSuccess GHOST_WindowWin32::invalidate()
685 {
686         GHOST_TSuccess success;
687         if (m_hWnd) {
688                 success = ::InvalidateRect(m_hWnd, 0, FALSE) != 0 ? GHOST_kSuccess : GHOST_kFailure;
689         }
690         else {
691                 success = GHOST_kFailure;
692         }
693         return success;
694 }
695
696 GHOST_TSuccess GHOST_WindowWin32::initMultisample(PIXELFORMATDESCRIPTOR pfd)
697 {
698         int pixelFormat;
699         bool success = FALSE;
700         UINT numFormats;
701         HDC hDC = GetDC(getHWND());
702         float fAttributes[] = {0, 0};
703         UINT nMaxFormats = 1;
704
705         // The attributes to look for
706         int iAttributes[] = {
707                 WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
708                 WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
709                 WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
710                 WGL_COLOR_BITS_ARB, pfd.cColorBits,
711                 WGL_DEPTH_BITS_ARB, pfd.cDepthBits,
712                 WGL_STENCIL_BITS_ARB, pfd.cStencilBits,
713                 WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
714                 WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
715                 WGL_SAMPLES_ARB, m_multisample,
716                 0, 0
717         };
718
719         // Get the function
720         PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");  
721
722         if (!wglChoosePixelFormatARB)
723         {
724                 m_multisampleEnabled = GHOST_kFailure;
725                 return GHOST_kFailure;
726         }
727
728         // iAttributes[17] is the initial multisample. If not valid try to use the closest valid value under it.
729         while (iAttributes[17] > 0) {
730                 // See if the format is valid
731                 success = wglChoosePixelFormatARB(hDC, iAttributes, fAttributes, nMaxFormats, &pixelFormat, &numFormats);
732                 GHOST_PRINTF("WGL_SAMPLES_ARB = %i --> success = %i, %i formats\n", iAttributes[17], success, numFormats);
733
734                 if (success && numFormats >= 1 && m_multisampleEnabled == GHOST_kFailure) {
735                         GHOST_PRINTF("valid pixel format with %i multisamples\n", iAttributes[17]);
736                         m_multisampleEnabled = GHOST_kSuccess;
737                         m_msPixelFormat = pixelFormat;
738                 }
739                 iAttributes[17] -= 1;
740                 success = GHOST_kFailure;
741         }
742         if (m_multisampleEnabled == GHOST_kSuccess) {
743                 return GHOST_kSuccess;
744         }
745         GHOST_PRINT("no available pixel format\n");
746         return GHOST_kFailure;
747 }
748
749 GHOST_TSuccess GHOST_WindowWin32::installDrawingContext(GHOST_TDrawingContextType type)
750 {
751         GHOST_TSuccess success;
752         switch (type) {
753                 case GHOST_kDrawingContextTypeOpenGL:
754                 {
755                         // If this window has multisample enabled, use the supplied format
756                         if (m_multisampleEnabled)
757                         {
758                                 if (SetPixelFormat(m_hDC, m_msPixelFormat, &sPreferredFormat) == FALSE)
759                                 {
760                                         success = GHOST_kFailure;
761                                         break;
762                                 }
763
764                                 // Create the context
765                                 m_hGlRc = ::wglCreateContext(m_hDC);
766                                 if (m_hGlRc) {
767                                         if (::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE) {
768                                                 if (s_firsthGLRc) {
769                                                         if (is_crappy_intel_card()) {
770                                                                 if (::wglMakeCurrent(NULL, NULL) == TRUE) {
771                                                                         ::wglDeleteContext(m_hGlRc);
772                                                                         m_hGlRc = s_firsthGLRc;
773                                                                 }
774                                                                 else {
775                                                                         ::wglDeleteContext(m_hGlRc);
776                                                                         m_hGlRc = NULL;
777                                                                 }
778                                                         }
779                                                         else {
780                                                                 ::wglCopyContext(s_firsthGLRc, m_hGlRc, GL_ALL_ATTRIB_BITS);
781                                                                 ::wglShareLists(s_firsthGLRc, m_hGlRc);
782                                                         }
783                                                 }
784                                                 else {
785                                                         s_firsthGLRc = m_hGlRc;
786                                                 }
787
788                                                 if (m_hGlRc) {
789                                                         success = ::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
790                                                 }
791                                                 else {
792                                                         success = GHOST_kFailure;
793                                                 }
794                                         }
795                                         else {
796                                                 success = GHOST_kFailure;
797                                         }
798                                 }
799                                 else {
800                                         success = GHOST_kFailure;
801                                 }
802
803                                 if (success == GHOST_kFailure) {
804                                         printf("Failed to get a context....\n");
805                                 }
806                         }
807                         else {
808                                 if (m_stereoVisual)
809                                         sPreferredFormat.dwFlags |= PFD_STEREO;
810
811                                 // Attempt to match device context pixel format to the preferred format
812                                 int iPixelFormat = EnumPixelFormats(m_hDC);
813                                 if (iPixelFormat == 0) {
814                                         success = GHOST_kFailure;
815                                         break;
816                                 }
817                                 if (::SetPixelFormat(m_hDC, iPixelFormat, &sPreferredFormat) == FALSE) {
818                                         success = GHOST_kFailure;
819                                         break;
820                                 }
821                                 // For debugging only: retrieve the pixel format chosen
822                                 PIXELFORMATDESCRIPTOR preferredFormat;
823                                 ::DescribePixelFormat(m_hDC, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &preferredFormat);
824
825                                 // Create the context
826                                 m_hGlRc = ::wglCreateContext(m_hDC);
827                                 if (m_hGlRc) {
828                                         if (::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE) {
829                                                 if (s_firsthGLRc) {
830                                                         if (is_crappy_intel_card()) {
831                                                                 if (::wglMakeCurrent(NULL, NULL) == TRUE) {
832                                                                         ::wglDeleteContext(m_hGlRc);
833                                                                         m_hGlRc = s_firsthGLRc;
834                                                                 }
835                                                                 else {
836                                                                         ::wglDeleteContext(m_hGlRc);
837                                                                         m_hGlRc = NULL;
838                                                                 }
839                                                         }
840                                                         else {
841                                                                 ::wglShareLists(s_firsthGLRc, m_hGlRc);
842                                                         }
843                                                 }
844                                                 else {
845                                                         s_firsthGLRc = m_hGlRc;
846                                                 }
847
848                                                 if (m_hGlRc) {
849                                                         success = ::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
850                                                 }
851                                                 else {
852                                                         success = GHOST_kFailure;
853                                                 }
854                                         }
855                                         else {
856                                                 success = GHOST_kFailure;
857                                         }
858                                 }
859                                 else {
860                                         success = GHOST_kFailure;
861                                 }
862                                         
863                                 if (success == GHOST_kFailure) {
864                                         printf("Failed to get a context....\n");
865                                 }
866
867                                 // Attempt to enable multisample
868                                 if (m_multisample && WGL_ARB_multisample && !m_multisampleEnabled)
869                                 {
870                                         success = initMultisample(preferredFormat);
871
872                                         if (success)
873                                         {
874
875                                                 // Make sure we don't screw up the context
876                                                 if (m_hGlRc == s_firsthGLRc)
877                                                         s_firsthGLRc = NULL;
878                                                 m_drawingContextType = GHOST_kDrawingContextTypeOpenGL;
879                                                 removeDrawingContext();
880
881                                                 // Create a new window
882                                                 GHOST_TWindowState new_state = getState();
883
884                                                 m_nextWindow = new GHOST_WindowWin32((GHOST_SystemWin32 *)GHOST_ISystem::getSystem(),
885                                                                                      m_title,
886                                                                                      m_left,
887                                                                                      m_top,
888                                                                                      m_width,
889                                                                                      m_height,
890                                                                                      new_state,
891                                                                                      type,
892                                                                                      m_stereo,
893                                                                                      m_multisample,
894                                                                                      m_parentWindowHwnd,
895                                                                                      m_multisampleEnabled,
896                                                                                      m_msPixelFormat);
897
898                                                 // Return failure so we can trash this window.
899                                                 success = GHOST_kFailure;
900                                                 break;
901                                         }
902                                         else {
903                                                 m_multisampleEnabled = GHOST_kSuccess;
904                                                 printf("Multisample failed to initialized\n");
905                                                 success = GHOST_kSuccess;
906                                         }
907                                 }
908                         }
909
910                 }
911                 break;
912
913                 case GHOST_kDrawingContextTypeNone:
914                         success = GHOST_kSuccess;
915                         break;
916
917                 default:
918                         success = GHOST_kFailure;
919         }
920         return success;
921 }
922
923 GHOST_TSuccess GHOST_WindowWin32::removeDrawingContext()
924 {
925         GHOST_TSuccess success;
926         switch (m_drawingContextType) {
927                 case GHOST_kDrawingContextTypeOpenGL:
928                         // we shouldn't remove the drawing context if it's the first OpenGL context
929                         // If we do, we get corrupted drawing. See #19997
930                         if (m_hGlRc && m_hGlRc != s_firsthGLRc) {
931                                 success = ::wglDeleteContext(m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
932                                 m_hGlRc = 0;
933                         }
934                         else {
935                                 success = GHOST_kFailure;
936                         }
937                         break;
938                 case GHOST_kDrawingContextTypeNone:
939                         success = GHOST_kSuccess;
940                         break;
941                 default:
942                         success = GHOST_kFailure;
943         }
944         return success;
945 }
946
947 void GHOST_WindowWin32::lostMouseCapture()
948 {
949         if (m_hasMouseCaptured)
950         {   m_hasGrabMouse = false;
951                 m_nPressedButtons = 0;
952                 m_hasMouseCaptured = false; };
953 }
954
955 void GHOST_WindowWin32::registerMouseClickEvent(int press)
956 {
957
958         switch (press)
959         {
960                 case 0: m_nPressedButtons++;    break;
961                 case 1: if (m_nPressedButtons) m_nPressedButtons--; break;
962                 case 2: m_hasGrabMouse = true;    break;
963                 case 3: m_hasGrabMouse = false;   break;
964         }
965
966         if (!m_nPressedButtons && !m_hasGrabMouse && m_hasMouseCaptured)
967         {
968                 ::ReleaseCapture();
969                 m_hasMouseCaptured = false;
970         }
971         else if ((m_nPressedButtons || m_hasGrabMouse) && !m_hasMouseCaptured)
972         {
973                 ::SetCapture(m_hWnd);
974                 m_hasMouseCaptured = true;
975
976         }
977 }
978
979
980 void GHOST_WindowWin32::loadCursor(bool visible, GHOST_TStandardCursor cursor) const
981 {
982         if (!visible) {
983                 while (::ShowCursor(FALSE) >= 0) ;
984         }
985         else {
986                 while (::ShowCursor(TRUE) < 0) ;
987         }
988
989         if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
990                 ::SetCursor(m_customCursor);
991         }
992         else {
993                 // Convert GHOST cursor to Windows OEM cursor
994                 bool success = true;
995                 LPCSTR id;
996                 switch (cursor) {
997                         case GHOST_kStandardCursorDefault:              id = IDC_ARROW;     break;
998                         case GHOST_kStandardCursorRightArrow:           id = IDC_ARROW;     break;
999                         case GHOST_kStandardCursorLeftArrow:            id = IDC_ARROW;     break;
1000                         case GHOST_kStandardCursorInfo:                 id = IDC_SIZEALL;   break;  // Four-pointed arrow pointing north, south, east, and west
1001                         case GHOST_kStandardCursorDestroy:              id = IDC_NO;        break;  // Slashed circle
1002                         case GHOST_kStandardCursorHelp:                 id = IDC_HELP;      break;  // Arrow and question mark
1003                         case GHOST_kStandardCursorCycle:                id = IDC_NO;        break;  // Slashed circle
1004                         case GHOST_kStandardCursorSpray:                id = IDC_SIZEALL;   break;  // Four-pointed arrow pointing north, south, east, and west
1005                         case GHOST_kStandardCursorWait:                 id = IDC_WAIT;      break;  // Hourglass
1006                         case GHOST_kStandardCursorText:                 id = IDC_IBEAM;     break;  // I-beam
1007                         case GHOST_kStandardCursorCrosshair:            id = IDC_CROSS;     break;  // Crosshair
1008                         case GHOST_kStandardCursorUpDown:               id = IDC_SIZENS;    break;  // Double-pointed arrow pointing north and south
1009                         case GHOST_kStandardCursorLeftRight:            id = IDC_SIZEWE;    break;  // Double-pointed arrow pointing west and east
1010                         case GHOST_kStandardCursorTopSide:              id = IDC_UPARROW;   break;  // Vertical arrow
1011                         case GHOST_kStandardCursorBottomSide:           id = IDC_SIZENS;    break;
1012                         case GHOST_kStandardCursorLeftSide:             id = IDC_SIZEWE;    break;
1013                         case GHOST_kStandardCursorTopLeftCorner:        id = IDC_SIZENWSE;  break;
1014                         case GHOST_kStandardCursorTopRightCorner:       id = IDC_SIZENESW;  break;
1015                         case GHOST_kStandardCursorBottomRightCorner:    id = IDC_SIZENWSE;  break;
1016                         case GHOST_kStandardCursorBottomLeftCorner:     id = IDC_SIZENESW;  break;
1017                         case GHOST_kStandardCursorPencil:               id = IDC_ARROW;     break;
1018                         case GHOST_kStandardCursorCopy:                 id = IDC_ARROW;     break;
1019                         default:
1020                                 success = false;
1021                 }
1022
1023                 if (success) {
1024                         ::SetCursor(::LoadCursor(0, id));
1025                 }
1026         }
1027 }
1028
1029 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorVisibility(bool visible)
1030 {
1031         if (::GetForegroundWindow() == m_hWnd) {
1032                 loadCursor(visible, getCursorShape());
1033         }
1034
1035         return GHOST_kSuccess;
1036 }
1037
1038 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
1039 {
1040         if (mode != GHOST_kGrabDisable) {
1041                 if (mode != GHOST_kGrabNormal) {
1042                         m_system->getCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
1043                         setCursorGrabAccum(0, 0);
1044
1045                         if (mode == GHOST_kGrabHide)
1046                                 setWindowCursorVisibility(false);
1047                 }
1048                 registerMouseClickEvent(2);
1049         }
1050         else {
1051                 if (m_cursorGrab == GHOST_kGrabHide) {
1052                         m_system->setCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
1053                         setWindowCursorVisibility(true);
1054                 }
1055                 if (m_cursorGrab != GHOST_kGrabNormal) {
1056                         /* use to generate a mouse move event, otherwise the last event
1057                          * blender gets can be outside the screen causing menus not to show
1058                          * properly unless the user moves the mouse */
1059                         GHOST_TInt32 pos[2];
1060                         m_system->getCursorPosition(pos[0], pos[1]);
1061                         m_system->setCursorPosition(pos[0], pos[1]);
1062                 }
1063
1064                 /* Almost works without but important otherwise the mouse GHOST location can be incorrect on exit */
1065                 setCursorGrabAccum(0, 0);
1066                 m_cursorGrabBounds.m_l = m_cursorGrabBounds.m_r = -1; /* disable */
1067                 registerMouseClickEvent(3);
1068         }
1069         
1070         return GHOST_kSuccess;
1071 }
1072
1073 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorShape(GHOST_TStandardCursor cursorShape)
1074 {
1075         if (m_customCursor) {
1076                 DestroyCursor(m_customCursor);
1077                 m_customCursor = NULL;
1078         }
1079
1080         if (::GetForegroundWindow() == m_hWnd) {
1081                 loadCursor(getCursorVisibility(), cursorShape);
1082         }
1083
1084         return GHOST_kSuccess;
1085 }
1086
1087 void GHOST_WindowWin32::processWin32TabletInitEvent()
1088 {
1089         if (m_wintab) {
1090                 GHOST_WIN32_WTInfo fpWTInfo = (GHOST_WIN32_WTInfo) ::GetProcAddress(m_wintab, "WTInfoA");
1091
1092                 // let's see if we can initialize tablet here
1093                 /* check if WinTab available. */
1094                 if (fpWTInfo) {
1095                         AXIS Pressure, Orientation[3]; /* The maximum tablet size */
1096
1097                         BOOL pressureSupport = fpWTInfo(WTI_DEVICES, DVC_NPRESSURE, &Pressure);
1098                         if (pressureSupport)
1099                                 m_maxPressure = Pressure.axMax;
1100                         else
1101                                 m_maxPressure = 0;
1102
1103                         BOOL tiltSupport = fpWTInfo(WTI_DEVICES, DVC_ORIENTATION, &Orientation);
1104                         if (tiltSupport) {
1105                                 /* does the tablet support azimuth ([0]) and altitude ([1]) */
1106                                 if (Orientation[0].axResolution && Orientation[1].axResolution) {
1107                                         m_maxAzimuth = Orientation[0].axMax;
1108                                         m_maxAltitude = Orientation[1].axMax;
1109                                 }
1110                                 else {  /* no so dont do tilt stuff */
1111                                         m_maxAzimuth = m_maxAltitude = 0;
1112                                 }
1113                         }
1114
1115                         m_tabletData->Active = GHOST_kTabletModeNone;
1116                 }
1117         }
1118 }
1119
1120 void GHOST_WindowWin32::processWin32TabletEvent(WPARAM wParam, LPARAM lParam)
1121 {
1122         PACKET pkt;
1123         if (m_wintab) {
1124                 GHOST_WIN32_WTPacket fpWTPacket = (GHOST_WIN32_WTPacket) ::GetProcAddress(m_wintab, "WTPacket");
1125                 if (fpWTPacket) {
1126                         if (fpWTPacket((HCTX)lParam, wParam, &pkt)) {
1127                                 if (m_tabletData) {
1128                                         switch (pkt.pkCursor) {
1129                                                 case 0: /* first device */
1130                                                 case 3: /* second device */
1131                                                         m_tabletData->Active = GHOST_kTabletModeNone; /* puck - not yet supported */
1132                                                         break;
1133                                                 case 1:
1134                                                 case 4:
1135                                                         m_tabletData->Active = GHOST_kTabletModeStylus; /* stylus */
1136                                                         break;
1137                                                 case 2:
1138                                                 case 5:
1139                                                         m_tabletData->Active = GHOST_kTabletModeEraser; /* eraser */
1140                                                         break;
1141                                         }
1142                                         if (m_maxPressure > 0) {
1143                                                 m_tabletData->Pressure = (float)pkt.pkNormalPressure / (float)m_maxPressure;
1144                                         }
1145                                         else {
1146                                                 m_tabletData->Pressure = 1.0f;
1147                                         }
1148
1149                                         if ((m_maxAzimuth > 0) && (m_maxAltitude > 0)) {
1150                                                 ORIENTATION ort = pkt.pkOrientation;
1151                                                 float vecLen;
1152                                                 float altRad, azmRad;   /* in radians */
1153
1154                                                 /*
1155                                                  * from the wintab spec:
1156                                                  * orAzimuth    Specifies the clockwise rotation of the
1157                                                  * cursor about the z axis through a full circular range.
1158                                                  *
1159                                                  * orAltitude   Specifies the angle with the x-y plane
1160                                                  * through a signed, semicircular range.  Positive values
1161                                                  * specify an angle upward toward the positive z axis;
1162                                                  * negative values specify an angle downward toward the negative z axis.
1163                                                  *
1164                                                  * wintab.h defines .orAltitude as a UINT but documents .orAltitude
1165                                                  * as positive for upward angles and negative for downward angles.
1166                                                  * WACOM uses negative altitude values to show that the pen is inverted;
1167                                                  * therefore we cast .orAltitude as an (int) and then use the absolute value.
1168                                                  */
1169
1170                                                 /* convert raw fixed point data to radians */
1171                                                 altRad = (float)((fabs((float)ort.orAltitude) / (float)m_maxAltitude) * M_PI / 2.0);
1172                                                 azmRad = (float)(((float)ort.orAzimuth / (float)m_maxAzimuth) * M_PI * 2.0);
1173
1174                                                 /* find length of the stylus' projected vector on the XY plane */
1175                                                 vecLen = cos(altRad);
1176
1177                                                 /* from there calculate X and Y components based on azimuth */
1178                                                 m_tabletData->Xtilt = sin(azmRad) * vecLen;
1179                                                 m_tabletData->Ytilt = (float)(sin(M_PI / 2.0 - azmRad) * vecLen);
1180
1181                                         }
1182                                         else {
1183                                                 m_tabletData->Xtilt = 0.0f;
1184                                                 m_tabletData->Ytilt = 0.0f;
1185                                         }
1186                                 }
1187                         }
1188                 }
1189         }
1190 }
1191
1192 /** Reverse the bits in a GHOST_TUns8 */
1193 static GHOST_TUns8 uns8ReverseBits(GHOST_TUns8 ch)
1194 {
1195         ch = ((ch >> 1) & 0x55) | ((ch << 1) & 0xAA);
1196         ch = ((ch >> 2) & 0x33) | ((ch << 2) & 0xCC);
1197         ch = ((ch >> 4) & 0x0F) | ((ch << 4) & 0xF0);
1198         return ch;
1199 }
1200
1201 /** Reverse the bits in a GHOST_TUns16 */
1202 static GHOST_TUns16 uns16ReverseBits(GHOST_TUns16 shrt)
1203 {
1204         shrt = ((shrt >> 1) & 0x5555) | ((shrt << 1) & 0xAAAA);
1205         shrt = ((shrt >> 2) & 0x3333) | ((shrt << 2) & 0xCCCC);
1206         shrt = ((shrt >> 4) & 0x0F0F) | ((shrt << 4) & 0xF0F0);
1207         shrt = ((shrt >> 8) & 0x00FF) | ((shrt << 8) & 0xFF00);
1208         return shrt;
1209 }
1210 GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2],
1211                                                              GHOST_TUns8 mask[16][2],
1212                                                              int hotX, int hotY)
1213 {
1214         return setWindowCustomCursorShape((GHOST_TUns8 *)bitmap, (GHOST_TUns8 *)mask,
1215                                           16, 16, hotX, hotY, 0, 1);
1216 }
1217
1218 GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(GHOST_TUns8 *bitmap,
1219                                                              GHOST_TUns8 *mask, int sizeX, int sizeY, int hotX, int hotY,
1220                                                              int fg_color, int bg_color)
1221 {
1222         GHOST_TUns32 andData[32];
1223         GHOST_TUns32 xorData[32];
1224         GHOST_TUns32 fullBitRow, fullMaskRow;
1225         int x, y, cols;
1226
1227         cols = sizeX / 8; /* Num of whole bytes per row (width of bm/mask) */
1228         if (sizeX % 8) cols++;
1229
1230         if (m_customCursor) {
1231                 DestroyCursor(m_customCursor);
1232                 m_customCursor = NULL;
1233         }
1234
1235         memset(&andData, 0xFF, sizeof(andData));
1236         memset(&xorData, 0, sizeof(xorData));
1237
1238         for (y = 0; y < sizeY; y++) {
1239                 fullBitRow = 0;
1240                 fullMaskRow = 0;
1241                 for (x = cols - 1; x >= 0; x--) {
1242                         fullBitRow <<= 8;
1243                         fullMaskRow <<= 8;
1244                         fullBitRow  |= uns8ReverseBits(bitmap[cols * y + x]);
1245                         fullMaskRow |= uns8ReverseBits(mask[cols * y + x]);
1246                 }
1247                 xorData[y] = fullBitRow & fullMaskRow;
1248                 andData[y] = ~fullMaskRow;
1249         }
1250
1251         m_customCursor = ::CreateCursor(::GetModuleHandle(0), hotX, hotY, 32, 32, andData, xorData);
1252         if (!m_customCursor) {
1253                 return GHOST_kFailure;
1254         }
1255
1256         if (::GetForegroundWindow() == m_hWnd) {
1257                 loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
1258         }
1259
1260         return GHOST_kSuccess;
1261 }
1262
1263
1264 GHOST_TSuccess GHOST_WindowWin32::setProgressBar(float progress)
1265 {       
1266         /*SetProgressValue sets state to TBPF_NORMAL automaticly*/
1267         if (m_Bar && S_OK == m_Bar->SetProgressValue(m_hWnd, 10000 * progress, 10000))
1268                 return GHOST_kSuccess;
1269
1270         return GHOST_kFailure;
1271 }
1272
1273 GHOST_TSuccess GHOST_WindowWin32::endProgressBar()
1274 {
1275         if (m_Bar && S_OK == m_Bar->SetProgressState(m_hWnd, TBPF_NOPROGRESS))
1276                 return GHOST_kSuccess;
1277
1278         return GHOST_kFailure;
1279 }
1280
1281 /* Ron Fosner's code for weighting pixel formats and forcing software.
1282  * See http://www.opengl.org/resources/faq/technical/weight.cpp */
1283
1284 static int WeightPixelFormat(PIXELFORMATDESCRIPTOR& pfd)
1285 {
1286         int weight = 0;
1287
1288         /* assume desktop color depth is 32 bits per pixel */
1289
1290         /* cull unusable pixel formats */
1291         /* if no formats can be found, can we determine why it was rejected? */
1292         if (!(pfd.dwFlags & PFD_SUPPORT_OPENGL) ||
1293             !(pfd.dwFlags & PFD_DRAW_TO_WINDOW) ||
1294             !(pfd.dwFlags & PFD_DOUBLEBUFFER) || /* Blender _needs_ this */
1295             (pfd.cDepthBits <= 8) ||
1296             !(pfd.iPixelType == PFD_TYPE_RGBA))
1297         {
1298                 return 0;
1299         }
1300
1301         weight = 1;  /* it's usable */
1302
1303         /* the bigger the depth buffer the better */
1304         /* give no weight to a 16-bit depth buffer, because those are crap */
1305         weight += pfd.cDepthBits - 16;
1306
1307         weight += pfd.cColorBits - 8;
1308
1309         /* want swap copy capability -- it matters a lot */
1310         if (pfd.dwFlags & PFD_SWAP_COPY) weight += 16;
1311
1312         /* but if it's a generic (not accelerated) view, it's really bad */
1313         if (pfd.dwFlags & PFD_GENERIC_FORMAT) weight /= 10;
1314
1315         return weight;
1316 }
1317
1318 /* A modification of Ron Fosner's replacement for ChoosePixelFormat */
1319 /* returns 0 on error, else returns the pixel format number to be used */
1320 static int EnumPixelFormats(HDC hdc)
1321 {
1322         int iPixelFormat;
1323         int i, n, w, weight = 0;
1324         PIXELFORMATDESCRIPTOR pfd;
1325
1326         /* we need a device context to do anything */
1327         if (!hdc) return 0;
1328
1329         iPixelFormat = 1; /* careful! PFD numbers are 1 based, not zero based */
1330
1331         /* obtain detailed information about
1332          * the device context's first pixel format */
1333         n = 1 + ::DescribePixelFormat(hdc, iPixelFormat,
1334                                       sizeof(PIXELFORMATDESCRIPTOR), &pfd);
1335
1336         /* choose a pixel format using the useless Windows function in case
1337          * we come up empty handed */
1338         iPixelFormat = ::ChoosePixelFormat(hdc, &sPreferredFormat);
1339
1340         if (!iPixelFormat) return 0;  /* couldn't find one to use */
1341
1342         for (i = 1; i <= n; i++) { /* not the idiom, but it's right */
1343                 ::DescribePixelFormat(hdc, i, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
1344                 w = WeightPixelFormat(pfd);
1345                 // be strict on stereo
1346                 if (!((sPreferredFormat.dwFlags ^ pfd.dwFlags) & PFD_STEREO)) {
1347                         if (w > weight) {
1348                                 weight = w;
1349                                 iPixelFormat = i;
1350                         }
1351                 }
1352         }
1353         if (weight == 0) {
1354                 // we could find the correct stereo setting, just find any suitable format
1355                 for (i = 1; i <= n; i++) { /* not the idiom, but it's right */
1356                         ::DescribePixelFormat(hdc, i, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
1357                         w = WeightPixelFormat(pfd);
1358                         if (w > weight) {
1359                                 weight = w;
1360                                 iPixelFormat = i;
1361                         }
1362                 }
1363         }
1364         return iPixelFormat;
1365 }
1366
1367