forked from Tracktion/choc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
choc_WebView.h
4838 lines (4568 loc) · 866 KB
/
choc_WebView.h
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
//
// ██████ ██ ██ ██████ ██████
// ██ ██ ██ ██ ██ ██ ** Classy Header-Only Classes **
// ██ ███████ ██ ██ ██
// ██ ██ ██ ██ ██ ██ https://github.com/Tracktion/choc
// ██████ ██ ██ ██████ ██████
//
// CHOC is (C)2022 Tracktion Corporation, and is offered under the terms of the ISC license:
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or
// without fee is hereby granted, provided that the above copyright notice and this permission
// notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifndef CHOC_WEBVIEW_HEADER_INCLUDED
#define CHOC_WEBVIEW_HEADER_INCLUDED
#include <optional>
#include <unordered_map>
#include <vector>
#include <functional>
#include "../platform/choc_Platform.h"
#include "../text/choc_JSON.h"
//==============================================================================
namespace choc::ui
{
/**
Creates an embedded browser which can be placed inside some kind of parent window.
After creating a WebView object, its getViewHandle() returns a platform-specific
handle that can be added to whatever kind of window is appropriate. The
choc::ui::DesktopWindow class is an example of a window that can have the
webview added to it via its choc::ui::DesktopWindow::setContent() method.
There are unfortunately a few extra build steps needed for using WebView
in your projects:
- On OSX, you'll need to add the `WebKit` framework to your project
- On Linux, you'll need to:
1. Install the libgtk-3-dev and libwebkit2gtk-4.0-dev packages.
2. Link the gtk+3.0 and webkit2gtk-4.0 libraries in your build.
You might want to have a look inside choc/tests/CMakeLists.txt for
an example of how to add those packages to your build without too
much fuss.
- On Windows, no extra build steps needed!! This is a bigger deal than it
sounds, because normally to use an embedded Edge browser on Windows is a
total PITA, involving downloading a special Microsoft SDK with redistributable
DLLs, etc, but I've jumped through many ugly hoops to make this class
fully self-contained.
Because this is a GUI, it needs a message loop to be running. If you're using
it inside an app which already runs a message loop, it should just work,
or you can use choc::messageloop::run() and choc::messageloop::stop() for an easy
but basic loop.
For an example of how to use this class, see `choc/tests/main.cpp` where
there's a simple demo.
*/
class WebView
{
public:
/// Contains optional settings to pass to a WebView constructor.
struct Options
{
/// If supported, this enables developer features in the browser
bool enableDebugMode = false;
/// On OSX, setting this to true will allow the first click on a non-focused
/// webview to be used as input, rather than the default behaviour, which is
/// for the first click to give the webview focus but not trigger any action.
bool acceptsFirstMouseClick = false;
/// Optional user-agent string which can be used to override the default. Leave
// this empty for default behaviour.
std::string customUserAgent;
/// Serve resources to the browser from a C++ callback function.
/// This can effectively be used to implement a basic web server,
/// serving resources to the browser in any way the client code chooses.
/// Given the path URL component (i.e. starting from "/"), the client should
/// return some bytes, and the associated MIME type, for that resource.
/// When provided, this function will initially be called with the root path
/// ("/") in order to serve the initial content for the page.
/// (i.e. the client should return some HTML with a "text/html" MIME type).
/// Subsequent relative requests made from the page (i.e. via `img` tags,
/// `fetch` calls from javascript etc) will result in subsequent calls here.
struct Resource
{
std::vector<uint8_t> data;
std::string mimeType;
};
using Path = std::string;
using FetchResource = std::function<std::optional<Resource>(const Path&)>;
FetchResource fetchResource;
};
/// Creates a WebView with default options
WebView();
/// Creates a WebView with some options
WebView (const Options&);
WebView (const WebView&) = delete;
WebView (WebView&&) = default;
WebView& operator= (WebView&&) = default;
~WebView();
/// Directly sets the HTML content of the browser
void setHTML (const std::string& html);
/// Directly evaluates some javascript.
/// This call isn't guaranteed to be thread-safe, so calling it on
/// threads other than the main message thread could lead to problems.
/// It also goes without saying this this is not realtime-safe, and the
/// call may block, allocate or make system calls.
void evaluateJavascript (const std::string& script);
/// Sends the browser to this URL
void navigate (const std::string& url);
/// A callback function which can be passed to bind().
using CallbackFn = std::function<choc::value::Value(const choc::value::ValueView& args)>;
/// Binds a C++ function to a named javascript function that can be called
/// by code running in the browser.
void bind (const std::string& functionName, CallbackFn&& function);
/// Removes a previously-bound function.
void unbind (const std::string& functionName);
/// Adds a script to run when the browser loads a page
void addInitScript (const std::string& script);
/// Returns a platform-specific handle for this view
void* getViewHandle() const;
private:
//==============================================================================
struct Pimpl;
std::unique_ptr<Pimpl> pimpl;
std::unordered_map<std::string, CallbackFn> bindings;
void invokeBinding (const std::string&);
};
} // namespace choc::ui
//==============================================================================
// _ _ _ _
// __| | ___ | |_ __ _ (_)| | ___
// / _` | / _ \| __| / _` || || |/ __|
// | (_| || __/| |_ | (_| || || |\__ \ _ _ _
// \__,_| \___| \__| \__,_||_||_||___/(_)(_)(_)
//
// Code beyond this point is implementation detail...
//
//==============================================================================
#if CHOC_LINUX
#include "../platform/choc_DisableAllWarnings.h"
#include <JavaScriptCore/JavaScript.h>
#include <webkit2/webkit2.h>
#include "../platform/choc_ReenableAllWarnings.h"
struct choc::ui::WebView::Pimpl
{
Pimpl (WebView& v, const Options& options)
: owner (v), fetchResource (options.fetchResource)
{
if (! gtk_init_check (nullptr, nullptr))
return;
webviewContext = webkit_web_context_new();
g_object_ref_sink (G_OBJECT (webviewContext));
webview = webkit_web_view_new_with_context (webviewContext);
g_object_ref_sink (G_OBJECT (webview));
manager = webkit_web_view_get_user_content_manager (WEBKIT_WEB_VIEW (webview));
signalHandlerID = g_signal_connect (manager, "script-message-received::external",
G_CALLBACK (+[] (WebKitUserContentManager*, WebKitJavascriptResult* r, gpointer arg)
{
static_cast<Pimpl*> (arg)->invokeCallback (r);
}),
this);
webkit_user_content_manager_register_script_message_handler (manager, "external");
WebKitSettings* settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW (webview));
webkit_settings_set_javascript_can_access_clipboard (settings, true);
if (options.enableDebugMode)
{
webkit_settings_set_enable_write_console_messages_to_stdout (settings, true);
webkit_settings_set_enable_developer_extras (settings, true);
if (auto inspector = WEBKIT_WEB_INSPECTOR (webkit_web_view_get_inspector (WEBKIT_WEB_VIEW (webview))))
webkit_web_inspector_show (inspector);
}
if (! options.customUserAgent.empty())
webkit_settings_set_user_agent (settings, options.customUserAgent.c_str());
if (options.fetchResource)
{
const auto onResourceRequested = [](auto* request, auto* context)
{
try
{
const auto* path = webkit_uri_scheme_request_get_path (request);
if (const auto resource = static_cast<Pimpl*> (context)->fetchResource (path))
{
const auto& [bytes, mimeType] = *resource;
auto* streamBytes = g_bytes_new (bytes.data(), static_cast<gsize> (bytes.size()));
auto* stream = g_memory_input_stream_new_from_bytes (streamBytes);
g_bytes_unref (streamBytes);
auto* response = webkit_uri_scheme_response_new (stream, static_cast<gint64> (bytes.size()));
webkit_uri_scheme_response_set_status (response, 200, nullptr);
webkit_uri_scheme_response_set_content_type (response, mimeType.c_str());
auto* headers = soup_message_headers_new (SOUP_MESSAGE_HEADERS_RESPONSE);
soup_message_headers_append (headers, "Cache-Control", "no-store");
webkit_uri_scheme_response_set_http_headers (response, headers); // response takes ownership of the headers
webkit_uri_scheme_request_finish_with_response (request, response);
g_object_unref (stream);
g_object_unref (response);
}
else
{
auto* stream = g_memory_input_stream_new();
auto* response = webkit_uri_scheme_response_new (stream, -1);
webkit_uri_scheme_response_set_status (response, 404, nullptr);
webkit_uri_scheme_request_finish_with_response (request, response);
g_object_unref (stream);
g_object_unref (response);
}
}
catch (...)
{
auto* error = g_error_new (WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_FAILED, "Something went wrong");
webkit_uri_scheme_request_finish_error (request, error);
g_error_free (error);
}
};
webkit_web_context_register_uri_scheme (webviewContext, "choc", onResourceRequested, this, nullptr);
navigate ("choc://choc.choc/");
}
gtk_widget_show_all (webview);
}
~Pimpl()
{
if (signalHandlerID != 0 && webview != nullptr)
g_signal_handler_disconnect (manager, signalHandlerID);
g_clear_object (&webview);
g_clear_object (&webviewContext);
}
static constexpr const char* postMessageFn = "window.webkit.messageHandlers.external.postMessage";
void* getViewHandle() const { return (void*) webview; }
void evaluateJavascript (const std::string& js)
{
#if WEBKIT_CHECK_VERSION (2, 40, 0)
webkit_web_view_evaluate_javascript (WEBKIT_WEB_VIEW (webview), js.c_str(), static_cast<gssize> (js.length()), nullptr, nullptr, nullptr, nullptr, nullptr);
#else
webkit_web_view_run_javascript (WEBKIT_WEB_VIEW (webview), js.c_str(), nullptr, nullptr, nullptr);
#endif
}
void navigate (const std::string& url)
{
webkit_web_view_load_uri (WEBKIT_WEB_VIEW (webview), url.c_str());
}
void setHTML (const std::string& html)
{
webkit_web_view_load_html (WEBKIT_WEB_VIEW (webview), html.c_str(), nullptr);
}
void addInitScript (const std::string& js)
{
if (manager != nullptr)
webkit_user_content_manager_add_script (manager, webkit_user_script_new (js.c_str(),
WEBKIT_USER_CONTENT_INJECT_TOP_FRAME,
WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START,
nullptr, nullptr));
}
void invokeCallback (WebKitJavascriptResult* r)
{
auto s = jsc_value_to_string (webkit_javascript_result_get_js_value (r));
owner.invokeBinding (s);
g_free (s);
}
WebView& owner;
Options::FetchResource fetchResource;
WebKitWebContext* webviewContext = {};
GtkWidget* webview = {};
WebKitUserContentManager* manager = {};
unsigned long signalHandlerID = 0;
};
//==============================================================================
#elif CHOC_APPLE
#include "choc_MessageLoop.h"
struct choc::ui::WebView::Pimpl
{
Pimpl (WebView& v, const Options& optionsToUse)
: owner (v), options (optionsToUse)
{
using namespace choc::objc;
AutoReleasePool autoreleasePool;
auto config = call<id> (getClass ("WKWebViewConfiguration"), "new");
auto prefs = call<id> (config, "preferences");
call<id> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("fullScreenEnabled"));
call<id> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("DOMPasteAllowed"));
call<id> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("javaScriptCanAccessClipboard"));
if (options.enableDebugMode)
call<id> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("developerExtrasEnabled"));
delegate = createDelegate();
objc_setAssociatedObject (delegate, "choc_webview", (id) this, OBJC_ASSOCIATION_ASSIGN);
manager = call<id> (config, "userContentController");
call<void> (manager, "retain");
call<void> (manager, "addScriptMessageHandler:name:", delegate, getNSString ("external"));
if (options.fetchResource)
call<void> (config, "setURLSchemeHandler:forURLScheme:", delegate, getNSString ("choc"));
webview = call<id> (allocateWebview(), "initWithFrame:configuration:", CGRect(), config);
objc_setAssociatedObject (webview, "choc_webview", (id) this, OBJC_ASSOCIATION_ASSIGN);
if (! options.customUserAgent.empty())
call<void> (webview, "setValue:forKey:", getNSString (options.customUserAgent), getNSString ("customUserAgent"));
call<void> (config, "release");
if (options.fetchResource)
navigate ("choc://choc.choc/");
}
~Pimpl()
{
objc::AutoReleasePool autoreleasePool;
objc_setAssociatedObject (delegate, "choc_webview", nil, OBJC_ASSOCIATION_ASSIGN);
objc_setAssociatedObject (webview, "choc_webview", nil, OBJC_ASSOCIATION_ASSIGN);
objc::call<void> (webview, "release");
objc::call<void> (manager, "removeScriptMessageHandlerForName:", objc::getNSString ("external"));
objc::call<void> (manager, "release");
objc::call<void> (delegate, "release");
}
static constexpr const char* postMessageFn = "window.webkit.messageHandlers.external.postMessage";
void* getViewHandle() const { return (void*) webview; }
void addInitScript (const std::string& script)
{
using namespace choc::objc;
AutoReleasePool autoreleasePool;
auto s = call<id> (call<id> (getClass ("WKUserScript"), "alloc"), "initWithSource:injectionTime:forMainFrameOnly:",
getNSString (script), WKUserScriptInjectionTimeAtDocumentStart, (BOOL) 1);
call<void> (manager, "addUserScript:", s);
call<void> (s, "release");
}
void navigate (const std::string& url)
{
using namespace choc::objc;
AutoReleasePool autoreleasePool;
auto nsURL = call<id> (getClass ("NSURL"), "URLWithString:", getNSString (url));
call<void> (webview, "loadRequest:", call<id> (getClass ("NSURLRequest"), "requestWithURL:", nsURL));
}
void setHTML (const std::string& html)
{
objc::AutoReleasePool autoreleasePool;
objc::call<void> (webview, "loadHTMLString:baseURL:", objc::getNSString (html), (id) nullptr);
}
void evaluateJavascript (const std::string& script)
{
objc::AutoReleasePool autoreleasePool;
objc::call<void> (webview, "evaluateJavaScript:completionHandler:", objc::getNSString (script), (id) nullptr);
}
private:
id createDelegate()
{
static DelegateClass dc;
return objc::call<id> ((id) dc.delegateClass, "new");
}
id allocateWebview()
{
static WebviewClass c;
return objc::call<id> ((id) c.webviewClass, "alloc");
}
void onResourceRequested (id task)
{
using namespace choc::objc;
AutoReleasePool autoreleasePool;
try
{
auto requestUrl = call<id> (call<id> (task, "request"), "URL");
auto makeResponse = [&] (auto responseCode, id headerFields)
{
return call<id> (call<id> (call<id> (getClass ("NSHTTPURLResponse"), "alloc"),
"initWithURL:statusCode:HTTPVersion:headerFields:",
requestUrl,
responseCode,
getNSString ("HTTP/1.1"),
headerFields),
"autorelease");
};
auto path = objc::getString (call<id> (requestUrl, "path"));
if (auto resource = options.fetchResource (path))
{
const auto& [bytes, mimeType] = *resource;
auto contentLength = std::to_string (bytes.size());
id headerKeys[] = { getNSString ("Content-Length"), getNSString ("Content-Type"), getNSString ("Cache-Control") };
id headerObjects[] = { getNSString (contentLength), getNSString (mimeType), getNSString ("no-store") };
auto headerFields = call<id> (getClass ("NSDictionary"), "dictionaryWithObjects:forKeys:count:",
headerObjects, headerKeys, sizeof (headerObjects) / sizeof (id));
call<void> (task, "didReceiveResponse:", makeResponse (200, headerFields));
auto data = call<id> (getClass ("NSData"), "dataWithBytes:length:", bytes.data(), bytes.size());
call<void> (task, "didReceiveData:", data);
}
else
{
call<void> (task, "didReceiveResponse:", makeResponse (404, nullptr));
}
call<void> (task, "didFinish");
}
catch (...)
{
auto error = call<id> (getClass ("NSError"), "errorWithDomain:code:userInfo:",
getNSString ("NSURLErrorDomain"), -1, nullptr);
call<void> (task, "didFailWithError:", error);
}
}
BOOL sendAppAction (id self, const char* action)
{
objc::call<void> (objc::getSharedNSApplication(), "sendAction:to:from:",
sel_registerName (action), (id) nullptr, self);
return true;
}
BOOL performKeyEquivalent (id self, id e)
{
enum
{
NSEventTypeKeyDown = 10,
NSEventModifierFlagShift = 1 << 17,
NSEventModifierFlagControl = 1 << 18,
NSEventModifierFlagOption = 1 << 19,
NSEventModifierFlagCommand = 1 << 20
};
if (objc::call<int> (e, "type") == NSEventTypeKeyDown)
{
auto flags = objc::call<int> (e, "modifierFlags") & (NSEventModifierFlagShift | NSEventModifierFlagCommand
| NSEventModifierFlagControl | NSEventModifierFlagOption);
auto path = objc::getString (objc::call<id> (e, "charactersIgnoringModifiers"));
if (flags == NSEventModifierFlagCommand)
{
if (path == "c") return sendAppAction (self, "copy:");
if (path == "x") return sendAppAction (self, "cut:");
if (path == "v") return sendAppAction (self, "paste:");
if (path == "z") return sendAppAction (self, "undo:");
if (path == "a") return sendAppAction (self, "selectAll:");
}
else if (flags == (NSEventModifierFlagShift | NSEventModifierFlagCommand))
{
if (path == "Z") return sendAppAction (self, "redo:");
}
}
return false;
}
WebView& owner;
Options options;
id webview = {}, manager = {}, delegate = {};
struct WebviewClass
{
WebviewClass()
{
webviewClass = choc::objc::createDelegateClass ("WKWebView", "CHOCWebView_");
class_addMethod (webviewClass, sel_registerName ("acceptsFirstMouse:"),
(IMP) (+[](id self, SEL, id) -> BOOL
{
if (auto p = reinterpret_cast<Pimpl*> (objc_getAssociatedObject (self, "choc_webview")))
return p->options.acceptsFirstMouseClick;
return false;
}), "B@:@");
class_addMethod (webviewClass, sel_registerName ("performKeyEquivalent:"),
(IMP) (+[](id self, SEL, id e) -> BOOL
{
if (auto p = reinterpret_cast<Pimpl*> (objc_getAssociatedObject (self, "choc_webview")))
return p->performKeyEquivalent (self, e);
return false;
}), "B@:@");
objc_registerClassPair (webviewClass);
}
~WebviewClass()
{
// NB: it doesn't seem possible to dispose of this class late enough to avoid a warning on shutdown
// about the KVO system still using it, so unfortunately the only option seems to be to let it leak..
// objc_disposeClassPair (webviewClass);
}
Class webviewClass = {};
};
struct DelegateClass
{
DelegateClass()
{
delegateClass = choc::objc::createDelegateClass ("NSObject", "CHOCWebViewDelegate_");
class_addMethod (delegateClass, sel_registerName ("userContentController:didReceiveScriptMessage:"),
(IMP) (+[](id self, SEL, id, id msg)
{
if (auto p = reinterpret_cast<Pimpl*> (objc_getAssociatedObject (self, "choc_webview")))
{
p->owner.invokeBinding (objc::getString (objc::call<id> (msg, "body")));
}
}),
"v@:@@");
class_addMethod (delegateClass, sel_registerName ("webView:startURLSchemeTask:"),
(IMP) (+[](id self, SEL, id, id task)
{
if (auto p = reinterpret_cast<Pimpl*> (objc_getAssociatedObject (self, "choc_webview")))
p->onResourceRequested (task);
}),
"v@:@@");
class_addMethod (delegateClass, sel_registerName ("webView:stopURLSchemeTask:"), (IMP) (+[](id, SEL, id, id) {}), "v@:@@");
objc_registerClassPair (delegateClass);
}
~DelegateClass()
{
objc_disposeClassPair (delegateClass);
}
Class delegateClass = {};
};
static constexpr long WKUserScriptInjectionTimeAtDocumentStart = 0;
// Including CodeGraphics.h can create all kinds of messy C/C++ symbol clashes
// with other headers, but all we actually need are these coordinate structs:
#if defined (__LP64__) && __LP64__
using CGFloat = double;
#else
using CGFloat = float;
#endif
struct CGPoint { CGFloat x = 0, y = 0; };
struct CGSize { CGFloat width = 0, height = 0; };
struct CGRect { CGPoint origin; CGSize size; };
};
//==============================================================================
#elif CHOC_WINDOWS
#include "../platform/choc_DynamicLibrary.h"
// If you want to supply your own mechanism for finding the Microsoft
// Webview2Loader.dll file, then define the CHOC_FIND_WEBVIEW2LOADER_DLL
// macro, which must evaluate to a choc::file::DynamicLibrary object
// which points to the DLL.
#ifndef CHOC_FIND_WEBVIEW2LOADER_DLL
#define CHOC_USE_INTERNAL_WEBVIEW_DLL 1
#define CHOC_FIND_WEBVIEW2LOADER_DLL choc::ui::getWebview2LoaderDLL()
#include "../platform/choc_MemoryDLL.h"
namespace choc::ui
{
using WebViewDLL = choc::memory::MemoryDLL;
static WebViewDLL getWebview2LoaderDLL();
}
#else
namespace choc::ui
{
using WebViewDLL = choc::file::DynamicLibrary;
}
#endif
#include "choc_DesktopWindow.h"
#ifndef __webview2_h__
#define __webview2_h__
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include <atomic>
#include <shlobj.h>
#include <rpc.h>
#include <rpcndr.h>
#include <objidl.h>
#include <oaidl.h>
#ifndef __RPCNDR_H_VERSION__
#error "This code requires an updated version of <rpcndr.h>"
#endif
extern "C"
{
struct EventRegistrationToken { __int64 value; };
typedef interface ICoreWebView2 ICoreWebView2;
typedef interface ICoreWebView2Controller ICoreWebView2Controller;
typedef interface ICoreWebView2Environment ICoreWebView2Environment;
typedef interface ICoreWebView2HttpHeadersCollectionIterator ICoreWebView2HttpHeadersCollectionIterator;
typedef interface ICoreWebView2HttpRequestHeaders ICoreWebView2HttpRequestHeaders;
typedef interface ICoreWebView2HttpResponseHeaders ICoreWebView2HttpResponseHeaders;
typedef interface ICoreWebView2WebResourceRequest ICoreWebView2WebResourceRequest;
typedef interface ICoreWebView2WebResourceRequestedEventArgs ICoreWebView2WebResourceRequestedEventArgs;
typedef interface ICoreWebView2WebResourceRequestedEventHandler ICoreWebView2WebResourceRequestedEventHandler;
typedef interface ICoreWebView2WebResourceResponse ICoreWebView2WebResourceResponse;
MIDL_INTERFACE("8B4F98CE-DB0D-4E71-85FD-C4C4EF1F2630")
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(HRESULT, ICoreWebView2Environment*) = 0;
};
MIDL_INTERFACE("86EF6808-3C3F-4C6F-975E-8CE0B98F70BA")
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(HRESULT, ICoreWebView2Controller*) = 0;
};
MIDL_INTERFACE("DA66D884-6DA8-410E-9630-8C48F8B3A40E")
ICoreWebView2Environment : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE CreateCoreWebView2Controller(HWND, ICoreWebView2CreateCoreWebView2ControllerCompletedHandler*) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateWebResourceResponse(IStream*, int, LPCWSTR, LPCWSTR, ICoreWebView2WebResourceResponse**) = 0;
virtual HRESULT STDMETHODCALLTYPE get_BrowserVersionString(LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE add_NewBrowserVersionAvailable(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_NewBrowserVersionAvailable(EventRegistrationToken) = 0;
};
MIDL_INTERFACE("B263B5AE-9C54-4B75-B632-40AE1A0B6912")
ICoreWebView2WebMessageReceivedEventArgs : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Source(LPWSTR *) = 0;
virtual HRESULT STDMETHODCALLTYPE get_WebMessageAsJson(LPWSTR *) = 0;
virtual HRESULT STDMETHODCALLTYPE TryGetWebMessageAsString(LPWSTR *) = 0;
};
MIDL_INTERFACE("199328C8-9964-4F5F-84E6-E875B1B763D6")
ICoreWebView2WebMessageReceivedEventHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(ICoreWebView2 *, ICoreWebView2WebMessageReceivedEventArgs *) = 0;
};
enum COREWEBVIEW2_PERMISSION_KIND
{
COREWEBVIEW2_PERMISSION_KIND_UNKNOWN_PERMISSION = 0,
COREWEBVIEW2_PERMISSION_KIND_MICROPHONE = (COREWEBVIEW2_PERMISSION_KIND_UNKNOWN_PERMISSION + 1),
COREWEBVIEW2_PERMISSION_KIND_CAMERA = (COREWEBVIEW2_PERMISSION_KIND_MICROPHONE + 1),
COREWEBVIEW2_PERMISSION_KIND_GEOLOCATION = (COREWEBVIEW2_PERMISSION_KIND_CAMERA + 1),
COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS = (COREWEBVIEW2_PERMISSION_KIND_GEOLOCATION + 1),
COREWEBVIEW2_PERMISSION_KIND_OTHER_SENSORS = (COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS + 1),
COREWEBVIEW2_PERMISSION_KIND_CLIPBOARD_READ = (COREWEBVIEW2_PERMISSION_KIND_OTHER_SENSORS + 1)
};
enum COREWEBVIEW2_PERMISSION_STATE
{
COREWEBVIEW2_PERMISSION_STATE_DEFAULT = 0,
COREWEBVIEW2_PERMISSION_STATE_ALLOW = (COREWEBVIEW2_PERMISSION_STATE_DEFAULT + 1),
COREWEBVIEW2_PERMISSION_STATE_DENY = (COREWEBVIEW2_PERMISSION_STATE_ALLOW + 1)
};
enum COREWEBVIEW2_MOVE_FOCUS_REASON
{
COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC = 0,
COREWEBVIEW2_MOVE_FOCUS_REASON_NEXT = (COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC + 1),
COREWEBVIEW2_MOVE_FOCUS_REASON_PREVIOUS = (COREWEBVIEW2_MOVE_FOCUS_REASON_NEXT + 1)
};
enum COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT {};
enum COREWEBVIEW2_WEB_RESOURCE_CONTEXT
{
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL = 0
};
MIDL_INTERFACE("A7ED8BF0-3EC9-4E39-8427-3D6F157BD285")
ICoreWebView2Deferral : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Complete() = 0;
};
MIDL_INTERFACE("97055cd4-512c-4264-8b5f-e3f446cea6a5")
ICoreWebView2WebResourceRequest : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Uri(LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Uri(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Method(LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Method(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Content(IStream**) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Content(IStream*) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Headers(ICoreWebView2HttpRequestHeaders**) = 0;
};
MIDL_INTERFACE("774B5EA1-3FAD-435C-B1FC-A77D1ACD5EAF")
ICoreWebView2PermissionRequestedEventArgs : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Uri(LPWSTR *) = 0;
virtual HRESULT STDMETHODCALLTYPE get_PermissionKind(COREWEBVIEW2_PERMISSION_KIND *) = 0;
virtual HRESULT STDMETHODCALLTYPE get_IsUserInitiated(BOOL *) = 0;
virtual HRESULT STDMETHODCALLTYPE get_State(COREWEBVIEW2_PERMISSION_STATE *) = 0;
virtual HRESULT STDMETHODCALLTYPE put_State(COREWEBVIEW2_PERMISSION_STATE) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDeferral(ICoreWebView2Deferral **) = 0;
};
MIDL_INTERFACE("543B4ADE-9B0B-4748-9AB7-D76481B223AA")
ICoreWebView2PermissionRequestedEventHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(ICoreWebView2 *, ICoreWebView2PermissionRequestedEventArgs *) = 0;
};
MIDL_INTERFACE("189B8AAF-0426-4748-B9AD-243F537EB46B")
ICoreWebView2 : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Settings(void**) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Source(LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE Navigate(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE NavigateToString(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE add_NavigationStarting(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_NavigationStarting(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_ContentLoading(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_ContentLoading(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_SourceChanged(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_SourceChanged(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_HistoryChanged(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_HistoryChanged(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_NavigationCompleted(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_NavigationCompleted(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_FrameNavigationStarting(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_FrameNavigationStarting(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_FrameNavigationCompleted(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_FrameNavigationCompleted(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_ScriptDialogOpening(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_ScriptDialogOpening(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_PermissionRequested(ICoreWebView2PermissionRequestedEventHandler*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_PermissionRequested(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_ProcessFailed(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_ProcessFailed(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE AddScriptToExecuteOnDocumentCreated(LPCWSTR, void*) = 0;
virtual HRESULT STDMETHODCALLTYPE RemoveScriptToExecuteOnDocumentCreated(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE ExecuteScript(LPCWSTR, void*) = 0;
virtual HRESULT STDMETHODCALLTYPE CapturePreview(COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT, void*, void*) = 0;
virtual HRESULT STDMETHODCALLTYPE Reload() = 0;
virtual HRESULT STDMETHODCALLTYPE PostWebMessageAsJson(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE PostWebMessageAsString(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE add_WebMessageReceived(ICoreWebView2WebMessageReceivedEventHandler*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_WebMessageReceived(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE CallDevToolsProtocolMethod(LPCWSTR, LPCWSTR, void*) = 0;
virtual HRESULT STDMETHODCALLTYPE get_BrowserProcessId(UINT32*) = 0;
virtual HRESULT STDMETHODCALLTYPE get_CanGoBack(BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE get_CanGoForward(BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE GoBack() = 0;
virtual HRESULT STDMETHODCALLTYPE GoForward() = 0;
virtual HRESULT STDMETHODCALLTYPE GetDevToolsProtocolEventReceiver(LPCWSTR, void**) = 0;
virtual HRESULT STDMETHODCALLTYPE Stop() = 0;
virtual HRESULT STDMETHODCALLTYPE add_NewWindowRequested(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_NewWindowRequested(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_DocumentTitleChanged(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_DocumentTitleChanged(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE get_DocumentTitle(LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE AddHostObjectToScript(LPCWSTR, VARIANT*) = 0;
virtual HRESULT STDMETHODCALLTYPE RemoveHostObjectFromScript(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenDevToolsWindow() = 0;
virtual HRESULT STDMETHODCALLTYPE add_ContainsFullScreenElementChanged(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_ContainsFullScreenElementChanged(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE get_ContainsFullScreenElement(BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE add_WebResourceRequested(ICoreWebView2WebResourceRequestedEventHandler*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_WebResourceRequested(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE AddWebResourceRequestedFilter(const LPCWSTR, const COREWEBVIEW2_WEB_RESOURCE_CONTEXT) = 0;
virtual HRESULT STDMETHODCALLTYPE RemoveWebResourceRequestedFilter(const LPCWSTR, const COREWEBVIEW2_WEB_RESOURCE_CONTEXT) = 0;
virtual HRESULT STDMETHODCALLTYPE add_WindowCloseRequested(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_WindowCloseRequested(EventRegistrationToken) = 0;
};
MIDL_INTERFACE("7CCC5C7F-8351-4572-9077-9C1C80913835")
ICoreWebView2Controller : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_IsVisible(BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_IsVisible(BOOL) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Bounds(RECT*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Bounds(RECT) = 0;
virtual HRESULT STDMETHODCALLTYPE get_ZoomFactor(double*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_ZoomFactor(double) = 0;
virtual HRESULT STDMETHODCALLTYPE add_ZoomFactorChanged(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_ZoomFactorChanged(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE SetBoundsAndZoomFactor(RECT, double) = 0;
virtual HRESULT STDMETHODCALLTYPE MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON) = 0;
virtual HRESULT STDMETHODCALLTYPE add_MoveFocusRequested(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_MoveFocusRequested(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_GotFocus(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_GotFocus(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_LostFocus(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_LostFocus(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE add_AcceleratorKeyPressed(void*, EventRegistrationToken*) = 0;
virtual HRESULT STDMETHODCALLTYPE remove_AcceleratorKeyPressed(EventRegistrationToken) = 0;
virtual HRESULT STDMETHODCALLTYPE get_ParentWindow(HWND*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_ParentWindow(HWND) = 0;
virtual HRESULT STDMETHODCALLTYPE NotifyParentWindowPositionChanged() = 0;
virtual HRESULT STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE get_CoreWebView2(ICoreWebView2**) = 0;
};
STDAPI CreateCoreWebView2EnvironmentWithOptions(PCWSTR, PCWSTR, void*, ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
MIDL_INTERFACE("4212F3A7-0FBC-4C9C-8118-17ED6370C1B3")
ICoreWebView2HttpHeadersCollectionIterator : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetCurrentHeader(LPWSTR*, LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE get_HasCurrentHeader(BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE MoveNext(BOOL*) = 0;
};
MIDL_INTERFACE("2C1F04DF-C90E-49E4-BD25-4A659300337B")
ICoreWebView2HttpRequestHeaders : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetHeader(LPCWSTR, LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHeaders(LPCWSTR, ICoreWebView2HttpHeadersCollectionIterator**) = 0;
virtual HRESULT STDMETHODCALLTYPE Contains(LPCWSTR, BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE SetHeader(LPCWSTR, LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE RemoveHeader(LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE GetIterator(ICoreWebView2HttpHeadersCollectionIterator**) = 0;
};
MIDL_INTERFACE("B5F6D4D5-1BFF-4869-85B8-158153017B04")
ICoreWebView2HttpResponseHeaders : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE AppendHeader(LPCWSTR, LPCWSTR) = 0;
virtual HRESULT STDMETHODCALLTYPE Contains(LPCWSTR, BOOL*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHeader(LPCWSTR, LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHeaders(LPCWSTR, ICoreWebView2HttpHeadersCollectionIterator**) = 0;
virtual HRESULT STDMETHODCALLTYPE GetIterator(ICoreWebView2HttpHeadersCollectionIterator**) = 0;
};
MIDL_INTERFACE("2D7B3282-83B1-41CA-8BBF-FF18F6BFE320")
ICoreWebView2WebResourceRequestedEventArgs : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Request(ICoreWebView2WebResourceRequest**) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Response(ICoreWebView2WebResourceResponse**) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Response(ICoreWebView2WebResourceResponse*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDeferral(ICoreWebView2Deferral**) = 0;
virtual HRESULT STDMETHODCALLTYPE get_ResourceContext(COREWEBVIEW2_WEB_RESOURCE_CONTEXT*) = 0;
};
MIDL_INTERFACE("F6DC79F2-E1FA-4534-8968-4AFF10BBAA32")
ICoreWebView2WebResourceRequestedEventHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(ICoreWebView2*, ICoreWebView2WebResourceRequestedEventArgs*) = 0;
};
MIDL_INTERFACE("5953D1FC-B08F-46DD-AFD3-66B172419CD0")
ICoreWebView2WebResourceResponse : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Content(IStream**) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Content(IStream*) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Headers(ICoreWebView2HttpResponseHeaders**) = 0;
virtual HRESULT STDMETHODCALLTYPE get_StatusCode(int*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_StatusCode(int) = 0;
virtual HRESULT STDMETHODCALLTYPE get_ReasonPhrase(LPWSTR*) = 0;
virtual HRESULT STDMETHODCALLTYPE put_ReasonPhrase(LPCWSTR) = 0;
};
}
#endif // __webview2_h__
namespace choc::ui
{
//==============================================================================
struct WebView::Pimpl
{
Pimpl (WebView& v, const Options& options)
: owner (v), fetchResource (options.fetchResource), customUserAgent (options.customUserAgent)
{
// You cam define this macro to provide a custom way of getting a
// choc::file::DynamicLibrary that contains the redistributable
// Microsoft WebView2Loader.dll
webviewDLL = CHOC_FIND_WEBVIEW2LOADER_DLL;
if (! webviewDLL)
return;
hwnd = windowClass.createWindow (WS_POPUP, 400, 400, this);
if (hwnd.hwnd == nullptr)
return;
SetWindowLongPtr (hwnd, GWLP_USERDATA, (LONG_PTR) this);
if (createEmbeddedWebView())
{
resizeContentToFit();
// coreWebViewController->MoveFocus (COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
}
~Pimpl()
{
if (coreWebView != nullptr)
{
coreWebView->Release();
coreWebView = nullptr;
}
if (coreWebViewController != nullptr)
{
coreWebViewController->Release();
coreWebViewController = nullptr;
}
if (coreWebViewEnvironment != nullptr)
{
coreWebViewEnvironment->Release();
coreWebViewEnvironment = nullptr;
}