-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwebview.h
616 lines (540 loc) · 17.7 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
/*
* 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 width,int height,int hide,int debug);
// 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);
//show webview window
WEBVIEW_API void webview_show(webview_t w);
//hide webview window
WEBVIEW_API void webview_hide(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);
//set window icon
WEBVIEW_API void webview_set_icon(webview_t w, const void *icon,int size);
// Navigates webview to the given URL. URL may be a data URI, i.e.
// "data:text/text,<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);
// 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);
// 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(__linux__)
#define WEBVIEW_GTK
#elif defined(__APPLE__)
#define WEBVIEW_COCOA
#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()>;
// Convert ASCII hex digit to a nibble (four bits, 0 - 15).
//
// Use unsigned to avoid signed overflow UB.
static inline unsigned char hex2nibble(unsigned char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
return 10 + (c - 'A');
}
return 0;
}
// Convert ASCII hex string (two characters) to byte.
//
// E.g., "0B" => 0x0B, "af" => 0xAF.
static inline char hex2char(const char *p) {
return hex2nibble(p[0]) * 16 + hex2nibble(p[1]);
}
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 std::string url_decode(const std::string st) {
std::string decoded;
const char *s = st.c_str();
size_t length = strlen(s);
for (unsigned int i = 0; i < length; i++) {
if (s[i] == '%') {
decoded.push_back(hex2char(s + i + 1));
i = i + 2;
} else if (s[i] == '+') {
decoded.push_back(' ');
} else {
decoded.push_back(s[i]);
}
}
return decoded;
}
inline std::string html_from_uri(const std::string s) {
if (s.substr(0, 15) == "data:text/html,") {
return url_decode(s.substr(15));
}
return "";
}
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(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)
#include "webview_linux.h"
#elif defined(WEBVIEW_COCOA)
#include "webview_darwin.h"
#elif defined(WEBVIEW_EDGE)
#include "webview_win.h"
#endif /* WEBVIEW_GTK, WEBVIEW_COCOA, WEBVIEW_EDGE */
namespace webview {
class webview : public browser_engine {
public:
webview(int width,int height,bool hide = false,bool debug = false)
: browser_engine(width,height,hide,debug) {}
void navigate(const std::string url) {
if (url == "") {
browser_engine::navigate("data:text/html," +
url_encode("<html><body>Hello</body></html>"));
return;
}
std::string html = html_from_uri(url);
if (html != "") {
browser_engine::navigate("data:text/html," + url_encode(html));
} else {
browser_engine::navigate(url);
}
}
using binding_t = std::function<void(std::string, std::string, void *)>;
using binding_ctx_t = std::pair<binding_t *, void *>;
using sync_binding_t = std::function<std::string(std::string)>;
using sync_binding_ctx_t = std::pair<webview *, sync_binding_t>;
void bind(const std::string name, sync_binding_t fn) {
bind(
name,
[](std::string seq, std::string req, void *arg) {
auto pair = static_cast<sync_binding_ctx_t *>(arg);
pair->first->resolve(seq, 0, pair->second(req));
},
new sync_binding_ctx_t(this, fn));
}
void bind(const std::string name, binding_t f, void *arg) {
auto js = "(function() { var name = '" + name + "';" + R"(
var RPC = window._rpc = (window._rpc || {nextSeq: 1});
window[name] = function() {
var seq = RPC.nextSeq++;
var promise = new Promise(function(resolve, reject) {
RPC[seq] = {
resolve: resolve,
reject: reject,
};
});
window.external.invoke(JSON.stringify({
id: seq,
method: name,
params: Array.prototype.slice.call(arguments),
}));
return promise;
}
})())";
init(js);
bindings[name] = new binding_ctx_t(new binding_t(f), arg);
}
void resolve(const std::string seq, int status, const std::string result) {
dispatch([=]() {
if (status == 0) {
eval("window._rpc[" + seq + "].resolve(" + result + "); window._rpc[" +
seq + "] = undefined");
} else {
eval("window._rpc[" + seq + "].reject(" + result + "); window._rpc[" +
seq + "] = undefined");
}
});
}
private:
void on_message(const std::string msg) {
auto seq = json_parse(msg, "id", 0);
auto name = json_parse(msg, "method", 0);
auto args = json_parse(msg, "params", 0);
if (bindings.find(name) == bindings.end()) {
return;
}
auto fn = bindings[name];
(*fn->first)(seq, args, fn->second);
}
std::map<std::string, binding_ctx_t *> bindings;
};
} // namespace webview
WEBVIEW_API webview_t webview_create(int width,int height,int hide,int debug) {
return new webview::webview(width,height,hide,debug);
}
WEBVIEW_API void webview_destroy(webview_t w) {
delete static_cast<webview::webview *>(w);
}
WEBVIEW_API void webview_run(webview_t w) {
static_cast<webview::webview *>(w)->run();
}
WEBVIEW_API void webview_terminate(webview_t w) {
static_cast<webview::webview *>(w)->terminate();
}
WEBVIEW_API void webview_show(webview_t w) {
static_cast<webview::webview *>(w)->show();
}
WEBVIEW_API void webview_hide(webview_t w) {
static_cast<webview::webview *>(w)->hide();
}
WEBVIEW_API void webview_dispatch(webview_t w, void (*fn)(webview_t, void *),
void *arg) {
static_cast<webview::webview *>(w)->dispatch([=]() { fn(w, arg); });
}
WEBVIEW_API void *webview_get_window(webview_t w) {
return static_cast<webview::webview *>(w)->window();
}
WEBVIEW_API void webview_set_title(webview_t w, const char *title) {
static_cast<webview::webview *>(w)->set_title(title);
}
WEBVIEW_API void webview_set_icon(webview_t w, const void *icon,int size) {
static_cast<webview::webview *>(w)->set_icon(std::string((char*)icon,size));
}
WEBVIEW_API void webview_set_size(webview_t w, int width, int height,
int hints) {
static_cast<webview::webview *>(w)->set_size(width, height, hints);
}
WEBVIEW_API void webview_navigate(webview_t w, const char *url) {
static_cast<webview::webview *>(w)->navigate(url);
}
WEBVIEW_API void webview_init(webview_t w, const char *js) {
static_cast<webview::webview *>(w)->init(js);
}
WEBVIEW_API void webview_eval(webview_t w, const char *js) {
static_cast<webview::webview *>(w)->eval(js);
}
WEBVIEW_API void webview_bind(webview_t w, const char *name,
void (*fn)(const char *seq, const char *req,
void *arg),
void *arg) {
static_cast<webview::webview *>(w)->bind(
name,
[=](std::string seq, std::string req, void *arg) {
fn(seq.c_str(), req.c_str(), arg);
},
arg);
}
WEBVIEW_API void webview_return(webview_t w, const char *seq, int status,
const char *result) {
static_cast<webview::webview *>(w)->resolve(seq, status, result);
}
#endif /* WEBVIEW_HEADER */
#endif /* WEBVIEW_H */