SPB Git

Repository Public License

PDFReportRenderer.swift 13.3 KB 294 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Monitor9// File             : App/Sources/Reporting/PDFReportRenderer.swift10// Description      : Paginated PDF rendering of a report with Core Text:11//                    headings, tables, per-metric charts drawn from the stored12//                    points.13// Module           : Reporting14// Repository       : https://git.spboucher.ai/orix-monitor15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AppKit92import CoreText93import ORIXMonitorCore9495/// A small top-down layout engine over a PDF context. Everything it draws comes from the `Report` value.96@MainActor97final class PDFReportRenderer {98    private let page = CGRect(x: 0, y: 0, width: 612, height: 792)   // US Letter, points99    private let margin: CGFloat = 48100    private var context: CGContext!101    private var y: CGFloat = 0102    private var pageNumber = 0103    private let report: Report104    private let f: ValueFormatter105    private let ink = NSColor(hex: 0x0E1222), muted = NSColor(hex: 0x596078), line = NSColor(hex: 0xDDE0EA), accent = NSColor(hex: 0x0891B2)106107    init(report: Report, formatter: ValueFormatter) {108        self.report = report109        f = formatter110    }111112    private var width: CGFloat { page.width - 2 * margin }113114    func render() -> Data {115        let data = NSMutableData()116        var box = page117        guard let consumer = CGDataConsumer(data: data as CFMutableData), let ctx = CGContext(consumer: consumer, mediaBox: &box, [118            kCGPDFContextTitle: report.title, kCGPDFContextCreator: "ORIX Monitor \(report.appVersion)",119        ] as CFDictionary) else { return Data() }120        context = ctx121        newPage()122        text(report.title, size: 22, weight: .bold)123        text("ORIX Monitor \(report.appVersion) · \(L("Generated")) \(f.date(report.generated))", size: 9, color: muted)124        text("\(L("Period")): \(f.date(report.from)) → \(f.date(report.to)) · \(L("Sampling interval")): \(f.number(report.samplingInterval, digits: 1)) s", size: 9, color: muted)125        space(10)126127        heading(L("System"))128        table([L("Item"), L("Value")], report.system, weights: [1, 2.4])129130        heading(L("Metrics"))131        table([L("Metric"), L("Minimum"), L("Average"), L("Maximum"), L("Samples"), L("Quality")], report.series.map { s in132            [s.name, s.minimum.map { value($0, s) } ?? "—", s.average.map { value($0, s) } ?? "—", s.maximum.map { value($0, s) } ?? "—", String(s.sampleCount), L(s.quality.rawValue)]133        }, weights: [2.2, 1.2, 1.2, 1.2, 0.9, 1])134135        for s in report.series where s.points.count > 1 { chart(s) }136        for t in report.tables {137            heading(t.title)138            table(t.headers, t.rows, weights: t.headers.indices.map { $0 == 0 ? 2 : 1 })139        }140        if !report.findings.isEmpty {141            heading(L("Findings"))142            for finding in report.findings {143                text("• \(FindingText.title(finding)) — \(finding.severity.title)", size: 10, weight: .semibold)144                text(FindingText.explanation(finding, f), size: 9, color: muted, indent: 10)145            }146        }147        heading(L("Collection methods"))148        for s in report.series {149            text("\(s.name) — \(s.source)", size: 9, weight: .semibold)150            text(L(s.method), size: 8.5, color: muted, indent: 10)151        }152        heading(L("Data gaps"))153        let gaps = report.series.filter { !$0.gaps.isEmpty }154        if gaps.isEmpty {155            text(L("No gap in the selected period."), size: 9, color: muted)156        } else {157            table([L("Metric"), L("Gaps"), L("Total missing"), L("Longest")], gaps.map {158                [$0.name, String($0.gaps.count), f.duration($0.gaps.reduce(0) { $0 + $1.duration }), f.duration($0.gaps.map(\.duration).max() ?? 0)]159            }, weights: [2, 1, 1.4, 1.4])160        }161        heading(L("Limitations"))162        for item in report.limitations { text("• \(item)", size: 9, color: muted) }163        footer()164        context.endPDFPage()165        context.closePDF()166        return data as Data167    }168169    private func value(_ v: Double, _ s: ReportSeriesSummary) -> String { AlertText.formatted(v, metric: s.metric, formatter: f) }170171    // MARK: Primitives172173    private func newPage() {174        if pageNumber > 0 {175            footer()176            context.endPDFPage()177        }178        context.beginPDFPage(nil)179        pageNumber += 1180        y = page.height - margin181    }182183    private func footer() {184        draw(attributed("ORIX Monitor · \(report.title) · \(pageNumber)", size: 8, weight: .regular, color: muted), at: CGPoint(x: margin, y: 26), width: width)185    }186187    private func ensure(_ height: CGFloat) { if y - height < margin + 16 { newPage() } }188    private func space(_ amount: CGFloat) { y -= amount }189190    private func attributed(_ string: String, size: CGFloat, weight: NSFont.Weight, color: NSColor) -> NSAttributedString {191        NSAttributedString(string: string, attributes: [.font: NSFont.systemFont(ofSize: size, weight: weight), .foregroundColor: color])192    }193194    private func height(_ string: NSAttributedString, width: CGFloat) -> CGFloat {195        let setter = CTFramesetterCreateWithAttributedString(string)196        return ceil(CTFramesetterSuggestFrameSizeWithConstraints(setter, CFRange(), nil, CGSize(width: width, height: .greatestFiniteMagnitude), nil).height)197    }198199    /// Draws text whose top-left corner is at (x, top), wrapping to `width`.200    @discardableResult201    private func draw(_ string: NSAttributedString, at origin: CGPoint, width: CGFloat) -> CGFloat {202        let h = height(string, width: width)203        let setter = CTFramesetterCreateWithAttributedString(string)204        let frame = CTFramesetterCreateFrame(setter, CFRange(), CGPath(rect: CGRect(x: origin.x, y: origin.y - h, width: width, height: h), transform: nil), nil)205        CTFrameDraw(frame, context)206        return h207    }208209    private func text(_ string: String, size: CGFloat, weight: NSFont.Weight = .regular, color: NSColor? = nil, indent: CGFloat = 0) {210        let a = attributed(string, size: size, weight: weight, color: color ?? ink)211        let h = height(a, width: width - indent)212        ensure(h)213        draw(a, at: CGPoint(x: margin + indent, y: y), width: width - indent)214        y -= h + 3215    }216217    private func heading(_ string: String) {218        ensure(60)219        space(12)220        text(string, size: 13, weight: .bold)221        context.setStrokeColor(accent.cgColor)222        context.setLineWidth(1)223        context.move(to: CGPoint(x: margin, y: y))224        context.addLine(to: CGPoint(x: margin + width, y: y))225        context.strokePath()226        space(8)227    }228229    private func table(_ headers: [String], _ rows: [[String]], weights: [CGFloat]) {230        let total = weights.reduce(0, +)231        let widths = weights.map { $0 / total * width }232        func row(_ cells: [String], header: Bool) {233            let strings = cells.enumerated().map { attributed($0.element, size: header ? 8 : 8.5, weight: header ? .semibold : .regular, color: header ? muted : ink) }234            let h = zip(strings, widths).map { height($0, width: $1 - 6) }.max() ?? 10235            ensure(h + 6)236            var x = margin237            for (string, w) in zip(strings, widths) {238                draw(string, at: CGPoint(x: x, y: y), width: w - 6)239                x += w240            }241            y -= h + 3242            context.setStrokeColor(line.cgColor)243            context.setLineWidth(0.5)244            context.move(to: CGPoint(x: margin, y: y))245            context.addLine(to: CGPoint(x: margin + width, y: y))246            context.strokePath()247            y -= 3248        }249        row(headers, header: true)250        for cells in rows { row(Array(cells.prefix(headers.count)) + Array(repeating: "", count: max(0, headers.count - cells.count)), header: false) }251        space(4)252    }253254    /// Min–max band and average line of one stored series. The line is broken wherever the store reported a gap.255    private func chart(_ s: ReportSeriesSummary) {256        let h: CGFloat = 96257        ensure(h + 34)258        text("\(s.name) · \(L(s.tier.rawValue)) · \(f.duration(s.step))", size: 9, weight: .semibold)259        let rect = CGRect(x: margin + 54, y: y - h, width: width - 54, height: h)260        let lo = min(0, s.minimum ?? 0), hi = max(s.maximum ?? 1, lo + 1e-9)261        let t0 = report.from.timeIntervalSince1970, t1 = max(report.to.timeIntervalSince1970, t0 + 1)262        func point(_ time: Double, _ v: Double) -> CGPoint {263            CGPoint(x: rect.minX + CGFloat((time - t0) / (t1 - t0)) * rect.width, y: rect.minY + CGFloat((v - lo) / (hi - lo)) * rect.height)264        }265        context.setFillColor(NSColor(hex: 0xF4F5FA).cgColor)266        context.fill(rect)267        context.setFillColor(muted.withAlphaComponent(0.12).cgColor)268        for gap in s.gaps { context.fill(CGRect(x: point(gap.start, lo).x, y: rect.minY, width: max(0.5, point(gap.end, lo).x - point(gap.start, lo).x), height: rect.height)) }269        var runs: [[SeriesPoint]] = [[]]270        for p in s.points {271            if let last = runs[runs.count - 1].last, p.time - last.time > s.step * 2.5 { runs.append([]) }272            runs[runs.count - 1].append(p)273        }274        for run in runs where !run.isEmpty {275            let band = CGMutablePath()276            band.move(to: point(run[0].time, run[0].max))277            for p in run.dropFirst() { band.addLine(to: point(p.time, p.max)) }278            for p in run.reversed() { band.addLine(to: point(p.time, p.min)) }279            band.closeSubpath()280            context.addPath(band)281            context.setFillColor(accent.withAlphaComponent(0.2).cgColor)282            context.fillPath()283            context.move(to: point(run[0].time, run[0].avg))284            for p in run.dropFirst() { context.addLine(to: point(p.time, p.avg)) }285            context.setStrokeColor(accent.cgColor)286            context.setLineWidth(1)287            context.strokePath()288        }289        draw(attributed(value(hi, s), size: 7, weight: .regular, color: muted), at: CGPoint(x: margin, y: rect.maxY), width: 50)290        draw(attributed(value(lo, s), size: 7, weight: .regular, color: muted), at: CGPoint(x: margin, y: rect.minY + 9), width: 50)291        y -= h + 12292    }293}294
Files main
Menu

Theme