==== GHOST Win32 ====
[blender.git] / intern / ghost / intern / GHOST_WindowWin32.cpp
1 /**
2  * $Id$
3  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. The Blender
9  * Foundation also sells licenses for use in proprietary software under
10  * the Blender License.  See http://www.blender.org/BL/ for information
11  * about this.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL/BL DUAL LICENSE BLOCK *****
30  */
31
32 /**
33
34  * $Id$
35  * Copyright (C) 2001 NaN Technologies B.V.
36  * @author      Maarten Gribnau
37  * @date        May 10, 2001
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #include <config.h>
42 #endif
43
44 #include <string.h>
45 #include "GHOST_WindowWin32.h"
46 #include <GL/gl.h>
47 #include <math.h>
48
49 // MSVC6 still doesn't define M_PI
50 #ifndef M_PI
51 #define M_PI 3.1415926536
52 #endif
53
54 LPCSTR GHOST_WindowWin32::s_windowClassName = "GHOST_WindowClass";
55 const int GHOST_WindowWin32::s_maxTitleLength = 128;
56 HGLRC GHOST_WindowWin32::s_firsthGLRc = NULL;
57
58 static int WeightPixelFormat(PIXELFORMATDESCRIPTOR& pfd);
59 static int EnumPixelFormats(HDC hdc);
60
61 /*
62  * Color and depth bit values are not to be trusted.
63  * For instance, on TNT2:
64  * When the screen color depth is set to 16 bit, we get 5 color bits
65  * and 16 depth bits.
66  * When the screen color depth is set to 32 bit, we get 8 color bits
67  * and 24 depth bits.
68  * Just to be safe, we request high waulity settings.
69  */
70 static PIXELFORMATDESCRIPTOR sPreferredFormat = {
71         sizeof(PIXELFORMATDESCRIPTOR),  /* size */
72         1,                              /* version */
73         PFD_SUPPORT_OPENGL |
74         PFD_DRAW_TO_WINDOW |
75         PFD_SWAP_COPY |                                 /* support swap copy */
76         PFD_DOUBLEBUFFER,               /* support double-buffering */
77         PFD_TYPE_RGBA,                  /* color type */
78         32,                             /* prefered color depth */
79         0, 0, 0, 0, 0, 0,               /* color bits (ignored) */
80         0,                              /* no alpha buffer */
81         0,                              /* alpha bits (ignored) */
82         0,                              /* no accumulation buffer */
83         0, 0, 0, 0,                     /* accum bits (ignored) */
84         32,                             /* depth buffer */
85         0,                              /* no stencil buffer */
86         0,                              /* no auxiliary buffers */
87         PFD_MAIN_PLANE,                 /* main layer */
88         0,                              /* reserved */
89         0, 0, 0                         /* no layer, visible, damage masks */
90 };
91
92 GHOST_WindowWin32::GHOST_WindowWin32(
93         const STR_String& title,
94         GHOST_TInt32 left,
95         GHOST_TInt32 top,
96         GHOST_TUns32 width,
97         GHOST_TUns32 height,
98         GHOST_TWindowState state,
99         GHOST_TDrawingContextType type,
100         const bool stereoVisual)
101 :
102         GHOST_Window(title, left, top, width, height, state, GHOST_kDrawingContextTypeNone,
103         stereoVisual),
104         m_hDC(0),
105         m_hGlRc(0),
106         m_hasMouseCaptured(false),
107         m_nPressedButtons(0),
108         m_customCursor(0),
109         m_tabletData(NULL),
110         m_tablet(0),
111         m_wintab(NULL),
112         m_maxPressure(0)
113 {
114         if (state != GHOST_kWindowStateFullScreen) {
115                         /* Convert client size into window size */
116                 width += GetSystemMetrics(SM_CXSIZEFRAME)*2;
117                 height += GetSystemMetrics(SM_CYSIZEFRAME)*2 + GetSystemMetrics(SM_CYCAPTION);
118
119                 m_hWnd = ::CreateWindow(
120                         s_windowClassName,                      // pointer to registered class name
121                         title,                                          // pointer to window name
122                         WS_OVERLAPPEDWINDOW,            // window style
123                         left,                                           // horizontal position of window
124                         top,                                            // vertical position of window
125                         width,                                          // window width
126                         height,                                         // window height
127                         0,                                                      // handle to parent or owner window
128                         0,                                                      // handle to menu or child-window identifier
129                         ::GetModuleHandle(0),           // handle to application instance
130                         0);                                                     // pointer to window-creation data
131         }
132         else {
133                 m_hWnd = ::CreateWindow(
134                         s_windowClassName,                      // pointer to registered class name
135                         title,                                          // pointer to window name
136                         WS_POPUP | WS_MAXIMIZE,         // window style
137                         left,                                           // horizontal position of window
138                         top,                                            // vertical position of window
139                         width,                                          // window width
140                         height,                                         // window height
141                         0,                                                      // handle to parent or owner window
142                         0,                                                      // handle to menu or child-window identifier
143                         ::GetModuleHandle(0),           // handle to application instance
144                         0);                                                     // pointer to window-creation data
145         }
146         if (m_hWnd) {
147                 // Store a pointer to this class in the window structure
148                 LONG result = ::SetWindowLong(m_hWnd, GWL_USERDATA, (LONG)this);
149
150                 // Store the device context
151                 m_hDC = ::GetDC(m_hWnd);
152
153                 // Show the window
154                 int nCmdShow;
155                 switch (state) {
156                         case GHOST_kWindowStateMaximized:
157                                 nCmdShow = SW_SHOWMAXIMIZED;
158                                 break;
159                         case GHOST_kWindowStateMinimized:
160                                 nCmdShow = SW_SHOWMINIMIZED;
161                                 break;
162                         case GHOST_kWindowStateNormal:
163                         default:
164                                 nCmdShow = SW_SHOWNORMAL;
165                                 break;
166                 }
167                 setDrawingContextType(type);
168                 ::ShowWindow(m_hWnd, nCmdShow);
169                 // Force an initial paint of the window
170                 ::UpdateWindow(m_hWnd);
171         }
172
173         m_wintab = ::LoadLibrary("Wintab32.dll");
174         if (m_wintab) {
175                 GHOST_WIN32_WTInfo fpWTInfo = ( GHOST_WIN32_WTInfo ) ::GetProcAddress( m_wintab, "WTInfoA" );
176                 GHOST_WIN32_WTOpen fpWTOpen = ( GHOST_WIN32_WTOpen ) ::GetProcAddress( m_wintab, "WTOpenA" );
177
178                 // let's see if we can initialize tablet here
179                 /* check if WinTab available. */
180                 if (fpWTInfo && fpWTInfo(0, 0, NULL)) {
181                         // Now init the tablet
182                         LOGCONTEXT lc;
183                         AXIS TabletX, TabletY, Pressure, Orientation[3]; /* The maximum tablet size, pressure and orientation (tilt) */
184
185                         // Open a Wintab context
186
187                         // Get default context information
188                         fpWTInfo( WTI_DEFCONTEXT, 0, &lc );
189
190                         // Open the context
191                         lc.lcPktData = PACKETDATA;
192                         lc.lcPktMode = PACKETMODE;
193                         lc.lcOptions |= CXO_MESSAGES | CXO_SYSTEM;
194
195                         /* Set the entire tablet as active */
196                         fpWTInfo(WTI_DEVICES,DVC_X,&TabletX);
197                         fpWTInfo(WTI_DEVICES,DVC_Y,&TabletY);
198
199                         /* get the max pressure, to divide into a float */
200                         BOOL pressureSupport = fpWTInfo (WTI_DEVICES, DVC_NPRESSURE, &Pressure);
201                         if (pressureSupport)
202                                 m_maxPressure = Pressure.axMax;
203                         else
204                                 m_maxPressure = 0;
205
206                         /* get the max tilt axes, to divide into floats */
207                         BOOL tiltSupport = fpWTInfo (WTI_DEVICES, DVC_ORIENTATION, &Orientation);
208                         if (tiltSupport) {
209                                 /* does the tablet support azimuth ([0]) and altitude ([1]) */
210                                 if (Orientation[0].axResolution && Orientation[1].axResolution) {
211                                         /* all this assumes the minimum is 0 */
212                                         m_maxAzimuth = Orientation[0].axMax;
213                                         m_maxAltitude = Orientation[1].axMax;
214                                 }
215                                 else {  /* no so dont do tilt stuff */
216                                         m_maxAzimuth = m_maxAltitude = 0;
217                                 }
218                         }
219
220                         if (fpWTOpen) {
221                                 m_tablet = fpWTOpen( m_hWnd, &lc, TRUE );
222                                 if (m_tablet) {
223                                         m_tabletData = new GHOST_TabletData();
224                                         m_tabletData->Active = 0;
225                                 }
226                         }
227                 }
228         }
229 }
230
231
232 GHOST_WindowWin32::~GHOST_WindowWin32()
233 {
234         if (m_wintab) {
235                 GHOST_WIN32_WTClose fpWTClose = ( GHOST_WIN32_WTClose ) ::GetProcAddress( m_wintab, "WTClose" );
236                 if (fpWTClose) {
237                         if (m_tablet) 
238                                 fpWTClose(m_tablet);
239                         if (m_tabletData)
240                                 delete m_tabletData;
241                                 m_tabletData = NULL;
242                 }
243         }
244         if (m_customCursor) {
245                 DestroyCursor(m_customCursor);
246                 m_customCursor = NULL;
247         }
248
249         setDrawingContextType(GHOST_kDrawingContextTypeNone);
250         if (m_hDC) {
251                 ::ReleaseDC(m_hWnd, m_hDC);
252                 m_hDC = 0;
253         }
254         if (m_hWnd) {
255                 ::DestroyWindow(m_hWnd);
256                 m_hWnd = 0;
257         }
258 }
259
260 bool GHOST_WindowWin32::getValid() const
261 {
262         return m_hWnd != 0;
263 }
264
265
266 void GHOST_WindowWin32::setTitle(const STR_String& title)
267 {
268         ::SetWindowText(m_hWnd, title);
269 }
270
271
272 void GHOST_WindowWin32::getTitle(STR_String& title) const
273 {
274         char buf[s_maxTitleLength];
275         ::GetWindowText(m_hWnd, buf, s_maxTitleLength);
276         STR_String temp (buf);
277         title = buf;
278 }
279
280
281 void GHOST_WindowWin32::getWindowBounds(GHOST_Rect& bounds) const
282 {
283         RECT rect;
284         ::GetWindowRect(m_hWnd, &rect);
285         bounds.m_b = rect.bottom;
286         bounds.m_l = rect.left;
287         bounds.m_r = rect.right;
288         bounds.m_t = rect.top;
289 }
290
291
292 void GHOST_WindowWin32::getClientBounds(GHOST_Rect& bounds) const
293 {
294         RECT rect;
295         ::GetClientRect(m_hWnd, &rect);
296         bounds.m_b = rect.bottom;
297         bounds.m_l = rect.left;
298         bounds.m_r = rect.right;
299         bounds.m_t = rect.top;
300 }
301
302
303 GHOST_TSuccess GHOST_WindowWin32::setClientWidth(GHOST_TUns32 width)
304 {
305         GHOST_TSuccess success;
306         GHOST_Rect cBnds, wBnds;
307         getClientBounds(cBnds);
308         if (cBnds.getWidth() != width) {
309                 getWindowBounds(wBnds);
310                 int cx = wBnds.getWidth() + width - cBnds.getWidth();
311                 int cy = wBnds.getHeight();
312                 success =  ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
313                         GHOST_kSuccess : GHOST_kFailure;
314         }
315         else {
316                 success = GHOST_kSuccess;
317         }
318         return success;
319 }
320
321
322 GHOST_TSuccess GHOST_WindowWin32::setClientHeight(GHOST_TUns32 height)
323 {
324         GHOST_TSuccess success;
325         GHOST_Rect cBnds, wBnds;
326         getClientBounds(cBnds);
327         if (cBnds.getHeight() != height) {
328                 getWindowBounds(wBnds);
329                 int cx = wBnds.getWidth();
330                 int cy = wBnds.getHeight() + height - cBnds.getHeight();
331                 success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
332                         GHOST_kSuccess : GHOST_kFailure;
333         }
334         else {
335                 success = GHOST_kSuccess;
336         }
337         return success;
338 }
339
340
341 GHOST_TSuccess GHOST_WindowWin32::setClientSize(GHOST_TUns32 width, GHOST_TUns32 height)
342 {
343         GHOST_TSuccess success;
344         GHOST_Rect cBnds, wBnds;
345         getClientBounds(cBnds);
346         if ((cBnds.getWidth() != width) || (cBnds.getHeight() != height)) {
347                 getWindowBounds(wBnds);
348                 int cx = wBnds.getWidth() + width - cBnds.getWidth();
349                 int cy = wBnds.getHeight() + height - cBnds.getHeight();
350                 success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
351                         GHOST_kSuccess : GHOST_kFailure;
352         }
353         else {
354                 success = GHOST_kSuccess;
355         }
356         return success;
357 }
358
359
360 GHOST_TWindowState GHOST_WindowWin32::getState() const
361 {
362         GHOST_TWindowState state;
363         if (::IsIconic(m_hWnd)) {
364                 state = GHOST_kWindowStateMinimized;
365         }
366         else if (::IsZoomed(m_hWnd)) {
367                 state = GHOST_kWindowStateMaximized;
368         }
369         else {
370                 state = GHOST_kWindowStateNormal;
371         }
372         return state;
373 }
374
375
376 void GHOST_WindowWin32::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
377 {
378         POINT point = { inX, inY };
379         ::ScreenToClient(m_hWnd, &point);
380         outX = point.x;
381         outY = point.y;
382 }
383
384
385 void GHOST_WindowWin32::clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
386 {
387         POINT point = { inX, inY };
388         ::ClientToScreen(m_hWnd, &point);
389         outX = point.x;
390         outY = point.y;
391 }
392
393
394 GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state)
395 {
396         WINDOWPLACEMENT wp;
397         wp.length = sizeof(WINDOWPLACEMENT);
398         ::GetWindowPlacement(m_hWnd, &wp);
399         switch (state) {
400         case GHOST_kWindowStateMinimized: 
401                 wp.showCmd = SW_SHOWMINIMIZED; 
402                 break;
403         case GHOST_kWindowStateMaximized: 
404                 ShowWindow(m_hWnd, SW_HIDE); //fe. HACK!
405                                 //Solves redraw problems when switching from fullscreen to normal.
406                                 
407                 wp.showCmd = SW_SHOWMAXIMIZED; 
408                 SetWindowLong(m_hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
409                 break;
410         case GHOST_kWindowStateFullScreen:
411                 wp.showCmd = SW_SHOWMAXIMIZED;
412                 SetWindowLong(m_hWnd, GWL_STYLE, WS_POPUP | WS_MAXIMIZE);
413                 break;
414         case GHOST_kWindowStateNormal: 
415         default: 
416                 wp.showCmd = SW_SHOWNORMAL; 
417                 break;
418         }
419         return ::SetWindowPlacement(m_hWnd, &wp) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
420 }
421
422
423 GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
424 {
425         HWND hWndInsertAfter = order == GHOST_kWindowOrderTop ? HWND_TOP : HWND_BOTTOM;
426         return ::SetWindowPos(m_hWnd, hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
427 }
428
429
430 GHOST_TSuccess GHOST_WindowWin32::swapBuffers()
431 {
432         // adding a glFinish() here is to prevent Geforce in 'full scene antialias' mode
433         // from antialising the Blender window. Officially a swapbuffers does a glFinish
434         // itself, so this feels really like a hack... but it won't harm. (ton)
435         glFinish();
436         return ::SwapBuffers(m_hDC) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
437 }
438
439
440 GHOST_TSuccess GHOST_WindowWin32::activateDrawingContext()
441 {
442         GHOST_TSuccess success;
443         if (m_drawingContextType == GHOST_kDrawingContextTypeOpenGL) {
444                 if (m_hDC && m_hGlRc) {
445                         success = ::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
446                 }
447                 else {
448                         success = GHOST_kFailure;
449                 }
450         }
451         else {
452                 success = GHOST_kSuccess;
453         }
454         return success;
455 }
456
457
458 GHOST_TSuccess GHOST_WindowWin32::invalidate()
459 {
460         GHOST_TSuccess success;
461         if (m_hWnd) {
462                 success = ::InvalidateRect(m_hWnd, 0, FALSE) != 0 ? GHOST_kSuccess : GHOST_kFailure;
463         }
464         else {
465                 success = GHOST_kFailure;
466         }
467         return success;
468 }
469
470
471 GHOST_TSuccess GHOST_WindowWin32::installDrawingContext(GHOST_TDrawingContextType type)
472 {
473         GHOST_TSuccess success;
474         switch (type) {
475         case GHOST_kDrawingContextTypeOpenGL:
476                 {
477                 if(m_stereoVisual) 
478                         sPreferredFormat.dwFlags |= PFD_STEREO;
479
480                 // Attempt to match device context pixel format to the preferred format
481                 int iPixelFormat = EnumPixelFormats(m_hDC);
482                 if (iPixelFormat == 0) {
483                         success = GHOST_kFailure;
484                         break;
485                 }
486                 if (::SetPixelFormat(m_hDC, iPixelFormat, &sPreferredFormat) == FALSE) {
487                         success = GHOST_kFailure;
488                         break;
489                 }
490                 // For debugging only: retrieve the pixel format chosen
491                 PIXELFORMATDESCRIPTOR preferredFormat;
492                 ::DescribePixelFormat(m_hDC, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &preferredFormat);
493                 // Create the context
494                 m_hGlRc = ::wglCreateContext(m_hDC);
495                 if (m_hGlRc) {
496                         if (s_firsthGLRc) {
497                                 wglShareLists(s_firsthGLRc, m_hGlRc);
498                         } else {
499                                 s_firsthGLRc = m_hGlRc;
500                         }
501
502                         success = ::wglMakeCurrent(m_hDC, m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
503                 }
504                 else {
505                         success = GHOST_kFailure;
506                 }
507                 }
508                 break;
509
510         case GHOST_kDrawingContextTypeNone:
511                 success = GHOST_kSuccess;
512                 break;
513
514         default:
515                 success = GHOST_kFailure;
516         }
517         return success;
518 }
519
520
521 GHOST_TSuccess GHOST_WindowWin32::removeDrawingContext()
522 {
523         GHOST_TSuccess success;
524         switch (m_drawingContextType) {
525         case GHOST_kDrawingContextTypeOpenGL:
526                 if (m_hGlRc) {
527                         success = ::wglDeleteContext(m_hGlRc) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
528                         if (m_hGlRc == s_firsthGLRc) {
529                                 s_firsthGLRc = NULL;
530                         }
531                         m_hGlRc = 0;
532                 }
533                 else {
534                         success = GHOST_kFailure;
535                 }
536                 break;
537         case GHOST_kDrawingContextTypeNone:
538                 success = GHOST_kSuccess;
539                 break;
540         default:
541                 success = GHOST_kFailure;
542         }
543         return success;
544 }
545
546 void GHOST_WindowWin32::lostMouseCapture()
547 {
548         if (m_hasMouseCaptured) {
549                 m_hasMouseCaptured = false;
550                 m_nPressedButtons = 0;
551         }
552 }
553
554 void GHOST_WindowWin32::registerMouseClickEvent(bool press)
555 {
556         if (press) {
557                 if (!m_hasMouseCaptured) {
558                         ::SetCapture(m_hWnd);
559                         m_hasMouseCaptured = true;
560                 }
561                 m_nPressedButtons++;
562         } else {
563                 if (m_nPressedButtons) {
564                         m_nPressedButtons--;
565                         if (!m_nPressedButtons) {
566                                 ::ReleaseCapture();
567                                 m_hasMouseCaptured = false;
568                         }
569                 }
570         }
571 }
572
573
574 void GHOST_WindowWin32::loadCursor(bool visible, GHOST_TStandardCursor cursor) const
575 {
576         if (!visible) {
577                 while (::ShowCursor(FALSE) >= 0);
578         }
579         else {
580                 while (::ShowCursor(TRUE) < 0);
581         }
582
583         if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
584                 ::SetCursor( m_customCursor );
585         } else {
586                 // Convert GHOST cursor to Windows OEM cursor
587                 bool success = true;
588                 LPCSTR id;
589                 switch (cursor) {
590                         case GHOST_kStandardCursorDefault:              id = IDC_ARROW;         break;
591                         case GHOST_kStandardCursorRightArrow:           id = IDC_ARROW;         break;
592                         case GHOST_kStandardCursorLeftArrow:            id = IDC_ARROW;         break;
593                         case GHOST_kStandardCursorInfo:                 id = IDC_SIZEALL;       break;  // Four-pointed arrow pointing north, south, east, and west
594                         case GHOST_kStandardCursorDestroy:              id = IDC_NO;            break;  // Slashed circle
595                         case GHOST_kStandardCursorHelp:                 id = IDC_HELP;          break;  // Arrow and question mark
596                         case GHOST_kStandardCursorCycle:                id = IDC_NO;            break;  // Slashed circle
597                         case GHOST_kStandardCursorSpray:                id = IDC_SIZEALL;       break;  // Four-pointed arrow pointing north, south, east, and west
598                         case GHOST_kStandardCursorWait:                 id = IDC_WAIT;          break;  // Hourglass
599                         case GHOST_kStandardCursorText:                 id = IDC_IBEAM;         break;  // I-beam
600                         case GHOST_kStandardCursorCrosshair:            id = IDC_CROSS;         break;  // Crosshair
601                         case GHOST_kStandardCursorUpDown:               id = IDC_SIZENS;        break;  // Double-pointed arrow pointing north and south
602                         case GHOST_kStandardCursorLeftRight:            id = IDC_SIZEWE;        break;  // Double-pointed arrow pointing west and east
603                         case GHOST_kStandardCursorTopSide:              id = IDC_UPARROW;       break;  // Vertical arrow
604                         case GHOST_kStandardCursorBottomSide:           id = IDC_SIZENS;        break;
605                         case GHOST_kStandardCursorLeftSide:             id = IDC_SIZEWE;        break;
606                         case GHOST_kStandardCursorTopLeftCorner:        id = IDC_SIZENWSE;      break;
607                         case GHOST_kStandardCursorTopRightCorner:       id = IDC_SIZENESW;      break;
608                         case GHOST_kStandardCursorBottomRightCorner:    id = IDC_SIZENWSE;      break;
609                         case GHOST_kStandardCursorBottomLeftCorner:     id = IDC_SIZENESW;      break;
610                         case GHOST_kStandardCursorPencil:               id = IDC_ARROW;         break;
611                         default:
612                         success = false;
613                 }
614                 
615                 if (success) {
616                         HCURSOR hCursor = ::SetCursor(::LoadCursor(0, id));
617                 }
618         }
619 }
620
621 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorVisibility(bool visible)
622 {
623         if (::GetForegroundWindow() == m_hWnd) {
624                 loadCursor(visible, getCursorShape());
625         }
626
627         return GHOST_kSuccess;
628 }
629
630 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorShape(GHOST_TStandardCursor cursorShape)
631 {
632         if (m_customCursor) {
633                 DestroyCursor(m_customCursor);
634                 m_customCursor = NULL;
635         }
636
637         if (::GetForegroundWindow() == m_hWnd) {
638                 loadCursor(getCursorVisibility(), cursorShape);
639         }
640
641         return GHOST_kSuccess;
642 }
643 void GHOST_WindowWin32::processWin32TabletInitEvent()
644 {
645         if (m_wintab) {
646                 GHOST_WIN32_WTInfo fpWTInfo = ( GHOST_WIN32_WTInfo ) ::GetProcAddress( m_wintab, "WTInfoA" );
647                 
648                 // let's see if we can initialize tablet here
649                 /* check if WinTab available. */
650                 if (fpWTInfo) {
651                         AXIS Pressure, Orientation[3]; /* The maximum tablet size */
652
653                         BOOL pressureSupport = fpWTInfo (WTI_DEVICES, DVC_NPRESSURE, &Pressure);
654                         if (pressureSupport)
655                                 m_maxPressure = Pressure.axMax;
656                         else
657                                 m_maxPressure = 0;
658                         
659                         BOOL tiltSupport = fpWTInfo (WTI_DEVICES, DVC_ORIENTATION, &Orientation);
660                         if (tiltSupport) {
661                                 /* does the tablet support azimuth ([0]) and altitude ([1]) */
662                                 if (Orientation[0].axResolution && Orientation[1].axResolution) {
663                                         m_maxAzimuth = Orientation[0].axMax;
664                                         m_maxAltitude = Orientation[1].axMax;
665                                 }
666                                 else {  /* no so dont do tilt stuff */
667                                         m_maxAzimuth = m_maxAltitude = 0;
668                                 }
669                         }
670
671                         m_tabletData->Active = 0;
672                 }
673         }
674 }
675
676 void GHOST_WindowWin32::processWin32TabletEvent(WPARAM wParam, LPARAM lParam)
677 {
678         PACKET pkt;
679         if (m_wintab) {
680                 GHOST_WIN32_WTPacket fpWTPacket = ( GHOST_WIN32_WTPacket ) ::GetProcAddress( m_wintab, "WTPacket" );
681                 if (fpWTPacket) {
682                         if (fpWTPacket((HCTX)lParam, wParam, &pkt)) {
683                                 if (m_tabletData) {
684                                         switch (pkt.pkCursor) {
685                                                 case 0: /* first device */
686                                                 case 3: /* second device */
687                                                         m_tabletData->Active = 0; /* puck - not yet supported */
688                                                         break;
689                                                 case 1:
690                                                 case 4:
691                                                         m_tabletData->Active = 1; /* stylus */
692                                                         break;
693                                                 case 2:
694                                                 case 5:
695                                                         m_tabletData->Active = 2; /* eraser */
696                                                         break;
697                                         }
698                                         if (m_maxPressure > 0) {
699                                                 m_tabletData->Pressure = (float)pkt.pkNormalPressure / (float)m_maxPressure;
700                                         } else {
701                                                 m_tabletData->Pressure = 1.0f;
702                                         }
703
704                                         if ((m_maxAzimuth > 0) && (m_maxAltitude > 0)) {
705                                                 ORIENTATION ort = pkt.pkOrientation;
706                                                 float vecLen;
707                                                 float altRad, azmRad;   /* in radians */
708
709                                                 /*
710                                                 from the wintab spec:
711                                                 orAzimuth       Specifies the clockwise rotation of the
712                                                 cursor about the z axis through a full circular range.
713
714                                                 orAltitude      Specifies the angle with the x-y plane
715                                                 through a signed, semicircular range.  Positive values
716                                                 specify an angle upward toward the positive z axis;
717                                                 negative values specify an angle downward toward the negative z axis.
718
719                                                 wintab.h defines .orAltitude as a UINT but documents .orAltitude
720                                                 as positive for upward angles and negative for downward angles.
721                                                 WACOM uses negative altitude values to show that the pen is inverted;
722                                                 therefore we cast .orAltitude as an (int) and then use the absolute value.
723                                                 */
724                                                 
725                                                 /* convert raw fixed point data to radians */
726                                                 altRad = (fabs((float)ort.orAltitude)/(float)m_maxAltitude) * M_PI/2.0;
727                                                 azmRad = ((float)ort.orAzimuth/(float)m_maxAzimuth) * M_PI*2.0;
728
729                                                 /* find length of the stylus' projected vector on the XY plane */
730                                                 vecLen = cos(altRad);
731
732                                                 /* from there calculate X and Y components based on azimuth */
733                                                 m_tabletData->Xtilt = sin(azmRad) * vecLen;
734                                                 m_tabletData->Ytilt = sin(M_PI/2.0 - azmRad) * vecLen;
735
736                                         } else {
737                                                 m_tabletData->Xtilt = 0.0f;
738                                                 m_tabletData->Ytilt = 0.0f;
739                                         }
740                                 }
741                         }
742                 }
743         }
744 }
745
746 /** Reverse the bits in a GHOST_TUns8 */
747 static GHOST_TUns8 uns8ReverseBits(GHOST_TUns8 ch)
748 {
749         ch= ((ch>>1)&0x55) | ((ch<<1)&0xAA);
750         ch= ((ch>>2)&0x33) | ((ch<<2)&0xCC);
751         ch= ((ch>>4)&0x0F) | ((ch<<4)&0xF0);
752         return ch;
753 }
754
755 /** Reverse the bits in a GHOST_TUns16 */
756 static GHOST_TUns16 uns16ReverseBits(GHOST_TUns16 shrt)
757 {
758         shrt= ((shrt>>1)&0x5555) | ((shrt<<1)&0xAAAA);
759         shrt= ((shrt>>2)&0x3333) | ((shrt<<2)&0xCCCC);
760         shrt= ((shrt>>4)&0x0F0F) | ((shrt<<4)&0xF0F0);
761         shrt= ((shrt>>8)&0x00FF) | ((shrt<<8)&0xFF00);
762         return shrt;
763 }
764 GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2], 
765                                         GHOST_TUns8 mask[16][2], int hotX, int hotY)
766 {
767         return setWindowCustomCursorShape((GHOST_TUns8*)bitmap, (GHOST_TUns8*)mask, 
768                                                                         16, 16, hotX, hotY, 0, 1);
769 }
770
771 GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(GHOST_TUns8 *bitmap, 
772                                         GHOST_TUns8 *mask, int sizeX, int sizeY, int hotX, int hotY, 
773                                         int fg_color, int bg_color)
774 {
775         GHOST_TUns32 andData[32];
776         GHOST_TUns32 xorData[32];
777         GHOST_TUns32 fullBitRow, fullMaskRow;
778         int x, y, cols;
779         
780         cols=sizeX/8; /* Num of whole bytes per row (width of bm/mask) */
781         if (sizeX%8) cols++;
782         
783         if (m_customCursor) {
784                 DestroyCursor(m_customCursor);
785                 m_customCursor = NULL;
786         }
787
788         memset(&andData, 0xFF, sizeof(andData));
789         memset(&xorData, 0, sizeof(xorData));
790
791         for (y=0; y<sizeY; y++) {
792                 fullBitRow=0;
793                 fullMaskRow=0;
794                 for (x=cols-1; x>=0; x--){
795                         fullBitRow<<=8;
796                         fullMaskRow<<=8;
797                         fullBitRow  |= uns8ReverseBits(bitmap[cols*y + x]);
798                         fullMaskRow |= uns8ReverseBits(  mask[cols*y + x]);
799                 }
800                 xorData[y]= fullBitRow & fullMaskRow;
801                 andData[y]= ~fullMaskRow;
802         }
803
804         m_customCursor = ::CreateCursor(::GetModuleHandle(0), hotX, hotY, 32, 32, andData, xorData);
805         if (!m_customCursor) {
806                 return GHOST_kFailure;
807         }
808
809         if (::GetForegroundWindow() == m_hWnd) {
810                 loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
811         }
812
813         return GHOST_kSuccess;
814 }
815
816
817 /*  Ron Fosner's code for weighting pixel formats and forcing software.
818         See http://www.opengl.org/resources/faq/technical/weight.cpp */
819
820 static int WeightPixelFormat(PIXELFORMATDESCRIPTOR& pfd) {
821         int weight = 0;
822         
823         /* assume desktop color depth is 32 bits per pixel */
824         
825         /* cull unusable pixel formats */
826         /* if no formats can be found, can we determine why it was rejected? */
827         if( !(pfd.dwFlags & PFD_SUPPORT_OPENGL) ||
828                 !(pfd.dwFlags & PFD_DRAW_TO_WINDOW) ||
829                 !(pfd.dwFlags & PFD_DOUBLEBUFFER) || /* Blender _needs_ this */
830                 ( pfd.cDepthBits <= 8 ) ||
831                 !(pfd.iPixelType == PFD_TYPE_RGBA) )
832                 return 0;
833         
834         weight = 1;  /* it's usable */
835         
836         /* the bigger the depth buffer the better */
837         /* give no weight to a 16-bit depth buffer, because those are crap */
838         weight += pfd.cDepthBits - 16;
839         
840         weight += pfd.cColorBits - 8;
841         
842         /* want swap copy capability -- it matters a lot */
843         if(pfd.dwFlags & PFD_SWAP_COPY) weight += 16;
844         
845         /* but if it's a generic (not accelerated) view, it's really bad */
846         if(pfd.dwFlags & PFD_GENERIC_FORMAT) weight /= 10;
847         
848         return weight;
849 }
850
851 /* A modification of Ron Fosner's replacement for ChoosePixelFormat */ 
852 /* returns 0 on error, else returns the pixel format number to be used */
853 static int EnumPixelFormats(HDC hdc) {
854         int iPixelFormat;
855         int i, n, w, weight = 0;
856         PIXELFORMATDESCRIPTOR pfd, pfd_fallback;
857         
858         /* we need a device context to do anything */
859         if(!hdc) return 0;
860
861         iPixelFormat = 1; /* careful! PFD numbers are 1 based, not zero based */
862         
863         /* obtain detailed information about 
864         the device context's first pixel format */
865         n = 1+::DescribePixelFormat(hdc, iPixelFormat, 
866                 sizeof(PIXELFORMATDESCRIPTOR), &pfd);
867         
868         /* choose a pixel format using the useless Windows function in case
869                 we come up empty handed */
870         iPixelFormat = ::ChoosePixelFormat( hdc, &sPreferredFormat );
871         
872         if(!iPixelFormat) return 0; /* couldn't find one to use */
873
874         for(i=1; i<=n; i++) { /* not the idiom, but it's right */
875                 ::DescribePixelFormat( hdc, i, sizeof(PIXELFORMATDESCRIPTOR), &pfd );
876                 w = WeightPixelFormat(pfd);
877                 if(w > weight) {
878                         weight = w;
879                         iPixelFormat = i;
880                 }
881         }
882         
883         return iPixelFormat;
884 }
885
886