Repository Public License
1// ORIX Convert — App/Sources/Features/Studio/CompareCanvas.swift2// Description: The zoomable comparison canvas shared by Quality Lab and Vector Studio: one or two synchronized panes3// or a draggable split, bitmaps (nearest-neighbour past 100 %) or CGPath layers (crisp at any zoom),4// checkerboard under transparency, pinch / scroll / drag, and the pixel position under the pointer.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import AppKit7import Observation8import SwiftUI910/// What one side of the canvas draws. Coordinates are those of the original image (pixels, y down).11enum CanvasLayer {12 /// A bounded preview and, once loaded, a larger "detail" bitmap used when the zoom needs more pixels.13 case image(preview: CGImage, detail: CGImage?)14 /// Filled paths (a traced drawing).15 case vector(layers: [(path: CGPath, color: CGColor)], background: CGColor?)16 /// The same paths stroked without fill; `nodes` are drawn as small squares when given.17 case outline(layers: [(path: CGPath, color: CGColor)], nodes: [CGPoint]?)18}1920enum CanvasMode: String, CaseIterable, Identifiable {21 case original, result, sideBySide, split22 var id: String { rawValue }23}2425/// Zoom and position shared by every pane (and by the toolbar and the menu commands).26@Observable final class Viewport {27 /// Device pixels per image pixel; `nil` fits the image in the pane.28 var zoom: Double?29 /// Image point (0…1 on both axes) shown at the centre of each pane.30 var center = CGPoint(x: 0.5, y: 0.5)31 /// Position of the split handle, 0…1 across the pane.32 var split = 0.533 /// Zoom that "fit" currently amounts to; written by the canvas when it is laid out.34 var fitZoom = 1.03536 static let steps: [Double] = [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16, 32]37 static let range: ClosedRange<Double> = 0.02...643839 var effectiveZoom: Double { zoom ?? fitZoom }40 var isFit: Bool { zoom == nil }41 var percentText: String { effectiveZoom.formatted(.percent.precision(.fractionLength(0))) }4243 func fit() { zoom = nil; center = CGPoint(x: 0.5, y: 0.5) }44 func set(_ value: Double) { zoom = min(Self.range.upperBound, max(Self.range.lowerBound, value)) }45 func zoomIn() { set(Self.steps.first { $0 > effectiveZoom * 1.01 } ?? Self.range.upperBound) }46 func zoomOut() { set(Self.steps.last { $0 < effectiveZoom * 0.99 } ?? Self.range.lowerBound) }47}4849struct CompareCanvas: NSViewRepresentable {50 var left: CanvasLayer?51 var right: CanvasLayer?52 var leftLabel: String53 var rightLabel: String54 var mode: CanvasMode55 /// Size of the original image in pixels: the coordinate space of both sides.56 var imageSize: CGSize57 var viewport: Viewport58 var checkerboard = true59 /// Pixel of the original under the pointer (`nil` outside the image).60 var onHover: ((CGPoint?) -> Void)?6162 func makeNSView(context: Context) -> CanvasNSView {63 let view = CanvasNSView()64 apply(to: view)65 return view66 }6768 func updateNSView(_ view: CanvasNSView, context: Context) {69 // Reading the viewport here makes SwiftUI call this again when the toolbar or a menu command changes it.70 _ = (viewport.zoom, viewport.center, viewport.split)71 apply(to: view)72 }7374 private func apply(to view: CanvasNSView) {75 view.left = left; view.right = right76 view.leftLabel = leftLabel; view.rightLabel = rightLabel77 view.mode = mode; view.imageSize = imageSize78 view.viewport = viewport; view.checkerboard = checkerboard79 view.onHover = onHover80 view.needsDisplay = true81 }82}8384final class CanvasNSView: NSView {85 var left: CanvasLayer?86 var right: CanvasLayer?87 var leftLabel = ""88 var rightLabel = ""89 var mode: CanvasMode = .split90 var imageSize: CGSize = .zero91 var viewport = Viewport()92 var checkerboard = true93 var onHover: ((CGPoint?) -> Void)?9495 private var draggingSplit = false96 private var lastDrag: CGPoint?97 private var tracking: NSTrackingArea?9899 override var isFlipped: Bool { true }100 override var acceptsFirstResponder: Bool { true }101 override var isOpaque: Bool { false }102103 // MARK: Geometry104105 private var backing: CGFloat { window?.backingScaleFactor ?? 2 }106107 private var panes: [CGRect] {108 guard mode == .sideBySide else { return [bounds] }109 let gap: CGFloat = 1, width = (bounds.width - gap) / 2110 return [CGRect(x: 0, y: 0, width: width, height: bounds.height), CGRect(x: width + gap, y: 0, width: width, height: bounds.height)]111 }112113 /// Points per image pixel.114 private var scale: CGFloat {115 CGFloat(viewport.effectiveZoom) / backing116 }117118 private func fitZoom(for pane: CGRect) -> Double {119 guard imageSize.width > 0, imageSize.height > 0, pane.width > 40, pane.height > 40 else { return 1 }120 let points = min((pane.width - 32) / imageSize.width, (pane.height - 32) / imageSize.height)121 return min(Viewport.range.upperBound, max(Viewport.range.lowerBound, Double(points * backing)))122 }123124 /// Where the image lies in a pane, in view coordinates.125 private func imageRect(in pane: CGRect) -> CGRect {126 let s = scale127 let size = CGSize(width: imageSize.width * s, height: imageSize.height * s)128 // An axis on which the whole image fits stays centred.129 let cx = size.width <= pane.width ? 0.5 : min(1 - pane.width / size.width / 2, max(pane.width / size.width / 2, viewport.center.x))130 let cy = size.height <= pane.height ? 0.5 : min(1 - pane.height / size.height / 2, max(pane.height / size.height / 2, viewport.center.y))131 return CGRect(x: pane.midX - cx * size.width, y: pane.midY - cy * size.height, width: size.width, height: size.height)132 }133134 private func pane(at point: CGPoint) -> CGRect { panes.first { $0.contains(point) } ?? panes[0] }135136 private func imagePoint(at point: CGPoint) -> CGPoint? {137 guard imageSize.width > 0 else { return nil }138 let rect = imageRect(in: pane(at: point))139 guard rect.contains(point) else { return nil }140 return CGPoint(x: (point.x - rect.minX) / scale, y: (point.y - rect.minY) / scale)141 }142143 override func layout() {144 super.layout()145 updateFit()146 }147148 override func viewDidMoveToWindow() {149 super.viewDidMoveToWindow()150 updateFit()151 }152153 private func updateFit() {154 let fit = fitZoom(for: panes[0])155 guard abs(fit - viewport.fitZoom) / max(fit, 0.0001) > 0.004 else { return }156 let viewport = viewport157 // Not during a SwiftUI update: the viewport is observed by the toolbar.158 DispatchQueue.main.async { [weak self] in159 viewport.fitZoom = fit160 self?.needsDisplay = true161 }162 }163164 // MARK: Drawing165166 override func draw(_ dirtyRect: NSRect) {167 guard let context = NSGraphicsContext.current?.cgContext else { return }168 let dark = effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua169 context.setFillColor((dark ? NSColor(hex: 0x0F1322) : NSColor(hex: 0xE9EBF3)).cgColor)170 context.fill(bounds)171 guard imageSize.width > 0, imageSize.height > 0 else { return }172 let all = panes173 for (index, pane) in all.enumerated() {174 context.saveGState()175 context.clip(to: pane)176 let rect = imageRect(in: pane)177 let visible = rect.intersection(pane)178 if !visible.isNull, !visible.isEmpty {179 switch mode {180 case .original: drawSide(left, rect: rect, clip: visible, in: context, dark: dark)181 case .result: drawSide(right, rect: rect, clip: visible, in: context, dark: dark)182 case .sideBySide: drawSide(index == 0 ? left : right, rect: rect, clip: visible, in: context, dark: dark)183 case .split:184 let x = pane.minX + pane.width * viewport.split185 let leftClip = visible.intersection(CGRect(x: pane.minX, y: pane.minY, width: x - pane.minX, height: pane.height))186 let rightClip = visible.intersection(CGRect(x: x, y: pane.minY, width: pane.maxX - x, height: pane.height))187 if !leftClip.isNull, !leftClip.isEmpty { drawSide(left, rect: rect, clip: leftClip, in: context, dark: dark) }188 if !rightClip.isNull, !rightClip.isEmpty { drawSide(right, rect: rect, clip: rightClip, in: context, dark: dark) }189 }190 context.setStrokeColor((dark ? NSColor(hex: 0x343B58) : NSColor(hex: 0xC3C8D8)).cgColor)191 context.setLineWidth(1)192 context.stroke(rect.insetBy(dx: -0.5, dy: -0.5))193 }194 context.restoreGState()195 switch mode {196 case .original: drawLabel(leftLabel, in: pane, trailing: false, dark: dark)197 case .result: drawLabel(rightLabel, in: pane, trailing: false, dark: dark)198 case .sideBySide: drawLabel(index == 0 ? leftLabel : rightLabel, in: pane, trailing: false, dark: dark)199 case .split:200 drawLabel(leftLabel, in: pane, trailing: false, dark: dark)201 drawLabel(rightLabel, in: pane, trailing: true, dark: dark)202 drawSplitHandle(in: pane, context: context)203 }204 }205 if mode == .sideBySide, all.count == 2 {206 context.setFillColor((dark ? NSColor(hex: 0x262C44) : NSColor(hex: 0xD3D7E4)).cgColor)207 context.fill(CGRect(x: all[0].maxX, y: 0, width: 1, height: bounds.height))208 }209 }210211 private func drawSide(_ layer: CanvasLayer?, rect: CGRect, clip: CGRect, in context: CGContext, dark: Bool) {212 guard let layer else { return }213 context.saveGState()214 context.clip(to: clip)215 if checkerboard { drawCheckerboard(in: clip, origin: rect.origin, context: context, dark: dark) }216 switch layer {217 case .image(let preview, let detail):218 // Use the detail bitmap as soon as the preview would be stretched on screen.219 let devicePixelsWide = rect.width * backing220 let bitmap = (detail != nil && devicePixelsWide > CGFloat(preview.width) * 1.02) ? (detail ?? preview) : preview221 drawBitmap(bitmap, rect: rect, clip: clip, in: context)222 case .vector(let layers, let background):223 context.translateBy(x: rect.minX, y: rect.minY)224 context.scaleBy(x: scale, y: scale)225 context.setShouldAntialias(true)226 if let background {227 context.setFillColor(background)228 context.fill(CGRect(origin: .zero, size: imageSize))229 }230 for item in layers {231 context.addPath(item.path)232 context.setFillColor(item.color)233 context.fillPath(using: .winding)234 }235 case .outline(let layers, let nodes):236 let s = scale237 context.translateBy(x: rect.minX, y: rect.minY)238 context.scaleBy(x: s, y: s)239 context.setLineWidth(1 / s)240 context.setLineJoin(.round)241 for item in layers {242 context.addPath(item.path)243 context.setStrokeColor(Self.outlineColor(for: item.color, dark: dark))244 context.strokePath()245 }246 if let nodes {247 // Only the nodes inside the visible area, and only while they stay readable.248 let visible = CGRect(x: (clip.minX - rect.minX) / s, y: (clip.minY - rect.minY) / s, width: clip.width / s, height: clip.height / s).insetBy(dx: -2 / s, dy: -2 / s)249 let side = 4 / s250 context.setFillColor((dark ? NSColor(hex: 0x22D3EE) : NSColor(hex: 0x5B4BE8)).cgColor)251 var drawn = 0252 for node in nodes where visible.contains(node) {253 context.fill(CGRect(x: node.x - side / 2, y: node.y - side / 2, width: side, height: side))254 drawn += 1255 if drawn >= 40_000 { break }256 }257 }258 }259 context.restoreGState()260 }261262 /// Stroke colour of an outline: the colour of the shape, moved away from the canvas when it would not show.263 private static func outlineColor(for color: CGColor, dark: Bool) -> CGColor {264 guard let c = color.components, c.count >= 3 else { return color }265 let luminance = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]266 if dark, luminance < 0.35 { return NSColor(hex: 0xA3ABC2).cgColor }267 if !dark, luminance > 0.75 { return NSColor(hex: 0x555B6E).cgColor }268 return color269 }270271 /// Draws the part of `bitmap` that falls in `clip`. `rect` is where the whole image lies.272 private func drawBitmap(_ bitmap: CGImage, rect: CGRect, clip: CGRect, in context: CGContext) {273 let sx = CGFloat(bitmap.width) / rect.width, sy = CGFloat(bitmap.height) / rect.height274 var source = CGRect(x: (clip.minX - rect.minX) * sx, y: (clip.minY - rect.minY) * sy, width: clip.width * sx, height: clip.height * sy).integral275 source = source.intersection(CGRect(x: 0, y: 0, width: bitmap.width, height: bitmap.height))276 guard !source.isNull, source.width >= 1, source.height >= 1, let part = bitmap.cropping(to: source) else { return }277 let target = CGRect(x: rect.minX + source.minX / sx, y: rect.minY + source.minY / sy, width: source.width / sx, height: source.height / sy)278 // Nearest neighbour as soon as one bitmap pixel covers more than one device pixel.279 let magnified = (1 / sx) * backing > 1.001280 context.interpolationQuality = magnified ? .none : .high281 context.saveGState()282 context.translateBy(x: target.minX, y: target.maxY)283 context.scaleBy(x: 1, y: -1)284 context.draw(part, in: CGRect(origin: .zero, size: target.size))285 context.restoreGState()286 }287288 private func drawCheckerboard(in clip: CGRect, origin: CGPoint, context: CGContext, dark: Bool) {289 let a = (dark ? NSColor(hex: 0x1B2034) : NSColor(hex: 0xFFFFFF)).cgColor, b = (dark ? NSColor(hex: 0x262C44) : NSColor(hex: 0xE3E6EF)).cgColor290 context.setFillColor(a)291 context.fill(clip)292 context.setFillColor(b)293 let cell: CGFloat = 8294 let firstColumn = Int(floor((clip.minX - origin.x) / cell)), lastColumn = Int(ceil((clip.maxX - origin.x) / cell))295 let firstRow = Int(floor((clip.minY - origin.y) / cell)), lastRow = Int(ceil((clip.maxY - origin.y) / cell))296 guard (lastColumn - firstColumn) * (lastRow - firstRow) < 200_000 else { return }297 for row in firstRow..<lastRow {298 for column in firstColumn..<lastColumn where (row + column) & 1 == 0 {299 context.fill(CGRect(x: origin.x + CGFloat(column) * cell, y: origin.y + CGFloat(row) * cell, width: cell, height: cell))300 }301 }302 }303304 private func drawLabel(_ text: String, in pane: CGRect, trailing: Bool, dark: Bool) {305 guard !text.isEmpty else { return }306 let attributes: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 11, weight: .semibold), .foregroundColor: NSColor.white]307 let string = NSAttributedString(string: text, attributes: attributes)308 let size = string.size()309 let box = CGRect(x: trailing ? pane.maxX - size.width - 26 : pane.minX + 10, y: pane.minY + 10, width: size.width + 16, height: size.height + 6)310 let path = NSBezierPath(roundedRect: box, xRadius: box.height / 2, yRadius: box.height / 2)311 NSColor.black.withAlphaComponent(dark ? 0.55 : 0.6).setFill()312 path.fill()313 string.draw(at: CGPoint(x: box.minX + 8, y: box.minY + 3))314 }315316 private func drawSplitHandle(in pane: CGRect, context: CGContext) {317 let x = (pane.minX + pane.width * viewport.split).rounded()318 context.setFillColor(NSColor.black.withAlphaComponent(0.35).cgColor)319 context.fill(CGRect(x: x - 1.5, y: pane.minY, width: 3, height: pane.height))320 context.setFillColor(NSColor.white.cgColor)321 context.fill(CGRect(x: x - 0.5, y: pane.minY, width: 1, height: pane.height))322 let knob = CGRect(x: x - 14, y: pane.midY - 14, width: 28, height: 28)323 context.setShadow(offset: .zero, blur: 6, color: NSColor.black.withAlphaComponent(0.35).cgColor)324 context.setFillColor(NSColor.white.cgColor)325 context.fillEllipse(in: knob)326 context.setShadow(offset: .zero, blur: 0, color: nil)327 context.setStrokeColor(NSColor(hex: 0x5B4BE8).cgColor)328 context.setLineWidth(1.6)329 context.setLineCap(.round)330 context.setLineJoin(.round)331 for direction in [-1.0, 1.0] {332 let tip = knob.midX + direction * 8, base = knob.midX + direction * 4333 context.move(to: CGPoint(x: base, y: knob.midY - 4))334 context.addLine(to: CGPoint(x: tip, y: knob.midY))335 context.addLine(to: CGPoint(x: base, y: knob.midY + 4))336 }337 context.strokePath()338 }339340 // MARK: Events341342 override func updateTrackingAreas() {343 super.updateTrackingAreas()344 if let tracking { removeTrackingArea(tracking) }345 let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)346 addTrackingArea(area)347 tracking = area348 }349350 override func mouseMoved(with event: NSEvent) {351 let point = convert(event.locationInWindow, from: nil)352 onHover?(imagePoint(at: point).map { CGPoint(x: floor($0.x), y: floor($0.y)) })353 }354355 override func mouseExited(with event: NSEvent) { onHover?(nil) }356357 private func isOnSplitHandle(_ point: CGPoint) -> Bool {358 guard mode == .split else { return false }359 let pane = panes[0]360 return abs(point.x - (pane.minX + pane.width * viewport.split)) <= 16361 }362363 override func mouseDown(with event: NSEvent) {364 window?.makeFirstResponder(self)365 let point = convert(event.locationInWindow, from: nil)366 if event.clickCount == 2, !isOnSplitHandle(point) {367 if viewport.isFit { zoom(to: 1, around: point) } else { viewport.fit() }368 needsDisplay = true369 return370 }371 draggingSplit = isOnSplitHandle(point)372 lastDrag = point373 }374375 override func mouseDragged(with event: NSEvent) {376 let point = convert(event.locationInWindow, from: nil)377 defer { lastDrag = point; needsDisplay = true }378 if draggingSplit {379 let pane = panes[0]380 viewport.split = min(1, max(0, (point.x - pane.minX) / pane.width))381 return382 }383 guard let lastDrag else { return }384 pan(dx: point.x - lastDrag.x, dy: point.y - lastDrag.y)385 }386387 override func mouseUp(with event: NSEvent) { draggingSplit = false; lastDrag = nil }388389 override func resetCursorRects() {390 guard mode == .split else { return }391 let pane = panes[0]392 addCursorRect(CGRect(x: pane.minX + pane.width * viewport.split - 12, y: pane.minY, width: 24, height: pane.height), cursor: .resizeLeftRight)393 }394395 private func pan(dx: CGFloat, dy: CGFloat) {396 let s = scale397 guard imageSize.width > 0, s > 0 else { return }398 // Start from where the image really is (the stored centre may be outside the clamped range).399 let pane = panes[0], rect = imageRect(in: pane)400 let current = CGPoint(x: (pane.midX - rect.minX) / rect.width, y: (pane.midY - rect.minY) / rect.height)401 viewport.center = CGPoint(x: min(1, max(0, current.x - dx / (imageSize.width * s))), y: min(1, max(0, current.y - dy / (imageSize.height * s))))402 }403404 /// Changes the zoom while keeping the image point under `point` where it is.405 private func zoom(to newZoom: Double, around point: CGPoint) {406 let pane = pane(at: point)407 let before = imageRect(in: pane)408 let anchor = CGPoint(x: (point.x - before.minX) / before.width, y: (point.y - before.minY) / before.height)409 viewport.set(newZoom)410 let s = scale411 let size = CGSize(width: imageSize.width * s, height: imageSize.height * s)412 guard size.width > 0, size.height > 0 else { return }413 // Solve pane.mid − c·size + anchor·size = point for c.414 viewport.center = CGPoint(x: min(1, max(0, anchor.x - (point.x - pane.midX) / size.width)), y: min(1, max(0, anchor.y - (point.y - pane.midY) / size.height)))415 }416417 override func scrollWheel(with event: NSEvent) {418 let point = convert(event.locationInWindow, from: nil)419 if event.modifierFlags.contains(.command) || !event.hasPreciseScrollingDeltas {420 let delta = event.hasPreciseScrollingDeltas ? event.scrollingDeltaY / 120 : event.scrollingDeltaY / 12421 zoom(to: viewport.effectiveZoom * pow(2, Double(delta)), around: point)422 } else {423 pan(dx: event.scrollingDeltaX, dy: event.scrollingDeltaY)424 }425 needsDisplay = true426 }427428 override func magnify(with event: NSEvent) {429 zoom(to: viewport.effectiveZoom * (1 + Double(event.magnification)), around: convert(event.locationInWindow, from: nil))430 needsDisplay = true431 }432433 override func keyDown(with event: NSEvent) {434 let step: CGFloat = event.modifierFlags.contains(.shift) ? 200 : 40435 switch event.keyCode {436 case 123: pan(dx: step, dy: 0)437 case 124: pan(dx: -step, dy: 0)438 case 125: pan(dx: 0, dy: -step)439 case 126: pan(dx: 0, dy: step)440 default:441 switch event.charactersIgnoringModifiers {442 case "+", "=": viewport.zoomIn()443 case "-": viewport.zoomOut()444 case "0": viewport.fit()445 case "1": viewport.set(1)446 case "[" where mode == .split: viewport.split = max(0, viewport.split - 0.05)447 case "]" where mode == .split: viewport.split = min(1, viewport.split + 0.05)448 default: super.keyDown(with: event); return449 }450 }451 needsDisplay = true452 }453}454455/// Zoom controls drawn by the app: − / percentage menu / + / fit.456struct ZoomControls: View {457 let viewport: Viewport458 var body: some View {459 HStack(spacing: 2) {460 IconButton(symbol: "minus.magnifyingglass", label: L("Zoom Out")) { viewport.zoomOut() }461 Menu {462 Button(L("Fit")) { viewport.fit() }463 Divider()464 ForEach([0.25, 0.5, 1, 2, 4, 8, 16], id: \.self) { value in465 Button(value.formatted(.percent.precision(.fractionLength(0)))) { viewport.set(value) }466 }467 } label: {468 Text(viewport.isFit ? L("Fit · %@", viewport.percentText) : viewport.percentText).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textPrimary)469 .frame(minWidth: 74)470 }471 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()472 .accessibilityLabel(L("Zoom"))473 .accessibilityValue(viewport.percentText)474 IconButton(symbol: "plus.magnifyingglass", label: L("Zoom In")) { viewport.zoomIn() }475 IconButton(symbol: "arrow.up.left.and.arrow.down.right", label: L("Fit"), tint: viewport.isFit ? ORIX.Palette.accent : ORIX.Palette.textSecondary) { viewport.fit() }476 }477 .padding(.horizontal, 3).padding(.vertical, 1)478 .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: 9, style: .continuous))479 .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))480 }481}482483/// Reads one pixel of a bitmap as 8-bit sRGB (straight alpha).484nonisolated enum PixelProbe {485 struct Sample: Equatable, Sendable {486 let red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8487 var text: String { "\(red) \(green) \(blue) \(alpha)" }488 var hex: String { String(format: "#%02X%02X%02X", red, green, blue) }489 }490491 /// `point` is in the pixels of the original image; the bitmap may be a reduced copy of it.492 static func sample(_ image: CGImage, at point: CGPoint, originalSize: CGSize) -> Sample? {493 guard originalSize.width > 0, originalSize.height > 0 else { return nil }494 let x = min(image.width - 1, max(0, Int((point.x + 0.5) / originalSize.width * CGFloat(image.width))))495 let y = min(image.height - 1, max(0, Int((point.y + 0.5) / originalSize.height * CGFloat(image.height))))496 guard let pixel = image.cropping(to: CGRect(x: x, y: y, width: 1, height: 1)), let space = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }497 var bytes = [UInt8](repeating: 0, count: 4)498 let ok: Bool = bytes.withUnsafeMutableBytes { raw in499 guard let context = CGContext(data: raw.baseAddress, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: space,500 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return false }501 context.interpolationQuality = .none502 context.draw(pixel, in: CGRect(x: 0, y: 0, width: 1, height: 1))503 return true504 }505 guard ok else { return nil }506 let a = bytes[3]507 func straight(_ v: UInt8) -> UInt8 { a == 0 ? 0 : UInt8(min(255, (Int(v) * 255 + Int(a) / 2) / Int(a))) }508 return Sample(red: straight(bytes[0]), green: straight(bytes[1]), blue: straight(bytes[2]), alpha: a)509 }510}511