src/core/winrt/SDL_winrtapp_direct3d.cpp
author David Ludwig <dludwig@pobox.com>
Mon, 24 Mar 2014 22:51:03 -0400
changeset 8679 dd52820b7f5c
parent 8678 7149b02f106b
child 8755 f2fc45874b9c
permissions -rw-r--r--
WinRT: Call IDXGIDevice3::Trim before app-suspend, as required on Windows 8.1

Thanks to Sylvain Becker for pointing this out!
     1 /*
     2   Simple DirectMedia Layer
     3   Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
     4 
     5   This software is provided 'as-is', without any express or implied
     6   warranty.  In no event will the authors be held liable for any damages
     7   arising from the use of this software.
     8 
     9   Permission is granted to anyone to use this software for any purpose,
    10   including commercial applications, and to alter it and redistribute it
    11   freely, subject to the following restrictions:
    12 
    13   1. The origin of this software must not be misrepresented; you must not
    14      claim that you wrote the original software. If you use this software
    15      in a product, an acknowledgment in the product documentation would be
    16      appreciated but is not required.
    17   2. Altered source versions must be plainly marked as such, and must not be
    18      misrepresented as being the original software.
    19   3. This notice may not be removed or altered from any source distribution.
    20 */
    21 #include "../../SDL_internal.h"
    22 
    23 /* Standard C++11 includes */
    24 #include <functional>
    25 #include <string>
    26 #include <sstream>
    27 using namespace std;
    28 
    29 
    30 /* Windows includes */
    31 #include "ppltasks.h"
    32 using namespace concurrency;
    33 using namespace Windows::ApplicationModel;
    34 using namespace Windows::ApplicationModel::Core;
    35 using namespace Windows::ApplicationModel::Activation;
    36 using namespace Windows::Devices::Input;
    37 using namespace Windows::Graphics::Display;
    38 using namespace Windows::Foundation;
    39 using namespace Windows::System;
    40 using namespace Windows::UI::Core;
    41 using namespace Windows::UI::Input;
    42 
    43 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
    44 using namespace Windows::Phone::UI::Input;
    45 #endif
    46 
    47 
    48 /* SDL includes */
    49 extern "C" {
    50 #include "../../SDL_internal.h"
    51 #include "SDL_assert.h"
    52 #include "SDL_events.h"
    53 #include "SDL_hints.h"
    54 #include "SDL_log.h"
    55 #include "SDL_main.h"
    56 #include "SDL_stdinc.h"
    57 #include "SDL_render.h"
    58 #include "../../video/SDL_sysvideo.h"
    59 //#include "../../SDL_hints_c.h"
    60 #include "../../events/SDL_events_c.h"
    61 #include "../../events/SDL_keyboard_c.h"
    62 #include "../../events/SDL_mouse_c.h"
    63 #include "../../events/SDL_windowevents_c.h"
    64 #include "../../render/SDL_sysrender.h"
    65 #include "../windows/SDL_windows.h"
    66 }
    67 
    68 #include "../../video/winrt/SDL_winrtevents_c.h"
    69 #include "../../video/winrt/SDL_winrtvideo_cpp.h"
    70 #include "SDL_winrtapp_common.h"
    71 #include "SDL_winrtapp_direct3d.h"
    72 
    73 #if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
    74 /* Calling IDXGIDevice3::Trim on the active Direct3D 11.x device is necessary
    75  * when Windows 8.1 apps are about to get suspended.
    76  */
    77 extern "C" void D3D11_Trim(SDL_Renderer *);
    78 #endif
    79 
    80 
    81 // Compile-time debugging options:
    82 // To enable, uncomment; to disable, comment them out.
    83 //#define LOG_POINTER_EVENTS 1
    84 //#define LOG_WINDOW_EVENTS 1
    85 //#define LOG_ORIENTATION_EVENTS 1
    86 
    87 
    88 // HACK, DLudwig: record a reference to the global, WinRT 'app'/view.
    89 // SDL/WinRT will use this throughout its code.
    90 //
    91 // TODO, WinRT: consider replacing SDL_WinRTGlobalApp with something
    92 // non-global, such as something created inside
    93 // SDL_InitSubSystem(SDL_INIT_VIDEO), or something inside
    94 // SDL_CreateWindow().
    95 SDL_WinRTApp ^ SDL_WinRTGlobalApp = nullptr;
    96 
    97 ref class SDLApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
    98 {
    99 public:
   100     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
   101 };
   102 
   103 IFrameworkView^ SDLApplicationSource::CreateView()
   104 {
   105     // TODO, WinRT: see if this function (CreateView) can ever get called
   106     // more than once.  For now, just prevent it from ever assigning
   107     // SDL_WinRTGlobalApp more than once.
   108     SDL_assert(!SDL_WinRTGlobalApp);
   109     SDL_WinRTApp ^ app = ref new SDL_WinRTApp();
   110     if (!SDL_WinRTGlobalApp)
   111     {
   112         SDL_WinRTGlobalApp = app;
   113     }
   114     return app;
   115 }
   116 
   117 int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **))
   118 {
   119     WINRT_SDLAppEntryPoint = mainFunction;
   120     auto direct3DApplicationSource = ref new SDLApplicationSource();
   121     CoreApplication::Run(direct3DApplicationSource);
   122     return 0;
   123 }
   124 
   125 static void WINRT_SetDisplayOrientationsPreference(void *userdata, const char *name, const char *oldValue, const char *newValue)
   126 {
   127     SDL_assert(SDL_strcmp(name, SDL_HINT_ORIENTATIONS) == 0);
   128 
   129     // Start with no orientation flags, then add each in as they're parsed
   130     // from newValue.
   131     unsigned int orientationFlags = 0;
   132     if (newValue) {
   133         std::istringstream tokenizer(newValue);
   134         while (!tokenizer.eof()) {
   135             std::string orientationName;
   136             std::getline(tokenizer, orientationName, ' ');
   137             if (orientationName == "LandscapeLeft") {
   138                 orientationFlags |= (unsigned int) DisplayOrientations::LandscapeFlipped;
   139             } else if (orientationName == "LandscapeRight") {
   140                 orientationFlags |= (unsigned int) DisplayOrientations::Landscape;
   141             } else if (orientationName == "Portrait") {
   142                 orientationFlags |= (unsigned int) DisplayOrientations::Portrait;
   143             } else if (orientationName == "PortraitUpsideDown") {
   144                 orientationFlags |= (unsigned int) DisplayOrientations::PortraitFlipped;
   145             }
   146         }
   147     }
   148 
   149     // If no valid orientation flags were specified, use a reasonable set of defaults:
   150     if (!orientationFlags) {
   151         // TODO, WinRT: consider seeing if an app's default orientation flags can be found out via some API call(s).
   152         orientationFlags = (unsigned int) ( \
   153             DisplayOrientations::Landscape |
   154             DisplayOrientations::LandscapeFlipped |
   155             DisplayOrientations::Portrait |
   156             DisplayOrientations::PortraitFlipped);
   157     }
   158 
   159     // Set the orientation/rotation preferences.  Please note that this does
   160     // not constitute a 100%-certain lock of a given set of possible
   161     // orientations.  According to Microsoft's documentation on WinRT [1]
   162     // when a device is not capable of being rotated, Windows may ignore
   163     // the orientation preferences, and stick to what the device is capable of
   164     // displaying.
   165     //
   166     // [1] Documentation on the 'InitialRotationPreference' setting for a
   167     // Windows app's manifest file describes how some orientation/rotation
   168     // preferences may be ignored.  See
   169     // http://msdn.microsoft.com/en-us/library/windows/apps/hh700343.aspx
   170     // for details.  Microsoft's "Display orientation sample" also gives an
   171     // outline of how Windows treats device rotation
   172     // (http://code.msdn.microsoft.com/Display-Orientation-Sample-19a58e93).
   173 #if NTDDI_VERSION > NTDDI_WIN8
   174     DisplayInformation::AutoRotationPreferences = (DisplayOrientations) orientationFlags;
   175 #else
   176     DisplayProperties::AutoRotationPreferences = (DisplayOrientations) orientationFlags;
   177 #endif
   178 }
   179 
   180 static void
   181 WINRT_ProcessWindowSizeChange()
   182 {
   183     SDL_VideoDevice *_this = SDL_GetVideoDevice();
   184 
   185     // Make the new window size be the one true fullscreen mode.
   186     // This change was initially done, in part, to allow the Direct3D 11.1
   187     // renderer to receive window-resize events as a device rotates.
   188     // Before, rotating a device from landscape, to portrait, and then
   189     // back to landscape would cause the Direct3D 11.1 swap buffer to
   190     // not get resized appropriately.  SDL would, on the rotation from
   191     // landscape to portrait, re-resize the SDL window to it's initial
   192     // size (landscape).  On the subsequent rotation, SDL would drop the
   193     // window-resize event as it appeared the SDL window didn't change
   194     // size, and the Direct3D 11.1 renderer wouldn't resize its swap
   195     // chain.
   196     SDL_DisplayMode newDisplayMode;
   197     if (WINRT_CalcDisplayModeUsingNativeWindow(&newDisplayMode) != 0) {
   198         return;
   199     }
   200 
   201     // Make note of the old display mode, and it's old driverdata.
   202     SDL_DisplayMode oldDisplayMode;
   203     SDL_zero(oldDisplayMode);
   204     if (_this) {
   205         oldDisplayMode = _this->displays[0].desktop_mode;
   206     }
   207 
   208     // Setup the new display mode in the appropriate spots.
   209     if (_this) {
   210         // Make a full copy of the display mode for display_modes[0],
   211         // one with with a separately malloced 'driverdata' field.
   212         // SDL_VideoQuit(), if called, will attempt to free the driverdata
   213         // fields in 'desktop_mode' and each entry in the 'display_modes'
   214         // array.
   215         if (_this->displays[0].display_modes[0].driverdata) {
   216             // Free the previous mode's memory
   217             SDL_free(_this->displays[0].display_modes[0].driverdata);
   218             _this->displays[0].display_modes[0].driverdata = NULL;
   219         }
   220         if (WINRT_DuplicateDisplayMode(&(_this->displays[0].display_modes[0]), &newDisplayMode) != 0) {
   221             // Uh oh, something went wrong.  A malloc call probably failed.
   222             SDL_free(newDisplayMode.driverdata);
   223             return;
   224         }
   225 
   226         // Install 'newDisplayMode' into 'current_mode' and 'desktop_mode'.
   227         _this->displays[0].current_mode = newDisplayMode;
   228         _this->displays[0].desktop_mode = newDisplayMode;
   229     }
   230 
   231     if (WINRT_GlobalSDLWindow) {
   232         // Send a window-resize event to the rest of SDL, and to apps:
   233         SDL_SendWindowEvent(
   234             WINRT_GlobalSDLWindow,
   235             SDL_WINDOWEVENT_RESIZED,
   236             newDisplayMode.w,
   237             newDisplayMode.h);
   238 
   239 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   240         // HACK: On Windows Phone, make sure that orientation changes from
   241         // Landscape to LandscapeFlipped, Portrait to PortraitFlipped,
   242         // or vice-versa on either of those two, lead to the Direct3D renderer
   243         // getting updated.
   244         const DisplayOrientations oldOrientation = ((SDL_DisplayModeData *)oldDisplayMode.driverdata)->currentOrientation;
   245         const DisplayOrientations newOrientation = ((SDL_DisplayModeData *)newDisplayMode.driverdata)->currentOrientation;
   246 
   247         if ((oldOrientation == DisplayOrientations::Landscape && newOrientation == DisplayOrientations::LandscapeFlipped) ||
   248             (oldOrientation == DisplayOrientations::LandscapeFlipped && newOrientation == DisplayOrientations::Landscape) ||
   249             (oldOrientation == DisplayOrientations::Portrait && newOrientation == DisplayOrientations::PortraitFlipped) ||
   250             (oldOrientation == DisplayOrientations::PortraitFlipped && newOrientation == DisplayOrientations::Portrait))
   251         {
   252             // One of the reasons this event is getting sent out is because SDL
   253             // will ignore requests to send out SDL_WINDOWEVENT_RESIZED events
   254             // if and when the event size doesn't change (and the Direct3D 11.1
   255             // renderer doesn't get the memo).
   256             //
   257             // Make sure that the display/window size really didn't change.  If
   258             // it did, then a SDL_WINDOWEVENT_SIZE_CHANGED event got sent, and
   259             // the Direct3D 11.1 renderer picked it up, presumably.
   260             if (oldDisplayMode.w == newDisplayMode.w &&
   261                 oldDisplayMode.h == newDisplayMode.h)
   262             {
   263                 SDL_SendWindowEvent(
   264                     WINRT_GlobalSDLWindow,
   265                     SDL_WINDOWEVENT_SIZE_CHANGED,
   266                     newDisplayMode.w,
   267                     newDisplayMode.h);
   268             }
   269         }
   270 #endif
   271     }
   272     
   273     // Finally, free the 'driverdata' field of the old 'desktop_mode'.
   274     if (oldDisplayMode.driverdata) {
   275         SDL_free(oldDisplayMode.driverdata);
   276         oldDisplayMode.driverdata = NULL;
   277     }
   278 }
   279 
   280 SDL_WinRTApp::SDL_WinRTApp() :
   281     m_windowClosed(false),
   282     m_windowVisible(true)
   283 {
   284 }
   285 
   286 void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView)
   287 {
   288     applicationView->Activated +=
   289         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &SDL_WinRTApp::OnActivated);
   290 
   291     CoreApplication::Suspending +=
   292         ref new EventHandler<SuspendingEventArgs^>(this, &SDL_WinRTApp::OnSuspending);
   293 
   294     CoreApplication::Resuming +=
   295         ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnResuming);
   296 
   297     CoreApplication::Exiting +=
   298         ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnExiting);
   299 }
   300 
   301 #if NTDDI_VERSION > NTDDI_WIN8
   302 void SDL_WinRTApp::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
   303 #else
   304 void SDL_WinRTApp::OnOrientationChanged(Object^ sender)
   305 #endif
   306 {
   307 #if LOG_ORIENTATION_EVENTS==1
   308     CoreWindow^ window = CoreWindow::GetForCurrentThread();
   309     if (window) {
   310         SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Size={%f,%f}\n",
   311             __FUNCTION__,
   312             (int)DisplayProperties::CurrentOrientation,
   313             (int)DisplayProperties::NativeOrientation,
   314             (int)DisplayProperties::AutoRotationPreferences,
   315             window->Bounds.Width,
   316             window->Bounds.Height);
   317     } else {
   318         SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d\n",
   319             __FUNCTION__,
   320             (int)DisplayProperties::CurrentOrientation,
   321             (int)DisplayProperties::NativeOrientation,
   322             (int)DisplayProperties::AutoRotationPreferences);
   323     }
   324 #endif
   325 
   326 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   327     // On Windows Phone, treat an orientation change as a change in window size.
   328     // The native window's size doesn't seem to change, however SDL will simulate
   329     // a window size change.
   330     WINRT_ProcessWindowSizeChange();
   331 #endif
   332 }
   333 
   334 void SDL_WinRTApp::SetWindow(CoreWindow^ window)
   335 {
   336 #if LOG_WINDOW_EVENTS==1
   337     SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window Size={%f,%f}\n",
   338         __FUNCTION__,
   339         (int)DisplayProperties::CurrentOrientation,
   340         (int)DisplayProperties::NativeOrientation,
   341         (int)DisplayProperties::AutoRotationPreferences,
   342         window->Bounds.Width,
   343         window->Bounds.Height);
   344 #endif
   345 
   346     window->SizeChanged += 
   347         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &SDL_WinRTApp::OnWindowSizeChanged);
   348 
   349     window->VisibilityChanged +=
   350         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &SDL_WinRTApp::OnVisibilityChanged);
   351 
   352     window->Closed += 
   353         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &SDL_WinRTApp::OnWindowClosed);
   354 
   355 #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
   356     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
   357 #endif
   358 
   359     window->PointerPressed +=
   360         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerPressed);
   361 
   362     window->PointerMoved +=
   363         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerMoved);
   364 
   365     window->PointerReleased +=
   366         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerReleased);
   367 
   368     window->PointerWheelChanged +=
   369         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerWheelChanged);
   370 
   371 #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
   372     // Retrieves relative-only mouse movements:
   373     Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
   374         ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &SDL_WinRTApp::OnMouseMoved);
   375 #endif
   376 
   377     window->KeyDown +=
   378         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyDown);
   379 
   380     window->KeyUp +=
   381         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyUp);
   382 
   383 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   384     HardwareButtons::BackPressed +=
   385         ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
   386 #endif
   387 
   388 #if NTDDI_VERSION > NTDDI_WIN8
   389     DisplayInformation::GetForCurrentView()->OrientationChanged +=
   390         ref new TypedEventHandler<Windows::Graphics::Display::DisplayInformation^, Object^>(this, &SDL_WinRTApp::OnOrientationChanged);
   391 #else
   392     DisplayProperties::OrientationChanged +=
   393         ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged);
   394 #endif
   395 
   396     // Register the hint, SDL_HINT_ORIENTATIONS, with SDL.
   397     // TODO, WinRT: see if an app's default orientation can be found out via WinRT API(s), then set the initial value of SDL_HINT_ORIENTATIONS accordingly.
   398     SDL_AddHintCallback(SDL_HINT_ORIENTATIONS, WINRT_SetDisplayOrientationsPreference, NULL);
   399 
   400 #if WINAPI_FAMILY == WINAPI_FAMILY_APP  // for Windows 8/8.1/RT apps... (and not Phone apps)
   401     // Make sure we know when a user has opened the app's settings pane.
   402     // This is needed in order to display a privacy policy, which needs
   403     // to be done for network-enabled apps, as per Windows Store requirements.
   404     using namespace Windows::UI::ApplicationSettings;
   405     SettingsPane::GetForCurrentView()->CommandsRequested +=
   406         ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>
   407             (this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
   408 #endif
   409 }
   410 
   411 void SDL_WinRTApp::Load(Platform::String^ entryPoint)
   412 {
   413 }
   414 
   415 void SDL_WinRTApp::Run()
   416 {
   417     SDL_SetMainReady();
   418     if (WINRT_SDLAppEntryPoint)
   419     {
   420         // TODO, WinRT: pass the C-style main() a reasonably realistic
   421         // representation of command line arguments.
   422         int argc = 0;
   423         char **argv = NULL;
   424         WINRT_SDLAppEntryPoint(argc, argv);
   425     }
   426 }
   427 
   428 static bool IsSDLWindowEventPending(SDL_WindowEventID windowEventID)
   429 {
   430     SDL_Event events[128];
   431     const int count = SDL_PeepEvents(events, sizeof(events)/sizeof(SDL_Event), SDL_PEEKEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT);
   432     for (int i = 0; i < count; ++i) {
   433         if (events[i].window.event == windowEventID) {
   434             return true;
   435         }
   436     }
   437     return false;
   438 }
   439 
   440 bool SDL_WinRTApp::ShouldWaitForAppResumeEvents()
   441 {
   442     /* Don't wait if the app is visible: */
   443     if (m_windowVisible) {
   444         return false;
   445     }
   446     
   447     /* Don't wait until the window-hide events finish processing.
   448      * Do note that if an app-suspend event is sent (as indicated
   449      * by SDL_APP_WILLENTERBACKGROUND and SDL_APP_DIDENTERBACKGROUND
   450      * events), then this code may be a moot point, as WinRT's
   451      * own event pump (aka ProcessEvents()) will pause regardless
   452      * of what we do here.  This happens on Windows Phone 8, to note.
   453      * Windows 8.x apps, on the other hand, may get a chance to run
   454      * these.
   455      */
   456     if (IsSDLWindowEventPending(SDL_WINDOWEVENT_HIDDEN)) {
   457         return false;
   458     } else if (IsSDLWindowEventPending(SDL_WINDOWEVENT_FOCUS_LOST)) {
   459         return false;
   460     } else if (IsSDLWindowEventPending(SDL_WINDOWEVENT_MINIMIZED)) {
   461         return false;
   462     }
   463 
   464     return true;
   465 }
   466 
   467 void SDL_WinRTApp::PumpEvents()
   468 {
   469     if (!m_windowClosed) {
   470         if (!ShouldWaitForAppResumeEvents()) {
   471             /* This is the normal way in which events should be pumped.
   472              * 'ProcessAllIfPresent' will make ProcessEvents() process anywhere
   473              * from zero to N events, and will then return.
   474              */
   475             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
   476         } else {
   477             /* This style of event-pumping, with 'ProcessOneAndAllPending',
   478              * will cause anywhere from one to N events to be processed.  If
   479              * at least one event is processed, the call will return.  If
   480              * no events are pending, then the call will wait until one is
   481              * available, and will not return (to the caller) until this
   482              * happens!  This should only occur when the app is hidden.
   483              */
   484             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
   485         }
   486     }
   487 }
   488 
   489 void SDL_WinRTApp::Uninitialize()
   490 {
   491 }
   492 
   493 #if WINAPI_FAMILY == WINAPI_FAMILY_APP
   494 void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
   495     Windows::UI::ApplicationSettings::SettingsPane ^p,
   496     Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args)
   497 {
   498     using namespace Platform;
   499     using namespace Windows::UI::ApplicationSettings;
   500     using namespace Windows::UI::Popups;
   501 
   502     String ^privacyPolicyURL = nullptr;     // a URL to an app's Privacy Policy
   503     String ^privacyPolicyLabel = nullptr;   // label/link text
   504     const char *tmpHintValue = NULL;        // SDL_GetHint-retrieved value, used immediately
   505     wchar_t *tmpStr = NULL;                 // used for UTF8 to UCS2 conversion
   506 
   507     // Setup a 'Privacy Policy' link, if one is available (via SDL_GetHint):
   508     tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_URL);
   509     if (tmpHintValue && tmpHintValue[0] != '\0') {
   510         // Convert the privacy policy's URL to UCS2:
   511         tmpStr = WIN_UTF8ToString(tmpHintValue);
   512         privacyPolicyURL = ref new String(tmpStr);
   513         SDL_free(tmpStr);
   514 
   515         // Optionally retrieve custom label-text for the link.  If this isn't
   516         // available, a default value will be used instead.
   517         tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_LABEL);
   518         if (tmpHintValue && tmpHintValue[0] != '\0') {
   519             tmpStr = WIN_UTF8ToString(tmpHintValue);
   520             privacyPolicyLabel = ref new String(tmpStr);
   521             SDL_free(tmpStr);
   522         } else {
   523             privacyPolicyLabel = ref new String(L"Privacy Policy");
   524         }
   525 
   526         // Register the link, along with a handler to be called if and when it is
   527         // clicked:
   528         auto cmd = ref new SettingsCommand(L"privacyPolicy", privacyPolicyLabel,
   529             ref new UICommandInvokedHandler([=](IUICommand ^) {
   530                 Windows::System::Launcher::LaunchUriAsync(ref new Uri(privacyPolicyURL));
   531         }));
   532         args->Request->ApplicationCommands->Append(cmd);
   533     }
   534 }
   535 #endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
   536 
   537 void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
   538 {
   539 #if LOG_WINDOW_EVENTS==1
   540     SDL_Log("%s, size={%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n",
   541         __FUNCTION__,
   542         args->Size.Width, args->Size.Height,
   543         (int)DisplayProperties::CurrentOrientation,
   544         (int)DisplayProperties::NativeOrientation,
   545         (int)DisplayProperties::AutoRotationPreferences,
   546         (WINRT_GlobalSDLWindow ? "yes" : "no"));
   547 #endif
   548 
   549     WINRT_ProcessWindowSizeChange();
   550 }
   551 
   552 void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
   553 {
   554 #if LOG_WINDOW_EVENTS==1
   555     SDL_Log("%s, visible?=%s, WINRT_GlobalSDLWindow?=%s\n",
   556         __FUNCTION__,
   557         (args->Visible ? "yes" : "no"),
   558         (WINRT_GlobalSDLWindow ? "yes" : "no"));
   559 #endif
   560 
   561     m_windowVisible = args->Visible;
   562     if (WINRT_GlobalSDLWindow) {
   563         SDL_bool wasSDLWindowSurfaceValid = WINRT_GlobalSDLWindow->surface_valid;
   564 
   565         if (args->Visible) {
   566             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SHOWN, 0, 0);
   567             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
   568             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_RESTORED, 0, 0);
   569         } else {
   570             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_HIDDEN, 0, 0);
   571             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
   572             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
   573         }
   574 
   575         // HACK: Prevent SDL's window-hide handling code, which currently
   576         // triggers a fake window resize (possibly erronously), from
   577         // marking the SDL window's surface as invalid.
   578         //
   579         // A better solution to this probably involves figuring out if the
   580         // fake window resize can be prevented.
   581         WINRT_GlobalSDLWindow->surface_valid = wasSDLWindowSurfaceValid;
   582     }
   583 }
   584 
   585 void SDL_WinRTApp::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
   586 {
   587 #if LOG_WINDOW_EVENTS==1
   588     SDL_Log("%s\n", __FUNCTION__);
   589 #endif
   590     m_windowClosed = true;
   591 }
   592 
   593 void SDL_WinRTApp::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
   594 {
   595     CoreWindow::GetForCurrentThread()->Activate();
   596 }
   597 
   598 void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
   599 {
   600     // Save app state asynchronously after requesting a deferral. Holding a deferral
   601     // indicates that the application is busy performing suspending operations. Be
   602     // aware that a deferral may not be held indefinitely. After about five seconds,
   603     // the app will be forced to exit.
   604 
   605     // ... but first, let the app know it's about to go to the background.
   606     // The separation of events may be important, given that the deferral
   607     // runs in a separate thread.  This'll make SDL_APP_WILLENTERBACKGROUND
   608     // the only event among the two that runs in the main thread.  Given
   609     // that a few WinRT operations can only be done from the main thread
   610     // (things that access the WinRT CoreWindow are one example of this),
   611     // this could be important.
   612     SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
   613 
   614     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
   615     create_task([this, deferral]()
   616     {
   617         // Send an app did-enter-background event immediately to observers.
   618         // CoreDispatcher::ProcessEvents, which is the backbone on which
   619         // SDL_WinRTApp::PumpEvents is built, will not return to its caller
   620         // once it sends out a suspend event.  Any events posted to SDL's
   621         // event queue won't get received until the WinRT app is resumed.
   622         // SDL_AddEventWatch() may be used to receive app-suspend events on
   623         // WinRT.
   624         SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
   625 
   626         // Let the Direct3D 11 renderer prepare for the app to be backgrounded.
   627         // This is necessary for Windows 8.1, possibly elsewhere in the future.
   628         // More details at: http://msdn.microsoft.com/en-us/library/windows/apps/Hh994929.aspx
   629 #if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
   630         if (WINRT_GlobalSDLWindow) {
   631             SDL_Renderer * renderer = SDL_GetRenderer(WINRT_GlobalSDLWindow);
   632             if (renderer && (SDL_strcmp(renderer->info.name, "direct3d11") == 0)) {
   633                 D3D11_Trim(renderer);
   634             }
   635         }
   636 #endif
   637 
   638         deferral->Complete();
   639     });
   640 }
   641 
   642 void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args)
   643 {
   644     // Restore any data or state that was unloaded on suspend. By default, data
   645     // and state are persisted when resuming from suspend. Note that these events
   646     // do not occur if the app was previously terminated.
   647     SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
   648     SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
   649 }
   650 
   651 void SDL_WinRTApp::OnExiting(Platform::Object^ sender, Platform::Object^ args)
   652 {
   653     SDL_SendAppEvent(SDL_APP_TERMINATING);
   654 }
   655 
   656 static void
   657 WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
   658 {
   659     Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint;
   660     SDL_Log("%s: Position={%f,%f}, Transformed Pos={%f, %f}, MouseWheelDelta=%d, FrameId=%d, PointerId=%d, SDL button=%d\n",
   661         header,
   662         pt->Position.X, pt->Position.Y,
   663         transformedPoint.X, transformedPoint.Y,
   664         pt->Properties->MouseWheelDelta,
   665         pt->FrameId,
   666         pt->PointerId,
   667         WINRT_GetSDLButtonForPointerPoint(pt));
   668 }
   669 
   670 void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
   671 {
   672 #if LOG_POINTER_EVENTS
   673     WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   674 #endif
   675 
   676     WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   677 }
   678 
   679 void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
   680 {
   681 #if LOG_POINTER_EVENTS
   682     WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   683 #endif
   684 
   685     WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   686 }
   687 
   688 void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
   689 {
   690 #if LOG_POINTER_EVENTS
   691     WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   692 #endif
   693 
   694     WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   695 }
   696 
   697 void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args)
   698 {
   699 #if LOG_POINTER_EVENTS
   700     WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   701 #endif
   702 
   703     WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   704 }
   705 
   706 void SDL_WinRTApp::OnMouseMoved(MouseDevice^ mouseDevice, MouseEventArgs^ args)
   707 {
   708     WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args);
   709 }
   710 
   711 void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
   712 {
   713     WINRT_ProcessKeyDownEvent(args);
   714 }
   715 
   716 void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
   717 {
   718     WINRT_ProcessKeyUpEvent(args);
   719 }
   720 
   721 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   722 void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
   723 {
   724     SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_AC_BACK);
   725     SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_AC_BACK);
   726 
   727     const char *hint = SDL_GetHint(SDL_HINT_WINRT_HANDLE_BACK_BUTTON);
   728     if (hint) {
   729         if (*hint == '1') {
   730             args->Handled = true;
   731         }
   732     }
   733 }
   734 #endif
   735