-
Notifications
You must be signed in to change notification settings - Fork 49
/
choc_WebView.h
5902 lines (5518 loc) · 998 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;
/// If supported, this pops up a separate debug inspector window
bool enableDebugInspector = 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;
/// If you provide a fetchResource function, it is expected to return this
/// object, which is simply the raw content of the resource, and its MIME type.
struct Resource
{
Resource() = default;
Resource (std::string_view content, std::string mimeType);
std::vector<uint8_t> data;
std::string mimeType;
};
using FetchResource = std::function<std::optional<Resource>(const std::string& path)>;
/// 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 (or if the
/// customSchemeURI property is also set, it will navigate to that URI).
/// When this happens, the client should return some HTML with a "text/html"
/// MIME type.
/// Subsequent relative requests made from the page (e.g. via `img` tags,
/// `fetch` calls from javascript etc) will all invoke calls to this callback
/// with the requested path as their argument.
FetchResource fetchResource;
/// If fetchResource is being used to serve custom data, you can choose to
/// override the default URI scheme by providing a home URI here, e.g. if
/// you wanted a scheme called `foo:`, you might set this to `foo://myname.com`
/// and the view will navigate to that address when launched.
/// Leave blank for a default.
std::string customSchemeURI;
/// Where supported, this property gives the webview a transparent background
/// by default, so you can avoid a flash of white while it's loading the
/// content.
bool transparentBackground = false;
/// On OSX there's some custom code to intercept copy/paste keys, which
/// otherwise wouldn't work by default. This lets you turn that off if you
/// need to.
bool enableDefaultClipboardKeyShortcutsInSafari = true;
};
/// 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();
/// Returns true if the webview has been successfully initialised. This could
/// fail on some systems if the OS doesn't provide a suitable component.
bool loadedOK() const;
/// Directly sets the HTML content of the browser
bool setHTML (const std::string& html);
/// This function type is used by evaluateJavascript().
using CompletionHandler = std::function<void(const std::string& error,
const choc::value::ValueView& result)>;
/// Asynchronously evaluates some javascript.
/// If you want to find out the result of the expression (or whether there
/// was a compile error etc), then provide a callback function which will be
/// invoked when the script is complete.
/// This will return true if the webview is in a state that lets it run code, or
/// false if something prevents that.
bool evaluateJavascript (const std::string& script, CompletionHandler completionHandler = {});
/// Sends the browser to this URL
bool 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.
bool bind (const std::string& functionName, CallbackFn&& function);
/// Removes a previously-bound function.
bool unbind (const std::string& functionName);
/// Adds a script to run when the browser loads a page
bool 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&);
static std::string getURIScheme (const Options&);
static std::string getURIHome (const Options&);
struct DeletionChecker { bool deleted = false; };
};
#ifdef JUCE_GUI_EXTRA_H_INCLUDED
// This function will create a JUCE Component that contains and manages the given WebView.
// (Obviously it's only available if you've already included the juce_gui_extra module
// headers before this file).
inline std::unique_ptr<juce::Component> createJUCEWebViewHolder (choc::ui::WebView&);
#endif
} // 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;
defaultURI = getURIHome (options);
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 (options.enableDebugInspector)
{
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");
soup_message_headers_append (headers, "Access-Control-Allow-Origin", "*");
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, getURIScheme (options).c_str(), onResourceRequested, this, nullptr);
navigate ({});
}
gtk_widget_show_all (webview);
}
~Pimpl()
{
deletionChecker->deleted = true;
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";
bool loadedOK() const { return getViewHandle() != nullptr; }
void* getViewHandle() const { return (void*) webview; }
std::shared_ptr<DeletionChecker> deletionChecker { std::make_shared<DeletionChecker>() };
bool evaluateJavascript (const std::string& js, CompletionHandler&& completionHandler)
{
GAsyncReadyCallback callback = {};
gpointer userData = {};
if (completionHandler)
{
callback = evaluationCompleteCallback;
userData = new CompletionHandler (std::move (completionHandler));
}
#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, callback, userData);
#else
webkit_web_view_run_javascript (WEBKIT_WEB_VIEW (webview), js.c_str(), nullptr, callback, userData);
#endif
return true;
}
static void evaluationCompleteCallback (GObject* object, GAsyncResult* result, gpointer userData)
{
std::unique_ptr<CompletionHandler> completionHandler (reinterpret_cast<CompletionHandler*> (userData));
choc::value::Value value;
std::string errorMessage;
GError* error = {};
#if WEBKIT_CHECK_VERSION (2, 40, 0)
if (auto js_result = webkit_web_view_evaluate_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error))
#else
if (auto js_result = webkit_web_view_run_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error))
#endif
{
if (error != nullptr)
{
errorMessage = error->message;
g_error_free (error);
}
#if WEBKIT_CHECK_VERSION (2, 40, 0)
if (auto js_value = js_result)
#else
if (auto js_value = webkit_javascript_result_get_js_value (js_result))
#endif
{
if (auto json = jsc_value_to_json (js_value, 0))
{
try
{
auto jsonView = std::string_view (json);
if (! jsonView.empty())
value = choc::json::parseValue (jsonView);
}
catch (const std::exception& e)
{
if (errorMessage.empty())
errorMessage = e.what();
}
g_free (json);
}
#if WEBKIT_CHECK_VERSION (2, 40, 0)
g_object_unref (js_value);
#endif
}
else
{
if (errorMessage.empty())
errorMessage = "Failed to fetch result";
}
#if ! WEBKIT_CHECK_VERSION (2, 40, 0)
webkit_javascript_result_unref (js_result);
#endif
}
else
{
errorMessage = "Failed to fetch result";
}
(*completionHandler) (errorMessage, value);
}
bool navigate (const std::string& url)
{
if (url.empty())
return navigate (defaultURI);
webkit_web_view_load_uri (WEBKIT_WEB_VIEW (webview), url.c_str());
return true;
}
bool setHTML (const std::string& html)
{
webkit_web_view_load_html (WEBKIT_WEB_VIEW (webview), html.c_str(), nullptr);
return true;
}
bool 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));
return true;
}
return false;
}
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 = {};
std::string defaultURI;
unsigned long signalHandlerID = 0;
};
//==============================================================================
#elif CHOC_APPLE
#include "../platform/choc_ObjectiveCHelpers.h"
struct choc::ui::WebView::Pimpl
{
Pimpl (WebView& v, const Options& optionsToUse)
: owner (v), options (std::make_unique<Options> (optionsToUse))
{
using namespace choc::objc;
CHOC_AUTORELEASE_BEGIN
defaultURI = getURIHome (*options);
id config = callClass<id> ("WKWebViewConfiguration", "new");
id prefs = call<id> (config, "preferences");
call<void> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("fullScreenEnabled"));
call<void> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("DOMPasteAllowed"));
call<void> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("javaScriptCanAccessClipboard"));
if (options->enableDebugMode)
call<void> (prefs, "setValue:forKey:", getNSNumberBool (true), getNSString ("developerExtrasEnabled"));
delegate = createDelegate();
objc_setAssociatedObject (delegate, "choc_webview", (CHOC_OBJC_CAST_BRIDGED 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 (getURIScheme (*options)));
webview = call<id> (allocateWebview(), "initWithFrame:configuration:", objc::CGRect(), config);
objc_setAssociatedObject (webview, "choc_webview", (CHOC_OBJC_CAST_BRIDGED id) this, OBJC_ASSOCIATION_ASSIGN);
if (! options->customUserAgent.empty())
call<void> (webview, "setValue:forKey:", getNSString (options->customUserAgent), getNSString ("customUserAgent"));
call<void> (webview, "setUIDelegate:", delegate);
call<void> (webview, "setNavigationDelegate:", delegate);
if (options->transparentBackground)
call<void> (webview, "setValue:forKey:", getNSNumberBool (false), getNSString ("drawsBackground"));
call<void> (config, "release");
if (options->fetchResource)
navigate ({});
CHOC_AUTORELEASE_END
}
~Pimpl()
{
CHOC_AUTORELEASE_BEGIN
deletionChecker->deleted = true;
objc_setAssociatedObject (delegate, "choc_webview", nil, OBJC_ASSOCIATION_ASSIGN);
objc_setAssociatedObject (webview, "choc_webview", nil, OBJC_ASSOCIATION_ASSIGN);
objc::call<void> (webview, "release");
webview = {};
objc::call<void> (manager, "removeScriptMessageHandlerForName:", objc::getNSString ("external"));
objc::call<void> (manager, "release");
manager = {};
objc::call<void> (delegate, "release");
delegate = {};
CHOC_AUTORELEASE_END
}
static constexpr const char* postMessageFn = "window.webkit.messageHandlers.external.postMessage";
bool loadedOK() const { return getViewHandle() != nullptr; }
void* getViewHandle() const { return (CHOC_OBJC_CAST_BRIDGED void*) webview; }
std::shared_ptr<DeletionChecker> deletionChecker { std::make_shared<DeletionChecker>() };
bool addInitScript (const std::string& script)
{
CHOC_AUTORELEASE_BEGIN
if (id s = objc::call<id> (objc::callClass<id> ("WKUserScript", "alloc"),
"initWithSource:injectionTime:forMainFrameOnly:",
objc::getNSString (script), WKUserScriptInjectionTimeAtDocumentStart, (BOOL) 1))
{
objc::call<void> (manager, "addUserScript:", s);
objc::call<void> (s, "release");
return true;
}
CHOC_AUTORELEASE_END
return false;
}
bool navigate (const std::string& url)
{
if (url.empty())
return navigate (defaultURI);
CHOC_AUTORELEASE_BEGIN
if (id nsURL = objc::callClass<id> ("NSURL", "URLWithString:", objc::getNSString (url)))
return objc::call<id> (webview, "loadRequest:", objc::callClass<id> ("NSURLRequest", "requestWithURL:", nsURL)) != nullptr;
CHOC_AUTORELEASE_END
return false;
}
bool setHTML (const std::string& html)
{
CHOC_AUTORELEASE_BEGIN
return objc::call<id> (webview, "loadHTMLString:baseURL:", objc::getNSString (html), (id) nullptr) != nullptr;
CHOC_AUTORELEASE_END
}
bool evaluateJavascript (const std::string& script, CompletionHandler completionHandler)
{
CHOC_AUTORELEASE_BEGIN
auto s = objc::getNSString (script);
if (completionHandler)
{
objc::call<void> (webview, "evaluateJavaScript:completionHandler:", s,
^(id result, id error)
{
CHOC_AUTORELEASE_BEGIN
auto errorMessage = getMessageFromNSError (error);
choc::value::Value value;
try
{
if (auto json = convertNSObjectToJSON (result); ! json.empty())
value = choc::json::parseValue (json);
}
catch (const std::exception& e)
{
errorMessage = e.what();
}
completionHandler (errorMessage, value);
CHOC_AUTORELEASE_END
});
}
else
{
objc::call<void> (webview, "evaluateJavaScript:completionHandler:", s, (id) nullptr);
}
return true;
CHOC_AUTORELEASE_END
}
static std::string convertNSObjectToJSON (id value)
{
if (value)
{
if (id nsData = objc::callClass<id> ("NSJSONSerialization", "dataWithJSONObject:options:error:",
value, 12, (id) nullptr))
{
auto data = objc::call<void*> (nsData, "bytes");
auto length = objc::call<unsigned long> (nsData, "length");
return std::string (static_cast<const char*> (data), static_cast<size_t> (length));
}
}
return {};
}
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");
}
static std::string getMessageFromNSError (id nsError)
{
if (nsError)
{
if (id userInfo = objc::call<id> (nsError, "userInfo"))
if (id message = objc::call<id> (userInfo, "objectForKey:", objc::getNSString ("WKJavaScriptExceptionMessage")))
if (auto s = objc::getString (message); ! s.empty())
return s;
return objc::getString (objc::call<id> (nsError, "localizedDescription"));
}
return {};
}
void onResourceRequested (id task)
{
using namespace choc::objc;
CHOC_AUTORELEASE_BEGIN
try
{
id requestUrl = call<id> (call<id> (task, "request"), "URL");
auto makeResponse = [&] (auto responseCode, id headerFields)
{
return call<id> (call<id> (callClass<id> ("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"), getNSString ("Access-Control-Allow-Origin") };
id headerObjects[] = { getNSString (contentLength), getNSString (mimeType), getNSString ("no-store") , getNSString ("*") };
id headerFields = callClass<id> ("NSDictionary", "dictionaryWithObjects:forKeys:count:",
headerObjects, headerKeys, sizeof (headerObjects) / sizeof (id));
call<void> (task, "didReceiveResponse:", makeResponse (200, headerFields));
id data = callClass<id> ("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 (...)
{
id error = callClass<id> ("NSError", "errorWithDomain:code:userInfo:",
getNSString ("NSURLErrorDomain"), -1, nullptr);
call<void> (task, "didFailWithError:", error);
}
CHOC_AUTORELEASE_END
}
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)
{
if (! options->enableDefaultClipboardKeyShortcutsInSafari)
return false;
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;
}
void handleError (id error)
{
static constexpr int NSURLErrorCancelled = -999;
if (objc::call<int> (error, "code") == NSURLErrorCancelled)
return;
setHTML ("<!DOCTYPE html><html><head><title>Error</title></head>"
"<body><h2>" + getMessageFromNSError (error) + "</h2></body></html>");
}
static Pimpl* getPimpl (id self)
{
return (CHOC_OBJC_CAST_BRIDGED Pimpl*) (objc_getAssociatedObject (self, "choc_webview"));
}
WebView& owner;
// NB: this is a pointer because making it a member forces the alignment of this Pimpl class
// to 16, which then conflicts with obj-C pointer alignment...
std::unique_ptr<Options> options;
id webview = {}, manager = {}, delegate = {};
std::string defaultURI;
struct WebviewClass
{
WebviewClass()
{
webviewClass = choc::objc::createDelegateClass ("WKWebView", "CHOCWebView_");
class_addMethod (webviewClass, sel_registerName ("acceptsFirstMouse:"),
(IMP) (+[](id self, SEL, id) -> BOOL
{
if (auto p = getPimpl (self))
return p->options->acceptsFirstMouseClick;
return false;
}), "B@:@");
class_addMethod (webviewClass, sel_registerName ("performKeyEquivalent:"),
(IMP) (+[](id self, SEL, id e) -> BOOL
{
if (auto p = getPimpl (self))
if (p->performKeyEquivalent (self, e))
return true;
return choc::objc::callSuper<BOOL> (self, "performKeyEquivalent:", e);
}), "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 = objc::createDelegateClass ("NSObject", "CHOCWebViewDelegate_");
class_addMethod (delegateClass, sel_registerName ("userContentController:didReceiveScriptMessage:"),
(IMP) (+[](id self, SEL, id, id msg)
{
if (auto p = getPimpl (self))
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 = getPimpl (self))
p->onResourceRequested (task);
}),
"v@:@@");
class_addMethod (delegateClass, sel_registerName ("webView:didFailProvisionalNavigation:withError:"),
(IMP) (+[](id self, SEL, id, id, id error)
{
if (auto p = getPimpl (self))
p->handleError (error);
}),
"v@:@@@");
class_addMethod (delegateClass, sel_registerName ("webView:didFailNavigation:withError:"),
(IMP) (+[](id self, SEL, id, id, id error)
{
if (auto p = getPimpl (self))
p->handleError (error);
}),
"v@:@@@");
class_addMethod (delegateClass, sel_registerName ("webView:stopURLSchemeTask:"), (IMP) (+[](id, SEL, id, id) {}), "v@:@@");
class_addMethod (delegateClass, sel_registerName ("webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:"),
(IMP) (+[](id, SEL, id wkwebview, id params, id /*frame*/, void (^completionHandler)(id))
{
CHOC_AUTORELEASE_BEGIN
id panel = objc::callClass<id> ("NSOpenPanel", "openPanel");
auto allowsMultipleSelection = objc::call<BOOL> (params, "allowsMultipleSelection");
id allowedFileExtensions = objc::call<id> (params, "_allowedFileExtensions");
id window = objc::call<id> (wkwebview, "window");
objc::call<void> (panel, "setAllowsMultipleSelection:", allowsMultipleSelection);
objc::call<void> (panel, "setAllowedFileTypes:", allowedFileExtensions);
objc::call<void> (panel, "beginSheetModalForWindow:completionHandler:", window,
^(long result)
{
CHOC_AUTORELEASE_BEGIN
if (result == 1) // NSModalResponseOK
completionHandler (objc::call<id> (panel, "URLs"));
else
completionHandler (nil);
CHOC_AUTORELEASE_END
});
CHOC_AUTORELEASE_END
}), "v@:@@@@");
objc_registerClassPair (delegateClass);
}
~DelegateClass()
{
objc_disposeClassPair (delegateClass);
}
Class delegateClass = {};
};
static constexpr long WKUserScriptInjectionTimeAtDocumentStart = 0;
};
//==============================================================================
#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 ICoreWebView2Controller2 ICoreWebView2Controller2;
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("4e8a3389-c9d8-4bd2-b6b5-124fee6cc14d")
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(HRESULT, ICoreWebView2Environment*) = 0;
};
MIDL_INTERFACE("6c4819f3-c9b7-4260-8127-c9f5bde7f68c")
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Invoke(HRESULT, ICoreWebView2Controller*) = 0;
};
MIDL_INTERFACE("b96d755e-0319-4e92-a296-23436f46a1fc")
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("0f99a40c-e962-4207-9e92-e3d542eff849")
ICoreWebView2WebMessageReceivedEventArgs : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Source(LPWSTR *) = 0;