forked from webview/webview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebview.h
2866 lines (2565 loc) · 95.3 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
* Copyright (c) 2022 Steffen André Langnes
*
* 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
#if defined(WEBVIEW_SHARED) || defined(WEBVIEW_BUILD_SHARED)
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(WEBVIEW_BUILD_SHARED)
#define WEBVIEW_API __declspec(dllexport)
#else
#define WEBVIEW_API __declspec(dllimport)
#endif
#else
#define WEBVIEW_API __attribute__((visibility("default")))
#endif
#elif !defined(WEBVIEW_STATIC) && defined(__cplusplus)
#define WEBVIEW_API inline
#else
#define WEBVIEW_API extern
#endif
#endif
#ifndef WEBVIEW_VERSION_MAJOR
// The current library major version.
#define WEBVIEW_VERSION_MAJOR 0
#endif
#ifndef WEBVIEW_VERSION_MINOR
// The current library minor version.
#define WEBVIEW_VERSION_MINOR 11
#endif
#ifndef WEBVIEW_VERSION_PATCH
// The current library patch version.
#define WEBVIEW_VERSION_PATCH 0
#endif
#ifndef WEBVIEW_VERSION_PRE_RELEASE
// SemVer 2.0.0 pre-release labels prefixed with "-".
#define WEBVIEW_VERSION_PRE_RELEASE ""
#endif
#ifndef WEBVIEW_VERSION_BUILD_METADATA
// SemVer 2.0.0 build metadata prefixed with "+".
#define WEBVIEW_VERSION_BUILD_METADATA ""
#endif
// Utility macro for stringifying a macro argument.
#define WEBVIEW_STRINGIFY(x) #x
// Utility macro for stringifying the result of a macro argument expansion.
#define WEBVIEW_EXPAND_AND_STRINGIFY(x) WEBVIEW_STRINGIFY(x)
// SemVer 2.0.0 version number in MAJOR.MINOR.PATCH format.
#define WEBVIEW_VERSION_NUMBER \
WEBVIEW_EXPAND_AND_STRINGIFY(WEBVIEW_VERSION_MAJOR) \
"." WEBVIEW_EXPAND_AND_STRINGIFY( \
WEBVIEW_VERSION_MINOR) "." WEBVIEW_EXPAND_AND_STRINGIFY(WEBVIEW_VERSION_PATCH)
// Holds the elements of a MAJOR.MINOR.PATCH version number.
typedef struct {
// Major version.
unsigned int major;
// Minor version.
unsigned int minor;
// Patch version.
unsigned int patch;
} webview_version_t;
// Holds the library's version information.
typedef struct {
// The elements of the version number.
webview_version_t version;
// SemVer 2.0.0 version number in MAJOR.MINOR.PATCH format.
char version_number[32];
// SemVer 2.0.0 pre-release labels prefixed with "-" if specified, otherwise
// an empty string.
char pre_release[48];
// SemVer 2.0.0 build metadata prefixed with "+", otherwise an empty string.
char build_metadata[48];
} webview_version_info_t;
#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). The 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. Returns null on failure. Creation can fail for various reasons
// such as when required runtime dependencies are missing or when window creation
// fails.
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 a GTK backend the pointer
// is a GtkWindow pointer, when using a Cocoa backend the pointer is a NSWindow
// pointer, when using a Win32 backend the pointer is a 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 the size of the native window. 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 properly encoded data URI.
// Examples:
// webview_navigate(w, "https://github.com/webview/webview");
// webview_navigate(w, "data:text/html,%3Ch1%3EHello%3C%2Fh1%3E");
// webview_navigate(w, "data:text/html;base64,PGgxPkhlbGxvPC9oMT4=");
WEBVIEW_API void webview_navigate(webview_t w, const char *url);
// Set webview HTML directly.
// Example: webview_set_html(w, "<h1>Hello</h1>");
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 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(). The callback
// receives a sequential request id, a request string and a user-provided
// argument pointer. The 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);
// Responds to a binding call from the JS side. The ID/sequence number must
// match the value passed to the binding handler in order to respond to the
// call and complete the promise on the JS side. A status of zero resolves
// the promise, and any other value rejects it. The result must either be a
// valid JSON value or an empty string for the primitive JS value "undefined".
WEBVIEW_API void webview_return(webview_t w, const char *seq, int status,
const char *result);
// Get the library's version information.
// @since 0.10
WEBVIEW_API const webview_version_info_t *webview_version(void);
#ifdef __cplusplus
}
#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
#ifndef WEBVIEW_DEPRECATED
#if __cplusplus >= 201402L
#define WEBVIEW_DEPRECATED(reason) [[deprecated(reason)]]
#elif defined(_MSC_VER)
#define WEBVIEW_DEPRECATED(reason) __declspec(deprecated(reason))
#else
#define WEBVIEW_DEPRECATED(reason) __attribute__((deprecated(reason)))
#endif
#endif
#ifndef WEBVIEW_DEPRECATED_PRIVATE
#define WEBVIEW_DEPRECATED_PRIVATE \
WEBVIEW_DEPRECATED("Private API should not be used")
#endif
#include <array>
#include <atomic>
#include <cstdint>
#include <functional>
#include <future>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include <cstring>
namespace webview {
using dispatch_fn_t = std::function<void()>;
namespace detail {
// The library's version information.
constexpr const webview_version_info_t library_version_info{
{WEBVIEW_VERSION_MAJOR, WEBVIEW_VERSION_MINOR, WEBVIEW_VERSION_PATCH},
WEBVIEW_VERSION_NUMBER,
WEBVIEW_VERSION_PRE_RELEASE,
WEBVIEW_VERSION_BUILD_METADATA};
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 = nullptr;
int index = 1;
int depth = 0;
int utf8_bytes = 0;
*value = nullptr;
*valuesz = 0;
if (key == nullptr) {
index = static_cast<decltype(index)>(keysz);
if (index < 0) {
return -1;
}
keysz = 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;
auto c = static_cast<unsigned char>(*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 != nullptr && index == 0) {
*valuesz = (size_t)(s + 1 - *value);
return 0;
} else if (keysz > 0 && k != nullptr) {
if (keysz == (size_t)(s - k - 1) && memcmp(key, k + 1, keysz) == 0) {
index = 0;
} else {
index = 2;
}
k = nullptr;
}
}
}
if (action == JSON_ACTION_START_STRUCT) {
depth++;
}
}
return -1;
}
constexpr bool is_json_special_char(unsigned int c) {
return c == '"' || c == '\\';
}
constexpr bool is_control_char(unsigned int c) {
return c <= 0x1f || (c >= 0x7f && c <= 0x9f);
}
inline std::string json_escape(const std::string &s, bool add_quotes = true) {
constexpr char hex_alphabet[]{"0123456789abcdef"};
// Calculate the size of the resulting string.
// Add space for the double quotes.
auto required_length = s.size() + (add_quotes ? 2 : 0);
for (auto c : s) {
auto uc = static_cast<unsigned char>(c);
if (is_json_special_char(uc)) {
// '\' and a single following character
required_length += 2;
continue;
}
if (is_control_char(uc)) {
// '\', 'u', 4 digits
required_length += 6;
continue;
}
++required_length;
}
// Allocate memory for resulting string only once.
std::string result;
result.reserve(required_length);
if (add_quotes) {
result += '"';
}
// Copy string while escaping characters.
for (auto c : s) {
auto uc = static_cast<unsigned char>(c);
if (is_json_special_char(uc)) {
result += '\\';
result += c;
continue;
}
if (is_control_char(uc)) {
auto h = (uc >> 4) & 0x0f;
auto l = uc & 0x0f;
result += "\\u00";
// NOLINTBEGIN(cppcoreguidelines-pro-bounds-constant-array-index)
result += hex_alphabet[h];
result += hex_alphabet[l];
// NOLINTEND(cppcoreguidelines-pro-bounds-constant-array-index)
continue;
}
result += c;
}
if (add_quotes) {
result += '"';
}
return result;
}
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 != nullptr) {
*out++ = c;
}
s++;
n--;
r++;
}
if (*s != '"') {
return -1;
}
if (out != nullptr) {
*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.empty()) {
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 {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 detail
WEBVIEW_DEPRECATED_PRIVATE
inline int json_parse_c(const char *s, size_t sz, const char *key, size_t keysz,
const char **value, size_t *valuesz) {
return detail::json_parse_c(s, sz, key, keysz, value, valuesz);
}
WEBVIEW_DEPRECATED_PRIVATE
inline std::string json_escape(const std::string &s) {
return detail::json_escape(s);
}
WEBVIEW_DEPRECATED_PRIVATE
inline int json_unescape(const char *s, size_t n, char *out) {
return detail::json_unescape(s, n, out);
}
WEBVIEW_DEPRECATED_PRIVATE
inline std::string json_parse(const std::string &s, const std::string &key,
const int index) {
return detail::json_parse(s, key, index);
}
} // 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 {
namespace detail {
class gtk_webkit_engine {
public:
gtk_webkit_engine(bool debug, void *window)
: m_window(static_cast<GtkWidget *>(window)) {
if (!m_window) {
if (gtk_init_check(nullptr, nullptr) == FALSE) {
return;
}
m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
inc_window_count();
g_signal_connect(G_OBJECT(m_window), "destroy",
G_CALLBACK(+[](GtkWidget *, gpointer arg) {
auto *w = static_cast<gtk_webkit_engine *>(arg);
if (dec_window_count() <= 0) {
w->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(),
nullptr);
}
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,
nullptr, nullptr));
}
void eval(const std::string &js) {
webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(m_webview), js.c_str(),
nullptr, nullptr, nullptr);
}
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) || \
WEBKIT_MAJOR_VERSION > 2
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, nullptr);
size_t n = JSStringGetMaximumUTF8CStringSize(js);
s = g_new(char, n);
JSStringGetUTF8CString(js, s, n);
JSStringRelease(js);
#endif
return s;
}
static std::atomic_uint &window_ref_count() {
static std::atomic_uint ref_count{0};
return ref_count;
}
static unsigned int inc_window_count() { return ++window_ref_count(); }
static unsigned int dec_window_count() {
auto &count = window_ref_count();
if (count > 0) {
return --count;
}
return 0;
}
GtkWidget *m_window;
GtkWidget *m_webview;
};
} // namespace detail
using browser_engine = detail::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/NSObjCRuntime.h>
#include <objc/objc-runtime.h>
namespace webview {
namespace detail {
namespace objc {
// A convenient template function for unconditionally casting the specified
// C-like function into a function that can be called with the given return
// type and arguments. Caller takes full responsibility for ensuring that
// the function call is valid. It is assumed that the function will not
// throw exceptions.
template <typename Result, typename Callable, typename... Args>
Result invoke(Callable callable, Args... args) noexcept {
return reinterpret_cast<Result (*)(Args...)>(callable)(args...);
}
// Calls objc_msgSend.
template <typename Result, typename... Args>
Result msg_send(Args... args) noexcept {
return invoke<Result>(objc_msgSend, args...);
}
// Wrapper around NSAutoreleasePool that drains the pool on destruction.
class autoreleasepool {
public:
autoreleasepool()
: m_pool(msg_send<id>(objc_getClass("NSAutoreleasePool"),
sel_registerName("new"))) {}
~autoreleasepool() {
if (m_pool) {
msg_send<void>(m_pool, sel_registerName("drain"));
}
}
autoreleasepool(const autoreleasepool &) = delete;
autoreleasepool &operator=(const autoreleasepool &) = delete;
autoreleasepool(autoreleasepool &&) = delete;
autoreleasepool &operator=(autoreleasepool &&) = delete;
private:
id m_pool{};
};
} // namespace objc
enum NSBackingStoreType : NSUInteger { NSBackingStoreBuffered = 2 };
enum NSWindowStyleMask : NSUInteger {
NSWindowStyleMaskTitled = 1,
NSWindowStyleMaskClosable = 2,
NSWindowStyleMaskMiniaturizable = 4,
NSWindowStyleMaskResizable = 8
};
enum NSApplicationActivationPolicy : NSInteger {
NSApplicationActivationPolicyRegular = 0
};
enum WKUserScriptInjectionTime : NSInteger {
WKUserScriptInjectionTimeAtDocumentStart = 0
};
enum NSModalResponse : NSInteger { NSModalResponseOK = 1 };
// Convenient conversion of string literals.
inline id operator"" _cls(const char *s, std::size_t) {
return (id)objc_getClass(s);
}
inline SEL operator"" _sel(const char *s, std::size_t) {
return sel_registerName(s);
}
inline id operator"" _str(const char *s, std::size_t) {
return objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, s);
}
class cocoa_wkwebview_engine {
public:
cocoa_wkwebview_engine(bool debug, void *window)
: m_debug{debug}, m_window{static_cast<id>(window)}, m_owns_window{
!window} {
auto app = get_shared_application();
// See comments related to application lifecycle in create_app_delegate().
if (!m_owns_window) {
create_window();
} else {
// Only set the app delegate if it hasn't already been set.
auto delegate = objc::msg_send<id>(app, "delegate"_sel);
if (delegate) {
create_window();
} else {
delegate = create_app_delegate();
objc_setAssociatedObject(delegate, "webview", (id)this,
OBJC_ASSOCIATION_ASSIGN);
objc::msg_send<void>(app, "setDelegate:"_sel, delegate);
// Start the main run loop so that the app delegate gets the
// NSApplicationDidFinishLaunchingNotification notification after the run
// loop has started in order to perform further initialization.
// We need to return from this constructor so this run loop is only
// temporary.
objc::msg_send<void>(app, "run"_sel);
}
}
}
virtual ~cocoa_wkwebview_engine() = default;
void *window() { return (void *)m_window; }
void terminate() { stop_run_loop(); }
void run() {
auto app = get_shared_application();
objc::msg_send<void>(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) {
objc::msg_send<void>(m_window, "setTitle:"_sel,
objc::msg_send<id>("NSString"_cls,
"stringWithUTF8String:"_sel,
title.c_str()));
}
void set_size(int width, int height, int hints) {
auto style = static_cast<NSWindowStyleMask>(
NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable);
if (hints != WEBVIEW_HINT_FIXED) {
style =
static_cast<NSWindowStyleMask>(style | NSWindowStyleMaskResizable);
}
objc::msg_send<void>(m_window, "setStyleMask:"_sel, style);
if (hints == WEBVIEW_HINT_MIN) {
objc::msg_send<void>(m_window, "setContentMinSize:"_sel,
CGSizeMake(width, height));
} else if (hints == WEBVIEW_HINT_MAX) {
objc::msg_send<void>(m_window, "setContentMaxSize:"_sel,
CGSizeMake(width, height));
} else {
objc::msg_send<void>(m_window, "setFrame:display:animate:"_sel,
CGRectMake(0, 0, width, height), YES, NO);
}
objc::msg_send<void>(m_window, "center"_sel);
}
void navigate(const std::string &url) {
objc::autoreleasepool pool;
auto nsurl = objc::msg_send<id>(
"NSURL"_cls, "URLWithString:"_sel,
objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel,
url.c_str()));
objc::msg_send<void>(
m_webview, "loadRequest:"_sel,
objc::msg_send<id>("NSURLRequest"_cls, "requestWithURL:"_sel, nsurl));
}
void set_html(const std::string &html) {
objc::autoreleasepool pool;
objc::msg_send<void>(m_webview, "loadHTMLString:baseURL:"_sel,
objc::msg_send<id>("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]]
objc::msg_send<void>(
m_manager, "addUserScript:"_sel,
objc::msg_send<id>(objc::msg_send<id>("WKUserScript"_cls, "alloc"_sel),
"initWithSource:injectionTime:forMainFrameOnly:"_sel,
objc::msg_send<id>("NSString"_cls,
"stringWithUTF8String:"_sel,
js.c_str()),
WKUserScriptInjectionTimeAtDocumentStart, YES));
}
void eval(const std::string &js) {
objc::msg_send<void>(m_webview, "evaluateJavaScript:completionHandler:"_sel,
objc::msg_send<id>("NSString"_cls,
"stringWithUTF8String:"_sel,
js.c_str()),
nullptr);
}
private:
virtual void on_message(const std::string &msg) = 0;
id create_app_delegate() {
constexpr auto class_name = "WebviewAppDelegate";
// Avoid crash due to registering same class twice
auto cls = objc_lookUpClass(class_name);
if (!cls) {
// Note: Avoid registering the class name "AppDelegate" as it is the
// default name in projects created with Xcode, and using the same name
// causes objc_registerClassPair to crash.
cls = objc_allocateClassPair((Class) "NSResponder"_cls, class_name, 0);
class_addProtocol(cls, objc_getProtocol("NSTouchBarProvider"));
class_addMethod(cls,
"applicationShouldTerminateAfterLastWindowClosed:"_sel,
(IMP)(+[](id, SEL, id) -> BOOL { return YES; }), "c@:@");
class_addMethod(cls, "applicationShouldTerminate:"_sel,
(IMP)(+[](id self, SEL, id sender) -> int {
auto w = get_associated_webview(self);
return w->on_application_should_terminate(self, sender);
}),
"i@:@");
// If the library was not initialized with an existing window then the user
// is likely managing the application lifecycle and we would not get the
// "applicationDidFinishLaunching:" message and therefore do not need to
// add this method.
if (m_owns_window) {
class_addMethod(cls, "applicationDidFinishLaunching:"_sel,
(IMP)(+[](id self, SEL, id notification) {
auto app =
objc::msg_send<id>(notification, "object"_sel);
auto w = get_associated_webview(self);
w->on_application_did_finish_launching(self, app);
}),
"v@:@");
}
objc_registerClassPair(cls);
}
return objc::msg_send<id>((id)cls, "new"_sel);
}
id create_script_message_handler() {
constexpr auto class_name = "WebviewWKScriptMessageHandler";
// Avoid crash due to registering same class twice
auto cls = objc_lookUpClass(class_name);
if (!cls) {
cls = objc_allocateClassPair((Class) "NSResponder"_cls, class_name, 0);
class_addProtocol(cls, objc_getProtocol("WKScriptMessageHandler"));
class_addMethod(
cls, "userContentController:didReceiveScriptMessage:"_sel,
(IMP)(+[](id self, SEL, id, id msg) {
auto w = get_associated_webview(self);
w->on_message(objc::msg_send<const char *>(
objc::msg_send<id>(msg, "body"_sel), "UTF8String"_sel));
}),
"v@:@@");
objc_registerClassPair(cls);
}
auto instance = objc::msg_send<id>((id)cls, "new"_sel);
objc_setAssociatedObject(instance, "webview", (id)this,
OBJC_ASSOCIATION_ASSIGN);
return instance;