forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webview.d
22667 lines (20019 loc) · 846 KB
/
webview.d
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
/++
A web view wrapper. Uses CEF on Linux and WebView2 on Windows.
Microsoft WebView2 is fairly stable and is unlikely to break, but CEF
is not remotely stable and likely to break every release. You'll have
to get the same version as me to use this unless you want to generate
your own bindings (procedure found in the file comments). Details below.
I currently built against 95.7.17+g4208276+chromium-95.0.4638.69 and it
uses UTF-16 strings.
Then to install the cef put in the Resources in the RElease directory and
copy the locales to /opt/cef/Resources/Locales
You can download compatible builds from https://cef-builds.spotifycdn.com/index.html
just make sure to put in the version filter and check "all builds" to match it.
You do NOT actually need the cef to build the application, but it must be
on the user's machine to run it. It looks in /opt/cef/ on Linux.
Work in progress. DO NOT USE YET as I am prolly gonna break everything too.
On Windows, you need to distribute the WebView2Loader.dll with your exe. That
is found in the web view 2 sdk. Furthermore, users will have to install the runtime.
Please note; the Microsoft terms and conditions say they may be able to collect
information about your users if you use this on Windows.
see: https://developer.microsoft.com/en-us/microsoft-edge/webview2/
+/
module arsd.webview;
enum WebviewEngine {
none,
cef,
wv2,
webkit_gtk
}
// see activeEngine which is an enum you can static if on
// I might recover this gtk thing but i don't like gtk
// dmdi webview -version=linux_gtk -version=Demo
// the setup link for Microsoft:
// https://go.microsoft.com/fwlink/p/?LinkId=2124703
version(Windows) {
import arsd.simpledisplay;
import arsd.com;
import core.atomic;
//import std.stdio;
T callback(T)(typeof(&T.init.Invoke) dg) {
return new class T {
extern(Windows):
static if(is(typeof(T.init.Invoke) R == return))
static if(is(typeof(T.init.Invoke) P == __parameters))
override R Invoke(P _args_) {
return dg(_args_);
}
override HRESULT QueryInterface(const (IID)*riid, LPVOID *ppv) {
if (IID_IUnknown == *riid) {
*ppv = cast(void*) cast(IUnknown) this;
}
else if (T.iid == *riid) {
*ppv = cast(void*) cast(T) this;
}
else {
*ppv = null;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
shared LONG count = 0;
ULONG AddRef() {
return atomicOp!"+="(count, 1);
}
ULONG Release() {
return atomicOp!"-="(count, 1);
}
};
}
enum activeEngine = WebviewEngine.wv2;
struct RC(T) {
private T object;
this(T t) {
object = t;
object.AddRef();
}
this(this) {
if(object is null) return;
object.AddRef();
}
~this() {
if(object is null) return;
object.Release();
object = null;
}
void opAssign(T obj) {
obj.AddRef();
if(object)
object.Release();
this.object = obj;
}
T raw() { return object; }
T returnable() {
if(object is null) return null;
return object;
}
T passable() {
if(object is null) return null;
object.AddRef();
return object;
}
static foreach(memberName; __traits(derivedMembers, T)) {
mixin ForwardMethod!(memberName);
}
}
extern(Windows)
alias StringMethod = int delegate(wchar**);
string toGC(scope StringMethod dg) {
wchar* t;
auto res = dg(&t);
if(res != S_OK)
throw new ComException(res);
auto ot = t;
string s;
// FIXME: encode properly in UTF-8
while(*t) {
s ~= *t;
t++;
}
auto ret = s;
CoTaskMemFree(ot);
return ret;
}
class ComException : Exception {
HRESULT errorCode;
this(HRESULT errorCode) {
import std.format;
super(format("HRESULT: 0x%08x", errorCode));
// FIXME: call FormatMessage
}
}
mixin template ForwardMethod(string methodName) {
static if(methodName.length > 4 && methodName[0 .. 4] == "put_") {
static if(is(typeof(__traits(getMember, T, memberName)) Params == function))
private alias Type = Params[0];
mixin(q{ @property void } ~ memberName[4 .. $] ~ q{(Type v) {
auto errorCode = __traits(getMember, object, memberName)(v);
if(errorCode)
throw new ComException(errorCode);
}
});
} else
static if(methodName.length > 4 && methodName[0 .. 4] == "get_") {
static if(is(typeof(__traits(getMember, T, memberName)) Params == function))
private alias Type = typeof(*(Params[0].init));
mixin(q{ @property Type } ~ memberName[4 .. $] ~ q{() {
Type response;
auto errorCode = __traits(getMember, object, memberName)(&response);
if(errorCode)
throw new ComException(errorCode);
return response;
}
});
} else
static if(methodName.length > 4 && methodName[0 .. 4] == "add_") {
static if(is(typeof(__traits(getMember, T, memberName)) Params == function))
alias Handler = Params[0];
alias HandlerDg = typeof(&Handler.init.Invoke);
mixin(q{ EventRegistrationToken } ~ memberName ~ q{ (HandlerDg handler) {
EventRegistrationToken token;
__traits(getMember, object, memberName)(callback!Handler(handler), &token);
return token;
}});
} else
static if(methodName.length > 7 && methodName[0 .. 4] == "remove_") {
mixin(q{ void } ~ memberName ~ q{ (EventRegistrationToken token) {
__traits(getMember, object, memberName)(token);
}});
} else {
// I could do the return value things by looking for these comments:
// /+[out]+/ but be warned it is possible or a thing to have multiple out params (only one such function in here though i think)
// /+[out, retval]+/
// a find/replace could make them a UDA or something.
static if(is(typeof(__traits(getMember, T, memberName)) Params == function))
static if(is(typeof(__traits(getMember, T, memberName)) Return == return))
mixin(q{ Return } ~ memberName ~ q{ (Params p) {
// FIXME: check the return value and throw
return __traits(getMember, object, memberName)(p);
}
});
}
}
struct Wv2App {
static bool active = false;
static HRESULT code;
static bool initialized = false;
static RC!ICoreWebView2Environment webview_env;
@disable this(this);
static void delegate(RC!ICoreWebView2Environment)[] pending;
this(void delegate(RC!ICoreWebView2Environment) withEnvironment) {
if(withEnvironment)
pending ~= withEnvironment;
import core.sys.windows.com;
CoInitializeEx(null, COINIT_APARTMENTTHREADED);
active = true;
auto lib = LoadLibraryW("WebView2Loader.dll"w.ptr);
typeof(&CreateCoreWebView2EnvironmentWithOptions) func;
if(lib is null)
throw new Exception("WebView2Loader.dll unable to load. The developer should bundle this with the application exe. It is found with the WebView2 SDK from nuget.");
func = cast(typeof(func)) GetProcAddress(lib, CreateCoreWebView2EnvironmentWithOptions.mangleof);
if(func is null)
throw new Exception("CreateCoreWebView2EnvironmentWithOptions failed from WebView2Loader...");
auto result = func(null, null, null,
callback!(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler)(
delegate(error, env) {
initialized = true;
code = error;
if(error)
return error;
webview_env = env;
auto len = pending.length;
foreach(item; pending) {
item(webview_env);
}
pending = pending[len .. $];
return S_OK;
}
)
);
if(result != S_OK) {
if(MessageBox(null, "The WebView2 runtime is not installed. Would you like to install it now? This will open a browser to download a file. After it installs, you can try running this program again.", "Missing file", MB_YESNO) == IDYES) {
import std.process;
browse("https://go.microsoft.com/fwlink/p/?LinkId=2124703");
}
throw new ComException(result);
}
}
@disable this();
~this() {
active = false;
}
static void useEnvironment(void delegate(RC!ICoreWebView2Environment) withEnvironment) {
assert(active);
assert(withEnvironment !is null);
if(initialized) {
if(code)
throw new ComException(code);
withEnvironment(webview_env);
} else
pending ~= withEnvironment;
}
}
}
/+
interface WebView {
void refresh();
void back();
void forward();
void stop();
void navigate(string url);
// the url and line are for error reporting purposes
void executeJavascript(string code, string url = null, int line = 0);
void showDevTools();
// these are get/set properties that you can subscribe to with some system
mixin Observable!(string, "title");
mixin Observable!(string, "url");
mixin Observable!(string, "status");
mixin Observable!(int, "loadingProgress");
}
+/
version(linux) {
version(linux_gtk) {} else
version=cef;
}
version(cef) {
import arsd.simpledisplay;
//pragma(lib, "cef");
class BrowserProcessHandler : CEF!cef_browser_process_handler_t {
override void on_context_initialized() { }
override void on_before_child_process_launch(RC!cef_command_line_t) { }
override void on_schedule_message_pump_work(long delayMs) { }
override cef_client_t* get_default_client() { return null; }
}
int cefProcessHelper() {
import core.runtime;
import core.stdc.stdlib;
cef_main_args_t main_args;
version(linux) {
main_args.argc = Runtime.cArgs.argc;
main_args.argv = Runtime.cArgs.argv;
} else version(Windows) {
main_args.instance = GetModuleHandle(null);
}
if(libcef.loadDynamicLibrary()) {
int code = libcef.execute_process(&main_args, null, null);
if(code >= 0)
exit(code);
return code;
}
return -1;
}
shared static this() {
cefProcessHelper();
}
public struct CefApp {
static bool active() {
return count > 0;
}
private __gshared int count = 0;
@disable this(this);
@disable new();
this(void delegate(cef_settings_t* settings) setSettings) {
if(!libcef.loadDynamicLibrary())
throw new Exception("failed to load cef dll");
count++;
import core.runtime;
import core.stdc.stdlib;
cef_main_args_t main_args;
version(linux) {
main_args.argc = Runtime.cArgs.argc;
main_args.argv = Runtime.cArgs.argv;
} else version(Windows) {
main_args.instance = GetModuleHandle(null);
}
cef_settings_t settings;
settings.size = cef_settings_t.sizeof;
//settings.log_severity = cef_log_severity_t.LOGSEVERITY_DISABLE; // Show only warnings/errors
settings.log_severity = cef_log_severity_t.LOGSEVERITY_INFO; // Show only warnings/errors
settings.multi_threaded_message_loop = 1;
settings.no_sandbox = 1;
version(linux)
settings.locales_dir_path = cef_string_t("/opt/cef/Resources/locales");
if(setSettings !is null)
setSettings(&settings);
auto app = new class CEF!cef_app_t {
BrowserProcessHandler bph;
this() {
bph = new BrowserProcessHandler();
}
override void on_before_command_line_processing(const(cef_string_t)*, RC!cef_command_line_t) {}
override cef_resource_bundle_handler_t* get_resource_bundle_handler() {
return null;
}
override cef_browser_process_handler_t* get_browser_process_handler() {
return bph.returnable;
}
override cef_render_process_handler_t* get_render_process_handler() {
return null;
}
override void on_register_custom_schemes(cef_scheme_registrar_t*) {
}
};
if(!libcef.initialize(&main_args, &settings, app.passable, null)) {
throw new Exception("cef_initialize failed");
}
}
~this() {
count--;
// this call hangs and idk why.
// FIXME
//libcef.shutdown();
}
}
version(Demo)
void main() {
auto app = CefApp(null);
auto window = new SimpleWindow(640, 480, "D Browser", Resizability.allowResizing);
flushGui;
cef_window_info_t window_info;
/*
window_info.x = 100;
window_info.y = 100;
window_info.width = 300;
window_info.height = 300;
*/
//window_info.parent_window = window.nativeWindowHandle;
cef_string_t cef_url = cef_string_t("http://dpldocs.info/");//"http://youtube.com/"w);
//string url = "http://arsdnet.net/";
//cef_string_utf8_to_utf16(url.ptr, url.length, &cef_url);
cef_browser_settings_t browser_settings;
browser_settings.size = cef_browser_settings_t.sizeof;
auto client = new MyCefClient();
auto got = libcef.browser_host_create_browser(&window_info, client.passable, &cef_url, &browser_settings, null, null); // or _sync
window.eventLoop(0);
}
/++
This gives access to the CEF functions. If you get a linker error for using an undefined function,
it is probably because you did NOT go through this when dynamically loading.
(...similarly, if you get a segfault, it is probably because you DID go through this when static binding.)
+/
struct libcef {
static __gshared:
bool isLoaded;
bool loadAttempted;
void* libHandle;
/// Make sure you call this only from one thread, probably at process startup. It caches internally and returns true if the load was successful.
bool loadDynamicLibrary() {
if(loadAttempted)
return isLoaded;
loadAttempted = true;
version(linux) {
import core.sys.posix.dlfcn;
libHandle = dlopen("libcef.so", RTLD_NOW);
static void* loadsym(const char* name) {
return dlsym(libHandle, name);
}
} else version(Windows) {
import core.sys.windows.windows;
libHandle = LoadLibrary("libcef.dll");
static void* loadsym(const char* name) {
return GetProcAddress(libHandle, name);
}
}
//import std.stdio;
if(libHandle is null) {
//writeln("libhandlenull");
return false;
}
foreach(memberName; __traits(allMembers, libcef)[4 .. $]) { // cutting off everything until the actual static foreach below; this trims off isLoaded to loadDynamicLibrary
alias mem = __traits(getMember, libcef, memberName);
mem = cast(typeof(mem)) loadsym("cef_" ~ memberName);
if(mem is null) {
// writeln(memberName);
// throw new Exception("cef_" ~ memberName ~ " failed to load");
return false;
}
}
import core.stdc.string;
if(strcmp(libcef.api_hash(1), CEF_API_HASH_UNIVERSAL) != 0)
throw new Exception("libcef versions not matching bindings");
isLoaded = true;
return true;
}
static foreach(memberName; __traits(allMembers, arsd.webview))
static if(is(typeof(__traits(getMember, arsd.webview, memberName)) == function))
static if(memberName.length > 4 && memberName[0 .. 4] == "cef_") {
mixin(q{ typeof(&__traits(getMember, arsd.webview, memberName)) } ~ memberName[4 .. $] ~ ";"); // = &" ~ memberName ~ ";");
}
}
}
version(linux_gtk)
version(Demo)
void main() {
auto wv = new WebView(true, null);
wv.navigate("http://dpldocs.info/");
wv.setTitle("omg a D webview");
wv.setSize(500, 500, true);
wv.eval("console.log('just testing');");
wv.run();
}
version(linux_gtk)
enum activeEngine = WebviewEngine.webkit_gtk;
/++
+/
version(linux_gtk)
class WebView : browser_engine {
/++
Creates a new webview instance. If dbg 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.
+/
this(bool dbg, void* window) {
super(&on_message, dbg, window);
}
extern(C)
static void on_message(const char*) {}
/// Destroys a webview and closes the native window.
void destroy() {
}
/// Runs the main loop until it's terminated. After this function exits - you
/// must destroy the webview.
override void run() { super.run(); }
/// Stops the main loop. It is safe to call this function from another other
/// background thread.
override void terminate() { super.terminate(); }
/+
/// 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.
void dispatch(void function(WebView w, void *arg) fn, 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.
void* getWindow() { return m_window; }
/// Updates the title of the native window. Must be called from the UI thread.
override void setTitle(const char *title) { super.setTitle(title); }
/// Navigates webview to the given URL. URL may be a data URI.
override void navigate(const char *url) { super.navigate(url); }
/// 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.
override void init(const char *js) { super.init(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.
override void eval(const char *js) { super.eval(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.
void bind(const char *name, void function(const char *, void *) fn, void *arg) {}
/// 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.
void webview_return(const char *req, int status, const char *result) {}
/*
void on_message(const char *msg) {
auto seq = json_parse(msg, "seq", 0);
auto name = json_parse(msg, "name", 0);
auto args = json_parse(msg, "args", 0);
auto fn = bindings[name];
if (fn == null) {
return;
}
std::async(std::launch::async, [=]() {
auto result = (*fn)(args);
dispatch([=]() {
eval(("var b = window['" + name + "'];b['callbacks'][" + seq + "](" +
result + ");b['callbacks'][" + seq +
"] = undefined;b['errors'][" + seq + "] = undefined;")
.c_str());
});
});
}
std::map<std::string, binding_t *> bindings;
alias binding_t = std::function<std::string(std::string)>;
void bind(const char *name, binding_t f) {
auto js = "(function() { var name = '" + std::string(name) + "';" + R"(
window[name] = function() {
var me = window[name];
var errors = me['errors'];
var callbacks = me['callbacks'];
if (!callbacks) {
callbacks = {};
me['callbacks'] = callbacks;
}
if (!errors) {
errors = {};
me['errors'] = errors;
}
var seq = (me['lastSeq'] || 0) + 1;
me['lastSeq'] = seq;
var promise = new Promise(function(resolve, reject) {
callbacks[seq] = resolve;
errors[seq] = reject;
});
window.external.invoke(JSON.stringify({
name: name,
seq:seq,
args: Array.prototype.slice.call(arguments),
}));
return promise;
}
})())";
init(js.c_str());
bindings[name] = new binding_t(f);
}
*/
}
private extern(C) {
alias dispatch_fn_t = void function();
alias msg_cb_t = void function(const char *msg);
}
version(linux_gtk) {
/* Original https://github.com/zserge/webview notice below:
* 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.
*/
/*
Port to D by Adam D. Ruppe, November 30, 2019
*/
pragma(lib, "gtk-3");
pragma(lib, "glib-2.0");
pragma(lib, "gobject-2.0");
pragma(lib, "webkit2gtk-4.0");
pragma(lib, "javascriptcoregtk-4.0");
private extern(C) {
import core.stdc.config;
alias GtkWidget = void;
enum GtkWindowType {
GTK_WINDOW_TOPLEVEL = 0
}
bool gtk_init_check(int*, char***);
GtkWidget* gtk_window_new(GtkWindowType);
c_ulong g_signal_connect_data(void*, const char*, void* /* function pointer!!! */, void*, void*, int);
GtkWidget* webkit_web_view_new();
alias WebKitUserContentManager = void;
WebKitUserContentManager* webkit_web_view_get_user_content_manager(GtkWidget*);
void gtk_container_add(GtkWidget*, GtkWidget*);
void gtk_widget_grab_focus(GtkWidget*);
void gtk_widget_show_all(GtkWidget*);
void gtk_main();
void gtk_main_quit();
void webkit_web_view_load_uri(GtkWidget*, const char*);
alias WebKitSettings = void;
WebKitSettings* webkit_web_view_get_settings(GtkWidget*);
void webkit_settings_set_enable_write_console_messages_to_stdout(WebKitSettings*, bool);
void webkit_settings_set_enable_developer_extras(WebKitSettings*, bool);
void webkit_user_content_manager_register_script_message_handler(WebKitUserContentManager*, const char*);
alias JSCValue = void;
alias WebKitJavascriptResult = void;
JSCValue* webkit_javascript_result_get_js_value(WebKitJavascriptResult*);
char* jsc_value_to_string(JSCValue*);
void g_free(void*);
void webkit_web_view_run_javascript(GtkWidget*, const char*, void*, void*, void*);
alias WebKitUserScript = void;
void webkit_user_content_manager_add_script(WebKitUserContentManager*, WebKitUserScript*);
WebKitUserScript* webkit_user_script_new(const char*, WebKitUserContentInjectedFrames, WebKitUserScriptInjectionTime, const char*, const char*);
enum WebKitUserContentInjectedFrames {
WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
WEBKIT_USER_CONTENT_INJECT_TOP_FRAME
}
enum WebKitUserScriptInjectionTime {
WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START,
WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_END
}
void gtk_window_set_title(GtkWidget*, const char*);
void gtk_window_set_resizable(GtkWidget*, bool);
void gtk_window_set_default_size(GtkWidget*, int, int);
void gtk_widget_set_size_request(GtkWidget*, int, int);
}
private class browser_engine {
static extern(C)
void ondestroy (GtkWidget *w, void* arg) {
(cast(browser_engine) arg).terminate();
}
static extern(C)
void smr(WebKitUserContentManager* m, WebKitJavascriptResult* r, void* arg) {
auto w = cast(browser_engine) arg;
JSCValue *value = webkit_javascript_result_get_js_value(r);
auto s = jsc_value_to_string(value);
w.m_cb(s);
g_free(s);
}
this(msg_cb_t cb, bool dbg, void* window) {
m_cb = cb;
gtk_init_check(null, null);
m_window = cast(GtkWidget*) window;
if (m_window == null)
m_window = gtk_window_new(GtkWindowType.GTK_WINDOW_TOPLEVEL);
g_signal_connect_data(m_window, "destroy", &ondestroy, cast(void*) this, null, 0);
m_webview = webkit_web_view_new();
WebKitUserContentManager* manager = webkit_web_view_get_user_content_manager(m_webview);
g_signal_connect_data(manager, "script-message-received::external", &smr, cast(void*) this, null, 0);
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(m_window, m_webview);
gtk_widget_grab_focus(m_webview);
if (dbg) {
WebKitSettings *settings = webkit_web_view_get_settings(m_webview);
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);
}
void run() { gtk_main(); }
void terminate() { gtk_main_quit(); }
void navigate(const char *url) {
webkit_web_view_load_uri(m_webview, url);
}
void setTitle(const char* title) {
gtk_window_set_title(m_window, title);
}
/+
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 setSize(int width, int height, bool resizable) {
gtk_window_set_resizable(m_window, resizable);
if (resizable) {
gtk_window_set_default_size(m_window, width, height);
}
gtk_widget_set_size_request(m_window, width, height);
}
void init(const char *js) {
WebKitUserContentManager *manager = webkit_web_view_get_user_content_manager(m_webview);
webkit_user_content_manager_add_script(
manager, webkit_user_script_new(
js, WebKitUserContentInjectedFrames.WEBKIT_USER_CONTENT_INJECT_TOP_FRAME,
WebKitUserScriptInjectionTime.WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, null, null));
}
void eval(const char *js) {
webkit_web_view_run_javascript(m_webview, js, null, null, null);
}
protected:
GtkWidget* m_window;
GtkWidget* m_webview;
msg_cb_t m_cb;
}
} else version(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.
//
// ====================================================================
//
#define OBJC_OLD_DISPATCH_PROTOTYPES 1
#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
id operator"" _cls(const char *s, std::size_t sz) {
return (id)objc_getClass(s);
}
SEL operator"" _sel(const char *s, std::size_t sz) {
return sel_registerName(s);
}
id operator"" _str(const char *s, std::size_t sz) {
return objc_msgSend("NSString"_cls, "stringWithUTF8String:"_sel, s);
}
class browser_engine {
public:
browser_engine(msg_cb_t cb, bool dbg, void *window) : m_cb(cb) {
// Application
id app = objc_msgSend("NSApplication"_cls, "sharedApplication"_sel);
objc_msgSend(app, "setActivationPolicy:"_sel,
NSApplicationActivationPolicyRegular);
// Delegate
auto cls = objc_allocateClassPair((Class) "NSObject"_cls, "AppDelegate", 0);
class_addProtocol(cls, objc_getProtocol("NSApplicationDelegate"));
class_addProtocol(cls, objc_getProtocol("WKScriptMessageHandler"));
class_addMethod(
cls, "applicationShouldTerminateAfterLastWindowClosed:"_sel,
(IMP)(+[](id self, SEL cmd, id notification) -> BOOL { return 1; }),
"c@:@");
class_addMethod(
cls, "userContentController:didReceiveScriptMessage:"_sel,
(IMP)(+[](id self, SEL cmd, id notification, id msg) {
auto w = (browser_engine *)objc_getAssociatedObject(self, "webview");
w->m_cb((const char *)objc_msgSend(objc_msgSend(msg, "body"_sel),
"UTF8String"_sel));
}),
"v@:@@");
objc_registerClassPair(cls);
auto delegate = objc_msgSend((id)cls, "new"_sel);
objc_setAssociatedObject(delegate, "webview", (id)this,
OBJC_ASSOCIATION_ASSIGN);
objc_msgSend(app, sel_registerName("setDelegate:"), delegate);
// Main window
if (window is null) {
m_window = objc_msgSend("NSWindow"_cls, "alloc"_sel);
m_window = objc_msgSend(
m_window, "initWithContentRect:styleMask:backing:defer:"_sel,
CGRectMake(0, 0, 0, 0), 0, NSBackingStoreBuffered, 0);
setSize(480, 320, true);
} else {
m_window = (id)window;
}
// Webview
auto config = objc_msgSend("WKWebViewConfiguration"_cls, "new"_sel);
m_manager = objc_msgSend(config, "userContentController"_sel);
m_webview = objc_msgSend("WKWebView"_cls, "alloc"_sel);
objc_msgSend(m_webview, "initWithFrame:configuration:"_sel,
CGRectMake(0, 0, 0, 0), config);
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");
if (dbg) {
objc_msgSend(objc_msgSend(config, "preferences"_sel),
"setValue:forKey:"_sel, 1, "developerExtrasEnabled"_str);
}
objc_msgSend(m_window, "setContentView:"_sel, m_webview);
objc_msgSend(m_window, "makeKeyAndOrderFront:"_sel, null);
}
~browser_engine() { close(); }
void terminate() { close(); objc_msgSend("NSApp"_cls, "terminate:"_sel, null); }
void run() {
id app = objc_msgSend("NSApplication"_cls, "sharedApplication"_sel);
dispatch([&]() { objc_msgSend(app, "activateIgnoringOtherApps:"_sel, 1); });
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 setTitle(const char *title) {
objc_msgSend(
m_window, "setTitle:"_sel,