Cotton code
101 lines · 5.0 KB · SwiftRaw
// Sending the script out of Story: the core's laid-out pages drawn as a PDF// at the paper's real size (Courier Prime 12 pt, black on white, as a printed// screenplay is), and the core's Fountain text as a file. The share sheet is// the system's own.#if os(iOS)import CottonPaperimport CottonValuesimport UIKit/// Where Story's outgoing files are written, and their names made safe.enum StoryFiles {    static func folder() -> URL {        let url = FileManager.default.temporaryDirectory.appendingPathComponent("story-out", isDirectory: true)        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)        return url    }    /// A file name with nothing a file system refuses.    static func safe(_ name: String) -> String {        let refused = CharacterSet(charactersIn: "/\\:?%*|\"<>")        let cleaned = name.components(separatedBy: refused).joined(separator: " ").trimmingCharacters(in: .whitespaces)        return cleaned.isEmpty ? "script" : cleaned    }}/// The script as a PDF, Courier Prime at 12 points, with the system's fonts/// for any script Courier Prime does not carry.@MainActorenum StoryPDF {    /// 12 points on the page, 6 lines an inch.    static let pointSize: CGFloat = 12    static let lineHeight: CGFloat = 12    /// The last scalar of Latin Extended-B: past it a line is in a script Courier Prime lacks.    static let latinEnd: UInt32 = 0x24F    /// Such a line's size, of the script's own 12 points.    static let otherScript: CGFloat = 0.82    static func write(_ script: StoryScript, named title: String) -> URL? {        let paper = script.paper        let bounds = CGRect(x: 0, y: 0, width: paper.width, height: paper.height)        let renderer = UIGraphicsPDFRenderer(bounds: bounds)        _ = CottonFonts.type(pointSize)        let plain = UIFont(name: CottonFonts.typeFace, size: pointSize) ?? .monospacedSystemFont(ofSize: pointSize, weight: .regular)        let ink = UIColor.black        let url = StoryFiles.folder().appendingPathComponent(StoryFiles.safe(title) + ".pdf")        do {            try renderer.writePDF(to: url) { context in                if let page = script.titlePage {                    context.beginPage()                    drawTitle(page, paper: paper, font: plain, ink: ink)                }                for page in script.pages {                    context.beginPage()                    let number = NSAttributedString(string: ShellLines.line("story", "script.page", ["n": String(page.number)]),                                                    attributes: [.font: plain, .foregroundColor: ink])                    number.draw(at: CGPoint(x: paper.width - paper.margins.right - number.size().width, y: paper.margins.top / 2))                    for (index, line) in page.lines.enumerated() {                        var face = line.kind == "heading" ? bold(plain) : plain                        if line.text.unicodeScalars.contains(where: { $0.value > latinEnd }) {                            face = face.withSize(pointSize * otherScript)                        }                        let words = NSAttributedString(string: line.text, attributes: [.font: face, .foregroundColor: ink])                        words.draw(at: CGPoint(x: paper.margins.left + Double(line.indent) * 7.2,                                               y: paper.margins.top + Double(index) * lineHeight))                    }                }            }            return url        } catch {            return nil        }    }    private static func bold(_ font: UIFont) -> UIFont {        guard let descriptor = font.fontDescriptor.withSymbolicTraits(.traitBold) else { return font }        return UIFont(descriptor: descriptor, size: font.pointSize)    }    private static func drawTitle(_ page: StoryScript.TitlePage, paper: StoryScript.Paper, font: UIFont, ink: UIColor) {        let centred = NSMutableParagraphStyle()        centred.alignment = .center        let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: ink, .paragraphStyle: centred]        var y = paper.height * 0.38        let width = paper.width - paper.margins.left - paper.margins.right        for words in [page.title, page.credit, page.author].compactMap({ $0 }) {            let drawn = NSAttributedString(string: words, attributes: attributes)            let height = drawn.boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).height            drawn.draw(in: CGRect(x: paper.margins.left, y: y, width: width, height: height + 2))            y += height + lineHeight * 2        }        if let lines = page.lines {            var bottom = paper.height - paper.margins.bottom - Double(lines.count) * lineHeight            for line in lines {                NSAttributedString(string: line, attributes: [.font: font, .foregroundColor: ink]).draw(at: CGPoint(x: paper.margins.left, y: bottom))                bottom += lineHeight            }        }    }}#endif