From a0986fa657b790f950480a7c74ba6da747d420b6 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:06 -0500 Subject: [PATCH 1/7] Added Silica's Android backend, moved from Silica --- Sources/AndroidSilica/AndroidBackend.swift | 164 +++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 Sources/AndroidSilica/AndroidBackend.swift diff --git a/Sources/AndroidSilica/AndroidBackend.swift b/Sources/AndroidSilica/AndroidBackend.swift new file mode 100644 index 0000000..eedad86 --- /dev/null +++ b/Sources/AndroidSilica/AndroidBackend.swift @@ -0,0 +1,164 @@ +// +// AndroidBackend.swift +// AndroidSilica +// +// Created by Alsey Coleman Miller on 7/13/26. +// Copyright © 2026 PureSwift. All rights reserved. +// + +#if canImport(AndroidGraphics) + +import AndroidGraphics +import SwiftJava +import JavaIO +import JavaLangIO +import Foundation +import Silica + +/// Android Canvas rendering backend. +public enum AndroidBackend: SilicaBackendProtocol { + + /// Registers Android as the default rendering backend. + public static func register() { + + SilicaBackend.default = AndroidBackend.self + } + + internal static func registerIfNeeded() { + + guard SilicaBackend.default == nil else { return } + register() + } + + // MARK: - SilicaBackendProtocol + + public static func font(named name: String) -> Silica.CGFont? { + + guard let handle = AndroidFontHandle(name: name) + else { return nil } + + return Silica.CGFont(name: name, family: handle.familyName, handle: handle) + } + + public static func decodePNG(_ data: Data) -> Silica.CGImage? { + + let bytes = data.map { Int8(bitPattern: $0) } + + guard let factoryClass = try? JavaClass(), + let bitmap = factoryClass.decodeByteArray(bytes, 0, Int32(bytes.count)) + else { return nil } + + return Silica.CGImage(bitmap) + } + + public static func encodePNG(_ image: Silica.CGImage) -> Data? { + + guard let bitmap = image.toAndroidBitmap() + else { return nil } + + let stream = ByteArrayOutputStream() + + guard bitmap.compress(Bitmap.CompressFormat(.PNG), 100, stream) + else { return nil } + + let bytes = stream.toByteArray() + + return Data(bytes.map { UInt8(bitPattern: $0) }) + } +} + +// MARK: - CGImage Conversion + +public extension Silica.CGImage { + + /// Creates a Silica bitmap image from an Android bitmap, + /// normalizing the pixel format to premultiplied RGBA. + convenience init?(_ bitmap: AndroidGraphics.Bitmap) { + + let width = Int(bitmap.getWidth()) + let height = Int(bitmap.getHeight()) + + guard width > 0, height > 0 + else { return nil } + + let bytesPerRow = width * 4 + var data = Data(count: bytesPerRow * height) + + data.withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) in + + let bytes = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self) + + for y in 0 ..< height { + + let row = bytes + (y * bytesPerRow) + + for x in 0 ..< width { + + // non-premultiplied ARGB color value + let color = UInt32(bitPattern: bitmap.getPixel(Int32(x), Int32(y))) + + let alpha = UInt8((color >> 24) & 0xFF) + let red = UInt8((color >> 16) & 0xFF) + let green = UInt8((color >> 8) & 0xFF) + let blue = UInt8(color & 0xFF) + + func premultiply(_ component: UInt8) -> UInt8 { + return UInt8((UInt16(component) * UInt16(alpha) + 127) / 255) + } + + row[x * 4] = premultiply(red) + row[x * 4 + 1] = premultiply(green) + row[x * 4 + 2] = premultiply(blue) + row[x * 4 + 3] = alpha + } + } + } + + self.init(width: width, height: height, bytesPerRow: bytesPerRow, data: data) + } + + /// Converts to an Android bitmap (`ARGB_8888`). + func toAndroidBitmap() -> AndroidGraphics.Bitmap? { + + var pixels = [Int32]() + pixels.reserveCapacity(width * height) + + data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in + + let bytes = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self) + + for y in 0 ..< height { + + let row = bytes + (y * bytesPerRow) + + for x in 0 ..< width { + + let red = row[x * 4] + let green = row[x * 4 + 1] + let blue = row[x * 4 + 2] + let alpha = row[x * 4 + 3] + + // un-premultiply into an ARGB color value + func unpremultiply(_ component: UInt8) -> UInt32 { + guard alpha > 0 else { return 0 } + return min(255, (UInt32(component) * 255 + UInt32(alpha) / 2) / UInt32(alpha)) + } + + let color: UInt32 = (UInt32(alpha) << 24) + | (unpremultiply(red) << 16) + | (unpremultiply(green) << 8) + | unpremultiply(blue) + + pixels.append(Int32(bitPattern: color)) + } + } + } + + guard let bitmapClass = try? JavaClass() + else { return nil } + + return bitmapClass.createBitmap(pixels, Int32(width), Int32(height), Bitmap.Config(.ARGB_8888)) + } +} + +#endif // canImport(AndroidGraphics) From 1b00a92779bb75b32a34d2829496644cefd67893 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:06 -0500 Subject: [PATCH 2/7] Added Silica's Android Canvas context, moved from Silica --- .../AndroidSilica/AndroidCanvasContext.swift | 898 ++++++++++++++++++ 1 file changed, 898 insertions(+) create mode 100644 Sources/AndroidSilica/AndroidCanvasContext.swift diff --git a/Sources/AndroidSilica/AndroidCanvasContext.swift b/Sources/AndroidSilica/AndroidCanvasContext.swift new file mode 100644 index 0000000..949759a --- /dev/null +++ b/Sources/AndroidSilica/AndroidCanvasContext.swift @@ -0,0 +1,898 @@ +// +// AndroidCanvasContext.swift +// AndroidSilica +// +// Created by Alsey Coleman Miller on 7/13/26. +// Copyright © 2026 PureSwift. All rights reserved. +// + +#if canImport(AndroidGraphics) + +import AndroidGraphics +import SwiftJava +import JavaIO +import JavaLangIO +import Foundation +import Silica + +/// Android Canvas backed implementation of `CGContext`. +/// +/// Android's Canvas is already a top-left origin, y-down coordinate system, so no +/// base flip is required. PDF output uses `android.graphics.pdf.PdfDocument`, +/// whose page canvas operates in points (1/72 inch). +/// +/// The current transformation matrix is tracked on the Swift side: path points are +/// transformed into device space at add time (matching Cairo and Quartz semantics) +/// and strokes are rendered under the CTM so pen geometry transforms correctly. +/// +/// - Note: `finish()` is mandatory for PDF destinations — the document is only +/// written to disk when it is called. JNI-backed objects must be used from a +/// JVM-attached thread; a context should be created, used and finished on the +/// same thread. +/// - Note: Glyph rendering requires Android API 31 (`Canvas.drawGlyphs`). +public final class AndroidCanvasContext: Silica.CGContext { + + // MARK: - Properties + + public let size: CGSize + + /// Android's Canvas is natively top-left origin, y-down. + public var isFlipped: Bool { true } + + /// The underlying Android canvas (replaced on `beginPage()` for PDF destinations). + public private(set) var canvas: AndroidGraphics.Canvas + + public var textMatrix = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) + + // MARK: - Private Properties + + private let pdfDocument: PdfDocument? + + private let pdfURL: URL? + + private let bitmap: AndroidGraphics.Bitmap? + + private var page: PdfDocument.Page? + + private var pageNumber: Int32 = 0 + + private var isFinished = false + + private var internalState: State = State() + + private var devicePath = AndroidGraphics.Path() + + /// Mirror of the current path (device space) for the `path` accessor. + private var deviceElements = [PathElement]() + + private var deviceCurrentPoint: CGPoint? + + private var deviceSubpathStart: CGPoint? + + private var saveCounts = [Int32]() + + private var layerCounts = [Int32]() + + // MARK: - Initialization + + /// Creates a PDF drawing destination at the specified file URL. + /// + /// Call `finish()` to write the document to disk. + public init(pdf url: URL, size: CGSize) throws(SilicaError) { + + let document = PdfDocument() + + self.pdfDocument = document + self.pdfURL = url + self.bitmap = nil + self.size = size + + let info = PdfDocument.PageInfo.Builder(Int32(size.width), Int32(size.height), 1).create() + + guard let page = document.startPage(info), + let canvas = page.getCanvas() + else { throw SilicaError.invalidContext } + + self.page = page + self.canvas = canvas + self.pageNumber = 1 + + AndroidBackend.registerIfNeeded() + } + + /// Creates a bitmap drawing destination of the specified size. + public init(bitmap size: CGSize) throws(SilicaError) { + + guard let bitmapClass = try? JavaClass(), + let bitmap = bitmapClass.createBitmap(Int32(size.width), Int32(size.height), Bitmap.Config(.ARGB_8888)) + else { throw SilicaError.noMemory } + + self.pdfDocument = nil + self.pdfURL = nil + self.bitmap = bitmap + self.size = size + self.canvas = Canvas(bitmap) + + AndroidBackend.registerIfNeeded() + } + + /// Wraps an existing canvas (e.g. provided to `View.onDraw`). + public init(canvas: AndroidGraphics.Canvas, size: CGSize) { + + self.pdfDocument = nil + self.pdfURL = nil + self.bitmap = nil + self.size = size + self.canvas = canvas + + AndroidBackend.registerIfNeeded() + } + + // MARK: - Defining Pages + + public func beginPage() { + + guard let document = pdfDocument, isFinished == false + else { return } + + if page != nil { + endPage() + } + + pageNumber += 1 + + let info = PdfDocument.PageInfo.Builder(Int32(size.width), Int32(size.height), pageNumber).create() + + guard let newPage = document.startPage(info), + let newCanvas = newPage.getCanvas() + else { assertionFailure("Unable to start PDF page"); return } + + page = newPage + canvas = newCanvas + saveCounts.removeAll() + layerCounts.removeAll() + } + + public func endPage() { + + guard let document = pdfDocument, let openPage = page + else { return } + + document.finishPage(openPage) + page = nil + } + + /// Writes the PDF document to disk and closes it. + /// + /// This method is mandatory for PDF destinations. + public func finish() throws(SilicaError) { + + guard isFinished == false + else { return } + + defer { isFinished = true } + + guard let document = pdfDocument, let url = pdfURL + else { return } + + if page != nil { + endPage() + } + + let stream: FileOutputStream + + do { + stream = try FileOutputStream(url.path) + } + catch { + throw SilicaError.writeError + } + + do { + try document.writeTo(stream) + try stream.close() + } + catch { + throw SilicaError.writeError + } + + document.close() + } + + // MARK: - Transforming the Coordinate Space + + public var currentTransform: CGAffineTransform { + + return internalState.ctm + } + + public func scaleBy(x: CGFloat, y: CGFloat) { + + concatenate(CGAffineTransform(a: x, b: 0, c: 0, d: y, tx: 0, ty: 0)) + } + + public func translateBy(x: CGFloat, y: CGFloat) { + + concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: x, ty: y)) + } + + public func rotateBy(_ angle: CGFloat) { + + let cosine = cos(angle) + let sine = sin(angle) + + concatenate(CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: 0, ty: 0)) + } + + public func concatenate(_ transform: CGAffineTransform) { + + // new = transform * ctm (transform applied first, in user space) + internalState.ctm = transform.multiplied(by: internalState.ctm) + } + + // MARK: - Saving and Restoring the Graphics State + + public func save() throws(SilicaError) { + + saveCounts.append(canvas.save()) + + let newState = internalState.copy + newState.next = internalState + internalState = newState + } + + public func restore() throws(SilicaError) { + + guard let restoredState = internalState.next, + let saveCount = saveCounts.popLast() + else { throw .invalidRestore } + + canvas.restoreToCount(saveCount) + internalState = restoredState + } + + // MARK: - Graphics State Attributes + + public var shouldAntialias: Bool { + + get { return internalState.shouldAntialias } + + set { internalState.shouldAntialias = newValue } + } + + public var lineWidth: CGFloat { + + get { return internalState.lineWidth } + + set { internalState.lineWidth = newValue } + } + + public var lineJoin: CGLineJoin { + + get { return internalState.lineJoin } + + set { internalState.lineJoin = newValue } + } + + public var lineCap: CGLineCap { + + get { return internalState.lineCap } + + set { internalState.lineCap = newValue } + } + + public var miterLimit: CGFloat { + + get { return internalState.miterLimit } + + set { internalState.miterLimit = newValue } + } + + public var lineDash: (phase: CGFloat, lengths: [CGFloat]) { + + get { return internalState.lineDash } + + set { internalState.lineDash = newValue } + } + + public var tolerance: CGFloat { + + get { return internalState.tolerance } + + set { internalState.tolerance = newValue } + } + + public var fillColor: CGColor { + + get { return internalState.fill ?? CGColor.black } + + set { internalState.fill = newValue } + } + + public var strokeColor: CGColor { + + get { return internalState.stroke ?? CGColor.black } + + set { internalState.stroke = newValue } + } + + public var alpha: CGFloat { + + get { return internalState.alpha } + + set { + + internalState.alpha = newValue + + // match the Cairo backend: setting alpha overwrites the color alpha + internalState.fill?.alpha = newValue + internalState.stroke?.alpha = newValue + } + } + + public func setShadow(offset: CGSize, radius: CGFloat, color: CGColor) { + + internalState.shadow = (offset: offset, radius: radius, color: color) + } + + // MARK: - Constructing Paths + + public var path: CGPath { + + let inverse = internalState.ctm.inverse + + return CGPath(elements: deviceElements.map { $0.applying(inverse) }) + } + + public var currentPoint: CGPoint? { + + guard let devicePoint = deviceCurrentPoint + else { return nil } + + return devicePoint.applying(internalState.ctm.inverse) + } + + public func beginPath() { + + devicePath.reset() + deviceElements.removeAll() + deviceCurrentPoint = nil + deviceSubpathStart = nil + } + + public func closePath() { + + devicePath.close() + deviceElements.append(.closeSubpath) + deviceCurrentPoint = deviceSubpathStart + } + + public func move(to point: CGPoint) { + + let device = point.applying(internalState.ctm) + + devicePath.moveTo(Float(device.x), Float(device.y)) + deviceElements.append(.moveToPoint(device)) + deviceCurrentPoint = device + deviceSubpathStart = device + } + + public func addLine(to point: CGPoint) { + + let device = point.applying(internalState.ctm) + + devicePath.lineTo(Float(device.x), Float(device.y)) + deviceElements.append(.addLineToPoint(device)) + deviceCurrentPoint = device + } + + public func addCurve(to end: CGPoint, control1: CGPoint, control2: CGPoint) { + + let deviceControl1 = control1.applying(internalState.ctm) + let deviceControl2 = control2.applying(internalState.ctm) + let deviceEnd = end.applying(internalState.ctm) + + devicePath.cubicTo(Float(deviceControl1.x), Float(deviceControl1.y), + Float(deviceControl2.x), Float(deviceControl2.y), + Float(deviceEnd.x), Float(deviceEnd.y)) + deviceElements.append(.addCurveToPoint(deviceControl1, deviceControl2, deviceEnd)) + deviceCurrentPoint = deviceEnd + } + + public func addArc(center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) { + + // Match Cairo's angle normalization: arcs sweep from the start angle to the + // end angle in increasing direction (decreasing when clockwise). + let start = Double(startAngle) + var end = Double(endAngle) + + if clockwise { + while end > start { end -= 2.0 * .pi } + } else { + while end < start { end += 2.0 * .pi } + } + + let radius = Double(radius) + + func point(at angle: Double) -> CGPoint { + return CGPoint(x: center.x + CGFloat(radius * Foundation.cos(angle)), + y: center.y + CGFloat(radius * Foundation.sin(angle))) + } + + let startPoint = point(at: start) + + // Cairo adds a line from the current point to the arc start (or moves to it). + if deviceCurrentPoint != nil { + addLine(to: startPoint) + } else { + move(to: startPoint) + } + + let total = end - start + + guard total != 0, radius > 0 + else { return } + + // subdivide into segments of at most 90°, lowered to cubic Béziers + let segments = max(1, Int((abs(total) / (Double.pi / 2.0)).rounded(.up))) + let delta = total / Double(segments) + let k = (4.0 / 3.0) * Foundation.tan(delta / 4.0) + + var angle1 = start + + for _ in 0 ..< segments { + + let angle2 = angle1 + delta + + let p1 = point(at: angle1) + let p2 = point(at: angle2) + + let control1 = CGPoint(x: p1.x - CGFloat(k * radius * Foundation.sin(angle1)), + y: p1.y + CGFloat(k * radius * Foundation.cos(angle1))) + let control2 = CGPoint(x: p2.x + CGFloat(k * radius * Foundation.sin(angle2)), + y: p2.y - CGFloat(k * radius * Foundation.cos(angle2))) + + addCurve(to: p2, control1: control1, control2: control2) + + angle1 = angle2 + } + } + + public func addRect(_ rect: CGRect) { + + move(to: CGPoint(x: rect.minX, y: rect.minY)) + addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) + addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) + addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) + closePath() + } + + // MARK: - Painting Paths + + public func strokePath() { + + if let shadow = internalState.shadow { + drawShadow(shadow) { canvas, paint in + self.strokeUnderTransform(paint: paint, canvas: canvas) + } + } + + strokeUnderTransform(paint: strokePaint(), canvas: canvas) + resetPath() + } + + public func fillPath(evenOdd: Bool, preserve: Bool) { + + devicePath.setFillType(Path.FillType(evenOdd ? .EVEN_ODD : .WINDING)) + + if let shadow = internalState.shadow { + drawShadow(shadow) { canvas, paint in + canvas.drawPath(self.devicePath, paint) + } + } + + canvas.drawPath(devicePath, fillPaint()) + + if preserve == false { + resetPath() + } + } + + public func clear() { + + clip(evenOdd: false) + } + + public func clip(evenOdd: Bool) { + + devicePath.setFillType(Path.FillType(evenOdd ? .EVEN_ODD : .WINDING)) + _ = canvas.clipPath(devicePath) + resetPath() + } + + // MARK: - Transparency Layers + + public func beginTransparencyLayer(in rect: CGRect?, auxiliaryInfo: CGAuxiliaryInfo?) { + + let alpha = Int32((internalState.alpha * 255).rounded()) + + let count: Int32 + + if let rect = rect { + // transform the user-space rect corners into device space and take their bounds + let corners = [ + CGPoint(x: rect.minX, y: rect.minY).applying(internalState.ctm), + CGPoint(x: rect.maxX, y: rect.minY).applying(internalState.ctm), + CGPoint(x: rect.minX, y: rect.maxY).applying(internalState.ctm), + CGPoint(x: rect.maxX, y: rect.maxY).applying(internalState.ctm) + ] + let minX = corners.map { $0.x }.min()! + let minY = corners.map { $0.y }.min()! + let maxX = corners.map { $0.x }.max()! + let maxY = corners.map { $0.y }.max()! + let bounds = RectF(Float(minX), Float(minY), Float(maxX), Float(maxY)) + count = canvas.saveLayerAlpha(bounds, alpha) + } else { + count = canvas.saveLayerAlpha(nil, alpha) + } + + layerCounts.append(count) + + let newState = internalState.copy + newState.next = internalState + newState.alpha = 1.0 + newState.shadow = nil + internalState = newState + } + + public func endTransparencyLayer() { + + guard let count = layerCounts.popLast() + else { return } + + canvas.restoreToCount(count) + + if let restoredState = internalState.next { + internalState = restoredState + } + } + + // MARK: - Drawing Images + + public func draw(_ image: CGImage, in rect: CGRect) { + + guard let bitmap = image.toAndroidBitmap() + else { assertionFailure("Unable to convert image"); return } + + // Silica's `draw(_:in:)` follows Apple's y-up image convention (callers + // flip the CTM to draw upright, as UIKit code does), so mirror the image + // vertically about the rect's centerline. + _ = canvas.save() + canvas.concat(internalState.ctm.toAndroid()) + canvas.translate(0, Float(rect.minY + rect.maxY)) + canvas.scale(1, -1) + + let destination = RectF(Float(rect.minX), Float(rect.minY), Float(rect.maxX), Float(rect.maxY)) + let paint = Paint() + paint.setAntiAlias(internalState.shouldAntialias) + canvas.drawBitmap(bitmap, nil, destination, paint) + + canvas.restore() + } + + // MARK: - Drawing Text + + public var font: CGFont? { + + return internalState.font + } + + public func setFont(_ font: CGFont) { + + internalState.font = font + } + + public var fontSize: CGFloat { + + get { return internalState.fontSize } + + set { internalState.fontSize = newValue } + } + + public var characterSpacing: CGFloat { + + get { return internalState.characterSpacing } + + set { internalState.characterSpacing = newValue } + } + + public var textDrawingMode: CGTextDrawingMode { + + get { return internalState.textMode } + + set { internalState.textMode = newValue } + } + + /// Primitive glyph rendering; positions are user-space baseline origins. + /// + /// Requires Android API 31 (`Canvas.drawGlyphs`). The linear components of the + /// text matrix (scale / rotation of glyph shapes) are not supported on Android. + public func draw(glyphs: [(glyph: CGGlyph, position: CGPoint)]) { + + guard let font = internalState.font, + fontSize > 0.0 && glyphs.isEmpty == false + else { return } + + guard let handle = font.handle as? AndroidFontHandle + else { assertionFailure("Font \(font.name) was not loaded by the Android backend"); return } + + guard internalState.textMode != .invisible + else { return } + + let paint = Paint() + paint.setAntiAlias(internalState.shouldAntialias) + paint.setColor(colorValue(internalState.fill ?? .black)) + paint.setTextSize(Float(fontSize)) + + switch internalState.textMode { + case .stroke, .strokeClip: + paint.setStyle(Paint.Style(.STROKE)) + paint.setColor(colorValue(internalState.stroke ?? .black)) + paint.setStrokeWidth(Float(internalState.lineWidth)) + case .fillStroke, .fillStrokeClip: + paint.setStyle(Paint.Style(.FILL_AND_STROKE)) + paint.setStrokeWidth(Float(internalState.lineWidth)) + default: + paint.setStyle(Paint.Style(.FILL)) + } + + _ = canvas.save() + canvas.concat(internalState.ctm.toAndroid()) + + for element in glyphs { + + let glyphFont = handle.font(for: element.glyph) ?? handle.baseFont + + canvas.drawGlyphs([Int32(element.glyph)], 0, + [Float(element.position.x), Float(element.position.y)], 0, + 1, glyphFont, paint) + } + + canvas.restore() + } + + // MARK: - Bitmap Contexts + + public func makeImage() -> CGImage? { + + guard let bitmap = self.bitmap + else { return nil } + + return CGImage(bitmap) + } + + // MARK: - Private Methods + + private func resetPath() { + + beginPath() + } + + private func fillPaint() -> Paint { + + let paint = Paint() + paint.setAntiAlias(internalState.shouldAntialias) + paint.setStyle(Paint.Style(.FILL)) + paint.setColor(colorValue(internalState.fill ?? .black)) + return paint + } + + private func strokePaint() -> Paint { + + let paint = Paint() + paint.setAntiAlias(internalState.shouldAntialias) + paint.setStyle(Paint.Style(.STROKE)) + paint.setColor(colorValue(internalState.stroke ?? .black)) + paint.setStrokeWidth(Float(internalState.lineWidth)) + paint.setStrokeMiter(Float(internalState.miterLimit)) + + switch internalState.lineCap { + case .butt: paint.setStrokeCap(Paint.Cap(.BUTT)) + case .round: paint.setStrokeCap(Paint.Cap(.ROUND)) + case .square: paint.setStrokeCap(Paint.Cap(.SQUARE)) + } + + switch internalState.lineJoin { + case .miter: paint.setStrokeJoin(Paint.Join(.MITER)) + case .round: paint.setStrokeJoin(Paint.Join(.ROUND)) + case .bevel: paint.setStrokeJoin(Paint.Join(.BEVEL)) + } + + let dash = internalState.lineDash + + if dash.lengths.isEmpty == false { + _ = paint.setPathEffect(DashPathEffect(dash.lengths.map { Float($0) }, Float(dash.phase))) + } + + return paint + } + + /// Strokes the current device-space path with the pen transformed by the CTM, + /// reproducing Cairo's stroke semantics (including non-uniform scales). + private func strokeUnderTransform(paint: Paint, canvas: AndroidGraphics.Canvas) { + + let ctm = internalState.ctm + + // transform the device path back into user space + let userPath = AndroidGraphics.Path() + devicePath.transform(ctm.inverse.toAndroid(), userPath) + + _ = canvas.save() + canvas.concat(ctm.toAndroid()) + canvas.drawPath(userPath, paint) + canvas.restore() + } + + /// Draws the shadow pass: the shape silhouette in the shadow color at the + /// shadow offset (no blur, matching the Cairo backend's emulation). + private func drawShadow(_ shadow: (offset: CGSize, radius: CGFloat, color: CGColor), + _ draw: (AndroidGraphics.Canvas, Paint) -> ()) { + + let ctm = internalState.ctm + + // the offset is specified in user space + let deviceOffset = CGSize(width: ctm.a * shadow.offset.width + ctm.c * shadow.offset.height, + height: ctm.b * shadow.offset.width + ctm.d * shadow.offset.height) + + let paint = Paint() + paint.setAntiAlias(internalState.shouldAntialias) + paint.setStyle(Paint.Style(.FILL)) + paint.setColor(colorValue(shadow.color)) + + _ = canvas.save() + canvas.translate(Float(deviceOffset.width), Float(deviceOffset.height)) + draw(canvas, paint) + canvas.restore() + } + + private func colorValue(_ color: CGColor) -> Int32 { + + func component(_ value: CGFloat) -> UInt32 { + return UInt32((max(0, min(1, value)) * 255).rounded()) + } + + let argb: UInt32 = (component(color.alpha) << 24) + | (component(color.red) << 16) + | (component(color.green) << 8) + | component(color.blue) + + return Int32(bitPattern: argb) + } +} + +// MARK: - State + +internal extension AndroidCanvasContext { + + fileprivate final class State { + + var next: State? + var ctm = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) + var alpha: CGFloat = 1.0 + var fill: CGColor? + var stroke: CGColor? + var shadow: (offset: CGSize, radius: CGFloat, color: CGColor)? + var font: CGFont? + var fontSize: CGFloat = 0.0 + var characterSpacing: CGFloat = 0.0 + var textMode = CGTextDrawingMode() + var shouldAntialias = true + var lineWidth: CGFloat = 1.0 + var lineCap = CGLineCap() + var lineJoin = CGLineJoin() + var miterLimit: CGFloat = 10.0 + var lineDash: (phase: CGFloat, lengths: [CGFloat]) = (0.0, []) + var tolerance: CGFloat = 0.1 + + init() { } + + var copy: State { + + let copy = State() + + copy.next = next + copy.ctm = ctm + copy.alpha = alpha + copy.fill = fill + copy.stroke = stroke + copy.shadow = shadow + copy.font = font + copy.fontSize = fontSize + copy.characterSpacing = characterSpacing + copy.textMode = textMode + copy.shouldAntialias = shouldAntialias + copy.lineWidth = lineWidth + copy.lineCap = lineCap + copy.lineJoin = lineJoin + copy.miterLimit = miterLimit + copy.lineDash = lineDash + copy.tolerance = tolerance + + return copy + } + } +} + +// MARK: - Geometry Helpers + +internal extension CGAffineTransform { + + /// The result of applying `self` first, then `other`. + func multiplied(by other: CGAffineTransform) -> CGAffineTransform { + + return CGAffineTransform( + a: a * other.a + b * other.c, + b: a * other.b + b * other.d, + c: c * other.a + d * other.c, + d: c * other.b + d * other.d, + tx: tx * other.a + ty * other.c + other.tx, + ty: tx * other.b + ty * other.d + other.ty + ) + } + + var inverse: CGAffineTransform { + + let determinant = a * d - b * c + + guard determinant != 0 + else { return self } + + return CGAffineTransform( + a: d / determinant, + b: -b / determinant, + c: -c / determinant, + d: a / determinant, + tx: (c * ty - d * tx) / determinant, + ty: (b * tx - a * ty) / determinant + ) + } + + func toAndroid() -> AndroidGraphics.Matrix { + + let matrix = AndroidGraphics.Matrix() + + matrix.setValues([ + Float(a), Float(c), Float(tx), + Float(b), Float(d), Float(ty), + 0, 0, 1 + ]) + + return matrix + } +} + +internal extension PathElement { + + func applying(_ transform: CGAffineTransform) -> PathElement { + + switch self { + + case let .moveToPoint(point): + return .moveToPoint(point.applying(transform)) + + case let .addLineToPoint(point): + return .addLineToPoint(point.applying(transform)) + + case let .addQuadCurveToPoint(control, destination): + return .addQuadCurveToPoint(control.applying(transform), destination.applying(transform)) + + case let .addCurveToPoint(control1, control2, destination): + return .addCurveToPoint(control1.applying(transform), control2.applying(transform), destination.applying(transform)) + + case .closeSubpath: + return .closeSubpath + } + } +} + +#endif // canImport(AndroidGraphics) From 5f46fd28a7ec8137ad1911a14845e52d61ac84cb Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:06 -0500 Subject: [PATCH 3/7] Added Silica's Android font handle, moved from Silica --- Sources/AndroidSilica/AndroidFontHandle.swift | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 Sources/AndroidSilica/AndroidFontHandle.swift diff --git a/Sources/AndroidSilica/AndroidFontHandle.swift b/Sources/AndroidSilica/AndroidFontHandle.swift new file mode 100644 index 0000000..1a2fb12 --- /dev/null +++ b/Sources/AndroidSilica/AndroidFontHandle.swift @@ -0,0 +1,169 @@ +// +// AndroidFontHandle.swift +// AndroidSilica +// +// Created by Alsey Coleman Miller on 7/13/26. +// Copyright © 2026 PureSwift. All rights reserved. +// + +#if canImport(AndroidGraphics) + +import AndroidGraphics +import SwiftJava +import Foundation +import Silica + +/// Android Typeface backed font. +/// +/// Glyph indices and advances are obtained by shaping through +/// `android.graphics.text.TextRunShaper` (API 31), which also yields the +/// `android.graphics.fonts.Font` needed by `Canvas.drawGlyphs`. +/// +/// - Note: `Typeface.create` falls back to the system default for unknown +/// family names (matching FontConfig's fuzzy behavior on Linux), so font +/// creation does not fail for unrecognized names. +public final class AndroidFontHandle: CGFontHandle { + + // MARK: - Constants + + /// Nominal em size used for measuring (Android exposes no font-unit metrics). + internal static let nominalSize: CGFloat = 2048 + + // MARK: - Properties + + public let typeface: Typeface + + public let familyName: String + + // MARK: - Private Properties + + /// Paint configured at the nominal size, used for measuring and shaping. + private let measuringPaint: Paint + + private let internalMetrics: (ascent: CGFloat, descent: CGFloat, capHeight: CGFloat) + + /// Shaped glyph information, populated by `glyph(for:)`. + private var glyphCache = [Silica.CGGlyph: (advance: CGFloat, font: AndroidGraphics.Font?)]() + + /// The font of the first shaped glyph, used as a fallback for `Canvas.drawGlyphs`. + internal private(set) var baseFont: AndroidGraphics.Font? + + // MARK: - Initialization + + /// Resolves a Silica font name (e.g. `"TimesNewRoman-Bold"`). + public init?(name: String) { + + // parse "Family-Traits" + let separator: Character = "-" + let components = name.split(separator: separator, maxSplits: 2, omittingEmptySubsequences: true) + + let family: String + let traits: String? + + if components.count == 2 { + family = String(components[0]) + traits = String(components[1]) + } else { + family = name + traits = nil + } + + var isBold = false + var isItalic = false + + if let traits = traits { + isBold = traits.contains("Bold") + isItalic = traits.contains("Italic") || traits.contains("Oblique") + } + + // Typeface style constants: NORMAL = 0, BOLD = 1, ITALIC = 2, BOLD_ITALIC = 3 + let style: Int32 = (isBold ? 1 : 0) | (isItalic ? 2 : 0) + + guard let typefaceClass = try? JavaClass(), + let typeface = typefaceClass.create(family, style) + else { return nil } + + self.typeface = typeface + self.familyName = family + + let paint = Paint() + paint.setAntiAlias(true) + _ = paint.setTypeface(typeface) + paint.setTextSize(Float(AndroidFontHandle.nominalSize)) + self.measuringPaint = paint + + guard let fontMetrics = paint.getFontMetrics() + else { return nil } + + // FontMetrics.ascent is negative above the baseline; descent positive below. + let ascent = CGFloat(-fontMetrics.ascent) / AndroidFontHandle.nominalSize + let descent = CGFloat(-fontMetrics.descent) / AndroidFontHandle.nominalSize + + // approximate the cap height from the bounds of an uppercase letter + let bounds = Rect() + paint.getTextBounds("H", 0, 1, bounds) + let capHeight = CGFloat(bounds.height()) / AndroidFontHandle.nominalSize + + self.internalMetrics = (ascent: ascent, descent: descent, capHeight: capHeight) + } + + // MARK: - CGFontHandle + + /// The family name (Android exposes no full font name). + public var fullName: String { familyName } + + public var unitsPerEm: Int { Int(AndroidFontHandle.nominalSize) } + + public var ascent: CGFloat { internalMetrics.ascent } + + public var descent: CGFloat { internalMetrics.descent } + + public var capHeight: CGFloat { internalMetrics.capHeight } + + public func glyph(for scalar: Unicode.Scalar) -> Silica.CGGlyph { + + let characters = Array(String(scalar).utf16) + + guard let shaperClass = try? JavaClass(), + let shaped = shaperClass.shapeTextRun(characters, 0, Int32(characters.count), + 0, Int32(characters.count), + 0, 0, false, measuringPaint), + shaped.glyphCount() > 0 + else { return 0 } + + let glyph = Silica.CGGlyph(truncatingIfNeeded: shaped.getGlyphId(0)) + + if glyphCache[glyph] == nil { + + let font = shaped.getFont(0) + + glyphCache[glyph] = (advance: CGFloat(shaped.getAdvance()) / AndroidFontHandle.nominalSize, + font: font) + + if baseFont == nil { + baseFont = font + } + } + + return glyph + } + + /// Advances for previously shaped glyphs. + /// + /// Android exposes no advance lookup by glyph index; advances are memoized + /// when glyphs are shaped via `glyph(for:)`. Unknown glyph indices report 0. + public func advances(for glyphs: [Silica.CGGlyph]) -> [CGFloat] { + + return glyphs.map { glyphCache[$0]?.advance ?? 0 } + } + + // MARK: - Internal Methods + + /// The `android.graphics.fonts.Font` for a previously shaped glyph. + internal func font(for glyph: Silica.CGGlyph) -> AndroidGraphics.Font? { + + return glyphCache[glyph]?.font + } +} + +#endif // canImport(AndroidGraphics) From 8e0af9b5b5d207802a3d2b396151c304479b2edd Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:07 -0500 Subject: [PATCH 4/7] Added the AndroidSilica module's exports of Silica's types --- Sources/AndroidSilica/Export.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Sources/AndroidSilica/Export.swift diff --git a/Sources/AndroidSilica/Export.swift b/Sources/AndroidSilica/Export.swift new file mode 100644 index 0000000..32f0bbe --- /dev/null +++ b/Sources/AndroidSilica/Export.swift @@ -0,0 +1,26 @@ +// +// Export.swift +// AndroidSilica +// +// Created by Alsey Coleman Miller on 7/13/26. +// Copyright © 2026 PureSwift. All rights reserved. +// + +@_exported import Silica + +#if canImport(AndroidGraphics) + +// These module-local aliases resolve every unqualified reference to Silica's types; +// Android's types are referenced fully qualified (e.g. `AndroidGraphics.Canvas`). +public typealias CGContext = Silica.CGContext +public typealias CGColor = Silica.CGColor +public typealias CGPath = Silica.CGPath +public typealias CGFont = Silica.CGFont +public typealias CGImage = Silica.CGImage +public typealias CGGlyph = Silica.CGGlyph +public typealias CGLineCap = Silica.CGLineCap +public typealias CGLineJoin = Silica.CGLineJoin +public typealias CGTextDrawingMode = Silica.CGTextDrawingMode +public typealias PathElement = Silica.PathElement + +#endif From 4cb96954bc62f7b0453085c86ec0f0caee6937bb Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:07 -0500 Subject: [PATCH 5/7] Added the AndroidSilica tests, moved from Silica --- .../AndroidStyleKitTests.swift | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 Tests/AndroidSilicaTests/AndroidStyleKitTests.swift diff --git a/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift b/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift new file mode 100644 index 0000000..b2182fd --- /dev/null +++ b/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift @@ -0,0 +1,134 @@ +// +// AndroidStyleKitTests.swift +// AndroidSilicaTests +// +// Created by Alsey Coleman Miller on 7/13/26. +// Copyright © 2026 PureSwift. All rights reserved. +// + +#if canImport(AndroidGraphics) && os(Android) + +import Testing +import Foundation +import SwiftJava +import JavaIO +import AndroidOS +import AndroidApp +import AndroidContext +@preconcurrency import AndroidContent +import AndroidSilica +import SilicaTestSupport + +/// Renders the shared StyleKit content through the Android Canvas backend. +/// +/// These tests run on-device via `skip android test` and require API 31+ +/// for glyph rendering (`Canvas.drawGlyphs`). +@Suite(.serialized) +struct AndroidStyleKitTests { + + @Test func simpleShapes() throws { + let data = try render(TestStyleKit.drawSimpleShapes(), name: "android_simpleShapes", size: CGSize(width: 240, height: 120)) + try expectPDF(data) + } + + @Test func advancedShapes() throws { + let data = try render(TestStyleKit.drawAdvancedShapes(), name: "android_advancedShapes", size: CGSize(width: 240, height: 120)) + try expectPDF(data) + } + + @Test func swiftLogo() throws { + let size = CGSize(width: 200, height: 200) + let data = try render(TestStyleKit.drawSwiftLogo(frame: CGRect(origin: .zero, size: size)), name: "android_SwiftLogo", size: size) + try expectPDF(data) + } + + @Test func singleLineText() throws { + let data = try render(TestStyleKit.drawSingleLineText(), name: "android_singleLineText", size: CGSize(width: 240, height: 120)) + try expectPDF(data) + } + + @Test func bitmapContext() throws { + AndroidBackend.register() + + let context = try AndroidCanvasContext(bitmap: CGSize(width: 20, height: 20)) + context.fillColor = CGColor(red: 1, green: 0, blue: 0) + context.addRect(CGRect(x: 0, y: 0, width: 20, height: 20)) + context.fillPath() + + let image = try #require(context.makeImage()) + #expect(image.width == 20) + #expect(image.height == 20) + + // solid red (premultiplied RGBA) + #expect(image.data[0] > 200) + #expect(image.data[1] < 50) + } + + // MARK: - Utilities + + private func render(_ drawingMethod: @autoclosure () -> (), name: String, size: CGSize) throws -> Data { + + AndroidBackend.register() + + let path = try Self.outputDirectory() + "/" + name + ".pdf" + + let context = try AndroidCanvasContext(pdf: URL(fileURLWithPath: path), size: size) + + UIGraphicsPushContext(context) + + drawingMethod() + + UIGraphicsPopContext() + + try context.finish() + + print("Wrote to \(path)") + + return try Data(contentsOf: URL(fileURLWithPath: path)) + } + + private func expectPDF(_ data: Data) throws { + #expect(data.count > 4) + #expect(String(decoding: data.prefix(4), as: UTF8.self) == "%PDF") + } + + private struct ContextError: Error { } + + /// Cached by `outputDirectory()`; safe because the suite is serialized. + private nonisolated(unsafe) static var cachedOutputDirectory: String? + + /// The application cache directory — the reliably writable location + /// inside the on-device test harness. + private static func outputDirectory() throws -> String { + + if let cached = cachedOutputDirectory { + return cached + } + + let jvm = try JavaVirtualMachine.shared() + let environment = try jvm.environment() + + // get the low-level application context from swift-android-native + // and wrap it in the @JavaClass Context (like PureSwift/Android's tests). + // JavaObjectHolder takes ownership of a local reference (it promotes it + // to a global reference and deletes the local one), so hand it a fresh + // local reference rather than the stored context pointer. + let lowLevelContext = try AndroidContext.application + + guard let localContext = environment.interface.NewLocalRef(environment, lowLevelContext.pointer) + else { throw ContextError() } + + let application = Application(javaHolder: JavaObjectHolder(object: localContext, environment: environment)) + + let context = try #require(application.as(AndroidContent.Context.self)) + let cacheDirectory = try #require(context.getCacheDir()) + + let path = cacheDirectory.getAbsolutePath() + + cachedOutputDirectory = path + + return path + } +} + +#endif // canImport(AndroidGraphics) && os(Android) From 8f3bbfd0baecbc0f5006378499ebf8136c3876f3 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:07 -0500 Subject: [PATCH 6/7] Added the AndroidSilica product, apart from AndroidKit --- Package.swift | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/Package.swift b/Package.swift index 83b6e28..e8e140f 100644 --- a/Package.swift +++ b/Package.swift @@ -78,6 +78,11 @@ var package = Package( .library( name: "AndroidNFC", targets: ["AndroidNFC"] ), + // Silica's drawing API on android.graphics.Canvas. Not part of AndroidKit, + // so AndroidKit doesn't bring Silica in. + .library( + name: "AndroidSilica", targets: ["AndroidSilica"] + ), ], dependencies: [ .package( @@ -96,6 +101,10 @@ var package = Package( url: "https://github.com/swift-android-sdk/swift-android-native.git", branch: "main" ), + .package( + url: "https://github.com/PureSwift/Silica.git", + branch: "master" + ), ], targets: [ .target( @@ -489,6 +498,57 @@ var package = Package( sdkVersionDefine, ] ), + .target( + name: "AndroidSilica", + dependencies: [ + .product( + name: "Silica", + package: "Silica" + ), + "AndroidGraphics", + .product( + name: "SwiftJava", + package: "swift-java" + ), + .product( + name: "JavaIO", + package: "swift-java" + ), + .product( + name: "JavaLangIO", + package: "JavaLang" + ), + ], + swiftSettings: [ + .swiftLanguageMode(.v6), + ndkVersionDefine, + sdkVersionDefine, + ] + ), + .testTarget( + name: "AndroidSilicaTests", + dependencies: [ + "AndroidSilica", + "AndroidOS", + "AndroidApp", + "AndroidContent", + .product( + name: "SilicaTestSupport", + package: "Silica" + ), + .product( + name: "AndroidContext", + package: "swift-android-native" + ), + .product( + name: "SwiftJava", + package: "swift-java" + ), + ], + swiftSettings: [ + .swiftLanguageMode(.v6), + ] + ), ], swiftLanguageModes: [.v5, .v6] ) From 8bd4f34e602aec180b1b54f9ff6a3c462061c6ec Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 11:13:07 -0500 Subject: [PATCH 7/7] Documented drawing with Silica --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 1c152ec..ca0d451 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,27 @@ cd Demo Then you can compile the app from the Android IDE. +## Drawing with Silica + +`AndroidSilica` draws [Silica](https://github.com/PureSwift/Silica)'s drawing API on `android.graphics.Canvas`. It is a product of its own, and `AndroidKit` doesn't include it. + +```swift +import AndroidSilica + +let context = try AndroidCanvasContext(pdf: url, size: CGSize(width: 200, height: 200)) +// ... CoreGraphics style drawing code ... +try context.finish() // writes the PDF +``` + +`AndroidCanvasContext` also has `init(bitmap:)` for raster output, and `init(canvas:size:)` to draw into a canvas you already have, such as the one a view's draw pass hands you. + +- Requires **API 31+** at runtime for glyph rendering (`Canvas.drawGlyphs`, `TextRunShaper`). +- `finish()` is **mandatory** for PDF contexts — the document is only written to disk when it is called. +- JNI-backed objects must be used from a JVM-attached thread; create, use, and finish a context on the same thread. +- The linear (scale/rotation) components of the text matrix are not applied to glyph shapes. +- Unknown font names fall back to the system typeface (Android provides no font-matching failure signal). +- Shadows are drawn without blur (a silhouette at the shadow offset). + ### See Also - [AndroidSwiftUI](https://github.com/PureSwift/AndroidSwiftUI) - SwiftUI for Android