-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathwebview.hpp
1152 lines (984 loc) · 35.4 KB
/
webview.hpp
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
#ifndef WEBVIEW_H
#define WEBVIEW_H
#if !defined(WEBVIEW_WIN) && !defined(WEBVIEW_EDGE) && \
!defined(WEBVIEW_MAC) && !defined(WEBVIEW_GTK)
#error "Define one of WEBVIEW_WIN, WEBVIEW_EDGE, WEBVIEW_MAC, or WEBVIEW_GTK"
#endif
#if defined(WEBVIEW_WIN) || defined(WEBVIEW_EDGE)
#define WEBVIEW_IS_WIN
#endif
// Helper defines
#if defined(WEBVIEW_IS_WIN)
#define WEBVIEW_MAIN int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
#define GetProcNameAddress(hmod, proc) \
reinterpret_cast<decltype(proc)*>(GetProcAddress(hmod, #proc))
#define UNICODE
#define _UNICODE
#define Str(s) L##s
#else
#define WEBVIEW_MAIN int main(int, char**)
#define Str(s) s
#endif
// Headers
#include <functional>
#include <string>
#if defined(WEBVIEW_WIN)
#define WIN32_LEAN_AND_MEAN
#pragma comment(lib, "windowsapp")
#include <objbase.h>
#include <shellscalingapi.h>
#include <windows.h>
#include <winrt/Windows.Web.UI.Interop.h>
#include <memory>
#include <type_traits>
#include <utility>
#pragma warning(push)
#pragma warning(disable : 4265)
#include <winrt/Windows.Foundation.Collections.h>
#pragma warning(pop)
#elif defined(WEBVIEW_EDGE) // WEBVIEW_WIN
#pragma comment(lib, "Advapi32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "user32.lib")
#include <WebView2.h>
#include <shellscalingapi.h>
#include <shlwapi.h>
#include <tchar.h>
#include <wil/com.h>
#include <windows.h>
#include <wrl.h>
#include <cstdlib>
#include <utility>
#elif defined(WEBVIEW_MAC) // WEBVIEW_EDGE
#import <Cocoa/Cocoa.h>
#import <Webkit/Webkit.h>
#include <objc/objc-runtime.h>
// ObjC declarations may only appear in global scope
@interface WindowDelegate : NSObject <NSWindowDelegate, WKScriptMessageHandler>
@end
@implementation WindowDelegate
- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)scriptMessage {
}
@end
#elif defined(WEBVIEW_GTK) // WEBVIEW_MAC
#include <JavaScriptCore/JavaScript.h>
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>
#endif
constexpr auto DEFAULT_URL = Str(R"(data:text/html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<div id="app"></div>
<script type="text/javascript"></script>
</body>
</html>)");
namespace wv {
// wv::String
#if defined(WEBVIEW_IS_WIN)
using String = std::wstring;
#else
using String = std::string;
#endif
// Namespaces
#if defined(WEBVIEW_WIN)
using namespace winrt::impl;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Windows::Web::UI::Interop;
#elif defined(WEBVIEW_EDGE)
using namespace Microsoft::WRL;
#endif
class WebView {
using jscb = std::function<void(WebView&, String&)>;
public:
WebView(int width_ = 800, int height_ = 600, bool resizable_ = true,
bool debug_ = true, const String& title_ = Str("Webview"),
const String& url_ = DEFAULT_URL)
: width(width_),
height(height_),
resizable(resizable_),
debug(debug_),
title(title_),
url(url_) {}
int init(); // Initialize webview
void setCallback(jscb callback); // JS callback
void setTitle(String t); // Set title of window
void setFullscreen(bool fs); // Set fullscreen
void setFullscreenFromJS(bool allow); // Allow setting fullscreen from JS
void setBgColor(uint8_t r, uint8_t g, uint8_t b,
uint8_t a); // Set background color
bool run(); // Main loop
void navigate(String u); // Navigate to URL
void preEval(const String& js); // Eval JS before page loads
void eval(const String& js); // Eval JS
void css(const String& css); // Inject CSS
void exit(); // Stop loop
private:
// Properties for init
int width;
int height;
bool resizable;
bool fullscreen = false;
bool fullscreenFromJS = false;
bool debug;
String title;
String url;
jscb js_callback;
bool init_done = false; // Finished running init
uint8_t bgR = 255, bgG = 255, bgB = 255, bgA = 255;
// Common Windows stuff
#if defined(WEBVIEW_IS_WIN)
HWND hwnd = nullptr;
MSG msg{}; // Message from main loop
bool isFullscreen = false;
UINT dpi = USER_DEFAULT_SCREEN_DPI;
struct WindowInfo {
LONG_PTR style; // GWL_STYLE
LONG_PTR exstyle; // GWL_EXSTYLE
RECT rect; // GetWindowRect
} savedWindowInfo{};
int WinInit();
void onDPIChange(const UINT dpi, const RECT& rect);
void resize();
static LRESULT CALLBACK WndProcedure(HWND hwnd, UINT msg, WPARAM wparam,
LPARAM lparam);
#endif // WEBVIEW_WIN || WEBVIEW_EDGE
#if defined(WEBVIEW_WIN)
String inject =
Str("window.external.invoke=arg=>window.external.notify(arg);");
WebViewControl webview{nullptr};
#elif defined(WEBVIEW_EDGE) // WEBVIEW_WIN
String inject = Str(
"window.external.invoke=arg=>window.chrome.webview.postMessage(arg);");
wil::com_ptr<ICoreWebView2Controller>
webviewController; // Pointer to WebViewController
wil::com_ptr<ICoreWebView2> webviewWindow; // Pointer to WebView window
#elif defined(WEBVIEW_MAC) // WEBVIEW_EDGE
String inject =
Str("window.external={invoke:arg=>window.webkit."
"messageHandlers.webview.postMessage(arg)};");
bool should_exit = false; // Close window
NSAutoreleasePool* pool;
NSWindow* window;
WKWebView* webview;
#elif defined(WEBVIEW_GTK) // WEBVIEW_MAC
String inject =
Str("window.external={invoke:arg=>window.webkit."
"messageHandlers.external.postMessage(arg)};");
bool ready = false; // Done loading page
bool js_busy = false; // Currently in JS eval
bool should_exit = false; // Close window
GtkWidget* window;
GtkWidget* webview;
static void external_message_received_cb(WebKitUserContentManager* m,
WebKitJavascriptResult* r,
gpointer arg);
static void webview_eval_finished(GObject* object, GAsyncResult* result,
gpointer arg);
static void webview_load_changed_cb(WebKitWebView* webview,
WebKitLoadEvent event, gpointer arg);
static void destroyWindowCb(GtkWidget* widget, gpointer arg);
// static gboolean closeWebViewCb(WebKitWebView *webView, GtkWidget
// *window);
static gboolean webview_context_menu_cb(
WebKitWebView* webview, GtkWidget* default_menu,
WebKitHitTestResult* hit_test_result, gboolean triggered_with_keyboard,
gpointer userdata);
static gboolean webview_enter_fullscreen_cb(WebKitWebView* webview,
gpointer userdata);
static gboolean webview_leave_fullscreen_cb(WebKitWebView* webview,
gpointer userdata);
#endif // WEBVIEW_GTK
};
// Common Windows methods
#if defined(WEBVIEW_IS_WIN)
auto LoadLibraryPtr(LPCWSTR dll) {
// WIL alternative: wil::unique_hmodule(LoadLibrary(dll));
return std::unique_ptr<std::remove_pointer_t<HMODULE>,
decltype(&::FreeLibrary)>(LoadLibrary(dll),
FreeLibrary);
}
void setDPIAwareness() {
// Set default DPI awareness
auto user32 = LoadLibraryPtr(TEXT("User32.dll"));
auto pSPDAC =
GetProcNameAddress(user32.get(), SetProcessDpiAwarenessContext);
if (pSPDAC != nullptr) {
// Windows 10
pSPDAC(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
return;
}
auto shcore = LoadLibraryPtr(TEXT("ShCore.dll"));
auto pSPDA = GetProcNameAddress(shcore.get(), SetProcessDpiAwareness);
if (pSPDA != nullptr) {
// Windows 8.1
pSPDA(PROCESS_PER_MONITOR_DPI_AWARE);
return;
}
// Windows Vista
SetProcessDPIAware(); // Equivalent to DPI_AWARENESS_CONTEXT_SYSTEM_AWARE
}
UINT getDPI(HWND hwnd) {
auto user32 = LoadLibraryPtr(TEXT("User32.dll"));
auto pGDFW = GetProcNameAddress(user32.get(), GetDpiForWindow);
if (pGDFW != nullptr) {
// Windows 10
return pGDFW(hwnd);
}
auto shcore = LoadLibraryPtr(TEXT("ShCore.dll"));
auto pGDFM = GetProcNameAddress(shcore.get(), GetDpiForMonitor);
if (pGDFM != nullptr) {
// Windows 8.1
UINT newDpi;
HMONITOR hmonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
HRESULT hr = pGDFM(hmonitor, MDT_EFFECTIVE_DPI, &newDpi, nullptr);
if (SUCCEEDED(hr)) {
return newDpi;
}
}
// Windows 2000
if (HDC hdc = GetDC(hwnd)) {
auto dpi = GetDeviceCaps(hdc, LOGPIXELSX);
ReleaseDC(hwnd, hdc);
return dpi;
}
return USER_DEFAULT_SCREEN_DPI;
}
int WebView::WinInit() {
HINSTANCE hInt = GetModuleHandle(nullptr);
if (hInt == nullptr) {
return -1;
}
// Initialize Win32 window
WNDCLASSEX wc{};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProcedure;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInt;
wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = nullptr;
wc.lpszClassName = L"webview";
wc.hIconSm = LoadIcon(nullptr, IDI_APPLICATION);
if (!RegisterClassEx(&wc)) {
MessageBox(nullptr, L"Call to RegisterClassEx failed!", L"Error!",
NULL);
return -1;
}
// Set default DPI awareness
setDPIAwareness();
hwnd = CreateWindow(L"webview", title.c_str(), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, width, height, nullptr,
nullptr, hInt, nullptr);
if (hwnd == nullptr) {
MessageBox(nullptr, L"Window Registration Failed!", L"Error!",
MB_ICONEXCLAMATION | MB_OK);
return -1;
}
// Scale window based on DPI
dpi = getDPI(hwnd);
RECT rect = {};
GetWindowRect(hwnd, &rect);
SetWindowPos(hwnd, nullptr, rect.left, rect.top,
MulDiv(width, dpi, USER_DEFAULT_SCREEN_DPI),
MulDiv(height, dpi, USER_DEFAULT_SCREEN_DPI),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
if (!resizable) {
auto style = GetWindowLongPtr(hwnd, GWL_STYLE);
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
SetWindowLongPtr(hwnd, GWL_STYLE, style);
}
// Used with GetWindowLongPtr in WndProcedure
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this);
ShowWindow(hwnd, SW_SHOWDEFAULT);
UpdateWindow(hwnd);
SetFocus(hwnd);
return 0;
}
void WebView::setTitle(std::wstring t) {
if (!init_done) {
title = t;
} else {
SetWindowText(hwnd, t.c_str());
}
}
// Adapted from
// https://source.chromium.org/chromium/chromium/src/+/main:ui/views/win/fullscreen_handler.cc
void WebView::setFullscreen(bool fs) {
if (isFullscreen == fs) return;
isFullscreen = fs;
if (fs) {
// Store window style before going fullscreen
savedWindowInfo.style = GetWindowLongPtr(hwnd, GWL_STYLE);
savedWindowInfo.exstyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
GetWindowRect(hwnd, &savedWindowInfo.rect);
// Set new window style
SetWindowLongPtr(hwnd, GWL_STYLE,
savedWindowInfo.style & ~(WS_CAPTION | WS_THICKFRAME));
SetWindowLongPtr(
hwnd, GWL_EXSTYLE,
savedWindowInfo.exstyle & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE |
WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
// Get monitor size
MONITORINFO monitorInfo;
monitorInfo.cbSize = sizeof(monitorInfo);
GetMonitorInfo(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST),
&monitorInfo);
// Set window size to monitor size
SetWindowPos(hwnd, nullptr, monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.top,
monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
} else {
// Restore window style
SetWindowLongPtr(hwnd, GWL_STYLE, savedWindowInfo.style);
SetWindowLongPtr(hwnd, GWL_EXSTYLE, savedWindowInfo.exstyle);
// Restore window size
SetWindowPos(hwnd, nullptr, savedWindowInfo.rect.left,
savedWindowInfo.rect.top,
savedWindowInfo.rect.right - savedWindowInfo.rect.left,
savedWindowInfo.rect.bottom - savedWindowInfo.rect.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
}
bool WebView::run() {
bool loop = GetMessage(&msg, nullptr, 0, 0) > 0;
if (loop) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return !loop;
}
LRESULT CALLBACK WebView::WndProcedure(HWND hwnd, UINT msg, WPARAM wparam,
LPARAM lparam) {
WebView* w =
reinterpret_cast<WebView*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
switch (msg) {
case WM_SIZE:
// WM_SIZE will first fire before the webview finishes loading
// init() calls resize(), so this call is only for size changes
// after fully loading.
if (w != nullptr && w->init_done) {
w->resize();
}
return DefWindowProc(hwnd, msg, wparam, lparam);
case WM_DPICHANGED:
if (w != nullptr) {
// Resize on DPI change
UINT dpi = HIWORD(wparam);
const auto& rect = *reinterpret_cast<RECT*>(lparam);
w->onDPIChange(dpi, rect);
}
break;
case WM_DESTROY:
w->exit();
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
void WebView::onDPIChange(const UINT newDpi, const RECT& rect) {
auto oldDpi = std::exchange(dpi, newDpi);
if (isFullscreen) {
// Scale the saved window size by the change in DPI
auto oldWidth = savedWindowInfo.rect.right - savedWindowInfo.rect.left;
auto oldHeight = savedWindowInfo.rect.bottom - savedWindowInfo.rect.top;
savedWindowInfo.rect.right =
savedWindowInfo.rect.left + MulDiv(oldWidth, newDpi, oldDpi);
savedWindowInfo.rect.bottom =
savedWindowInfo.rect.top + MulDiv(oldHeight, newDpi, oldDpi);
} else {
SetWindowPos(hwnd, nullptr, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
}
#endif
#if defined(WEBVIEW_WIN)
// Await helper
template <typename T>
auto block(T const& async) {
if (async.Status() != AsyncStatus::Completed) {
winrt::handle h(CreateEvent(nullptr, false, false, nullptr));
async.Completed([h = h.get()](auto, auto) { SetEvent(h); });
HANDLE hs[] = {h.get()};
DWORD i;
CoWaitForMultipleHandles(COWAIT_DISPATCH_WINDOW_MESSAGES |
COWAIT_DISPATCH_CALLS |
COWAIT_INPUTAVAILABLE,
INFINITE, 1, hs, &i);
}
return async.GetResults();
}
int WebView::init() {
if (auto res = WinInit(); res) {
return res;
}
// Set to single-thread
init_apartment(winrt::apartment_type::single_threaded);
// Allow intranet access (and localhost)
WebViewControlProcessOptions options;
options.PrivateNetworkClientServerCapability(
WebViewControlProcessCapabilityState::Enabled);
WebViewControlProcess proc(options);
webview = block(proc.CreateWebViewControlAsync(
reinterpret_cast<int64_t>(hwnd), Rect()));
webview.Settings().IsScriptNotifyAllowed(true);
webview.ScriptNotify([this](const auto&, const auto& args) {
if (js_callback) {
std::wstring ws{args.Value()};
js_callback(*this, ws);
}
});
webview.NavigationStarting([this](const auto&, const auto&) {
webview.AddInitializeScript(inject);
});
// Detect fullscreen request from JS
webview.ContainsFullScreenElementChanged([this](const auto&, const auto&) {
if (fullscreenFromJS) {
this->setFullscreen(webview.ContainsFullScreenElement());
}
});
// Set webview bounds
resize();
webview.IsVisible(true);
// Done initialization, set properties
init_done = true;
setTitle(title);
if (fullscreen) {
setFullscreen(true);
}
setBgColor(bgR, bgG, bgB, bgA);
navigate(url);
return 0;
}
void WebView::setFullscreenFromJS(bool allow) { fullscreenFromJS = allow; }
void WebView::setBgColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
if (!init_done) {
bgR = r;
bgG = g;
bgB = b;
bgA = a;
} else {
webview.DefaultBackgroundColor({a, r, g, b});
}
}
void WebView::navigate(std::wstring u) {
if (!init_done) {
url = u;
} else if (constexpr auto prefix = L"data:text/html,";
u.rfind(prefix, 0) == 0) {
constexpr auto len = std::wstring_view(prefix).size();
webview.NavigateToString(u.substr(len));
} else {
Uri uri{u};
webview.Navigate(uri);
}
}
void WebView::eval(const std::wstring& js) {
auto result = block(webview.InvokeScriptAsync(
L"eval", std::vector<winrt::hstring>({winrt::hstring(js)})));
// if (debug) {
// std::cout << winrt::to_string(result) << std::endl;
//}
}
void WebView::exit() { PostQuitMessage(WM_QUIT); }
void WebView::resize() {
RECT rc;
GetClientRect(hwnd, &rc);
Rect bounds((float)rc.left, (float)rc.top, (float)(rc.right - rc.left),
(float)(rc.bottom - rc.top));
webview.Bounds(bounds);
}
#elif defined(WEBVIEW_EDGE) // WEBVIEW_WIN
int WebView::init() {
if (auto res = WinInit(); res) {
return res;
}
// Set to single-thread
auto inithr = CoInitializeEx(
nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (FAILED(inithr)) {
return -1;
}
auto onWebMessageReceieved =
[this](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) {
if (js_callback) {
// Consider args->get_WebMessageAsJson?
LPWSTR messageRaw;
auto getMessageResult =
args->TryGetWebMessageAsString(&messageRaw);
if (FAILED(getMessageResult)) {
return getMessageResult;
}
std::wstring message(messageRaw);
js_callback(*this, message);
CoTaskMemFree(messageRaw);
}
return S_OK;
};
auto onWebViewControllerCreate =
[this, onWebMessageReceieved](
HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
if (FAILED(result)) {
return result;
}
if (controller != nullptr) {
webviewController = controller;
webviewController->get_CoreWebView2(&webviewWindow);
}
wil::com_ptr<ICoreWebView2Settings> settings;
webviewWindow->get_Settings(&settings);
if (!debug) {
settings->put_AreDevToolsEnabled(FALSE);
}
// Resize WebView
resize();
webviewWindow->AddScriptToExecuteOnDocumentCreated(inject.c_str(),
nullptr);
webviewWindow->add_WebMessageReceived(
Callback<ICoreWebView2WebMessageReceivedEventHandler>(
onWebMessageReceieved)
.Get(),
nullptr);
// Detect fullscreen change from JS
webviewWindow->add_ContainsFullScreenElementChanged(
Callback<ICoreWebView2ContainsFullScreenElementChangedEventHandler>(
[this](ICoreWebView2*, IUnknown*) {
if (fullscreenFromJS) {
BOOL containsFs = false;
webviewWindow->get_ContainsFullScreenElement(
&containsFs);
this->setFullscreen(containsFs);
}
return S_OK;
})
.Get(),
nullptr);
// Done initialization, set properties
init_done = true;
setTitle(title);
if (fullscreen) {
setFullscreen(true);
}
setBgColor(bgR, bgG, bgB, bgA);
navigate(url);
return S_OK;
};
auto onCreateEnvironment = [this, onWebViewControllerCreate](
HRESULT result,
ICoreWebView2Environment* env) -> HRESULT {
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) {
MessageBox(nullptr, L"Could not find Edge installation.", L"Error!",
NULL);
return result;
}
// Create Webview2 controller
return env->CreateCoreWebView2Controller(
hwnd,
Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
onWebViewControllerCreate)
.Get());
};
// Get APPDATA path
PCWSTR userDataFolderPtr = nullptr;
std::wstring userDataFolder;
DWORD bufferLength = 32767;
std::wstring appdataPath;
appdataPath.resize(bufferLength);
bufferLength = GetEnvironmentVariable(Str("APPDATA"), appdataPath.data(),
bufferLength);
if (bufferLength) {
appdataPath.resize(bufferLength);
// Get executable file name
wchar_t exePath[MAX_PATH];
GetModuleFileName(NULL, exePath, MAX_PATH);
userDataFolder = (appdataPath + Str("/") + PathFindFileName(exePath));
userDataFolderPtr = userDataFolder.c_str();
}
// Create WebView2 environment
auto hr = CreateCoreWebView2EnvironmentWithOptions(
nullptr, userDataFolderPtr, nullptr,
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
onCreateEnvironment)
.Get());
if (FAILED(hr)) {
CoUninitialize();
return -1;
}
return 0;
}
void WebView::setFullscreenFromJS(bool allow) { fullscreenFromJS = allow; }
void WebView::setBgColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
if (!init_done) {
bgR = r;
bgG = g;
bgB = b;
bgA = a;
} else {
// TODO
}
}
void WebView::navigate(std::wstring u) {
if (!init_done) {
url = u;
} else {
webviewWindow->Navigate(u.c_str());
}
}
void WebView::eval(const std::wstring& js) {
// Schedule an async task to get the document URL
webviewWindow->ExecuteScript(
js.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT, LPCWSTR) -> HRESULT {
// LPCWSTR URL = resultObjectAsJson;
// doSomethingWithURL(URL);
return S_OK;
})
.Get());
// if (debug) {
// std::cout << winrt::to_string(result) << std::endl;
//}
}
void WebView::exit() {
PostQuitMessage(WM_QUIT);
CoUninitialize();
}
void WebView::resize() {
RECT rc;
GetClientRect(hwnd, &rc);
webviewController->put_Bounds(rc);
}
#elif defined(WEBVIEW_MAC) // WEBVIEW_EDGE
int WebView::init() {
// Initialize autorelease pool
pool = [NSAutoreleasePool new];
// Window style: titled, closable, minimizable
uint style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable;
// Set window to be resizable
if (resizable) {
style |= NSWindowStyleMaskResizable;
}
// Initialize Cocoa window
window = [[NSWindow alloc]
// Initial window size
initWithContentRect:NSMakeRect(0, 0, width, height)
// Window style
styleMask:style
backing:NSBackingStoreBuffered
defer:NO];
// Minimum window size
[window setContentMinSize:NSMakeSize(width, height)];
// Position window in center of screen
[window center];
// Initialize WKWebView
WKWebViewConfiguration* config = [WKWebViewConfiguration new];
WKPreferences* prefs = [config preferences];
[prefs setJavaScriptCanOpenWindowsAutomatically:NO];
if (debug) {
[prefs setValue:@YES forKey:@"developerExtrasEnabled"];
}
// Allow fullscreen control from JS
if (fullscreenFromJS) {
[prefs setValue:@YES forKey:@"fullScreenEnabled"];
}
WKUserContentController* controller = [config userContentController];
// Add inject script
WKUserScript* userScript = [WKUserScript alloc];
[userScript initWithSource:[NSString stringWithUTF8String:inject.c_str()]
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[controller addUserScript:userScript];
webview = [[WKWebView alloc] initWithFrame:NSZeroRect configuration:config];
// Add delegate methods manually in order to capture "this"
class_replaceMethod(
[WindowDelegate class], @selector(windowWillClose:),
imp_implementationWithBlock([=](id, SEL, id) { this->exit(); }),
"v@:@");
class_replaceMethod(
[WindowDelegate class],
@selector(userContentController:didReceiveScriptMessage:),
imp_implementationWithBlock(
[=](id, SEL, WKScriptMessage* scriptMessage) {
if (this->js_callback) {
id body = [scriptMessage body];
if (![body isKindOfClass:[NSString class]]) {
return;
}
std::string msg = [body UTF8String];
this->js_callback(*this, msg);
}
}),
"v@:@");
WindowDelegate* delegate = [WindowDelegate alloc];
[controller addScriptMessageHandler:delegate name:@"webview"];
// Set delegate to window
[window setDelegate:delegate];
// Initialize application
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Sets the app as the active app
[NSApp activateIgnoringOtherApps:YES];
// Add webview to window
[window setContentView:webview];
// Display window
[window makeKeyAndOrderFront:nil];
// Done initialization, set properties
init_done = true;
setTitle(title);
if (fullscreen) {
setFullscreen(true);
}
setBgColor(bgR, bgG, bgB, bgA);
navigate(url);
return 0;
}
void WebView::setTitle(std::string t) {
if (!init_done) {
title = t;
} else {
[window setTitle:[NSString stringWithUTF8String:t.c_str()]];
}
}
void WebView::setFullscreen(bool fs) {
if (!init_done) {
fullscreen = fs;
} else {
// TODO: replace toggle with set
[window toggleFullScreen:nil];
}
}
void WebView::setFullscreenFromJS(bool allow) { fullscreenFromJS = allow; }
void WebView::setBgColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
if (!init_done) {
bgR = r;
bgG = g;
bgB = b;
bgA = a;
} else {
[window setBackgroundColor:[NSColor colorWithCalibratedRed:r / 255.0
green:g / 255.0
blue:b / 255.0
alpha:a / 255.0]];
}
}
bool WebView::run() {
NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
untilDate:[NSDate distantFuture]
inMode:NSDefaultRunLoopMode
dequeue:true];
if (event) {
[NSApp sendEvent:event];
}
return should_exit;
}
void WebView::navigate(std::string u) {
if (!init_done) {
url = u;
} else if (u.rfind("data:", 0) == 0) {
[webview loadHTMLString:[NSString stringWithUTF8String:u.c_str()]
baseURL:nil];
} else {
[webview
loadRequest:[NSURLRequest
requestWithURL:
[NSURL URLWithString:[NSString
stringWithUTF8String:
u.c_str()]]]];
}
}
void WebView::eval(const std::string& js) {
[webview evaluateJavaScript:[NSString stringWithUTF8String:js.c_str()]
completionHandler:nil];
}
void WebView::exit() {
// Distinguish window closing with app exiting
should_exit = true;
[NSApp terminate:nil];
}
#elif defined(WEBVIEW_GTK) // WEBVIEW_MAC
int WebView::init() {
if (gtk_init_check(0, NULL) == FALSE) {
return -1;
}
// Initialize GTK window
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
if (resizable) {
gtk_window_set_default_size(GTK_WINDOW(window), width, height);
} else {
gtk_widget_set_size_request(window, width, height);
}
gtk_window_set_resizable(GTK_WINDOW(window), resizable);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
// Add scrolling container
GtkWidget* scroller = gtk_scrolled_window_new(nullptr, nullptr);
gtk_container_add(GTK_CONTAINER(window), scroller);
// Content manager
WebKitUserContentManager* cm = webkit_user_content_manager_new();
webkit_user_content_manager_register_script_message_handler(cm, "external");
g_signal_connect(cm, "script-message-received::external",
G_CALLBACK(external_message_received_cb), this);
// WebView
webview = webkit_web_view_new_with_user_content_manager(cm);
g_signal_connect(G_OBJECT(webview), "load-changed",
G_CALLBACK(webview_load_changed_cb), this);
gtk_container_add(GTK_CONTAINER(scroller), webview);
g_signal_connect(window, "destroy", G_CALLBACK(destroyWindowCb), this);
// g_signal_connect(webview, "close", G_CALLBACK(closeWebViewCb), window);
// Dev Tools if debug
if (debug) {
WebKitSettings* settings =
webkit_web_view_get_settings(WEBKIT_WEB_VIEW(webview));
webkit_settings_set_enable_write_console_messages_to_stdout(settings,
true);
webkit_settings_set_enable_developer_extras(settings, true);
} else {
g_signal_connect(G_OBJECT(webview), "context-menu",
G_CALLBACK(webview_context_menu_cb), nullptr);
}
webkit_user_content_manager_add_script(
cm, webkit_user_script_new(
inject.c_str(), WEBKIT_USER_CONTENT_INJECT_TOP_FRAME,
WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, NULL, NULL));
// Monitor for fullscreen changes