-
Notifications
You must be signed in to change notification settings - Fork 460
/
AppWindow.cpp
1279 lines (1176 loc) · 43.2 KB
/
AppWindow.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) Microsoft Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "stdafx.h"
#include "AppWindow.h"
#include <DispatcherQueue.h>
#include <functional>
#include <string>
#include <vector>
#include <ShObjIdl_core.h>
#include <Shellapi.h>
#include <ShlObj_core.h>
#include <winrt/windows.system.h>
#include "App.h"
#include "AppStartPage.h"
#include "CheckFailure.h"
#include "ControlComponent.h"
#include "DpiUtil.h"
#include "FileComponent.h"
#include "ProcessComponent.h"
#include "Resource.h"
#include "ScenarioAddHostObject.h"
#include "ScenarioAuthentication.h"
#include "ScenarioCookieManagement.h"
#include "ScenarioDOMContentLoaded.h"
#include "ScenarioNavigateWithWebResourceRequest.h"
#include "ScenarioWebMessage.h"
#include "ScenarioWebViewEventMonitor.h"
#include "ScriptComponent.h"
#include "SettingsComponent.h"
#include "TextInputDialog.h"
#include "ViewComponent.h"
using namespace Microsoft::WRL;
static constexpr size_t s_maxLoadString = 100;
static constexpr UINT s_runAsyncWindowMessage = WM_APP;
static thread_local size_t s_appInstances = 0;
// The minimum height and width for Window Features.
// See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Size
static constexpr int s_minNewWindowSize = 100;
// Run Download and Install in another thread so we don't block the UI thread
DWORD WINAPI DownloadAndInstallWV2RT(_In_ LPVOID lpParameter)
{
AppWindow* appWindow = (AppWindow*) lpParameter;
int returnCode = 2; // Download failed
// Use fwlink to download WebView2 Bootstrapper at runtime and invoke installation
// Broken/Invalid Https Certificate will fail to download
// Use of the download link below is governed by the below terms. You may acquire the link for your use at https://developer.microsoft.com/microsoft-edge/webview2/.
// Microsoft owns all legal right, title, and interest in and to the WebView2 Runtime Bootstrapper ("Software") and related documentation,
// including any intellectual property in the Software.
// You must acquire all code, including any code obtained from a Microsoft URL, under a separate license directly from Microsoft, including a Microsoft download site
// (e.g., https://developer.microsoft.com/microsoft-edge/webview2/).
HRESULT hr = URLDownloadToFile(NULL, L"https://go.microsoft.com/fwlink/p/?LinkId=2124703", L".\\MicrosoftEdgeWebview2Setup.exe", 0, 0);
if (hr == S_OK)
{
// Either Package the WebView2 Bootstrapper with your app or download it using fwlink
// Then invoke install at Runtime.
SHELLEXECUTEINFO shExInfo = {0};
shExInfo.cbSize = sizeof(shExInfo);
shExInfo.fMask = SEE_MASK_NOASYNC;
shExInfo.hwnd = 0;
shExInfo.lpVerb = L"runas";
shExInfo.lpFile = L"MicrosoftEdgeWebview2Setup.exe";
shExInfo.lpParameters = L" /silent /install";
shExInfo.lpDirectory = 0;
shExInfo.nShow = 0;
shExInfo.hInstApp = 0;
if (ShellExecuteEx(&shExInfo))
{
returnCode = 0; // Install successfull
}
else
{
returnCode = 1; // Install failed
}
}
appWindow->InstallComplete(returnCode);
appWindow->Release();
return returnCode;
}
// Creates a new window which is a copy of the entire app, but on the same thread.
AppWindow::AppWindow(
UINT creationModeId,
std::wstring initialUri,
bool isMainWindow,
std::function<void()> webviewCreatedCallback,
bool customWindowRect,
RECT windowRect,
bool shouldHaveToolbar)
: m_creationModeId(creationModeId),
m_initialUri(initialUri),
m_onWebViewFirstInitialized(webviewCreatedCallback)
{
// Initialize COM as STA.
CHECK_FAILURE(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
++s_appInstances;
WCHAR szTitle[s_maxLoadString]; // The title bar text
LoadStringW(g_hInstance, IDS_APP_TITLE, szTitle, s_maxLoadString);
if (customWindowRect)
{
m_mainWindow = CreateWindowExW(
WS_EX_CONTROLPARENT, GetWindowClass(), szTitle, WS_OVERLAPPEDWINDOW, windowRect.left,
windowRect.top, windowRect.right-windowRect.left, windowRect.bottom-windowRect.top, nullptr, nullptr, g_hInstance, nullptr);
}
else
{
m_mainWindow = CreateWindowExW(
WS_EX_CONTROLPARENT, GetWindowClass(), szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
0, CW_USEDEFAULT, 0, nullptr, nullptr, g_hInstance, nullptr);
}
SetWindowLongPtr(m_mainWindow, GWLP_USERDATA, (LONG_PTR)this);
#ifdef USE_WEBVIEW2_WIN10
//! [TextScaleChanged1]
if (winrt::try_get_activation_factory<winrt::Windows::UI::ViewManagement::UISettings>())
{
m_uiSettings = winrt::Windows::UI::ViewManagement::UISettings();
m_uiSettings.TextScaleFactorChanged({ this, &AppWindow::OnTextScaleChanged });
}
//! [TextScaleChanged1]
#endif
if (shouldHaveToolbar)
{
m_toolbar.Initialize(this);
}
UpdateCreationModeMenu();
ShowWindow(m_mainWindow, g_nCmdShow);
UpdateWindow(m_mainWindow);
// If no WebVieRuntime installed, create new thread to do install/download.
// Otherwise just initialize webview.
wil::unique_cotaskmem_string version_info;
HRESULT hr = GetAvailableCoreWebView2BrowserVersionString(nullptr, &version_info);
if (hr == S_OK && version_info != nullptr)
{
RunAsync([this] {
InitializeWebView();
});
}
else
{
if (isMainWindow) {
AddRef();
CreateThread(0, 0, DownloadAndInstallWV2RT, (void*) this, 0, 0);
}
else
{
MessageBox(m_mainWindow, L"WebView Runtime not installed", L"WebView Runtime Installation status", MB_OK);
}
}
}
// Register the Win32 window class for the app window.
PCWSTR AppWindow::GetWindowClass()
{
// Only do this once
static PCWSTR windowClass = [] {
static WCHAR windowClass[s_maxLoadString];
LoadStringW(g_hInstance, IDC_WEBVIEW2APISAMPLE, windowClass, s_maxLoadString);
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProcStatic;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = g_hInstance;
wcex.hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_WEBVIEW2APISAMPLE));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_WEBVIEW2APISAMPLE);
wcex.lpszClassName = windowClass;
wcex.hIconSm = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_SMALL));
RegisterClassExW(&wcex);
return windowClass;
}();
return windowClass;
}
LRESULT CALLBACK AppWindow::WndProcStatic(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (auto app = (AppWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA))
{
LRESULT result = 0;
if (app->HandleWindowMessage(hWnd, message, wParam, lParam, &result))
{
return result;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// Handle Win32 window messages sent to the main window
bool AppWindow::HandleWindowMessage(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, LRESULT* result)
{
// Give all components a chance to handle the message first.
for (auto& component : m_components)
{
if (component->HandleWindowMessage(hWnd, message, wParam, lParam, result))
{
return true;
}
}
switch (message)
{
case WM_SIZE:
{
// Don't resize the app or webview when the app is minimized
// let WM_SYSCOMMAND to handle it
if (lParam != 0)
{
ResizeEverything();
return true;
}
}
break;
//! [DPIChanged]
case WM_DPICHANGED:
{
m_toolbar.UpdateDpiAndTextScale();
RECT* const newWindowSize = reinterpret_cast<RECT*>(lParam);
SetWindowPos(hWnd,
nullptr,
newWindowSize->left,
newWindowSize->top,
newWindowSize->right - newWindowSize->left,
newWindowSize->bottom - newWindowSize->top,
SWP_NOZORDER | SWP_NOACTIVATE);
return true;
}
break;
//! [DPIChanged]
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return true;
}
break;
case s_runAsyncWindowMessage:
{
auto* task = reinterpret_cast<std::function<void()>*>(wParam);
(*task)();
delete task;
return true;
}
break;
case WM_NCDESTROY:
{
int retValue = 0;
SetWindowLongPtr(hWnd, GWLP_USERDATA, NULL);
NotifyClosed();
if (--s_appInstances == 0)
{
PostQuitMessage(retValue);
}
}
break;
//! [RestartManager]
case WM_QUERYENDSESSION:
{
// yes, we can shut down
// Register how we might be restarted
RegisterApplicationRestart(L"--restore", RESTART_NO_CRASH | RESTART_NO_HANG);
*result = TRUE;
return true;
}
break;
case WM_ENDSESSION:
{
if (wParam == TRUE)
{
// save app state and exit.
PostQuitMessage(0);
return true;
}
}
break;
//! [RestartManager]
case WM_KEYDOWN:
{
// If bit 30 is set, it means the WM_KEYDOWN message is autorepeated.
// We want to ignore it in that case.
if (!(lParam & (1 << 30)))
{
if (auto action = GetAcceleratorKeyFunction((UINT)wParam))
{
action();
return true;
}
}
}
break;
case WM_COMMAND:
{
return ExecuteWebViewCommands(wParam, lParam) || ExecuteAppCommands(wParam, lParam);
}
break;
}
return false;
}
// Handle commands related to the WebView.
// This will do nothing if the WebView is not initialized.
bool AppWindow::ExecuteWebViewCommands(WPARAM wParam, LPARAM lParam)
{
if (!m_webView)
return false;
switch (LOWORD(wParam))
{
case IDM_GET_BROWSER_VERSION_AFTER_CREATION:
{
//! [GetBrowserVersionString]
wil::unique_cotaskmem_string version_info;
m_webViewEnvironment->get_BrowserVersionString(&version_info);
MessageBox(
m_mainWindow, version_info.get(), L"Browser Version Info After WebView Creation",
MB_OK);
//! [GetBrowserVersionString]
return true;
}
case IDM_CLOSE_WEBVIEW:
{
CloseWebView();
return true;
}
case IDM_CLOSE_WEBVIEW_CLEANUP:
{
CloseWebView(true);
return true;
}
case IDM_SCENARIO_POST_WEB_MESSAGE:
{
NewComponent<ScenarioWebMessage>(this);
return true;
}
case IDM_SCENARIO_ADD_HOST_OBJECT:
{
NewComponent<ScenarioAddHostObject>(this);
return true;
}
case IDM_SCENARIO_WEB_VIEW_EVENT_MONITOR:
{
NewComponent<ScenarioWebViewEventMonitor>(this);
return true;
}
case IDM_SCENARIO_JAVA_SCRIPT:
{
WCHAR c_scriptPath[] = L"ScenarioJavaScriptDebugIndex.html";
std::wstring m_scriptUri = GetLocalUri(c_scriptPath);
CHECK_FAILURE(m_webView->Navigate(m_scriptUri.c_str()));
return true;
}
case IDM_SCENARIO_TYPE_SCRIPT:
{
WCHAR c_scriptPath[] = L"ScenarioTypeScriptDebugIndex.html";
std::wstring m_scriptUri = GetLocalUri(c_scriptPath);
CHECK_FAILURE(m_webView->Navigate(m_scriptUri.c_str()));
}
case IDM_SCENARIO_AUTHENTICATION:
{
NewComponent<ScenarioAuthentication>(this);
return true;
}
case IDM_SCENARIO_COOKIE_MANAGEMENT:
{
NewComponent<ScenarioCookieManagement>(this);
return true;
}
case IDM_SCENARIO_DOM_CONTENT_LOADED:
{
NewComponent<ScenarioDOMContentLoaded>(this);
return true;
}
case IDM_SCENARIO_NAVIGATEWITHWEBRESOURCEREQUEST:
{
NewComponent<ScenarioNavigateWithWebResourceRequest>(this);
return true;
}
}
return false;
}
// Handle commands not related to the WebView, which will work even if the WebView
// is not currently initialized.
bool AppWindow::ExecuteAppCommands(WPARAM wParam, LPARAM lParam)
{
switch (LOWORD(wParam))
{
case IDM_ABOUT:
DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), m_mainWindow, About);
return true;
case IDM_GET_BROWSER_VERSION_BEFORE_CREATION:
{
wil::unique_cotaskmem_string version_info;
GetAvailableCoreWebView2BrowserVersionString(nullptr, &version_info);
MessageBox(
m_mainWindow, version_info.get(), L"Browser Version Info Before WebView Creation",
MB_OK);
return true;
}
case IDM_EXIT:
CloseAppWindow();
return true;
case IDM_CREATION_MODE_WINDOWED:
case IDM_CREATION_MODE_VISUAL_DCOMP:
case IDM_CREATION_MODE_TARGET_DCOMP:
#ifdef USE_WEBVIEW2_WIN10
case IDM_CREATION_MODE_VISUAL_WINCOMP:
#endif
m_creationModeId = LOWORD(wParam);
UpdateCreationModeMenu();
return true;
case IDM_REINIT:
InitializeWebView();
return true;
case IDM_TOGGLE_FULLSCREEN_ALLOWED:
{
m_fullScreenAllowed = !m_fullScreenAllowed;
MessageBox(
nullptr,
(std::wstring(L"Fullscreen is now ") +
(m_fullScreenAllowed ? L"allowed" : L"disallowed"))
.c_str(),
L"", MB_OK);
return true;
}
case IDM_NEW_WINDOW:
new AppWindow(m_creationModeId);
return true;
case IDM_NEW_THREAD:
CreateNewThread(m_creationModeId);
return true;
case IDM_SET_LANGUAGE:
ChangeLanguage();
return true;
case IDM_TOGGLE_AAD_SSO:
ToggleAADSSO();
return true;
}
return false;
}
// Prompt the user for a new language string
void AppWindow::ChangeLanguage()
{
TextInputDialog dialog(
GetMainWindow(), L"Language", L"Language:",
L"Enter a language to use for WebView, or leave blank to restore default.",
m_language.empty() ? L"zh-cn" : m_language.c_str());
if (dialog.confirmed)
{
m_language = (dialog.input);
}
}
// Toggle AAD SSO enabled
void AppWindow::ToggleAADSSO()
{
m_AADSSOEnabled = !m_AADSSOEnabled;
MessageBox(
nullptr,
m_AADSSOEnabled ? L"AAD single sign on will be enabled for new WebView "
L"created after all webviews are closed." :
L"AAD single sign on will be disabled for new WebView"
L" created after all webviews are closed.",
L"AAD SSO change",
MB_OK);
}
// Message handler for about dialog.
INT_PTR CALLBACK AppWindow::About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
// Decide what to do when an accelerator key is pressed. Instead of immediately performing
// the action, we hand it to the caller so they can decide whether to run it right away
// or running it asynchronously. Will return nullptr if there is no action for the key.
std::function<void()> AppWindow::GetAcceleratorKeyFunction(UINT key)
{
if (GetKeyState(VK_CONTROL) < 0)
{
switch (key)
{
case 'N':
return [this] { new AppWindow(m_creationModeId); };
case 'Q':
return [this] { CloseAppWindow(); };
case 'S':
return [this] {
if (auto file = GetComponent<FileComponent>())
{
file->SaveScreenshot();
}
};
case 'T':
return [this] { CreateNewThread(m_creationModeId); };
case 'W':
return [this] { CloseWebView(); };
}
}
return nullptr;
}
//! [CreateCoreWebView2Controller]
// Create or recreate the WebView and its environment.
void AppWindow::InitializeWebView()
{
// To ensure browser switches get applied correctly, we need to close
// the existing WebView. This will result in a new browser process
// getting created which will apply the browser switches.
CloseWebView();
m_dcompDevice = nullptr;
#ifdef USE_WEBVIEW2_WIN10
m_wincompCompositor = nullptr;
#endif
LPCWSTR subFolder = nullptr;
if (m_creationModeId == IDM_CREATION_MODE_VISUAL_DCOMP ||
m_creationModeId == IDM_CREATION_MODE_TARGET_DCOMP)
{
HRESULT hr = DCompositionCreateDevice2(nullptr, IID_PPV_ARGS(&m_dcompDevice));
if (!SUCCEEDED(hr))
{
MessageBox(
m_mainWindow,
L"Attempting to create WebView using DComp Visual is not supported.\r\n"
"DComp device creation failed.\r\n"
"Current OS may not support DComp.",
L"Create with Windowless DComp Visual Failed", MB_OK);
return;
}
}
#ifdef USE_WEBVIEW2_WIN10
else if (m_creationModeId == IDM_CREATION_MODE_VISUAL_WINCOMP)
{
HRESULT hr = TryCreateDispatcherQueue();
if (!SUCCEEDED(hr))
{
MessageBox(
m_mainWindow,
L"Attempting to create WebView using WinComp Visual is not supported.\r\n"
"WinComp compositor creation failed.\r\n"
"Current OS may not support WinComp.",
L"Create with Windowless WinComp Visual Failed", MB_OK);
return;
}
m_wincompCompositor = winrtComp::Compositor();
}
#endif
//! [CreateCoreWebView2EnvironmentWithOptions]
auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
CHECK_FAILURE(options->put_AllowSingleSignOnUsingOSPrimaryAccount(
m_AADSSOEnabled ? TRUE : FALSE));
if (!m_language.empty())
CHECK_FAILURE(options->put_Language(m_language.c_str()));
HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(
subFolder, nullptr, options.Get(),
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
this, &AppWindow::OnCreateEnvironmentCompleted)
.Get());
//! [CreateCoreWebView2EnvironmentWithOptions]
if (!SUCCEEDED(hr))
{
if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
MessageBox(
m_mainWindow,
L"Couldn't find Edge installation. "
"Do you have a version installed that's compatible with this "
"WebView2 SDK version?",
nullptr, MB_OK);
}
else
{
ShowFailure(hr, L"Failed to create webview environment");
}
}
}
// This is the callback passed to CreateWebViewEnvironmentWithOptions.
// Here we simply create the WebView.
HRESULT AppWindow::OnCreateEnvironmentCompleted(
HRESULT result, ICoreWebView2Environment* environment)
{
CHECK_FAILURE(result);
m_webViewEnvironment = environment;
auto webViewExperimentalEnvironment =
m_webViewEnvironment.try_query<ICoreWebView2ExperimentalEnvironment>();
#ifdef USE_WEBVIEW2_WIN10
if (webViewExperimentalEnvironment && (m_dcompDevice || m_wincompCompositor))
#else
if (webViewExperimentalEnvironment && m_dcompDevice)
#endif
{
CHECK_FAILURE(webViewExperimentalEnvironment->CreateCoreWebView2CompositionController(
m_mainWindow,
Callback<
ICoreWebView2ExperimentalCreateCoreWebView2CompositionControllerCompletedHandler>(
[this](
HRESULT result,
ICoreWebView2ExperimentalCompositionController* compositionController) -> HRESULT {
auto controller =
wil::com_ptr<ICoreWebView2ExperimentalCompositionController>(compositionController)
.query<ICoreWebView2Controller>();
return OnCreateCoreWebView2ControllerCompleted(result, controller.get());
})
.Get()));
}
else
{
CHECK_FAILURE(m_webViewEnvironment->CreateCoreWebView2Controller(
m_mainWindow, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
this, &AppWindow::OnCreateCoreWebView2ControllerCompleted)
.Get()));
}
return S_OK;
}
//! [CreateCoreWebView2Controller]
// This is the callback passed to CreateCoreWebView2Controller. Here we initialize all WebView-related
// state and register most of our event handlers with the WebView.
HRESULT AppWindow::OnCreateCoreWebView2ControllerCompleted(HRESULT result, ICoreWebView2Controller* controller)
{
if (result == S_OK)
{
m_controller = controller;
wil::com_ptr<ICoreWebView2> coreWebView2;
CHECK_FAILURE(m_controller->get_CoreWebView2(&coreWebView2));
// We should check for failure here because if this app is using a newer
// SDK version compared to the install of the Edge browser, the Edge
// browser might not have support for the latest version of the
// ICoreWebView2_N interface.
coreWebView2.query_to(&m_webView);
// Create components. These will be deleted when the WebView is closed.
NewComponent<FileComponent>(this);
NewComponent<ProcessComponent>(this);
NewComponent<ScriptComponent>(this);
NewComponent<SettingsComponent>(
this, m_webViewEnvironment.get(), m_oldSettingsComponent.get());
m_oldSettingsComponent = nullptr;
NewComponent<ViewComponent>(
this, m_dcompDevice.get(),
#ifdef USE_WEBVIEW2_WIN10
m_wincompCompositor,
#endif
m_creationModeId == IDM_CREATION_MODE_TARGET_DCOMP);
NewComponent<ControlComponent>(this, &m_toolbar);
// We have a few of our own event handlers to register here as well
RegisterEventHandlers();
// Set the initial size of the WebView
ResizeEverything();
if (m_onWebViewFirstInitialized)
{
m_onWebViewFirstInitialized();
m_onWebViewFirstInitialized = nullptr;
}
if (m_initialUri.empty())
{
// StartPage uses initialized values of the WebView and Environment
// so we wait to call StartPage::GetUri until after the WebView is
// created.
m_initialUri = AppStartPage::GetUri(this);
}
if (m_initialUri != L"none")
{
CHECK_FAILURE(m_webView->Navigate(m_initialUri.c_str()));
}
}
else
{
ShowFailure(result, L"Failed to create webview");
}
return S_OK;
}
void AppWindow::ReinitializeWebView()
{
// Save the settings component from being deleted when the WebView is closed, so we can
// copy its properties to the next settings component.
m_oldSettingsComponent = MoveComponent<SettingsComponent>();
InitializeWebView();
}
void AppWindow::ReinitializeWebViewWithNewBrowser()
{
// Save the settings component from being deleted when the WebView is closed, so we can
// copy its properties to the next settings component.
m_oldSettingsComponent = MoveComponent<SettingsComponent>();
// Use the reference to the web view before we close it
UINT webviewProcessId = 0;
m_webView->get_BrowserProcessId(&webviewProcessId);
// We need to close the current webviews and wait for the browser_process to exit
// This is so the new webviews don't use the old browser exe
CloseWebView();
// Make sure the browser process inside webview is closed
ProcessComponent::EnsureProcessIsClosed(webviewProcessId, 2000);
InitializeWebView();
}
void AppWindow::RestartApp()
{
// Use the reference to the web view before we close the app window
UINT webviewProcessId = 0;
m_webView->get_BrowserProcessId(&webviewProcessId);
// To restart the app completely, first we close the current App Window
CloseAppWindow();
// Make sure the browser process inside webview is closed
ProcessComponent::EnsureProcessIsClosed(webviewProcessId, 2000);
// Get the command line arguments used to start this app
// so we can re-create the process with them
LPWSTR args = GetCommandLineW();
STARTUPINFOW startup_info = {0};
startup_info.cb = sizeof(startup_info);
PROCESS_INFORMATION temp_process_info = {};
// Start a new process
if (!::CreateProcess(
nullptr, args,
nullptr, // default process attributes
nullptr, // default thread attributes
FALSE, // do not inherit handles
0,
nullptr, // no environment
nullptr, // default current directory
&startup_info, &temp_process_info))
{
// Log some error information if desired
}
// Terminate this current process
::exit(0);
}
void AppWindow::RegisterEventHandlers()
{
//! [ContainsFullScreenElementChanged]
// Register a handler for the ContainsFullScreenChanged event.
CHECK_FAILURE(m_webView->add_ContainsFullScreenElementChanged(
Callback<ICoreWebView2ContainsFullScreenElementChangedEventHandler>(
[this](ICoreWebView2* sender, IUnknown* args) -> HRESULT {
if (m_fullScreenAllowed)
{
CHECK_FAILURE(
sender->get_ContainsFullScreenElement(&m_containsFullscreenElement));
if (m_containsFullscreenElement)
{
EnterFullScreen();
}
else
{
ExitFullScreen();
}
}
return S_OK;
})
.Get(),
nullptr));
//! [ContainsFullScreenElementChanged]
//! [NewWindowRequested]
// Register a handler for the NewWindowRequested event.
// This handler will defer the event, create a new app window, and then once the
// new window is ready, it'll provide that new window's WebView as the response to
// the request.
CHECK_FAILURE(m_webView->add_NewWindowRequested(
Callback<ICoreWebView2NewWindowRequestedEventHandler>(
[this](ICoreWebView2* sender, ICoreWebView2NewWindowRequestedEventArgs* args) {
wil::com_ptr<ICoreWebView2Deferral> deferral;
CHECK_FAILURE(args->GetDeferral(&deferral));
AppWindow* newAppWindow;
wil::com_ptr<ICoreWebView2WindowFeatures> windowFeatures;
CHECK_FAILURE(args->get_WindowFeatures(&windowFeatures));
RECT windowRect = {0};
UINT32 left = 0;
UINT32 top = 0;
UINT32 height = 0;
UINT32 width = 0;
BOOL shouldHaveToolbar = true;
BOOL hasPosition = FALSE;
BOOL hasSize = FALSE;
CHECK_FAILURE(windowFeatures->get_HasPosition(&hasPosition));
CHECK_FAILURE(windowFeatures->get_HasSize(&hasSize));
bool useDefaultWindow = true;
if (!!hasPosition && !!hasSize)
{
CHECK_FAILURE(windowFeatures->get_Left(&left));
CHECK_FAILURE(windowFeatures->get_Top(&top));
CHECK_FAILURE(windowFeatures->get_Height(&height));
CHECK_FAILURE(windowFeatures->get_Width(&width));
useDefaultWindow = false;
}
CHECK_FAILURE(windowFeatures->get_ShouldDisplayToolbar(&shouldHaveToolbar));
windowRect.left = left;
windowRect.right = left + (width < s_minNewWindowSize ? s_minNewWindowSize : width);
windowRect.top = top;
windowRect.bottom = top + (height < s_minNewWindowSize ? s_minNewWindowSize : height);
if (!useDefaultWindow)
{
newAppWindow = new AppWindow(m_creationModeId, L"", false, nullptr, true, windowRect, !!shouldHaveToolbar);
}
else
{
newAppWindow = new AppWindow(m_creationModeId, L"");
}
newAppWindow->m_isPopupWindow = true;
newAppWindow->m_onWebViewFirstInitialized = [args, deferral, newAppWindow]() {
CHECK_FAILURE(args->put_NewWindow(newAppWindow->m_webView.get()));
CHECK_FAILURE(args->put_Handled(TRUE));
CHECK_FAILURE(deferral->Complete());
};
return S_OK;
})
.Get(),
nullptr));
//! [NewWindowRequested]
//! [WindowCloseRequested]
// Register a handler for the WindowCloseRequested event.
// This handler will close the app window if it is not the main window.
CHECK_FAILURE(m_webView->add_WindowCloseRequested(
Callback<ICoreWebView2WindowCloseRequestedEventHandler>([this](
ICoreWebView2* sender,
IUnknown* args) {
if (m_isPopupWindow)
{
CloseAppWindow();
}
return S_OK;
}).Get(),
nullptr));
//! [WindowCloseRequested]
//! [NewBrowserVersionAvailable]
// After the environment is successfully created,
// register a handler for the NewBrowserVersionAvailable event.
// This handler tells when there is a new Edge version available on the machine.
CHECK_FAILURE(m_webViewEnvironment->add_NewBrowserVersionAvailable(
Callback<ICoreWebView2NewBrowserVersionAvailableEventHandler>(
[this](ICoreWebView2Environment* sender, IUnknown* args) -> HRESULT {
std::wstring message = L"We detected there is a new version for the browser.";
if (m_webView)
{
message += L"Do you want to restart the app? \n\n";
message += L"Click No if you only want to re-create the webviews. \n";
message += L"Click Cancel for no action. \n";
}
int response = MessageBox(
m_mainWindow, message.c_str(), L"New available version",
m_webView ? MB_YESNOCANCEL : MB_OK);
if (response == IDYES)
{
RestartApp();
}
else if (response == IDNO)
{
ReinitializeWebViewWithNewBrowser();
}
else
{
// do nothing
}
return S_OK;
})
.Get(),
nullptr));
//! [NewBrowserVersionAvailable]
}
// Updates the sizing and positioning of everything in the window.
void AppWindow::ResizeEverything()
{
RECT availableBounds = {0};
GetClientRect(m_mainWindow, &availableBounds);
if (!m_containsFullscreenElement)
{
availableBounds = m_toolbar.Resize(availableBounds);
}
if (auto view = GetComponent<ViewComponent>())
{
view->SetBounds(availableBounds);
}
}
//! [Close]
// Close the WebView and deinitialize related state. This doesn't close the app window.
void AppWindow::CloseWebView(bool cleanupUserDataFolder)
{
DeleteAllComponents();
if (m_controller)
{
m_controller->Close();
m_controller = nullptr;
m_webView = nullptr;
}
m_webViewEnvironment = nullptr;
if (cleanupUserDataFolder)
{
// For non-UWP apps, the default user data folder {Executable File Name}.WebView2
// is in the same directory next to the app executable. If end
// developers specify userDataFolder during WebView environment
// creation, they would need to pass in that explicit value here.
// For more information about userDataFolder:
// https://docs.microsoft.com/microsoft-edge/webview2/reference/win32/webview2-idl#createcorewebview2environmentwithoptions
WCHAR userDataFolder[MAX_PATH] = L"";
// Obtain the absolute path for relative paths that include "./" or "../"
_wfullpath(
userDataFolder, GetLocalPath(L".WebView2", true).c_str(), MAX_PATH);
std::wstring userDataFolderPath(userDataFolder);
std::wstring message = L"Are you sure you want to clean up the user data folder at\n";
message += userDataFolderPath;
message += L"\n?\nWarning: This action is not reversible.\n\n";
message += L"Click No if there are other open WebView instances.\n";
if (MessageBox(m_mainWindow, message.c_str(), L"Cleanup User Data Folder", MB_YESNO) ==
IDYES)
{
CHECK_FAILURE(DeleteFileRecursive(userDataFolderPath));
}
}
}
//! [Close]
HRESULT AppWindow::DeleteFileRecursive(std::wstring path)
{
wil::com_ptr<IFileOperation> fileOperation;
CHECK_FAILURE(
CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL, IID_PPV_ARGS(&fileOperation)));
// Turn off all UI from being shown to the user during the operation.
CHECK_FAILURE(fileOperation->SetOperationFlags(FOF_NO_UI));
wil::com_ptr<IShellItem> userDataFolder;
CHECK_FAILURE(
SHCreateItemFromParsingName(path.c_str(), NULL, IID_PPV_ARGS(&userDataFolder)));
// Add the operation
CHECK_FAILURE(fileOperation->DeleteItem(userDataFolder.get(), NULL));
CHECK_FAILURE(userDataFolder->Release());
// Perform the operation to delete the directory