-
Notifications
You must be signed in to change notification settings - Fork 0
/
webview.h
1250 lines (1109 loc) · 40.9 KB
/
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
/*
* MIT License
*
* Copyright (c) 2017 Serge Zaitsev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef WEBVIEW_H
#define WEBVIEW_H
#ifndef WEBVIEW_API
#define WEBVIEW_API extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void *webview_t;
// Creates a new webview instance. If debug is non-zero - developer tools will
// be enabled (if the platform supports them). Window parameter can be a
// pointer to the native window handle. If it's non-null - then child WebView
// is embedded into the given parent window. Otherwise a new window is created.
// Depending on the platform, a GtkWindow, NSWindow or HWND pointer can be
// passed here.
WEBVIEW_API webview_t webview_create(int debug, void *window);
// Destroys a webview and closes the native window.
WEBVIEW_API void webview_destroy(webview_t w);
// Runs the main loop until it's terminated. After this function exits - you
// must destroy the webview.
WEBVIEW_API void webview_run(webview_t w);
// Stops the main loop. It is safe to call this function from another other
// background thread.
WEBVIEW_API void webview_terminate(webview_t w);
// Posts a function to be executed on the main thread. You normally do not need
// to call this function, unless you want to tweak the native window.
WEBVIEW_API void
webview_dispatch(webview_t w, void (*fn)(webview_t w, void *arg), void *arg);
// Returns a native window handle pointer. When using GTK backend the pointer
// is GtkWindow pointer, when using Cocoa backend the pointer is NSWindow
// pointer, when using Win32 backend the pointer is HWND pointer.
WEBVIEW_API void *webview_get_window(webview_t w);
// Updates the title of the native window. Must be called from the UI thread.
WEBVIEW_API void webview_set_title(webview_t w, const char *title);
// Window size hints
#define WEBVIEW_HINT_NONE 0 // Width and height are default size
#define WEBVIEW_HINT_MIN 1 // Width and height are minimum bounds
#define WEBVIEW_HINT_MAX 2 // Width and height are maximum bounds
#define WEBVIEW_HINT_FIXED 3 // Window size can not be changed by a user
// Updates native window size. See WEBVIEW_HINT constants.
WEBVIEW_API void webview_set_size(webview_t w, int width, int height,
int hints);
// Navigates webview to the given URL. URL may be a data URI, i.e.
// "data:text/html,<html>...</html>". It is often ok not to url-encode it
// properly, webview will re-encode it for you.
WEBVIEW_API void webview_navigate(webview_t w, const char *url);
// Set webview HTML directly.
WEBVIEW_API void webview_set_html(webview_t w, const char *html);
// Injects JavaScript code at the initialization of the new page. Every time
// the webview will open a the new page - this initialization code will be
// executed. It is guaranteed that code is executed before window.onload.
WEBVIEW_API void webview_init(webview_t w, const char *js);
// Evaluates arbitrary JavaScript code. Evaluation happens asynchronously, also
// the result of the expression is ignored. Use RPC bindings if you want to
// receive notifications about the results of the evaluation.
WEBVIEW_API void webview_eval(webview_t w, const char *js);
// Binds a native C callback so that it will appear under the given name as a
// global JavaScript function. Internally it uses webview_init(). Callback
// receives a request string and a user-provided argument pointer. Request
// string is a JSON array of all the arguments passed to the JavaScript
// function.
WEBVIEW_API void webview_bind(webview_t w, const char *name,
void (*fn)(const char *seq, const char *req,
void *arg),
void *arg);
// Removes a native C callback that was previously set by webview_bind.
WEBVIEW_API void webview_unbind(webview_t w, const char *name);
// Allows to return a value from the native binding. Original request pointer
// must be provided to help internal RPC engine match requests with responses.
// If status is zero - result is expected to be a valid JSON result value.
// If status is not zero - result is an error JSON object.
WEBVIEW_API void webview_return(webview_t w, const char *seq, int status,
const char *result);
#ifdef __cplusplus
}
#endif
#ifndef WEBVIEW_HEADER
#if !defined(WEBVIEW_GTK) && !defined(WEBVIEW_COCOA) && !defined(WEBVIEW_EDGE)
#if defined(__APPLE__)
#define WEBVIEW_COCOA
#elif defined(__unix__)
#define WEBVIEW_GTK
#elif defined(_WIN32)
#define WEBVIEW_EDGE
#else
#error "please, specify webview backend"
#endif
#endif
#include <atomic>
#include <functional>
#include <future>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include <cstring>
namespace webview {
using dispatch_fn_t = std::function<void()>;
inline std::string url_encode(const std::string &s) {
std::string encoded;
for (unsigned int i = 0; i < s.length(); i++) {
auto c = s[i];
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded = encoded + c;
} else {
char hex[4];
snprintf(hex, sizeof(hex), "%%%02x", c);
encoded = encoded + hex;
}
}
return encoded;
}
inline int json_parse_c(const char *s, size_t sz, const char *key, size_t keysz,
const char **value, size_t *valuesz) {
enum {
JSON_STATE_VALUE,
JSON_STATE_LITERAL,
JSON_STATE_STRING,
JSON_STATE_ESCAPE,
JSON_STATE_UTF8
} state = JSON_STATE_VALUE;
const char *k = NULL;
int index = 1;
int depth = 0;
int utf8_bytes = 0;
if (key == NULL) {
index = keysz;
keysz = 0;
}
*value = NULL;
*valuesz = 0;
for (; sz > 0; s++, sz--) {
enum {
JSON_ACTION_NONE,
JSON_ACTION_START,
JSON_ACTION_END,
JSON_ACTION_START_STRUCT,
JSON_ACTION_END_STRUCT
} action = JSON_ACTION_NONE;
unsigned char c = *s;
switch (state) {
case JSON_STATE_VALUE:
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' ||
c == ':') {
continue;
} else if (c == '"') {
action = JSON_ACTION_START;
state = JSON_STATE_STRING;
} else if (c == '{' || c == '[') {
action = JSON_ACTION_START_STRUCT;
} else if (c == '}' || c == ']') {
action = JSON_ACTION_END_STRUCT;
} else if (c == 't' || c == 'f' || c == 'n' || c == '-' ||
(c >= '0' && c <= '9')) {
action = JSON_ACTION_START;
state = JSON_STATE_LITERAL;
} else {
return -1;
}
break;
case JSON_STATE_LITERAL:
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' ||
c == ']' || c == '}' || c == ':') {
state = JSON_STATE_VALUE;
s--;
sz++;
action = JSON_ACTION_END;
} else if (c < 32 || c > 126) {
return -1;
} // fallthrough
case JSON_STATE_STRING:
if (c < 32 || (c > 126 && c < 192)) {
return -1;
} else if (c == '"') {
action = JSON_ACTION_END;
state = JSON_STATE_VALUE;
} else if (c == '\\') {
state = JSON_STATE_ESCAPE;
} else if (c >= 192 && c < 224) {
utf8_bytes = 1;
state = JSON_STATE_UTF8;
} else if (c >= 224 && c < 240) {
utf8_bytes = 2;
state = JSON_STATE_UTF8;
} else if (c >= 240 && c < 247) {
utf8_bytes = 3;
state = JSON_STATE_UTF8;
} else if (c >= 128 && c < 192) {
return -1;
}
break;
case JSON_STATE_ESCAPE:
if (c == '"' || c == '\\' || c == '/' || c == 'b' || c == 'f' ||
c == 'n' || c == 'r' || c == 't' || c == 'u') {
state = JSON_STATE_STRING;
} else {
return -1;
}
break;
case JSON_STATE_UTF8:
if (c < 128 || c > 191) {
return -1;
}
utf8_bytes--;
if (utf8_bytes == 0) {
state = JSON_STATE_STRING;
}
break;
default:
return -1;
}
if (action == JSON_ACTION_END_STRUCT) {
depth--;
}
if (depth == 1) {
if (action == JSON_ACTION_START || action == JSON_ACTION_START_STRUCT) {
if (index == 0) {
*value = s;
} else if (keysz > 0 && index == 1) {
k = s;
} else {
index--;
}
} else if (action == JSON_ACTION_END ||
action == JSON_ACTION_END_STRUCT) {
if (*value != NULL && index == 0) {
*valuesz = (size_t)(s + 1 - *value);
return 0;
} else if (keysz > 0 && k != NULL) {
if (keysz == (size_t)(s - k - 1) && memcmp(key, k + 1, keysz) == 0) {
index = 0;
} else {
index = 2;
}
k = NULL;
}
}
}
if (action == JSON_ACTION_START_STRUCT) {
depth++;
}
}
return -1;
}
inline std::string json_escape(const std::string &s) {
// TODO: implement
return '"' + s + '"';
}
inline int json_unescape(const char *s, size_t n, char *out) {
int r = 0;
if (*s++ != '"') {
return -1;
}
while (n > 2) {
char c = *s;
if (c == '\\') {
s++;
n--;
switch (*s) {
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
case '\\':
c = '\\';
break;
case '/':
c = '/';
break;
case '\"':
c = '\"';
break;
default: // TODO: support unicode decoding
return -1;
}
}
if (out != NULL) {
*out++ = c;
}
s++;
n--;
r++;
}
if (*s != '"') {
return -1;
}
if (out != NULL) {
*out = '\0';
}
return r;
}
inline std::string json_parse(const std::string &s, const std::string &key,
const int index) {
const char *value;
size_t value_sz;
if (key == "") {
json_parse_c(s.c_str(), s.length(), nullptr, index, &value, &value_sz);
} else {
json_parse_c(s.c_str(), s.length(), key.c_str(), key.length(), &value,
&value_sz);
}
if (value != nullptr) {
if (value[0] != '"') {
return std::string(value, value_sz);
}
int n = json_unescape(value, value_sz, nullptr);
if (n > 0) {
char *decoded = new char[n + 1];
json_unescape(value, value_sz, decoded);
std::string result(decoded, n);
delete[] decoded;
return result;
}
}
return "";
}
} // namespace webview
#if defined(WEBVIEW_GTK)
//
// ====================================================================
//
// This implementation uses webkit2gtk backend. It requires gtk+3.0 and
// webkit2gtk-4.0 libraries. Proper compiler flags can be retrieved via:
//
// pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0
//
// ====================================================================
//
#include <JavaScriptCore/JavaScript.h>
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>
namespace webview {
class gtk_webkit_engine {
public:
gtk_webkit_engine(bool debug, void *window)
: m_window(static_cast<GtkWidget *>(window)) {
gtk_init_check(0, NULL);
m_window = static_cast<GtkWidget *>(window);
if (m_window == nullptr) {
m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
}
g_signal_connect(G_OBJECT(m_window), "destroy",
G_CALLBACK(+[](GtkWidget *, gpointer arg) {
static_cast<gtk_webkit_engine *>(arg)->terminate();
}),
this);
// Initialize webview widget
m_webview = webkit_web_view_new();
WebKitUserContentManager *manager =
webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(m_webview));
g_signal_connect(manager, "script-message-received::external",
G_CALLBACK(+[](WebKitUserContentManager *,
WebKitJavascriptResult *r, gpointer arg) {
auto *w = static_cast<gtk_webkit_engine *>(arg);
char *s = get_string_from_js_result(r);
w->on_message(s);
g_free(s);
}),
this);
webkit_user_content_manager_register_script_message_handler(manager,
"external");
init("window.external={invoke:function(s){window.webkit.messageHandlers."
"external.postMessage(s);}}");
gtk_container_add(GTK_CONTAINER(m_window), GTK_WIDGET(m_webview));
gtk_widget_grab_focus(GTK_WIDGET(m_webview));
WebKitSettings *settings =
webkit_web_view_get_settings(WEBKIT_WEB_VIEW(m_webview));
webkit_settings_set_javascript_can_access_clipboard(settings, true);
if (debug) {
webkit_settings_set_enable_write_console_messages_to_stdout(settings,
true);
webkit_settings_set_enable_developer_extras(settings, true);
}
gtk_widget_show_all(m_window);
}
virtual ~gtk_webkit_engine() = default;
void *window() { return (void *)m_window; }
void run() { gtk_main(); }
void terminate() { gtk_main_quit(); }
void dispatch(std::function<void()> f) {
g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)([](void *f) -> int {
(*static_cast<dispatch_fn_t *>(f))();
return G_SOURCE_REMOVE;
}),
new std::function<void()>(f),
[](void *f) { delete static_cast<dispatch_fn_t *>(f); });
}
void set_title(const std::string &title) {
gtk_window_set_title(GTK_WINDOW(m_window), title.c_str());
}
void set_size(int width, int height, int hints) {
gtk_window_set_resizable(GTK_WINDOW(m_window), hints != WEBVIEW_HINT_FIXED);
if (hints == WEBVIEW_HINT_NONE) {
gtk_window_resize(GTK_WINDOW(m_window), width, height);
} else if (hints == WEBVIEW_HINT_FIXED) {
gtk_widget_set_size_request(m_window, width, height);
} else {
GdkGeometry g;
g.min_width = g.max_width = width;
g.min_height = g.max_height = height;
GdkWindowHints h =
(hints == WEBVIEW_HINT_MIN ? GDK_HINT_MIN_SIZE : GDK_HINT_MAX_SIZE);
// This defines either MIN_SIZE, or MAX_SIZE, but not both:
gtk_window_set_geometry_hints(GTK_WINDOW(m_window), nullptr, &g, h);
}
}
void navigate(const std::string &url) {
webkit_web_view_load_uri(WEBKIT_WEB_VIEW(m_webview), url.c_str());
}
void set_html(const std::string &html) {
webkit_web_view_load_html(WEBKIT_WEB_VIEW(m_webview), html.c_str(), NULL);
}
void init(const std::string &js) {
WebKitUserContentManager *manager =
webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(m_webview));
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, NULL, NULL));
}
void eval(const std::string &js) {
webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(m_webview), js.c_str(), NULL,
NULL, NULL);
}
private:
virtual void on_message(const std::string &msg) = 0;
static char *get_string_from_js_result(WebKitJavascriptResult *r) {
char *s;
#if WEBKIT_MAJOR_VERSION >= 2 && WEBKIT_MINOR_VERSION >= 22
JSCValue *value = webkit_javascript_result_get_js_value(r);
s = jsc_value_to_string(value);
#else
JSGlobalContextRef ctx = webkit_javascript_result_get_global_context(r);
JSValueRef value = webkit_javascript_result_get_value(r);
JSStringRef js = JSValueToStringCopy(ctx, value, NULL);
size_t n = JSStringGetMaximumUTF8CStringSize(js);
s = g_new(char, n);
JSStringGetUTF8CString(js, s, n);
JSStringRelease(js);
#endif
return s;
}
GtkWidget *m_window;
GtkWidget *m_webview;
};
using browser_engine = gtk_webkit_engine;
} // namespace webview
#elif defined(WEBVIEW_COCOA)
//
// ====================================================================
//
// This implementation uses Cocoa WKWebView backend on macOS. It is
// written using ObjC runtime and uses WKWebView class as a browser runtime.
// You should pass "-framework Webkit" flag to the compiler.
//
// ====================================================================
//
#include <CoreGraphics/CoreGraphics.h>
#include <objc/objc-runtime.h>
#define NSBackingStoreBuffered 2
#define NSWindowStyleMaskResizable 8
#define NSWindowStyleMaskMiniaturizable 4
#define NSWindowStyleMaskTitled 1
#define NSWindowStyleMaskClosable 2
#define NSApplicationActivationPolicyRegular 0
#define WKUserScriptInjectionTimeAtDocumentStart 0
namespace webview {
// Helpers to avoid too much typing
id operator"" _cls(const char *s, std::size_t) { return (id)objc_getClass(s); }
SEL operator"" _sel(const char *s, std::size_t) { return sel_registerName(s); }
id operator"" _str(const char *s, std::size_t) {
return ((id(*)(id, SEL, const char *))objc_msgSend)(
"NSString"_cls, "stringWithUTF8String:"_sel, s);
}
class cocoa_wkwebview_engine {
public:
cocoa_wkwebview_engine(bool debug, void *window) {
// Application
id app = ((id(*)(id, SEL))objc_msgSend)("NSApplication"_cls,
"sharedApplication"_sel);
((void (*)(id, SEL, long))objc_msgSend)(
app, "setActivationPolicy:"_sel, NSApplicationActivationPolicyRegular);
// Delegate
auto cls =
objc_allocateClassPair((Class) "NSResponder"_cls, "AppDelegate", 0);
class_addProtocol(cls, objc_getProtocol("NSTouchBarProvider"));
class_addMethod(cls, "applicationShouldTerminateAfterLastWindowClosed:"_sel,
(IMP)(+[](id, SEL, id) -> BOOL { return 1; }), "c@:@");
class_addMethod(cls, "userContentController:didReceiveScriptMessage:"_sel,
(IMP)(+[](id self, SEL, id, id msg) {
auto w =
(cocoa_wkwebview_engine *)objc_getAssociatedObject(
self, "webview");
assert(w);
w->on_message(((const char *(*)(id, SEL))objc_msgSend)(
((id(*)(id, SEL))objc_msgSend)(msg, "body"_sel),
"UTF8String"_sel));
}),
"v@:@@");
objc_registerClassPair(cls);
auto delegate = ((id(*)(id, SEL))objc_msgSend)((id)cls, "new"_sel);
objc_setAssociatedObject(delegate, "webview", (id)this,
OBJC_ASSOCIATION_ASSIGN);
((void (*)(id, SEL, id))objc_msgSend)(app, sel_registerName("setDelegate:"),
delegate);
// Main window
if (window == nullptr) {
m_window = ((id(*)(id, SEL))objc_msgSend)("NSWindow"_cls, "alloc"_sel);
m_window =
((id(*)(id, SEL, CGRect, int, unsigned long, int))objc_msgSend)(
m_window, "initWithContentRect:styleMask:backing:defer:"_sel,
CGRectMake(0, 0, 0, 0), 0, NSBackingStoreBuffered, 0);
} else {
m_window = (id)window;
}
// Webview
auto config =
((id(*)(id, SEL))objc_msgSend)("WKWebViewConfiguration"_cls, "new"_sel);
m_manager =
((id(*)(id, SEL))objc_msgSend)(config, "userContentController"_sel);
m_webview = ((id(*)(id, SEL))objc_msgSend)("WKWebView"_cls, "alloc"_sel);
if (debug) {
// Equivalent Obj-C:
// [[config preferences] setValue:@YES forKey:@"developerExtrasEnabled"];
((id(*)(id, SEL, id, id))objc_msgSend)(
((id(*)(id, SEL))objc_msgSend)(config, "preferences"_sel),
"setValue:forKey:"_sel,
((id(*)(id, SEL, BOOL))objc_msgSend)("NSNumber"_cls,
"numberWithBool:"_sel, 1),
"developerExtrasEnabled"_str);
}
// Equivalent Obj-C:
// [[config preferences] setValue:@YES forKey:@"fullScreenEnabled"];
((id(*)(id, SEL, id, id))objc_msgSend)(
((id(*)(id, SEL))objc_msgSend)(config, "preferences"_sel),
"setValue:forKey:"_sel,
((id(*)(id, SEL, BOOL))objc_msgSend)("NSNumber"_cls,
"numberWithBool:"_sel, 1),
"fullScreenEnabled"_str);
// Equivalent Obj-C:
// [[config preferences] setValue:@YES forKey:@"javaScriptCanAccessClipboard"];
((id(*)(id, SEL, id, id))objc_msgSend)(
((id(*)(id, SEL))objc_msgSend)(config, "preferences"_sel),
"setValue:forKey:"_sel,
((id(*)(id, SEL, BOOL))objc_msgSend)("NSNumber"_cls,
"numberWithBool:"_sel, 1),
"javaScriptCanAccessClipboard"_str);
// Equivalent Obj-C:
// [[config preferences] setValue:@YES forKey:@"DOMPasteAllowed"];
((id(*)(id, SEL, id, id))objc_msgSend)(
((id(*)(id, SEL))objc_msgSend)(config, "preferences"_sel),
"setValue:forKey:"_sel,
((id(*)(id, SEL, BOOL))objc_msgSend)("NSNumber"_cls,
"numberWithBool:"_sel, 1),
"DOMPasteAllowed"_str);
((void (*)(id, SEL, CGRect, id))objc_msgSend)(
m_webview, "initWithFrame:configuration:"_sel, CGRectMake(0, 0, 0, 0),
config);
((void (*)(id, SEL, id, id))objc_msgSend)(
m_manager, "addScriptMessageHandler:name:"_sel, delegate,
"external"_str);
init(R"script(
window.external = {
invoke: function(s) {
window.webkit.messageHandlers.external.postMessage(s);
},
};
)script");
((void (*)(id, SEL, id))objc_msgSend)(m_window, "setContentView:"_sel,
m_webview);
((void (*)(id, SEL, id))objc_msgSend)(m_window, "makeKeyAndOrderFront:"_sel,
nullptr);
}
virtual ~cocoa_wkwebview_engine() { close(); }
void *window() { return (void *)m_window; }
void terminate() {
close();
((void (*)(id, SEL, id))objc_msgSend)("NSApp"_cls, "terminate:"_sel,
nullptr);
}
void run() {
id app = ((id(*)(id, SEL))objc_msgSend)("NSApplication"_cls,
"sharedApplication"_sel);
dispatch([&]() {
((void (*)(id, SEL, BOOL))objc_msgSend)(
app, "activateIgnoringOtherApps:"_sel, 1);
});
((void (*)(id, SEL))objc_msgSend)(app, "run"_sel);
}
void dispatch(std::function<void()> f) {
dispatch_async_f(dispatch_get_main_queue(), new dispatch_fn_t(f),
(dispatch_function_t)([](void *arg) {
auto f = static_cast<dispatch_fn_t *>(arg);
(*f)();
delete f;
}));
}
void set_title(const std::string &title) {
((void (*)(id, SEL, id))objc_msgSend)(
m_window, "setTitle:"_sel,
((id(*)(id, SEL, const char *))objc_msgSend)(
"NSString"_cls, "stringWithUTF8String:"_sel, title.c_str()));
}
void set_size(int width, int height, int hints) {
auto style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable;
if (hints != WEBVIEW_HINT_FIXED) {
style = style | NSWindowStyleMaskResizable;
}
((void (*)(id, SEL, unsigned long))objc_msgSend)(
m_window, "setStyleMask:"_sel, style);
if (hints == WEBVIEW_HINT_MIN) {
((void (*)(id, SEL, CGSize))objc_msgSend)(
m_window, "setContentMinSize:"_sel, CGSizeMake(width, height));
} else if (hints == WEBVIEW_HINT_MAX) {
((void (*)(id, SEL, CGSize))objc_msgSend)(
m_window, "setContentMaxSize:"_sel, CGSizeMake(width, height));
} else {
((void (*)(id, SEL, CGRect, BOOL, BOOL))objc_msgSend)(
m_window, "setFrame:display:animate:"_sel,
CGRectMake(0, 0, width, height), 1, 0);
}
((void (*)(id, SEL))objc_msgSend)(m_window, "center"_sel);
}
void navigate(const std::string &url) {
auto nsurl = ((id(*)(id, SEL, id))objc_msgSend)(
"NSURL"_cls, "URLWithString:"_sel,
((id(*)(id, SEL, const char *))objc_msgSend)(
"NSString"_cls, "stringWithUTF8String:"_sel, url.c_str()));
((void (*)(id, SEL, id))objc_msgSend)(
m_webview, "loadRequest:"_sel,
((id(*)(id, SEL, id))objc_msgSend)("NSURLRequest"_cls,
"requestWithURL:"_sel, nsurl));
}
void set_html(const std::string &html) {
((void (*)(id, SEL, id, id))objc_msgSend)(
m_webview, "loadHTMLString:baseURL:"_sel,
((id(*)(id, SEL, const char *))objc_msgSend)(
"NSString"_cls, "stringWithUTF8String:"_sel, html.c_str()),
nullptr);
}
void init(const std::string &js) {
// Equivalent Obj-C:
// [m_manager addUserScript:[[WKUserScript alloc] initWithSource:[NSString stringWithUTF8String:js.c_str()] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]]
((void (*)(id, SEL, id))objc_msgSend)(
m_manager, "addUserScript:"_sel,
((id(*)(id, SEL, id, long, BOOL))objc_msgSend)(
((id(*)(id, SEL))objc_msgSend)("WKUserScript"_cls, "alloc"_sel),
"initWithSource:injectionTime:forMainFrameOnly:"_sel,
((id(*)(id, SEL, const char *))objc_msgSend)(
"NSString"_cls, "stringWithUTF8String:"_sel, js.c_str()),
WKUserScriptInjectionTimeAtDocumentStart, 1));
}
void eval(const std::string &js) {
((void (*)(id, SEL, id, id))objc_msgSend)(
m_webview, "evaluateJavaScript:completionHandler:"_sel,
((id(*)(id, SEL, const char *))objc_msgSend)(
"NSString"_cls, "stringWithUTF8String:"_sel, js.c_str()),
nullptr);
}
private:
virtual void on_message(const std::string &msg) = 0;
void close() { ((void (*)(id, SEL))objc_msgSend)(m_window, "close"_sel); }
id m_window;
id m_webview;
id m_manager;
};
using browser_engine = cocoa_wkwebview_engine;
} // namespace webview
#elif defined(WEBVIEW_EDGE)
//
// ====================================================================
//
// This implementation uses Win32 API to create a native window. It
// uses Edge/Chromium webview2 backend as a browser engine.
//
// ====================================================================
//
#define WIN32_LEAN_AND_MEAN
#include <shlobj.h>
#include <shlwapi.h>
#include <stdlib.h>
#include <windows.h>
#include <winrt/Windows.Foundation.h>
#include "webview2.h"
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "windowsapp")
#pragma comment(lib, "shell32.lib")
namespace webview {
using msg_cb_t = std::function<void(const std::string)>;
using namespace winrt;
class win32_edge_engine {
public:
win32_edge_engine(bool debug, void *window) {
if (window == nullptr) {
HINSTANCE hInstance = GetModuleHandle(nullptr);
HICON icon = (HICON)LoadImage(
hInstance, IDI_APPLICATION, IMAGE_ICON, GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
WNDCLASSEXW wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hInstance = hInstance;
wc.lpszClassName = L"webview";
wc.hIcon = icon;
wc.hIconSm = icon;
wc.lpfnWndProc =
(WNDPROC)(+[](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) -> LRESULT {
auto w = (win32_edge_engine *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
switch (msg) {
case WM_SIZE:
w->resize(hwnd);
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
w->terminate();
break;
case WM_GETMINMAXINFO: {
auto lpmmi = (LPMINMAXINFO)lp;
if (w == nullptr) {
return 0;
}
if (w->m_maxsz.x > 0 && w->m_maxsz.y > 0) {
lpmmi->ptMaxSize = w->m_maxsz;
lpmmi->ptMaxTrackSize = w->m_maxsz;
}
if (w->m_minsz.x > 0 && w->m_minsz.y > 0) {
lpmmi->ptMinTrackSize = w->m_minsz;
}
} break;
default:
return DefWindowProcW(hwnd, msg, wp, lp);
}
return 0;
});
RegisterClassExW(&wc);
m_window = CreateWindowW(L"webview", L"", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, nullptr,
nullptr, GetModuleHandle(nullptr), nullptr);
SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);
} else {
m_window = *(static_cast<HWND *>(window));
}
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
ShowWindow(m_window, SW_SHOW);
UpdateWindow(m_window);
SetFocus(m_window);
auto cb =
std::bind(&win32_edge_engine::on_message, this, std::placeholders::_1);
embed(m_window, debug, cb);
resize(m_window);
m_controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
virtual ~win32_edge_engine() = default;
void run() {
MSG msg;
BOOL res;
while ((res = GetMessage(&msg, nullptr, 0, 0)) != -1) {
if (msg.hwnd) {
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
}
if (msg.message == WM_APP) {
auto f = (dispatch_fn_t *)(msg.lParam);
(*f)();
delete f;
} else if (msg.message == WM_QUIT) {
return;
}
}
}
void *window() { return (void *)m_window; }
void terminate() { PostQuitMessage(0); }
void dispatch(dispatch_fn_t f) {
PostThreadMessage(m_main_thread, WM_APP, 0, (LPARAM) new dispatch_fn_t(f));
}
void set_title(const std::string &title) {
SetWindowTextW(m_window, winrt::to_hstring(title).c_str());
}
void set_size(int width, int height, int hints) {
auto style = GetWindowLong(m_window, GWL_STYLE);
if (hints == WEBVIEW_HINT_FIXED) {
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
} else {
style |= (WS_THICKFRAME | WS_MAXIMIZEBOX);
}
SetWindowLong(m_window, GWL_STYLE, style);
if (hints == WEBVIEW_HINT_MAX) {
m_maxsz.x = width;
m_maxsz.y = height;
} else if (hints == WEBVIEW_HINT_MIN) {
m_minsz.x = width;
m_minsz.y = height;
} else {
RECT r;
r.left = r.top = 0;
r.right = width;
r.bottom = height;
AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, 0);
SetWindowPos(
m_window, NULL, r.left, r.top, r.right - r.left, r.bottom - r.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_FRAMECHANGED);
resize(m_window);
}
}
void navigate(const std::string &url) {
auto wurl = winrt::to_hstring(url);
m_webview->Navigate(wurl.c_str());
}
void init(const std::string &js) {
auto wjs = winrt::to_hstring(js);
m_webview->AddScriptToExecuteOnDocumentCreated(wjs.c_str(), nullptr);
}
void eval(const std::string &js) {
auto wjs = winrt::to_hstring(js);
m_webview->ExecuteScript(wjs.c_str(), nullptr);
}
void set_html(const std::string &html) {
auto html2 = winrt::to_hstring("data:text/html," + url_encode(html));
m_webview->Navigate(html2.c_str());
}
private:
bool embed(HWND wnd, bool debug, msg_cb_t cb) {
std::atomic_flag flag = ATOMIC_FLAG_INIT;
flag.test_and_set();
wchar_t currentExePath[MAX_PATH];
GetModuleFileNameW(NULL, currentExePath, MAX_PATH);
wchar_t *currentExeName = PathFindFileNameW(currentExePath);
wchar_t dataPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, dataPath))) {
return false;
}
wchar_t userDataFolder[MAX_PATH];
PathCombineW(userDataFolder, dataPath, currentExeName);
HRESULT res = CreateCoreWebView2EnvironmentWithOptions(
nullptr, userDataFolder, nullptr,
new webview2_com_handler(wnd, cb,
[&](ICoreWebView2Controller *controller) {
m_controller = controller;
m_controller->get_CoreWebView2(&m_webview);
m_webview->AddRef();
flag.clear();
}));
if (res != S_OK) {
return false;
}
MSG msg = {};
while (flag.test_and_set() && GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
init("window.external={invoke:s=>window.chrome.webview.postMessage(s)}");
return true;
}
void resize(HWND wnd) {
if (m_controller == nullptr) {
return;
}