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
|
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qdarwinwebview_p.h"
#include <private/qwebview_p.h>
#include <private/qwebviewloadrequest_p.h>
#include "qtwebviewfunctions.h"
#include <QtCore/private/qglobal_p.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qmap.h>
#include <QtCore/qvariant.h>
#include <QtQuick/qquickrendercontrol.h>
#include <QtQuick/qquickwindow.h>
#include <CoreFoundation/CoreFoundation.h>
#include <WebKit/WebKit.h>
#include <QtCore/qjsondocument.h>
#include <QtCore/qfile.h>
#ifdef Q_OS_IOS
#import <UIKit/UIKit.h>
#endif
#ifdef Q_OS_MACOS
#include <AppKit/AppKit.h>
typedef NSView UIView;
#endif
@interface QtWKWebViewDelegate : NSObject<WKNavigationDelegate> {
QDarwinWebViewPrivate *qDarwinWebViewPrivate;
}
- (QtWKWebViewDelegate *)initWithQAbstractWebView:(QDarwinWebViewPrivate *)webViewPrivate;
- (void)pageDone;
- (void)handleError:(NSError *)error;
// protocol:
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
withError:(NSError *)error;
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation
withError:(NSError *)error;
@end
@implementation QtWKWebViewDelegate
- (QtWKWebViewDelegate *)initWithQAbstractWebView:(QDarwinWebViewPrivate *)webViewPrivate
{
if ((self = [super init])) {
Q_ASSERT(webViewPrivate);
qDarwinWebViewPrivate = webViewPrivate;
}
return self;
}
- (void)pageDone
{
Q_EMIT qDarwinWebViewPrivate->loadProgressChanged(qDarwinWebViewPrivate->loadProgress());
}
- (void)handleError:(NSError *)error
{
[self pageDone];
NSString *errorString = [error localizedDescription];
NSURL *failingURL = error.userInfo[@"NSErrorFailingURLKey"];
const QUrl url = [failingURL isKindOfClass:[NSURL class]]
? QUrl::fromNSURL(failingURL) : qDarwinWebViewPrivate->url();
Q_EMIT qDarwinWebViewPrivate->loadingChanged(
QWebViewLoadRequestPrivate(url, QWebView::LoadFailedStatus,
QString::fromNSString(errorString)));
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
Q_UNUSED(webView);
// WKNavigationDelegate gives us per-frame notifications while the QWebView API
// should provide per-page notifications. Therefore we keep track of the last frame
// to be started, if that finishes or fails then we indicate that it has loaded.
if (qDarwinWebViewPrivate->wkNavigation != navigation)
qDarwinWebViewPrivate->wkNavigation = navigation;
else
return;
Q_EMIT qDarwinWebViewPrivate->loadingChanged(
QWebViewLoadRequestPrivate(qDarwinWebViewPrivate->url(),
QWebView::LoadStartedStatus,
QString()));
Q_EMIT qDarwinWebViewPrivate->loadProgressChanged(qDarwinWebViewPrivate->loadProgress());
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
Q_UNUSED(webView);
if (qDarwinWebViewPrivate->wkNavigation != navigation)
return;
[self pageDone];
Q_EMIT qDarwinWebViewPrivate->loadingChanged(
QWebViewLoadRequestPrivate(qDarwinWebViewPrivate->url(),
QWebView::LoadSucceededStatus,
QString()));
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
withError:(NSError *)error
{
Q_UNUSED(webView);
if (qDarwinWebViewPrivate->wkNavigation != navigation)
return;
[self handleError:error];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation
withError:(NSError *)error
{
Q_UNUSED(webView);
if (qDarwinWebViewPrivate->wkNavigation != navigation)
return;
[self handleError:error];
}
- (void)webView:(WKWebView *)webView
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
__attribute__((availability(ios_app_extension,unavailable)))
{
Q_UNUSED(webView);
NSURL *url = navigationAction.request.URL;
const BOOL handled = (^{
// For links with target="_blank", open externally
if (!navigationAction.targetFrame)
return NO;
#if QT_MACOS_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(101300, 110000)
if (__builtin_available(macOS 10.13, iOS 11.0, *)) {
return [WKWebView handlesURLScheme:url.scheme];
} else
#endif
{
// +[WKWebView handlesURLScheme:] is a stub that calls
// WebCore::SchemeRegistry::isBuiltinScheme();
// replicate that as closely as possible
return [@[
@"about", @"applewebdata", @"blob", @"data",
@"file", @"http", @"https", @"javascript",
#ifdef Q_OS_MACOS
@"safari-extension",
#endif
@"webkit-fake-url", @"wss", @"x-apple-content-filter",
#ifdef Q_OS_MACOS
@"x-apple-ql-id"
#endif
] containsObject:url.scheme];
}
})();
if (!handled) {
#ifdef Q_OS_MACOS
[[NSWorkspace sharedWorkspace] openURL:url];
#elif defined(Q_OS_IOS)
// Check if it can be opened first, if it is a file scheme then it can't
// be opened, therefore if it is a _blank target in that case we need to open
// inside the current webview
if ([[UIApplication sharedApplication] canOpenURL:url])
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
else if (!navigationAction.targetFrame)
[webView loadRequest:navigationAction.request];
#endif
}
decisionHandler(handled ? WKNavigationActionPolicyAllow : WKNavigationActionPolicyCancel);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change
context:(void *)context {
Q_UNUSED(object);
Q_UNUSED(change);
Q_UNUSED(context);
if ([keyPath isEqualToString:@"estimatedProgress"]) {
Q_EMIT qDarwinWebViewPrivate->loadProgressChanged(qDarwinWebViewPrivate->loadProgress());
} else if ([keyPath isEqualToString:@"title"]) {
Q_EMIT qDarwinWebViewPrivate->titleChanged(qDarwinWebViewPrivate->title());
}
}
@end
QT_BEGIN_NAMESPACE
QDarwinWebViewSettingsPrivate::QDarwinWebViewSettingsPrivate(WKWebViewConfiguration *conf, QObject *p)
: QAbstractWebViewSettings(p)
, m_conf(conf)
{
}
bool QDarwinWebViewSettingsPrivate::localStorageEnabled() const
{
return m_conf.websiteDataStore.persistent;
}
bool QDarwinWebViewSettingsPrivate::javaScriptEnabled() const
{
// Deprecated
bool isJsEnabled = false;
#if QT_MACOS_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(110000, 140000)
if (__builtin_available(macOS 11.0, iOS 14.0, *))
isJsEnabled = m_conf.defaultWebpagePreferences.allowsContentJavaScript;
#else
isJsEnabled = m_conf.preferences.javaScriptEnabled;
#endif
return isJsEnabled;
}
bool QDarwinWebViewSettingsPrivate::localContentCanAccessFileUrls() const
{
return m_localContentCanAccessFileUrls;
}
bool QDarwinWebViewSettingsPrivate::allowFileAccess() const
{
return m_allowFileAccess;
}
void QDarwinWebViewSettingsPrivate::setLocalContentCanAccessFileUrls(bool enabled)
{
// This will be checked in QDarwinWebViewPrivate::setUrl()
m_localContentCanAccessFileUrls = enabled;
}
void QDarwinWebViewSettingsPrivate::setJavaScriptEnabled(bool enabled)
{
#if QT_MACOS_IOS_PLATFORM_SDK_EQUAL_OR_ABOVE(110000, 140000)
if (__builtin_available(macOS 11.0, iOS 14.0, *))
m_conf.defaultWebpagePreferences.allowsContentJavaScript = enabled;
#else
m_conf.preferences.javaScriptEnabled = enabled;
#endif
}
void QDarwinWebViewSettingsPrivate::setLocalStorageEnabled(bool enabled)
{
if (enabled == localStorageEnabled())
return;
if (enabled)
m_conf.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
else
m_conf.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
}
void QDarwinWebViewSettingsPrivate::setAllowFileAccess(bool enabled)
{
// This will be checked in QDarwinWebViewPrivate::setUrl()
m_allowFileAccess = enabled;
}
QDarwinWebViewPrivate::QDarwinWebViewPrivate(QObject *p)
: QAbstractWebView(p)
, wkWebView(nil)
{
CGRect frame = CGRectMake(0.0, 0.0, 400, 400);
wkWebView = [[WKWebView alloc] initWithFrame:frame];
wkWebView.navigationDelegate = [[QtWKWebViewDelegate alloc] initWithQAbstractWebView:this];
[wkWebView addObserver:wkWebView.navigationDelegate forKeyPath:@"estimatedProgress"
options:NSKeyValueObservingOptions(NSKeyValueObservingOptionNew)
context:nil];
[wkWebView addObserver:wkWebView.navigationDelegate forKeyPath:@"title"
options:NSKeyValueObservingOptions(NSKeyValueObservingOptionNew)
context:nil];
m_window = QWindow::fromWinId(reinterpret_cast<WId>(wkWebView));
m_settings = new QDarwinWebViewSettingsPrivate(wkWebView.configuration, this);
}
QDarwinWebViewPrivate::~QDarwinWebViewPrivate()
{
[wkWebView stopLoading];
[wkWebView removeObserver:wkWebView.navigationDelegate forKeyPath:@"estimatedProgress"
context:nil];
[wkWebView removeObserver:wkWebView.navigationDelegate forKeyPath:@"title"
context:nil];
[wkWebView.navigationDelegate release];
wkWebView.navigationDelegate = nil;
[wkWebView release];
}
QUrl QDarwinWebViewPrivate::url() const
{
return QUrl::fromNSURL(wkWebView.URL);
}
void QDarwinWebViewPrivate::setUrl(const QUrl &url)
{
if (url.isValid()) {
if (url.isLocalFile()) {
// NOTE: Check if the file exists before attempting to load it, we follow the same
// asynchronous pattern as expected to not break the tests (Started + Failed).
if (!QFile::exists(url.toLocalFile())) {
QMetaObject::invokeMethod(this, &QDarwinWebViewPrivate::loadingChanged, Qt::QueuedConnection, QWebViewLoadRequestPrivate(url, QWebView::LoadStartedStatus, {}));
QMetaObject::invokeMethod(this, &QDarwinWebViewPrivate::loadingChanged, Qt::QueuedConnection, QWebViewLoadRequestPrivate(url, QWebView::LoadFailedStatus, QStringLiteral("File does not exist")));
return;
}
// We need to pass local files via loadFileURL and the read access should cover
// the directory that the file is in, to facilitate loading referenced images etc
if (m_settings->allowFileAccess()) {
if (m_settings->localContentCanAccessFileUrls())
[wkWebView loadFileURL:url.toNSURL() allowingReadAccessToURL:QUrl(url.toString(QUrl::RemoveFilename)).toNSURL()];
else
[wkWebView loadRequest:[NSURLRequest requestWithURL:url.toNSURL()]];
}
} else {
[wkWebView loadRequest:[NSURLRequest requestWithURL:url.toNSURL()]];
}
} else {
QMetaObject::invokeMethod(this, &QDarwinWebViewPrivate::loadingChanged, Qt::QueuedConnection, QWebViewLoadRequestPrivate(url, QWebView::LoadFailedStatus, QStringLiteral("Invalid URL")));
}
}
void QDarwinWebViewPrivate::loadHtml(const QString &html, const QUrl &baseUrl)
{
[wkWebView loadHTMLString:html.toNSString() baseURL:baseUrl.toNSURL()];
}
bool QDarwinWebViewPrivate::canGoBack() const
{
return wkWebView.canGoBack;
}
bool QDarwinWebViewPrivate::canGoForward() const
{
return wkWebView.canGoForward;
}
QString QDarwinWebViewPrivate::title() const
{
return QString::fromNSString(wkWebView.title);
}
int QDarwinWebViewPrivate::loadProgress() const
{
return int(wkWebView.estimatedProgress * 100);
}
bool QDarwinWebViewPrivate::isLoading() const
{
return wkWebView.loading;
}
void QDarwinWebViewPrivate::goBack()
{
[wkWebView goBack];
}
void QDarwinWebViewPrivate::goForward()
{
[wkWebView goForward];
}
void QDarwinWebViewPrivate::stop()
{
[wkWebView stopLoading];
}
void QDarwinWebViewPrivate::reload()
{
[wkWebView reload];
}
QVariant fromNSNumber(const NSNumber *number)
{
if (!number)
return QVariant();
if (strcmp([number objCType], @encode(BOOL)) == 0) {
return QVariant::fromValue(!![number boolValue]);
} else if (strcmp([number objCType], @encode(signed char)) == 0) {
return QVariant::fromValue([number charValue]);
} else if (strcmp([number objCType], @encode(unsigned char)) == 0) {
return QVariant::fromValue([number unsignedCharValue]);
} else if (strcmp([number objCType], @encode(signed short)) == 0) {
return QVariant::fromValue([number shortValue]);
} else if (strcmp([number objCType], @encode(unsigned short)) == 0) {
return QVariant::fromValue([number unsignedShortValue]);
} else if (strcmp([number objCType], @encode(signed int)) == 0) {
return QVariant::fromValue([number intValue]);
} else if (strcmp([number objCType], @encode(unsigned int)) == 0) {
return QVariant::fromValue([number unsignedIntValue]);
} else if (strcmp([number objCType], @encode(signed long long)) == 0) {
return QVariant::fromValue([number longLongValue]);
} else if (strcmp([number objCType], @encode(unsigned long long)) == 0) {
return QVariant::fromValue([number unsignedLongLongValue]);
} else if (strcmp([number objCType], @encode(float)) == 0) {
return QVariant::fromValue([number floatValue]);
} else if (strcmp([number objCType], @encode(double)) == 0) {
return QVariant::fromValue([number doubleValue]);
}
return QVariant();
}
QVariant fromJSValue(id result)
{
if ([result isKindOfClass:[NSString class]])
return QString::fromNSString(static_cast<NSString *>(result));
if ([result isKindOfClass:[NSNumber class]])
return fromNSNumber(static_cast<NSNumber *>(result));
if ([result isKindOfClass:[NSDate class]])
return QDateTime::fromNSDate(static_cast<NSDate *>(result));
if ([result isKindOfClass:[NSArray class]]
|| [result isKindOfClass:[NSDictionary class]]) {
@try {
// Round-trip via JSON, so we don't have to implement conversion
// from NSArray and NSDictionary manually.
// FIXME: NSJSONSerialization requires that any nested object
// is NSString, NSNumber, NSArray, NSDictionary, or NSNull, so
// nested NSDates are not supported -- meaning we support plain
// NSDate (above), but not in an array or dict. To handle this
// use-case we'd need a manual conversion.
auto jsonData = QByteArray::fromNSData(
[NSJSONSerialization dataWithJSONObject:result options:0 error:nil]);
QJsonParseError parseError;
auto jsonDocument = QJsonDocument::fromJson(jsonData, &parseError);
if (parseError.error == QJsonParseError::NoError)
return jsonDocument.toVariant();
} @catch (NSException *) {
return QVariant();
}
}
return QVariant();
}
void QDarwinWebViewPrivate::runJavaScriptPrivate(const QString &script, int callbackId)
{
[wkWebView evaluateJavaScript:script.toNSString() completionHandler:^(id result, NSError *) {
if (callbackId != -1)
Q_EMIT javaScriptResult(callbackId, fromJSValue(result));
}];
}
void QDarwinWebViewPrivate::setCookie(const QString &domain, const QString &name, const QString &value)
{
NSString *cookieDomain = domain.toNSString();
NSString *cookieName = name.toNSString();
NSString *cookieValue = value.toNSString();
WKHTTPCookieStore *cookieStore = wkWebView.configuration.websiteDataStore.httpCookieStore;
if (cookieStore == nullptr) {
return;
}
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:cookieName forKey:NSHTTPCookieName];
[cookieProperties setObject:cookieValue forKey:NSHTTPCookieValue];
[cookieProperties setObject:cookieDomain forKey:NSHTTPCookieDomain];
[cookieProperties setObject:cookieDomain forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
if (cookie == nullptr) {
return;
}
[cookieStore setCookie:cookie completionHandler:^{
Q_EMIT cookieAdded(QString::fromNSString(cookie.domain), QString::fromNSString(cookie.name));
}];
}
void QDarwinWebViewPrivate::deleteCookie(const QString &domain, const QString &name)
{
NSString *cookieDomain = domain.toNSString();
NSString *cookieName = name.toNSString();
WKHTTPCookieStore *cookieStore = wkWebView.configuration.websiteDataStore.httpCookieStore;
if (cookieStore == nullptr) {
return;
}
[cookieStore getAllCookies:^(NSArray *cookies) {
NSHTTPCookie *cookie;
for (cookie in cookies) {
if ([cookie.domain isEqualToString:cookieDomain] && [cookie.name isEqualToString:cookieName]) {
[cookieStore deleteCookie:cookie completionHandler:^{
Q_EMIT cookieRemoved(QString::fromNSString(cookie.domain), QString::fromNSString(cookie.name));
}];
}
}
}];
}
void QDarwinWebViewPrivate::deleteAllCookies()
{
WKHTTPCookieStore *cookieStore = wkWebView.configuration.websiteDataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray *cookies) {
NSHTTPCookie *cookie;
for (cookie in cookies) {
[cookieStore deleteCookie:cookie completionHandler:^{
Q_EMIT cookieRemoved(QString::fromNSString(cookie.domain), QString::fromNSString(cookie.name));
}];
}
}];
}
QString QDarwinWebViewPrivate::httpUserAgent() const
{
return QString::fromNSString(wkWebView.customUserAgent);
}
void QDarwinWebViewPrivate::setHttpUserAgent(const QString &userAgent)
{
if (!userAgent.isEmpty()) {
wkWebView.customUserAgent = userAgent.toNSString();
}
Q_EMIT httpUserAgentChanged(userAgent);
}
QAbstractWebViewSettings *QDarwinWebViewPrivate::getSettings() const
{
return m_settings;
}
QT_END_NAMESPACE
|