Sources/OrgstarMobile/PresentationScreen.swift
328 lines · 14547 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgPresentation
5import SwiftUI
6import UIKit
7
8/// A slide of `SlideShow` as styled text: the theme with its body at `size` points, the
9/// heading at the size of a first-level heading, images on lines of their own.
10@MainActor
11enum MobileSlideText {
12 static func attributed(_ slide: SlideShow.Slide, deck: SlideDeck, spec: ThemeSpec, size: CGFloat, width: CGFloat, options: EditingOptions) -> NSAttributedString {
13 var scaled = spec
14 scaled.fontSize = max(6, Int(size.rounded()))
15 scaled.headingSizeStep = max(1, Int((size * 0.2).rounded()))
16 scaled.lineSpacing = max(0, Int((CGFloat(spec.lineSpacing) * size / CGFloat(max(6, spec.fontSize))).rounded()))
17 let theme = MobileTheme(scaled)
18 let display = ReadingText.Display(options: options, highlighter: MobileEditor.highlighter)
19 let out = NSMutableAttributedString()
20 let centered = NSMutableParagraphStyle()
21 centered.alignment = .center
22 centered.paragraphSpacing = size * 0.4
23
24 func styled(_ range: Range<Int>, heading: Bool) -> NSAttributedString {
25 let storage = NSTextStorage()
26 for segment in ReadingText.segments(deck.tree, in: range, display: display) {
27 let start = storage.length
28 storage.append(NSAttributedString(string: segment.text, attributes: theme.base))
29 let r = NSRange(location: start, length: storage.length - start)
30 guard r.length > 0 else { continue }
31 if heading { theme.apply(.heading(level: 1), to: storage, range: r) }
32 for role in segment.roles.sorted(by: { depth($0) < depth($1) }) {
33 if case .heading = role { continue }
34 theme.apply(role, to: storage, range: r)
35 }
36 if let superscript = segment.superscript, let font = storage.attribute(.font, at: r.location, effectiveRange: nil) as? UIFont {
37 storage.addAttribute(.baselineOffset, value: (superscript ? 0.3 : -0.3) * font.pointSize, range: r)
38 storage.addAttribute(.font, value: font.withSize(font.pointSize * 0.7), range: r)
39 }
40 }
41 return storage
42 }
43 func newline() {
44 if out.length > 0, !out.string.hasSuffix("\n") { out.append(NSAttributedString(string: "\n", attributes: theme.base)) }
45 }
46
47 if let title = slide.title {
48 out.append(NSAttributedString(string: title + "\n", attributes: [
49 .font: MobileTheme.adding(.traitBold, to: theme.body.withSize(size * 2)),
50 .foregroundColor: theme.color("heading-1") ?? theme.foreground, .paragraphStyle: centered,
51 ]))
52 }
53 if !slide.byline.isEmpty {
54 out.append(NSAttributedString(string: slide.byline.joined(separator: "\n") + "\n\n",
55 attributes: [.font: theme.body, .foregroundColor: theme.color("metadata") ?? theme.foreground, .paragraphStyle: centered]))
56 }
57 if let heading = slide.heading {
58 out.append(styled(heading, heading: true))
59 out.append(NSAttributedString(string: "\n\n", attributes: theme.base))
60 }
61 for piece in slide.pieces {
62 newline()
63 switch piece {
64 case .text(let range):
65 out.append(styled(range, heading: false))
66 case .image(let path, let wanted):
67 guard let image = MobileEditor.loadImage(path, relativeTo: deck.directory, remote: .skip) else {
68 out.append(NSAttributedString(string: path, attributes: theme.base))
69 continue
70 }
71 let attachment = NSTextAttachment()
72 attachment.image = image
73 attachment.bounds = CGRect(origin: .zero, size: Presentation.imageSize(natural: image.size, width: wanted, maxWidth: width))
74 out.append(NSAttributedString(attachment: attachment))
75 }
76 }
77 return out
78 }
79
80 static func background(_ spec: ThemeSpec) -> Color {
81 Color(uiColor: MobileTheme(spec).color("background") ?? .systemBackground)
82 }
83
84 /// How deep a role's text usually nests, so inner roles are applied last.
85 static func depth(_ role: StyleRole) -> Int {
86 switch role {
87 case .heading: 0
88 case .metadata, .keyword, .comment, .block, .table, .rule: 1
89 case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2
90 default: 3
91 }
92 }
93}
94
95/// One slide filling the view, as the external display and the device show it.
96struct SlideView: View {
97 let deck: SlideDeck
98 let slide: SlideShow.Slide
99 let theme: ThemeSpec
100 let options: EditingOptions
101 /// Taps and swipes on the slide.
102 var onNext: (() -> Void)?
103 var onPrevious: (() -> Void)?
104
105 var body: some View {
106 GeometryReader { geometry in
107 let size = SlideDeck.bodySize(for: geometry.size, themeSize: theme.fontSize)
108 let margin = max(16, geometry.size.width * 0.06)
109 SlideTextView(text: MobileSlideText.attributed(slide, deck: deck, spec: theme, size: size, width: geometry.size.width - 2 * margin, options: options),
110 inset: UIEdgeInsets(top: slide.title != nil ? geometry.size.height * 0.25 : geometry.size.height * 0.06, left: margin, bottom: margin, right: margin),
111 onNext: onNext, onPrevious: onPrevious)
112 }
113 .background(MobileSlideText.background(theme).ignoresSafeArea())
114 }
115}
116
117/// The slide's text, not editable, scrolling when it runs past the bottom. A tap on the right
118/// two thirds or a swipe to the left goes on; a tap on the left third or a swipe to the right
119/// goes back.
120private struct SlideTextView: UIViewRepresentable {
121 let text: NSAttributedString
122 let inset: UIEdgeInsets
123 var onNext: (() -> Void)?
124 var onPrevious: (() -> Void)?
125
126 func makeUIView(context: Context) -> UITextView {
127 let view = UITextView()
128 view.isEditable = false
129 view.isSelectable = false
130 view.backgroundColor = .clear
131 view.textContainer.lineFragmentPadding = 0
132 let coordinator = context.coordinator
133 view.addGestureRecognizer(UITapGestureRecognizer(target: coordinator, action: #selector(Coordinator.tapped(_:))))
134 for direction in [UISwipeGestureRecognizer.Direction.left, .right] {
135 let swipe = UISwipeGestureRecognizer(target: coordinator, action: #selector(Coordinator.swiped(_:)))
136 swipe.direction = direction
137 view.addGestureRecognizer(swipe)
138 }
139 return view
140 }
141
142 func updateUIView(_ view: UITextView, context: Context) {
143 context.coordinator.parent = self
144 view.textContainerInset = inset
145 view.attributedText = text
146 view.setContentOffset(.zero, animated: false)
147 }
148
149 func makeCoordinator() -> Coordinator { Coordinator(parent: self) }
150
151 @MainActor
152 final class Coordinator: NSObject {
153 var parent: SlideTextView
154 init(parent: SlideTextView) { self.parent = parent }
155
156 @objc func tapped(_ tap: UITapGestureRecognizer) {
157 guard let view = tap.view as? UIScrollView else { return }
158 if tap.location(in: view).x - view.contentOffset.x < view.bounds.width / 3 { parent.onPrevious?() } else { parent.onNext?() }
159 }
160
161 @objc func swiped(_ swipe: UISwipeGestureRecognizer) {
162 if swipe.direction == .left { parent.onNext?() } else { parent.onPrevious?() }
163 }
164 }
165}
166
167/// Present: the open file one heading at a time, full screen. With an external display (an
168/// iPad's, with Stage Manager off), the slide shows there and this screen shows the next slide,
169/// the notes and the buttons.
170struct PresentationScreen: View {
171 let deck: SlideDeck
172 let theme: ThemeSpec
173 let options: EditingOptions
174 @Environment(\.dismiss) private var dismiss
175 private var external: ExternalDisplay { .shared }
176
177 var body: some View {
178 Group {
179 if external.connected {
180 presenter
181 } else {
182 SlideView(deck: deck, slide: deck.slide, theme: theme, options: options, onNext: deck.next, onPrevious: deck.previous)
183 .overlay(alignment: .bottomTrailing) { controls.padding() }
184 }
185 }
186 .background { keys }
187 .statusBarHidden()
188 .persistentSystemOverlays(.hidden)
189 .onAppear { external.show(deck, theme: theme, options: options) }
190 .onDisappear { external.show(nil, theme: theme, options: options) }
191 }
192
193 private var controls: some View {
194 HStack(spacing: 12) {
195 Text(deck.position).monospacedDigit().foregroundStyle(.secondary)
196 Button("Done") { dismiss() }
197 .buttonStyle(.bordered)
198 }
199 .font(.callout)
200 }
201
202 /// The presenter's screen: the next slide, the notes, the slide number and the buttons.
203 private var presenter: some View {
204 NavigationStack {
205 VStack(alignment: .leading, spacing: 16) {
206 Text("Next").font(.headline)
207 if let upcoming = deck.upcoming {
208 SlideView(deck: deck, slide: upcoming, theme: theme, options: options)
209 .aspectRatio(16 / 9, contentMode: .fit)
210 .clipShape(RoundedRectangle(cornerRadius: 8))
211 .overlay(RoundedRectangle(cornerRadius: 8).stroke(.separator))
212 } else {
213 Text("End of the slides").foregroundStyle(.secondary)
214 }
215 if !deck.slide.notes.isEmpty {
216 Text("Notes").font(.headline)
217 ScrollView { Text(deck.slide.notes).frame(maxWidth: .infinity, alignment: .leading) }
218 }
219 Spacer(minLength: 0)
220 HStack {
221 Button("Previous", systemImage: "chevron.left", action: deck.previous)
222 .disabled(deck.index == 0)
223 Spacer()
224 Text(deck.position).monospacedDigit().font(.title3)
225 Spacer()
226 Button("Next", systemImage: "chevron.right", action: deck.next)
227 .disabled(deck.upcoming == nil)
228 }
229 .buttonStyle(.borderedProminent)
230 .controlSize(.large)
231 }
232 .padding()
233 .navigationTitle("Present")
234 .navigationBarTitleDisplayMode(.inline)
235 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
236 }
237 }
238
239 /// A hardware keyboard's keys: →, ↓, Space, Page Down and Return go on; ←, ↑, Delete and
240 /// Page Up go back; Home and End go to the first and last slide; Escape leaves.
241 private var keys: some View {
242 ZStack {
243 ForEach([KeyEquivalent.rightArrow, .downArrow, .space, .pageDown, .return], id: \.character) { key in
244 Button { deck.next() } label: { EmptyView() }.keyboardShortcut(key, modifiers: [])
245 }
246 ForEach([KeyEquivalent.leftArrow, .upArrow, .pageUp, .delete], id: \.character) { key in
247 Button { deck.previous() } label: { EmptyView() }.keyboardShortcut(key, modifiers: [])
248 }
249 Button { deck.first() } label: { EmptyView() }.keyboardShortcut(.home, modifiers: [])
250 Button { deck.last() } label: { EmptyView() }.keyboardShortcut(.end, modifiers: [])
251 Button { dismiss() } label: { EmptyView() }.keyboardShortcut(.escape, modifiers: [])
252 }
253 .opacity(0)
254 .accessibilityHidden(true)
255 }
256}
257
258/// The external display while presenting: the slide on a non-interactive external display
259/// scene. Without a presentation the scene has no window, and the display mirrors the device.
260@MainActor @Observable
261final class ExternalDisplay {
262 static let shared = ExternalDisplay()
263 private(set) var deck: SlideDeck?
264 private(set) var theme = ThemeSpec.default
265 private(set) var options = EditingOptions.org
266 /// Scenes on external displays now.
267 var scenes = 0
268 var connected: Bool { scenes > 0 }
269 /// Called when a presentation starts or ends, for each scene's window.
270 @ObservationIgnored var changed: [ObjectIdentifier: () -> Void] = [:]
271
272 func show(_ deck: SlideDeck?, theme: ThemeSpec, options: EditingOptions) {
273 self.deck = deck
274 self.theme = theme
275 self.options = options
276 for update in changed.values { update() }
277 }
278}
279
280/// The scene iOS connects for an external display (`UIWindowSceneSessionRoleExternalDisplayNonInteractive`
281/// in Info.plist): a window with the slide while a presentation is showing.
282@objc(ExternalDisplaySceneDelegate)
283final class ExternalDisplaySceneDelegate: UIResponder, UIWindowSceneDelegate {
284 var window: UIWindow?
285
286 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
287 guard let scene = scene as? UIWindowScene else { return }
288 let display = ExternalDisplay.shared
289 display.scenes += 1
290 display.changed[ObjectIdentifier(self)] = { [weak self, weak scene] in
291 guard let self, let scene else { return }
292 self.update(scene)
293 }
294 update(scene)
295 }
296
297 func sceneDidDisconnect(_ scene: UIScene) {
298 let display = ExternalDisplay.shared
299 display.scenes = max(0, display.scenes - 1)
300 display.changed[ObjectIdentifier(self)] = nil
301 window = nil
302 }
303
304 private func update(_ scene: UIWindowScene) {
305 guard ExternalDisplay.shared.deck != nil else {
306 window?.isHidden = true
307 window = nil
308 return
309 }
310 guard window == nil else { return }
311 let window = UIWindow(windowScene: scene)
312 window.rootViewController = UIHostingController(rootView: ExternalSlide())
313 window.isHidden = false
314 self.window = window
315 }
316}
317
318private struct ExternalSlide: View {
319 private var display: ExternalDisplay { .shared }
320
321 var body: some View {
322 if let deck = display.deck {
323 SlideView(deck: deck, slide: deck.slide, theme: display.theme, options: display.options)
324 .ignoresSafeArea()
325 }
326 }
327}
328#endif