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