Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/FeatureCharts/Tests/FeatureChartsTests/RenderTests.swift10// Module : FeatureChartsTests11// Repository : https://git.spboucher.ai/orix-sheet12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import AppKit88import Foundation89import Testing90import SheetCore91import SheetCharts92import SheetUI93@testable import FeatureCharts9495@MainActor @Suite struct RenderCacheTests {96 func setup() -> (WorkbookSession, SheetObject, ChartRenderCache) {97 let s = makeSession()98 s.select(RangeRef(a1: "A1:D7")!)99 let o = ChartInsertion.quickInsert(.column, in: s)!100 let cache = ChartRenderCache()101 cache.vectorWhenOffscreen = false102 return (s, o, cache)103 }104105 func draw(_ cache: ChartRenderCache, _ s: WorkbookSession, _ o: SheetObject, w: Int? = nil, h: Int? = nil, dark: Bool = false, scale: CGFloat = 2) {106 let w = w ?? Int(o.width), h = h ?? Int(o.height)107 cache.draw(o, session: s, context: bitmapContext(width: w, height: h, scale: scale), rect: CGRect(x: 0, y: 0, width: w, height: h), dark: dark)108 }109110 @Test func invalidationKeys() {111 let (s, o, cache) = setup()112 draw(cache, s, o)113 #expect(cache.stats.misses == 1 && cache.stats.hits == 0)114 draw(cache, s, o); draw(cache, s, o)115 #expect(cache.stats.misses == 1 && cache.stats.hits == 2)116 #expect(cache.hasImage(for: o.id, key: RenderKey(size: CGSize(width: o.width, height: o.height), scale: 2, dark: false)))117118 // a cell the chart does not read: new content revision, same snapshot → still a hit119 s.perform("edit") { $0.set(sheet: 0, row: 30, col: 9, .value(.number(1))) }120 draw(cache, s, o)121 #expect(cache.stats.misses == 1 && cache.stats.hits == 3)122 // selection moves do not touch the content revision123 s.select(cell: CellRef(a1: "F9")!)124 draw(cache, s, o)125 #expect(cache.stats.hits == 4)126127 // a cell of the chart's range → re-render128 s.perform("edit") { $0.set(sheet: 0, row: 2, col: 1, .value(.number(99))) }129 draw(cache, s, o)130 #expect(cache.stats.misses == 2)131 // a formula input changes computed values of a charted column only if the chart reads it (column E is not charted)132 s.perform("edit") { $0.set(sheet: 0, row: 1, col: 7, .value(.number(3))) }133 draw(cache, s, o)134 #expect(cache.stats.misses == 2)135136 // appearance, pixel scale and size are part of the key137 draw(cache, s, o, dark: true)138 #expect(cache.stats.misses == 3)139 draw(cache, s, o, scale: 1)140 #expect(cache.stats.misses == 4)141 draw(cache, s, o, w: Int(o.width) + 40, h: Int(o.height)) // zoomed rect: same chart, more pixels142 #expect(cache.stats.misses == 5)143 var resized = o; resized.width += 60144 draw(cache, s, resized)145 #expect(cache.stats.misses == 6)146147 // payload edit → decode + render again; undo brings the old payload back148 let editor = ChartEditor.object(o.id, session: s)149 editor.apply("Chart Title") { $0.title = "Changed" }150 let hits = cache.stats.hits151 draw(cache, s, s.sheet.meta.objects[0])152 #expect(cache.stats.misses == 7 && cache.stats.hits == hits)153 draw(cache, s, s.sheet.meta.objects[0])154 #expect(cache.stats.hits == hits + 1)155 #expect(RenderKey(size: CGSize(width: 10, height: 10), scale: 2.001, dark: false) == RenderKey(size: CGSize(width: 10, height: 10), scale: 2, dark: false))156 }157158 @Test func formulaDrivenChartsFollowRecalculation() {159 let s = makeSession()160 s.select(RangeRef(a1: "E1:E7")!)161 let o = ChartInsertion.quickInsert(.line, in: s)!162 let cache = ChartRenderCache(); cache.vectorWhenOffscreen = false163 draw(cache, s, o)164 s.perform("edit") { $0.set(sheet: 0, row: 1, col: 7, .value(.number(5))) } // H2 drives column E165 draw(cache, s, o)166 #expect(cache.stats.misses == 2)167 #expect(cache.chartLayout(for: o, session: s, dark: false)?.hitItems.first?.y == 175) // (10 + 20 + 5) × 5168 }169170 @Test func vectorWhenPrinting() throws {171 let (s, o, cache) = setup()172 cache.forceVector = true173 let data = NSMutableData()174 var box = CGRect(x: 0, y: 0, width: o.width, height: o.height)175 let ctx = try #require(CGContext(consumer: CGDataConsumer(data: data)!, mediaBox: &box, nil))176 ctx.beginPDFPage(nil)177 ctx.translateBy(x: 0, y: box.height); ctx.scaleBy(x: 1, y: -1) // flipped, as the print renderer provides178 cache.draw(o, session: s, context: ctx, rect: box, dark: false)179 ctx.endPDFPage(); ctx.closePDF()180 #expect(cache.stats.vectorDraws == 1 && cache.stats.misses == 0)181 let text = String(decoding: data as Data, as: UTF8.self)182 #expect(text.hasPrefix("%PDF-") && text.contains("/Font") && !text.contains("/Subtype /Image"))183 // and through the real print path of SheetUI184 ChartsFeature.register()185 let printed = PrintRenderer.pdfData(session: s)186 let printedText = String(decoding: printed, as: UTF8.self)187 #expect(printedText.hasPrefix("%PDF-") && !printedText.contains("/Subtype /Image"))188 }189190 @Test func figureObjectsDraw() throws {191 let (s, o, cache) = setup()192 let spec = ChartPayload.chart(o)!.spec193 let figure = FigureTemplates.financialReport.makeFigure(charts: [spec, spec])194 let fo = try figure.sheetObject(x: 0, y: 0)195 s.addObject(fo)196 draw(cache, s, fo)197 draw(cache, s, fo, dark: true) // figures are never re-themed: same image198 #expect(cache.stats.misses == 1 && cache.stats.hits == 1)199 #expect(cache.accessibilityDescription(for: fo, session: s).contains("2"))200 }201202 @Test func accessibilityDescription() {203 let (s, o, cache) = setup()204 let text = cache.accessibilityDescription(for: o, session: s)205 #expect(text.contains("Column") && text.contains("3 series"))206 #expect(text.contains("North: minimum 10, maximum 25, last 25"))207 #expect(text.contains("South") && text.contains("6 categories"))208 let pie = ChartSpec(kind: .pie, title: "Share", series: [SeriesSpec(values: .literal([1, 3]))], categories: .labels(["a", "b"]))209 let d = ChartAccessibility.describe(pie, data: ChartData.resolve(pie, source: LiteralDataSource()))210 #expect(d.contains("“Share”") && d.contains("a: 1") && d.contains("b: 3"))211 let empty = ChartSpec(kind: .heatmap)212 #expect(ChartAccessibility.describe(empty, data: ChartData.resolve(empty, source: LiteralDataSource())).contains("No numeric data"))213 }214}215216@MainActor @Suite struct ExportTests {217 @Test func formatsAreValid() throws {218 let s = makeSession()219 let spec = ChartBuilder.spec(.column, detection(s, "A1:D7"))220 let snap = ChartSnapshot.capture([spec], workbook: s.workbook, lock: s.engine.lock)221 let size = CGSize(width: 480, height: 300)222 let pdf = try #require(ChartExporter.data(spec, source: snap, size: size, format: .pdf))223 let pdfText = String(decoding: pdf, as: UTF8.self)224 #expect(pdfText.hasPrefix("%PDF-") && pdfText.contains("/Font") && !pdfText.contains("/Subtype /Image"))225 let svg = try #require(ChartExporter.data(spec, source: snap, size: size, format: .svg))226 let parsed = XMLCheck.parse(svg)227 #expect(parsed.ok && parsed.elements > 20 && parsed.texts > 5)228 for scale in [1, 2, 3] {229 let png = try #require(ChartExporter.data(spec, source: snap, size: size, format: .png, scale: CGFloat(scale)))230 let px = try #require(pngSize(png))231 #expect(px == (480 * scale, 300 * scale))232 }233 #expect(ChartExporter.pixelSize(CGSize(width: 72, height: 144), dpi: 300) == (300, 600))234 // snapshots are independent of later edits (safe to render on another thread)235 s.perform("edit") { $0.set(sheet: 0, row: 1, col: 1, .value(.number(1000))) }236 #expect(ChartData.resolve(spec, source: snap).series[0].values.first == 10)237 // pasteboard: PDF + PNG representations238 let pb = NSPasteboard(name: NSPasteboard.Name("ai.spboucher.orix.charts.tests.\(UUID().uuidString)"))239 #expect(ChartExporter.copy(spec, source: snap, size: size, pasteboard: pb))240 #expect(pb.data(forType: .pdf)?.prefix(5) == Data("%PDF-".utf8) && pngSize(pb.data(forType: .png) ?? Data()) != nil)241 pb.releaseGlobally()242 }243244 @Test func exportAllWritesOneFilePerChart() throws {245 let s = makeSession()246 s.select(RangeRef(a1: "A1:D7")!)247 _ = ChartInsertion.quickInsert(.column, in: s)248 _ = ChartInsertion.quickInsert(.column, in: s)249 var o = s.sheet.meta.objects[1]; o.name = "Q1/Q2: sales?"; s.updateObject(o)250 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("fc-export-\(UUID().uuidString)")251 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)252 defer { try? FileManager.default.removeItem(at: folder) }253 let urls = try ChartExporter.exportAll(session: s, to: folder, format: .svg)254 #expect(urls.map(\.lastPathComponent) == ["Column.svg", "Q1 Q2 sales.svg"])255 #expect(try urls.allSatisfy { XMLCheck.parse(try Data(contentsOf: $0)).ok })256 var used = Set<String>()257 #expect(ChartExporter.fileName("A", ext: "png", used: &used) == "A.png")258 #expect(ChartExporter.fileName("a", ext: "png", used: &used) == "a 2.png")259 #expect(ChartExporter.fileName("///", ext: "pdf", used: &used) == "Chart.pdf")260 }261}262263@MainActor @Suite struct EditorTests {264 @Test func liveEditsCoalesceIntoOneUndoStep() throws {265 let s = makeSession()266 s.select(RangeRef(a1: "A1:D7")!)267 let o = try #require(ChartInsertion.quickInsert(.line, in: s))268 let editor = try #require(ChartsState.of(s).editor(for: o.id))269 #expect(ChartsState.of(s).editor(for: o.id) === editor)270 let before = s.engine.changeCount271 for i in 1...25 { editor.live("Line Width") { $0.series[0].style.lineWidth = Double(i) / 5 } }272 #expect(editor.isLive && editor.spec.series[0].style.lineWidth == 5)273 // the preview is visible to the renderer but not yet on the undo stack274 #expect(ChartPayload.chart(s.sheet.meta.objects[0])?.spec.series[0].style.lineWidth == 5)275 #expect(s.engine.changeCount == before)276 editor.flush()277 #expect(!editor.isLive && s.engine.changeCount == before + 1 && editor.commitCount == 1)278 s.undo()279 #expect(ChartPayload.chart(s.sheet.meta.objects[0])?.spec.series[0].style.lineWidth == nil)280 s.redo()281 #expect(editor.spec.series[0].style.lineWidth == 5)282 // a different control, or a discrete edit, ends the gesture first283 editor.live("Marker Size") { $0.series[0].style.markerSize = 9 }284 editor.apply("Chart Title") { $0.title = "Renamed" }285 #expect(s.engine.changeCount == before + 5 && s.sheet.meta.objects[0].name == "Renamed")286 editor.apply("Chart Title") { $0.title = "Renamed" } // no change → no undo step287 #expect(s.engine.changeCount == before + 5)288 editor.applyValue("Keep Theme") { $0.pinTheme = true }289 #expect(editor.pinTheme)290 }291}292