summaryrefslogtreecommitdiff
path: root/src/SFML/Window/Win32/WindowImplWin32.cpp
blob: e07eeab41be3c3d9661e25026adb2b54141060ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2008 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#define _WIN32_WINDOWS 0x0501
#define _WIN32_WINNT   0x0501
#include <SFML/Window/Win32/WindowImplWin32.hpp>
#include <SFML/Window/WindowSettings.hpp>
#include <SFML/Window/WindowStyle.hpp>
#include <GL/gl.h>
#include <SFML/Window/glext/wglext.h>
#include <SFML/Window/glext/glext.h>
#include <iostream>
#include <vector>

// Old versions of MinGW lack the definition of XBUTTON1 and XBUTTON2
#ifndef XBUTTON1
    #define XBUTTON1 0x0001
#endif
#ifndef XBUTTON2
    #define XBUTTON2 0x0002
#endif


namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
unsigned int     WindowImplWin32::ourWindowCount      = 0;
const char*      WindowImplWin32::ourClassNameA       = "SFML_Window";
const wchar_t*   WindowImplWin32::ourClassNameW       = L"SFML_Window";
WindowImplWin32* WindowImplWin32::ourFullscreenWindow = NULL;


////////////////////////////////////////////////////////////
/// Default constructor
/// (creates a dummy window to provide a valid OpenGL context)
////////////////////////////////////////////////////////////
WindowImplWin32::WindowImplWin32() :
myHandle          (NULL),
myCallback        (0),
myCursor          (NULL),
myIcon            (NULL),
myKeyRepeatEnabled(true),
myIsCursorIn      (false)
{
    // Register the window class at first call
    if (ourWindowCount == 0)
        RegisterWindowClass();

    // Use small dimensions
    myWidth  = 1;
    myHeight = 1;

    // Create a dummy window (disabled and hidden)
    if (HasUnicodeSupport())
    {
        myHandle = CreateWindowW(ourClassNameW, L"", WS_POPUP | WS_DISABLED, 0, 0, myWidth, myHeight, NULL, NULL, GetModuleHandle(NULL), NULL);
    }
    else
    {
        myHandle = CreateWindowA(ourClassNameA, "", WS_POPUP | WS_DISABLED, 0, 0, myWidth, myHeight, NULL, NULL, GetModuleHandle(NULL), NULL);
    }
    ShowWindow(myHandle, SW_HIDE);

    // Create the rendering context
    if (myHandle)
    {
        WindowSettings Params(0, 0, 0);
        CreateContext(VideoMode(myWidth, myHeight, 32), Params);

        // Don't activate by default
        SetActive(false);
    }
}


////////////////////////////////////////////////////////////
/// Create the window implementation from an existing control
////////////////////////////////////////////////////////////
WindowImplWin32::WindowImplWin32(WindowHandle Handle, WindowSettings& Params) :
myHandle          (NULL),
myCallback        (0),
myCursor          (NULL),
myIcon            (NULL),
myKeyRepeatEnabled(true),
myIsCursorIn      (false)
{
    // Save window handle
    myHandle = static_cast<HWND>(Handle);

    if (myHandle)
    {
        // Get window client size
        RECT Rect;
        GetClientRect(myHandle, &Rect);
        myWidth  = Rect.right - Rect.left;
        myHeight = Rect.bottom - Rect.top;

        // Create the rendering context
        VideoMode Mode(myWidth, myHeight, VideoMode::GetDesktopMode().BitsPerPixel);
        CreateContext(Mode, Params);

        // We change the event procedure of the control (it is important to save the old one)
        SetWindowLongPtr(myHandle, GWLP_USERDATA, reinterpret_cast<long>(this));
        myCallback = SetWindowLongPtr(myHandle, GWLP_WNDPROC, reinterpret_cast<long>(&WindowImplWin32::GlobalOnEvent));
    }
}


////////////////////////////////////////////////////////////
/// Create the window implementation
////////////////////////////////////////////////////////////
WindowImplWin32::WindowImplWin32(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params) :
myHandle          (NULL),
myCallback        (0),
myCursor          (NULL),
myIcon            (NULL),
myKeyRepeatEnabled(true),
myIsCursorIn      (false)
{
    // Register the window class at first call
    if (ourWindowCount == 0)
        RegisterWindowClass();

    // Compute position and size
    int Left   = (GetDeviceCaps(GetDC(NULL), HORZRES) - Mode.Width)  / 2;
    int Top    = (GetDeviceCaps(GetDC(NULL), VERTRES) - Mode.Height) / 2;
    int Width  = myWidth  = Mode.Width;
    int Height = myHeight = Mode.Height;

    // Choose the window style according to the Style parameter
    DWORD Win32Style = WS_VISIBLE;
    if (WindowStyle == Style::None)
    {
        Win32Style |= WS_POPUP;
    }
    else
    {
        if (WindowStyle & Style::Titlebar) Win32Style |= WS_CAPTION | WS_MINIMIZEBOX;
        if (WindowStyle & Style::Resize)   Win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
        if (WindowStyle & Style::Close)    Win32Style |= WS_SYSMENU;
    }

    // In windowed mode, adjust width and height so that window will have the requested client area
    bool Fullscreen = (WindowStyle & Style::Fullscreen) != 0;
    if (!Fullscreen)
    {
        RECT Rect = {0, 0, Width, Height};
        AdjustWindowRect(&Rect, Win32Style, false);
        Width  = Rect.right - Rect.left;
        Height = Rect.bottom - Rect.top;
    }

    // Create the window
    if (HasUnicodeSupport())
    {
        wchar_t WTitle[256];
        int NbChars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Title.c_str(), static_cast<int>(Title.size()), WTitle, sizeof(WTitle) / sizeof(*WTitle));
        WTitle[NbChars] = L'\0';
        myHandle = CreateWindowW(ourClassNameW, WTitle, Win32Style, Left, Top, Width, Height, NULL, NULL, GetModuleHandle(NULL), this);
    }
    else
    {
        myHandle = CreateWindowA(ourClassNameA, Title.c_str(), Win32Style, Left, Top, Width, Height, NULL, NULL, GetModuleHandle(NULL), this);
    }

    // Switch to fullscreen if requested
    if (Fullscreen)
        SwitchToFullscreen(Mode);

    // Create the rendering context
    if (myHandle)
        CreateContext(Mode, Params);

    // Increment window count
    ourWindowCount++;

    // Get the actual size of the window, which can be smaller even after the call to AdjustWindowRect
    // This happens when the window is bigger than the desktop
    RECT ActualRect;
    GetClientRect(myHandle, &ActualRect);
    myWidth  = ActualRect.right - ActualRect.left;
    myHeight = ActualRect.bottom - ActualRect.top;
}


////////////////////////////////////////////////////////////
/// Destructor
////////////////////////////////////////////////////////////
WindowImplWin32::~WindowImplWin32()
{
    // Destroy the custom icon, if any
    if (myIcon)
        DestroyIcon(myIcon);

    if (!myCallback)
    {
        // Destroy the window
        if (myHandle)
            DestroyWindow(myHandle);

        // Decrement the window count
        ourWindowCount--;

        // Unregister window class if we were the last window
        if (ourWindowCount == 0)
        {
            if (HasUnicodeSupport())
            {
                UnregisterClassW(ourClassNameW, GetModuleHandle(NULL));
            }
            else
            {
                UnregisterClassA(ourClassNameA, GetModuleHandle(NULL));
            }
        }
    }
    else
    {
        // The window is external : remove the hook on its message callback
        SetWindowLongPtr(myHandle, GWLP_WNDPROC, myCallback);
    }
}


////////////////////////////////////////////////////////////
/// Check if there's an active context on the current thread
////////////////////////////////////////////////////////////
bool WindowImplWin32::IsContextActive()
{
    return wglGetCurrentContext() != NULL;
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::ProcessEvents
////////////////////////////////////////////////////////////
void WindowImplWin32::ProcessEvents()
{
    // We update the window only if we own it
    if (!myCallback)
    {
        MSG Message;
        while (PeekMessage(&Message, myHandle, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&Message);
            DispatchMessage(&Message);
        }
    }
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::Display
////////////////////////////////////////////////////////////
void WindowImplWin32::Display()
{
    if (myDeviceContext && myGLContext)
        SwapBuffers(myDeviceContext);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::SetActive
////////////////////////////////////////////////////////////
void WindowImplWin32::SetActive(bool Active) const
{
    if (Active)
    {
        if (myDeviceContext && myGLContext && (wglGetCurrentContext() != myGLContext))
            wglMakeCurrent(myDeviceContext, myGLContext);
    }
    else
    {
        if (wglGetCurrentContext() == myGLContext)
            wglMakeCurrent(NULL, NULL);
    }
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::UseVerticalSync
////////////////////////////////////////////////////////////
void WindowImplWin32::UseVerticalSync(bool Enabled)
{
    PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = reinterpret_cast<PFNWGLSWAPINTERVALEXTPROC>(wglGetProcAddress("wglSwapIntervalEXT"));
    if (wglSwapIntervalEXT)
        wglSwapIntervalEXT(Enabled ? 1 : 0);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::ShowMouseCursor
////////////////////////////////////////////////////////////
void WindowImplWin32::ShowMouseCursor(bool Show)
{
    if (Show)
        myCursor = LoadCursor(NULL, IDC_ARROW);
    else
        myCursor = NULL;

    SetCursor(myCursor);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::SetCursorPosition
////////////////////////////////////////////////////////////
void WindowImplWin32::SetCursorPosition(unsigned int Left, unsigned int Top)
{
    POINT Pos = {Left, Top};
    ClientToScreen(myHandle, &Pos);
    SetCursorPos(Pos.x, Pos.y);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::SetPosition
////////////////////////////////////////////////////////////
void WindowImplWin32::SetPosition(int Left, int Top)
{
    SetWindowPos(myHandle, NULL, Left, Top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::SetSize
////////////////////////////////////////////////////////////
void WindowImplWin32::SetSize(unsigned int Width, unsigned int Height)
{
    SetWindowPos(myHandle, NULL, 0, 0, Width, Height, SWP_NOMOVE | SWP_NOZORDER);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::Show
////////////////////////////////////////////////////////////
void WindowImplWin32::Show(bool State)
{
    ShowWindow(myHandle, State ? SW_SHOW : SW_HIDE);
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::EnableKeyRepeat
////////////////////////////////////////////////////////////
void WindowImplWin32::EnableKeyRepeat(bool Enabled)
{
    myKeyRepeatEnabled = Enabled;
}


////////////////////////////////////////////////////////////
/// /see WindowImpl::SetIcon
////////////////////////////////////////////////////////////
void WindowImplWin32::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
{
    // First destroy the previous one
    if (myIcon)
        DestroyIcon(myIcon);

    // Windows wants BGRA pixels : swap red and blue channels
    std::vector<Uint8> IconPixels(Width * Height * 4);
    for (std::size_t i = 0; i < IconPixels.size() / 4; ++i)
    {
        IconPixels[i * 4 + 0] = Pixels[i * 4 + 2];
        IconPixels[i * 4 + 1] = Pixels[i * 4 + 1];
        IconPixels[i * 4 + 2] = Pixels[i * 4 + 0];
        IconPixels[i * 4 + 3] = Pixels[i * 4 + 3];
    }

    // Create the icon from the pixels array
    myIcon = CreateIcon(GetModuleHandle(NULL), Width, Height, 1, 32, NULL, &IconPixels[0]);

    // Set it as both big and small icon of the window
    if (myIcon)
    {
        SendMessage(myHandle, WM_SETICON, ICON_BIG,   (LPARAM)myIcon);
        SendMessage(myHandle, WM_SETICON, ICON_SMALL, (LPARAM)myIcon);
    }
    else
    {
        std::cerr << "Failed to set the window's icon" << std::endl;
    }
}


////////////////////////////////////////////////////////////
/// Register the window class
////////////////////////////////////////////////////////////
void WindowImplWin32::RegisterWindowClass()
{
    if (HasUnicodeSupport())
    {
        WNDCLASSW WindowClass;
        WindowClass.style         = 0;
        WindowClass.lpfnWndProc   = &WindowImplWin32::GlobalOnEvent;
        WindowClass.cbClsExtra    = 0;
        WindowClass.cbWndExtra    = 0;
        WindowClass.hInstance     = GetModuleHandle(NULL);
        WindowClass.hIcon         = NULL;
        WindowClass.hCursor       = 0;
        WindowClass.hbrBackground = 0;
        WindowClass.lpszMenuName  = NULL;
        WindowClass.lpszClassName = ourClassNameW;
        RegisterClassW(&WindowClass);
    }
    else
    {
        WNDCLASSA WindowClass;
        WindowClass.style         = 0;
        WindowClass.lpfnWndProc   = &WindowImplWin32::GlobalOnEvent;
        WindowClass.cbClsExtra    = 0;
        WindowClass.cbWndExtra    = 0;
        WindowClass.hInstance     = GetModuleHandle(NULL);
        WindowClass.hIcon         = NULL;
        WindowClass.hCursor       = 0;
        WindowClass.hbrBackground = 0;
        WindowClass.lpszMenuName  = NULL;
        WindowClass.lpszClassName = ourClassNameA;
        RegisterClassA(&WindowClass);
    }
}


////////////////////////////////////////////////////////////
/// Switch to fullscreen mode
////////////////////////////////////////////////////////////
void WindowImplWin32::SwitchToFullscreen(const VideoMode& Mode)
{
    DEVMODE DevMode;
    DevMode.dmSize       = sizeof(DEVMODE);
    DevMode.dmPelsWidth  = Mode.Width;
    DevMode.dmPelsHeight = Mode.Height;
    DevMode.dmBitsPerPel = Mode.BitsPerPixel;
    DevMode.dmFields     = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;

    // Apply fullscreen mode
    if (ChangeDisplaySettings(&DevMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
    {
        std::cerr << "Failed to change display mode for fullscreen" << std::endl;
        return;
    }

    // Change window style (no border, no titlebar, ...)
    SetWindowLong(myHandle, GWL_STYLE,   WS_POPUP);
    SetWindowLong(myHandle, GWL_EXSTYLE, WS_EX_APPWINDOW);

    // And resize it so that it fits the entire screen
    SetWindowPos(myHandle, HWND_TOP, 0, 0, Mode.Width, Mode.Height, SWP_FRAMECHANGED);
    ShowWindow(myHandle, SW_SHOW);

    // Set "this" as the current fullscreen window
    ourFullscreenWindow = this;

    // SetPixelFormat can fail (really ?) if window style doesn't contain these flags
    long Style = GetWindowLong(myHandle, GWL_STYLE);
    SetWindowLong(myHandle, GWL_STYLE, Style | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
}


////////////////////////////////////////////////////////////
/// Construct the context from graphics settings
////////////////////////////////////////////////////////////
void WindowImplWin32::CreateContext(const VideoMode& Mode, WindowSettings& Params)
{
    // Get the device context attached to the window
    myDeviceContext = GetDC(myHandle);
    if (myDeviceContext == NULL)
    {
        std::cerr << "Failed to get device context of window -- cannot create OpenGL context" << std::endl;
        return;
    }

    // Let's find a suitable pixel format -- first try with antialiasing
    int BestFormat = 0;
    if (Params.AntialiasingLevel > 0)
    {
        // Get the wglChoosePixelFormatARB function (it is an extension)
        PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB"));

        // Define the basic attributes we want for our window
        int IntAttributes[] =
        {
            WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
		    WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
		    WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB,
		    WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
            WGL_SAMPLE_BUFFERS_ARB, (Params.AntialiasingLevel ? GL_TRUE : GL_FALSE),
		    WGL_SAMPLES_ARB,        Params.AntialiasingLevel,
		    0,                      0
        };

        // Let's check how many formats are supporting our requirements
        int   Formats[128];
	    UINT  NbFormats;
	    float FloatAttributes[] = {0, 0};
	    bool  IsValid = wglChoosePixelFormatARB(myDeviceContext, IntAttributes, FloatAttributes, sizeof(Formats) / sizeof(*Formats), Formats, &NbFormats) != 0;
        if (!IsValid || (NbFormats == 0))
        {
            if (Params.AntialiasingLevel > 2)
            {
                // No format matching our needs : reduce the multisampling level
                std::cerr << "Failed to find a pixel format supporting "
                          << Params.AntialiasingLevel << " antialiasing levels ; trying with 2 levels" << std::endl;

                Params.AntialiasingLevel = IntAttributes[1] = 2;
	            IsValid = wglChoosePixelFormatARB(myDeviceContext, IntAttributes, FloatAttributes, sizeof(Formats) / sizeof(*Formats), Formats, &NbFormats) != 0;
            }

            if (!IsValid || (NbFormats == 0))
            {
                // Cannot find any pixel format supporting multisampling ; disabling antialiasing
                std::cerr << "Failed to find a pixel format supporting antialiasing ; antialiasing will be disabled" << std::endl;
                Params.AntialiasingLevel = 0;
            }
        }

        // Get the best format among the returned ones
        if (IsValid && (NbFormats > 0))
        {
            int BestScore = 0xFFFF;
            for (UINT i = 0; i < NbFormats; ++i)
            {
                // Get the current format's attributes
                PIXELFORMATDESCRIPTOR Attribs;
                Attribs.nSize    = sizeof(PIXELFORMATDESCRIPTOR);
                Attribs.nVersion = 1;
                DescribePixelFormat(myDeviceContext, Formats[i], sizeof(PIXELFORMATDESCRIPTOR), &Attribs);

                // Evaluate the current configuration
                int Color = Attribs.cRedBits + Attribs.cGreenBits + Attribs.cBlueBits + Attribs.cAlphaBits;
                int Score = EvaluateConfig(Mode, Params, Color, Attribs.cDepthBits, Attribs.cStencilBits, Params.AntialiasingLevel);

                // Keep it if it's better than the current best
                if (Score < BestScore)
                {
                    BestScore  = Score;
                    BestFormat = Formats[i];
                }
            }
        }
    }

    // Find a pixel format with no antialiasing, if not needed or not supported
    if (BestFormat == 0)
    {
        // Setup a pixel format descriptor from the rendering settings
        PIXELFORMATDESCRIPTOR PixelDescriptor;
        ZeroMemory(&PixelDescriptor, sizeof(PIXELFORMATDESCRIPTOR));
        PixelDescriptor.nSize        = sizeof(PIXELFORMATDESCRIPTOR);
        PixelDescriptor.nVersion     = 1;
        PixelDescriptor.iLayerType   = PFD_MAIN_PLANE;
        PixelDescriptor.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
        PixelDescriptor.iPixelType   = PFD_TYPE_RGBA;
        PixelDescriptor.cColorBits   = static_cast<BYTE>(Mode.BitsPerPixel);
        PixelDescriptor.cDepthBits   = static_cast<BYTE>(Params.DepthBits);
        PixelDescriptor.cStencilBits = static_cast<BYTE>(Params.StencilBits);

        // Get the pixel format that best matches our requirements
        BestFormat = ChoosePixelFormat(myDeviceContext, &PixelDescriptor);
        if (BestFormat == 0)
        {
            std::cerr << "Failed to find a suitable pixel format for device context -- cannot create OpenGL context" << std::endl;
            return;
        }
    }

    // Extract the depth and stencil bits from the chosen format
    PIXELFORMATDESCRIPTOR ActualFormat;
    ActualFormat.nSize    = sizeof(PIXELFORMATDESCRIPTOR);
    ActualFormat.nVersion = 1;
    DescribePixelFormat(myDeviceContext, BestFormat, sizeof(PIXELFORMATDESCRIPTOR), &ActualFormat);
    Params.DepthBits   = ActualFormat.cDepthBits;
    Params.StencilBits = ActualFormat.cStencilBits;

    // Set the chosen pixel format
    if (!SetPixelFormat(myDeviceContext, BestFormat, &ActualFormat))
    {
        std::cerr << "Failed to set pixel format for device context -- cannot create OpenGL context" << std::endl;
        return;
    }

    // Create the OpenGL context from the device context
    myGLContext = wglCreateContext(myDeviceContext);
    if (myGLContext == NULL)
    {
        std::cerr << "Failed to create an OpenGL context for this window" << std::endl;
        return;
    }

    // Share display lists with other contexts
    HGLRC CurrentContext = wglGetCurrentContext();
    if (CurrentContext)
        wglShareLists(CurrentContext, myGLContext);

    // Activate the context
    SetActive(true);

    // Enable multisampling
    if (Params.AntialiasingLevel > 0)
        glEnable(GL_MULTISAMPLE_ARB);
}


////////////////////////////////////////////////////////////
/// Free all the graphical resources attached to the window
////////////////////////////////////////////////////////////
void WindowImplWin32::Cleanup()
{
    // Restore the previous video mode (in case we were running in fullscreen)
    if (ourFullscreenWindow == this)
    {
        ChangeDisplaySettings(NULL, 0);
        ourFullscreenWindow = NULL;
    }

    // Unhide the mouse cursor (in case it was hidden)
    ShowMouseCursor(true);

    // Destroy the OpenGL context
    if (myGLContext)
    {
        // Unbind the context before destroying it
        SetActive(false);

        wglDeleteContext(myGLContext);
        myGLContext = NULL;
    }
    if (myDeviceContext)
    {
        ReleaseDC(myHandle, myDeviceContext);
        myDeviceContext = NULL;
    }
}


////////////////////////////////////////////////////////////
/// Process a Win32 event
////////////////////////////////////////////////////////////
void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
{
    // Don't process any message until window is created
    if (myHandle == NULL)
        return;

    switch (Message)
    {
        // Destroy event
        case WM_DESTROY :
        {
            // Here we must cleanup resources !
            Cleanup();
            break;
        }

        // Set cursor event
        case WM_SETCURSOR :
        {
            // The mouse has moved, if the cursor is in our window we must refresh the cursor
            if (LOWORD(LParam) == HTCLIENT)
                SetCursor(myCursor);

            break;
        }

        // Close event
        case WM_CLOSE :
        {
            Event Evt;
            Evt.Type = Event::Closed;
            SendEvent(Evt);
            break;
        }

        // Resize event
        case WM_SIZE :
        {
            // Update window size
            RECT Rect;
            GetClientRect(myHandle, &Rect);
            myWidth  = Rect.right - Rect.left;
            myHeight = Rect.bottom - Rect.top;

            Event Evt;
            Evt.Type        = Event::Resized;
            Evt.Size.Width  = myWidth;
            Evt.Size.Height = myHeight;
            SendEvent(Evt);
            break;
        }

        // Gain focus event
        case WM_SETFOCUS :
        {
            Event Evt;
            Evt.Type = Event::GainedFocus;
            SendEvent(Evt);
            break;
        }

        // Lost focus event
        case WM_KILLFOCUS :
        {
            Event Evt;
            Evt.Type = Event::LostFocus;
            SendEvent(Evt);
            break;
        }

        // Text event
        case WM_CHAR :
        {
            Event Evt;
            Evt.Type = Event::TextEntered;
            Evt.Text.Unicode = static_cast<Uint32>(WParam);
            SendEvent(Evt);
            break;
        }

        // Keydown event
        case WM_KEYDOWN :
        case WM_SYSKEYDOWN :
        {
            if (myKeyRepeatEnabled || ((LParam & (1 << 30)) == 0))
            {
                Event Evt;
                Evt.Type        = Event::KeyPressed;
                Evt.Key.Code    = (WParam == VK_SHIFT) ? GetShiftState(true) : VirtualKeyCodeToSF(WParam, LParam);
                Evt.Key.Alt     = HIWORD(GetAsyncKeyState(VK_MENU))    != 0;
                Evt.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
                Evt.Key.Shift   = HIWORD(GetAsyncKeyState(VK_SHIFT))   != 0;
                SendEvent(Evt);
            }
            break;
        }

        // Keyup event
        case WM_KEYUP :
        case WM_SYSKEYUP :
        {
            Event Evt;
            Evt.Type        = Event::KeyReleased;
            Evt.Key.Code    = (WParam == VK_SHIFT) ? GetShiftState(false) : VirtualKeyCodeToSF(WParam, LParam);
            Evt.Key.Alt     = HIWORD(GetAsyncKeyState(VK_MENU))    != 0;
            Evt.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
            Evt.Key.Shift   = HIWORD(GetAsyncKeyState(VK_SHIFT))   != 0;
            SendEvent(Evt);
            break;
        }

        // Mouse wheel event
        case WM_MOUSEWHEEL :
        {
            Event Evt;
            Evt.Type = Event::MouseWheelMoved;
            Evt.MouseWheel.Delta = static_cast<Int16>(HIWORD(WParam)) / 120;
            SendEvent(Evt);
            break;
        }

        // Mouse left button down event
        case WM_LBUTTONDOWN :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonPressed;
            Evt.MouseButton.Button = Mouse::Left;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse left button up event
        case WM_LBUTTONUP :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonReleased;
            Evt.MouseButton.Button = Mouse::Left;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse right button down event
        case WM_RBUTTONDOWN :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonPressed;
            Evt.MouseButton.Button = Mouse::Right;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse right button up event
        case WM_RBUTTONUP :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonReleased;
            Evt.MouseButton.Button = Mouse::Right;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse wheel button down event
        case WM_MBUTTONDOWN :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonPressed;
            Evt.MouseButton.Button = Mouse::Middle;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse wheel button up event
        case WM_MBUTTONUP :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonReleased;
            Evt.MouseButton.Button = Mouse::Middle;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse X button down event
        case WM_XBUTTONDOWN :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonPressed;
            Evt.MouseButton.Button = HIWORD(WParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse X button up event
        case WM_XBUTTONUP :
        {
            Event Evt;
            Evt.Type               = Event::MouseButtonReleased;
            Evt.MouseButton.Button = HIWORD(WParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
            Evt.MouseButton.X      = LOWORD(LParam);
            Evt.MouseButton.Y      = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse move event
        case WM_MOUSEMOVE :
        {
            // Check if we need to generate a MouseEntered event
            if (!myIsCursorIn)
            {
                TRACKMOUSEEVENT MouseEvent;
                MouseEvent.cbSize    = sizeof(TRACKMOUSEEVENT);
                MouseEvent.hwndTrack = myHandle;
                MouseEvent.dwFlags   = TME_LEAVE;
                TrackMouseEvent(&MouseEvent);

                myIsCursorIn = true;

                Event Evt;
                Evt.Type = Event::MouseEntered;
                SendEvent(Evt);
            }

            Event Evt;
            Evt.Type        = Event::MouseMoved;
            Evt.MouseMove.X = LOWORD(LParam);
            Evt.MouseMove.Y = HIWORD(LParam);
            SendEvent(Evt);
            break;
        }

        // Mouse leave event
        case WM_MOUSELEAVE :
        {
            myIsCursorIn = false;

            Event Evt;
            Evt.Type = Event::MouseLeft;
            SendEvent(Evt);
            break;
        }
    }
}


////////////////////////////////////////////////////////////
/// Check the state of the shift keys on a key event,
/// and return the corresponding SF key code
////////////////////////////////////////////////////////////
Key::Code WindowImplWin32::GetShiftState(bool KeyDown)
{
    static bool LShiftPrevDown = false;
    static bool RShiftPrevDown = false;

    bool LShiftDown = (HIWORD(GetAsyncKeyState(VK_LSHIFT)) != 0);
    bool RShiftDown = (HIWORD(GetAsyncKeyState(VK_RSHIFT)) != 0);

    Key::Code Code = Key::Code(0);
    if (KeyDown)
    {
        if      (!LShiftPrevDown && LShiftDown) Code = Key::LShift;
        else if (!RShiftPrevDown && RShiftDown) Code = Key::RShift;
    }
    else
    {
        if      (LShiftPrevDown && !LShiftDown) Code = Key::LShift;
        else if (RShiftPrevDown && !RShiftDown) Code = Key::RShift;
    }

    LShiftPrevDown = LShiftDown;
    RShiftPrevDown = RShiftDown;

    return Code;
}


////////////////////////////////////////////////////////////
/// Convert a Win32 virtual key code to a SFML key code
////////////////////////////////////////////////////////////
Key::Code WindowImplWin32::VirtualKeyCodeToSF(WPARAM VirtualKey, LPARAM Flags)
{
    switch (VirtualKey)
    {
        // VK_SHIFT is handled by the GetShiftState function
        case VK_MENU :       return (Flags & (1 << 24)) ? Key::RAlt     : Key::LAlt;
        case VK_CONTROL :    return (Flags & (1 << 24)) ? Key::RControl : Key::LControl;
        case VK_LWIN :       return Key::LSystem;
        case VK_RWIN :       return Key::RSystem;
        case VK_APPS :       return Key::Menu;
        case VK_OEM_1 :      return Key::SemiColon;
        case VK_OEM_2 :      return Key::Slash;
        case VK_OEM_PLUS :   return Key::Equal;
        case VK_OEM_MINUS :  return Key::Dash;
        case VK_OEM_4 :      return Key::LBracket;
        case VK_OEM_6 :      return Key::RBracket;
        case VK_OEM_COMMA :  return Key::Comma;
        case VK_OEM_PERIOD : return Key::Period;
        case VK_OEM_7 :      return Key::Quote;
        case VK_OEM_5 :      return Key::BackSlash;
        case VK_OEM_3 :      return Key::Tilde;
        case VK_ESCAPE :     return Key::Escape;
        case VK_SPACE :      return Key::Space;
        case VK_RETURN :     return Key::Return;
        case VK_BACK :       return Key::Back;
        case VK_TAB :        return Key::Tab;
        case VK_PRIOR :      return Key::PageUp;
        case VK_NEXT :       return Key::PageDown;
        case VK_END :        return Key::End;
        case VK_HOME :       return Key::Home;
        case VK_INSERT :     return Key::Insert;
        case VK_DELETE :     return Key::Delete;
        case VK_ADD :        return Key::Add;
        case VK_SUBTRACT :   return Key::Subtract;
        case VK_MULTIPLY :   return Key::Multiply;
        case VK_DIVIDE :     return Key::Divide;
        case VK_PAUSE :      return Key::Pause;
        case VK_F1 :         return Key::F1;
        case VK_F2 :         return Key::F2;
        case VK_F3 :         return Key::F3;
        case VK_F4 :         return Key::F4;
        case VK_F5 :         return Key::F5;
        case VK_F6 :         return Key::F6;
        case VK_F7 :         return Key::F7;
        case VK_F8 :         return Key::F8;
        case VK_F9 :         return Key::F9;
        case VK_F10 :        return Key::F10;
        case VK_F11 :        return Key::F11;
        case VK_F12 :        return Key::F12;
        case VK_F13 :        return Key::F13;
        case VK_F14 :        return Key::F14;
        case VK_F15 :        return Key::F15;
        case VK_LEFT :       return Key::Left;
        case VK_RIGHT :      return Key::Right;
        case VK_UP :         return Key::Up;
        case VK_DOWN :       return Key::Down;
        case VK_NUMPAD0 :    return Key::Numpad0;
        case VK_NUMPAD1 :    return Key::Numpad1;
        case VK_NUMPAD2 :    return Key::Numpad2;
        case VK_NUMPAD3 :    return Key::Numpad3;
        case VK_NUMPAD4 :    return Key::Numpad4;
        case VK_NUMPAD5 :    return Key::Numpad5;
        case VK_NUMPAD6 :    return Key::Numpad6;
        case VK_NUMPAD7 :    return Key::Numpad7;
        case VK_NUMPAD8 :    return Key::Numpad8;
        case VK_NUMPAD9 :    return Key::Numpad9;
        case 'A' :           return Key::A;
        case 'Z' :           return Key::Z;
        case 'E' :           return Key::E;
        case 'R' :           return Key::R;
        case 'T' :           return Key::T;
        case 'Y' :           return Key::Y;
        case 'U' :           return Key::U;
        case 'I' :           return Key::I;
        case 'O' :           return Key::O;
        case 'P' :           return Key::P;
        case 'Q' :           return Key::Q;
        case 'S' :           return Key::S;
        case 'D' :           return Key::D;
        case 'F' :           return Key::F;
        case 'G' :           return Key::G;
        case 'H' :           return Key::H;
        case 'J' :           return Key::J;
        case 'K' :           return Key::K;
        case 'L' :           return Key::L;
        case 'M' :           return Key::M;
        case 'W' :           return Key::W;
        case 'X' :           return Key::X;
        case 'C' :           return Key::C;
        case 'V' :           return Key::V;
        case 'B' :           return Key::B;
        case 'N' :           return Key::N;
        case '0' :           return Key::Num0;
        case '1' :           return Key::Num1;
        case '2' :           return Key::Num2;
        case '3' :           return Key::Num3;
        case '4' :           return Key::Num4;
        case '5' :           return Key::Num5;
        case '6' :           return Key::Num6;
        case '7' :           return Key::Num7;
        case '8' :           return Key::Num8;
        case '9' :           return Key::Num9;
    }

    return Key::Code(0);
}


////////////////////////////////////////////////////////////
/// Check if the current version of the OS supports unicode
/// messages and functions ; Windows 95/98/Me may not support
/// it, whereas Windows NT/2000/XP/Vista will
////////////////////////////////////////////////////////////
bool WindowImplWin32::HasUnicodeSupport()
{
    OSVERSIONINFO VersionInfo;
    ZeroMemory(&VersionInfo, sizeof(VersionInfo));
    VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);

    if (GetVersionEx(&VersionInfo))
    {
        return VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT;
    }
    else
    {
        return false;
    }
}


////////////////////////////////////////////////////////////
/// Function called whenever one of our windows receives a message
////////////////////////////////////////////////////////////
LRESULT CALLBACK WindowImplWin32::GlobalOnEvent(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam)
{
    // Associate handle and Window instance when the creation message is received
    if (Message == WM_CREATE)
    {
        // Get WindowImplWin32 instance (it was passed as the last argument of CreateWindow)
        long This = reinterpret_cast<long>(reinterpret_cast<CREATESTRUCT*>(LParam)->lpCreateParams);

        // Set as the "user data" parameter of the window
        SetWindowLongPtr(Handle, GWLP_USERDATA, This);
    }

    // Get the WindowImpl instance corresponding to the window handle
    WindowImplWin32* Window = reinterpret_cast<WindowImplWin32*>(GetWindowLongPtr(Handle, GWLP_USERDATA));

    // Forward the event to the appropriate function
    if (Window)
    {
        Window->ProcessEvent(Message, WParam, LParam);

        if (Window->myCallback)
            return CallWindowProc(reinterpret_cast<WNDPROC>(Window->myCallback), Handle, Message, WParam, LParam);
    }

    // We don't forward the WM_CLOSE message to prevent the OS from automatically destroying the window
    if (Message == WM_CLOSE)
        return 0;

    static const bool HasUnicode = HasUnicodeSupport();
    return HasUnicode ? DefWindowProcW(Handle, Message, WParam, LParam) :
                        DefWindowProcA(Handle, Message, WParam, LParam);
}

} // namespace priv

} // namespace sf