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
|
// Copyright (C) 2025 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
#if ENABLE_SWIFTUI && compiler(>=6.0)
public import CoreTransferable
import Foundation
import UniformTypeIdentifiers
@_weakLinked internal import SwiftUI
internal import WebKit_Private
internal import WebKit_Private.WKSnapshotConfigurationPrivate
internal import WebKit_Private.WKWebViewPrivate
@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)
@available(watchOS, unavailable)
@available(tvOS, unavailable)
extension WebPage: Transferable {
/// A specialized configuration of a specific exportable type that can have specific properties unique to the content type.
public nonisolated struct ExportedContentConfiguration: Sendable {
/// Represents a specific semantic region of a webpage.
public struct Region: Sendable {
private enum Storage {
case contents
case rect(CGRect)
}
/// A region that corresponds to a rectangle in the page's coordinate system.
///
/// - Parameter rect: The rectangle to use for the region.
/// - Returns: A ``Region`` that uses the specified rectangle.
public static func rect(_ rect: CGRect) -> Self {
.init(storage: .rect(rect))
}
/// The entire region of the webpage.
public static var contents: Self {
.init(storage: .contents)
}
private let storage: Storage
private init(storage: Storage) {
self.storage = storage
}
fileprivate var rect: CGRect? {
switch storage {
case .contents: nil
case .rect(let value): value
}
}
fileprivate var usesContentsRect: Bool {
switch storage {
case .contents: true
case .rect(_): false
}
}
}
fileprivate enum Storage {
case pdf(Region, allowTransparentBackground: Bool)
case image(Region, allowTransparentBackground: Bool, snapshotWidth: CGFloat?, afterScreenUpdates: Bool)
}
/// A configuration of a webpage for a representation as PDF data.
///
/// - Parameters:
/// - region: The region of the page used to generate the PDF.
/// - allowTransparentBackground: Indicates whether the PDF may have a transparent background.
/// - Returns: The PDF configuration of this page that will be used when producing its representation.
public static func pdf(region: Region = .contents, allowTransparentBackground: Bool = false) -> Self {
.init(storage: .pdf(region, allowTransparentBackground: allowTransparentBackground))
}
/// A configuration of a webpage for a representation as image data.
///
/// - Parameters:
/// - region: The region of the page used to generate the image.
/// - allowTransparentBackground: Indicates whether the image may have a transparent background.
/// - snapshotWidth: The width of the captured image, in points.
///
/// Use this property to scale the generated image to the specified width. The webpage maintains the aspect ratio of the captured content, but scales it to match the width you specify.
///
/// The default value of this parameter is `nil`, which returns an image whose size matches the original size of the captured region.
///
/// - afterScreenUpdates: Indicates whether to take the snapshot after incorporating any pending screen updates.
///
/// - Returns: The image configuration of this page that will be used when producing its representation.
public static func image(
region: Region = .contents,
allowTransparentBackground: Bool = false,
snapshotWidth: CGFloat? = nil,
afterScreenUpdates: Bool = true
) -> Self {
.init(
storage: .image(
region,
allowTransparentBackground: allowTransparentBackground,
snapshotWidth: snapshotWidth,
afterScreenUpdates: afterScreenUpdates
)
)
}
fileprivate let storage: Storage
private init(storage: Storage) {
self.storage = storage
}
}
// Protocol requirement; no documentation needed.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public nonisolated static var transferRepresentation: some TransferRepresentation {
// FIXME: Add more exportable types, like .html, .linkPresentationMetadata, etc.
// FIXME: Ideally, each of these would be conditionalized on content being loaded on the page.
// The preferred types are roughly in order of descending losslessness.
DataRepresentation(exportedContentType: .webArchive) {
try await $0.webArchiveRepresentation()
}
DataRepresentation(exportedContentType: .pdf) {
try await $0.exported(as: .pdf())
}
// FIXME: Support all the types that NSImage/UIImage support (this can't use ProxyRepresentation since it needs to be async).
// FIXME: This is slightly inefficient since it will be converting data to an image and then back to data.
DataRepresentation(exportedContentType: .png) {
try await $0.exported(as: .image())
}
// FIXME: See if this can somehow be made synchronous, so then it can use `ProxyRepresentation` with `exportingCondition`.
DataRepresentation(exportedContentType: .url) {
try await $0.urlRepresentation()
}
DataRepresentation(exportedContentType: .flatRTFD) {
try await $0.richTextRepresentation(.rtfd)
}
DataRepresentation(exportedContentType: .rtf) {
try await $0.richTextRepresentation(.rtf)
}
DataRepresentation(exportedContentType: .utf8PlainText) {
try await $0.plainTextRepresentation()
}
}
/// Using the type's `Transferable` conformance implementation, exports a value as binary data,
/// optionally with a specified configuration for that type of data.
///
/// For example, you can export a 100 pt by 100 pt region of a webpage as a PDF, and allow it to have a transparent background:
///
/// ```swift
/// let page = WebPage()
/// // Load web content and wait for navigation to complete.
///
/// let square = CGRect(x: 0, y: 0, width: 100, height: 100)
/// let pdf = try await page.exported(as: .pdf(region: .rect(square), allowTransparentBackground: true))
/// ```
///
/// If no configuration is needed, use the ``Transferable`` conformance of ``WebPage`` directly:
///
/// ```swift
/// let page = WebPage()
/// // Load web content and wait for navigation to complete.
///
/// let pdf = try await page.exported(as: .pdf)
/// ```
///
/// - Parameter representation: A configuration for a representation for a specific type of data with optional customizable properties.
/// - Returns: The data with the specified representation type.
/// - Throws: An error if the specified representation cannot be created from the page.
public nonisolated func exported(as representation: ExportedContentConfiguration) async throws -> Data {
switch representation.storage {
case .pdf(let region, let allowTransparentBackground):
try await pdfRepresentation(region: region, allowTransparentBackground: allowTransparentBackground)
case .image(let region, let allowTransparentBackground, let snapshotWidth, let afterScreenUpdates):
try await imageRepresentation(
region: region,
allowTransparentBackground: allowTransparentBackground,
snapshotWidth: snapshotWidth,
afterScreenUpdates: afterScreenUpdates
)
}
}
}
// MARK: Private helper functions
extension WebPage {
private func webArchiveRepresentation() async throws -> Data {
try await withCheckedThrowingContinuation { continuation in
backingWebView.createWebArchiveData {
continuation.resume(with: $0)
}
}
}
private func pdfRepresentation(
region: ExportedContentConfiguration.Region,
allowTransparentBackground: Bool
) async throws -> Data {
let configuration = WKPDFConfiguration()
configuration.rect = region.rect
configuration.allowTransparentBackground = allowTransparentBackground
return try await backingWebView.pdf(configuration: configuration)
}
private func imageRepresentation(
region: ExportedContentConfiguration.Region,
allowTransparentBackground: Bool,
snapshotWidth: CGFloat?,
afterScreenUpdates: Bool
) async throws -> Data {
let configuration = WKSnapshotConfiguration()
configuration.rect = region.rect ?? .null
#if os(macOS)
// FIXME: This should not be limited to macOS.
configuration._usesContentsRect = region.usesContentsRect
#endif
configuration._usesTransparentBackground = allowTransparentBackground
configuration.snapshotWidth = snapshotWidth.map {
NSNumber(value: $0)
}
configuration.afterScreenUpdates = afterScreenUpdates
let snapshot = try await backingWebView.takeSnapshot(configuration: configuration)
guard #_hasSymbol(Image.self) else {
throw WKError(.unknown)
}
#if os(macOS)
let image = Image(nsImage: snapshot)
#else
let image = Image(uiImage: snapshot)
#endif
return try await image.exported(as: .png)
}
private func urlRepresentation() async throws -> Data {
guard let url else {
throw WKError(.unknown)
}
return try await url.exported(as: .url)
}
private func plainTextRepresentation() async throws -> Data {
guard let string = await backingWebView._getContentsOfAllFramesAsString() else {
throw WKError(.unknown)
}
return try await string.exported(as: .utf8PlainText)
}
private func richTextRepresentation(_ type: NSAttributedString.DocumentType) async throws -> Data {
let (string, attributes) = try await backingWebView._getContentsAsAttributedString()
guard let string, var attributes else {
throw WKError(.unknown)
}
attributes[.documentType] = type
return try string.data(from: .init(location: 0, length: string.length), documentAttributes: attributes)
}
}
#endif // ENABLE_SWIFTUI && compiler(>=6.0)
|