import AppKit import CoreGraphics import CoreText import Foundation import ImageIO import os private let pdfLog = Logger(subsystem: "ai.flowmaster.shotdeck", category: "PDF") public struct PDFComposer: Sendable { public init() {} /// `toolVersion` is the running Redline version (CFBundleShortVersionString) and /// `composedAt` the build time; both are printed in the page footer and the PDF's /// document info so a printed or returned page says which tools produced it. @discardableResult public func compose( session: CaptureSession, imageURL: (Capture) -> URL, title: String, to outputURL: URL, toolVersion: String = "", composedAt: Date = Date() ) throws -> Int { if session.isEmpty { throw ShotdeckError.pdfCompositionFailed(reason: "session has no captures") } var loaded: [(Capture, CGImage)] = [] loaded.reserveCapacity(session.captures.count) for capture in session.captures { let url = imageURL(capture) if let image = Self.loadCGImage(from: url) { loaded.append((capture, image)) } else { pdfLog.error( "skipping capture \(capture.id.uuidString, privacy: .public) seq \(capture.sequence, privacy: .public): image unreadable at \(url.path, privacy: .public)" ) } } guard !loaded.isEmpty else { throw ShotdeckError.pdfCompositionFailed(reason: "no readable images in session") } let pageCount = loaded.count let tmpURL = outputURL .deletingLastPathComponent() .appendingPathComponent(".tmp-\(UUID().uuidString)-\(outputURL.lastPathComponent)") let footerLines = Self.footerLines( session: session, toolVersion: toolVersion, composedAt: composedAt) do { try Self.writePDF( loaded: loaded, pageCount: pageCount, title: title, sessionID: session.id, footerLines: footerLines, metadata: Self.documentInfo( session: session, title: title, toolVersion: toolVersion, composedAt: composedAt), to: tmpURL ) let handle = try FileHandle(forWritingTo: tmpURL) try handle.synchronize() try handle.close() if FileManager.default.fileExists(atPath: outputURL.path) { try FileManager.default.removeItem(at: outputURL) } try FileManager.default.moveItem(at: tmpURL, to: outputURL) return pageCount } catch { try? FileManager.default.removeItem(at: tmpURL) if let shotdeck = error as? ShotdeckError { throw shotdeck } throw ShotdeckError.pdfCompositionFailed(reason: error.localizedDescription) } } /// `Redline---.pdf` — see `PDFFileName`. public static func fileName(for session: CaptureSession) -> String { PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id) } /// Both footer lines for a session, untruncated. Line 1 identifies the document /// (tool, build time, session); line 2 states what it reviewed (lane, deployed /// build, commit, reviewer, note). Empty context fields are omitted rather than /// printed as blanks. public static func footerLines( session: CaptureSession, toolVersion: String, composedAt: Date ) -> [String] { let tool = toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)" let first = "\(tool) · \(DubaiTime.stamp(composedAt)) · Session \(session.shortID)" let context = session.context var review: [String] = [] if !context.lane.isEmpty { review.append("Lane \(context.lane)") } if !context.deployedVersion.isEmpty { review.append("Deployed \(context.deployedVersion)") } if !context.commit.isEmpty { review.append("Commit \(context.commit)") } if !context.reviewer.isEmpty { review.append("Reviewer \(context.reviewer)") } if !context.note.isEmpty { review.append("Note \(context.note)") } return review.isEmpty ? [first] : [first, review.joined(separator: " · ")] } /// The PDF document info a reader sees in Preview/Acrobat. The subject stays the /// session UUID (it is the stable machine handle); everything a person needs to /// identify the review is in Author/Keywords as well as the page footers. public static func documentInfo( session: CaptureSession, title: String, toolVersion: String, composedAt: Date ) -> [String: Any] { let context = session.context // Commas separate keywords in the PDF format itself, so a value containing one // would silently split into two keywords (and PDF readers return a list // instead of a string). Strip them from every keyword value. func keywordValue(_ raw: String) -> String { raw.replacingOccurrences(of: ",", with: " ") .split(whereSeparator: \.isWhitespace) .joined(separator: " ") } var keywords: [String] = ["Redline", "session=\(session.shortID)"] if !context.lane.isEmpty { keywords.append("lane=\(keywordValue(context.lane))") } if !context.deployedVersion.isEmpty { keywords.append("deployed=\(keywordValue(context.deployedVersion))") } if !context.commit.isEmpty { keywords.append("commit=\(keywordValue(context.commit))") } if !context.reviewer.isEmpty { keywords.append("reviewer=\(keywordValue(context.reviewer))") } if !context.note.isEmpty { keywords.append("note=\(keywordValue(context.note))") } keywords.append("built=\(DubaiTime.keywordStamp(composedAt))") if !toolVersion.isEmpty { keywords.append("tool=\(toolVersion)") } var info: [String: Any] = [ kCGPDFContextCreator as String: toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)", kCGPDFContextTitle as String: title, kCGPDFContextSubject as String: session.id.uuidString.lowercased(), kCGPDFContextKeywords as String: keywords.joined(separator: "; "), ] if !context.reviewer.isEmpty { info[kCGPDFContextAuthor as String] = context.reviewer } return info } private static func writePDF( loaded: [(Capture, CGImage)], pageCount: Int, title: String, sessionID: UUID, footerLines: [String], metadata: [String: Any], to tmpURL: URL ) throws { guard let consumer = CGDataConsumer(url: tmpURL as CFURL) else { throw ShotdeckError.pdfCompositionFailed(reason: "cannot open output location") } let auxiliaryInfo = metadata guard let context = CGContext( consumer: consumer, mediaBox: nil, auxiliaryInfo as CFDictionary ) else { throw ShotdeckError.pdfCompositionFailed(reason: "cannot open output location") } let lightGrey = CGColor(gray: 0.75, alpha: 1) let black = CGColor(gray: 0, alpha: 1) let timestampColor = CGColor(gray: 0.45, alpha: 1) for pageIndex in 1...pageCount { let (capture, cgImage) = loaded[pageIndex - 1] let layout = PageLayout( capture: capture, pageIndex: pageIndex, pageCount: pageCount, footerLines: footerLines) context.beginPDFPage(Self.pageInfo(mediaBox: layout.pageRect)) context.draw(cgImage, in: layout.imageRect) context.setStrokeColor(lightGrey) context.setLineWidth(0.5) context.move(to: CGPoint(x: layout.headerRect.minX, y: layout.headerRect.minY)) context.addLine(to: CGPoint(x: layout.headerRect.maxX, y: layout.headerRect.minY)) context.strokePath() drawText( layout.pageNumberText, font: layout.pageNumberFont, color: black, at: layout.pageNumberOrigin, in: context ) drawText( layout.timestampText, font: layout.timestampFont, color: timestampColor, at: layout.timestampOrigin, in: context ) drawText( "PASS", font: layout.tickLabelFont, color: black, at: layout.passLabelOrigin, in: context ) drawText( "FAIL", font: layout.tickLabelFont, color: black, at: layout.failLabelOrigin, in: context ) strokeTickBox(layout.passTickBox, in: context, color: black) strokeTickBox(layout.failTickBox, in: context, color: black) for (line, origin) in zip(layout.footerLines, layout.footerOrigins) { drawTruncatedText( line, font: layout.footerFont, color: timestampColor, at: origin, maxWidth: layout.footerRect.width, in: context ) } context.endPDFPage() } context.closePDF() } private static func pageInfo(mediaBox: CGRect) -> CFDictionary { var box = mediaBox let data = Data(bytes: &box, count: MemoryLayout.size) return [kCGPDFContextMediaBox as String: data] as CFDictionary } private static func drawText( _ string: String, font: NSFont, color: CGColor, at origin: CGPoint, in context: CGContext ) { let attributes: [CFString: Any] = [ kCTFontAttributeName: font, kCTForegroundColorAttributeName: color, ] guard let attributed = CFAttributedStringCreate( nil, string as CFString, attributes as CFDictionary ) else { return } let line = CTLineCreateWithAttributedString(attributed) context.textMatrix = .identity context.textPosition = origin CTLineDraw(line, context) } /// Draws one footer line, truncated with an ellipsis when it is wider than the /// page content width — the reference block must never run into the page edge. private static func drawTruncatedText( _ string: String, font: NSFont, color: CGColor, at origin: CGPoint, maxWidth: CGFloat, in context: CGContext ) { let attributes: [CFString: Any] = [ kCTFontAttributeName: font, kCTForegroundColorAttributeName: color, ] guard let attributed = CFAttributedStringCreate( nil, string as CFString, attributes as CFDictionary) else { return } var line = CTLineCreateWithAttributedString(attributed) if CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) > maxWidth, let ellipsisAttributed = CFAttributedStringCreate( nil, "…" as CFString, attributes as CFDictionary) { let ellipsis = CTLineCreateWithAttributedString(ellipsisAttributed) if let truncated = CTLineCreateTruncatedLine( line, Double(maxWidth), .end, ellipsis) { line = truncated } } context.textMatrix = .identity context.textPosition = origin CTLineDraw(line, context) } private static func strokeTickBox(_ box: CGRect, in context: CGContext, color: CGColor) { let path = CGPath( roundedRect: box, cornerWidth: 2, cornerHeight: 2, transform: nil ) context.addPath(path) context.setStrokeColor(color) context.setLineWidth(1.0) context.strokePath() } private static func loadCGImage(from url: URL) -> CGImage? { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil } return CGImageSourceCreateImageAtIndex(source, 0, nil) } }