Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a cross-import overlay with AppKit to allow attaching NSImages. #869

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ let package = Package(
name: "TestingTests",
dependencies: [
"Testing",
"_Testing_AppKit",
"_Testing_CoreGraphics",
"_Testing_Foundation",
],
Expand Down Expand Up @@ -95,6 +96,15 @@ let package = Package(
),

// Cross-import overlays (not supported by Swift Package Manager)
.target(
name: "_Testing_AppKit",
dependencies: [
"Testing",
"_Testing_CoreGraphics",
],
path: "Sources/Overlays/_Testing_AppKit",
swiftSettings: .packageSettings
),
.target(
name: "_Testing_CoreGraphics",
dependencies: [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//

#if SWT_TARGET_OS_APPLE && canImport(AppKit)
public import AppKit
@_spi(ForSwiftTestingOnly) @_spi(Experimental) public import _Testing_CoreGraphics

@_spi(Experimental)
extension NSImage: AttachableAsCGImage {
public var attachableCGImage: CGImage {
get throws {
let ctm = AffineTransform(scale: _attachmentScaleFactor) as NSAffineTransform
guard let result = cgImage(forProposedRect: nil, context: nil, hints: [.ctm: ctm]) else {
throw ImageAttachmentError.couldNotCreateCGImage
}
return result
}
}

public var _attachmentScaleFactor: CGFloat {
let maxRepWidth = representations.lazy
.map { CGFloat($0.pixelsWide) / $0.size.width }
.filter { $0 > 0.0 }
.max()
return maxRepWidth ?? 1.0
}

/// Get the base address of the loaded image containing `class`.
///
/// - Parameters:
/// - class: The class to look for.
///
/// - Returns: The base address of the image containing `class`, or `nil` if
/// no image was found (for instance, if the class is generic or dynamically
/// generated.)
///
/// "Image" in this context refers to a binary/executable image.
private static func _baseAddressOfImage(containing `class`: AnyClass) -> UnsafeRawPointer? {
let classAsAddress = Unmanaged.passUnretained(`class` as AnyObject).toOpaque()

var info = Dl_info()
guard 0 != dladdr(classAsAddress, &info) else {
return nil
}
return .init(info.dli_fbase)
}

/// The base address of the image containing AppKit's symbols, if known.
private static nonisolated(unsafe) let _appKitBaseAddress = _baseAddressOfImage(containing: NSImageRep.self)

public func _makeCopyForAttachment() -> Self {
// If this image is of an NSImage subclass, we cannot reliably make a deep
// copy of it because we don't know what its `init(data:)` implementation
// might do. Try to make a copy (using NSCopying), but if that doesn't work
// then just return `self` verbatim.
//
// Third-party NSImage subclasses are presumably rare in the wild, so
// hopefully this case doesn't pop up too often.
guard isMember(of: NSImage.self) else {
return self.copy() as? Self ?? self
}

// Check whether the image contains any representations that we don't think
// are safe. If it does, then make a "safe" copy.
let allImageRepsAreSafe = representations.allSatisfy { imageRep in
// NSCustomImageRep includes an arbitrary rendering block that may not be
// concurrency-safe in Swift.
if imageRep is NSCustomImageRep {
return false
}

// Treat all other classes declared in AppKit as safe. We can't reason
// about classes declared in other modules, so treat them all as if they
// are unsafe.
return Self._baseAddressOfImage(containing: type(of: imageRep)) == Self._appKitBaseAddress
}
if !allImageRepsAreSafe, let safeCopy = tiffRepresentation.flatMap(Self.init(data:)) {
// Create a "safe" copy of this image by flattening it to TIFF and then
// creating a new NSImage instance from it.
return safeCopy
}

// This image appears to be safe to copy directly. (This call should never
// fail since we already know `self` is a direct instance of `NSImage`.)
return unsafeDowncast(self.copy() as AnyObject, to: Self.self)
}
}
#endif
12 changes: 12 additions & 0 deletions Sources/Overlays/_Testing_AppKit/ReexportTesting.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//

@_exported public import Testing
@_exported public import _Testing_CoreGraphics
114 changes: 111 additions & 3 deletions Tests/TestingTests/AttachmentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@

@testable @_spi(Experimental) @_spi(ForToolsIntegrationOnly) import Testing
private import _TestingInternals
#if canImport(Foundation)
import Foundation
@_spi(Experimental) import _Testing_Foundation
#if canImport(AppKit)
import AppKit
@_spi(Experimental) import _Testing_AppKit
#endif
#if canImport(CoreGraphics)
import CoreGraphics
@_spi(Experimental) @_spi(ForSwiftTestingOnly) import _Testing_CoreGraphics
#endif
#if canImport(Foundation)
import Foundation
@_spi(Experimental) import _Testing_Foundation
#endif
#if canImport(UniformTypeIdentifiers)
import UniformTypeIdentifiers
#endif
Expand Down Expand Up @@ -555,6 +559,71 @@ extension AttachmentTests {
}
}
#endif

#if canImport(AppKit)
static var nsImage: NSImage {
get throws {
let cgImage = try cgImage.get()
let size = CGSize(width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
return NSImage(cgImage: cgImage, size: size)
}
}

@available(_uttypesAPI, *)
@Test func attachNSImage() throws {
let image = try Self.nsImage
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
try attachment.attachableValue.withUnsafeBufferPointer(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}

@available(_uttypesAPI, *)
@Test func attachNSImageWithCustomRep() throws {
let image = NSImage(size: NSSize(width: 32.0, height: 32.0), flipped: false) { rect in
NSColor.red.setFill()
rect.fill()
return true
}
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
try attachment.attachableValue.withUnsafeBufferPointer(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}

@available(_uttypesAPI, *)
@Test func attachNSImageWithSubclassedNSImage() throws {
let image = MyImage(size: NSSize(width: 32.0, height: 32.0))
image.addRepresentation(NSCustomImageRep(size: image.size, flipped: false) { rect in
NSColor.green.setFill()
rect.fill()
return true
})

let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue === image)
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
try attachment.attachableValue.withUnsafeBufferPointer(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}

@available(_uttypesAPI, *)
@Test func attachNSImageWithSubclassedRep() throws {
let image = NSImage(size: NSSize(width: 32.0, height: 32.0))
image.addRepresentation(MyImageRep<Int>())

let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
let firstRep = try #require(attachment.attachableValue.representations.first)
#expect(!(firstRep is MyImageRep<Int>))
try attachment.attachableValue.withUnsafeBufferPointer(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}
#endif
#endif
}
}
Expand Down Expand Up @@ -644,3 +713,42 @@ final class MyCodableAndSecureCodingAttachable: NSObject, Codable, NSSecureCodin
}
}
#endif

#if canImport(AppKit)
private final class MyImage: NSImage {
override init(size: NSSize) {
super.init(size: size)
}

required init(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) {
fatalError("Unimplemented")
}

required init(coder: NSCoder) {
fatalError("Unimplemented")
}

override func copy(with zone: NSZone?) -> Any {
// Intentionally make a copy as NSImage instead of MyImage to exercise the
// cast-failed code path in the overlay.
NSImage()
}
}

private final class MyImageRep<T>: NSImageRep {
override init() {
super.init()
size = NSSize(width: 32.0, height: 32.0)
}

required init?(coder: NSCoder) {
fatalError("Unimplemented")
}

override func draw() -> Bool {
NSColor.blue.setFill()
NSRect(origin: .zero, size: size).fill()
return true
}
}
#endif