import AppKit import Foundation /// Renders review derivatives with two untouched screenshots and an independently sized recommendation column. let root = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true) let manifestData = try Data(contentsOf: root.appendingPathComponent("manifest.json")) let manifest = try JSONSerialization.jsonObject(with: manifestData) as! [String: Any] let pairs = manifest["pairs"] as! [[String: Any]] let output = root.appendingPathComponent("comparison", isDirectory: true) try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) /// Returns review fields as display text while accepting optional or array-valued notes. func textValue(_ value: Any?) -> String { if let string = value as? String { return string.trimmingCharacters(in: .whitespacesAndNewlines) } if let strings = value as? [String] { return strings.joined(separator: "\n") } return "" } /// Supplies a readable conclusion if a review object only specifies its baseline. func recommendationLabel(_ recommendation: [String: Any]) -> String { let label = textValue(recommendation["label"]) if !label.isEmpty { return label } let baseline = textValue(recommendation["baseline"]) switch baseline.lowercased() { case "ios": return "以 iOS 为准" case "android": return "以 Android 为准" case "both", "mixed", "mix", "hybrid": return "结合两端" case "keep", "native", "platform": return "保留平台习惯" case "", "pending": return "待补充建议" default: return baseline } } /// Measures wrapped Chinese or Latin paragraphs with the same attributes used during drawing. func styledText(_ text: String, size: CGFloat, color: NSColor = .black, weight: NSFont.Weight = .regular) -> NSAttributedString { let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byWordWrapping paragraph.lineSpacing = 4 return NSAttributedString(string: text, attributes: [ .font: NSFont.systemFont(ofSize: size, weight: weight), .foregroundColor: color, .paragraphStyle: paragraph ]) } /// Includes a small drawing allowance so the last line never clips at a fractional glyph boundary. func textHeight(_ text: NSAttributedString, width: CGFloat) -> CGFloat { let bounds = text.boundingRect(with: NSSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading]) return ceil(bounds.height) + 6 } /// Draws every wrapped line and returns the consumed vertical space. @discardableResult func wrappedLabel(_ text: NSAttributedString, x: CGFloat, y: CGFloat, width: CGFloat) -> CGFloat { let height = textHeight(text, width: width) text.draw(with: NSRect(x: x, y: y, width: width, height: height), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) return height } /// Draws short headings with the same minimum type size as all other review text. func label(_ text: String, x: CGFloat, y: CGFloat, width: CGFloat, size: CGFloat, color: NSColor = .black, weight: NSFont.Weight = .regular) { wrappedLabel(styledText(text, size: size, color: color, weight: weight), x: x, y: y, width: width) } /// Reads source screenshots without writing or transforming their files. func image(_ record: [String: Any]?) -> NSImage? { guard let path = record?["path"] as? String else { return nil } return NSImage(contentsOf: root.appendingPathComponent(path)) } /// Creates a correctly oriented PNG canvas used exclusively for derived comparison images. func render(width: Int, height: Int, file: URL, draw: () -> Void) throws { let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! let context = NSGraphicsContext(bitmapImageRep: rep)! NSGraphicsContext.saveGraphicsState() context.cgContext.translateBy(x: 0, y: CGFloat(height)) context.cgContext.scaleBy(x: 1, y: -1) let flipped = NSGraphicsContext(cgContext: context.cgContext, flipped: true) NSGraphicsContext.current = flipped flipped.imageInterpolation = .high NSColor.white.setFill() NSRect(x: 0, y: 0, width: width, height: height).fill() draw() NSGraphicsContext.restoreGraphicsState() try rep.representation(using: .png, properties: [:])!.write(to: file) } /// Scales each complete source image to its column width without cropping. func drawImage(_ img: NSImage?, x: CGFloat, y: CGFloat, width: CGFloat, placeholderHeight: CGFloat) { guard let img else { NSColor(white: 0.96, alpha: 1).setFill() NSRect(x: x, y: y, width: width, height: placeholderHeight).fill() label("本次未截图", x: x + 20, y: y + 50, width: width - 40, size: 20, color: .secondaryLabelColor) return } let height = img.size.height * width / img.size.width img.draw(in: NSRect(x: x, y: y, width: width, height: height), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) } /// Describes one measured block in the right-hand review column. struct ReviewBlock { let content: NSAttributedString let trailingSpace: CGFloat } /// Separates the conclusion, rationale, action, and limitations without truncating any field. func reviewBlocks(_ recommendation: [String: Any]) -> [ReviewBlock] { var blocks = [ReviewBlock(content: styledText(recommendationLabel(recommendation), size: 25, weight: .semibold), trailingSpace: 28)] for (key, heading) in [("reason", "理由"), ("action", "建议调整"), ("note", "对照说明")] { let value = textValue(recommendation[key]) guard !value.isEmpty else { continue } blocks.append(ReviewBlock(content: styledText(heading, size: 18, color: .secondaryLabelColor, weight: .medium), trailingSpace: 6)) blocks.append(ReviewBlock(content: styledText(value, size: key == "note" ? 18 : 20), trailingSpace: 26)) } return blocks } let screenshotWidth: CGFloat = 540 let reviewX: CGFloat = 1180 let reviewWidth: CGFloat = 320 let canvasWidth = 1534 for (index, pair) in pairs.enumerated() { let a = image(pair["ios"] as? [String: Any]) let b = image(pair["android"] as? [String: Any]) let recommendation = pair["recommendation"] as? [String: Any] ?? [:] let blocks = reviewBlocks(recommendation) let reviewHeight = blocks.reduce(CGFloat(0)) { $0 + textHeight($1.content, width: reviewWidth) + $1.trailingSpace } let imageHeight = max(a.map { $0.size.height * screenshotWidth / $0.size.width } ?? 240, b.map { $0.size.height * screenshotWidth / $0.size.width } ?? 240) let contentHeight = max(imageHeight, reviewHeight) let filename = String(format: "%02d-", index + 1) + (pair["key"] as! String) + ".png" try render(width: canvasWidth, height: Int(ceil(contentHeight + 190)), file: output.appendingPathComponent(filename)) { label(pair["title"] as! String, x: 34, y: 20, width: CGFloat(canvasWidth - 68), size: 30, weight: .semibold) label("iOS", x: 34, y: 76, width: screenshotWidth, size: 25, weight: .medium) label("Android", x: 606, y: 76, width: screenshotWidth, size: 25, weight: .medium) label("推荐以哪端为准", x: reviewX, y: 76, width: reviewWidth, size: 24, weight: .medium) drawImage(a, x: 34, y: 120, width: screenshotWidth, placeholderHeight: 240) drawImage(b, x: 606, y: 120, width: screenshotWidth, placeholderHeight: 240) NSColor(white: 0.88, alpha: 1).setFill() NSRect(x: 1162, y: 120, width: 1, height: contentHeight).fill() var y: CGFloat = 120 for block in blocks { y += wrappedLabel(block.content, x: reviewX, y: y, width: reviewWidth) + block.trailingSpace } label("本地模拟 · 2026-11-05 · 完整原图请查看 ios / android 目录", x: 34, y: contentHeight + 144, width: CGFloat(canvasWidth - 68), size: 18, color: .secondaryLabelColor) } } /// Stores measured overview geometry so long recommendation labels expand the corresponding row. struct OverviewCell { let pair: [String: Any] let iosImage: NSImage? let androidImage: NSImage? let title: NSAttributedString let recommendation: NSAttributedString let titleHeight: CGFloat let recommendationHeight: CGFloat let imageOffset: CGFloat let height: CGFloat } let overviewColumns = 3 let cellWidth: CGFloat = 476 let cellContentWidth: CGFloat = 450 let overviewImageWidth: CGFloat = 216 let cells: [OverviewCell] = pairs.enumerated().map { index, pair in let a = image(pair["ios"] as? [String: Any]) let b = image(pair["android"] as? [String: Any]) let title = styledText(String(format: "%02d ", index + 1) + (pair["title"] as! String), size: 20, weight: .medium) let recommendation = styledText("建议:" + recommendationLabel(pair["recommendation"] as? [String: Any] ?? [:]), size: 18, color: .systemBlue, weight: .medium) let titleHeight = textHeight(title, width: cellContentWidth) let recommendationHeight = textHeight(recommendation, width: cellContentWidth) let imageOffset = titleHeight + 6 + recommendationHeight + 8 + 32 let imageHeight = max(a.map { $0.size.height * overviewImageWidth / $0.size.width } ?? 180, b.map { $0.size.height * overviewImageWidth / $0.size.width } ?? 180) return OverviewCell(pair: pair, iosImage: a, androidImage: b, title: title, recommendation: recommendation, titleHeight: titleHeight, recommendationHeight: recommendationHeight, imageOffset: imageOffset, height: imageOffset + imageHeight + 64) } let rows = Int(ceil(Double(cells.count) / Double(overviewColumns))) let rowHeights: [CGFloat] = (0..