-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathWebEngine.swift
More file actions
2242 lines (1989 loc) · 80.1 KB
/
WebEngine.swift
File metadata and controls
2242 lines (1989 loc) · 80.1 KB
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
// SPDX-License-Identifier: LGPL-3.0-only WITH LGPL-3.0-linking-exception
#if !SKIP_BRIDGE
import Foundation
import SwiftUI
#if !SKIP
import WebKit
import UniformTypeIdentifiers
import CryptoKit
#else
import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
#endif
#if SKIP || os(iOS)
public struct SkipWebSnapshotRect: Equatable, Sendable {
public static let null = SkipWebSnapshotRect(x: 0.0, y: 0.0, width: -1.0, height: -1.0)
public var x: Double
public var y: Double
public var width: Double
public var height: Double
public init(x: Double, y: Double, width: Double, height: Double) {
self.x = x
self.y = y
self.width = width
self.height = height
}
public var isNull: Bool {
width < 0.0 || height < 0.0
}
fileprivate var asCGRect: CGRect {
isNull ? .null : CGRect(x: x, y: y, width: width, height: height)
}
}
/// Snapshot configuration for `WebEngine.takeSnapshot(configuration:)`.
///
/// This mirrors the key behavior of `WKSnapshotConfiguration`:
/// - `rect`: view-coordinate capture region (`.null` means full visible bounds)
/// - `snapshotWidth`: optional output width while preserving aspect ratio
/// - `afterScreenUpdates`: capture after pending updates when possible
public struct SkipWebSnapshotConfiguration {
public var rect: SkipWebSnapshotRect
public var snapshotWidth: Double?
public var afterScreenUpdates: Bool
public init(rect: SkipWebSnapshotRect = .null, snapshotWidth: Double? = nil, afterScreenUpdates: Bool = true) {
self.rect = rect
self.snapshotWidth = snapshotWidth
self.afterScreenUpdates = afterScreenUpdates
}
}
/// A captured web-view snapshot stored as PNG bytes plus pixel dimensions.
public struct SkipWebSnapshot {
public let pngData: Data
public let pixelWidth: Int
public let pixelHeight: Int
public init(pngData: Data, pixelWidth: Int, pixelHeight: Int) {
self.pngData = pngData
self.pixelWidth = pixelWidth
self.pixelHeight = pixelHeight
}
}
public enum WebSnapshotError: Error {
case viewNotLaidOut
case afterScreenUpdatesUnavailable
case invalidRect
case emptySnapshot
case pngEncodingFailed
}
/// Portable cookie representation shared by iOS and Android implementations.
public struct WebCookie: Equatable, Hashable, Sendable {
public var name: String
public var value: String
public var domain: String?
public var path: String?
public var expires: Date?
public var isSecure: Bool
public var isHTTPOnly: Bool
public init(
name: String,
value: String,
domain: String? = nil,
path: String? = nil,
expires: Date? = nil,
isSecure: Bool = false,
isHTTPOnly: Bool = false
) {
self.name = name
self.value = value
self.domain = domain
self.path = path
self.expires = expires
self.isSecure = isSecure
self.isHTTPOnly = isHTTPOnly
}
}
public enum WebCookieError: Error {
case invalidCookieName
case missingCookieDomain
case invalidCookie
}
public enum WebProfile: Equatable, Hashable, Sendable {
case `default`
case named(String)
fileprivate var normalizedNamedIdentifier: String? {
guard case .named(let rawIdentifier) = self else {
return nil
}
let identifier = rawIdentifier.trimmingCharacters(in: .whitespacesAndNewlines)
guard !identifier.isEmpty else {
return nil
}
if identifier.lowercased() == "default" {
return nil
}
return identifier
}
}
public enum WebProfileError: Error, Equatable {
case unsupportedOnAndroid
case invalidProfileName
case profileSetupFailed
}
public enum WebSiteDataType: String, CaseIterable, Hashable, Sendable {
case cookies
case diskCache
case memoryCache
case offlineWebApplicationCache
case localStorage
case sessionStorage
case webSQLDatabases
case indexedDBDatabases
}
public enum WebDataRemovalError: Error, Equatable {
case unsupportedModifiedSinceOnAndroid
}
enum WebDataRemovalBucket: Hashable {
case cookies
case cache
case storage
}
extension WebSiteDataType {
var androidRemovalBucket: WebDataRemovalBucket {
switch self {
case .cookies:
return .cookies
case .diskCache, .memoryCache, .offlineWebApplicationCache:
return .cache
case .localStorage, .sessionStorage, .webSQLDatabases, .indexedDBDatabases:
return .storage
}
}
#if !SKIP
var webKitDataType: String {
switch self {
case .cookies:
return WKWebsiteDataTypeCookies
case .diskCache:
return WKWebsiteDataTypeDiskCache
case .memoryCache:
return WKWebsiteDataTypeMemoryCache
case .offlineWebApplicationCache:
return WKWebsiteDataTypeOfflineWebApplicationCache
case .localStorage:
return WKWebsiteDataTypeLocalStorage
case .sessionStorage:
return WKWebsiteDataTypeSessionStorage
case .webSQLDatabases:
return WKWebsiteDataTypeWebSQLDatabases
case .indexedDBDatabases:
return WKWebsiteDataTypeIndexedDBDatabases
}
}
#endif
}
extension WebCookie {
func matches(url: URL, now: Date = Date()) -> Bool {
guard let host = url.host?.lowercased(), !host.isEmpty else {
return false
}
if isSecure && (url.scheme?.lowercased() != "https") {
return false
}
if let expires, expires <= now {
return false
}
if let domain = normalizedDomain, !domain.isEmpty {
// Treat no-dot domains as host-only so they don't leak to subdomains.
if isHostOnlyDomain {
if host != domain {
return false
}
} else if host != domain && !host.hasSuffix("." + domain) {
return false
}
}
let requestPath = normalizedRequestPath(url.path)
let cookiePath = normalizedCookiePath
// Enforce RFC-style path boundary matching ("/a" does not match "/ab").
return requestPathMatchesCookiePath(requestPath, cookiePath: cookiePath)
}
static func parseRequestCookieHeader(_ header: String) -> [WebCookie] {
let rawComponents = header.split(separator: ";")
var cookies: [WebCookie] = []
for rawComponent in rawComponents {
let component = String(rawComponent).trimmingCharacters(in: .whitespacesAndNewlines)
if component.isEmpty {
continue
}
guard let equalIndex = component.firstIndex(of: "=") else {
continue
}
let name = String(component[..<equalIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
let valueIndex = component.index(after: equalIndex)
let value = String(component[valueIndex...]).trimmingCharacters(in: .whitespacesAndNewlines)
if name.isEmpty {
continue
}
cookies.append(WebCookie(name: name, value: value))
}
return cookies
}
static func parseSetCookieHeaders(_ headers: [String], responseURL: URL) -> [WebCookie] {
#if !SKIP
var parsedCookies: [WebCookie] = []
for header in headers {
let trimmed = header.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
continue
}
let nativeCookies = HTTPCookie.cookies(
withResponseHeaderFields: ["Set-Cookie": trimmed],
for: responseURL
)
for nativeCookie in nativeCookies {
parsedCookies.append(WebCookie(nativeCookie: nativeCookie))
}
}
return parsedCookies
#else
var parsedCookies: [WebCookie] = []
for header in headers {
if let cookie = parseSingleSetCookieHeader(header, responseURL: responseURL) {
parsedCookies.append(cookie)
}
}
return parsedCookies
#endif
}
fileprivate static func parseSingleSetCookieHeader(_ header: String, responseURL: URL) -> WebCookie? {
let segments = header.split(separator: ";")
guard let firstSegment = segments.first else {
return nil
}
let first = String(firstSegment).trimmingCharacters(in: .whitespacesAndNewlines)
guard let firstEqualIndex = first.firstIndex(of: "=") else {
return nil
}
let name = String(first[..<firstEqualIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
let valueStartIndex = first.index(after: firstEqualIndex)
let value = String(first[valueStartIndex...]).trimmingCharacters(in: .whitespacesAndNewlines)
if name.isEmpty {
return nil
}
var domain: String? = responseURL.host
var path: String? = "/"
var expires: Date?
var isSecure = false
var isHTTPOnly = false
if segments.count > 1 {
for segmentIndex in 1..<segments.count {
let rawAttribute = String(segments[segmentIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
if rawAttribute.isEmpty {
continue
}
let lowercasedAttribute = rawAttribute.lowercased()
if lowercasedAttribute == "secure" {
isSecure = true
continue
}
if lowercasedAttribute == "httponly" {
isHTTPOnly = true
continue
}
guard let equalIndex = rawAttribute.firstIndex(of: "=") else {
continue
}
let key = String(rawAttribute[..<equalIndex]).trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let valueIndex = rawAttribute.index(after: equalIndex)
let attributeValue = String(rawAttribute[valueIndex...]).trimmingCharacters(in: .whitespacesAndNewlines)
if attributeValue.isEmpty {
continue
}
if key == "domain" {
// Preserve "Domain=" semantics as subdomain-capable for matching.
domain = attributeValue.hasPrefix(".") ? attributeValue : "." + attributeValue
} else if key == "path" {
path = attributeValue
} else if key == "max-age", let maxAgeSeconds = Int(attributeValue) {
expires = Date(timeIntervalSinceNow: TimeInterval(maxAgeSeconds))
}
}
}
return WebCookie(
name: name,
value: value,
domain: domain,
path: path,
expires: expires,
isSecure: isSecure,
isHTTPOnly: isHTTPOnly
)
}
fileprivate var normalizedDomain: String? {
guard let domain else {
return nil
}
let trimmed = domain.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if trimmed.isEmpty {
return nil
}
if trimmed.hasPrefix(".") {
let start = trimmed.index(after: trimmed.startIndex)
let stripped = String(trimmed[start...])
return stripped.isEmpty ? nil : stripped
}
return trimmed
}
fileprivate var isHostOnlyDomain: Bool {
// A leading dot indicates explicit subdomain matching semantics.
guard let domain else {
return false
}
let trimmed = domain.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
return false
}
return !trimmed.hasPrefix(".")
}
fileprivate var normalizedCookiePath: String {
guard let rawPath = path?.trimmingCharacters(in: .whitespacesAndNewlines), !rawPath.isEmpty else {
return "/"
}
if rawPath.hasPrefix("/") {
return rawPath
}
return "/" + rawPath
}
fileprivate func normalizedRequestPath(_ requestPath: String) -> String {
if requestPath.isEmpty {
return "/"
}
if requestPath.hasPrefix("/") {
return requestPath
}
return "/" + requestPath
}
fileprivate func requestPathMatchesCookiePath(_ requestPath: String, cookiePath: String) -> Bool {
// Follow cookie path-match rules so sibling prefixes are not accepted.
if requestPath == cookiePath {
return true
}
if !requestPath.hasPrefix(cookiePath) {
return false
}
if cookiePath.hasSuffix("/") {
return true
}
let boundaryIndex = requestPath.index(requestPath.startIndex, offsetBy: cookiePath.count)
return boundaryIndex < requestPath.endIndex && requestPath[boundaryIndex] == "/"
}
fileprivate func androidTargetURL(requestURL: URL?) -> URL? {
if let requestURL {
return requestURL
}
guard let domain = normalizedDomain, !domain.isEmpty else {
return nil
}
let normalizedPath = normalizedCookiePath
return URL(string: "https://\(domain)\(normalizedPath)")
}
fileprivate func asAndroidSetCookieString(requestURL: URL?) throws -> String {
if name.isEmpty {
throw WebCookieError.invalidCookieName
}
var cookieParts: [String] = ["\(name)=\(value)"]
if let domain = normalizedDomain, !domain.isEmpty {
cookieParts.append("Domain=\(domain)")
} else if let fallbackDomain = requestURL?.host?.lowercased(), !fallbackDomain.isEmpty {
cookieParts.append("Domain=\(fallbackDomain)")
} else {
throw WebCookieError.missingCookieDomain
}
cookieParts.append("Path=\(normalizedCookiePath)")
if let expires {
let maxAge = max(0, Int(expires.timeIntervalSinceNow.rounded()))
cookieParts.append("Max-Age=\(maxAge)")
}
if isSecure {
cookieParts.append("Secure")
}
if isHTTPOnly {
cookieParts.append("HttpOnly")
}
return cookieParts.joined(separator: "; ")
}
}
#if !SKIP
extension WebCookie {
fileprivate init(nativeCookie: HTTPCookie) {
self.init(
name: nativeCookie.name,
value: nativeCookie.value,
domain: nativeCookie.domain,
path: nativeCookie.path,
expires: nativeCookie.expiresDate,
isSecure: nativeCookie.isSecure,
isHTTPOnly: nativeCookie.isHTTPOnly
)
}
fileprivate func asNativeCookie(requestURL: URL?) throws -> HTTPCookie {
if name.isEmpty {
throw WebCookieError.invalidCookieName
}
// Preserve an explicit leading-dot domain so domain cookies keep subdomain scope.
let explicitDomain = domain?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
let fallbackDomain = requestURL?.host?.lowercased()
guard let effectiveDomain = (explicitDomain?.isEmpty == false ? explicitDomain : nil) ?? fallbackDomain, !effectiveDomain.isEmpty else {
throw WebCookieError.missingCookieDomain
}
var properties: [HTTPCookiePropertyKey: Any] = [
.name: name,
.value: value,
.domain: effectiveDomain,
.path: normalizedCookiePath
]
if let expires {
properties[.expires] = expires
}
if isSecure {
properties[.secure] = "TRUE"
}
if isHTTPOnly {
properties[HTTPCookiePropertyKey("HttpOnly")] = "TRUE"
}
guard let nativeCookie = HTTPCookie(properties: properties) else {
throw WebCookieError.invalidCookie
}
return nativeCookie
}
}
#endif
/// An web engine that holds a system web view:
/// [`WebKit.WKWebView`](https://developer.apple.com/documentation/webkit/wkwebview) on iOS and
/// [`android.webkit.WebView`](https://developer.android.com/reference/android/webkit/WebView) on Android
///
/// The `WebEngine` is used both as the render for a `WebView` and `BrowserView`,
/// and can also be used in a headless context to drive web pages
/// and evaluate JavaScript.
@MainActor public class WebEngine : WebObjectBase {
public let configuration: WebEngineConfiguration
public let webView: PlatformWebView
#if !SKIP
public override var description: String {
"WebEngine: \(webView)"
}
private var observers: [NSKeyValueObservation] = []
private var profileSetupError: WebProfileError?
#else
private var profileSetupError: WebProfileError?
private var androidProfileCookieManager: android.webkit.CookieManager?
private var androidProfileWebStorage: android.webkit.WebStorage?
#endif
/// Create a WebEngine with the specified configuration.
/// - Parameters:
/// - configuration: the configuration to use
/// - webView: when set, the given platform-specific web view will
public init(configuration: WebEngineConfiguration = WebEngineConfiguration(), webView: PlatformWebView? = nil) {
self.configuration = configuration
#if !SKIP
self.webView = webView ?? WKWebView(frame: .zero, configuration: configuration.webViewConfiguration)
if case .named = configuration.profile, configuration.profile.normalizedNamedIdentifier == nil {
self.profileSetupError = .invalidProfileName
}
#else
// fall back to using the global android context if the activity context is not set in the configuration
self.webView = webView ?? PlatformWebView(configuration.context ?? ProcessInfo.processInfo.androidContext)
switch Self.configureAndroidProfile(configuration.profile, for: self.webView) {
case .success(let androidProfileResources):
self.androidProfileCookieManager = androidProfileResources.cookieManager
self.androidProfileWebStorage = androidProfileResources.webStorage
self.profileSetupError = nil
case .failure(let error):
self.profileSetupError = error
}
#endif
}
public func reload() {
if profileSetupError != nil {
return
}
webView.reload()
}
public func stopLoading() {
if profileSetupError != nil {
return
}
webView.stopLoading()
}
public func go(to item: WebHistoryItem) {
if profileSetupError != nil {
return
}
#if !SKIP
webView.go(to: item.item)
#else
// TODO: there's no "go" equivalent in WebView, so we'll probably need to use `goBackOrForward(int steps)` based on matching the item in the back/forward list
#endif
}
public func goBack() {
if profileSetupError != nil {
return
}
webView.goBack()
}
public func goForward() {
if profileSetupError != nil {
return
}
webView.goForward()
}
/// Preferred URL accessor for parity with `WKWebView.url`.
/// A typed `URL` keeps call sites aligned with Apple WebKit ergonomics.
public var url: URL? {
#if SKIP
guard let raw = webView.getUrl() else {
return nil
}
return URL(string: raw)
#else
webView.url
#endif
}
/// Evaluates the given JavaScript string and returns the resulting JSON string, which may be a top-level fragment
public func evaluate(js: String) async throws -> String? {
try throwProfileSetupErrorIfNeeded()
return try await evaluateJavaScriptAsync(js)
}
static func androidRemovalBuckets(for types: Set<WebSiteDataType>) -> Set<WebDataRemovalBucket> {
var buckets = Set<WebDataRemovalBucket>()
for type in types {
buckets.insert(type.androidRemovalBucket)
}
return buckets
}
static func profileValidationError(for profile: WebProfile) -> WebProfileError? {
switch profile {
case .default:
return nil
case .named:
return profile.normalizedNamedIdentifier == nil ? .invalidProfileName : nil
}
}
private func throwProfileSetupErrorIfNeeded() throws {
if let profileSetupError {
throw profileSetupError
}
}
#if SKIP
struct AndroidProfileResources {
let cookieManager: android.webkit.CookieManager?
let webStorage: android.webkit.WebStorage?
}
public static func isAndroidMultiProfileSupported() -> Bool {
WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)
}
private static func configureAndroidProfile(_ profile: WebProfile, for webView: PlatformWebView) -> Result<AndroidProfileResources, WebProfileError> {
if let supportError = androidProfileSupportError(for: profile, isMultiProfileFeatureSupported: isAndroidMultiProfileSupported()) {
return .failure(supportError)
}
switch profile {
case .default:
return .success(AndroidProfileResources(cookieManager: nil, webStorage: nil))
case .named:
guard let identifier = profile.normalizedNamedIdentifier else {
return .failure(.invalidProfileName)
}
guard applyAndroidProfile(identifier, to: webView) else {
return .failure(.profileSetupFailed)
}
let profile = WebViewCompat.getProfile(webView)
return .success(
AndroidProfileResources(
cookieManager: profile.getCookieManager(),
webStorage: profile.getWebStorage()
)
)
}
}
static func androidProfileSupportError(for profile: WebProfile, isMultiProfileFeatureSupported: Bool) -> WebProfileError? {
if let validationError = profileValidationError(for: profile) {
return validationError
}
switch profile {
case .default:
return nil
case .named:
return isMultiProfileFeatureSupported ? nil : .unsupportedOnAndroid
}
}
@discardableResult
func inheritAndroidProfile(from parentProfile: WebProfile) -> WebProfileError? {
if configuration.profile == parentProfile, profileSetupError == nil {
return nil
}
configuration.profile = parentProfile
switch Self.configureAndroidProfile(parentProfile, for: webView) {
case .success(let androidProfileResources):
self.androidProfileCookieManager = androidProfileResources.cookieManager
self.androidProfileWebStorage = androidProfileResources.webStorage
self.profileSetupError = nil
return nil
case .failure(let error):
self.profileSetupError = error
return error
}
}
private static func applyAndroidProfile(_ identifier: String, to webView: PlatformWebView) -> Bool {
// SKIP INSERT: try { androidx.webkit.WebViewCompat.setProfile(webView, identifier); return true } catch (t: Throwable) { return false }
WebViewCompat.setProfile(webView, identifier)
return true
}
private func androidCookieManager() -> android.webkit.CookieManager {
androidProfileCookieManager ?? android.webkit.CookieManager.getInstance()
}
private func androidWebStorage() -> android.webkit.WebStorage {
androidProfileWebStorage ?? android.webkit.WebStorage.getInstance()
}
#endif
static func androidRemovalBucketNames(for types: Set<WebSiteDataType>) -> Set<String> {
var names = Set<String>()
for bucket in androidRemovalBuckets(for: types) {
switch bucket {
case .cookies:
names.insert("cookies")
case .cache:
names.insert("cache")
case .storage:
names.insert("storage")
}
}
return names
}
#if !SKIP
static func webKitDataTypes(for types: Set<WebSiteDataType>) -> Set<String> {
var mapped = Set<String>()
for type in types {
mapped.insert(type.webKitDataType)
}
return mapped
}
#endif
public func cookies(for url: URL) async -> [WebCookie] {
if profileSetupError != nil {
return []
}
#if !SKIP
let store = webView.configuration.websiteDataStore.httpCookieStore
let allCookies = await getAllCookies(from: store)
var filtered: [WebCookie] = []
for nativeCookie in allCookies {
let webCookie = WebCookie(nativeCookie: nativeCookie)
if webCookie.matches(url: url) {
filtered.append(webCookie)
}
}
return filtered
#else
let cookieHeader = androidCookieManager().getCookie(url.absoluteString) ?? ""
if cookieHeader.isEmpty {
return []
}
return WebCookie.parseRequestCookieHeader(cookieHeader)
#endif
}
public func cookieHeader(for url: URL) async -> String? {
if profileSetupError != nil {
return nil
}
#if !SKIP
let matchingCookies = await cookies(for: url)
if matchingCookies.isEmpty {
return nil
}
var cookiePairs: [String] = []
for cookie in matchingCookies {
cookiePairs.append("\(cookie.name)=\(cookie.value)")
}
return cookiePairs.joined(separator: "; ")
#else
let cookieHeader = androidCookieManager().getCookie(url.absoluteString) ?? ""
return cookieHeader.isEmpty ? nil : cookieHeader
#endif
}
public func setCookie(_ cookie: WebCookie, requestURL: URL? = nil) async throws {
try throwProfileSetupErrorIfNeeded()
#if !SKIP
let nativeCookie = try cookie.asNativeCookie(requestURL: requestURL)
let store = webView.configuration.websiteDataStore.httpCookieStore
await setCookie(nativeCookie, in: store)
#else
let targetURL = cookie.androidTargetURL(requestURL: requestURL)
guard let targetURL else {
throw WebCookieError.missingCookieDomain
}
let cookieString = try cookie.asAndroidSetCookieString(requestURL: requestURL)
let cookieManager = androidCookieManager()
await setAndroidCookie(cookieManager, forURLString: targetURL.absoluteString, cookieString: cookieString)
#endif
}
public func applySetCookieHeaders(_ headers: [String], for responseURL: URL) async throws {
try throwProfileSetupErrorIfNeeded()
#if !SKIP
let parsedCookies = WebCookie.parseSetCookieHeaders(headers, responseURL: responseURL)
for cookie in parsedCookies {
try await setCookie(cookie, requestURL: responseURL)
}
#else
let cookieManager = androidCookieManager()
let targetURLString = responseURL.absoluteString
for header in headers {
let trimmed = header.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
continue
}
await setAndroidCookie(cookieManager, forURLString: targetURLString, cookieString: trimmed)
}
#endif
}
public func clearCookies() async {
if profileSetupError != nil {
return
}
#if !SKIP
let store = webView.configuration.websiteDataStore.httpCookieStore
let allCookies = await getAllCookies(from: store)
for cookie in allCookies {
await deleteCookie(cookie, from: store)
}
#else
let cookieManager = androidCookieManager()
await removeAllAndroidCookies(cookieManager)
#endif
}
@MainActor
public func removeData(ofTypes types: Set<WebSiteDataType>, modifiedSince: Date) async throws {
try throwProfileSetupErrorIfNeeded()
if types.isEmpty {
return
}
#if !SKIP
let webKitTypes = Self.webKitDataTypes(for: types)
if webKitTypes.isEmpty {
return
}
await removeData(
from: webView.configuration.websiteDataStore,
ofTypes: webKitTypes,
modifiedSince: modifiedSince
)
#else
if modifiedSince != .distantPast {
throw WebDataRemovalError.unsupportedModifiedSinceOnAndroid
}
let buckets = Self.androidRemovalBuckets(for: types)
if buckets.contains(.cookies) {
await removeAllAndroidCookies(androidCookieManager())
}
if buckets.contains(.cache) {
webView.clearCache(true)
}
if buckets.contains(.storage) {
androidWebStorage().deleteAllData()
}
#endif
}
@MainActor public func takeSnapshot(configuration: SkipWebSnapshotConfiguration? = nil) async throws -> SkipWebSnapshot {
try throwProfileSetupErrorIfNeeded()
let config = configuration ?? SkipWebSnapshotConfiguration()
#if !SKIP
let platformConfig = WKSnapshotConfiguration()
platformConfig.rect = config.rect.asCGRect
if let snapshotWidth = config.snapshotWidth {
platformConfig.snapshotWidth = NSNumber(value: snapshotWidth)
}
platformConfig.afterScreenUpdates = config.afterScreenUpdates
let snapshotImage = try await webView.takeSnapshot(configuration: platformConfig)
guard let pngData = snapshotImage.pngData() else {
throw WebSnapshotError.pngEncodingFailed
}
let pixelWidth = Int(snapshotImage.size.width * snapshotImage.scale)
let pixelHeight = Int(snapshotImage.size.height * snapshotImage.scale)
return SkipWebSnapshot(
pngData: pngData,
pixelWidth: pixelWidth,
pixelHeight: pixelHeight
)
#else
let sourceWidth = Int(webView.getWidth())
let sourceHeight = Int(webView.getHeight())
guard sourceWidth > 0, sourceHeight > 0 else {
throw WebSnapshotError.viewNotLaidOut
}
if config.afterScreenUpdates {
let didScheduleUIUpdateWait: Bool = suspendCancellableCoroutine { continuation in
let scheduled = webView.post {
continuation.resume(true)
}
guard scheduled else {
continuation.resume(false)
return
}
continuation.invokeOnCancellation { _ in
continuation.cancel()
}
}
guard didScheduleUIUpdateWait else {
throw WebSnapshotError.afterScreenUpdatesUnavailable
}
}
let fullRect = CGRect(x: 0.0, y: 0.0, width: CGFloat(sourceWidth), height: CGFloat(sourceHeight))
let requestedRect = config.rect.isNull ? fullRect : config.rect.asCGRect
let clampedRect = requestedRect.intersection(fullRect)
let minX = max(0, Int(floor(clampedRect.minX)))
let minY = max(0, Int(floor(clampedRect.minY)))
let maxX = min(sourceWidth, Int(ceil(clampedRect.maxX)))
let maxY = min(sourceHeight, Int(ceil(clampedRect.maxY)))
let captureWidth = maxX - minX
let captureHeight = maxY - minY
guard captureWidth > 0, captureHeight > 0 else {
throw WebSnapshotError.invalidRect
}
let targetWidth: Int
if let snapshotWidth = config.snapshotWidth {
guard snapshotWidth > 0 else {
throw WebSnapshotError.invalidRect
}
targetWidth = max(1, Int(snapshotWidth.rounded()))
} else {
targetWidth = captureWidth
}
let targetHeight = max(1, Int((Double(captureHeight) * (Double(targetWidth) / Double(captureWidth))).rounded()))
let bitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888)
let canvas = Canvas(bitmap)
let scaleX = Float(Double(targetWidth) / Double(captureWidth))
let scaleY = Float(Double(targetHeight) / Double(captureHeight))
let scrollX = Int(webView.getScrollX())
let scrollY = Int(webView.getScrollY())
canvas.scale(scaleX, scaleY)
// Android WebView drawing is offset by the current scroll position,
// so we must compensate or the snapshot is padded by blank space.
canvas.translate(-Float(minX + scrollX), -Float(minY + scrollY))
webView.draw(canvas)
let outputStream = java.io.ByteArrayOutputStream()
let encoded = bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
bitmap.recycle()
guard encoded else {
throw WebSnapshotError.pngEncodingFailed
}
let base64 = android.util.Base64.encodeToString(outputStream.toByteArray(), android.util.Base64.NO_WRAP)
guard let pngData: Data = Data(base64Encoded: base64, options: []) else {
throw WebSnapshotError.pngEncodingFailed
}
return SkipWebSnapshot(
pngData: pngData,
pixelWidth: targetWidth,
pixelHeight: targetHeight
)
#endif
}
public func loadHTML(_ html: String, baseURL: URL? = nil, mimeType: String = "text/html") {
if profileSetupError != nil {
return
}
logger.info("loadHTML webView: \(self.description)")
let encoding: String = "UTF-8"
#if SKIP
// see https://developer.android.com/reference/android/webkit/WebView#loadDataWithBaseURL(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String)
let baseUrl: String? = baseURL?.absoluteString // the URL to use as the page's base URL. If null defaults to 'about:blank'
//var htmlContent = android.util.Base64.encodeToString(html.toByteArray(), android.util.Base64.NO_PADDING)
var htmlContent = html
let historyUrl: String? = nil // the URL to use as the history entry. If null defaults to 'about:blank'. If non-null, this must be a valid URL.
webView.loadDataWithBaseURL(baseUrl, htmlContent, mimeType, encoding, historyUrl)
#else
refreshMessageHandlers()
//try await awaitPageLoaded {
webView.load(Data(html.utf8), mimeType: mimeType, characterEncodingName: encoding, baseURL: baseURL ?? URL(string: "about:blank")!)