Repository Public License
1// ORIX Convert — App/Sources/Features/Shared/SampleFiles.swift2// Description: Sample files generated in code (Core Graphics, Core Text, ImageIO) for the self-test and the3// screenshots. Real, valid files: nothing is mocked.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import AppKit6import ConvertCore7import CoreText8import ImageIO9import UniformTypeIdentifiers1011nonisolated enum SampleFiles {12 /// A PDF with `pages` US-Letter pages of real text and a coloured band.13 @discardableResult14 static func makePDF(at url: URL, pages: Int, title: String) -> Bool {15 var box = CGRect(x: 0, y: 0, width: 612, height: 792)16 let info = [kCGPDFContextTitle: title, kCGPDFContextAuthor: "ORIX Convert", kCGPDFContextCreator: "ORIX Convert sample generator"] as CFDictionary17 guard let context = CGContext(url as CFURL, mediaBox: &box, info) else { return false }18 let palette: [CGColor] = [CGColor(red: 0.99, green: 0.73, blue: 0.30, alpha: 1), CGColor(red: 0.91, green: 0.31, blue: 0.62, alpha: 1),19 CGColor(red: 0.55, green: 0.36, blue: 0.96, alpha: 1), CGColor(red: 0.13, green: 0.83, blue: 0.93, alpha: 1)]20 for page in 1...max(1, pages) {21 context.beginPDFPage(nil)22 context.setFillColor(palette[(page - 1) % palette.count])23 context.fill(CGRect(x: 0, y: 700, width: 612, height: 92))24 draw("\(title)", size: 26, bold: true, at: CGPoint(x: 54, y: 735), in: context, color: CGColor(gray: 1, alpha: 1))25 draw("Page \(page) of \(max(1, pages))", size: 13, bold: false, at: CGPoint(x: 54, y: 712), in: context, color: CGColor(gray: 1, alpha: 1))26 for line in 0..<18 {27 draw("Line \(line + 1): the quick brown fox jumps over the lazy dog — page \(page).", size: 12, bold: false,28 at: CGPoint(x: 54, y: 650 - CGFloat(line) * 22), in: context, color: CGColor(gray: 0.1, alpha: 1))29 }30 context.endPDFPage()31 }32 context.closePDF()33 return FileManager.default.fileExists(atPath: url.path)34 }3536 private static func draw(_ text: String, size: CGFloat, bold: Bool, at point: CGPoint, in context: CGContext, color: CGColor) {37 let font = CTFontCreateWithName((bold ? "Helvetica-Bold" : "Helvetica") as CFString, size, nil)38 let attributes = [kCTFontAttributeName: font, kCTForegroundColorAttributeName: color] as CFDictionary39 guard let attributed = CFAttributedStringCreate(nil, text as CFString, attributes) else { return }40 let line = CTLineCreateWithAttributedString(attributed)41 context.textPosition = point42 CTLineDraw(line, context)43 }4445 /// A gradient image; `alpha` leaves a transparent hole in the middle (PNG).46 @discardableResult47 static func makeImage(at url: URL, width: Int, height: Int, type: UTType, alpha: Bool = false, seed: Int = 0) -> Bool {48 guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(),49 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return false }50 let hues: [[CGFloat]] = [[0.99, 0.73, 0.30], [0.98, 0.48, 0.36], [0.91, 0.31, 0.62], [0.55, 0.36, 0.96], [0.36, 0.55, 0.97], [0.13, 0.83, 0.93]]51 let a = hues[seed % hues.count], b = hues[(seed + 3) % hues.count]52 let colors = [CGColor(red: a[0], green: a[1], blue: a[2], alpha: 1), CGColor(red: b[0], green: b[1], blue: b[2], alpha: 1)] as CFArray53 if let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: [0, 1]) {54 context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: width, y: height), options: [])55 }56 context.setFillColor(CGColor(gray: 1, alpha: 0.85))57 context.fillEllipse(in: CGRect(x: Double(width) * 0.12, y: Double(height) * 0.5, width: Double(width) * 0.2, height: Double(width) * 0.2))58 if alpha {59 context.setBlendMode(.clear)60 context.fillEllipse(in: CGRect(x: Double(width) * 0.35, y: Double(height) * 0.25, width: Double(width) * 0.3, height: Double(height) * 0.5))61 }62 guard let image = context.makeImage(), let destination = CGImageDestinationCreateWithURL(url as CFURL, type.identifier as CFString, 1, nil) else { return false }63 CGImageDestinationAddImage(destination, image, nil)64 return CGImageDestinationFinalize(destination)65 }6667 /// The demonstration set used by screenshots: a mixed batch with honest edge cases.68 static func makeDemoSet(in folder: URL, extraCount: Int = 0) -> [URL] {69 let fm = FileManager.default70 try? fm.createDirectory(at: folder, withIntermediateDirectories: true)71 var made: [URL] = []72 func add(_ name: String, _ make: (URL) -> Bool) {73 let url = folder.appendingPathComponent(name)74 if make(url) { made.append(url) }75 }76 add("Annual report 2026.pdf") { makePDF(at: $0, pages: 12, title: "Annual report 2026") }77 add("Invoice 0042.pdf") { makePDF(at: $0, pages: 1, title: "Invoice 0042") }78 add("Research notes — a deliberately long file name to check truncation in every list of the app.pdf") { makePDF(at: $0, pages: 3, title: "Research notes") }79 add("Contract (signed).pdf") { makePDF(at: $0, pages: 5, title: "Contract") }80 add("Cover.png") { makeImage(at: $0, width: 1600, height: 1000, type: .png, alpha: true, seed: 0) }81 add("Logo.png") { makeImage(at: $0, width: 512, height: 512, type: .png, alpha: true, seed: 2) }82 add("Beach.jpg") { makeImage(at: $0, width: 2400, height: 1600, type: .jpeg, seed: 1) }83 add("Mountains.jpg") { makeImage(at: $0, width: 2400, height: 1600, type: .jpeg, seed: 4) }84 add("Scan.tiff") { makeImage(at: $0, width: 1240, height: 1754, type: .tiff, seed: 5) }85 // A PNG whose name claims JPEG: detection by content must say so.86 add("Wrongly named.jpg") { makeImage(at: $0, width: 800, height: 600, type: .png, seed: 3) }87 add("Notes.txt") { (try? Data("Meeting notes\n\n- convert the report\n- send the invoice\n".utf8).write(to: $0)) != nil }88 // Bytes that are no known format.89 add("Unknown.bin") { url in90 var bytes = [UInt8](repeating: 0, count: 4096)91 for index in bytes.indices { bytes[index] = UInt8((index &* 131 &+ 17) & 0xFF) | 0x80 }92 return (try? Data(bytes).write(to: url)) != nil93 }94 if extraCount > 0 {95 let bulk = folder.appendingPathComponent("Bulk", isDirectory: true)96 try? fm.createDirectory(at: bulk, withIntermediateDirectories: true)97 for index in 1...extraCount {98 let name = String(format: "%04d", index)99 let url: URL100 let ok: Bool101 switch index % 4 {102 case 0: url = bulk.appendingPathComponent("Document \(name).pdf"); ok = makePDF(at: url, pages: 1 + index % 3, title: "Document \(name)")103 case 1: url = bulk.appendingPathComponent("Photo \(name).jpg"); ok = makeImage(at: url, width: 640, height: 480, type: .jpeg, seed: index)104 case 2: url = bulk.appendingPathComponent("Graphic \(name).png"); ok = makeImage(at: url, width: 320, height: 320, type: .png, alpha: true, seed: index)105 default: url = bulk.appendingPathComponent("Scan \(name).tiff"); ok = makeImage(at: url, width: 400, height: 560, type: .tiff, seed: index)106 }107 if ok { made.append(url) }108 }109 }110 return made111 }112 // MARK: Studio samples113114 /// A logo-like image: a few flat colours, hard edges, letters, on a transparent or white background.115 @discardableResult116 static func makeLogo(at url: URL, side: Int = 1024, transparent: Bool = true) -> Bool {117 guard let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(),118 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return false }119 let s = CGFloat(side)120 if !transparent { context.setFillColor(CGColor(gray: 1, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: s, height: s)) }121 func rgb(_ hex: UInt32) -> CGColor { CGColor(srgbRed: CGFloat((hex >> 16) & 0xFF) / 255, green: CGFloat((hex >> 8) & 0xFF) / 255, blue: CGFloat(hex & 0xFF) / 255, alpha: 1) }122 // Rounded tile.123 context.addPath(CGPath(roundedRect: CGRect(x: s * 0.08, y: s * 0.30, width: s * 0.84, height: s * 0.62), cornerWidth: s * 0.12, cornerHeight: s * 0.12, transform: nil))124 context.setFillColor(rgb(0x241B5E)); context.fillPath()125 // Sun and its ring.126 context.setFillColor(rgb(0xFDBA4D)); context.fillEllipse(in: CGRect(x: s * 0.17, y: s * 0.50, width: s * 0.30, height: s * 0.30))127 context.setStrokeColor(rgb(0xFB7A5C)); context.setLineWidth(s * 0.028)128 context.strokeEllipse(in: CGRect(x: s * 0.125, y: s * 0.455, width: s * 0.39, height: s * 0.39))129 // Arrow: the "conversion" stroke.130 context.setFillColor(rgb(0x22D3EE))131 context.move(to: CGPoint(x: s * 0.52, y: s * 0.60)); context.addLine(to: CGPoint(x: s * 0.72, y: s * 0.60)); context.addLine(to: CGPoint(x: s * 0.72, y: s * 0.52))132 context.addLine(to: CGPoint(x: s * 0.86, y: s * 0.65)); context.addLine(to: CGPoint(x: s * 0.72, y: s * 0.78)); context.addLine(to: CGPoint(x: s * 0.72, y: s * 0.70))133 context.addLine(to: CGPoint(x: s * 0.52, y: s * 0.70)); context.closePath(); context.fillPath()134 // Mountains.135 context.setFillColor(rgb(0xE8509E))136 context.move(to: CGPoint(x: s * 0.14, y: s * 0.36)); context.addLine(to: CGPoint(x: s * 0.36, y: s * 0.58)); context.addLine(to: CGPoint(x: s * 0.50, y: s * 0.44))137 context.addLine(to: CGPoint(x: s * 0.62, y: s * 0.52)); context.addLine(to: CGPoint(x: s * 0.86, y: s * 0.36)); context.closePath(); context.fillPath()138 // Wordmark.139 draw("ORIX", size: s * 0.19, bold: true, at: CGPoint(x: s * 0.085, y: s * 0.085), in: context, color: rgb(0x5B4BE8))140 draw("studio", size: s * 0.085, bold: false, at: CGPoint(x: s * 0.60, y: s * 0.10), in: context, color: rgb(0x241B5E))141 guard let image = context.makeImage(), let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil) else { return false }142 CGImageDestinationAddImage(destination, image, nil)143 return CGImageDestinationFinalize(destination)144 }145146 /// A photo-like image: smooth gradients, soft overlapping lights and per-pixel noise (many colours, no flat area).147 @discardableResult148 static func makePhoto(at url: URL, width: Int = 2400, height: Int = 1600, type: UTType = .jpeg, quality: Double = 0.92) -> Bool {149 guard let space = CGColorSpace(name: CGColorSpace.sRGB) else { return false }150 var pixels = [UInt8](repeating: 255, count: width * height * 4)151 var state: UInt64 = 0x9E3779B97F4A7C15152 func next() -> Double { state = state &* 6364136223846793005 &+ 1442695040888963407; return Double((state >> 33) & 0xFFFFFF) / Double(0xFFFFFF) }153 let made: Bool = pixels.withUnsafeMutableBytes { raw in154 guard let context = CGContext(data: raw.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: space,155 bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return false }156 let w = CGFloat(width), h = CGFloat(height)157 // Sky to ground.158 let sky = [CGColor(srgbRed: 0.10, green: 0.16, blue: 0.38, alpha: 1), CGColor(srgbRed: 0.93, green: 0.52, blue: 0.36, alpha: 1), CGColor(srgbRed: 0.99, green: 0.84, blue: 0.55, alpha: 1)] as CFArray159 if let gradient = CGGradient(colorsSpace: space, colors: sky, locations: [0, 0.62, 1]) {160 context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: h), end: CGPoint(x: w * 0.2, y: h * 0.38), options: [.drawsAfterEndLocation])161 }162 // Soft lights.163 for _ in 0..<70 {164 let centre = CGPoint(x: CGFloat(next()) * w, y: CGFloat(next()) * h), radius = CGFloat(40 + next() * 420)165 let colour = CGColor(srgbRed: CGFloat(next()), green: CGFloat(0.3 + next() * 0.6), blue: CGFloat(0.3 + next() * 0.7), alpha: CGFloat(0.10 + next() * 0.22))166 let clear = colour.copy(alpha: 0) ?? colour167 if let glow = CGGradient(colorsSpace: space, colors: [colour, clear] as CFArray, locations: [0, 1]) {168 context.drawRadialGradient(glow, startCenter: centre, startRadius: 0, endCenter: centre, endRadius: radius, options: [])169 }170 }171 // Hills.172 for layer in 0..<4 {173 let base = h * (0.34 - CGFloat(layer) * 0.07), shade = 0.26 - CGFloat(layer) * 0.05174 context.move(to: CGPoint(x: 0, y: 0)); context.addLine(to: CGPoint(x: 0, y: base))175 var x: CGFloat = 0176 while x < w {177 let step = w / 9178 context.addQuadCurve(to: CGPoint(x: x + step, y: base + CGFloat(next() - 0.5) * h * 0.12), control: CGPoint(x: x + step / 2, y: base + CGFloat(next()) * h * 0.14))179 x += step180 }181 context.addLine(to: CGPoint(x: w, y: 0)); context.closePath()182 context.setFillColor(CGColor(srgbRed: shade * 0.7, green: shade, blue: shade * 1.5, alpha: 0.92)); context.fillPath()183 }184 return true185 }186 guard made else { return false }187 // Sensor-like noise.188 for index in stride(from: 0, to: pixels.count, by: 4) {189 let noise = Int((next() - 0.5) * 22)190 pixels[index] = UInt8(min(255, max(0, Int(pixels[index]) + noise)))191 pixels[index + 1] = UInt8(min(255, max(0, Int(pixels[index + 1]) + noise + Int((next() - 0.5) * 6))))192 pixels[index + 2] = UInt8(min(255, max(0, Int(pixels[index + 2]) + noise + Int((next() - 0.5) * 6))))193 }194 guard let provider = CGDataProvider(data: Data(pixels) as CFData),195 let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: space,196 bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue), provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent),197 let destination = CGImageDestinationCreateWithURL(url as CFURL, type.identifier as CFString, 1, nil) else { return false }198 CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)199 return CGImageDestinationFinalize(destination)200 }201202 /// A short video (moving test pattern with a tone) and an audio file (a chord with a slow swell), produced by203 /// the bundled ffmpeg from its own generators. Returns the files that were really written.204 static func makeMedia(in folder: URL, videoName: String = "Clip.mov", audioName: String = "Chord.wav", seconds: Int = 6) async -> [URL] {205 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)206 guard let ffmpeg = try? BundledTools.require("ffmpeg") else { return [] }207 var made: [URL] = []208 let video = folder.appendingPathComponent(videoName)209 // The bundled ffmpeg has no "lavfi" input device: its source filters are used through -filter_complex.210 let videoArgs = ["-hide_banner", "-loglevel", "error", "-y", "-filter_complex",211 "testsrc2=size=1280x720:rate=30:duration=\(seconds)[v];sine=frequency=440:sample_rate=48000:duration=\(seconds)[a]",212 "-map", "[v]", "-map", "[a]", "-c:v", "mpeg4", "-q:v", "3", "-pix_fmt", "yuv420p", "-c:a", "pcm_s16le", video.path]213 if let result = try? await ProcessRunner.run(ffmpeg, arguments: videoArgs, timeout: 120), result.status == 0, FileManager.default.fileExists(atPath: video.path) { made.append(video) }214 let audio = folder.appendingPathComponent(audioName)215 let expression = "aevalsrc=exprs='0.30*sin(2*PI*220*t)*(0.55+0.45*sin(2*PI*0.4*t))+0.22*sin(2*PI*277.18*t)*(0.5+0.5*sin(2*PI*0.25*t+1))+0.18*sin(2*PI*329.63*t)*exp(-mod(t\\,1.5)*2.2)'"216 let audioArgs = ["-hide_banner", "-loglevel", "error", "-y", "-filter_complex", expression + ":sample_rate=44100:duration=\(seconds + 6)[a]",217 "-map", "[a]", "-ac", "2", "-c:a", "pcm_s16le", audio.path]218 if let result = try? await ProcessRunner.run(ffmpeg, arguments: audioArgs, timeout: 120), result.status == 0, FileManager.default.fileExists(atPath: audio.path) { made.append(audio) }219 return made220 }221222 /// The files the studios' screenshots and self-test open.223 static func makeStudioSet(in folder: URL) async -> [URL] {224 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)225 var made: [URL] = []226 let logo = folder.appendingPathComponent("Logo mark.png"), photo = folder.appendingPathComponent("Dusk photo.jpg"), large = folder.appendingPathComponent("Large photo 50 MP.jpg")227 if makeLogo(at: logo) { made.append(logo) }228 if makePhoto(at: photo) { made.append(photo) }229 if makePhoto(at: large, width: 8660, height: 5774, quality: 0.85) { made.append(large) }230 made += await makeMedia(in: folder)231 return made232 }233234 // MARK: Preview samples235236 /// One generated file per kind of preview: a torus (OBJ), a table (CSV), places (GeoJSON), subtitles (SRT), a ZIP237 /// made by the archive engine from the others, and a copy of a system font (read-only use, never redistributed).238 static func makePreviewSet(in folder: URL, manager: ConversionJobManager) async -> [URL] {239 let fm = FileManager.default240 try? fm.createDirectory(at: folder, withIntermediateDirectories: true)241 var made: [URL] = []242 func write(_ name: String, _ text: String) { let url = folder.appendingPathComponent(name); if (try? Data(text.utf8).write(to: url)) != nil { made.append(url) } }243 // Torus: 48 × 24 quads.244 var obj = "o torus\n"245 let major = 48, minor = 24246 for i in 0..<major {247 for j in 0..<minor {248 let u = Double(i) / Double(major) * 2 * .pi, v = Double(j) / Double(minor) * 2 * .pi249 obj += String(format: "v %.5f %.5f %.5f\n", (2 + 0.7 * cos(v)) * cos(u), 0.7 * sin(v), (2 + 0.7 * cos(v)) * sin(u))250 }251 }252 for i in 0..<major {253 for j in 0..<minor {254 let a = i * minor + j + 1, b = ((i + 1) % major) * minor + j + 1, c = ((i + 1) % major) * minor + (j + 1) % minor + 1, d = i * minor + (j + 1) % minor + 1255 obj += "f \(a) \(d) \(c) \(b)\n"256 }257 }258 write("Torus.obj", obj)259 let cities = [("Montréal", 45.5019, -73.5674, 1_762_949), ("Québec", 46.8139, -71.2080, 549_459), ("Gatineau", 45.4765, -75.7013, 291_041), ("Sherbrooke", 45.4042, -71.8929, 172_950),260 ("Trois-Rivières", 46.3430, -72.5479, 139_163), ("Saguenay", 48.4284, -71.0685, 144_723), ("Rimouski", 48.4390, -68.5350, 48_935), ("Val-d’Or", 48.0975, -77.7828, 32_752)]261 write("Cities.csv", "city,latitude,longitude,population,founded,capital\n" + cities.enumerated().map { index, c in262 "\(c.0),\(c.1),\(c.2),\(c.3),\(1608 + index * 37)-07-03,\(index == 1)" }.joined(separator: "\n") + "\n" + (1...120).map { "Place \($0),\(45.0 + Double($0) * 0.03),\(-74.0 + Double($0) * 0.05),\($0 * 137),,false" }.joined(separator: "\n") + "\n")263 let points = cities.map { #"{"type":"Feature","properties":{"name":"\#($0.0)","population":\#($0.3)},"geometry":{"type":"Point","coordinates":[\#($0.2),\#($0.1)]}}"# }264 let river = cities.sorted { $0.2 < $1.2 }.map { "[\($0.2),\($0.1)]" }.joined(separator: ",")265 let area = #"{"type":"Feature","properties":{"name":"Study area","population":null},"geometry":{"type":"Polygon","coordinates":[[[-76.5,45],[-70.5,45],[-68,47.2],[-70.5,48.9],[-76.5,48.6],[-76.5,45]],[[-73.4,46.4],[-72.2,46.4],[-72.2,47.2],[-73.4,47.2],[-73.4,46.4]]]}}"#266 write("Places.geojson", #"{"type":"FeatureCollection","features":["# + ([area, #"{"type":"Feature","properties":{"name":"Route","population":null},"geometry":{"type":"LineString","coordinates":[\#(river)]}}"#] + points).joined(separator: ",") + "]}")267 write("Dialogue.srt", (1...40).map { n in268 let start = n * 3, end = n * 3 + 2269 return "\(n)\n00:\(String(format: "%02d", start / 60)):\(String(format: "%02d", start % 60)),000 --> 00:\(String(format: "%02d", end / 60)):\(String(format: "%02d", end % 60)),400\n" + (n % 5 == 0 ? "<i>Line \(n), in italics</i>" : "Line \(n) of the dialogue") + "\n"270 }.joined(separator: "\n"))271 let font = folder.appendingPathComponent("Geneva.ttf")272 if (try? fm.copyItem(at: URL(fileURLWithPath: "/System/Library/Fonts/Geneva.ttf"), to: font)) != nil { made.append(font) }273 // A ZIP of everything above, made by the archive engine (also puts a folder in it).274 let extra = folder.appendingPathComponent("Notes", isDirectory: true)275 try? fm.createDirectory(at: extra, withIntermediateDirectories: true)276 try? Data("Read me first.\n".utf8).write(to: extra.appendingPathComponent("Read me.txt"))277 let request = ConversionJobRequest(sources: made + [extra], sourceFormat: .folder, destinationFormat: .zip, operation: "archive.create",278 destination: OutputDestination(directory: folder, nameTemplate: "Everything", conflictPolicy: .replace))279 var unrecorded = request280 unrecorded.recordInHistory = false281 if let job = await manager.queue.waitForJob(await manager.queue.enqueue(unrecorded)), job.state == .finished, let zip = job.outputs.first?.url { made.append(zip) }282 return made283 }284}285