Merge remote-tracking branch 'origin/master' into blender2.8
[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): Maarten Gribnau.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file ghost/intern/GHOST_WindowWin32.cpp
29  *  \ingroup GHOST
30  */
31
32 #define _USE_MATH_DEFINES
33
34 #include "GHOST_WindowWin32.h"
35 #include "GHOST_SystemWin32.h"
36 #include "GHOST_DropTargetWin32.h"
37 #include "GHOST_ContextNone.h"
38 #include "utfconv.h"
39 #include "utf_winfunc.h"
40
41 #if defined(WITH_GL_EGL)
42 #  include "GHOST_ContextEGL.h"
43 #else
44 #  include "GHOST_ContextWGL.h"
45 #endif
46 #ifdef WIN32_COMPOSITING
47 #include <Dwmapi.h>
48 #endif
49
50 #include <math.h>
51 #include <string.h>
52 #include <assert.h>
53
54
55
56 const wchar_t *GHOST_WindowWin32::s_windowClassName = L"GHOST_WindowClass";
57 const int GHOST_WindowWin32::s_maxTitleLength = 128;
58
59
60
61
62 /* force NVidia Optimus to used dedicated graphics */
63 extern "C" {
64         __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
65 }
66
67 GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
68         const STR_String &title,
69         GHOST_TInt32 left,
70         GHOST_TInt32 top,
71         GHOST_TUns32 width,
72         GHOST_TUns32 height,
73         GHOST_TWindowState state,
74         GHOST_TDrawingContextType type,
75         bool wantStereoVisual,
76         bool alphaBackground,
77         GHOST_TUns16 wantNumOfAASamples,
78         GHOST_TEmbedderWindowID parentwindowhwnd,
79         bool is_debug)
80     : GHOST_Window(width, height, state,
81                    wantStereoVisual, false, wantNumOfAASamples),
82       m_inLiveResize(false),
83       m_system(system),
84       m_hDC(0),
85       m_hasMouseCaptured(false),
86       m_hasGrabMouse(false),
87       m_nPressedButtons(0),
88       m_customCursor(0),
89       m_wantAlphaBackground(alphaBackground),
90       m_wintab(NULL),
91       m_tabletData(NULL),
92       m_tablet(0),
93       m_maxPressure(0),
94       m_normal_state(GHOST_kWindowStateNormal),
95           m_user32(NULL),
96       m_parentWindowHwnd(parentwindowhwnd),
97       m_debug_context(is_debug)
98 {
99         if (state != GHOST_kWindowStateFullScreen) {
100                 RECT rect;
101                 MONITORINFO monitor;
102                 GHOST_TUns32 tw, th;
103
104 #ifndef _MSC_VER
105                 int cxsizeframe = GetSystemMetrics(SM_CXSIZEFRAME);
106                 int cysizeframe = GetSystemMetrics(SM_CYSIZEFRAME);
107 #else
108                 // MSVC 2012+ returns bogus values from GetSystemMetrics, bug in Windows
109                 // http://connect.microsoft.com/VisualStudio/feedback/details/753224/regression-getsystemmetrics-delivers-different-values
110                 RECT cxrect = {0, 0, 0, 0};
111                 AdjustWindowRectEx(&cxrect, WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_THICKFRAME | WS_DLGFRAME, FALSE, 0);
112
113                 int cxsizeframe = abs(cxrect.bottom);
114                 int cysizeframe = abs(cxrect.left);
115 #endif
116
117                 width += cxsizeframe * 2;
118                 height += cysizeframe * 2 + GetSystemMetrics(SM_CYCAPTION);
119
120                 rect.left = left;
121                 rect.right = left + width;
122                 rect.top = top;
123                 rect.bottom = top + height;
124
125                 monitor.cbSize = sizeof(monitor);
126                 monitor.dwFlags = 0;
127
128                 // take taskbar into account
129                 GetMonitorInfo(MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST), &monitor);
130
131                 th = monitor.rcWork.bottom - monitor.rcWork.top;
132                 tw = monitor.rcWork.right - monitor.rcWork.left;
133
134                 if (tw < width) {
135                         width = tw;
136                         left = monitor.rcWork.left;
137                 }
138                 else if (monitor.rcWork.right < left + (int)width)
139                         left = monitor.rcWork.right - width;
140                 else if (left < monitor.rcWork.left)
141                         left = monitor.rcWork.left;
142
143                 if (th < height) {
144                         height = th;
145                         top = monitor.rcWork.top;
146                 }
147                 else if (monitor.rcWork.bottom < top + (int)height)
148                         top = monitor.rcWork.bottom - height;
149                 else if (top < monitor.rcWork.top)
150                         top = monitor.rcWork.top;
151
152                 int wintype = WS_OVERLAPPEDWINDOW;
153                 if (m_parentWindowHwnd != 0) {
154                         wintype = WS_CHILD;
155                         GetWindowRect((HWND)m_parentWindowHwnd, &rect);
156                         left = 0;
157                         top = 0;
158                         width = rect.right - rect.left;
159                         height = rect.bottom - rect.top;
160                 }
161
162                 wchar_t *title_16 = alloc_utf16_from_8((char *)(const char *)title, 0);
163                 m_hWnd = ::CreateWindowW(
164                         s_windowClassName,          // pointer to registered class name
165                         title_16,                   // pointer to window name
166                         wintype,                    // window style
167                         left,                       // horizontal position of window
168                         top,                        // vertical position of window
169                         width,                      // window width
170                         height,                     // window height
171                         (HWND)m_parentWindowHwnd,  // handle to parent or owner window
172                         0,                          // handle to menu or child-window identifier
173                         ::GetModuleHandle(0),       // handle to application instance
174                         0);                         // pointer to window-creation data
175                 free(title_16);
176         }
177         else {
178                 wchar_t *title_16 = alloc_utf16_from_8((char *)(const char *)title, 0);
179                 m_hWnd = ::CreateWindowW(
180                     s_windowClassName,          // pointer to registered class name
181                     title_16,                   // pointer to window name
182                     WS_POPUP | WS_MAXIMIZE,     // window style
183                     left,                       // horizontal position of window
184                     top,                        // vertical position of window
185                     width,                      // window width
186                     height,                     // window height
187                     HWND_DESKTOP,               // handle to parent or owner window
188                     0,                          // handle to menu or child-window identifier
189                     ::GetModuleHandle(0),       // handle to application instance
190                     0);                         // pointer to window-creation data
191                 free(title_16);
192         }
193         if (m_hWnd) {
194                 // Register this window as a droptarget. Requires m_hWnd to be valid.
195                 // Note that OleInitialize(0) has to be called prior to this. Done in GHOST_SystemWin32.
196                 m_dropTarget = new GHOST_DropTargetWin32(this, m_system);
197                 if (m_dropTarget) {
198                         ::RegisterDragDrop(m_hWnd, m_dropTarget);
199                 }
200
201                 // Store a pointer to this class in the window structure
202                 ::SetWindowLongPtr(m_hWnd, GWLP_USERDATA, (LONG_PTR) this);
203
204                 if (!m_system->m_windowFocus) {
205                         // Lower to bottom and don't activate if we don't want focus
206                         ::SetWindowPos(m_hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
207                 }
208
209                 // Store the device context
210                 m_hDC = ::GetDC(m_hWnd);
211
212                 GHOST_TSuccess success = setDrawingContextType(type);
213
214                 if (success) {
215                         // Show the window
216                         int nCmdShow;
217                         switch (state) {
218                                 case GHOST_kWindowStateMaximized:
219                                         nCmdShow = SW_SHOWMAXIMIZED;
220                                         break;
221                                 case GHOST_kWindowStateMinimized:
222                                         nCmdShow = (m_system->m_windowFocus) ? SW_SHOWMINIMIZED : SW_SHOWMINNOACTIVE;
223                                         break;
224                                 case GHOST_kWindowStateNormal:
225                                 default:
226                                         nCmdShow = (m_system->m_windowFocus) ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE;
227                                         break;
228                         }
229
230                         ::ShowWindow(m_hWnd, nCmdShow);
231 #ifdef WIN32_COMPOSITING
232                         if (alphaBackground && parentwindowhwnd == 0) {
233
234                                 HRESULT hr = S_OK;
235
236                                 // Create and populate the Blur Behind structure
237                                 DWM_BLURBEHIND bb = { 0 };
238
239                                 // Enable Blur Behind and apply to the entire client area
240                                 bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
241                                 bb.fEnable = true;
242                                 bb.hRgnBlur = CreateRectRgn(0, 0, -1, -1);
243
244                                 // Apply Blur Behind
245                                 hr = DwmEnableBlurBehindWindow(m_hWnd, &bb);
246                                 DeleteObject(bb.hRgnBlur);
247                         }
248 #endif
249                         // Force an initial paint of the window
250                         ::UpdateWindow(m_hWnd);
251                 }
252                 else {
253                         //invalidate the window
254                         ::DestroyWindow(m_hWnd);
255                         m_hWnd = NULL;
256                 }
257         }
258
259         if (parentwindowhwnd != 0) {
260                 RAWINPUTDEVICE device = {0};
261                 device.usUsagePage  = 0x01; /* usUsagePage & usUsage for keyboard*/
262                 device.usUsage      = 0x06; /* http://msdn.microsoft.com/en-us/windows/hardware/gg487473.aspx */
263                 device.dwFlags |= RIDEV_INPUTSINK; // makes WM_INPUT is visible for ghost when has parent window
264                 device.hwndTarget = m_hWnd;
265                 RegisterRawInputDevices(&device, 1, sizeof(device));
266         }
267
268         m_wintab = ::LoadLibrary("Wintab32.dll");
269         if (m_wintab) {
270                 GHOST_WIN32_WTInfo fpWTInfo = (GHOST_WIN32_WTInfo) ::GetProcAddress(m_wintab, "WTInfoA");
271                 GHOST_WIN32_WTOpen fpWTOpen = (GHOST_WIN32_WTOpen) ::GetProcAddress(m_wintab, "WTOpenA");
272
273                 // Let's see if we can initialize tablet here.
274                 // Check if WinTab available by getting system context info.
275                 LOGCONTEXT lc = { 0 };
276                 lc.lcOptions |= CXO_SYSTEM;
277                 if (fpWTInfo && fpWTInfo(WTI_DEFSYSCTX, 0, &lc)) {
278                         // Now init the tablet
279                         /* The maximum tablet size, pressure and orientation (tilt) */
280                         AXIS TabletX, TabletY, Pressure, Orientation[3];
281
282                         // Open a Wintab context
283
284                         // Open the context
285                         lc.lcPktData = PACKETDATA;
286                         lc.lcPktMode = PACKETMODE;
287                         lc.lcOptions |= CXO_MESSAGES;
288                         lc.lcMoveMask = PACKETDATA;
289
290                         /* Set the entire tablet as active */
291                         fpWTInfo(WTI_DEVICES, DVC_X, &TabletX);
292                         fpWTInfo(WTI_DEVICES, DVC_Y, &TabletY);
293
294                         /* get the max pressure, to divide into a float */
295                         BOOL pressureSupport = fpWTInfo(WTI_DEVICES, DVC_NPRESSURE, &Pressure);
296                         if (pressureSupport)
297                                 m_maxPressure = Pressure.axMax;
298                         else
299                                 m_maxPressure = 0;
300
301                         /* get the max tilt axes, to divide into floats */
302                         BOOL tiltSupport = fpWTInfo(WTI_DEVICES, DVC_ORIENTATION, &Orientation);
303                         if (tiltSupport) {
304                                 /* does the tablet support azimuth ([0]) and altitude ([1]) */
305                                 if (Orientation[0].axResolution && Orientation[1].axResolution) {
306                                         /* all this assumes the minimum is 0 */
307                                         m_maxAzimuth = Orientation[0].axMax;
308                                         m_maxAltitude = Orientation[1].axMax;
309                                 }
310                                 else {  /* no so dont do tilt stuff */
311                                         m_maxAzimuth = m_maxAltitude = 0;
312                                 }
313                         }
314
315                         if (fpWTOpen) {
316                                 // The Wintab spec says we must open the context disabled if we are using cursor masks.
317                                 m_tablet = fpWTOpen(m_hWnd, &lc, FALSE);
318                                 if (m_tablet) {
319                                         m_tabletData = new GHOST_TabletData();
320                                         m_tabletData->Active = GHOST_kTabletModeNone;
321                                 }
322
323                                 GHOST_WIN32_WTEnable fpWTEnable = (GHOST_WIN32_WTEnable) ::GetProcAddress(m_wintab, "WTEnable");
324                                 if (fpWTEnable) {
325                                         fpWTEnable(m_tablet, TRUE);
326                                 }
327                         }
328                 }
329         }
330         CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID *)&m_Bar);
331 }
332
333
334 GHOST_WindowWin32::~GHOST_WindowWin32()
335 {
336         if (m_Bar) {
337                 m_Bar->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
338                 m_Bar->Release();
339         }
340
341         if (m_wintab) {
342                 GHOST_WIN32_WTClose fpWTClose = (GHOST_WIN32_WTClose) ::GetProcAddress(m_wintab, "WTClose");
343                 if (fpWTClose) {
344                         if (m_tablet)
345                                 fpWTClose(m_tablet);
346                         delete m_tabletData;
347                         m_tabletData = NULL;
348                 }
349         }
350
351         if (m_customCursor) {
352                 DestroyCursor(m_customCursor);
353                 m_customCursor = NULL;
354         }
355
356         if (m_hWnd != NULL && m_hDC != NULL && releaseNativeHandles()) {
357                 ::ReleaseDC(m_hWnd, m_hDC);
358         }
359
360         if (m_hWnd) {
361                 if (m_dropTarget) {
362                         // Disable DragDrop
363                         RevokeDragDrop(m_hWnd);
364                         // Release our reference of the DropTarget and it will delete itself eventually.
365                         m_dropTarget->Release();
366                 }
367                 ::SetWindowLongPtr(m_hWnd, GWLP_USERDATA, NULL);
368                 ::DestroyWindow(m_hWnd);
369                 m_hWnd = 0;
370         }
371 }
372
373 bool GHOST_WindowWin32::getValid() const
374 {
375         return GHOST_Window::getValid() && m_hWnd != 0 && m_hDC != 0;
376 }
377
378 HWND GHOST_WindowWin32::getHWND() const
379 {
380         return m_hWnd;
381 }
382
383 void GHOST_WindowWin32::setTitle(const STR_String &title)
384 {
385         wchar_t *title_16 = alloc_utf16_from_8((char *)(const char *)title, 0);
386         ::SetWindowTextW(m_hWnd, (wchar_t *)title_16);
387         free(title_16);
388 }
389
390
391 void GHOST_WindowWin32::getTitle(STR_String &title) const
392 {
393         char buf[s_maxTitleLength]; /*CHANGE + never used yet*/
394         ::GetWindowText(m_hWnd, buf, s_maxTitleLength);
395         STR_String temp(buf);
396         title = buf;
397 }
398
399
400 void GHOST_WindowWin32::getWindowBounds(GHOST_Rect &bounds) const
401 {
402         RECT rect;
403         ::GetWindowRect(m_hWnd, &rect);
404         bounds.m_b = rect.bottom;
405         bounds.m_l = rect.left;
406         bounds.m_r = rect.right;
407         bounds.m_t = rect.top;
408 }
409
410
411 void GHOST_WindowWin32::getClientBounds(GHOST_Rect &bounds) const
412 {
413         RECT rect;
414         POINT coord;
415         if (!IsIconic(m_hWnd)) {
416                 ::GetClientRect(m_hWnd, &rect);
417
418                 coord.x = rect.left;
419                 coord.y = rect.top;
420                 ::ClientToScreen(m_hWnd, &coord);
421
422                 bounds.m_l = coord.x;
423                 bounds.m_t = coord.y;
424
425                 coord.x = rect.right;
426                 coord.y = rect.bottom;
427                 ::ClientToScreen(m_hWnd, &coord);
428
429                 bounds.m_r = coord.x;
430                 bounds.m_b = coord.y;
431         }
432         else {
433                 bounds.m_b = 0;
434                 bounds.m_l = 0;
435                 bounds.m_r = 0;
436                 bounds.m_t = 0;
437         }
438 }
439
440
441 GHOST_TSuccess GHOST_WindowWin32::setClientWidth(GHOST_TUns32 width)
442 {
443         GHOST_TSuccess success;
444         GHOST_Rect cBnds, wBnds;
445         getClientBounds(cBnds);
446         if (cBnds.getWidth() != (GHOST_TInt32)width) {
447                 getWindowBounds(wBnds);
448                 int cx = wBnds.getWidth() + width - cBnds.getWidth();
449                 int cy = wBnds.getHeight();
450                 success =  ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
451                           GHOST_kSuccess : GHOST_kFailure;
452         }
453         else {
454                 success = GHOST_kSuccess;
455         }
456         return success;
457 }
458
459
460 GHOST_TSuccess GHOST_WindowWin32::setClientHeight(GHOST_TUns32 height)
461 {
462         GHOST_TSuccess success;
463         GHOST_Rect cBnds, wBnds;
464         getClientBounds(cBnds);
465         if (cBnds.getHeight() != (GHOST_TInt32)height) {
466                 getWindowBounds(wBnds);
467                 int cx = wBnds.getWidth();
468                 int cy = wBnds.getHeight() + height - cBnds.getHeight();
469                 success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
470                           GHOST_kSuccess : GHOST_kFailure;
471         }
472         else {
473                 success = GHOST_kSuccess;
474         }
475         return success;
476 }
477
478
479 GHOST_TSuccess GHOST_WindowWin32::setClientSize(GHOST_TUns32 width, GHOST_TUns32 height)
480 {
481         GHOST_TSuccess success;
482         GHOST_Rect cBnds, wBnds;
483         getClientBounds(cBnds);
484         if ((cBnds.getWidth() != (GHOST_TInt32)width) || (cBnds.getHeight() != (GHOST_TInt32)height)) {
485                 getWindowBounds(wBnds);
486                 int cx = wBnds.getWidth() + width - cBnds.getWidth();
487                 int cy = wBnds.getHeight() + height - cBnds.getHeight();
488                 success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
489                           GHOST_kSuccess : GHOST_kFailure;
490         }
491         else {
492                 success = GHOST_kSuccess;
493         }
494         return success;
495 }
496
497
498 GHOST_TWindowState GHOST_WindowWin32::getState() const
499 {
500         GHOST_TWindowState state;
501
502         // XXX 27.04.2011
503         // we need to find a way to combine parented windows + resizing if we simply set the
504         // state as GHOST_kWindowStateEmbedded we will need to check for them somewhere else.
505         // It's also strange that in Windows is the only platform we need to make this separation.
506         if (m_parentWindowHwnd != 0) {
507                 state = GHOST_kWindowStateEmbedded;
508                 return state;
509         }
510
511         if (::IsIconic(m_hWnd)) {
512                 state = GHOST_kWindowStateMinimized;
513         }
514         else if (::IsZoomed(m_hWnd)) {
515                 LONG_PTR result = ::GetWindowLongPtr(m_hWnd, GWL_STYLE);
516                 if ((result & (WS_POPUP | WS_MAXIMIZE)) != (WS_POPUP | WS_MAXIMIZE))
517                         state = GHOST_kWindowStateMaximized;
518                 else
519                         state = GHOST_kWindowStateFullScreen;
520         }
521         else {
522                 state = GHOST_kWindowStateNormal;
523         }
524         return state;
525 }
526
527
528 void GHOST_WindowWin32::screenToClient(
529         GHOST_TInt32 inX, GHOST_TInt32 inY,
530         GHOST_TInt32 &outX, GHOST_TInt32 &outY) const
531 {
532         POINT point = {inX, inY};
533         ::ScreenToClient(m_hWnd, &point);
534         outX = point.x;
535         outY = point.y;
536 }
537
538
539 void GHOST_WindowWin32::clientToScreen(
540         GHOST_TInt32 inX, GHOST_TInt32 inY,
541         GHOST_TInt32 &outX, GHOST_TInt32 &outY) const
542 {
543         POINT point = {inX, inY};
544         ::ClientToScreen(m_hWnd, &point);
545         outX = point.x;
546         outY = point.y;
547 }
548
549
550 GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state)
551 {
552         GHOST_TWindowState curstate = getState();
553         WINDOWPLACEMENT wp;
554         wp.length = sizeof(WINDOWPLACEMENT);
555         ::GetWindowPlacement(m_hWnd, &wp);
556
557         if (state == GHOST_kWindowStateNormal)
558                 state = m_normal_state;
559
560         switch (state) {
561                 case GHOST_kWindowStateMinimized:
562                         wp.showCmd = SW_SHOWMINIMIZED;
563                         break;
564                 case GHOST_kWindowStateMaximized:
565                         wp.showCmd = SW_SHOWMAXIMIZED;
566                         ::SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
567                         break;
568                 case GHOST_kWindowStateFullScreen:
569                         if (curstate != state && curstate != GHOST_kWindowStateMinimized)
570                                 m_normal_state = curstate;
571                         wp.showCmd = SW_SHOWMAXIMIZED;
572                         wp.ptMaxPosition.x = 0;
573                         wp.ptMaxPosition.y = 0;
574                         ::SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_POPUP | WS_MAXIMIZE);
575                         break;
576                 case GHOST_kWindowStateEmbedded:
577                         ::SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_CHILD);
578                         break;
579                 case GHOST_kWindowStateNormal:
580                 default:
581                         wp.showCmd = SW_SHOWNORMAL;
582                         ::SetWindowLongPtr(m_hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
583                         break;
584         }
585         /* Clears window cache for SetWindowLongPtr */
586         ::SetWindowPos(m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
587
588         return ::SetWindowPlacement(m_hWnd, &wp) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
589 }
590
591
592 GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
593 {
594         HWND hWndInsertAfter, hWndToRaise;
595
596         if (order == GHOST_kWindowOrderBottom) {
597                 hWndInsertAfter = HWND_BOTTOM;
598                 hWndToRaise = ::GetWindow(m_hWnd, GW_HWNDNEXT); /* the window to raise */
599         }
600         else {
601                 hWndInsertAfter = HWND_TOP;
602                 hWndToRaise = NULL;
603         }
604
605         if (::SetWindowPos(m_hWnd, hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) == FALSE) {
606                 return GHOST_kFailure;
607         }
608
609         if (hWndToRaise && ::SetWindowPos(hWndToRaise, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) == FALSE) {
610                 return GHOST_kFailure;
611         }
612         return GHOST_kSuccess;
613 }
614
615
616 GHOST_TSuccess GHOST_WindowWin32::invalidate()
617 {
618         GHOST_TSuccess success;
619         if (m_hWnd) {
620                 success = ::InvalidateRect(m_hWnd, 0, FALSE) != 0 ? GHOST_kSuccess : GHOST_kFailure;
621         }
622         else {
623                 success = GHOST_kFailure;
624         }
625         return success;
626 }
627
628
629 GHOST_Context *GHOST_WindowWin32::newDrawingContext(GHOST_TDrawingContextType type)
630 {
631         if (type == GHOST_kDrawingContextTypeOpenGL) {
632                 GHOST_Context *context;
633
634 #if defined(WITH_GL_PROFILE_CORE)
635                 /* - AMD and Intel give us exactly this version
636                  * - NVIDIA gives at least this version <-- desired behavior
637                  * So we ask for 4.5, 4.4 ... 3.3 in descending order to get the best version on the user's system. */
638                 for (int minor = 5; minor >= 0; --minor) {
639                         context = new GHOST_ContextWGL(
640                             m_wantStereoVisual,
641                             m_wantAlphaBackground,
642                             m_wantNumOfAASamples,
643                             m_hWnd,
644                             m_hDC,
645                             WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
646                             4, minor,
647                             (m_debug_context ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
648                             GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
649
650                         if (context->initializeDrawingContext()) {
651                                 return context;
652                         }
653                         else {
654                                 delete context;
655                         }
656                 }
657                 context = new GHOST_ContextWGL(
658                     m_wantStereoVisual,
659                     m_wantAlphaBackground,
660                     m_wantNumOfAASamples,
661                     m_hWnd,
662                     m_hDC,
663                     WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
664                     3, 3,
665                     (m_debug_context ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
666                     GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
667
668                 if (context->initializeDrawingContext()) {
669                         return context;
670                 }
671                 else {
672                         MessageBox(
673                                 m_hWnd,
674                                 "Blender requires a graphics driver with at least OpenGL 3.3 support.\n\n"
675                                 "The program will now close.",
676                                 "Blender - Unsupported Graphics Driver!",
677                                 MB_OK | MB_ICONERROR);
678                         delete context;
679                         exit(0);
680                 }
681
682 #elif defined(WITH_GL_PROFILE_COMPAT)
683                 // ask for 2.1 context, driver gives any GL version >= 2.1 (hopefully the latest compatibility profile)
684                 // 2.1 ignores the profile bit & is incompatible with core profile
685                 context = new GHOST_ContextWGL(
686                         m_wantStereoVisual,
687                         m_wantAlphaBackground,
688                         m_wantNumOfAASamples,
689                         m_hWnd,
690                         m_hDC,
691                         0, // no profile bit
692                         2, 1,
693                         (m_debug_context ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
694                         GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
695
696                 if (context->initializeDrawingContext()) {
697                         return context;
698                 }
699                 else {
700                         delete context;
701                 }
702 #else
703 #  error // must specify either core or compat at build time
704 #endif
705         }
706
707         return NULL;
708 }
709
710 void GHOST_WindowWin32::lostMouseCapture()
711 {
712         if (m_hasMouseCaptured) {
713                 m_hasGrabMouse = false;
714                 m_nPressedButtons = 0;
715                 m_hasMouseCaptured = false;
716         }
717 }
718
719 void GHOST_WindowWin32::registerMouseClickEvent(int press)
720 {
721
722         switch (press) {
723                 case 0: m_nPressedButtons++;    break;
724                 case 1: if (m_nPressedButtons) m_nPressedButtons--; break;
725                 case 2: m_hasGrabMouse = true;    break;
726                 case 3: m_hasGrabMouse = false;   break;
727         }
728
729         if (!m_nPressedButtons && !m_hasGrabMouse && m_hasMouseCaptured) {
730                 ::ReleaseCapture();
731                 m_hasMouseCaptured = false;
732         }
733         else if ((m_nPressedButtons || m_hasGrabMouse) && !m_hasMouseCaptured) {
734                 ::SetCapture(m_hWnd);
735                 m_hasMouseCaptured = true;
736
737         }
738 }
739
740
741 void GHOST_WindowWin32::loadCursor(bool visible, GHOST_TStandardCursor cursor) const
742 {
743         if (!visible) {
744                 while (::ShowCursor(FALSE) >= 0) ;
745         }
746         else {
747                 while (::ShowCursor(TRUE) < 0) ;
748         }
749
750         if (cursor == GHOST_kStandardCursorCustom && m_customCursor) {
751                 ::SetCursor(m_customCursor);
752         }
753         else {
754                 // Convert GHOST cursor to Windows OEM cursor
755                 bool success = true;
756                 LPCSTR id;
757                 switch (cursor) {
758                         case GHOST_kStandardCursorDefault:              id = IDC_ARROW;     break;
759                         case GHOST_kStandardCursorRightArrow:           id = IDC_ARROW;     break;
760                         case GHOST_kStandardCursorLeftArrow:            id = IDC_ARROW;     break;
761                         case GHOST_kStandardCursorInfo:                 id = IDC_SIZEALL;   break;  // Four-pointed arrow pointing north, south, east, and west
762                         case GHOST_kStandardCursorDestroy:              id = IDC_NO;        break;  // Slashed circle
763                         case GHOST_kStandardCursorHelp:                 id = IDC_HELP;      break;  // Arrow and question mark
764                         case GHOST_kStandardCursorCycle:                id = IDC_NO;        break;  // Slashed circle
765                         case GHOST_kStandardCursorSpray:                id = IDC_SIZEALL;   break;  // Four-pointed arrow pointing north, south, east, and west
766                         case GHOST_kStandardCursorWait:                 id = IDC_WAIT;      break;  // Hourglass
767                         case GHOST_kStandardCursorText:                 id = IDC_IBEAM;     break;  // I-beam
768                         case GHOST_kStandardCursorCrosshair:            id = IDC_CROSS;     break;  // Crosshair
769                         case GHOST_kStandardCursorUpDown:               id = IDC_SIZENS;    break;  // Double-pointed arrow pointing north and south
770                         case GHOST_kStandardCursorLeftRight:            id = IDC_SIZEWE;    break;  // Double-pointed arrow pointing west and east
771                         case GHOST_kStandardCursorTopSide:              id = IDC_UPARROW;   break;  // Vertical arrow
772                         case GHOST_kStandardCursorBottomSide:           id = IDC_SIZENS;    break;
773                         case GHOST_kStandardCursorLeftSide:             id = IDC_SIZEWE;    break;
774                         case GHOST_kStandardCursorTopLeftCorner:        id = IDC_SIZENWSE;  break;
775                         case GHOST_kStandardCursorTopRightCorner:       id = IDC_SIZENESW;  break;
776                         case GHOST_kStandardCursorBottomRightCorner:    id = IDC_SIZENWSE;  break;
777                         case GHOST_kStandardCursorBottomLeftCorner:     id = IDC_SIZENESW;  break;
778                         case GHOST_kStandardCursorPencil:               id = IDC_ARROW;     break;
779                         case GHOST_kStandardCursorCopy:                 id = IDC_ARROW;     break;
780                         default:
781                                 success = false;
782                 }
783
784                 if (success) {
785                         ::SetCursor(::LoadCursor(0, id));
786                 }
787         }
788 }
789
790 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorVisibility(bool visible)
791 {
792         if (::GetForegroundWindow() == m_hWnd) {
793                 loadCursor(visible, getCursorShape());
794         }
795
796         return GHOST_kSuccess;
797 }
798
799 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
800 {
801         if (mode != GHOST_kGrabDisable) {
802                 if (mode != GHOST_kGrabNormal) {
803                         m_system->getCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
804                         setCursorGrabAccum(0, 0);
805
806                         if (mode == GHOST_kGrabHide)
807                                 setWindowCursorVisibility(false);
808                 }
809                 registerMouseClickEvent(2);
810         }
811         else {
812                 if (m_cursorGrab == GHOST_kGrabHide) {
813                         m_system->setCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
814                         setWindowCursorVisibility(true);
815                 }
816                 if (m_cursorGrab != GHOST_kGrabNormal) {
817                         /* use to generate a mouse move event, otherwise the last event
818                          * blender gets can be outside the screen causing menus not to show
819                          * properly unless the user moves the mouse */
820                         GHOST_TInt32 pos[2];
821                         m_system->getCursorPosition(pos[0], pos[1]);
822                         m_system->setCursorPosition(pos[0], pos[1]);
823                 }
824
825                 /* Almost works without but important otherwise the mouse GHOST location can be incorrect on exit */
826                 setCursorGrabAccum(0, 0);
827                 m_cursorGrabBounds.m_l = m_cursorGrabBounds.m_r = -1; /* disable */
828                 registerMouseClickEvent(3);
829         }
830
831         return GHOST_kSuccess;
832 }
833
834 GHOST_TSuccess GHOST_WindowWin32::setWindowCursorShape(GHOST_TStandardCursor cursorShape)
835 {
836         if (m_customCursor) {
837                 DestroyCursor(m_customCursor);
838                 m_customCursor = NULL;
839         }
840
841         if (::GetForegroundWindow() == m_hWnd) {
842                 loadCursor(getCursorVisibility(), cursorShape);
843         }
844
845         return GHOST_kSuccess;
846 }
847
848 void GHOST_WindowWin32::processWin32TabletActivateEvent(WORD state)
849 {
850         if (!m_tablet) {
851                 return;
852         }
853
854         GHOST_WIN32_WTEnable fpWTEnable = (GHOST_WIN32_WTEnable) ::GetProcAddress(m_wintab, "WTEnable");
855         GHOST_WIN32_WTOverlap fpWTOverlap = (GHOST_WIN32_WTOverlap) ::GetProcAddress(m_wintab, "WTOverlap");
856
857         if (fpWTEnable) {
858                 fpWTEnable(m_tablet, state);
859                 if (fpWTOverlap && state) {
860                         fpWTOverlap(m_tablet, TRUE);
861                 }
862         }
863 }
864
865 void GHOST_WindowWin32::processWin32TabletInitEvent()
866 {
867         if (m_wintab && m_tabletData) {
868                 GHOST_WIN32_WTInfo fpWTInfo = (GHOST_WIN32_WTInfo) ::GetProcAddress(m_wintab, "WTInfoA");
869
870                 // let's see if we can initialize tablet here
871                 /* check if WinTab available. */
872                 if (fpWTInfo) {
873                         AXIS Pressure, Orientation[3]; /* The maximum tablet size */
874
875                         BOOL pressureSupport = fpWTInfo(WTI_DEVICES, DVC_NPRESSURE, &Pressure);
876                         if (pressureSupport)
877                                 m_maxPressure = Pressure.axMax;
878                         else
879                                 m_maxPressure = 0;
880
881                         BOOL tiltSupport = fpWTInfo(WTI_DEVICES, DVC_ORIENTATION, &Orientation);
882                         if (tiltSupport) {
883                                 /* does the tablet support azimuth ([0]) and altitude ([1]) */
884                                 if (Orientation[0].axResolution && Orientation[1].axResolution) {
885                                         m_maxAzimuth = Orientation[0].axMax;
886                                         m_maxAltitude = Orientation[1].axMax;
887                                 }
888                                 else {  /* no so dont do tilt stuff */
889                                         m_maxAzimuth = m_maxAltitude = 0;
890                                 }
891                         }
892
893                         m_tabletData->Active = GHOST_kTabletModeNone;
894                 }
895         }
896 }
897
898 void GHOST_WindowWin32::processWin32TabletEvent(WPARAM wParam, LPARAM lParam)
899 {
900         PACKET pkt;
901         if (m_wintab) {
902                 GHOST_WIN32_WTPacket fpWTPacket = (GHOST_WIN32_WTPacket) ::GetProcAddress(m_wintab, "WTPacket");
903                 if (fpWTPacket) {
904                         if (fpWTPacket((HCTX)lParam, wParam, &pkt)) {
905                                 if (m_tabletData) {
906                                         switch (pkt.pkCursor % 3) { /* % 3 for multiple devices ("DualTrack") */
907                                                 case 0:
908                                                         m_tabletData->Active = GHOST_kTabletModeNone; /* puck - not yet supported */
909                                                         break;
910                                                 case 1:
911                                                         m_tabletData->Active = GHOST_kTabletModeStylus; /* stylus */
912                                                         break;
913                                                 case 2:
914                                                         m_tabletData->Active = GHOST_kTabletModeEraser; /* eraser */
915                                                         break;
916                                         }
917                                         if (m_maxPressure > 0) {
918                                                 m_tabletData->Pressure = (float)pkt.pkNormalPressure / (float)m_maxPressure;
919                                         }
920                                         else {
921                                                 m_tabletData->Pressure = 1.0f;
922                                         }
923
924                                         if ((m_maxAzimuth > 0) && (m_maxAltitude > 0)) {
925                                                 ORIENTATION ort = pkt.pkOrientation;
926                                                 float vecLen;
927                                                 float altRad, azmRad;   /* in radians */
928
929                                                 /*
930                                                  * from the wintab spec:
931                                                  * orAzimuth    Specifies the clockwise rotation of the
932                                                  * cursor about the z axis through a full circular range.
933                                                  *
934                                                  * orAltitude   Specifies the angle with the x-y plane
935                                                  * through a signed, semicircular range.  Positive values
936                                                  * specify an angle upward toward the positive z axis;
937                                                  * negative values specify an angle downward toward the negative z axis.
938                                                  *
939                                                  * wintab.h defines .orAltitude as a UINT but documents .orAltitude
940                                                  * as positive for upward angles and negative for downward angles.
941                                                  * WACOM uses negative altitude values to show that the pen is inverted;
942                                                  * therefore we cast .orAltitude as an (int) and then use the absolute value.
943                                                  */
944
945                                                 /* convert raw fixed point data to radians */
946                                                 altRad = (float)((fabs((float)ort.orAltitude) / (float)m_maxAltitude) * M_PI / 2.0);
947                                                 azmRad = (float)(((float)ort.orAzimuth / (float)m_maxAzimuth) * M_PI * 2.0);
948
949                                                 /* find length of the stylus' projected vector on the XY plane */
950                                                 vecLen = cos(altRad);
951
952                                                 /* from there calculate X and Y components based on azimuth */
953                                                 m_tabletData->Xtilt = sin(azmRad) * vecLen;
954                                                 m_tabletData->Ytilt = (float)(sin(M_PI / 2.0 - azmRad) * vecLen);
955
956                                         }
957                                         else {
958                                                 m_tabletData->Xtilt = 0.0f;
959                                                 m_tabletData->Ytilt = 0.0f;
960                                         }
961                                 }
962                         }
963                 }
964         }
965 }
966
967 void GHOST_WindowWin32::bringTabletContextToFront()
968 {
969         if (m_wintab) {
970                 GHOST_WIN32_WTOverlap fpWTOverlap = (GHOST_WIN32_WTOverlap) ::GetProcAddress(m_wintab, "WTOverlap");
971                 if (fpWTOverlap) {
972                         fpWTOverlap(m_tablet, TRUE);
973                 }
974         }
975 }
976
977 GHOST_TUns16 GHOST_WindowWin32::getDPIHint()
978 {
979         if (!m_user32) {
980                 m_user32 = ::LoadLibrary("user32.dll");
981         }
982
983         if (m_user32) {
984                 GHOST_WIN32_GetDpiForWindow fpGetDpiForWindow = (GHOST_WIN32_GetDpiForWindow) ::GetProcAddress(m_user32, "GetDpiForWindow");
985
986                 if (fpGetDpiForWindow) {
987                         return fpGetDpiForWindow(this->m_hWnd);
988                 }
989         }
990
991         return USER_DEFAULT_SCREEN_DPI;
992 }
993
994 /** Reverse the bits in a GHOST_TUns8 */
995 static GHOST_TUns8 uns8ReverseBits(GHOST_TUns8 ch)
996 {
997         ch = ((ch >> 1) & 0x55) | ((ch << 1) & 0xAA);
998         ch = ((ch >> 2) & 0x33) | ((ch << 2) & 0xCC);
999         ch = ((ch >> 4) & 0x0F) | ((ch << 4) & 0xF0);
1000         return ch;
1001 }
1002
1003 #if 0  /* UNUSED */
1004 /** Reverse the bits in a GHOST_TUns16 */
1005 static GHOST_TUns16 uns16ReverseBits(GHOST_TUns16 shrt)
1006 {
1007         shrt = ((shrt >> 1) & 0x5555) | ((shrt << 1) & 0xAAAA);
1008         shrt = ((shrt >> 2) & 0x3333) | ((shrt << 2) & 0xCCCC);
1009         shrt = ((shrt >> 4) & 0x0F0F) | ((shrt << 4) & 0xF0F0);
1010         shrt = ((shrt >> 8) & 0x00FF) | ((shrt << 8) & 0xFF00);
1011         return shrt;
1012 }
1013 #endif
1014 GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(
1015         GHOST_TUns8 bitmap[16][2],
1016         GHOST_TUns8 mask[16][2],
1017         int hotX, int hotY)
1018 {
1019         return setWindowCustomCursorShape((GHOST_TUns8 *)bitmap, (GHOST_TUns8 *)mask,
1020                                           16, 16, hotX, hotY, 0, 1);
1021 }
1022
1023 GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(
1024         GHOST_TUns8 *bitmap,
1025         GHOST_TUns8 *mask, int sizeX, int sizeY, int hotX, int hotY,
1026         int fg_color, int bg_color)
1027 {
1028         GHOST_TUns32 andData[32];
1029         GHOST_TUns32 xorData[32];
1030         GHOST_TUns32 fullBitRow, fullMaskRow;
1031         int x, y, cols;
1032
1033         cols = sizeX / 8; /* Num of whole bytes per row (width of bm/mask) */
1034         if (sizeX % 8) cols++;
1035
1036         if (m_customCursor) {
1037                 DestroyCursor(m_customCursor);
1038                 m_customCursor = NULL;
1039         }
1040
1041         memset(&andData, 0xFF, sizeof(andData));
1042         memset(&xorData, 0, sizeof(xorData));
1043
1044         for (y = 0; y < sizeY; y++) {
1045                 fullBitRow = 0;
1046                 fullMaskRow = 0;
1047                 for (x = cols - 1; x >= 0; x--) {
1048                         fullBitRow <<= 8;
1049                         fullMaskRow <<= 8;
1050                         fullBitRow  |= uns8ReverseBits(bitmap[cols * y + x]);
1051                         fullMaskRow |= uns8ReverseBits(mask[cols * y + x]);
1052                 }
1053                 xorData[y] = fullBitRow & fullMaskRow;
1054                 andData[y] = ~fullMaskRow;
1055         }
1056
1057         m_customCursor = ::CreateCursor(::GetModuleHandle(0), hotX, hotY, 32, 32, andData, xorData);
1058         if (!m_customCursor) {
1059                 return GHOST_kFailure;
1060         }
1061
1062         if (::GetForegroundWindow() == m_hWnd) {
1063                 loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
1064         }
1065
1066         return GHOST_kSuccess;
1067 }
1068
1069
1070 GHOST_TSuccess GHOST_WindowWin32::setProgressBar(float progress)
1071 {
1072         /*SetProgressValue sets state to TBPF_NORMAL automaticly*/
1073         if (m_Bar && S_OK == m_Bar->SetProgressValue(m_hWnd, 10000 * progress, 10000))
1074                 return GHOST_kSuccess;
1075
1076         return GHOST_kFailure;
1077 }
1078
1079 GHOST_TSuccess GHOST_WindowWin32::endProgressBar()
1080 {
1081         if (m_Bar && S_OK == m_Bar->SetProgressState(m_hWnd, TBPF_NOPROGRESS))
1082                 return GHOST_kSuccess;
1083
1084         return GHOST_kFailure;
1085 }
1086
1087
1088 #ifdef WITH_INPUT_IME
1089 void GHOST_WindowWin32::beginIME(GHOST_TInt32 x, GHOST_TInt32 y, GHOST_TInt32 w, GHOST_TInt32 h, int completed)
1090 {
1091         m_imeInput.BeginIME(m_hWnd, GHOST_Rect(x, y - h, x, y), (bool)completed);
1092 }
1093
1094
1095 void GHOST_WindowWin32::endIME()
1096 {
1097         m_imeInput.EndIME(m_hWnd);
1098 }
1099 #endif /* WITH_INPUT_IME */