Sources/OrgEditorAppKit/SlideText.swift
102 lines · 5215 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgPresentation
5
6/// A slide of `SlideShow` as styled text: the editor's theme with its body at `size` points,
7/// the heading at the size of a first-level heading, images on lines of their own.
8public enum SlideText {
9 @MainActor
10 public static func attributed(
11 _ slide: SlideShow.Slide, tree: OrgTree, spec: ThemeSpec, size: CGFloat, width: CGFloat, directory: URL?,
12 options: EditingOptions = .org, highlighter: (any CodeHighlighter)? = nil
13 ) -> NSAttributedString {
14 var scaled = spec
15 scaled.fontSize = max(6, Int(size.rounded()))
16 scaled.headingSizeStep = max(1, Int((size * 0.2).rounded()))
17 scaled.lineSpacing = max(0, Int((CGFloat(spec.lineSpacing) * size / CGFloat(max(6, spec.fontSize))).rounded()))
18 let theme = Theme(scaled)
19 let display = ReadingText.Display(options: options, highlighter: highlighter)
20 let out = NSTextStorage()
21 let centered = NSMutableParagraphStyle()
22 centered.alignment = .center
23 centered.paragraphSpacing = size * 0.4
24
25 func styled(_ range: Range<Int>, heading: Bool) -> NSAttributedString {
26 let storage = NSTextStorage()
27 for segment in ReadingText.segments(tree, in: range, display: display) {
28 let start = storage.length
29 storage.append(NSAttributedString(string: segment.text, attributes: theme.base))
30 let r = NSRange(location: start, length: storage.length - start)
31 guard r.length > 0 else { continue }
32 if heading { theme.apply(.heading(level: 1), to: storage, range: r) }
33 for role in segment.roles.sorted(by: { depth($0) < depth($1) }) {
34 if case .heading = role { continue }
35 theme.apply(role, to: storage, range: r)
36 }
37 if let superscript = segment.superscript, let font = storage.attribute(.font, at: r.location, effectiveRange: nil) as? NSFont {
38 storage.addAttribute(.baselineOffset, value: (superscript ? 0.3 : -0.3) * font.pointSize, range: r)
39 storage.addAttribute(.font, value: font.withSize(font.pointSize * 0.7), range: r)
40 }
41 }
42 return storage
43 }
44 func newline() {
45 if out.length > 0, !out.string.hasSuffix("\n") { out.append(NSAttributedString(string: "\n", attributes: theme.base)) }
46 }
47
48 if let title = slide.title {
49 let heading = NSMutableAttributedString(string: title + "\n", attributes: theme.base)
50 let font = NSFontManager.shared.convert(theme.body.withSize(size * 2), toHaveTrait: .boldFontMask)
51 heading.addAttributes([.font: font, .foregroundColor: theme.color("heading-1") ?? theme.foreground, .paragraphStyle: centered], range: NSRange(location: 0, length: heading.length))
52 out.append(heading)
53 }
54 if !slide.byline.isEmpty {
55 out.append(NSAttributedString(string: slide.byline.joined(separator: "\n") + "\n\n",
56 attributes: [.font: theme.body, .foregroundColor: theme.color("metadata") ?? theme.foreground, .paragraphStyle: centered]))
57 }
58 if let heading = slide.heading {
59 out.append(styled(heading, heading: true))
60 out.append(NSAttributedString(string: "\n\n", attributes: theme.base))
61 }
62 for piece in slide.pieces {
63 switch piece {
64 case .text(let range):
65 newline()
66 out.append(styled(range, heading: false))
67 case .image(let path, let wanted):
68 newline()
69 let url = path.hasPrefix("/") || path.hasPrefix("~") ? URL(fileURLWithPath: OrgPaths.expandingTilde(path))
70 : directory?.appendingPathComponent(path.hasPrefix("file:") ? String(path.dropFirst(5)) : path)
71 guard let url, let image = NSImage(contentsOf: url) else {
72 out.append(NSAttributedString(string: path, attributes: theme.base))
73 continue
74 }
75 let natural = image.size
76 let shown = Presentation.imageSize(natural: natural, width: wanted, maxWidth: width)
77 let attachment = NSTextAttachment()
78 attachment.image = image
79 attachment.bounds = CGRect(origin: .zero, size: shown)
80 out.append(NSAttributedString(attachment: attachment))
81 }
82 }
83 return out
84 }
85
86 /// The editor's background in `spec`.
87 @MainActor
88 public static func background(_ spec: ThemeSpec) -> NSColor {
89 Theme(spec).color("background") ?? .textBackgroundColor
90 }
91
92 /// How deep a role's text usually nests, so inner roles are applied last.
93 static func depth(_ role: StyleRole) -> Int {
94 switch role {
95 case .heading: 0
96 case .metadata, .keyword, .comment, .block, .table, .rule: 1
97 case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2
98 default: 3
99 }
100 }
101}
102#endif