From 408c0ed39346529804dea53945732f29088e0bc3 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 14 Nov 2026 20:47:29 -0500 Subject: [PATCH 1/5] A repeating gradient background paints as tiles on iOS, so a resize draws nothing A repeating gradient made its node draw its whole box in draw(_:), and contentMode .redraw drew that bitmap again at every size. A sheet with detents is resized every frame of an interactive drag, so a sheet whose page has two diagonal repeating-linear-gradient textures re-rasterized the full-screen texture every frame. When every background layer is a repeating linear gradient whose period does not change with the box, the gradients now paint as tile cells on sublayers and the node keeps no bitmap. Tiles start from the device pixel of the corner the gradient line starts at, and each tile's picture is keyed by its phase along the line, so a resize by whole pixels moves the tiles and draws nothing. Tiles are drawn with the same code that draws the whole box. Percentage stops, to-corner directions and boxes drawn for another reason keep the drawn path. --- host/apple/Sources/ExactKit/Gradient.swift | 47 ++--- .../apple/Sources/ExactKit/GradientTile.swift | 178 ++++++++++++++++++ .../Sources/ExactKit/IOS/BoxLayerIOS.swift | 7 +- .../ExactKit/IOS/GradientTilesIOS.swift | 112 +++++++++++ .../Sources/ExactKit/IOS/NodeExtrasIOS.swift | 3 + .../ExactKitTests/GradientTileTests.swift | 108 +++++++++++ .../ExactKitTests/GradientTilesIOSTests.swift | 83 ++++++++ 7 files changed, 513 insertions(+), 25 deletions(-) create mode 100644 host/apple/Sources/ExactKit/GradientTile.swift create mode 100644 host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift create mode 100644 host/apple/tests/ExactKitTests/GradientTileTests.swift create mode 100644 host/apple/tests/ExactKitTests/GradientTilesIOSTests.swift diff --git a/host/apple/Sources/ExactKit/Gradient.swift b/host/apple/Sources/ExactKit/Gradient.swift index be320951d..b99f39e4a 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 @@ -427,8 +430,8 @@ extension NodeView { func paintGradient(_ ctx: CGContext, clip: CGPath) { guard surface == nil, !cssVisibilityHidden else { return } #if os(iOS) - // A fixed gradient is the layer's (LLP 1066 D7). - if gradientLayered && boxGradient != nil { return } + // A fixed gradient is the layer's (LLP 1066 D7), and tiles are their layers'. + if gradientLayered && boxGradient != nil || 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() { diff --git a/host/apple/Sources/ExactKit/GradientTile.swift b/host/apple/Sources/ExactKit/GradientTile.swift new file mode 100644 index 000000000..0d12e1109 --- /dev/null +++ b/host/apple/Sources/ExactKit/GradientTile.swift @@ -0,0 +1,178 @@ +// 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. + func period(dark: Bool) -> Period? { + guard css?.hasPrefix("repeating-linear-gradient(") == true 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: the whole number of pixels + /// up to 512 that comes closest to whole periods, so that tiles next to + /// each other fall at the same place in a period and share a picture; + /// 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) } + } + // Fewer, larger tiles where a small one repeats exactly. + return best.pixels * max(1, (best.error < 1e-6 ? 256 : 1) / best.pixels) + } + return (side(direction.x), side(direction.y)) + } + + /// Tiles over a layer's `bounds` for a gradient box `box`. + struct Layout: Equatable { + /// 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 + /// How far along the line the first tile's top left is past where + /// a period begins, and how much further each column and row is, + /// in points. + let phase: CGFloat, 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. + 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 anchor = Gradient.startCorner(of: box, direction: u) + let ax = ((anchor.x - bounds.minX) * scale).rounded(), ay = ((anchor.y - bounds.minY) * scale).rounded() + let gx = ax - tw * (ax / tw).rounded(.up), gy = ay - th * (ay / th).rounded(.up) + let along = (bounds.minX + gx / scale - anchor.x) * u.x + (bounds.minY + gy / scale - anchor.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)), + phase: along, column: tw / scale * u.x, row: th / scale * u.y) + } + + /// The picture for the tile at `column`, `row`: its phase in + /// thirty-seconds of a device pixel, which tiles that fall at the same + /// place in a period share. + func key(_ layout: Layout, column: Int, row: Int, scale: CGFloat) -> Int { + let along = layout.phase + layout.column * CGFloat(column) + layout.row * CGFloat(row) + let phase = along - (along / length).rounded(.down) * length + return Int((phase * scale * 32).rounded()) + } + + /// The tile picture for `key` (`key(_:column:row:scale:)`). + func image(_ layout: Layout, key: Int, scale: CGFloat) -> CGImage? { + image(width: layout.width, height: layout.height, scale: scale, phase: CGFloat(key) / (scale * 32)) + } + + /// 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, [:]), 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 { cache = (scale, at.width, at.height, [:]) } + 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..e896987bd --- /dev/null +++ b/host/apple/tests/ExactKitTests/GradientTileTests.swift @@ -0,0 +1,108 @@ +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)" + + 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) + } + } + + func testWhatATileCannotSayStaysDrawn() { + for css in ["repeating-linear-gradient(45deg, red 0 10%, blue 10% 20%)", + "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 [2, 3] { + for css in Self.hatch + Self.grid + [Self.contrast] { + let gradient = Self.gradient(css), period = gradient.period(dark: false)! + for size in [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) + for pixels in 1...300 { + let after = Self.keys(period, size: CGSize(width: 402, height: 700 - CGFloat(pixels) / scale), scale: scale) + XCTAssert(after.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 From c331287266f5cc81364a1e6ac3b390eb01c0b835 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 14 Nov 2026 21:07:56 -0500 Subject: [PATCH 2/5] A repeating gradient with any percentage stop keeps the drawn path CSS fix-up can clamp a percentage stop to an earlier length stop at both of the sizes the period is checked at and leave it free at a larger box, so the two-size check alone accepted a period that changes with the box. --- host/apple/Sources/ExactKit/GradientTile.swift | 6 ++++-- host/apple/tests/ExactKitTests/GradientTileTests.swift | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/host/apple/Sources/ExactKit/GradientTile.swift b/host/apple/Sources/ExactKit/GradientTile.swift index 0d12e1109..976d532d1 100644 --- a/host/apple/Sources/ExactKit/GradientTile.swift +++ b/host/apple/Sources/ExactKit/GradientTile.swift @@ -29,9 +29,11 @@ extension Gradient { /// 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. + /// 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 css?.hasPrefix("repeating-linear-gradient(") == true else { return nil } + guard let 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 } diff --git a/host/apple/tests/ExactKitTests/GradientTileTests.swift b/host/apple/tests/ExactKitTests/GradientTileTests.swift index e896987bd..1abaf77b6 100644 --- a/host/apple/tests/ExactKitTests/GradientTileTests.swift +++ b/host/apple/tests/ExactKitTests/GradientTileTests.swift @@ -64,6 +64,7 @@ final class GradientTileTests: XCTestCase { 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) From 7f7fe491cf3b3ba659a4033961b76753c4aa97dc Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 14 Nov 2026 21:13:53 -0500 Subject: [PATCH 3/5] A tile grows to about 256 pixels whatever its period's fit A period a hair off a whole number of pixels kept a tile one period wide, thousands of tile layers over a phone screen. Each tile carries its own phase, so its size only decides how many tiles share a picture. The tvOS build, which compiles the tiles too, also leaves a tiled gradient to them in draw(_:). --- host/apple/Sources/ExactKit/Gradient.swift | 8 ++++++-- host/apple/Sources/ExactKit/GradientTile.swift | 17 +++++++++-------- .../tests/ExactKitTests/GradientTileTests.swift | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/host/apple/Sources/ExactKit/Gradient.swift b/host/apple/Sources/ExactKit/Gradient.swift index b99f39e4a..574aafba4 100644 --- a/host/apple/Sources/ExactKit/Gradient.swift +++ b/host/apple/Sources/ExactKit/Gradient.swift @@ -430,8 +430,12 @@ extension NodeView { func paintGradient(_ ctx: CGContext, clip: CGPath) { guard surface == nil, !cssVisibilityHidden else { return } #if os(iOS) - // A fixed gradient is the layer's (LLP 1066 D7), and tiles are their layers'. - if gradientLayered && boxGradient != nil || gradientTiles?.layer != nil { return } + // 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() { diff --git a/host/apple/Sources/ExactKit/GradientTile.swift b/host/apple/Sources/ExactKit/GradientTile.swift index 976d532d1..0caacc5ba 100644 --- a/host/apple/Sources/ExactKit/GradientTile.swift +++ b/host/apple/Sources/ExactKit/GradientTile.swift @@ -88,11 +88,11 @@ extension Gradient.Period { && zip(locations, other.locations).allSatisfy { abs($0 - $1) < 1e-4 } } - /// A tile's device pixels along each axis: the whole number of pixels - /// up to 512 that comes closest to whole periods, so that tiles next to - /// each other fall at the same place in a period and share a picture; - /// 256 along an axis the stripes run along, or one too long to repeat - /// within 512. + /// 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 @@ -104,8 +104,7 @@ extension Gradient.Period { let error = abs(exact - CGFloat(pixels)) / CGFloat(pixels) if error < best.error - 1e-12 { best = (pixels, error) } } - // Fewer, larger tiles where a small one repeats exactly. - return best.pixels * max(1, (best.error < 1e-6 ? 256 : 1) / best.pixels) + return best.pixels * max(1, 256 / best.pixels) } return (side(direction.x), side(direction.y)) } @@ -126,7 +125,9 @@ extension Gradient.Period { /// 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. + /// 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 diff --git a/host/apple/tests/ExactKitTests/GradientTileTests.swift b/host/apple/tests/ExactKitTests/GradientTileTests.swift index 1abaf77b6..de0fe38c3 100644 --- a/host/apple/tests/ExactKitTests/GradientTileTests.swift +++ b/host/apple/tests/ExactKitTests/GradientTileTests.swift @@ -62,6 +62,21 @@ final class GradientTileTests: XCTestCase { } } + /// A phone-sized box takes few tiles and fewer pictures, including + /// for a period a hair off a whole number of pixels. + func testAPhoneSizedBoxTakesFewTiles() { + let hatch = "repeating-linear-gradient(-45deg, transparent 0 4.243px, #e6e6e6 4.243px 5.657px)" + for scale: CGFloat in [1, 2, 3] { + for css in Self.hatch + Self.grid + [Self.contrast, hatch] { + 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)", From 47b2e571983c135e3836c4f9e055ec6023fe4975 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 14 Nov 2026 21:33:10 -0500 Subject: [PATCH 4/5] Tile pictures take their phase from the tile at the gradient's start corner The corner tile drew with the corner pixel's phase while its top left sits a tile away, a few thousandths of a point off where its period is not a whole number of pixels. That moved every stripe edge that falls on a pixel centre, as the Chrome parity page's hatch does. Each picture is now keyed by its phase's distance from the corner tile's, which draws exactly. --- .../apple/Sources/ExactKit/GradientTile.swift | 41 +++++++++++-------- .../ExactKit/IOS/GradientTilesIOS.swift | 10 +++-- .../ExactKitTests/GradientTileTests.swift | 19 +++++---- 3 files changed, 41 insertions(+), 29 deletions(-) diff --git a/host/apple/Sources/ExactKit/GradientTile.swift b/host/apple/Sources/ExactKit/GradientTile.swift index 0caacc5ba..a33f6b22c 100644 --- a/host/apple/Sources/ExactKit/GradientTile.swift +++ b/host/apple/Sources/ExactKit/GradientTile.swift @@ -110,17 +110,19 @@ extension Gradient.Period { } /// Tiles over a layer's `bounds` for a gradient box `box`. - struct Layout: Equatable { + 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 - /// How far along the line the first tile's top left is past where - /// a period begins, and how much further each column and row is, - /// in points. - let phase: CGFloat, column: CGFloat, row: CGFloat + /// 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 @@ -131,27 +133,32 @@ extension Gradient.Period { 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 anchor = Gradient.startCorner(of: box, direction: u) - let ax = ((anchor.x - bounds.minX) * scale).rounded(), ay = ((anchor.y - bounds.minY) * scale).rounded() - let gx = ax - tw * (ax / tw).rounded(.up), gy = ay - th * (ay / th).rounded(.up) - let along = (bounds.minX + gx / scale - anchor.x) * u.x + (bounds.minY + gy / scale - anchor.y) * u.y - offset + 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)), - phase: along, column: tw / scale * u.x, row: th / scale * u.y) + 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`: its phase in - /// thirty-seconds of a device pixel, which tiles that fall at the same - /// place in a period share. + /// 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.phase + layout.column * CGFloat(column) + layout.row * CGFloat(row) - let phase = along - (along / length).rounded(.down) * length - return Int((phase * scale * 32).rounded()) + 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? { - image(width: layout.width, height: layout.height, scale: scale, phase: CGFloat(key) / (scale * 32)) + 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 diff --git a/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift b/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift index c13e36f1b..39cc89bb5 100644 --- a/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift @@ -16,8 +16,8 @@ final class GradientTiles { /// layer of tiles for each gradient, the last first. var layer: CALayer? /// Each gradient's tile pictures by key (`Gradient.Period.key`), at a - /// scale and tile size. - var pictures: [(scale: CGFloat, width: Int, height: Int, images: [Int: CGImage])] = [] + /// scale, tile size and start corner phase. + var pictures: [(scale: CGFloat, width: Int, height: Int, phase: CGFloat, images: [Int: CGImage])] = [] init(source: BatchValue, dark: Bool, periods: [Gradient.Period]?) { self.source = source; self.dark = dark; self.periods = periods @@ -78,12 +78,14 @@ extension NodeView { 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, [:]), count: periods.count) } + 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 { cache = (scale, at.width, at.height, [:]) } + 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) diff --git a/host/apple/tests/ExactKitTests/GradientTileTests.swift b/host/apple/tests/ExactKitTests/GradientTileTests.swift index de0fe38c3..23e700e85 100644 --- a/host/apple/tests/ExactKitTests/GradientTileTests.swift +++ b/host/apple/tests/ExactKitTests/GradientTileTests.swift @@ -12,6 +12,8 @@ final class GradientTileTests: XCTestCase { "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)! } @@ -65,9 +67,8 @@ final class GradientTileTests: XCTestCase { /// A phone-sized box takes few tiles and fewer pictures, including /// for a period a hair off a whole number of pixels. func testAPhoneSizedBoxTakesFewTiles() { - let hatch = "repeating-linear-gradient(-45deg, transparent 0 4.243px, #e6e6e6 4.243px 5.657px)" for scale: CGFloat in [1, 2, 3] { - for css in Self.hatch + Self.grid + [Self.contrast, hatch] { + 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") @@ -89,10 +90,10 @@ final class GradientTileTests: XCTestCase { /// 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 [2, 3] { - for css in Self.hatch + Self.grid + [Self.contrast] { + 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: 190, height: 150), CGSize(width: 190, height: 150 + 37 / scale)] { + 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) @@ -113,10 +114,12 @@ final class GradientTileTests: XCTestCase { 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) + 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 after = Self.keys(period, size: CGSize(width: 402, height: 700 - CGFloat(pixels) / scale), scale: scale) - XCTAssert(after.isSubset(of: before), "\(css) -\(pixels) px at \(scale)x") + 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") } } } From 2440dac02469e665228d3d114b09462173245fec Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Sat, 14 Nov 2026 23:10:56 -0500 Subject: [PATCH 5/5] Tiles read a gradient's dark-scheme source and the view's tint A gradient that interpolates differently in the dark scheme carries a source of its own there, and one that names AccentColor resolves with the view's tint. The period comes from the source for the appearance, and the tiles are drawn again when the tint changes. --- host/apple/Sources/ExactKit/GradientTile.swift | 2 +- .../Sources/ExactKit/IOS/GradientTilesIOS.swift | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/host/apple/Sources/ExactKit/GradientTile.swift b/host/apple/Sources/ExactKit/GradientTile.swift index a33f6b22c..50b2f1260 100644 --- a/host/apple/Sources/ExactKit/GradientTile.swift +++ b/host/apple/Sources/ExactKit/GradientTile.swift @@ -33,7 +33,7 @@ extension Gradient { /// 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, css.hasPrefix("repeating-linear-gradient("), !css.contains("%") else { return nil } + 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 } diff --git a/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift b/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift index 39cc89bb5..ab01c7ec4 100644 --- a/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/GradientTilesIOS.swift @@ -9,6 +9,8 @@ import UIKit final class GradientTiles { let source: BatchValue let dark: Bool + /// The view's tint, which a gradient's `AccentColor` stop takes. + let tint: UIColor? /// Each gradient's period, first on top; nil when one is not a repeating /// linear gradient a tile can paint. let periods: [Gradient.Period]? @@ -19,8 +21,8 @@ final class GradientTiles { /// scale, tile size and start corner phase. var pictures: [(scale: CGFloat, width: Int, height: Int, phase: CGFloat, images: [Int: CGImage])] = [] - init(source: BatchValue, dark: Bool, periods: [Gradient.Period]?) { - self.source = source; self.dark = dark; self.periods = periods + init(source: BatchValue, dark: Bool, tint: UIColor?, periods: [Gradient.Period]?) { + self.source = source; self.dark = dark; self.tint = tint; self.periods = periods } } @@ -29,10 +31,10 @@ extension NodeView { /// gradient whose period is the same at every size. private var gradientPeriods: [Gradient.Period]? { guard let source = style["background_image"] else { return nil } - let dark = drawsDark - if let tiles = gradientTiles, tiles.source == source, tiles.dark == dark { return tiles.periods } - let layers = Gradient.layers(source), periods = layers.compactMap { $0.period(dark: dark) } - let made = GradientTiles(source: source, dark: dark, periods: !layers.isEmpty && periods.count == layers.count ? periods : nil) + let dark = drawsDark, tint = source.namesTint ? gradientTint : nil + if let tiles = gradientTiles, tiles.source == source, tiles.dark == dark, tiles.tint == tint { return tiles.periods } + let layers = Gradient.layers(source, tint: tint), periods = layers.compactMap { $0.period(dark: dark) } + let made = GradientTiles(source: source, dark: dark, tint: tint, periods: !layers.isEmpty && periods.count == layers.count ? periods : nil) made.layer = gradientTiles?.layer gradientTiles = made return made.periods