Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/FeatureCharts/Sources/charts-preview/main.swift10// Module : charts-preview11// 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 SwiftUI89import SheetCore90import SheetCharts91import SheetUI92import FeatureCharts9394// Development harness of FeatureCharts.95// charts-preview [--state sheet|picker|inspector|viewer|figure|dashboard|perf] [--kind <chart kind>] [--tab data|style|axes|elements]96// [--hover x,y] [--template id] [--panel n] [--export-figure out.pdf|svg|png] [--shot out.png] [--dark] [--size WxH]97// With --shot the window content is rendered to a PNG by the app itself and the process exits.9899struct PickerOverlay: View {100 let session: WorkbookSession101 @State private var model: ChartPickerModel102 init(session: WorkbookSession) { self.session = session; _model = State(initialValue: ChartPickerModel(session: session)) }103 var body: some View {104 ZStack {105 Color.black.opacity(0.28)106 ChartPickerView(model: model, onClose: {})107 .frame(width: 820, height: 640)108 .clipShape(RoundedRectangle(cornerRadius: 12))109 .shadow(color: .black.opacity(0.35), radius: 30, y: 12)110 }111 }112}113114final class AppDelegate: NSObject, NSApplicationDelegate {115 var window: NSWindow!116 var session: WorkbookSession!117118 func applicationDidFinishLaunching(_ notification: Notification) {119 let args = CommandLine.arguments120 func value(_ flag: String) -> String? { args.firstIndex(of: flag).flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil } }121 var size = NSSize(width: 1440, height: 900)122 if let s = value("--size")?.split(separator: "x").compactMap({ Double($0) }), s.count == 2 { size = NSSize(width: s[0], height: s[1]) }123 if args.contains("--dark") { NSApp.appearance = NSAppearance(named: .darkAqua) }124 let state = value("--state") ?? "sheet"125 let kind = value("--kind").flatMap { ChartKind(rawValue: $0) } ?? .column126 let shot = value("--shot")127128 ChartsFeature.register()129 if shot != nil { ChartRenderCache.shared.vectorWhenOffscreen = false }130 session = Demo.session()131 let s = session!132 s.showSidebar = false133 var overlay = false134135 switch state {136 case "picker":137 s.select(RangeRef(a1: "A1:D13")!)138 overlay = true139 case "inspector":140 s.activateSheet(Demo.sheet(for: kind))141 s.select(RangeRef(a1: "A1")!)142 let o = Demo.place(Demo.spec(kind, s), s, x: 440, y: 300, w: 470, h: 310)143 s.selectedObjectID = o.id144 s.inspectorPane = ChartsFeature.inspectorPaneID145 if let tab = value("--tab").flatMap({ ChartInspectorTab(rawValue: $0) }) { ChartsState.of(s).inspectorTab = tab }146 case "viewer":147 s.activateSheet(Demo.sheet(for: kind))148 let o = Demo.place(Demo.spec(kind, s), s, x: 520, y: 30, w: 620, h: 380)149 s.inspectorPane = nil150 ChartsFeature.openViewer(o, in: s)151 if let h = value("--hover")?.split(separator: ",").compactMap({ Double($0) }), h.count == 2 { ChartsState.of(s).previewHover = CGPoint(x: h[0], y: h[1]) }152 if let cell = value("--whatif") { let m = ChartViewerModel.of(s); if m.whatIf.setTarget(text: cell) { m.whatIfText = m.whatIf.targetText } }153 case "figure":154 s.inspectorPane = nil155 let charts = [ChartKind.line, .scatter, .boxPlot, .heatmap].map { k -> ChartSpec in156 s.activateSheet(Demo.sheet(for: k))157 let spec = Demo.spec(k, s)158 Demo.place(spec, s, x: 560, y: 30, w: 460, h: 300)159 return spec160 }161 s.activateSheet(0)162 let template = FigureTemplates.template(id: value("--template") ?? "academic-double") ?? FigureTemplates.academicDoubleColumn163 ChartsFeature.openFigureStudio(editing: nil, in: s)164 ChartsState.of(s).figureDraft = template.makeFigure(charts: charts, title: "")165 if let out = value("--export-figure"), let d = ChartsState.of(s).figureDraft {166 let snap = ChartSnapshot.capture(d.panels.map(\.chart), workbook: s.workbook, lock: s.engine.lock)167 let format = ChartExportFormat(rawValue: URL(fileURLWithPath: out).pathExtension) ?? .pdf168 try? ChartExporter.data(d, source: snap, format: format, dpi: 300, formatter: ChartFormat.formatter(date1904: snap.date1904))?.write(to: URL(fileURLWithPath: out))169 }170 if let i = value("--panel").flatMap({ Int($0) }), let d = ChartsState.of(s).figureDraft, i < d.panels.count { ChartsState.of(s).figureSelectedPanel = d.panels[i].id }171 case "dashboard":172 s.activateSheet(4)173 s.inspectorPane = nil174 // the table is laid out with one series per row175 var d = Demo.detection(s, 4, "A2:E7"); d.seriesInRows = true; d.firstRowIsHeader = true; d.firstColumnIsCategories = true176 var combo = ChartBuilder.spec(.combo, d)177 combo.series = [combo.series[0], combo.series[2], combo.series[4]]178 for i in combo.series.indices { combo.series[i].kind = i == 0 ? .column : .line; combo.series[i].axis = .primary }179 combo.title = "Quarterly results"; combo.subtitle = "Synthetic sample data"; combo.yAxis.numberFormat = "#,##0"180 Demo.place(combo, s, x: 660, y: 20, w: 470, h: 290)181 Demo.place(Demo.spec(.waterfall, s), s, x: 20, y: 330, w: 400, h: 290)182 Demo.place(Demo.spec(.donut, s), s, x: 440, y: 330, w: 330, h: 290)183 var md = Demo.detection(s, 4, "A2:E8"); md.seriesInRows = true; md.firstRowIsHeader = true; md.firstColumnIsCategories = true184 var margin = ChartBuilder.spec(.line, md)185 margin.series = [margin.series[5]]186 margin.title = "Operating margin"; margin.yAxis.numberFormat = "0.0%"; margin.subtitle = "Synthetic sample data"187 margin.annotations = [.referenceLine(.horizontal, at: 0.27, label: "Target 27%")]188 Demo.place(margin, s, x: 790, y: 330, w: 340, h: 290)189 s.selectedObjectID = nil190 s.select(RangeRef(a1: "A1")!)191 case "perf":192 s.activateSheet(0); s.inspectorPane = nil193 let kinds: [ChartKind] = [.column, .line, .area, .bar, .combo, .radar, .column, .line, .area, .bar]194 for (i, k) in kinds.enumerated() {195 Demo.place(Demo.spec(k, s), s, x: 700 + Double(i % 3) * 250, y: 20 + Double(i / 3) * 190, w: 240, h: 180)196 }197 s.selectedObjectID = nil198 default:199 s.select(RangeRef(a1: "A1")!)200 Demo.place(Demo.spec(kind, s), s, x: 740, y: 20, w: 460, h: 290)201 Demo.place(Demo.spec(.line, s), s, x: 20, y: 300, w: 450, h: 290)202 Demo.place(Demo.spec(.area, s), s, x: 490, y: 330, w: 450, h: 260)203 s.selectedObjectID = nil204 s.inspectorPane = nil205 }206207 window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)208 window.title = "ORIX Sheet — charts preview"209 let root = ZStack {210 WorkbookView(session: s)211 if overlay { PickerOverlay(session: s) }212 }213 window.contentView = NSHostingView(rootView: root)214 window.center()215 window.makeKeyAndOrderFront(nil)216 NSApp.activate(ignoringOtherApps: false)217218 if state == "perf" { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { MainActor.assumeIsolated { self.measure() } }; return }219 if let out = shot {220 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {221 MainActor.assumeIsolated {222 guard let view = self.window.contentView, let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { exit(2) }223 view.cacheDisplay(in: view.bounds, to: rep)224 try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))225 let st = ChartRenderCache.shared.stats226 if let g = self.session.gridView { print(String(format: "grid draw: %.2f ms (%d draws)", g.lastDrawDuration * 1000, g.drawCount)) }227 print(String(format: "chart cache: %d hits (mean %.3f ms), %d misses (mean %.2f ms), %d vector draws",228 st.hits, st.meanHitSeconds * 1000, st.misses, st.meanMissSeconds * 1000, st.vectorDraws))229 exit(0)230 }231 }232 }233 }234235 /// Measures the object renderer on a sheet with ten charts: cache hits (plain redraws), misses (every chart236 /// re-rendered after a data change) and the whole grid redraw time.237 @MainActor func measure() {238 guard let grid = session.gridView else { print("no grid"); exit(2) }239 let cache = ChartRenderCache.shared240 cache.vectorWhenOffscreen = false241 func redraw() -> Double { grid.needsDisplay = true; grid.displayIfNeeded(); return grid.lastDrawDuration }242 _ = redraw()243 cache.resetStats()244 var gridHit = 0.0245 for _ in 0..<50 { gridHit += redraw() }246 let hit = cache.stats247 cache.resetStats()248 var gridMiss = 0.0249 for i in 0..<20 {250 session.perform("edit") { e in for r in 1...12 { e.set(sheet: 0, row: r, col: 1, .value(.number(Double(100 + i * 3 + r)))) } }251 gridMiss += redraw()252 }253 let miss = cache.stats254 print(String(format: "10 charts, cache hit : %.4f ms per chart (%d draws), grid redraw %.2f ms", hit.meanHitSeconds * 1000, hit.hits, gridHit / 50 * 1000))255 print(String(format: "10 charts, cache miss: %.3f ms per chart (%d renders, %d hits), grid redraw %.2f ms", miss.meanMissSeconds * 1000, miss.misses, miss.hits, gridMiss / 20 * 1000))256 exit(0)257 }258259 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }260}261262let app = NSApplication.shared263let delegate = AppDelegate()264app.delegate = delegate265app.setActivationPolicy(CommandLine.arguments.contains("--shot") || CommandLine.arguments.contains("perf") ? .accessory : .regular)266app.run()267