Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFeatureGraph/Tests/ORIXFeatureGraphTests/Support.swift3// Description: Test helpers — isolated AppModel, model factories and off-screen rendering with pixel access.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import SwiftUI9import Testing10import ORIXExpression11import ORIXGraph12import ORIXUI13@testable import ORIXFeatureGraph14#if canImport(UIKit)15import UIKit16#endif1718@MainActor19func makeApp() -> AppModel {20 let suite = "orix.graph.tests." + UUID().uuidString21 let settings = AppSettings(defaults: UserDefaults(suiteName: suite)!)22 settings.data.angleMode = .radians23 let app = AppModel(settings: settings, inMemory: true)24 app.applySettings()25 return app26}2728@MainActor29func makeModel(_ texts: [String], app: AppModel? = nil, width: Double = 800, height: Double = 600) -> GraphModel {30 var s = GraphSessionData()31 s.entries = texts.enumerated().map { GraphEntryData(text: $1, colorIndex: $0) }32 s.selected = s.entries.first?.id33 let m = GraphModel(app: app ?? makeApp(), session: s)34 m.setCanvasSize(width: width, height: height)35 return m36}3738/// An RGBA8 bitmap with a top-left origin, in pixels.39struct Bitmap {40 let width: Int41 let height: Int42 let scale: Double43 let data: [UInt8]4445 func pixel(_ x: Int, _ y: Int) -> (r: Int, g: Int, b: Int) {46 let i = (min(max(y, 0), height - 1) * width + min(max(x, 0), width - 1)) * 447 return (Int(data[i]), Int(data[i + 1]), Int(data[i + 2]))48 }49 func isNear(_ x: Int, _ y: Int, _ c: (r: Int, g: Int, b: Int), tolerance: Int = 70) -> Bool {50 let p = pixel(x, y)51 return abs(p.r - c.r) + abs(p.g - c.g) + abs(p.b - c.b) <= tolerance52 }53 /// Longest vertical run of pixels close to `color` in the pixel column `x` (and its two neighbours).54 func longestVerticalRun(x: Int, color: (r: Int, g: Int, b: Int)) -> Int {55 var best = 056 for column in (x - 1)...(x + 1) {57 var run = 058 for y in 0..<height {59 if isNear(column, y, color) { run += 1; best = max(best, run) } else { run = 0 }60 }61 }62 return best63 }64 /// True when a pixel close to `color` lies within `radius` pixels of (x, y).65 func hasColor(nearX x: Int, y: Int, radius: Int, color: (r: Int, g: Int, b: Int)) -> Bool {66 for dy in -radius...radius { for dx in -radius...radius where isNear(x + dx, y + dy, color) { return true } }67 return false68 }69 func count(color: (r: Int, g: Int, b: Int), tolerance: Int = 70) -> Int {70 var n = 071 for y in 0..<height { for x in 0..<width where isNear(x, y, color, tolerance: tolerance) { n += 1 } }72 return n73 }74}7576#if canImport(UIKit)77@MainActor78func render<V: View>(_ view: V, width: CGFloat, height: CGFloat, scale: CGFloat = 2, scheme: ColorScheme = .light) -> (bitmap: Bitmap, png: Data)? {79 let renderer = ImageRenderer(content: view.frame(width: width, height: height).environment(\.colorScheme, scheme))80 renderer.scale = scale81 renderer.isOpaque = true82 guard let image = renderer.uiImage, let cg = image.cgImage, let png = image.pngData() else { return nil }83 let w = cg.width, h = cg.height84 var data = [UInt8](repeating: 0, count: w * h * 4)85 let ok = data.withUnsafeMutableBytes { buffer -> Bool in86 guard let ctx = CGContext(data: buffer.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,87 space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return false }88 ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h))89 return true90 }91 guard ok else { return nil }92 return (Bitmap(width: w, height: h, scale: Double(scale), data: data), png)93}9495/// Renders a view through UIKit (a hosting controller in a window), which also draws scroll views and UIKit-backed fields.96@MainActor97func snapshot<V: View>(_ view: V, width: CGFloat, height: CGFloat, scheme: ColorScheme, settle: Duration = .milliseconds(500)) async -> Data? {98 let host = UIHostingController(rootView: view.environment(\.colorScheme, scheme))99 host.overrideUserInterfaceStyle = scheme == .dark ? .dark : .light100 host.safeAreaRegions = []101 let frame = CGRect(x: 0, y: 0, width: width, height: height)102 // A window gives the hosted view its life cycle (appear, geometry changes); no window scene exists in a package test103 // process, so the picture is taken from the layer tree rather than from the screen.104 let window = UIWindow()105 window.frame = frame106 window.rootViewController = host107 window.isHidden = false108 host.view.frame = frame109 host.view.setNeedsLayout(); host.view.layoutIfNeeded()110 try? await Task.sleep(for: settle)111 host.view.setNeedsLayout(); host.view.layoutIfNeeded()112 let format = UIGraphicsImageRendererFormat()113 format.scale = 2114 format.opaque = true115 let image = UIGraphicsImageRenderer(size: frame.size, format: format).image { context in116 host.view.layer.render(in: context.cgContext)117 }118 window.isHidden = true119 window.rootViewController = nil120 return image.pngData()121}122123/// The sRGB components of an adaptive colour in the given appearance.124@MainActor125func rgb(_ color: Color, dark: Bool = false) -> (r: Int, g: Int, b: Int) {126 let resolved = UIColor(color).resolvedColor(with: UITraitCollection(userInterfaceStyle: dark ? .dark : .light))127 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0128 resolved.getRed(&r, green: &g, blue: &b, alpha: &a)129 return (Int((r * 255).rounded()), Int((g * 255).rounded()), Int((b * 255).rounded()))130}131#endif132133/// Where the screenshots the engineer looks at are written (inside the package's build folder).134func shotsDirectory(file: String = #filePath) -> URL {135 let package = URL(fileURLWithPath: file).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()136 let dir = package.appendingPathComponent(".build/shots", isDirectory: true)137 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)138 return dir139}140