forked from microsoft/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.xaml.cpp
477 lines (419 loc) · 18.2 KB
/
App.xaml.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// App.xaml.cpp
// Implementation of the App class.
//
#include "pch.h"
#include "App.xaml.h"
#include "CalcViewModel/Common/TraceLogger.h"
#include "CalcViewModel/Common/Automation/NarratorNotifier.h"
#include "CalcViewModel/Common/AppResourceProvider.h"
#include "CalcViewModel/Common/LocalizationSettings.h"
#include "CalcViewModel/ViewState.h"
#include "Views/MainPage.xaml.h"
using namespace CalculatorApp;
using namespace CalculatorApp::Common;
using namespace CalculatorApp::Common::Automation;
using namespace Concurrency;
using namespace Microsoft::WRL;
using namespace Platform;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Resources;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage;
using namespace Windows::System;
using namespace Windows::UI::Core;
using namespace Windows::UI::Popups;
using namespace Windows::UI::StartScreen;
using namespace Windows::UI::ViewManagement;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Media::Animation;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::ApplicationModel::Activation;
namespace CalculatorApp
{
namespace ApplicationResourceKeys
{
StringReference AppMinWindowHeight(L"AppMinWindowHeight");
StringReference AppMinWindowWidth(L"AppMinWindowWidth");
}
}
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
App::App()
{
InitializeComponent();
m_preLaunched = false;
RegisterDependencyProperties();
// TODO: MSFT 14645325: Set this directly from XAML.
// Currently this is bugged so the property is only respected from code-behind.
this->HighContrastAdjustment = ApplicationHighContrastAdjustment::None;
this->Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
#if _DEBUG
this->DebugSettings->IsBindingTracingEnabled = true;
this->DebugSettings->BindingFailed += ref new BindingFailedEventHandler([](_In_ Object ^ /*sender*/, _In_ BindingFailedEventArgs ^ e) {
if (IsDebuggerPresent())
{
::Platform::String ^ errorMessage = e->Message;
__debugbreak();
}
});
#endif
}
bool App::m_isAnimationEnabled = true;
/// <summary>
/// Return True if animation is enabled by user setting.
/// </summary>
bool App::IsAnimationEnabled()
{
return App::m_isAnimationEnabled;
}
/// <summary>
/// Return the current application view state. The value
/// will match one of the constants in the ViewState namespace.
/// </summary>
String ^ App::GetAppViewState()
{
String ^ newViewState;
CoreWindow ^ window = CoreWindow::GetForCurrentThread();
if ((window->Bounds.Width >= 560) && (window->Bounds.Height >= 356))
{
newViewState = ViewState::DockedView;
}
else
{
newViewState = ViewState::Snap;
}
return newViewState;
}
void App::AddWindowToMap(_In_ WindowFrameService ^ frameService)
{
reader_writer_lock::scoped_lock lock(m_windowsMapLock);
m_secondaryWindows[frameService->GetViewId()] = frameService;
TraceLogger::GetInstance().UpdateWindowCount(m_secondaryWindows.size());
}
WindowFrameService ^ App::GetWindowFromMap(int viewId)
{
reader_writer_lock::scoped_lock_read lock(m_windowsMapLock);
auto windowMapEntry = m_secondaryWindows.find(viewId);
if (windowMapEntry != m_secondaryWindows.end())
{
return windowMapEntry->second;
}
return nullptr;
}
void App::RemoveWindowFromMap(int viewId)
{
reader_writer_lock::scoped_lock lock(m_windowsMapLock);
auto iter = m_secondaryWindows.find(viewId);
assert(iter != m_secondaryWindows.end() && "Window does not exist in the list");
m_secondaryWindows.erase(viewId);
}
void App::RemoveWindow(_In_ WindowFrameService ^ frameService)
{
// Shell does not allow killing the main window.
if (m_mainViewId != frameService->GetViewId())
{
HandleViewReleaseAndRemoveWindowFromMap(frameService);
}
}
task<void> App::HandleViewReleaseAndRemoveWindowFromMap(_In_ WindowFrameService ^ frameService)
{
WeakReference weak(this);
// Unregister the event handler of the Main Page
auto frame = safe_cast<Frame ^>(Window::Current->Content);
auto mainPage = safe_cast<MainPage ^>(frame->Content);
mainPage->UnregisterEventHandlers();
return frameService->HandleViewRelease().then(
[weak, frameService]() {
auto that = weak.Resolve<App>();
that->RemoveWindowFromMap(frameService->GetViewId());
},
task_continuation_context::use_arbitrary());
}
#pragma optimize("", off) // Turn off optimizations to work around coroutine optimization bug
task<void> App::SetupJumpList()
{
try
{
auto calculatorOptions = NavCategoryGroup::CreateCalculatorCategory();
auto jumpList = co_await JumpList::LoadCurrentAsync();
jumpList->SystemGroupKind = JumpListSystemGroupKind::None;
jumpList->Items->Clear();
for (NavCategory ^ option : calculatorOptions->Categories)
{
ViewMode mode = option->Mode;
auto item = JumpListItem::CreateWithArguments(((int)mode).ToString(), L"ms-resource:///Resources/" + NavCategory::GetNameResourceKey(mode));
item->Description = L"ms-resource:///Resources/" + NavCategory::GetNameResourceKey(mode);
item->Logo = ref new Uri("ms-appx:///Assets/" + mode.ToString() + ".png");
jumpList->Items->Append(item);
}
co_await jumpList->SaveAsync();
}
catch (...)
{
}
};
#pragma optimize("", on)
void App::RemoveSecondaryWindow(_In_ WindowFrameService ^ frameService)
{
// Shell does not allow killing the main window.
if (m_mainViewId != frameService->GetViewId())
{
RemoveWindowFromMap(frameService->GetViewId());
}
}
Frame ^ App::CreateFrame()
{
auto frame = ref new Frame();
frame->FlowDirection = LocalizationService::GetInstance()->GetFlowDirection();
return frame;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
void App::OnLaunched(LaunchActivatedEventArgs ^ args)
{
if (args->PrelaunchActivated)
{
// If the app got pre-launch activated, then save that state in a flag
m_preLaunched = true;
}
OnAppLaunch(args, args->Arguments);
}
void App::OnAppLaunch(IActivatedEventArgs ^ args, String ^ argument)
{
// Uncomment the following lines to display frame-rate and per-frame CPU usage info.
//#if _DEBUG
// if (IsDebuggerPresent())
// {
// DebugSettings->EnableFrameRateCounter = true;
// }
//#endif
auto userSettings = ref new Windows::UI::ViewManagement::UISettings();
m_isAnimationEnabled = userSettings->AnimationsEnabled;
args->SplashScreen->Dismissed += ref new TypedEventHandler<SplashScreen ^, Object ^>(this, &App::DismissedEventHandler);
auto rootFrame = dynamic_cast<Frame ^>(Window::Current->Content);
WeakReference weak(this);
float minWindowWidth = static_cast<float>(static_cast<double>(this->Resources->Lookup(ApplicationResourceKeys::AppMinWindowWidth)));
float minWindowHeight = static_cast<float>(static_cast<double>(this->Resources->Lookup(ApplicationResourceKeys::AppMinWindowHeight)));
Size minWindowSize = SizeHelper::FromDimensions(minWindowWidth, minWindowHeight);
ApplicationView ^ appView = ApplicationView::GetForCurrentView();
ApplicationDataContainer ^ localSettings = ApplicationData::Current->LocalSettings;
// For very first launch, set the size of the calc as size of the default standard mode
if (!localSettings->Values->HasKey(L"VeryFirstLaunch"))
{
localSettings->Values->Insert(ref new String(L"VeryFirstLaunch"), false);
appView->SetPreferredMinSize(minWindowSize);
appView->TryResizeView(minWindowSize);
}
else
{
appView->PreferredLaunchWindowingMode = ApplicationViewWindowingMode::Auto;
}
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == nullptr)
{
if (!Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // PC Family
{
// Disable the system view activation policy during the first launch of the app
// only for PC family devices and not for phone family devices
try
{
ApplicationViewSwitcher::DisableSystemViewActivationPolicy();
}
catch (Exception ^ e)
{
// Log that DisableSystemViewActionPolicy didn't work
}
}
// Create a Frame to act as the navigation context
rootFrame = App::CreateFrame();
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame->Navigate(MainPage::typeid, argument))
{
// We couldn't navigate to the main page, kill the app so we have a good
// stack to debug
throw std::bad_exception();
}
SetMinWindowSizeAndActivate(rootFrame, minWindowSize);
m_mainViewId = ApplicationView::GetForCurrentView()->Id;
AddWindowToMap(WindowFrameService::CreateNewWindowFrameService(rootFrame, false, weak));
}
else
{
// For first launch, LaunchStart is logged in constructor, this is for subsequent launches.
// !Phone check is required because even in continuum mode user interaction mode is Mouse not Touch
if ((UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Mouse)
&& (!Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
{
// If the pre-launch hasn't happened then allow for the new window/view creation
if (!m_preLaunched)
{
auto newCoreAppView = CoreApplication::CreateNewView();
newCoreAppView->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal, ref new DispatchedHandler([args, argument, minWindowSize, weak]() {
auto that = weak.Resolve<App>();
if (that != nullptr)
{
auto rootFrame = App::CreateFrame();
SetMinWindowSizeAndActivate(rootFrame, minWindowSize);
if (!rootFrame->Navigate(MainPage::typeid, argument))
{
// We couldn't navigate to the main page, kill the app so we have a good
// stack to debug
throw std::bad_exception();
}
auto frameService = WindowFrameService::CreateNewWindowFrameService(rootFrame, true, weak);
that->AddWindowToMap(frameService);
auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
auto safeFrameServiceCreation = std::make_shared<SafeFrameWindowCreation>(frameService, that);
int newWindowId = ApplicationView::GetApplicationViewIdForWindow(CoreWindow::GetForCurrentThread());
ActivationViewSwitcher ^ activationViewSwitcher;
auto activateEventArgs = dynamic_cast<IViewSwitcherProvider ^>(args);
if (activateEventArgs != nullptr)
{
activationViewSwitcher = activateEventArgs->ViewSwitcher;
}
if (activationViewSwitcher != nullptr)
{
activationViewSwitcher->ShowAsStandaloneAsync(newWindowId, ViewSizePreference::Default);
safeFrameServiceCreation->SetOperationSuccess(true);
}
else
{
auto activatedEventArgs = dynamic_cast<IApplicationViewActivatedEventArgs ^>(args);
if ((activatedEventArgs != nullptr) && (activatedEventArgs->CurrentlyShownApplicationViewId != 0))
{
create_task(ApplicationViewSwitcher::TryShowAsStandaloneAsync(
frameService->GetViewId(),
ViewSizePreference::Default,
activatedEventArgs->CurrentlyShownApplicationViewId,
ViewSizePreference::Default))
.then(
[safeFrameServiceCreation](bool viewShown) {
// SafeFrameServiceCreation is used to automatically remove the frame
// from the list of frames if something goes bad.
safeFrameServiceCreation->SetOperationSuccess(viewShown);
},
task_continuation_context::use_current());
}
}
}
}));
}
else
{
ActivationViewSwitcher ^ activationViewSwitcher;
auto activateEventArgs = dynamic_cast<IViewSwitcherProvider ^>(args);
if (activateEventArgs != nullptr)
{
activationViewSwitcher = activateEventArgs->ViewSwitcher;
}
if (activationViewSwitcher != nullptr)
{
activationViewSwitcher->ShowAsStandaloneAsync(
ApplicationView::GetApplicationViewIdForWindow(CoreWindow::GetForCurrentThread()), ViewSizePreference::Default);
}
else
{
TraceLogger::GetInstance().LogError(ViewMode::None, L"App::OnAppLaunch", L"Null_ActivationViewSwitcher");
}
}
// Set the preLaunched flag to false
m_preLaunched = false;
}
else // for touch devices
{
if (rootFrame->Content == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame->Navigate(MainPage::typeid, argument))
{
// We couldn't navigate to the main page,
// kill the app so we have a good stack to debug
throw std::bad_exception();
}
}
if (ApplicationView::GetForCurrentView()->ViewMode != ApplicationViewMode::CompactOverlay)
{
if (!Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
// for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in
// activationArgs
ActivationViewSwitcher ^ activationViewSwitcher;
auto activateEventArgs = dynamic_cast<IViewSwitcherProvider ^>(args);
if (activateEventArgs != nullptr)
{
activationViewSwitcher = activateEventArgs->ViewSwitcher;
}
if (activationViewSwitcher != nullptr)
{
auto viewId = safe_cast<IApplicationViewActivatedEventArgs ^>(args)->CurrentlyShownApplicationViewId;
if (viewId != 0)
{
activationViewSwitcher->ShowAsStandaloneAsync(viewId);
}
}
}
// Ensure the current window is active
Window::Current->Activate();
}
}
}
}
void App::SetMinWindowSizeAndActivate(Frame ^ rootFrame, Size minWindowSize)
{
// SetPreferredMinSize should always be called before Window::Activate
ApplicationView ^ appView = ApplicationView::GetForCurrentView();
appView->SetPreferredMinSize(minWindowSize);
// Place the frame in the current Window
Window::Current->Content = rootFrame;
Window::Current->Activate();
}
void App::RegisterDependencyProperties()
{
NarratorNotifier::RegisterDependencyProperties();
}
void App::OnActivated(IActivatedEventArgs ^ args)
{
if (args->Kind == ActivationKind::Protocol)
{
// We currently don't pass the uri as an argument,
// and handle any protocol launch as a normal app launch.
OnAppLaunch(args, nullptr);
}
}
void CalculatorApp::App::OnSuspending(Object ^ sender, SuspendingEventArgs ^ args)
{
TraceLogger::GetInstance().LogButtonUsage();
}
void App::DismissedEventHandler(SplashScreen ^ sender, Object ^ e)
{
SetupJumpList();
}
float App::GetAppWindowHeight()
{
CoreWindow ^ window = CoreWindow::GetForCurrentThread();
return window->Bounds.Height;
}