gfx/gui (win32): Fixed warning with latest MinGW-w64 headers
[sdk] / ecere / src / gui / drivers / Win32Interface.ec
1 namespace gui::drivers;
2
3 import "instance"
4
5 #define UNICODE
6
7 #if defined(__WIN32__)
8
9 #undef WINVER
10 #define WINVER 0x0500
11 #undef _WIN32_WINNT
12 #define _WIN32_WINNT 0x0502
13
14 #undef JOY_BUTTON1
15 #undef JOY_BUTTON2
16 #undef JOY_BUTTON3
17 #undef JOY_BUTTON4
18
19 #define WIN32_LEAN_AND_MEAN
20 #define Method _Method
21 #define byte _byte
22 #define int64 _int64
23 #define String _String
24 #define Mutex _Mutex
25 #define Platform _Platform
26 #include <windows.h>
27 #include <wincon.h>
28 #include <shellapi.h>
29
30
31 #if defined(ECERE_VANILLA)
32 #define ECERE_NOJOYSTICK
33 #endif
34
35 #ifndef ECERE_NODINPUT
36 #ifndef ECERE_NOJOYSTICK
37 #define DIRECTINPUT_VERSION 0x700
38 #include <dinput.h>
39 #else
40 #define DIRECTINPUT_VERSION 0x300
41 #endif
42
43 #endif
44
45 #include <mmsystem.h>
46
47 #include <imm.h>
48
49 #define VK_SEMI       0xBA
50 #define VK_EQUALS     0xBB
51 #define VK_COMMA      0xBC
52 #define VK_MINUS      0xBD
53 #define VK_PERIOD     0xBE
54 #define VK_SLASH      0xBF
55 #define VK_TILDE      0xC0
56 #define VK_LBRACKET   0xDB
57 #define VK_BACK_SLASH 0xDC
58 #define VK_RBRACKET   0xDD
59 #define VK_QUOTE      0xDE
60
61 #ifndef WM_MOUSEWHEEL
62 #define WM_MOUSEWHEEL 0x20A
63 #endif
64
65 #ifndef IDC_HAND
66 #define IDC_HAND (char *)0x7F89
67 #endif
68
69 #ifndef WS_EX_LAYERED
70
71 #define LWA_COLORKEY            0x00000001
72 #define LWA_ALPHA               0x00000002
73
74 #define WS_EX_LAYERED           0x00080000
75
76 WINUSERAPI
77 BOOL
78 WINAPI
79 SetLayeredWindowAttributes(
80     HWND hwnd,
81     COLORREF crKey,
82     BYTE bAlpha,
83     DWORD dwFlags);
84
85 #endif
86
87 #undef Method
88 #undef byte
89 #undef int64
90 #undef String
91 #undef Mutex
92 #undef Platform
93
94 import "Window"
95
96 #ifdef ECERE_VANILLA
97 #define ECERE_NODINPUT
98 #define ECERE_NOJOYSTICK
99 #define ECERE_NOBLENDING
100 #endif
101
102 static byte key2VK[256] =
103 {
104    0,VK_ESCAPE,'1','2','3','4','5','6','7','8','9','0',VK_MINUS,VK_EQUALS,VK_BACK,VK_TAB,
105    'Q','W','E','R','T','Y','U','I','O','P',VK_LBRACKET,VK_RBRACKET,VK_RETURN,VK_LCONTROL,'A','S',
106    'D','F','G','H','J','K','L',VK_SEMI,VK_QUOTE,VK_TILDE,VK_LSHIFT,VK_BACK_SLASH,'Z','X','C','V',
107    'B','N','M',VK_COMMA,VK_PERIOD,VK_DIVIDE,VK_RSHIFT,VK_MULTIPLY,VK_LMENU,VK_SPACE,VK_CAPITAL,VK_F1,VK_F2,VK_F3,VK_F4,VK_F5,
108    VK_F6,VK_F7,VK_F8,VK_F9,VK_F10,VK_NUMLOCK,VK_SCROLL,VK_NUMPAD7,VK_NUMPAD8,VK_NUMPAD9,VK_SUBTRACT,VK_NUMPAD4,VK_NUMPAD5,VK_NUMPAD6,VK_ADD,VK_NUMPAD1,
109    VK_NUMPAD2,VK_NUMPAD3,VK_NUMPAD0,VK_DELETE,0,0,0,VK_F11,VK_F12,0,0,0,0,0,0,0,
110    0,VK_RCONTROL,0,0,VK_RMENU,0,VK_HOME,VK_UP,VK_PRIOR,VK_LEFT,VK_RIGHT,VK_END,VK_DOWN,VK_NEXT,VK_INSERT,VK_DELETE
111 };
112 static const uint16 className[] = L"Ecere Application";
113 static HINSTANCE hInstance;
114
115 static WPARAM lastBits;
116 static LPARAM lastRes;
117
118 static DEVMODE devMode;
119 #ifndef ECERE_NODINPUT
120 static HWND acquiredWindow = null;
121 #endif
122 static HCURSOR systemCursors[SystemCursor];
123 static bool fullScreenMode;
124 static int desktopX = 0, desktopY = 0, desktopW = 0, desktopH = 0;
125 static DWORD hiResTimer;
126 // static HWND topWindow;
127
128 static HWND startBar;
129
130 #ifndef ECERE_NODINPUT
131 #define NUMJOY    4
132 static HMODULE dInputDll = null;
133 static BOOL * (WINAPI * directInputCreate)(HINSTANCE, DWORD, IDirectInput **, void *);
134 static IDirectInput * dInput = null;
135 static IDirectInputDevice * directMouse = null;
136 #ifndef ECERE_NOJOYSTICK
137 static int numJoysticks = 0;
138 static IDirectInputDevice2 * directJoysticks[NUMJOY] = {null,null,null,null};
139 #endif
140 #endif
141
142 default:
143 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
144 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp;
145 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown;
146 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
147 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove;
148 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
149 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
150 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
151 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
152 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
153 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
154 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
155 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
156 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
157
158 private:
159
160 static Box lastMonitorAreas[32];
161 static Box monitorAreas[32];
162 static int monitor;
163
164 static bool EnumerateMonitors(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
165 {
166    MONITORINFO info = { 0 };
167    info.cbSize = sizeof(MONITORINFO);
168    GetMonitorInfo(hMonitor, &info);
169    monitorAreas[monitor] = { info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom };
170    monitor++;
171    return monitor < 32;
172 }
173
174 static bool externalDisplayChange;
175
176 static int taskBarState;
177 static WINDOWPLACEMENT taskBarPlacement;
178 static bool activateApp;
179
180 static SystemCursor lastCursor = (SystemCursor)-1;
181
182 static void SmartShowWindow(HWND windowHandle, WindowState state, bool doActivate)
183 {
184    int showCmd;
185    if(state == maximized)
186       showCmd = doActivate ? SW_SHOWMAXIMIZED : SW_MAXIMIZE;
187    else if(state == minimized)
188       showCmd = SW_MINIMIZE;
189    else
190       showCmd = doActivate ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE;
191    ShowWindow(windowHandle, showCmd);
192 }
193
194 void AeroSnapPosition(Window window, int x, int y, int w, int h)
195 {
196    int oldX = window.absPosition.x;
197
198    // To prevent having a window < minClientSize with Aero Snap, because we don't receive a WM_SIZING!
199    // The sensible implementation of this is in WM_SIZING
200    {
201       int gw = w, gh = h;
202       MinMaxValue ew, eh;
203       window.GetDecorationsSize(&ew, &eh);
204
205       gw -= ew;
206       gh -= eh;
207
208       gw = Max(gw, 1);
209       gh = Max(gh, 1);
210
211       gw = Max(gw, window.minSize.w);
212       gh = Max(gh, window.minSize.h);
213       gw = Min(gw, window.maxSize.w);
214       gh = Min(gh, window.maxSize.h);
215
216       if(!window.OnResizing(&gw, &gh))
217       {
218          gw = window.clientSize.w;
219          gh = window.clientSize.h;
220       }
221
222       gw = Max(gw, window.skinMinSize.w);
223       gh = Max(gh, window.skinMinSize.h);
224
225       gw += ew;
226       gh += eh;
227
228       if(w != gw || h != gh)
229       {
230          bool move = false;
231          // Adjust x position if we resized from top or bottom left corner
232          if(x != oldX)
233          {
234             x += w - gw;
235             move = true;
236          }
237          w = gw;
238          h = gh;
239          guiApp.interfaceDriver.PositionRootWindow(window, x, y, w, h, move, true);
240       }
241    }
242    window.ExternalPosition(x, y, w, h);
243 }
244
245 class Win32Interface : Interface
246 {
247    class_property(name) = "Win32";
248
249    void ::RepositionDesktop(bool updateChildren)
250    {
251       int c;
252       static double lastTime = 0, time;
253       int x = 0, y = 0;
254       int w = 0, h = 0;
255       //static Size lastScreen;
256       //static Point lastScreenPos;
257       static double lastAutoHideCheck = 0;
258       int newTaskBarState = taskBarState;
259       HMONITOR primaryMonitor = 0;
260
261       time = GetTime();
262       if(time - lastTime < 0.1) return;
263       lastTime = time;
264
265       // Every sec, check for the auto hide property
266       if(time - lastAutoHideCheck > 1)
267       {
268          APPBARDATA appBarData = { 0 };
269          newTaskBarState = (int)SHAppBarMessage(ABM_GETSTATE, &appBarData);
270          lastAutoHideCheck = time;
271       }
272
273       monitor = 0;
274       EnumDisplayMonitors(null, null, EnumerateMonitors, 0);
275       for(c = 0; c<monitor; c++)
276       {
277          if(monitorAreas[c].left != lastMonitorAreas[c].left ||
278             monitorAreas[c].top != lastMonitorAreas[c].top ||
279             monitorAreas[c].right != lastMonitorAreas[c].right ||
280             monitorAreas[c].bottom != lastMonitorAreas[c].bottom)
281          {
282             break;
283          }
284       }
285
286       memcpy(lastMonitorAreas, monitorAreas, sizeof(monitorAreas));
287
288       guiApp.virtualScreen =
289       {
290          GetSystemMetrics(SM_CXVIRTUALSCREEN),
291          GetSystemMetrics(SM_CYVIRTUALSCREEN)
292       };
293       guiApp.virtualScreenPos =
294       {
295          x = GetSystemMetrics(SM_XVIRTUALSCREEN),
296          y = GetSystemMetrics(SM_YVIRTUALSCREEN)
297       };
298
299       {
300          HMONITOR monitor = MonitorFromWindow(NULL, MONITOR_DEFAULTTOPRIMARY);
301          if(monitor)
302          {
303             MONITORINFO info = { 0 };
304             info.cbSize = sizeof(MONITORINFO);
305             primaryMonitor = monitor;
306             GetMonitorInfo(monitor, &info);
307             x = info.rcMonitor.left;
308             y = info.rcMonitor.top;
309             w = info.rcMonitor.right - info.rcWork.left;
310             h = info.rcMonitor.bottom - info.rcWork.top;
311          }
312       }
313
314      {
315          WINDOWPLACEMENT placement = { 0 };
316          placement.length = sizeof(WINDOWPLACEMENT);
317
318          if(!GetWindowPlacement(startBar, &placement))
319          {
320             startBar = FindWindowA("Shell_TrayWnd", null);
321             GetWindowPlacement(startBar, &placement);
322          }
323          {
324             HMONITOR taskBarMonitor = MonitorFromWindow(startBar, MONITOR_DEFAULTTONEAREST);
325             if(primaryMonitor == taskBarMonitor)
326             {
327                if(placement.rcNormalPosition.top <= 0 && placement.rcNormalPosition.bottom >= h - 1)
328                {
329                   if(placement.rcNormalPosition.left <= 0)
330                   {
331                      x = (taskBarState & ABS_AUTOHIDE) ? 1 : placement.rcNormalPosition.right;
332                      w -= x;
333                   }
334                   else
335                      w = (taskBarState & ABS_AUTOHIDE) ? (w - 1) : Min(placement.rcNormalPosition.left, w);
336                }
337                else if(placement.rcNormalPosition.left <= 0 && placement.rcNormalPosition.right >= w - 1)
338                {
339                   if(placement.rcNormalPosition.top <= 0)
340                   {
341                      y = (taskBarState & ABS_AUTOHIDE) ? 1 : placement.rcNormalPosition.bottom;
342                      h -= y;
343                   }
344                   else
345                      h = (taskBarState & ABS_AUTOHIDE) ? (h - 1) : Min(placement.rcNormalPosition.top, h);
346                }
347             }
348          }
349
350         if(c < monitor ||
351          placement.rcNormalPosition.left != taskBarPlacement.rcNormalPosition.left ||
352          placement.rcNormalPosition.top != taskBarPlacement.rcNormalPosition.top ||
353          placement.rcNormalPosition.right != taskBarPlacement.rcNormalPosition.right ||
354          placement.rcNormalPosition.bottom != taskBarPlacement.rcNormalPosition.bottom  ||
355          newTaskBarState != taskBarState)
356          {
357             taskBarState = newTaskBarState;
358             guiApp.desktop.size.w = 0;
359             desktopX = x;
360             desktopY = y;
361             desktopW = w;
362             desktopH = h;
363             taskBarPlacement = placement;
364             guiApp.SetDesktopPosition(x, y, w, h, updateChildren);
365          }
366
367          //lastScreen = guiApp.virtualScreen;
368          //lastScreenPos = guiApp.virtualScreenPos;
369       }
370    }
371
372    /****************************************************************************
373       /// PRIVATE UTILITY FUNCTIONS /////////////
374    ****************************************************************************/
375    // --- Keyboard Input ---
376    bool ::ProcessKeyMessage(Window window, DWORD msg, WPARAM wParam, LPARAM lParam, unichar ch)
377    {
378       bool result = true;
379       Key code = 0;
380       Key key;
381       // UNICODE FIX
382       bool frenchShift = (ch < 0x10000) ? (((VkKeyScan((uint16)ch) >> 8) & 6) == 6) : false;
383
384       if(msg == WM_CHAR || msg == WM_DEADCHAR)
385       {
386          wParam = 0;
387          lParam = 0;
388       }
389       if(msg == WM_MOUSEWHEEL)
390          code = (((short) HIWORD(wParam)) < 0) ? wheelDown : wheelUp;
391       else
392       {
393          key = (byte)((lParam & 0xFF0000)>>16);
394          if(lParam & 0x1000000)
395          {
396             key = Interface::GetExtendedKey(key);
397             if(!key)
398             {
399                if(wParam == 0xb3)
400                   key = KeyCode::play;
401             }
402          }
403          code = key;
404       }
405
406       if(msg == WM_MOUSEWHEEL)
407       {
408          if(::GetAsyncKeyState(VK_SHIFT) & 0x80000)
409             code.shift = true;
410          if(::GetAsyncKeyState(VK_CONTROL) & 0x80000)
411             code.ctrl = true;
412          if(::GetAsyncKeyState(VK_MENU) & 0x80000)
413             code.alt = true;
414
415          result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, code, 0);
416       }
417       else
418       {
419          if(key != leftShift && key != rightShift && ::GetKeyState(VK_SHIFT) & 0x80000)
420             code.shift = true;
421          if(key != leftControl && key != rightControl && ::GetKeyState(VK_CONTROL) & 0x80000 && !frenchShift)
422             code.ctrl = true;
423          if(key != leftAlt && key != rightAlt && ::GetKeyState(VK_MENU) & 0x80000 && !frenchShift)
424             code.alt = true;
425          /*
426          byte ch = Interface::TranslateKeykey, code.shift);
427          if(::GetKeyState(VK_CAPITAL))
428             ch = toupper(ch);
429          */
430
431          if(msg == WM_KEYUP || msg == WM_SYSKEYUP)
432          {
433             result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp, code, ch);
434          }
435          else
436          {
437             if(!(lParam & 0x40000000))
438             {
439                /*
440                {
441                   char string[256];
442                   Class * keyClass = eSystem_FindClass(__ecereModule, "Key");
443                   code.OnGetString(string, null, null);
444                   eSystem_Logf("%s\n", string);
445                }
446                */
447
448                result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown, code, ch);
449             }
450             else if(key<128)
451                result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, code,ch);
452          }
453       }
454
455       return result;
456    }
457
458    // --- Window procedure ---
459    DWORD CALLBACK ::ApplicationWindow(HWND windowHandle, UINT msg, WPARAM wParam, LPARAM lParam)
460    {
461 #ifdef _WIN64
462       Window window = (Window)GetWindowLongPtr(windowHandle, GWLP_USERDATA);
463 #else
464       Window window = (Window)GetWindowLong(windowHandle, GWL_USERDATA);
465 #endif
466       static Point lastPos;
467       if(window)
468       {
469          int x = 0,y = 0;
470          unichar ch = 0;
471          switch(msg)
472          {
473             case WM_QUERYNEWPALETTE:
474             case WM_PALETTECHANGED:
475                if(window.display)
476                   window.display.RestorePalette();
477                UpdateWindow(windowHandle);
478                break;
479             case WM_NCACTIVATE:
480             {
481                if(!fullScreenMode && !guiApp.IsModeSwitching())
482                {
483                   if(wParam)
484                   {
485                      Window modalRoot = window.FindModal();
486
487                      HWND modalWindow = modalRoot ? modalRoot.windowHandle : null;
488
489                      FLASHWINFO flashInfo = { 0 };
490                      flashInfo.cbSize = sizeof(FLASHWINFO);
491                      flashInfo.hwnd = window.windowHandle;
492                      flashInfo.uCount = 0;
493                      flashInfo.dwFlags = FLASHW_STOP;
494                      FlashWindowEx((void *)&flashInfo);
495
496                      if(modalWindow && modalWindow != windowHandle)
497                         modalRoot.ExternalActivate(true, true, window, null);
498                      else
499                         window.ExternalActivate(true, true, window, null);
500                   }
501                   else
502                   {
503                      HWND foreground;
504                      DWORD id;
505                      void * windowLong;
506                      foreground = GetForegroundWindow();
507                      if(foreground == windowHandle && lParam)
508                         foreground = (HWND)lParam;
509
510                      GetWindowThreadProcessId(foreground, &id);
511
512 #ifdef _WIN64
513                      windowLong = (void*)GetWindowLongPtr(foreground, GWLP_WNDPROC);
514 #else
515                      windowLong = (void*)GetWindowLong(foreground, GWL_WNDPROC);
516 #endif
517 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D)
518                      // The != ApplicationWindow check is for not recognizing the Console window as an Ecere Window
519                      // That check causes a problem with the OpenGL driver which seems to popup a window of a different class
520                      if(window.displaySystem && window.displaySystem.driver == class(OpenGLDisplayDriver))
521                         windowLong = (void *)ApplicationWindow;
522 #endif
523                      if(id != GetCurrentProcessId() || windowLong != (void *)ApplicationWindow)
524                         window.ExternalActivate(false, true, window, null);
525                      // DefWindowProc for WM_NCACTIVATE draws the decorations, make sure it's drawn in the right state
526                      return (uint)DefWindowProc(windowHandle, msg, window.active, lParam);
527                   }
528                }
529                if(activateApp)
530                {
531                   for(window = guiApp.desktop.firstChild; window; window = window.next)
532                      SetWindowPos(window.windowHandle, window.style.stayOnTop ? HWND_TOPMOST : HWND_TOP, 0,0,0,0,
533                         SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOSIZE); //|SWP_NOREDRAW);
534                   activateApp = false;
535                }
536
537                return (uint)DefWindowProc(windowHandle, msg, window ? window.active : wParam, lParam);
538             }
539             case WM_ACTIVATEAPP:
540                if(!guiApp.IsModeSwitching())
541                {
542                   if(fullScreenMode)
543                   {
544                      HDC hdc = GetDC(windowHandle);
545                      if(wParam != TRUE)
546                      {
547                         guiApp.SetAppFocus(false);
548                         ShowWindow(windowHandle, SW_MINIMIZE);
549                         ChangeDisplaySettings(null,0);
550                         SetSystemPaletteUse(hdc, SYSPAL_STATIC);
551                      }
552                      else
553                      {
554                         ChangeDisplaySettings(&devMode, CDS_FULLSCREEN);
555                         SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC);
556                         if(window.display)
557                            window.display.RestorePalette();
558                         ShowWindow(windowHandle, SW_SHOWNORMAL);
559                         guiApp.SetAppFocus(true);
560                         if(window.display)
561                            window.display.Resize(window.clientSize.w, window.clientSize.h);
562                         window.Update(null);
563                      }
564                      ReleaseDC(windowHandle, hdc);
565                   }
566                   else
567                   {
568                      //Window window;
569
570                      if(wParam && !guiApp.desktop.active /*&& lParam != GetCurrentThreadID()*/)
571                      {
572                         activateApp = true;
573                         /*
574                         for(window = guiApp.desktop.firstChild; window; window = window.next)
575                            SetWindowPos(window.windowHandle, window.style.stayOnTop ? HWND_TOPMOST : HWND_TOP, 0,0,0,0,
576                               SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOSIZE); //|SWP_NOREDRAW);
577                         */
578                      }
579                      guiApp.SetAppFocus((bool)wParam);
580                   }
581                }
582                else
583                   guiApp.SetAppFocus((bool)wParam);
584                break;
585             case WM_PAINT:
586             {
587                if(!window.alphaBlend || window.display.pixelFormat != pixelFormat888)
588                {
589                   PAINTSTRUCT ps;
590
591 /*
592 #define ACCESS_ITEM(l, id) \
593       ((FastItem)(((id) == -1) ? null : (((byte *)((l).items)) + (id) * (l).itemSize)))
594 */
595
596 #define ACCESS_ITEM(l, id) \
597    id
598
599                   BoxItem item = window.dirtyArea.count ? (BoxItem)ACCESS_ITEM(window.dirtyArea, window.dirtyArea.first) : null;
600
601                   BeginPaint(windowHandle, &ps);
602
603                   // Prevent flickering if we're going to update anyways
604                   /*
605                   printf("   Paint message (%d, %d)-(%d, %d)\n",
606                      item ? item.box.left : 0,
607                      item ? item.box.top : 0,
608                      item ? item.box.right : 0,
609                      item ? item.box.bottom : 0);
610                   */
611                   // Causes redraw bug...
612                   if(!window.manageDisplay || !item ||
613                      item.box.left > 0 ||
614                      item.box.top > 0 ||
615                      item.box.right < window.size.w - 1 ||
616                      item.box.bottom < window.size.h - 1)
617                   {
618                      Box box { ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right-1, ps.rcPaint.bottom-1 };
619                      window.UpdateDirty(box);
620                   }
621                      // TODO: Fix precompiler with
622                      // window.UpdateDirty((Box *)&ps.rcPaint);
623                   EndPaint(windowHandle, &ps);
624                }
625                break;
626             }
627             case WM_DISPLAYCHANGE:
628             {
629                if(!guiApp.fullScreenMode && (lastBits != wParam || lastRes != lParam))
630                {
631                   RECT rect;
632                   HWND foregroundWindow = GetForegroundWindow();
633                   int w = LOWORD(lParam);
634                   int h = HIWORD(lParam);
635
636                   GetWindowRect(foregroundWindow, &rect);
637                   if(rect.right == w && rect.bottom == h)
638                      break;
639
640                   lastBits = wParam;
641                   lastRes = lParam;
642
643                   externalDisplayChange = true;
644                   if(guiApp.desktop.DisplayModeChanged())
645                   {
646                      char caption[2048];
647                      if(!window.style.hidden)
648                         SmartShowWindow(window.windowHandle, (window.nativeDecorations && window.state == maximized) ? maximized : normal, false);
649                      window.FigureCaption(caption);
650                      SetRootWindowCaption(window, caption);
651                   }
652                   externalDisplayChange = false;
653                }
654                break;
655             }
656             // Keyboard Messages
657             case WM_SYSKEYDOWN:
658             case WM_KEYDOWN:
659             case WM_SYSKEYUP:
660             case WM_KEYUP:
661             case WM_CHAR:
662             //case WM_DEADCHAR:
663             {
664                MSG charMsg;
665                DWORD min = 0, max = 0;
666
667                if(msg != WM_CHAR && window.composing)
668                   break;
669
670                switch(msg)
671                {
672                   case WM_SYSKEYDOWN: min = max = WM_SYSCHAR; break;
673                   case WM_KEYDOWN: min = max = WM_CHAR; break;
674                   case WM_SYSKEYUP: min = WM_SYSCHAR; max = WM_SYSDEADCHAR; break;
675                   case WM_KEYUP: min = WM_CHAR; max = WM_DEADCHAR; break;
676                }
677
678                // This is very annoying.
679                // PeekMessage somehow invokes this function directly... don't know why.
680                // Only crashes when running through debug mode in visual studio
681                incref window;
682                if(msg == WM_CHAR || msg == WM_DEADCHAR || PeekMessage(&charMsg, windowHandle, min, max, PM_REMOVE))
683                {
684                   ch = (msg == WM_CHAR || msg == WM_DEADCHAR) ? (unichar)wParam : (unichar)charMsg.wParam;
685                   // TOCHECK: What is this for again? Fixing some obscure activation status?
686                   // -- I believe this was somehow allowing 'unmaximizing', but was causing problems
687                   // as there was no way to prevent AltEnter from doing so (e.g. when it is used for a node property)
688                   // Worked around by fixing ProcessHotKeys to properly check for sysButtons in parent.parent when sys buttons
689                   // are placed inside a menu bar for a document
690                   /*
691                   if(msg == WM_SYSKEYDOWN && ch == 13)
692                   {
693                      ShowWindow(window.windowHandle, window.state == maximized ? SW_MAXIMIZE : SW_SHOWNORMAL);
694                      // This last line been commented out for a long time:
695                      // window.ExternalActivate(true, true, window, null);
696                   }
697                   */
698                   if(msg == WM_SYSKEYUP || msg == WM_KEYUP)
699                   {
700                      if(!ProcessKeyMessage(window, WM_KEYDOWN, 0x40000000, 0, ch))
701                         break;
702                   }
703                }
704             }
705             case WM_MOUSEWHEEL:
706                ProcessKeyMessage(window, msg, wParam, lParam, ch);
707                if(window.composing && msg == WM_CHAR)
708                {
709                   COMPOSITIONFORM form;
710                   Window caretOwner = guiApp.caretOwner;
711                   if(caretOwner)
712                   {
713                      HIMC ctx = ImmGetContext(windowHandle);
714                      form.dwStyle = CFS_POINT;
715                      form.ptCurrentPos.x = caretOwner.caretPos.x - caretOwner.scroll.x + caretOwner.absPosition.x - window.absPosition.x + 4;
716                      form.ptCurrentPos.y = caretOwner.caretPos.y - caretOwner.scroll.x + caretOwner.absPosition.y - window.absPosition.y + 2;
717                      window.composing = true;
718                      ImmSetCompositionWindow(ctx, &form);
719                      ImmReleaseContext(windowHandle, ctx);
720                   }
721                }
722                if(msg != WM_MOUSEWHEEL)
723                   delete window;
724                break;
725
726             case WM_IME_STARTCOMPOSITION:
727             {
728                COMPOSITIONFORM form;
729                Window caretOwner = guiApp.caretOwner;
730                if(caretOwner)
731                {
732                   HIMC ctx = ImmGetContext(windowHandle);
733                   form.dwStyle = CFS_POINT;
734                   form.ptCurrentPos.x = caretOwner.caretPos.x - caretOwner.scroll.x + caretOwner.absPosition.x - window.absPosition.x + 4;
735                   form.ptCurrentPos.y = caretOwner.caretPos.y - caretOwner.scroll.y + caretOwner.absPosition.y - window.absPosition.y + 2;
736                   /*
737                   form.rcArea.left = window.caretPos.x;
738                   form.rcArea.top = 250;
739                   form.rcArea.right = 500;
740                   form.rcArea.bottom = 300;
741                   */
742                   window.composing = true;
743                   DefWindowProc(windowHandle, msg, wParam, lParam);
744                   ImmSetCompositionWindow(ctx, &form);
745                   ImmSetStatusWindowPos(ctx, &form.ptCurrentPos);
746                   {
747                      FontResource res = caretOwner.font;
748                      LOGFONT font = { 0 };
749                      HDC hdc = GetDC(0);
750                      int pixels = GetDeviceCaps(hdc, LOGPIXELSY);
751                      ReleaseDC(0, hdc);
752                      font.lfHeight = -(int)((float)res.size * pixels / 72 + 0.5);
753                      font.lfWeight = res.flags.bold ? FW_BOLD : FW_NORMAL;
754                      font.lfItalic = res.flags.italic ? TRUE : FALSE,
755                      font.lfUnderline = res.flags.underline ? TRUE : FALSE;
756                      font.lfCharSet = DEFAULT_CHARSET;
757                      font.lfOutPrecision = OUT_DEFAULT_PRECIS;
758                      font.lfClipPrecision = CLIP_DEFAULT_PRECIS;
759                      font.lfQuality = DEFAULT_QUALITY;
760                      font.lfPitchAndFamily = (byte)(DEFAULT_PITCH|FF_DONTCARE); // TODO: Fix compiler 0 | 0 to produce byte, not int
761                      UTF8toUTF16Buffer(res.faceName, font.lfFaceName, LF_FACESIZE);
762
763                      ImmSetCompositionFont(ctx, &font);
764                      ImmReleaseContext(windowHandle, ctx);
765                   }
766                   return 1;
767                }
768                break;
769             }
770             case WM_IME_ENDCOMPOSITION:
771                window.composing = false;
772                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
773             /*case WM_IME_COMPOSITION:
774                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
775             case WM_IME_REQUEST:
776                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
777             case WM_IME_NOTIFY:
778                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
779             case WM_IME_KEYDOWN:
780                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
781             case WM_IME_KEYUP:
782                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
783             case WM_IME_SELECT:
784                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
785             case WM_IME_SETCONTEXT:
786                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
787             case WM_IME_CONTROL:
788                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
789             case WM_IME_CHAR:
790                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
791             case WM_IME_COMPOSITIONFULL:
792                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
793             */
794             case WM_NCHITTEST:
795                if(window.nativeDecorations)
796                   return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
797                else
798                // return HTCAPTION;
799                   return HTCLIENT;
800
801             // Mouse Messages
802             case WM_LBUTTONUP:
803             case WM_RBUTTONUP:
804             case WM_MBUTTONUP:
805             case WM_LBUTTONDOWN:
806             case WM_LBUTTONDBLCLK:
807             case WM_RBUTTONDOWN:
808             case WM_RBUTTONDBLCLK:
809             case WM_MBUTTONDOWN:
810             case WM_MBUTTONDBLCLK:
811             case WM_MOUSEMOVE:
812                x = window.absPosition.x;
813                y = window.absPosition.y;
814             /*case WM_NCLBUTTONUP:
815             case WM_NCRBUTTONUP:
816             case WM_NCMBUTTONUP:
817             case WM_NCLBUTTONDOWN:
818             case WM_NCLBUTTONDBLCLK:
819             case WM_NCRBUTTONDOWN:
820             case WM_NCRBUTTONDBLCLK:
821             case WM_NCMBUTTONDOWN:
822             case WM_NCMBUTTONDBLCLK:*/
823             case WM_NCMOUSEMOVE:
824             {
825                Modifiers code = 0;
826                bool consequential = false;
827
828                x += (short)LOWORD(lParam);
829                y += (short)HIWORD(lParam);
830
831                if(window.nativeDecorations && msg != WM_NCMOUSEMOVE)
832                {
833                   x += window.clientStart.x;
834                   y += window.clientStart.y - (window.hasMenuBar ? skinMenuHeight : 0);
835                }
836
837                if(::GetKeyState(VK_SHIFT) & 0x80000)   code.shift = true;
838                if(::GetKeyState(VK_CONTROL) & 0x80000) code.ctrl = true;
839                if(::GetKeyState(VK_MENU) & 0x80000)    code.alt = true;
840                if(wParam & MK_LBUTTON) code.left = true;
841                if(wParam & MK_MBUTTON) code.middle = true;
842                if(wParam & MK_RBUTTON) code.right = true;
843
844                if(msg == WM_MOUSEMOVE)
845                {
846                   if(lastPos.x == x && lastPos.y == y)
847                      consequential = true;
848                   lastPos.x = x;
849                   lastPos.y = y;
850                }
851
852                incref window;
853                switch(msg)
854                {
855                   case WM_NCMOUSEMOVE:
856                   case WM_MOUSEMOVE:
857                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove, x,y,&code, consequential, false);
858                      break;
859                   //case WM_NCLBUTTONDBLCLK:
860                   case WM_LBUTTONDBLCLK:
861                      if(!window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick, x,y,&code, false, true))
862                         break;
863                   //case WM_NCLBUTTONDOWN:
864                   case WM_LBUTTONDOWN:
865                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown,x,y,&code, false,
866                                              /*(msg == WM_LBUTTONDBLCLK) ? false: */true);
867                      break;
868                   //case WM_NCLBUTTONUP:
869                   case WM_LBUTTONUP:      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp, x,y,&code, false, false);break;
870                   //case WM_NCMBUTTONDBLCLK:
871                   case WM_MBUTTONDBLCLK:
872                      if(!window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick, x,y,&code, false, false))
873                         break;
874                   //case WM_NCMBUTTONDOWN:
875                   case WM_MBUTTONDOWN:
876                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown, x,y,&code, false,
877                                              (msg == WM_LBUTTONDBLCLK) ? false: true);
878                      break;
879                   //case WM_NCMBUTTONUP:
880                   case WM_MBUTTONUP:
881                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp, x,y,&code, false, false);
882                      break;
883                   //case WM_NCRBUTTONDBLCLK:
884                   case WM_RBUTTONDBLCLK:
885                      if(!window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick, x,y,&code, false, true))
886                         break;
887                   //case WM_NCRBUTTONDOWN:
888                   case WM_RBUTTONDOWN:
889                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown, x,y,&code, false,
890                                              (msg == WM_LBUTTONDBLCLK) ? false: true);
891                      break;
892                   //case WM_NCRBUTTONUP:
893                   case WM_RBUTTONUP:
894                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp, x,y,&code, false, false);
895                      break;
896                }
897                delete window;
898                if(msg == WM_NCMOUSEMOVE)
899                   return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
900                break;
901             }
902             case WM_SETCURSOR:
903             {
904                if(window.nativeDecorations)
905                {
906                   if(DefWindowProc(windowHandle, msg, wParam, lParam))
907                      return 1;
908                }
909                // SetCursor(systemCursors[0]);
910                SetCursor((lastCursor == (SystemCursor)-1) ? null : systemCursors[lastCursor]);
911                return 0;
912             }
913             case WM_EXITMENULOOP:
914             case WM_EXITSIZEMOVE:
915                // We had some DirectInput stuff in here
916                break;
917             case WM_ENTERMENULOOP:
918             case WM_ENTERSIZEMOVE:
919                // We had some DirectInput stuff in here
920                break;
921             case WM_CLOSE:
922             {
923                window.Destroy(0);
924                return 0;
925             }
926             case WM_MOVE:
927             {
928                int x, y, w, h;
929                WINDOWPLACEMENT placement = { 0 };
930                RECT rcWindow;
931                placement.length = sizeof(WINDOWPLACEMENT);
932                GetWindowRect(windowHandle, &rcWindow);
933                GetWindowPlacement(windowHandle, &placement);
934
935                x = rcWindow.left - desktopX;
936                y = rcWindow.top  - desktopY;
937                w = rcWindow.right - rcWindow.left;
938                h = rcWindow.bottom - rcWindow.top;
939
940                AeroSnapPosition(window, x, y, w, h);
941                break;
942             }
943             /*case WM_MOVING:
944                break;*/
945             case WM_SIZING:
946             {
947                RECT * rect = (RECT *)lParam;
948                MinMaxValue ew, eh;
949                int w, h;
950
951                window.GetDecorationsSize(&ew, &eh);
952
953                w = rect->right - rect->left;
954                h = rect->bottom - rect->top;
955
956                w -= ew;
957                h -= eh;
958
959                w = Max(w, 1);
960                h = Max(h, 1);
961
962                w = Max(w, window.minSize.w);
963                h = Max(h, window.minSize.h);
964                w = Min(w, window.maxSize.w);
965                h = Min(h, window.maxSize.h);
966
967                if(!window.OnResizing(&w, &h))
968                {
969                   w = window.clientSize.w;
970                   h = window.clientSize.h;
971                }
972
973                w = Max(w, window.skinMinSize.w);
974                h = Max(h, window.skinMinSize.h);
975
976                w += ew;
977                h += eh;
978
979                if(wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT)
980                   rect->left = rect->right - w;
981                else
982                   rect->right = rect->left + w;
983
984                if(wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOP || wParam == WMSZ_TOPRIGHT)
985                   rect->top = rect->bottom - h;
986                else
987                   rect->bottom = rect->top + h;
988
989                return 1;
990             }
991             case WM_SIZE:
992             {
993                if(window.nativeDecorations)
994                {
995                   int x, y, w, h;
996                   RECT rcWindow;
997                   GetWindowRect(windowHandle, &rcWindow);
998
999                   if(wParam == SIZE_MAXIMIZED && window.state != maximized)
1000                      window.state = maximized;
1001                   else if(wParam == SIZE_MINIMIZED && window.state != minimized)
1002                      window.state = minimized;
1003                   else if(wParam == SIZE_RESTORED && window.state != normal && window.visible)
1004                      window.state = normal;
1005
1006                   x = rcWindow.left - desktopX;
1007                   y = rcWindow.top  - desktopY;
1008                   w = rcWindow.right - rcWindow.left;
1009                   h = rcWindow.bottom - rcWindow.top;
1010
1011                   AeroSnapPosition(window, x, y, w, h);
1012                   if(!guiApp.modeSwitching)
1013                      window.UpdateVisual(null);
1014                }
1015                else
1016                   return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
1017                break;
1018             }
1019             default:
1020                return (uint)DefWindowProc(windowHandle, msg, wParam, lParam);
1021          }
1022       }
1023       else
1024          return (uint)DefMDIChildProc(windowHandle, msg, wParam, lParam);
1025          // return DefWindowProc(windowHandle, msg, wParam, lParam);
1026       return 0;
1027    }
1028
1029    // --- DirectInput ---
1030
1031    #ifndef ECERE_NODINPUT
1032
1033    #ifndef ECERE_NOJOYSTICK
1034    bool CALLBACK ::JoystickCallback( const DIDEVICEINSTANCE* pdidInstance, void * context )
1035    {
1036       if(!dInput->lpVtbl->CreateDevice(dInput, &GUID_Joystick,
1037          (IDirectInputDevice **)&directJoysticks[numJoysticks], null ))
1038          numJoysticks++;
1039       return DIENUM_CONTINUE;
1040    }
1041
1042    bool CALLBACK ::JoystickAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi, void * context )
1043    {
1044       DIPROPRANGE diprg;
1045       IDirectInputDevice2 * curJoy = (IDirectInputDevice2 *)context;
1046
1047       diprg.diph.dwSize       = sizeof(DIPROPRANGE);
1048       diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
1049       diprg.diph.dwHow        = DIPH_BYOFFSET;
1050       diprg.diph.dwObj        = pdidoi->dwOfs;
1051       diprg.lMin              = -128;
1052       diprg.lMax              = 127;
1053       if(curJoy->lpVtbl->SetProperty(curJoy, DIPROP_RANGE, &diprg.diph))
1054          return DIENUM_STOP;
1055       return DIENUM_CONTINUE;
1056    }
1057    #endif
1058
1059    void ::TerminateDirectInput()
1060    {
1061       int j;
1062       if (directMouse)
1063       {
1064          directMouse->lpVtbl->Unacquire(directMouse);
1065          directMouse->lpVtbl->Release(directMouse);
1066          directMouse = null;
1067       }
1068    #ifndef ECERE_NOJOYSTICK
1069       for(j=0; j<numJoysticks; j++)
1070       {
1071          if (directJoysticks[j])
1072          {
1073             directJoysticks[j]->lpVtbl->Unacquire(directJoysticks[j]);
1074             directJoysticks[j]->lpVtbl->Release(directJoysticks[j]);
1075             directJoysticks[j] = null;
1076          }
1077       }
1078       numJoysticks = 0;
1079    #endif
1080       if(dInput)
1081       {
1082          dInput->lpVtbl->Release(dInput);
1083          dInput = null;
1084       }
1085
1086       directInputCreate = null;
1087
1088       if(dInputDll)
1089       {
1090          FreeLibrary(dInputDll);
1091          dInputDll = null;
1092       }
1093    }
1094
1095    bool ::InitDirectInput()
1096    {
1097       bool result = false;
1098
1099       dInputDll = LoadLibraryA("dinput.dll");
1100       if(dInputDll)
1101       {
1102          if((directInputCreate = (void *)GetProcAddress(dInputDll, "DirectInputCreateA")))
1103          {
1104             if(!directInputCreate( hInstance, DIRECTINPUT_VERSION, &dInput, null ))
1105             {
1106                int j;
1107
1108                // Mouse
1109                if(!dInput->lpVtbl->CreateDevice(dInput, &GUID_SysMouse, &directMouse, null ))
1110                   directMouse->lpVtbl->SetDataFormat(directMouse, &c_dfDIMouse );
1111
1112    #ifndef ECERE_NOJOYSTICK
1113                // Joystick
1114                dInput->lpVtbl->EnumDevices(dInput, DIDEVTYPE_JOYSTICK, JoystickCallback, null, DIEDFL_ATTACHEDONLY );
1115                for(j=0; j<NUMJOY; j++)
1116                   if(directJoysticks[j])
1117                      if(!directJoysticks[j]->lpVtbl->SetDataFormat(directJoysticks[j], &c_dfDIJoystick ))
1118                         directJoysticks[j]->lpVtbl->EnumObjects(directJoysticks[j], JoystickAxesCallback, directJoysticks[j], DIDFT_AXIS );
1119    #endif
1120                result = true;
1121             }
1122          }
1123       }
1124       return result;
1125    }
1126
1127    void ::AcquireDirectInput(HWND windowHandle, bool state)
1128    {
1129       if((state && !acquiredWindow) || (!state && acquiredWindow == windowHandle))
1130       {
1131          int j;
1132          if(directMouse)
1133          {
1134             if(state)
1135             {
1136                directMouse->lpVtbl->SetCooperativeLevel(directMouse, /*fullScreenMode ? */windowHandle /*: HWND_DESKTOP*/, DISCL_EXCLUSIVE|DISCL_FOREGROUND);
1137                directMouse->lpVtbl->Acquire(directMouse);
1138             }
1139             else
1140                directMouse->lpVtbl->Unacquire(directMouse);
1141          }
1142    #ifndef ECERE_NOJOYSTICK
1143          for(j = 0; j<NUMJOY; j++)
1144             if(directJoysticks[j])
1145             {
1146                if(state)
1147                {
1148                   directJoysticks[j]->lpVtbl->SetCooperativeLevel(directJoysticks[j], /*fullScreenMode ? */windowHandle /*: HWND_DESKTOP*/, DISCL_EXCLUSIVE|DISCL_FOREGROUND);
1149                   directJoysticks[j]->lpVtbl->Acquire(directJoysticks[j]);
1150                }
1151                else
1152                   directJoysticks[j]->lpVtbl->Unacquire(directJoysticks[j]);
1153             }
1154    #endif
1155          acquiredWindow = state ? windowHandle : null;
1156       }
1157    }
1158    #endif
1159
1160    /****************************************************************************
1161       /// INTEGRATION FUNCTIONALITY /////////////
1162    ****************************************************************************/
1163    bool eisWIN32ProcessKey(Window window, DWORD msg, DWORD wParam, DWORD lParam, byte ch)
1164    {
1165       return ProcessKeyMessage(window, msg, wParam, lParam, ch);
1166    }
1167
1168    HWND eisWIN32GetWindowHandle(Window window)
1169    {
1170       return window.windowHandle ? window.windowHandle : window.rootWindow.windowHandle;
1171    }
1172
1173    /****************************************************************************
1174       /// DRIVER IMPLEMENTATION /////////////
1175    ****************************************************************************/
1176
1177 #ifdef _WIN64
1178    void CALLBACK ::TimerProc(UINT uTimerID, UINT uMsg, uint64 dwUser, uint64 dw1, uint64 dw2)
1179 #else
1180    void CALLBACK ::TimerProc(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
1181 #endif
1182    {
1183       guiApp.SignalEvent();
1184    }
1185
1186    // --- User Interface System ---
1187    bool Initialize()
1188    {
1189       WNDCLASS wcl =
1190       {
1191          CS_DBLCLKS, ApplicationWindow, 0L, 0L, 0,
1192          LoadIcon(null, IDI_APPLICATION),
1193          null,
1194          null,
1195          null,
1196          className
1197       };
1198       HDC hdc = GetDC(0);
1199       lastRes = MAKELPARAM(GetSystemMetrics(SM_CYSCREEN), GetSystemMetrics(SM_CXSCREEN));
1200       lastBits = (WPARAM)GetDeviceCaps(hdc, BITSPIXEL);
1201       ReleaseDC(0, hdc);
1202
1203       AttachConsole(-1);
1204       wcl.hInstance = hInstance = GetModuleHandle(null);
1205       RegisterClass(&wcl);
1206
1207       // Move that in reposition desktop
1208       startBar = FindWindowA("Shell_TrayWnd", null);
1209
1210       systemCursors[arrow] = LoadCursor(null, IDC_ARROW);
1211       systemCursors[iBeam] = LoadCursor(null, IDC_IBEAM);
1212       systemCursors[cross] = LoadCursor(null, IDC_CROSS);
1213       systemCursors[moving] = LoadCursor(null, IDC_SIZEALL);
1214       systemCursors[sizeNESW] = LoadCursor(null, IDC_SIZENESW);
1215       systemCursors[sizeNS  ] = LoadCursor(null, IDC_SIZENS);
1216       systemCursors[sizeNWSE] = LoadCursor(null, IDC_SIZENWSE);
1217       systemCursors[sizeWE  ] = LoadCursor(null, IDC_SIZEWE);
1218       systemCursors[hand    ] = LoadCursor(null, IDC_HAND);
1219
1220       SetTimer(null, 0, (DWORD)(1000.0 / 18.2), null);
1221       //SetTimer(null, 0, 1, null);
1222       /*
1223       timeBeginPeriod(1);
1224
1225       hiResTimer = timeSetEvent(
1226          1000.0 / 250.0,
1227          1000.0 / 250.0,
1228          TimerProc,0,TIME_PERIODIC);
1229       */
1230       /*
1231       hiResTimer = timeSetEvent(
1232          1000.0 / 500.0,
1233          1000.0 / 500.0,
1234          TimerProc,0,TIME_PERIODIC);
1235          */
1236
1237    /*
1238       topWindow = CreateWindowEx(0, className, "",WS_POPUP,0,0,1,1,HWND_DESKTOP,
1239          null, hInstance, null);
1240    */
1241       return true;
1242    }
1243
1244    void Terminate()
1245    {
1246       if(hiResTimer) timeKillEvent(hiResTimer);
1247    #ifndef ECERE_NODINPUT
1248       TerminateDirectInput();
1249    #endif
1250    }
1251
1252    void SetTimerResolution(uint hertz)
1253    {
1254       if(hiResTimer) timeKillEvent(hiResTimer);
1255       if(hertz)
1256          hiResTimer = timeSetEvent(1000 / hertz, 1000 / hertz, TimerProc, 0, TIME_PERIODIC);
1257    }
1258
1259    bool ProcessInput(bool processAll)
1260    {
1261       MSG msg;
1262       if(!fullScreenMode)
1263          RepositionDesktop(true);
1264       if(PeekMessage(&msg,0,0,0,PM_NOREMOVE))
1265       {
1266          while(PeekMessage(&msg,0,0,0,PM_REMOVE))
1267          {
1268             TranslateMessage(&msg);
1269             DispatchMessage(&msg);
1270             // printf("%d\n", msg.message);
1271             if(!processAll || msg.message == WM_TIMER) break;
1272          }
1273          return true;
1274       }
1275       return false;
1276    }
1277
1278    void Wait()
1279    {
1280       MsgWaitForMultipleObjects(1, (void **)guiApp.semaphore, FALSE, (uint)(1000 / 18.2) /*INFINITE*/, QS_ALLINPUT);
1281    }
1282
1283    void Lock(Window window)
1284    {
1285
1286    }
1287
1288    void Unlock(Window window)
1289    {
1290
1291    }
1292
1293    const char ** GraphicsDrivers(int * numDrivers)
1294    {
1295       static const char *graphicsDrivers[] = { "GDI", "DirectDraw", "OpenGL", "Direct3D", "Direct3D8", "Direct3D9" };
1296       *numDrivers = sizeof(graphicsDrivers) / sizeof(char *);
1297       return (const char **)graphicsDrivers;
1298    }
1299
1300    void GetCurrentMode(bool * fullScreen, Resolution * resolution, PixelFormat * colorDepth, int * refreshRate)
1301    {
1302       *fullScreen = fullScreenMode;
1303       if(fullScreenMode)
1304       {
1305          Resolution c;
1306          for(c = 0; c<Resolution::enumSize; c++)
1307             if(GetResolutionWidth(c) == devMode.dmPelsWidth && GetResolutionHeight(c) == devMode.dmPelsHeight)
1308             {
1309                *resolution = c;
1310                break;
1311             }
1312          switch(devMode.dmBitsPerPel)
1313          {
1314             case 8: *colorDepth = pixelFormat8; break;
1315             case 16: *colorDepth = pixelFormat555; break;
1316             default: *colorDepth = pixelFormat888; break;
1317          }
1318          * refreshRate = devMode.dmDisplayFrequency;
1319       }
1320    }
1321
1322    void EnsureFullScreen(bool *fullScreen)
1323    {
1324
1325    }
1326
1327    bool ScreenMode(bool fullScreen, Resolution resolution, PixelFormat colorDepth, int refreshRate, bool * textMode)
1328    {
1329       bool result = true;
1330       HDC hdc = GetDC(0);
1331
1332       fullScreenMode = fullScreen;
1333
1334       if(fullScreen)
1335       {
1336          FillBytes(&devMode, 0, sizeof(DEVMODE));
1337            devMode.dmSize = (uint16)sizeof(devMode);
1338          devMode.dmFields |=DM_BITSPERPEL;
1339          devMode.dmFields |=DM_PELSWIDTH|DM_PELSHEIGHT;
1340          devMode.dmFields |= DM_DISPLAYFREQUENCY;
1341          devMode.dmBitsPerPel = colorDepth ? GetDepthBits(colorDepth) : GetDeviceCaps(hdc, BITSPIXEL);
1342          devMode.dmPelsWidth = resolution ? GetResolutionWidth(resolution) : GetSystemMetrics(SM_CXSCREEN);
1343          devMode.dmPelsHeight = resolution ? GetResolutionHeight(resolution) : GetSystemMetrics(SM_CYSCREEN);
1344          devMode.dmDisplayFrequency = refreshRate ? refreshRate : GetDeviceCaps(hdc, VREFRESH);
1345          if(ChangeDisplaySettings(&devMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1346             result = false;
1347          else
1348          {
1349             SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC);
1350             guiApp.SetDesktopPosition(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), false);
1351          }
1352       }
1353       else
1354       {
1355          static bool firstTime = true;
1356          if(!firstTime)
1357             ChangeDisplaySettings(null, 0);
1358          firstTime = false;
1359          SetSystemPaletteUse(hdc, SYSPAL_STATIC);
1360          desktopX = desktopY = desktopW = desktopH = 0;
1361
1362          RepositionDesktop(false);
1363       }
1364       ReleaseDC(0,hdc);
1365
1366       return result;
1367    }
1368
1369    // --- Window Creation ---
1370    void * CreateRootWindow(Window window)
1371    {
1372       HWND windowHandle;
1373       uint16 * text = UTF8toUTF16(window.text, null);
1374       if(fullScreenMode)
1375       {
1376          windowHandle = CreateWindowEx(0, className, text,
1377                         WS_POPUP,
1378                         0,0,GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN),
1379                         HWND_DESKTOP,
1380                         null, hInstance, null);
1381          ShowWindow(windowHandle, SW_SHOWNORMAL);
1382       }
1383       else if(window.systemParent)
1384          windowHandle = CreateWindowEx(0, className, text,
1385          WS_CHILD,0,0,1,1, window.systemParent, null, hInstance, null);
1386       else
1387       {
1388          DWORD style = 0;
1389          DWORD exStyle = 0;
1390          HWND parentWindow = null; //HWND_DESKTOP; // we get different behaviors with desktop...
1391          Window master = window.master, rootWindow = (master && master != guiApp.desktop) ? master.rootWindow : null;
1392          if(window.style.stayOnTop)
1393             exStyle |= WS_EX_TOPMOST;
1394
1395          if(rootWindow && (window._isModal || window.style.interim))
1396             parentWindow = rootWindow.is3D ? rootWindow.parent.windowHandle : rootWindow.windowHandle;
1397
1398          if(window.alphaBlend)
1399          // if(window.background.a < 255) //&& window.style & ES_REDRAW) Not needed anymore?
1400             exStyle |= WS_EX_LAYERED; // | WS_EX_TRANSPARENT;
1401
1402          // Toolwindow will disappear if they don't have AppWindow set
1403          if(window.style.showInTaskBar || (!parentWindow && window.style.thin))
1404          {
1405             exStyle |= WS_EX_APPWINDOW;
1406             parentWindow = null;
1407          }
1408
1409          if(window.style.thin)
1410             exStyle |= WS_EX_TOOLWINDOW;
1411
1412          if(window.windowHandle)
1413             windowHandle = window.windowHandle;
1414          else
1415          {
1416             if(window.nativeDecorations)
1417             {
1418                BorderBits borderStyle = window.borderStyle; // FIXME!
1419                style = WS_OVERLAPPED;
1420                if(borderStyle.fixed)
1421                   style |= WS_CAPTION;
1422                if(window.hasClose)
1423                   style |= WS_SYSMENU;
1424                if(borderStyle.sizable)
1425                   style |= WS_THICKFRAME;
1426                if(window.hasMinimize)
1427                   style |= WS_MINIMIZEBOX;
1428                if(window.hasMaximize)
1429                   style |= WS_MAXIMIZEBOX;
1430             }
1431             windowHandle = CreateWindowEx(
1432                exStyle,
1433                className, text,
1434                style | (window.systemParent ? WS_CHILD :
1435                (WS_POPUP | (window.style.hasMinimize ? WS_MINIMIZEBOX : 0))),
1436                   0,0,1,1, parentWindow, null, hInstance, null);
1437    #if 0
1438             if(exStyle & WS_EX_LAYERED)
1439                SetLayeredWindowAttributes(windowHandle, 0, 255 /*A(window.background)*/, LWA_ALPHA);
1440    #endif
1441          }
1442       }
1443       delete text;
1444 #ifdef _WIN64
1445       SetWindowLongPtr(windowHandle, GWLP_USERDATA, (int64)window);
1446 #else
1447       SetWindowLong(windowHandle, GWL_USERDATA, (DWORD)window);
1448 #endif
1449
1450       return windowHandle;
1451    }
1452
1453    void DestroyRootWindow(Window window)
1454    {
1455       HICON oldIcon;
1456       int c, lockCount = guiApp.lockMutex.lockCount;
1457       for(c = 0; c < lockCount; c++)
1458          guiApp.lockMutex.Release();
1459
1460       oldIcon = (HICON)SendMessage(window.windowHandle, WM_GETICON, ICON_BIG, 0);
1461 #ifdef _WIN64
1462       if(oldIcon && oldIcon != (HICON)GetClassLongPtr(window.windowHandle, GCLP_HICON))
1463 #else
1464       if(oldIcon && oldIcon != (HICON)GetClassLong(window.windowHandle, GCL_HICON))
1465 #endif
1466          DestroyIcon(oldIcon);
1467
1468         ShowWindow(window.windowHandle, SW_HIDE);
1469
1470 #ifdef _WIN64
1471       SetWindowLongPtr(window.windowHandle, GWLP_USERDATA, (int64)null);
1472 #else
1473       SetWindowLong(window.windowHandle, GWL_USERDATA, 0);
1474 #endif
1475       DestroyWindow(window.windowHandle);
1476
1477       for(c = 0; c < lockCount; c++)
1478          guiApp.lockMutex.Wait();
1479
1480       window.windowHandle = null;
1481    }
1482
1483    // -- Window manipulation ---
1484
1485    void SetRootWindowCaption(Window window, const char * name)
1486    {
1487       uint16 * text = UTF8toUTF16(name, null);
1488       guiApp.Unlock();
1489       SetWindowText(window.windowHandle, text);
1490       guiApp.Lock();
1491       delete text;
1492    }
1493
1494    void PositionRootWindow(Window window, int x, int y, int w, int h, bool move, bool resize)
1495    {
1496       int flags = SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS;
1497
1498       if(!window.systemParent && !fullScreenMode)
1499       {
1500          x += desktopX;
1501          y += desktopY;
1502       }
1503
1504       if(!move) flags |= SWP_NOMOVE;
1505       if(!resize) flags |= SWP_NOSIZE;
1506
1507       /*if(move && resize)
1508       {
1509          flags |= SWP_NOMOVE;
1510          SetWindowPos(window.windowHandle, null, x, y, w, h, flags);
1511          flags &=~SWP_NOMOVE;
1512          flags |= SWP_NOSIZE;
1513       }*/
1514       if(!window.nativeDecorations || window.state != maximized || !window.visible || guiApp.modeSwitching)
1515          SetWindowPos(window.windowHandle, null, x, y, w, h, flags);
1516    }
1517
1518    void OrderRootWindow(Window window, bool topMost)
1519    {
1520       SetWindowPos(window.windowHandle, topMost ? HWND_TOPMOST : HWND_NOTOPMOST, 0,0,0,0,
1521          SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOSIZE|SWP_NOREDRAW);
1522    }
1523
1524    void SetRootWindowColor(Window window)
1525    {
1526       if(window.alphaBlend && window.display.pixelFormat == pixelFormat888)
1527       {
1528          /*if(A(window.background) == 255)
1529          {
1530             if((style & WS_EX_LAYERED) == WS_EX_LAYERED)
1531                SetWindowLong(window.windowHandle, GWL_EXSTYLE, style &~WS_EX_LAYERED);
1532          }
1533          else*/
1534          {
1535 #ifndef ECERE_NOBLENDING
1536             DWORD style = GetWindowLong(window.windowHandle, GWL_EXSTYLE);
1537             if((style & WS_EX_LAYERED) != WS_EX_LAYERED)
1538                SetWindowLong(window.windowHandle, GWL_EXSTYLE, style | WS_EX_LAYERED);
1539 #endif
1540             // SetLayeredWindowAttributes(window.windowHandle, 0, 255 /*Max(A(window.background),1)*/, LWA_ALPHA);
1541          }
1542       }
1543    }
1544
1545    void OffsetWindow(Window window, int * x, int * y)
1546    {
1547       if(window.systemParent)
1548       {
1549          POINT point = {*x,*y};
1550          ClientToScreen(GetParent(window.windowHandle), &point);
1551          *x = point.x;
1552          *y = point.y;
1553       }
1554    }
1555
1556    void UpdateRootWindow(Window window)
1557    {
1558       UpdateWindow(window.windowHandle);
1559    }
1560
1561    void SetRootWindowState(Window window, WindowState state, bool visible)
1562    {
1563       if(visible)
1564       {
1565          WindowState curState = window.state;
1566          *&window.state = state;
1567          switch(state)
1568          {
1569             case maximized:
1570             case normal:
1571                SmartShowWindow(window.windowHandle, window.nativeDecorations ? state : normal, (window.active || window.creationActivation == activate) && !externalDisplayChange);
1572                break;
1573             case minimized:
1574                ShowWindow(window.windowHandle, SW_MINIMIZE);
1575                break;
1576          }
1577          *&window.state = curState;
1578       }
1579       else
1580       {
1581          ShowWindow(window.windowHandle, SW_HIDE);
1582       }
1583    }
1584
1585    void ActivateRootWindow(Window window)
1586    {
1587       if(!externalDisplayChange)
1588          SetForegroundWindow(window.windowHandle);
1589    }
1590
1591    void FlashRootWindow(Window window)
1592    {
1593       HWND hwnd = window.windowHandle;
1594       FLASHWINFO flashInfo = { 0 };
1595       Window master = window.master, rootWindow = (master && master != guiApp.desktop) ? master.rootWindow : null;
1596       if(!window.style.showInTaskBar && rootWindow && (window._isModal || window.style.interim))
1597          hwnd = rootWindow.windowHandle;
1598
1599       flashInfo.cbSize = sizeof(FLASHWINFO);
1600       flashInfo.hwnd = hwnd;
1601       flashInfo.uCount = 1;
1602       flashInfo.dwFlags = FLASHW_TRAY; // FLASHW_ALL;
1603       guiApp.Unlock();
1604       FlashWindowEx((void *)&flashInfo);
1605       guiApp.Lock();
1606    }
1607
1608    // --- Mouse-based window movement ---
1609    void StartMoving(Window window, int x, int y, bool fromKeyBoard)
1610    {
1611       if(!fullScreenMode && !window.systemParent)
1612          // Commented out for Chess game because AI thread takes over the moving of main window... Still required?
1613          //SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE);
1614          ; //SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
1615       if(fromKeyBoard)
1616       {
1617          SetWindowPos(window.windowHandle, HWND_TOPMOST, 0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
1618          mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
1619          if(!window.stayOnTop)
1620             SetWindowPos(window.windowHandle, HWND_NOTOPMOST, 0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
1621       }
1622    }
1623
1624    void StopMoving(Window window)
1625    {
1626       if(!fullScreenMode && !window.systemParent)
1627          SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
1628    }
1629
1630    // -- Mouse manipulation ---
1631
1632    void GetMousePosition(int *x, int *y)
1633    {
1634       POINT point;
1635       GetCursorPos(&point);
1636       *x = point.x;
1637       *y = point.y;
1638    }
1639
1640    void SetMousePosition(int x, int y)
1641    {
1642       SetCursorPos(x, y);
1643    }
1644
1645    void SetMouseRange(Window window, Box box)
1646    {
1647       ClipCursor((RECT *) box);
1648    }
1649
1650    void SetMouseCapture(Window window)
1651    {
1652       if(window)
1653          SetCapture(window.windowHandle);
1654       else
1655          ReleaseCapture();
1656    }
1657
1658    // -- Mouse cursor ---
1659
1660    void SetMouseCursor(Window window, SystemCursor cursor)
1661    {
1662       if(lastCursor != cursor)
1663       {
1664          lastCursor = cursor;
1665          SetCursor((cursor == (SystemCursor)-1) ? null : systemCursors[cursor]);
1666       }
1667    }
1668
1669    // --- Caret ---
1670
1671    void SetCaret(int x, int y, int size)
1672    {
1673
1674    }
1675
1676    // --- Clipboard manipulation ---
1677
1678    void ClearClipboard()
1679    {
1680         if(OpenClipboard(null))
1681         {
1682          EmptyClipboard();
1683            CloseClipboard();
1684       }
1685    }
1686
1687    bool AllocateClipboard(ClipBoard clipBoard, uint size)
1688    {
1689       bool result = false;
1690       clipBoard.text = new byte[size];
1691       result = true;
1692       return result;
1693    }
1694
1695    bool SaveClipboard(ClipBoard clipBoard)
1696    {
1697       bool result = false;
1698       if(clipBoard.text)
1699       {
1700          int wordCount;
1701          uint16 * u16text = UTF8toUTF16(clipBoard.text, &wordCount);
1702          wordCount++;
1703          clipBoard.handle = GlobalAlloc(GHND | GMEM_DDESHARE, wordCount * 2);
1704          if(clipBoard.handle)
1705          {
1706             uint16 * text = GlobalLock(clipBoard.handle);
1707             if(text)
1708             {
1709                memcpy(text, u16text, wordCount * 2);
1710                GlobalUnlock(clipBoard.handle);
1711                    if(OpenClipboard(null))
1712                    {
1713                   EmptyClipboard();
1714                       if(SetClipboardData(CF_UNICODETEXT, clipBoard.handle))
1715                   {
1716                          CloseClipboard();
1717                      result= true;
1718                   }
1719                }
1720             }
1721             if(!result)
1722                GlobalFree(clipBoard.handle);
1723          }
1724          delete u16text;
1725       }
1726       return result;
1727    }
1728
1729    bool LoadClipboard(ClipBoard clipBoard)
1730    {
1731       bool result = false;
1732         if(OpenClipboard(null))
1733         {
1734          if((clipBoard.handle = GetClipboardData(CF_UNICODETEXT)))
1735          {
1736             uint16 * u16text = GlobalLock(clipBoard.handle);
1737             if(u16text)
1738             {
1739                clipBoard.text = UTF16toUTF8(u16text);
1740                result = true;
1741                GlobalUnlock(clipBoard.handle);
1742             }
1743          }
1744          CloseClipboard();
1745       }
1746       return result;
1747    }
1748
1749    void UnloadClipboard(ClipBoard clipBoard)
1750    {
1751       delete clipBoard.text;
1752    }
1753
1754    // --- State based input ---
1755
1756    bool AcquireInput(Window window, bool state)
1757    {
1758    #ifndef ECERE_NODINPUT
1759       if(dInput || InitDirectInput())
1760       {
1761          AcquireDirectInput(window.windowHandle, state);
1762          return true;
1763       }
1764    #endif
1765       return false;
1766    }
1767
1768    bool GetMouseState(MouseButtons * buttons, int * x, int * y)
1769    {
1770       bool result = false;
1771    #ifndef ECERE_NODINPUT
1772       DIMOUSESTATE dims = {0};
1773
1774       if(acquiredWindow && directMouse)
1775       {
1776          if(directMouse->lpVtbl->GetDeviceState(directMouse, sizeof(DIMOUSESTATE), &dims ))
1777          {
1778             FillBytes(&dims, 0, sizeof(dims));
1779             directMouse->lpVtbl->Acquire(directMouse);
1780          }
1781          result = true;
1782       }
1783       /*  We don't really want this...
1784       else
1785       {
1786          if(GetAsyncKeyState(VK_LBUTTON))
1787             dims.rgbButtons[0] |= 0x80;
1788          if(GetAsyncKeyState(VK_RBUTTON))
1789             dims.rgbButtons[1] |= 0x80;
1790          if(GetAsyncKeyState(VK_MBUTTON))
1791             dims.rgbButtons[2] |= 0x80;
1792       }
1793       */
1794
1795       if(x)*x = dims.lX;
1796       if(y)*y = dims.lY;
1797       if(dims.lZ)
1798       {
1799 #ifdef _WIN64
1800          Window window = (Window)GetWindowLongPtr(acquiredWindow, GWLP_USERDATA);
1801 #else
1802          Window window = (Window)GetWindowLong(acquiredWindow, GWL_USERDATA);
1803 #endif
1804          ProcessKeyMessage(window, WM_MOUSEWHEEL, ((uint16)(short)dims.lZ) << 16, 0, 0);
1805       }
1806       if(buttons)
1807       {
1808          *buttons = MouseButtons {
1809              left = (dims.rgbButtons[0] & 0x80) ? true : false,
1810              right = (dims.rgbButtons[1] & 0x80) ? true : false,
1811              middle = (dims.rgbButtons[2] & 0x80) ? true : false };
1812       }
1813    #endif
1814
1815       return result;
1816    }
1817
1818    bool GetJoystickState(int device, Joystick joystick)
1819    {
1820       bool result = false;
1821    #ifndef ECERE_NODINPUT
1822       if(joystick != null)
1823       {
1824          DIJOYSTATE dijs = {0};
1825    #ifndef ECERE_NOJOYSTICK
1826          if(acquiredWindow && device < numJoysticks)
1827          {
1828             if(directJoysticks[device])
1829             {
1830                directJoysticks[device]->lpVtbl->Poll(directJoysticks[device]);
1831                if(directJoysticks[device]->lpVtbl->GetDeviceState(directJoysticks[device], sizeof(DIJOYSTATE), &dijs ))
1832                   directJoysticks[device]->lpVtbl->Acquire(directJoysticks[device]);
1833                result = true;
1834             }
1835          }
1836    #endif
1837          joystick.x = dijs.lX;
1838          joystick.y = dijs.lY;
1839          joystick.z = dijs.lZ;
1840          joystick.rx = dijs.lRx;
1841          joystick.ry = dijs.lRy;
1842          joystick.rz = dijs.lRz;
1843          joystick.buttons =
1844               ((dijs.rgbButtons[0] & 0x80) ? JOY_BUTTON1 : 0)
1845             | ((dijs.rgbButtons[1] & 0x80) ? JOY_BUTTON2 : 0)
1846             | ((dijs.rgbButtons[2] & 0x80) ? JOY_BUTTON3 : 0)
1847             | ((dijs.rgbButtons[3] & 0x80) ? JOY_BUTTON4 : 0);
1848       }
1849    #endif
1850       return result;
1851    }
1852
1853    bool GetKeyState(Key key)
1854    {
1855       bool keyState = false;
1856       if(key < 256 || key == alt || key == shift || key == control)
1857       {
1858          uint ks = 0;
1859          if(key == alt)
1860             ks = GetAsyncKeyState(VK_MENU);
1861          else if(key == control)
1862             ks = GetAsyncKeyState(VK_CONTROL);
1863          else if(key == shift)
1864             ks = GetAsyncKeyState(VK_SHIFT);
1865          else if(key2VK[key])
1866             ks = GetAsyncKeyState(key2VK[key]);
1867          keyState = (ks & 0x80000) ? true : false;
1868       }
1869       else if(key == capsState)
1870          keyState = (::GetKeyState(VK_CAPITAL) & 0x00000001) != 0;
1871       else if(key == numState)
1872          keyState = (::GetKeyState(VK_NUMLOCK) & 0x00000001) != 0;
1873       else if(key == scrollState)
1874          keyState = (::GetKeyState(VK_SCROLL) & 0x00000001) != 0;
1875       return keyState;
1876    }
1877
1878    bool SetIcon(Window window, BitmapResource resource)
1879    {
1880       HICON icon = null;
1881       HICON oldIcon = (HICON)SendMessage(window.windowHandle, WM_GETICON, ICON_BIG, 0);
1882
1883       // Dialogs Inherit master's icon if none set
1884       if(!window.style.showInTaskBar && window.hasClose)
1885       {
1886          Window master = window.master;
1887          while(master && !resource)
1888          {
1889             Window rootWindow = (master && master != guiApp.desktop) ? master.rootWindow : null;
1890             if(rootWindow && rootWindow.icon)
1891                resource = rootWindow.icon;
1892             else
1893                master = master.master;
1894          }
1895       }
1896
1897       // WARNING -- putting this here as it is right after CreateRootWindow
1898       // Take out Layered flag if we're not in 24 bit
1899       {
1900          if(window.alphaBlend && window.display.pixelFormat != pixelFormat888)
1901          {
1902 #ifndef ECERE_NOBLENDING
1903             DWORD style = GetWindowLong(window.windowHandle, GWL_EXSTYLE);
1904             style &= ~WS_EX_LAYERED;
1905             SetWindowLong(window.windowHandle, GWL_EXSTYLE, style);
1906 #endif
1907          }
1908       }
1909
1910 #ifdef _WIN64
1911       if(oldIcon && oldIcon != (HICON)GetClassLongPtr(window.windowHandle, GCLP_HICON))
1912 #else
1913       if(oldIcon && oldIcon != (HICON)GetClassLong(window.windowHandle, GCL_HICON))
1914 #endif
1915       {
1916          DestroyIcon(oldIcon);
1917       }
1918
1919       if(resource)
1920       {
1921          Bitmap bitmap { };
1922          if(bitmap.Load(resource.fileName, null, null))
1923          {
1924             Bitmap and { };
1925             PixelFormat format = window.display.pixelFormat;
1926             int bits = GetDepthBits(format);
1927             bool blend;
1928
1929             bitmap.Convert(null, pixelFormat888, null);
1930             and.Allocate(null, (bitmap.width+7/8), bitmap.height, 0, pixelFormat8, false);
1931
1932             blend = bits == 32 || bitmap.pixelFormat != pixelFormat888;
1933
1934             {
1935                byte * picture = and.picture;
1936                int c = 0;
1937                int b = 0;
1938                uint size = bitmap.height * bitmap.width;
1939                while(c < size)
1940                {
1941                   int m = 0;
1942                   byte mask = 0;
1943                   while(m < 8 && c < size)
1944                   {
1945                      mask <<= 1;
1946                      mask |= blend ? (!((ColorAlpha *)bitmap.picture)[c].a) : (((ColorAlpha *)bitmap.picture)[c].a <= 192);
1947                      c++;
1948                      m++;
1949                   }
1950                   picture[b++] = mask;
1951                }
1952                c = 0;
1953                while(c < size)
1954                {
1955                   ColorAlpha color = ((ColorAlpha *)bitmap.picture)[c];
1956                   if(blend ? (!color.a) : (color.a <= 192))
1957                   {
1958                      color.color = { 0, 0, 0 };
1959                      ((ColorAlpha *)bitmap.picture)[c] = color;
1960                   }
1961                   c++;
1962                }
1963             }
1964             if(bits == 15) { bits = 16; format = pixelFormat565; };
1965             bitmap.Convert(null, format, null);
1966
1967             icon = CreateIcon(hInstance, bitmap.width, bitmap.height, 1, (byte)bits, and.picture, bitmap.picture);
1968             delete and;
1969          }
1970          delete bitmap;
1971       }
1972       SendMessage(window.windowHandle, WM_SETICON, ICON_BIG, (LPARAM)icon);
1973       SendMessage(window.windowHandle, WM_SETICON, ICON_SMALL, (LPARAM)icon);
1974       return true;
1975    }
1976
1977    void ::GetScreenArea(Window window, Box box)
1978    {
1979       HMONITOR monitor = MonitorFromWindow(window.windowHandle, MONITOR_DEFAULTTONEAREST);
1980       HMONITOR taskBarMonitor = MonitorFromWindow(startBar, MONITOR_DEFAULTTONEAREST);
1981       if(monitor)
1982       {
1983          MONITORINFO info = { 0 };
1984          info.cbSize = sizeof(MONITORINFO);
1985          GetMonitorInfo(monitor, &info);
1986          // box = { info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom };
1987          box = { info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right-1, info.rcMonitor.bottom-1 };
1988
1989          if(taskBarMonitor == monitor)
1990          {
1991             if(taskBarPlacement.rcNormalPosition.top <= box.top && taskBarPlacement.rcNormalPosition.bottom >= box.bottom)
1992             {
1993                if(taskBarPlacement.rcNormalPosition.left <= box.left)
1994                {
1995                   if(taskBarState & ABS_AUTOHIDE)
1996                      box.left++;
1997                   else
1998                      box.left = taskBarPlacement.rcNormalPosition.right;
1999                }
2000                else if(taskBarState & ABS_AUTOHIDE)
2001                   box.right -= 1;
2002                else
2003                   box.right = taskBarPlacement.rcNormalPosition.left;
2004             }
2005             else if(taskBarPlacement.rcNormalPosition.left <= box.left && taskBarPlacement.rcNormalPosition.right >= box.right)
2006             {
2007                if(taskBarPlacement.rcNormalPosition.top <= box.top)
2008                {
2009                   if(taskBarState & ABS_AUTOHIDE)
2010                      box.top += 1;
2011                   else
2012                      box.top = taskBarPlacement.rcNormalPosition.bottom;
2013                }
2014                else if(taskBarState & ABS_AUTOHIDE)
2015                   box.bottom -= 1;
2016                else
2017                   box.bottom = taskBarPlacement.rcNormalPosition.top;
2018             }
2019          }
2020
2021          box.left -= desktopX;
2022          box.top -= desktopY;
2023          box.right -= desktopX;
2024          box.bottom -= desktopY;
2025       }
2026    }
2027 }
2028
2029 #endif