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