SPB Git

Repository Public

main.swift 8.3 KB 181 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetTemplates/Sources/templates-preview/main.swift10// Module           : templates-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 SheetEngine91import SheetUI92import SheetFormat93import SheetTemplates94#if HAS_FEATURE_CHARTS95import FeatureCharts96#endif97#if HAS_FEATURE_AUDIT98import FeatureAudit99#endif100101// Development harness of SheetTemplates: opens a template in a WorkbookView window.102//   templates-preview --template <id> [--locale fr_CA] [--dark] [--sheet <n>] [--size WxH] [--shot out.png] [--chrome]103//   templates-preview --list104// With --shot the window content is rendered to a PNG by the app itself and the process exits.105// Charts are drawn when FeatureCharts is linked, conditional formats when FeatureAudit is linked (see Package.swift);106// the harness prints which of the two are active.107108/// A window that keeps the requested size even when it is larger than the screen (for --shot).109final class UnconstrainedWindow: NSWindow {110    override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect { frameRect }111}112113final class AppDelegate: NSObject, NSApplicationDelegate {114    var window: NSWindow!115    var session: WorkbookSession!116117    func applicationDidFinishLaunching(_ notification: Notification) {118        let args = CommandLine.arguments119        func value(_ flag: String) -> String? { args.firstIndex(of: flag).flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil } }120        var size = NSSize(width: 1480, height: 920)121        if let s = value("--size")?.split(separator: "x").compactMap({ Double($0) }), s.count == 2 { size = NSSize(width: s[0], height: s[1]) }122        if args.contains("--dark") { NSApp.appearance = NSAppearance(named: .darkAqua) }123        let locale = Locale(identifier: value("--locale") ?? "en_CA")124        let shot = value("--shot")125126        ORIXEngine.bootstrap()127        Workspace.shared.displayProvider = FormatDisplayProvider(locale: FormatLocale(locale: locale))128        var features: [String] = []129        #if HAS_FEATURE_CHARTS130        ChartsFeature.register()131        if shot != nil { ChartRenderCache.shared.vectorWhenOffscreen = false }132        features.append("charts")133        #endif134        #if HAS_FEATURE_AUDIT135        AuditFeature.register()136        features.append("conditional formats")137        #endif138        print("rendering features: \(features.isEmpty ? "none (charts are placeholders, no conditional formats)" : features.joined(separator: ", "))")139140        guard let template = TemplateLibrary.template(id: value("--template") ?? TemplateLibrary.all[0].id) else {141            FileHandle.standardError.write(Data("unknown template; use --list\n".utf8)); exit(2)142        }143        let workbook = template.build(locale: locale)144        session = WorkbookSession(workbook: workbook, locale: locale)145        session.showSidebar = false146        if !args.contains("--chrome") { session.inspectorPane = nil }147        if let n = value("--sheet").flatMap({ Int($0) }), n >= 0, n < workbook.sheets.count { session.activateSheet(n) }148        if let cell = value("--cell").flatMap({ CellRef(a1: $0) }) { session.select(RangeRef(cell), active: cell) }149150        window = (shot != nil ? UnconstrainedWindow.self : NSWindow.self).init(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)151        window.title = "ORIX Sheet — \(template.title(locale: locale))"152        window.contentView = NSHostingView(rootView: WorkbookView(session: session))153        if shot == nil { window.center() } else { window.setFrameOrigin(NSPoint(x: 0, y: 0)) }154        window.makeKeyAndOrderFront(nil)155        NSApp.activate(ignoringOtherApps: false)156        if let out = shot {157            func capture(final: Bool) {158                guard let view = window.contentView, let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { exit(2) }159                view.cacheDisplay(in: view.bounds, to: rep)160                guard final else { return }161                try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))162                exit(0)163            }164            // a first pass lets asynchronous chart renders complete before the picture is taken165            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { MainActor.assumeIsolated { capture(final: false) } }166            DispatchQueue.main.asyncAfter(deadline: .now() + 2.2) { MainActor.assumeIsolated { capture(final: true) } }167        }168    }169    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }170}171172if CommandLine.arguments.contains("--list") {173    for t in TemplateLibrary.all { print("\(t.id)\t\(t.category.rawValue)\t\(t.title)") }174    exit(0)175}176let app = NSApplication.shared177let delegate = AppDelegate()178app.delegate = delegate179app.setActivationPolicy(CommandLine.arguments.contains("--shot") ? .accessory : .regular)180app.run()181
Files main
Menu

Theme