diff --git a/host/apple/Sources/ExactKit/Gradient.swift b/host/apple/Sources/ExactKit/Gradient.swift index be320951d..574aafba4 100644 --- a/host/apple/Sources/ExactKit/Gradient.swift +++ b/host/apple/Sources/ExactKit/Gradient.swift @@ -28,9 +28,9 @@ struct Gradient { case conic(CGPoint, CGFloat) } - private let css: String? + let css: String? /// The dark scheme's `css` where it interpolates otherwise. - private let darkCss: String? + let darkCss: String? /// The view's tint, light then dark: extended sRGB, unclipped, and alpha 0–1. private let tint: [[Float]]? private let resolvedPlacement: Placement? @@ -41,7 +41,7 @@ struct Gradient { /// extended linear sRGB with alpha 0–1. private let lightLinear: Bool private let darkLinear: Bool - private func linear(dark: Bool) -> Bool { dark && self.dark != nil ? darkLinear : lightLinear } + func linear(dark: Bool) -> Bool { dark && self.dark != nil ? darkLinear : lightLinear } init?(_ value: BatchValue?, tint: PlatformColor? = nil) { guard case .object(let o)? = value else { return nil } @@ -82,7 +82,7 @@ struct Gradient { } /// Resolve in the kernel after the presenter knows the gradient box. - private func resolved(in box: CGRect, dark: Bool) -> Gradient? { + func resolved(in box: CGRect, dark: Bool) -> Gradient? { guard let css = dark ? darkCss ?? css : css else { return nil } return Owner.shared.sync { let input = Array(css.utf8), w = Float(box.width), h = Float(box.height) @@ -235,24 +235,27 @@ struct Gradient { } let (locations, colors) = stops(dark: dark) if case .axial(let a, let b) = place { - let cuts = locations.indices.dropFirst().filter { - locations[$0] == locations[$0 - 1] && locations[$0] > locations[0] && locations[$0] < locations.last! - } - if !cuts.isEmpty { - paintAxialRuns(ctx, start: a, end: b, locations: locations, colors: colors, cuts: Array(cuts), dark: dark) - return - } + paintAxial(ctx, start: a, end: b, locations: locations, colors: colors, dark: dark) + return } - guard let g = CGGradient(colorsSpace: CGColorSpace(name: linear(dark: dark) ? CGColorSpace.extendedLinearSRGB : CGColorSpace.sRGB), colors: colors as CFArray, locations: locations) else { return } - switch place { - case .axial(let a, let b): - ctx.drawLinearGradient(g, start: a, end: b, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]) - case .radial(let c, let r): - ctx.translateBy(x: c.x, y: c.y); ctx.scaleBy(x: r.width, y: r.height) - ctx.drawRadialGradient(g, startCenter: .zero, startRadius: 0, endCenter: .zero, endRadius: 1, options: [.drawsAfterEndLocation]) - case .conic: - break + guard case .radial(let c, let r) = place, + let g = CGGradient(colorsSpace: CGColorSpace(name: linear(dark: dark) ? CGColorSpace.extendedLinearSRGB : CGColorSpace.sRGB), colors: colors as CFArray, locations: locations) else { return } + ctx.translateBy(x: c.x, y: c.y); ctx.scaleBy(x: r.width, y: r.height) + ctx.drawRadialGradient(g, startCenter: .zero, startRadius: 0, endCenter: .zero, endRadius: 1, options: [.drawsAfterEndLocation]) + } + + /// A linear ramp from `start` to `end` over the clip, its stops + /// `locations` along that line. + func paintAxial(_ ctx: CGContext, start a: CGPoint, end b: CGPoint, locations: [CGFloat], colors: [CGColor], dark: Bool) { + let cuts = locations.indices.dropFirst().filter { + locations[$0] == locations[$0 - 1] && locations[$0] > locations[0] && locations[$0] < locations.last! } + if !cuts.isEmpty { + paintAxialRuns(ctx, start: a, end: b, locations: locations, colors: colors, cuts: Array(cuts), dark: dark) + return + } + guard let g = CGGradient(colorsSpace: CGColorSpace(name: linear(dark: dark) ? CGColorSpace.extendedLinearSRGB : CGColorSpace.sRGB), colors: colors as CFArray, locations: locations) else { return } + ctx.drawLinearGradient(g, start: a, end: b, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]) } /// Core Graphics quantizes hard stops inside a ramp: an expanded hatch @@ -430,6 +433,10 @@ extension NodeView { // A fixed gradient is the layer's (LLP 1066 D7). if gradientLayered && boxGradient != nil { return } #endif + #if os(iOS) || os(tvOS) + // Tiles are their layers' (`GradientTilesIOS.swift`). + if gradientTiles?.layer != nil { return } + #endif // The last layer first, so the first is on top (LLP 1077 D5). for g in Gradient.layers(style["background_image"], tint: gradientTint).reversed() { g.paint(ctx, clip: clip, box: gradientBox, dark: drawsDark) diff --git a/host/apple/Sources/ExactKit/GradientTile.swift b/host/apple/Sources/ExactKit/GradientTile.swift new file mode 100644 index 000000000..50b2f1260 --- /dev/null +++ b/host/apple/Sources/ExactKit/GradientTile.swift @@ -0,0 +1,188 @@ +// A repeating linear gradient as tiles of device pixels. Its stripes run +// across the box at one angle, so the picture repeats along each axis after +// the period divided by that axis's share of the gradient line: tiles about +// that size fall at nearly the same place in a period, and those that fall +// at the same place share one picture. +import CoreGraphics +import Foundation + +extension Gradient { + /// One period of a repeating linear gradient whose stops are all + /// lengths, so it is the same period at every box size. + struct Period { + /// The resolved gradient: its colour space. + fileprivate let ramp: Gradient + fileprivate let dark: Bool + /// The gradient line's unit direction, y down. + let direction: CGPoint + /// Points along the line. + let length: CGFloat + /// Where a period begins, in points along the line from the + /// corner the line starts at (CSS places the line's start on the + /// perpendicular through that corner), 0 up to `length`. + let offset: CGFloat + /// One period's stops, 0 to 1 of it. + let locations: [CGFloat] + let colors: [CGColor] + } + + /// The period, when the gradient is a repeating linear one whose + /// period and place along the line do not change with the box: no + /// percentage stop and no `to `, which it checks by resolving + /// at two sizes. A percentage that an earlier length stop clamps at + /// both sizes is free at a larger one, so any percentage is refused + /// first: the kernel writes colours as hex, so a `%` is a stop. + func period(dark: Bool) -> Period? { + guard let css = dark ? darkCss ?? css : css, css.hasPrefix("repeating-linear-gradient("), !css.contains("%") else { return nil } + let boxes = [CGRect(x: 0, y: 0, width: 1000, height: 1000), CGRect(x: 0, y: 0, width: 1037, height: 1291)] + let periods = boxes.compactMap { box in resolved(in: box, dark: dark)?.cycle(in: box, dark: dark) } + guard periods.count == 2, periods[0].matches(periods[1]) else { return nil } + return periods[0] + } + + /// The resolved gradient's whole periods, laid end to end from the + /// line's start (`placed.rs`), as one period. + private func cycle(in box: CGRect, dark: Bool) -> Period? { + guard case .angle = shape, !linear(dark: dark), case .axial(let a, let b) = placement(in: box) else { return nil } + let (locations, colors) = stops(dark: dark) + let span = hypot(b.x - a.x, b.y - a.y), n = locations.count + guard n >= 2, span > 0 else { return nil } + // Premultiplying can add a stop where one period meets the next, + // which the line's start has none of, so the stop count need not + // divide evenly: a period is the shortest run from the first stop + // that the rest repeats, at least twice over. + guard let count = (1...(n / 2)).first(where: { q in + let d = locations[q] - locations[0] + return d > 0 && (q.. CGPoint { + CGPoint(x: u.x > 0 ? box.minX : box.maxX, y: u.y > 0 ? box.minY : box.maxY) + } +} + +extension Gradient.Period { + fileprivate func matches(_ other: Gradient.Period) -> Bool { + let tolerance: CGFloat = 1e-3 + var shift = abs(offset - other.offset) + shift = min(shift, length - shift) + return abs(length - other.length) < tolerance && shift < tolerance + && abs(direction.x - other.direction.x) < 1e-6 && abs(direction.y - other.direction.y) < 1e-6 + && locations.count == other.locations.count && colors == other.colors + && zip(locations, other.locations).allSatisfy { abs($0 - $1) < 1e-4 } + } + + /// A tile's device pixels along each axis: a whole number of pixels + /// that comes closest to whole periods, so that tiles fall at nearly + /// the same place in a period and share pictures, grown to about 256 + /// so a box needs few tiles; 256 along an axis the stripes run along, + /// or one too long to repeat within 512. + func tile(scale: CGFloat) -> (width: Int, height: Int) { + func side(_ share: CGFloat) -> Int { + let limit = 512 + let repeats = share == 0 ? .infinity : length * scale / abs(share) + guard repeats <= CGFloat(limit) else { return 256 } + var best = (pixels: 256, error: CGFloat.infinity) + for k in 1...Int(CGFloat(limit) / repeats) { + let exact = repeats * CGFloat(k), pixels = max(1, Int(exact.rounded())) + let error = abs(exact - CGFloat(pixels)) / CGFloat(pixels) + if error < best.error - 1e-12 { best = (pixels, error) } + } + return best.pixels * max(1, 256 / best.pixels) + } + return (side(direction.x), side(direction.y)) + } + + /// Tiles over a layer's `bounds` for a gradient box `box`. + struct Layout { + /// One tile's device pixels. + let width: Int, height: Int + /// The first tile's top left, from the bounds' top left: at most a + /// tile up and left of it, in whole device pixels. + let origin: CGPoint + let columns: Int, rows: Int + /// The tile at the start corner, and how far along the line its + /// top left is past where a period begins, in points. + let anchor: (column: Int, row: Int) + let phase: CGFloat + /// How much further along the line each column and row is, in points. + let column: CGFloat, row: CGFloat + } + + /// The tiles start from the device pixel of the corner the line starts + /// at, so a size that moves that corner by whole pixels moves them and + /// leaves each tile's picture as it was. A size that moves it within a + /// pixel changes every tile's phase and draws their pictures again; a + /// sheet dragged on the iOS simulator was sized in whole pixels. + func layout(box: CGRect, bounds: CGRect, scale: CGFloat) -> Layout? { + guard bounds.width > 0, bounds.height > 0 else { return nil } + let (w, h) = tile(scale: scale), (tw, th) = (CGFloat(w), CGFloat(h)), u = direction + let corner = Gradient.startCorner(of: box, direction: u) + let ax = ((corner.x - bounds.minX) * scale).rounded(), ay = ((corner.y - bounds.minY) * scale).rounded() + let (jx, jy) = ((ax / tw).rounded(.up), (ay / th).rounded(.up)) + let gx = ax - tw * jx, gy = ay - th * jy + // The tile inside the box at the corner: right of and below it, or left of and above it. + let (column, row) = (Int(jx) - (u.x > 0 ? 0 : 1), Int(jy) - (u.y > 0 ? 0 : 1)) + let top = CGPoint(x: bounds.minX + (gx + CGFloat(column) * tw) / scale, y: bounds.minY + (gy + CGFloat(row) * th) / scale) + let along = (top.x - corner.x) * u.x + (top.y - corner.y) * u.y - offset + return Layout(width: w, height: h, origin: CGPoint(x: gx / scale, y: gy / scale), + columns: Int(((bounds.width * scale - gx) / tw).rounded(.up)), rows: Int(((bounds.height * scale - gy) / th).rounded(.up)), + anchor: (column, row), phase: along - (along / length).rounded(.down) * length, column: tw / scale * u.x, row: th / scale * u.y) + } + + /// The picture for the tile at `column`, `row`: how far its phase is + /// from the corner tile's, less whole periods, in thirty-seconds of a + /// device pixel. Tiles at the corner tile's phase share its exact + /// picture. + func key(_ layout: Layout, column: Int, row: Int, scale: CGFloat) -> Int { + let along = layout.column * CGFloat(column - layout.anchor.column) + layout.row * CGFloat(row - layout.anchor.row) + return Int(((along - (along / length).rounded() * length) * scale * 32).rounded()) + } + + /// The tile picture for `key` (`key(_:column:row:scale:)`). + func image(_ layout: Layout, key: Int, scale: CGFloat) -> CGImage? { + let along = layout.phase + CGFloat(key) / (scale * 32) + return image(width: layout.width, height: layout.height, scale: scale, phase: along - (along / length).rounded(.down) * length) + } + + /// A tile `width` × `height` device pixels at `scale` whose top left + /// is `phase` points along the line from where a period begins, drawn + /// as `Gradient.paint` draws the whole box. + func image(width: Int, height: Int, scale: CGFloat, phase: CGFloat) -> CGImage? { + guard let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } + // y down, as the view's backing store. + ctx.translateBy(x: 0, y: CGFloat(height)); ctx.scaleBy(x: scale, y: -scale) + let rect = CGRect(x: 0, y: 0, width: CGFloat(width) / scale, height: CGFloat(height) / scale) + let u = direction, origin = CGPoint(x: -u.x * phase, y: -u.y * phase) + let along = [CGPoint(x: rect.minX, y: rect.minY), CGPoint(x: rect.maxX, y: rect.minY), CGPoint(x: rect.minX, y: rect.maxY), CGPoint(x: rect.maxX, y: rect.maxY)] + .map { (($0.x - origin.x) * u.x + ($0.y - origin.y) * u.y) / length } + let first = Int(along.min()!.rounded(.down)) - 1, last = Int(along.max()!.rounded(.up)) + 1, count = last - first + var stops: [CGFloat] = [], colors: [CGColor] = [] + for c in 0.. CGPoint { CGPoint(x: origin.x + u.x * length * CGFloat(periods), y: origin.y + u.y * length * CGFloat(periods)) } + ctx.addRect(rect); ctx.clip() + ramp.paintAxial(ctx, start: point(first), end: point(last), locations: stops, colors: colors, dark: dark) + return ctx.makeImage() + } +} diff --git a/host/apple/Sources/ExactKit/IOS/BoxLayerIOS.swift b/host/apple/Sources/ExactKit/IOS/BoxLayerIOS.swift index 88ac2c05b..e0cf5deef 100644 --- a/host/apple/Sources/ExactKit/IOS/BoxLayerIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/BoxLayerIOS.swift @@ -230,6 +230,7 @@ extension NodeView { /// `draw(_:)` paints the gradient there instead, in the same place — /// unless it is `background-attachment: fixed` (`gradientLayered`). func applyGradientLayer() { + applyGradientTiles() let fixed = gradientLayered guard !cssVisibilityHidden, !drawsPaint || fixed, surface == nil, let gradient = Gradient(style["background_image"], tint: gradientTint), !gradient.needsDrawing else { boxGradient?.removeFromSuperlayer(); boxGradient = nil @@ -355,7 +356,7 @@ extension NodeView { // content painted there, or it covers the image or text. let paintsContent = (kind == "image" && symbolView == nil && raster != nil) || (isParagraph && !canRasterText) || (Capture.capturing && (kind == "canvas" || Capture.web[id] != nil)) - boxDrawn = !away && ((shapedRadii && paintsContent) || patterned || !((oneBorder || edges) && (oneRadius || shapedRadii) && (shape == nil || continuous)) || gradientDraws || backgroundClip != "border-box") && (fill != nil || gradient || widths.contains { $0 > 0 }) + boxDrawn = !away && ((shapedRadii && paintsContent) || patterned || !((oneBorder || edges) && (oneRadius || shapedRadii) && (shape == nil || continuous)) || (gradientDraws && !gradientTiled) || backgroundClip != "border-box") && (fill != nil || gradient || widths.contains { $0 > 0 }) let onLayer = !boxDrawn var corners: CACornerMask = [] let masks: [CACornerMask] = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner, .layerMinXMaxYCorner] @@ -436,10 +437,10 @@ extension NodeView { } extension NodeView { /// The box's sublayers keep CSS's paint order, all under the children: - /// shadow, gradient, inset shadow, image, border, text — whichever of + /// shadow, gradient, its tiles, inset shadow, image, border, text — whichever of /// them joins first (as `Mac/BoxLayerMac.swift`). func insertBoxSublayer(_ l: CALayer) { - let order: [CALayer?] = [shadowCaster, boxFill, boxGradient, insetCaster, imageLayer, boxBorder, textBoxLayer] + let order: [CALayer?] = [shadowCaster, boxFill, boxGradient, gradientTiles?.layer, insetCaster, imageLayer, boxBorder, textBoxLayer] guard let rank = order.firstIndex(where: { $0 === l }) else { return } if let below = order[.. 0, bounds.height > 0 else { + gradientTiles?.layer?.removeFromSuperlayer() + gradientTiles?.layer = nil + gradientTiles?.pictures = [] + return + } + CATransaction.begin(); CATransaction.setDisableActions(true) + defer { CATransaction.commit() } + let container = tiles.layer ?? CALayer() + tiles.layer = container + if container.superlayer !== layer { insertBoxSublayer(container) } + if container.frame != layer.bounds { container.frame = layer.bounds } + if layer.cornerRadius == 0 && cornerRadii(in: bounds).contains(where: { $0 > 0 }) { + let outline = (container.mask as? CAShapeLayer) ?? CAShapeLayer() + let path = roundedPath(in: bounds).cgPath + if outline.path != path { outline.path = path } + if container.mask !== outline { container.mask = outline } + if container.cornerRadius != 0 { container.cornerRadius = 0 } + } else { + if container.mask != nil { container.mask = nil } + if container.cornerRadius != layer.cornerRadius { container.cornerRadius = layer.cornerRadius } + if container.maskedCorners != layer.maskedCorners { container.maskedCorners = layer.maskedCorners } + if container.cornerCurve != layer.cornerCurve { container.cornerCurve = layer.cornerCurve } + } + if !container.masksToBounds { container.masksToBounds = true } + var holders = container.sublayers ?? [] + while holders.count < periods.count { let h = CALayer(); container.addSublayer(h); holders.append(h) } + while holders.count > periods.count { holders.removeLast().removeFromSuperlayer() } + if tiles.pictures.count != periods.count { tiles.pictures = Array(repeating: (0, 0, 0, 0, [:]), count: periods.count) } + let box = gradientBox + for (i, period) in periods.reversed().enumerated() { + guard let at = period.layout(box: box, bounds: bounds, scale: scale) else { continue } + var cache = tiles.pictures[i] + if cache.scale != scale || cache.width != at.width || cache.height != at.height || abs(cache.phase - at.phase) * scale >= 1.0 / 256 { + cache = (scale, at.width, at.height, at.phase, [:]) + } + let (tw, th) = (CGFloat(at.width) / scale, CGFloat(at.height) / scale) + let holder = holders[i] + let frame = CGRect(x: at.origin.x, y: at.origin.y, width: CGFloat(at.columns) * tw, height: CGFloat(at.rows) * th) + if holder.frame != frame { holder.frame = frame } + var cells = holder.sublayers ?? [] + while cells.count < at.columns * at.rows { let c = CALayer(); holder.addSublayer(c); cells.append(c) } + while cells.count > at.columns * at.rows { cells.removeLast().removeFromSuperlayer() } + var used: Set = [] + for (k, cell) in cells.enumerated() { + let (column, row) = (k % at.columns, k / at.columns) + let key = period.key(at, column: column, row: row, scale: scale) + used.insert(key) + guard let image = cache.images[key] ?? period.image(at, key: key, scale: scale) else { continue } + cache.images[key] = image + let rect = CGRect(x: CGFloat(column) * tw, y: CGFloat(row) * th, width: tw, height: th) + if cell.frame != rect { cell.frame = rect } + if cell.contentsScale != scale { cell.contentsScale = scale } + if (cell.contents as AnyObject?) !== image { cell.contents = image } + } + // Pictures a resize took out of view stay for one coming back, up to a bound. + if cache.images.count > 2 * used.count + 16 { cache.images = cache.images.filter { used.contains($0.key) } } + tiles.pictures[i] = cache + } + } +} +#endif diff --git a/host/apple/Sources/ExactKit/IOS/NodeExtrasIOS.swift b/host/apple/Sources/ExactKit/IOS/NodeExtrasIOS.swift index c1924e006..9a936a8a5 100644 --- a/host/apple/Sources/ExactKit/IOS/NodeExtrasIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/NodeExtrasIOS.swift @@ -72,6 +72,8 @@ final class NodePaintExtras { var boxGradient: CAGradientLayer? /// What a fixed gradient was last aimed with (`reaimFixedGradient`). var aimedGradient: AimedGradient? + /// Repeating gradients painted as tiles (`GradientTilesIOS.swift`). + var gradientTiles: GradientTiles? /// `box-shadow` and the clip it casts outside (`BoxShadow.swift`). var shadowCaster: ShadowCaster? /// Inset `box-shadow`s (LLP 1077 D4). @@ -304,6 +306,7 @@ extension NodeView { var boxFill: CALayer? { get { paintExtras?.boxFill } set { if newValue != nil || paintExtras != nil { paintMore.boxFill = newValue } } } var boxGradient: CAGradientLayer? { get { paintExtras?.boxGradient } set { if newValue != nil || paintExtras != nil { paintMore.boxGradient = newValue } } } var aimedGradient: AimedGradient? { get { paintExtras?.aimedGradient } set { if newValue != nil || paintExtras != nil { paintMore.aimedGradient = newValue } } } + var gradientTiles: GradientTiles? { get { paintExtras?.gradientTiles } set { if newValue != nil || paintExtras != nil { paintMore.gradientTiles = newValue } } } var shadowCaster: ShadowCaster? { get { paintExtras?.shadowCaster } set { if newValue != nil || paintExtras != nil { paintMore.shadowCaster = newValue } } } var insetCaster: InsetShadowCaster? { get { paintExtras?.insetCaster } set { if newValue != nil || paintExtras != nil { paintMore.insetCaster = newValue } } } var clipBox: PlainView? { get { extras?.clipBox } set { if newValue != nil || extras != nil { more.clipBox = newValue } } } diff --git a/host/apple/tests/ExactKitTests/GradientTileTests.swift b/host/apple/tests/ExactKitTests/GradientTileTests.swift new file mode 100644 index 000000000..23e700e85 --- /dev/null +++ b/host/apple/tests/ExactKitTests/GradientTileTests.swift @@ -0,0 +1,127 @@ +import CoreGraphics +import XCTest +@testable import ExactKit + +/// Repeating gradients as tiles (`GradientTile.swift`), held to the whole box +/// as `Gradient.paint` draws it, which is what a node's `draw(_:)` paints. +final class GradientTileTests: XCTestCase { + /// Two faint diagonal hatches, as a sheet's page texture. + static let hatch = ["repeating-linear-gradient(45deg, rgba(0,0,0,0.07) 0px 2px, transparent 2px 5px)", + "repeating-linear-gradient(-45deg, rgba(255,220,170,0.07) 0px 2px, transparent 2px 6px)"] + static let grid = ["repeating-linear-gradient(0deg, #dfe7f1 0px 1px, transparent 1px 14px)", + "repeating-linear-gradient(90deg, #dfe7f1 0px 1px, transparent 1px 14px)"] + /// Opaque stripes, where a stripe out of place shows most. + static let contrast = "repeating-linear-gradient(30deg, #000 0px 3px, #fff 3px 7px)" + /// The Chrome parity page's hatch (`GradientParity`). + static let parityHatch = "repeating-linear-gradient(-45deg, transparent 0 4.243px, #e6e6e6 4.243px 5.657px)" + + static func gradient(_ css: String) -> Gradient { Gradient(["css": .string(css)] as BatchValue)! } + + static func pixels(_ image: CGImage) -> [UInt8] { + let ctx = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + ctx.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) + return Array(UnsafeBufferPointer(start: ctx.data!.assumingMemoryBound(to: UInt8.self), count: image.width * image.height * 4)) + } + + /// The tiles as a node's layers place them over a box of `size`. + static func tiled(_ period: Gradient.Period, size: CGSize, scale: CGFloat) -> CGImage { + let rect = CGRect(origin: .zero, size: size), at = period.layout(box: rect, bounds: rect, scale: scale)! + let (w, h) = (Int((size.width * scale).rounded(.up)), Int((size.height * scale).rounded(.up))) + let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + for row in 0.. Set { + let rect = CGRect(origin: .zero, size: size), at = period.layout(box: rect, bounds: rect, scale: scale)! + return Set((0.. (mean: Double, beyond: Double) { + var (sum, beyond) = (0, 0) + for p in stride(from: 0, to: a.count, by: 4) { + var far = false + for k in 0..<4 { let d = abs(Int(a[p + k]) - Int(b[p + k])); sum += d; far = far || d > by } + beyond += far ? 1 : 0 + } + return (Double(sum) / Double(a.count), Double(beyond) / Double(a.count / 4)) + } + + func testTexturesTakeTiles() { + for css in Self.hatch + Self.grid + [Self.contrast] { + XCTAssertNotNil(Self.gradient(css).period(dark: false), css) + } + } + + /// A phone-sized box takes few tiles and fewer pictures, including + /// for a period a hair off a whole number of pixels. + func testAPhoneSizedBoxTakesFewTiles() { + for scale: CGFloat in [1, 2, 3] { + for css in Self.hatch + Self.grid + [Self.contrast, Self.parityHatch] { + let period = Self.gradient(css).period(dark: false)!, rect = CGRect(x: 0, y: 0, width: 402, height: 874) + let at = period.layout(box: rect, bounds: rect, scale: scale)!, pictures = Self.keys(period, size: rect.size, scale: scale).count + print("tiles \(css) at \(scale)x: \(at.width)×\(at.height) px, \(at.columns * at.rows) tiles, \(pictures) pictures") + XCTAssertLessThanOrEqual(at.columns * at.rows, 120, "\(css) at \(scale)x") + XCTAssertLessThanOrEqual(pictures, 32, "\(css) at \(scale)x") + } + } + } + + func testWhatATileCannotSayStaysDrawn() { + for css in ["repeating-linear-gradient(45deg, red 0 10%, blue 10% 20%)", + "repeating-linear-gradient(90deg, red 0px 20px, blue 1% 30px)", + "repeating-linear-gradient(to top right, red 0 2px, blue 2px 5px)", + "linear-gradient(45deg, red, blue)"] { + XCTAssertNil(Self.gradient(css).period(dark: false), css) + } + } + + /// Two heights a whole number of pixels apart, neither a whole number + /// of periods, as a sheet's page has while it is dragged. + func testTilesPaintWhatTheBoxDraws() { + for scale: CGFloat in [1, 2, 3] { + for css in Self.hatch + Self.grid + [Self.contrast, Self.parityHatch] { + let gradient = Self.gradient(css), period = gradient.period(dark: false)! + for size in [CGSize(width: 100, height: 70), CGSize(width: 190, height: 150), CGSize(width: 190, height: 150 + 37 / scale)] { + let drawn = Self.pixels(gradient.image(size: size, scale: scale, dark: false)!) + let tiled = Self.pixels(Self.tiled(period, size: size, scale: scale)) + let (mean, beyond) = Self.difference(drawn, tiled, by: 2) + print("tiles \(css) \(size.height) at \(scale)x: mean \(String(format: "%.4f", mean)), \(String(format: "%.3f", beyond * 100))% beyond 2") + // A tile's phase is a thirty-second of a pixel: an opaque + // edge moves by up to a sixty-fourth. + XCTAssertLessThan(mean, 0.5, "\(css) \(size) at \(scale)x") + XCTAssertLessThan(beyond, 0.01, "\(css) \(size) at \(scale)x") + } + } + } + } + + /// A height that moves the corner the stripes start from by whole + /// pixels keeps the tiles' pictures: a sheet dragged shorter draws + /// nothing. + func testWholePixelResizeKeepsThePictures() { + for scale: CGFloat in [2, 3] { + for css in Self.hatch { + let period = Self.gradient(css).period(dark: false)!, tall = CGSize(width: 402, height: 700) + let before = Self.keys(period, size: tall, scale: scale), rect = CGRect(origin: .zero, size: tall) + let phase = period.layout(box: rect, bounds: rect, scale: scale)!.phase + for pixels in 1...300 { + let size = CGSize(width: 402, height: 700 - CGFloat(pixels) / scale), shorter = CGRect(origin: .zero, size: size) + XCTAssertEqual(period.layout(box: shorter, bounds: shorter, scale: scale)!.phase, phase, accuracy: 1 / (256 * scale)) + XCTAssert(Self.keys(period, size: size, scale: scale).isSubset(of: before), "\(css) -\(pixels) px at \(scale)x") + } + } + } + } +} diff --git a/host/apple/tests/ExactKitTests/GradientTilesIOSTests.swift b/host/apple/tests/ExactKitTests/GradientTilesIOSTests.swift new file mode 100644 index 000000000..5c2bcf283 --- /dev/null +++ b/host/apple/tests/ExactKitTests/GradientTilesIOSTests.swift @@ -0,0 +1,83 @@ +#if os(iOS) +import UIKit +import XCTest +@testable import ExactKit + +/// A node whose background is repeating gradients paints them as tiles +/// (`GradientTilesIOS.swift`) and keeps no bitmap of its own. +final class GradientTilesIOSTests: XCTestCase { + private let ground: [Double] = [251, 246, 238, 255] + + private func node(size: CGSize, scale: CGFloat) -> NodeView { + let p = Presenter() + let node = NodeView(id: 1, kind: "view", presenter: p) + p.views[node.id] = node + let window = UIWindow(frame: CGRect(origin: .zero, size: CGSize(width: 400, height: 800))) + window.addSubview(node) + node.frame = CGRect(origin: .zero, size: size) + node.contentScaleFactor = scale + node.applyStyle(["background_color": .array(ground.map { .number($0) }), + "background_image": .array(GradientTileTests.hatch.map { ["css": .string($0)] as BatchValue })]) + node.layer.displayIfNeeded() + return node + } + + /// The node's layers, as Core Animation's `render(in:)` composites them. + private func rendered(_ node: NodeView, scale: CGFloat) -> [UInt8] { + let (w, h) = (Int(node.bounds.width * scale), Int(node.bounds.height * scale)) + let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + ctx.translateBy(x: 0, y: CGFloat(h)); ctx.scaleBy(x: scale, y: -scale) + node.layer.render(in: ctx) + return GradientTileTests.pixels(ctx.makeImage()!) + } + + /// The box as `draw(_:)` paints it: the colour, then each gradient, the last first. + private func drawn(size: CGSize, scale: CGFloat) -> [UInt8] { + let (w, h) = (Int(size.width * scale), Int(size.height * scale)) + let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + ctx.translateBy(x: 0, y: CGFloat(h)); ctx.scaleBy(x: scale, y: -scale) + let rect = CGRect(origin: .zero, size: size) + ctx.setFillColor(CGColor(srgbRed: ground[0] / 255, green: ground[1] / 255, blue: ground[2] / 255, alpha: 1)); ctx.fill(rect) + for css in GradientTileTests.hatch.reversed() { + GradientTileTests.gradient(css).paint(ctx, clip: CGPath(rect: rect, transform: nil), box: rect, dark: false) + } + return GradientTileTests.pixels(ctx.makeImage()!) + } + + func testTexturedBoxKeepsNoBitmapAndResizesWithoutDrawing() { + let scale: CGFloat = 3, node = node(size: CGSize(width: 200, height: 300), scale: scale) + XCTAssertFalse(node.drawsPaint) + XCTAssertNil(node.layer.contents) + XCTAssertNotNil(node.gradientTiles?.layer) + var (mean, beyond) = GradientTileTests.difference(rendered(node, scale: scale), drawn(size: node.bounds.size, scale: scale), by: 2) + XCTAssertLessThan(mean, 0.5); XCTAssertLessThan(beyond, 0.01) + + // Shorter by whole pixels: every tile shows a picture it already had. + let before = Set((node.gradientTiles?.pictures ?? []).flatMap { $0.images.values.map(ObjectIdentifier.init) }) + node.frame.size.height = 300 - 41 / scale + node.layer.displayIfNeeded() + XCTAssertNil(node.layer.contents) + let shown = (node.gradientTiles?.layer?.sublayers ?? []).flatMap { $0.sublayers ?? [] }.compactMap { $0.contents.map { ObjectIdentifier($0 as AnyObject) } } + XCTAssertFalse(shown.isEmpty) + XCTAssert(Set(shown).isSubset(of: before), "a resize drew a tile") + (mean, beyond) = GradientTileTests.difference(rendered(node, scale: scale), drawn(size: node.bounds.size, scale: scale), by: 2) + XCTAssertLessThan(mean, 0.5); XCTAssertLessThan(beyond, 0.01) + } + + /// A dashed border draws the box, gradients and all. + func testDrawnBoxPaintsItsGradients() { + let node = node(size: CGSize(width: 120, height: 90), scale: 2) + var style = node.style + for side in ["top", "right", "bottom", "left"] { + style["border_width_" + side] = .number(2); style["border_style_" + side] = .string("dashed") + style["border_color_" + side] = .array([0.0, 0, 0, 255].map { .number($0) }) + } + node.applyStyle(style) + node.layer.displayIfNeeded() + XCTAssertTrue(node.drawsPaint) + XCTAssertNil(node.gradientTiles?.layer) + } +} +#endif