src/core/winrt/SDL_winrtapp_direct3d.cpp
author David Ludwig <dludwig@pobox.com>
Wed, 26 Nov 2014 21:34:15 -0500
changeset 9240 dc4ad21d8596
parent 8757 aeeeb47a5a77
child 9256 9c45fc8605d9
permissions -rw-r--r--
WinRT: added initial SDL_TEXTINPUT support

Further support regarding IME and on-screen keyboards is pending, some of
which might not be 100% compatible with other platforms, given WinRT platform
restrictions. An MSDN article at http://msdn.microsoft.com/en-us/library/windows/apps/hh465404.aspx
indicates that on-screen keyboard display requires that the user first tap on
a Windows/XAML text control.

This change adds basic SDL_TEXTINPUT support, with input coming from hardware
keyboards, at a minimum, and without the need for XAML integration (which is
still pending integration into SDL, by and large).
     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     WINRT_DISPLAY_PROPERTY(AutoRotationPreferences) = (DisplayOrientations) orientationFlags;
   174 }
   175 
   176 static void
   177 WINRT_ProcessWindowSizeChange()
   178 {
   179     SDL_VideoDevice *_this = SDL_GetVideoDevice();
   180 
   181     // Make the new window size be the one true fullscreen mode.
   182     // This change was initially done, in part, to allow the Direct3D 11.1
   183     // renderer to receive window-resize events as a device rotates.
   184     // Before, rotating a device from landscape, to portrait, and then
   185     // back to landscape would cause the Direct3D 11.1 swap buffer to
   186     // not get resized appropriately.  SDL would, on the rotation from
   187     // landscape to portrait, re-resize the SDL window to it's initial
   188     // size (landscape).  On the subsequent rotation, SDL would drop the
   189     // window-resize event as it appeared the SDL window didn't change
   190     // size, and the Direct3D 11.1 renderer wouldn't resize its swap
   191     // chain.
   192     SDL_DisplayMode newDisplayMode;
   193     if (WINRT_CalcDisplayModeUsingNativeWindow(&newDisplayMode) != 0) {
   194         return;
   195     }
   196 
   197     // Make note of the old display mode, and it's old driverdata.
   198     SDL_DisplayMode oldDisplayMode;
   199     SDL_zero(oldDisplayMode);
   200     if (_this) {
   201         oldDisplayMode = _this->displays[0].desktop_mode;
   202     }
   203 
   204     // Setup the new display mode in the appropriate spots.
   205     if (_this) {
   206         // Make a full copy of the display mode for display_modes[0],
   207         // one with with a separately malloced 'driverdata' field.
   208         // SDL_VideoQuit(), if called, will attempt to free the driverdata
   209         // fields in 'desktop_mode' and each entry in the 'display_modes'
   210         // array.
   211         if (_this->displays[0].display_modes[0].driverdata) {
   212             // Free the previous mode's memory
   213             SDL_free(_this->displays[0].display_modes[0].driverdata);
   214             _this->displays[0].display_modes[0].driverdata = NULL;
   215         }
   216         if (WINRT_DuplicateDisplayMode(&(_this->displays[0].display_modes[0]), &newDisplayMode) != 0) {
   217             // Uh oh, something went wrong.  A malloc call probably failed.
   218             SDL_free(newDisplayMode.driverdata);
   219             return;
   220         }
   221 
   222         // Install 'newDisplayMode' into 'current_mode' and 'desktop_mode'.
   223         _this->displays[0].current_mode = newDisplayMode;
   224         _this->displays[0].desktop_mode = newDisplayMode;
   225     }
   226 
   227     if (WINRT_GlobalSDLWindow) {
   228         // If the window size changed, send a resize event to SDL and its host app:
   229         int window_w = 0;
   230         int window_h = 0;
   231         SDL_GetWindowSize(WINRT_GlobalSDLWindow, &window_w, &window_h);
   232         if ((window_w != newDisplayMode.w) || (window_h != newDisplayMode.h)) {
   233             SDL_SendWindowEvent(
   234                 WINRT_GlobalSDLWindow,
   235                 SDL_WINDOWEVENT_RESIZED,
   236                 newDisplayMode.w,
   237                 newDisplayMode.h);
   238         } else {
   239 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   240             // HACK: Make sure that orientation changes
   241             // lead to the Direct3D renderer's viewport getting updated:
   242             //
   243             // For some reason, this doesn't seem to need to be done on Windows 8.x,
   244             // even when going from Landscape to LandscapeFlipped.  It only seems to
   245             // be needed on Windows Phone, at least when I tested on my devices.
   246             // I'm not currently sure why this is, but it seems to work fine. -- David L.
   247             //
   248             // TODO, WinRT: do more extensive research into why orientation changes on Win 8.x don't need D3D changes, or if they might, in some cases
   249             const DisplayOrientations oldOrientation = ((SDL_DisplayModeData *)oldDisplayMode.driverdata)->currentOrientation;
   250             const DisplayOrientations newOrientation = ((SDL_DisplayModeData *)newDisplayMode.driverdata)->currentOrientation;
   251             if (oldOrientation != newOrientation)
   252             {
   253                 SDL_SendWindowEvent(
   254                     WINRT_GlobalSDLWindow,
   255                     SDL_WINDOWEVENT_SIZE_CHANGED,
   256                     newDisplayMode.w,
   257                     newDisplayMode.h);
   258             }
   259 #endif
   260         }
   261     }
   262     
   263     // Finally, free the 'driverdata' field of the old 'desktop_mode'.
   264     if (oldDisplayMode.driverdata) {
   265         SDL_free(oldDisplayMode.driverdata);
   266         oldDisplayMode.driverdata = NULL;
   267     }
   268 }
   269 
   270 SDL_WinRTApp::SDL_WinRTApp() :
   271     m_windowClosed(false),
   272     m_windowVisible(true)
   273 {
   274 }
   275 
   276 void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView)
   277 {
   278     applicationView->Activated +=
   279         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &SDL_WinRTApp::OnActivated);
   280 
   281     CoreApplication::Suspending +=
   282         ref new EventHandler<SuspendingEventArgs^>(this, &SDL_WinRTApp::OnSuspending);
   283 
   284     CoreApplication::Resuming +=
   285         ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnResuming);
   286 
   287     CoreApplication::Exiting +=
   288         ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnExiting);
   289 }
   290 
   291 #if NTDDI_VERSION > NTDDI_WIN8
   292 void SDL_WinRTApp::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
   293 #else
   294 void SDL_WinRTApp::OnOrientationChanged(Object^ sender)
   295 #endif
   296 {
   297 #if LOG_ORIENTATION_EVENTS==1
   298     CoreWindow^ window = CoreWindow::GetForCurrentThread();
   299     if (window) {
   300         SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Size={%f,%f}\n",
   301             __FUNCTION__,
   302             WINRT_DISPLAY_PROPERTY(CurrentOrientation),
   303             WINRT_DISPLAY_PROPERTY(NativeOrientation),
   304             WINRT_DISPLAY_PROPERTY(AutoRotationPreferences),
   305             window->Bounds.Width,
   306             window->Bounds.Height);
   307     } else {
   308         SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d\n",
   309             __FUNCTION__,
   310             WINRT_DISPLAY_PROPERTY(CurrentOrientation),
   311             WINRT_DISPLAY_PROPERTY(NativeOrientation),
   312             WINRT_DISPLAY_PROPERTY(AutoRotationPreferences));
   313     }
   314 #endif
   315 
   316     WINRT_ProcessWindowSizeChange();
   317 }
   318 
   319 void SDL_WinRTApp::SetWindow(CoreWindow^ window)
   320 {
   321 #if LOG_WINDOW_EVENTS==1
   322     SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window Size={%f,%f}\n",
   323         __FUNCTION__,
   324         WINRT_DISPLAY_PROPERTY(CurrentOrientation),
   325         WINRT_DISPLAY_PROPERTY(NativeOrientation),
   326         WINRT_DISPLAY_PROPERTY(AutoRotationPreferences),
   327         window->Bounds.Width,
   328         window->Bounds.Height);
   329 #endif
   330 
   331     window->SizeChanged += 
   332         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &SDL_WinRTApp::OnWindowSizeChanged);
   333 
   334     window->VisibilityChanged +=
   335         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &SDL_WinRTApp::OnVisibilityChanged);
   336 
   337     window->Closed += 
   338         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &SDL_WinRTApp::OnWindowClosed);
   339 
   340 #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
   341     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
   342 #endif
   343 
   344     window->PointerPressed +=
   345         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerPressed);
   346 
   347     window->PointerMoved +=
   348         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerMoved);
   349 
   350     window->PointerReleased +=
   351         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerReleased);
   352 
   353     window->PointerWheelChanged +=
   354         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerWheelChanged);
   355 
   356 #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
   357     // Retrieves relative-only mouse movements:
   358     Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
   359         ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &SDL_WinRTApp::OnMouseMoved);
   360 #endif
   361 
   362     window->KeyDown +=
   363         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyDown);
   364 
   365     window->KeyUp +=
   366         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyUp);
   367 
   368     window->CharacterReceived +=
   369         ref new TypedEventHandler<CoreWindow^, CharacterReceivedEventArgs^>(this, &SDL_WinRTApp::OnCharacterReceived);
   370 
   371 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   372     HardwareButtons::BackPressed +=
   373         ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
   374 #endif
   375 
   376 #if NTDDI_VERSION > NTDDI_WIN8
   377     DisplayInformation::GetForCurrentView()->OrientationChanged +=
   378         ref new TypedEventHandler<Windows::Graphics::Display::DisplayInformation^, Object^>(this, &SDL_WinRTApp::OnOrientationChanged);
   379 #else
   380     DisplayProperties::OrientationChanged +=
   381         ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged);
   382 #endif
   383 
   384     // Register the hint, SDL_HINT_ORIENTATIONS, with SDL.
   385     // 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.
   386     SDL_AddHintCallback(SDL_HINT_ORIENTATIONS, WINRT_SetDisplayOrientationsPreference, NULL);
   387 
   388 #if WINAPI_FAMILY == WINAPI_FAMILY_APP  // for Windows 8/8.1/RT apps... (and not Phone apps)
   389     // Make sure we know when a user has opened the app's settings pane.
   390     // This is needed in order to display a privacy policy, which needs
   391     // to be done for network-enabled apps, as per Windows Store requirements.
   392     using namespace Windows::UI::ApplicationSettings;
   393     SettingsPane::GetForCurrentView()->CommandsRequested +=
   394         ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>
   395             (this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
   396 #endif
   397 }
   398 
   399 void SDL_WinRTApp::Load(Platform::String^ entryPoint)
   400 {
   401 }
   402 
   403 void SDL_WinRTApp::Run()
   404 {
   405     SDL_SetMainReady();
   406     if (WINRT_SDLAppEntryPoint)
   407     {
   408         // TODO, WinRT: pass the C-style main() a reasonably realistic
   409         // representation of command line arguments.
   410         int argc = 0;
   411         char **argv = NULL;
   412         WINRT_SDLAppEntryPoint(argc, argv);
   413     }
   414 }
   415 
   416 static bool IsSDLWindowEventPending(SDL_WindowEventID windowEventID)
   417 {
   418     SDL_Event events[128];
   419     const int count = SDL_PeepEvents(events, sizeof(events)/sizeof(SDL_Event), SDL_PEEKEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT);
   420     for (int i = 0; i < count; ++i) {
   421         if (events[i].window.event == windowEventID) {
   422             return true;
   423         }
   424     }
   425     return false;
   426 }
   427 
   428 bool SDL_WinRTApp::ShouldWaitForAppResumeEvents()
   429 {
   430     /* Don't wait if the app is visible: */
   431     if (m_windowVisible) {
   432         return false;
   433     }
   434     
   435     /* Don't wait until the window-hide events finish processing.
   436      * Do note that if an app-suspend event is sent (as indicated
   437      * by SDL_APP_WILLENTERBACKGROUND and SDL_APP_DIDENTERBACKGROUND
   438      * events), then this code may be a moot point, as WinRT's
   439      * own event pump (aka ProcessEvents()) will pause regardless
   440      * of what we do here.  This happens on Windows Phone 8, to note.
   441      * Windows 8.x apps, on the other hand, may get a chance to run
   442      * these.
   443      */
   444     if (IsSDLWindowEventPending(SDL_WINDOWEVENT_HIDDEN)) {
   445         return false;
   446     } else if (IsSDLWindowEventPending(SDL_WINDOWEVENT_FOCUS_LOST)) {
   447         return false;
   448     } else if (IsSDLWindowEventPending(SDL_WINDOWEVENT_MINIMIZED)) {
   449         return false;
   450     }
   451 
   452     return true;
   453 }
   454 
   455 void SDL_WinRTApp::PumpEvents()
   456 {
   457     if (!m_windowClosed) {
   458         if (!ShouldWaitForAppResumeEvents()) {
   459             /* This is the normal way in which events should be pumped.
   460              * 'ProcessAllIfPresent' will make ProcessEvents() process anywhere
   461              * from zero to N events, and will then return.
   462              */
   463             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
   464         } else {
   465             /* This style of event-pumping, with 'ProcessOneAndAllPending',
   466              * will cause anywhere from one to N events to be processed.  If
   467              * at least one event is processed, the call will return.  If
   468              * no events are pending, then the call will wait until one is
   469              * available, and will not return (to the caller) until this
   470              * happens!  This should only occur when the app is hidden.
   471              */
   472             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
   473         }
   474     }
   475 }
   476 
   477 void SDL_WinRTApp::Uninitialize()
   478 {
   479 }
   480 
   481 #if WINAPI_FAMILY == WINAPI_FAMILY_APP
   482 void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
   483     Windows::UI::ApplicationSettings::SettingsPane ^p,
   484     Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args)
   485 {
   486     using namespace Platform;
   487     using namespace Windows::UI::ApplicationSettings;
   488     using namespace Windows::UI::Popups;
   489 
   490     String ^privacyPolicyURL = nullptr;     // a URL to an app's Privacy Policy
   491     String ^privacyPolicyLabel = nullptr;   // label/link text
   492     const char *tmpHintValue = NULL;        // SDL_GetHint-retrieved value, used immediately
   493     wchar_t *tmpStr = NULL;                 // used for UTF8 to UCS2 conversion
   494 
   495     // Setup a 'Privacy Policy' link, if one is available (via SDL_GetHint):
   496     tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_URL);
   497     if (tmpHintValue && tmpHintValue[0] != '\0') {
   498         // Convert the privacy policy's URL to UCS2:
   499         tmpStr = WIN_UTF8ToString(tmpHintValue);
   500         privacyPolicyURL = ref new String(tmpStr);
   501         SDL_free(tmpStr);
   502 
   503         // Optionally retrieve custom label-text for the link.  If this isn't
   504         // available, a default value will be used instead.
   505         tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_LABEL);
   506         if (tmpHintValue && tmpHintValue[0] != '\0') {
   507             tmpStr = WIN_UTF8ToString(tmpHintValue);
   508             privacyPolicyLabel = ref new String(tmpStr);
   509             SDL_free(tmpStr);
   510         } else {
   511             privacyPolicyLabel = ref new String(L"Privacy Policy");
   512         }
   513 
   514         // Register the link, along with a handler to be called if and when it is
   515         // clicked:
   516         auto cmd = ref new SettingsCommand(L"privacyPolicy", privacyPolicyLabel,
   517             ref new UICommandInvokedHandler([=](IUICommand ^) {
   518                 Windows::System::Launcher::LaunchUriAsync(ref new Uri(privacyPolicyURL));
   519         }));
   520         args->Request->ApplicationCommands->Append(cmd);
   521     }
   522 }
   523 #endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
   524 
   525 void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
   526 {
   527 #if LOG_WINDOW_EVENTS==1
   528     SDL_Log("%s, size={%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n",
   529         __FUNCTION__,
   530         args->Size.Width, args->Size.Height,
   531         WINRT_DISPLAY_PROPERTY(CurrentOrientation),
   532         WINRT_DISPLAY_PROPERTY(NativeOrientation),
   533         WINRT_DISPLAY_PROPERTY(AutoRotationPreferences),
   534         (WINRT_GlobalSDLWindow ? "yes" : "no"));
   535 #endif
   536 
   537     WINRT_ProcessWindowSizeChange();
   538 }
   539 
   540 void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
   541 {
   542 #if LOG_WINDOW_EVENTS==1
   543     SDL_Log("%s, visible?=%s, WINRT_GlobalSDLWindow?=%s\n",
   544         __FUNCTION__,
   545         (args->Visible ? "yes" : "no"),
   546         (WINRT_GlobalSDLWindow ? "yes" : "no"));
   547 #endif
   548 
   549     m_windowVisible = args->Visible;
   550     if (WINRT_GlobalSDLWindow) {
   551         SDL_bool wasSDLWindowSurfaceValid = WINRT_GlobalSDLWindow->surface_valid;
   552 
   553         if (args->Visible) {
   554             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SHOWN, 0, 0);
   555             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
   556             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_RESTORED, 0, 0);
   557         } else {
   558             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_HIDDEN, 0, 0);
   559             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
   560             SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
   561         }
   562 
   563         // HACK: Prevent SDL's window-hide handling code, which currently
   564         // triggers a fake window resize (possibly erronously), from
   565         // marking the SDL window's surface as invalid.
   566         //
   567         // A better solution to this probably involves figuring out if the
   568         // fake window resize can be prevented.
   569         WINRT_GlobalSDLWindow->surface_valid = wasSDLWindowSurfaceValid;
   570     }
   571 }
   572 
   573 void SDL_WinRTApp::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
   574 {
   575 #if LOG_WINDOW_EVENTS==1
   576     SDL_Log("%s\n", __FUNCTION__);
   577 #endif
   578     m_windowClosed = true;
   579 }
   580 
   581 void SDL_WinRTApp::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
   582 {
   583     CoreWindow::GetForCurrentThread()->Activate();
   584 }
   585 
   586 void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
   587 {
   588     // Save app state asynchronously after requesting a deferral. Holding a deferral
   589     // indicates that the application is busy performing suspending operations. Be
   590     // aware that a deferral may not be held indefinitely. After about five seconds,
   591     // the app will be forced to exit.
   592 
   593     // ... but first, let the app know it's about to go to the background.
   594     // The separation of events may be important, given that the deferral
   595     // runs in a separate thread.  This'll make SDL_APP_WILLENTERBACKGROUND
   596     // the only event among the two that runs in the main thread.  Given
   597     // that a few WinRT operations can only be done from the main thread
   598     // (things that access the WinRT CoreWindow are one example of this),
   599     // this could be important.
   600     SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
   601 
   602     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
   603     create_task([this, deferral]()
   604     {
   605         // Send an app did-enter-background event immediately to observers.
   606         // CoreDispatcher::ProcessEvents, which is the backbone on which
   607         // SDL_WinRTApp::PumpEvents is built, will not return to its caller
   608         // once it sends out a suspend event.  Any events posted to SDL's
   609         // event queue won't get received until the WinRT app is resumed.
   610         // SDL_AddEventWatch() may be used to receive app-suspend events on
   611         // WinRT.
   612         SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
   613 
   614         // Let the Direct3D 11 renderer prepare for the app to be backgrounded.
   615         // This is necessary for Windows 8.1, possibly elsewhere in the future.
   616         // More details at: http://msdn.microsoft.com/en-us/library/windows/apps/Hh994929.aspx
   617 #if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
   618         if (WINRT_GlobalSDLWindow) {
   619             SDL_Renderer * renderer = SDL_GetRenderer(WINRT_GlobalSDLWindow);
   620             if (renderer && (SDL_strcmp(renderer->info.name, "direct3d11") == 0)) {
   621                 D3D11_Trim(renderer);
   622             }
   623         }
   624 #endif
   625 
   626         deferral->Complete();
   627     });
   628 }
   629 
   630 void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args)
   631 {
   632     // Restore any data or state that was unloaded on suspend. By default, data
   633     // and state are persisted when resuming from suspend. Note that these events
   634     // do not occur if the app was previously terminated.
   635     SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
   636     SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
   637 }
   638 
   639 void SDL_WinRTApp::OnExiting(Platform::Object^ sender, Platform::Object^ args)
   640 {
   641     SDL_SendAppEvent(SDL_APP_TERMINATING);
   642 }
   643 
   644 static void
   645 WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
   646 {
   647     Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint;
   648     SDL_Log("%s: Position={%f,%f}, Transformed Pos={%f, %f}, MouseWheelDelta=%d, FrameId=%d, PointerId=%d, SDL button=%d\n",
   649         header,
   650         pt->Position.X, pt->Position.Y,
   651         transformedPoint.X, transformedPoint.Y,
   652         pt->Properties->MouseWheelDelta,
   653         pt->FrameId,
   654         pt->PointerId,
   655         WINRT_GetSDLButtonForPointerPoint(pt));
   656 }
   657 
   658 void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
   659 {
   660 #if LOG_POINTER_EVENTS
   661     WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   662 #endif
   663 
   664     WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   665 }
   666 
   667 void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
   668 {
   669 #if LOG_POINTER_EVENTS
   670     WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   671 #endif
   672 
   673     WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   674 }
   675 
   676 void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
   677 {
   678 #if LOG_POINTER_EVENTS
   679     WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   680 #endif
   681 
   682     WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   683 }
   684 
   685 void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args)
   686 {
   687 #if LOG_POINTER_EVENTS
   688     WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
   689 #endif
   690 
   691     WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
   692 }
   693 
   694 void SDL_WinRTApp::OnMouseMoved(MouseDevice^ mouseDevice, MouseEventArgs^ args)
   695 {
   696     WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args);
   697 }
   698 
   699 void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
   700 {
   701     WINRT_ProcessKeyDownEvent(args);
   702 }
   703 
   704 void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
   705 {
   706     WINRT_ProcessKeyUpEvent(args);
   707 }
   708 
   709 void SDL_WinRTApp::OnCharacterReceived(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CharacterReceivedEventArgs^ args)
   710 {
   711     WINRT_ProcessCharacterReceivedEvent(args);
   712 }
   713 
   714 #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
   715 void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
   716 {
   717     SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_AC_BACK);
   718     SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_AC_BACK);
   719 
   720     const char *hint = SDL_GetHint(SDL_HINT_WINRT_HANDLE_BACK_BUTTON);
   721     if (hint) {
   722         if (*hint == '1') {
   723             args->Handled = true;
   724         }
   725     }
   726 }
   727 #endif
   728