forked from MicrosoftEdge/WebView2Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppWindow.cpp
More file actions
810 lines (731 loc) · 25.6 KB
/
AppWindow.cpp
File metadata and controls
810 lines (731 loc) · 25.6 KB
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
// 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 <functional>
#include <string>
#include <vector>
#include <ShObjIdl_core.h>
#include <Shellapi.h>
#include "App.h"
#include "CheckFailure.h"
#include "ControlComponent.h"
#include "FileComponent.h"
#include "ProcessComponent.h"
#include "Resource.h"
#include "ScenarioAddRemoteObject.h"
#include "ScenarioWebMessage.h"
#include "ScenarioWebViewEventMonitor.h"
#include "ScriptComponent.h"
#include "SettingsComponent.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;
// Creates a new window which is a copy of the entire app, but on the same thread.
AppWindow::AppWindow(std::wstring initialUri, std::function<void()> webviewCreatedCallback)
: m_initialUri(initialUri), m_onWebViewFirstInitialized(webviewCreatedCallback)
{
++s_appInstances;
WCHAR szTitle[s_maxLoadString]; // The title bar text
LoadStringW(g_hInstance, IDS_APP_TITLE, szTitle, s_maxLoadString);
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);
m_toolbar.Initialize(m_mainWindow);
ShowWindow(m_mainWindow, g_nCmdShow);
UpdateWindow(m_mainWindow);
RunAsync([this] {
InitializeWebView();
});
}
// 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;
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:
{
SetWindowLongPtr(hWnd, GWLP_USERDATA, NULL);
delete this;
if (--s_appInstances == 0)
{
PostQuitMessage(0);
}
}
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:
{
//! [GetBrowserVersionInfo]
wil::unique_cotaskmem_string version_info;
m_webViewEnvironment->get_BrowserVersionInfo(&version_info);
MessageBox(
m_mainWindow, version_info.get(), L"Browser Version Info After WebView Creation",
MB_OK);
//! [GetBrowserVersionInfo]
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_REMOTE_OBJECT:
{
NewComponent<ScenarioAddRemoteObject>(this);
return true;
}
case IDM_SCENARIO_WEB_VIEW_EVENT_MONITOR:
{
NewComponent<ScenarioWebViewEventMonitor>(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;
GetCoreWebView2BrowserVersionInfo(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_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();
return true;
case IDM_NEW_THREAD:
CreateNewThread();
return true;
}
return false;
}
// 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(); };
case 'Q':
return [this] { CloseAppWindow(); };
case 'S':
return [this] {
if (auto file = GetComponent<FileComponent>())
{
file->SaveScreenshot();
}
};
case 'T':
return [this] { CreateNewThread(); };
case 'W':
return [this] { CloseWebView(); };
}
}
return nullptr;
}
//! [CreateCoreWebView2Host]
// 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();
LPCWSTR subFolder = nullptr;
LPCWSTR additionalBrowserSwitches = nullptr;
HRESULT hr = CreateCoreWebView2EnvironmentWithDetails(
subFolder, nullptr, additionalBrowserSwitches,
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
this, &AppWindow::OnCreateEnvironmentCompleted)
.Get());
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 CreateWebViewEnvironmnetWithDetails.
// Here we simply create the WebView.
HRESULT AppWindow::OnCreateEnvironmentCompleted(
HRESULT result, ICoreWebView2Environment* environment)
{
CHECK_FAILURE(result);
CHECK_FAILURE(environment->QueryInterface(IID_PPV_ARGS(&m_webViewEnvironment)));
CHECK_FAILURE(m_webViewEnvironment->CreateCoreWebView2Host(
m_mainWindow, Callback<ICoreWebView2CreateCoreWebView2HostCompletedHandler>(
this, &AppWindow::OnCreateCoreWebView2HostCompleted)
.Get()));
return S_OK;
}
//! [CreateCoreWebView2Host]
// This is the callback passed to CreateCoreWebView2Host. Here we initialize all WebView-related
// state and register most of our event handlers with the WebView.
HRESULT AppWindow::OnCreateCoreWebView2HostCompleted(
HRESULT result, ICoreWebView2Host* host)
{
if (result == S_OK)
{
m_host = host;
ICoreWebView2* coreWebView2;
CHECK_FAILURE(m_host->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.
CHECK_FAILURE(coreWebView2->QueryInterface(IID_PPV_ARGS(&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);
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())
{
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));
auto newAppWindow = new AppWindow(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,
ICoreWebView2NewBrowserVersionAvailableEventArgs* args) -> HRESULT {
// Get the version value from args
wil::unique_cotaskmem_string newVersion;
CHECK_FAILURE(args->get_NewVersion(&newVersion));
std::wstring message = L"We detected there is a new version for the browser.";
message += L"\n\nVersion number: ";
message += newVersion.get();
message += L"\n\n";
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_host)
{
m_host->Close();
m_host = 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/hosting/webview2/reference/webview2.idl#createwebview2environmentwithdetails
WCHAR userDataFolder[MAX_PATH] = L"";
// Obtain the absolute path for relative paths that include "./" or "../"
_wfullpath(
userDataFolder, GetLocalPath(L"WebView2APISample.exe.WebView2").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 instnaces.\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)
{
// Initialize COM as STA.
CHECK_FAILURE(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
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
CHECK_FAILURE(fileOperation->PerformOperations());
CHECK_FAILURE(fileOperation->Release());
CoUninitialize();
return S_OK;
}
void AppWindow::CloseAppWindow()
{
CloseWebView();
DestroyWindow(m_mainWindow);
}
void AppWindow::DeleteComponent(ComponentBase* component)
{
for (auto iter = m_components.begin(); iter != m_components.end(); iter++)
{
if (iter->get() == component)
{
m_components.erase(iter);
return;
}
}
}
void AppWindow::DeleteAllComponents()
{
// Delete components in reverse order of initialization.
while (!m_components.empty())
{
m_components.pop_back();
}
}
template <class ComponentType> std::unique_ptr<ComponentType> AppWindow::MoveComponent()
{
for (auto iter = m_components.begin(); iter != m_components.end(); iter++)
{
if (dynamic_cast<ComponentType*>(iter->get()))
{
auto wanted = reinterpret_cast<std::unique_ptr<ComponentType>&&>(std::move(*iter));
m_components.erase(iter);
return std::move(wanted);
}
}
return nullptr;
}
void AppWindow::SetTitleText(PCWSTR titleText)
{
SetWindowText(m_mainWindow, titleText);
}
RECT AppWindow::GetWindowBounds()
{
RECT hwndBounds = {0};
GetClientRect(m_mainWindow, &hwndBounds);
return hwndBounds;
}
std::wstring AppWindow::GetLocalPath(std::wstring relativePath)
{
WCHAR rawPath[MAX_PATH];
GetModuleFileNameW(g_hInstance, rawPath, MAX_PATH);
std::wstring path(rawPath);
std::size_t index = path.find_last_of(L"\\") + 1;
path.replace(index, path.length(), relativePath);
return path;
}
std::wstring AppWindow::GetLocalUri(std::wstring relativePath)
{
std::wstring path = GetLocalPath(relativePath);
wil::com_ptr<IUri> uri;
CHECK_FAILURE(CreateUri(path.c_str(), Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME, 0, &uri));
wil::unique_bstr uriBstr;
CHECK_FAILURE(uri->GetAbsoluteUri(&uriBstr));
return std::wstring(uriBstr.get());
}
void AppWindow::RunAsync(std::function<void()> callback)
{
auto* task = new std::function<void()>(callback);
PostMessage(m_mainWindow, s_runAsyncWindowMessage, reinterpret_cast<WPARAM>(task), 0);
}
void AppWindow::EnterFullScreen()
{
DWORD style = GetWindowLong(m_mainWindow, GWL_STYLE);
MONITORINFO monitor_info = {sizeof(monitor_info)};
m_hMenu = ::GetMenu(m_mainWindow);
::SetMenu(m_mainWindow, nullptr);
if (GetWindowPlacement(m_mainWindow, &m_previousPlacement) &&
GetMonitorInfo(
MonitorFromWindow(m_mainWindow, MONITOR_DEFAULTTOPRIMARY), &monitor_info))
{
SetWindowLong(m_mainWindow, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW);
SetWindowPos(
m_mainWindow, HWND_TOP, monitor_info.rcMonitor.left, monitor_info.rcMonitor.top,
monitor_info.rcMonitor.right - monitor_info.rcMonitor.left,
monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top,
SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
}
void AppWindow::ExitFullScreen()
{
DWORD style = GetWindowLong(m_mainWindow, GWL_STYLE);
::SetMenu(m_mainWindow, m_hMenu);
SetWindowLong(m_mainWindow, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
SetWindowPlacement(m_mainWindow, &m_previousPlacement);
SetWindowPos(
m_mainWindow, NULL, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}