@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
swift 952 lines 39.1 KB
Raw
1 import ImageIO
2 import Photos
3 import UIKit
4
5 /// Full-screen image gallery modelled on Messages. It opens at once from the tapped thumbnail's
6 /// own pixels and sharpens when the original arrives, so a slow or failed load never holds it back.
7 final class T3NativeImageViewer: NSObject {
8 let identifier: String
9 private let completion: (Error?) -> Void
10 private let onFinish: () -> Void
11 private weak var sources: T3PresentationSources?
12 private let sourceIdentifiers: [String]
13 private var titles: [String] = []
14 private var urls: [URL?] = []
15 /// The original bytes on disk, kept for sharing.
16 private var files: [URL?] = []
17 private var placeholders: [UIImage?] = []
18 private var loads: [Int: Task<Void, Never>] = [:]
19 private var decodes: [Int: Task<Void, Never>] = [:]
20 /// The last queued decode; each one waits for it, so one original decodes at a time.
21 private var decodeQueue: Task<Void, Never>?
22 /// Pages showing their decoded original; only the current page and its neighbours keep one.
23 private var decoded: Set<Int> = []
24 private var currentIndex = 0
25 private var controller: T3ImageViewerController?
26 private var finished = false
27
28 init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
29 onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
30 self.identifier = identifier
31 self.sources = sources
32 self.sourceIdentifiers = sourceIdentifiers
33 self.onFinish = onFinish
34 self.completion = completion
35 super.init()
36 }
37
38 func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
39 self.urls = urls
40 self.titles = titles
41 files = Array(repeating: nil, count: urls.count)
42 currentIndex = selectedIndex
43 let viewer = T3ImageViewerController(titles: titles, selectedIndex: selectedIndex)
44 viewer.sourceView = { [weak self] index in self?.sourceView(index) }
45 viewer.fileForPage = { [weak self] index in self?.file(at: index) }
46 viewer.onRetry = { [weak self] index in self?.load(index, retry: true) }
47 viewer.onDismissed = { [weak self] in self?.finish() }
48 viewer.onPageChange = { [weak self] index in self?.show(page: index) }
49 controller = viewer
50 viewer.loadViewIfNeeded()
51 placeholders = urls.indices.map { sourceView($0).flatMap(Self.thumbnail(of:)) }
52 for (index, placeholder) in placeholders.enumerated() {
53 if let placeholder { viewer.setImage(placeholder, at: index, full: false) }
54 }
55 presenter.present(T3ImageViewerNavigation(viewer: viewer), animated: false) { viewer.animateIn() }
56 for index in urls.indices { load(index, retry: false) }
57 }
58
59 /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
60 func update(index: Int, url: URL?) {
61 guard !finished, urls.indices.contains(index), urls[index] == nil else { return }
62 guard let url else {
63 controller?.setFailed(at: index, retryable: false)
64 return
65 }
66 urls[index] = url
67 load(index, retry: false)
68 }
69
70 func dismiss() {
71 guard !finished else { return }
72 guard let controller else { finish(); return }
73 controller.close()
74 }
75
76 /// Ends at once, for a new viewer that must open while this one is still animating away.
77 func finishImmediately() {
78 guard !finished else { return }
79 controller?.presentingViewController?.dismiss(animated: false)
80 finish()
81 }
82
83 private func file(at index: Int) -> URL? {
84 files.indices.contains(index) ? files[index] : nil
85 }
86
87 private func sourceView(_ index: Int) -> UIView? {
88 guard sourceIdentifiers.indices.contains(index), !sourceIdentifiers[index].isEmpty else { return nil }
89 return sources?.view(for: sourceIdentifiers[index])
90 }
91
92 private func load(_ index: Int, retry: Bool) {
93 guard !finished, urls.indices.contains(index), let url = urls[index], loads[index] == nil else { return }
94 if retry { controller?.setLoading(at: index) }
95 let title = titles[index]
96 loads[index] = Task { @MainActor [self] in
97 defer { loads[index] = nil }
98 do {
99 let file = try await T3NativeFilePresentation.prepareFile(url: url, title: title)
100 guard !finished, !Task.isCancelled else { Self.remove(file); return }
101 if let previous = files[index] { Self.remove(previous) }
102 files[index] = file
103 decoded.remove(index)
104 if isNearCurrent(index) { decode(index) }
105 } catch {
106 guard !finished, !Task.isCancelled else { return }
107 controller?.setFailed(at: index, retryable: true)
108 }
109 }
110 }
111
112 /// Every original downloads up front, but a decoded one costs far more memory than its file,
113 /// so only pages next to the current one decode, and pages further away fall back to their thumbnail.
114 private func show(page index: Int) {
115 currentIndex = index
116 for other in decoded where !isNearCurrent(other) {
117 decoded.remove(other)
118 controller?.release(at: other, placeholder: placeholders[other])
119 }
120 // Queued decodes for pages paged past are skipped before they start.
121 for (other, task) in decodes where !isNearCurrent(other) { task.cancel() }
122 for near in files.indices where isNearCurrent(near) { decode(near) }
123 }
124
125 private func isNearCurrent(_ index: Int) -> Bool { abs(index - currentIndex) <= 1 }
126
127 private func decode(_ index: Int) {
128 guard !finished, let file = file(at: index), !decoded.contains(index), decodes[index] == nil else { return }
129 let source = sourceView(index)
130 let previous = decodeQueue
131 let task = Task { @MainActor [self] in
132 await previous?.value
133 var settled = false
134 defer {
135 decodes[index] = nil
136 // Paged away and back while this run waited: it was cancelled, so the page asks again.
137 if !settled, !finished, isNearCurrent(index), !decoded.contains(index) { decode(index) }
138 }
139 guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
140 // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size.
141 let isSVG = file.pathExtension.lowercased() == "svg"
142 let image = isSVG ? nil : await Task.detached(priority: .userInitiated) { Self.decode(file) }.value
143 guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
144 if isSVG {
145 // The open transition hides the thumbnail, which draws blank until it is back.
146 await controller?.untilRevealed()
147 guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
148 }
149 settled = true
150 if let image = image ?? (isSVG ? source.flatMap(Self.render(_:)) : nil) {
151 decoded.insert(index)
152 controller?.setImage(image, at: index, full: true)
153 } else {
154 // A corrupt download or an SVG whose thumbnail is scrolled away; retrying downloads it again.
155 // A file that is not an image must not reach Share.
156 if !isSVG {
157 Self.remove(file)
158 files[index] = nil
159 }
160 controller?.setFailed(at: index, retryable: true)
161 }
162 }
163 decodes[index] = task
164 decodeQueue = task
165 }
166
167 private func finish() {
168 guard !finished else { return }
169 finished = true
170 for task in loads.values { task.cancel() }
171 loads.removeAll()
172 for task in decodes.values { task.cancel() }
173 decodes.removeAll()
174 decodeQueue = nil
175 for file in files.compactMap({ $0 }) { Self.remove(file) }
176 files.removeAll()
177 controller = nil
178 DispatchQueue.main.async { [completion] in completion(nil) }
179 // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
180 onFinish()
181 }
182
183 private static func remove(_ file: URL) {
184 try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
185 }
186
187 /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one.
188 /// The largest image view wins, so an overlaid icon is never mistaken for the picture.
189 private static func thumbnail(of view: UIView) -> UIImage? {
190 var queue = [view]
191 var best: (image: UIImage, area: CGFloat)?
192 while let candidate = queue.popLast() {
193 queue.append(contentsOf: candidate.subviews)
194 guard let image = (candidate as? UIImageView)?.image, image.size.width > 0, image.size.height > 0 else { continue }
195 let area = candidate.bounds.width * candidate.bounds.height
196 if area > best?.area ?? 0 { best = (image, area) }
197 }
198 if let best, best.area >= view.bounds.width * view.bounds.height / 2 { return best.image }
199 return snapshot(view, scale: view.window?.screen.scale ?? 2)
200 }
201
202 private static func render(_ view: UIView) -> UIImage? {
203 let screen = view.window?.screen.bounds.size ?? CGSize(width: 1024, height: 1024)
204 let fit = min(screen.width / max(view.bounds.width, 1), screen.height / max(view.bounds.height, 1))
205 // The thumbnail was shown again after the open transition, in a frame not yet on screen.
206 return snapshot(view, scale: max(1, fit) * (view.window?.screen.scale ?? 2), afterScreenUpdates: true)
207 }
208
209 private static func snapshot(_ view: UIView, scale: CGFloat, afterScreenUpdates: Bool = false) -> UIImage? {
210 guard view.bounds.width > 1, view.bounds.height > 1, view.window != nil else { return nil }
211 let format = UIGraphicsImageRendererFormat()
212 format.scale = scale
213 format.opaque = false
214 return UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in
215 view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates)
216 }
217 }
218
219 /// Decodes off the main thread at no more than zooming needs, and keeps GIFs animated.
220 nonisolated private static func decode(_ file: URL) -> UIImage? {
221 guard let source = CGImageSourceCreateWithURL(file as CFURL, nil) else { return nil }
222 let count = CGImageSourceGetCount(source)
223 guard count > 0 else { return nil }
224 let options: [CFString: Any] = [
225 kCGImageSourceCreateThumbnailFromImageAlways: true,
226 kCGImageSourceCreateThumbnailWithTransform: true,
227 kCGImageSourceShouldCacheImmediately: true,
228 kCGImageSourceThumbnailMaxPixelSize: 4096,
229 ]
230 var animationOptions = options
231 animationOptions[kCGImageSourceThumbnailMaxPixelSize] = 1024
232 animationOptions[kCGImageSourceShouldCacheImmediately] = nil
233 // Every frame stays decoded while it plays, so an animation over this budget shows its first frame.
234 if count > 1, let first = CGImageSourceCreateThumbnailAtIndex(source, 0, animationOptions as CFDictionary),
235 first.bytesPerRow * first.height * count <= animationByteBudget {
236 var frames: [(image: UIImage, delay: Double)] = [(UIImage(cgImage: first), frameDuration(source, 0))]
237 for index in 1..<count {
238 guard let frame = CGImageSourceCreateThumbnailAtIndex(source, index, animationOptions as CFDictionary) else { continue }
239 frames.append((UIImage(cgImage: frame), frameDuration(source, index)))
240 }
241 // UIKit plays frames evenly, so each frame repeats once per tick of its delay; the repeats share
242 // one bitmap. The tick grows with the animation's length to keep the timeline near 1,000 entries.
243 let total = frames.reduce(0) { $0 + $1.delay }
244 let tick = max(0.02, total / 1_000)
245 let timeline = frames.flatMap { frame in
246 Array(repeating: frame.image, count: max(1, Int((frame.delay / tick).rounded())))
247 }
248 if frames.count > 1 { return UIImage.animatedImage(with: timeline, duration: Double(timeline.count) * tick) }
249 }
250 return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) }
251 }
252
253 nonisolated private static func frameDuration(_ source: CGImageSource, _ index: Int) -> Double {
254 let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any]
255 let gif = properties?[kCGImagePropertyGIFDictionary] as? [CFString: Any]
256 let png = properties?[kCGImagePropertyPNGDictionary] as? [CFString: Any]
257 let delay = gif?[kCGImagePropertyGIFUnclampedDelayTime] as? Double
258 ?? gif?[kCGImagePropertyGIFDelayTime] as? Double
259 ?? png?[kCGImagePropertyAPNGUnclampedDelayTime] as? Double
260 ?? png?[kCGImagePropertyAPNGDelayTime] as? Double
261 ?? 0.1
262 // Browsers treat near-zero delays as 0.1s.
263 return delay < 0.011 ? 0.1 : delay
264 }
265 }
266
267 private let animationByteBudget = 64 * 1024 * 1024
268
269 private extension Array {
270 subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }
271 }
272
273 /// One zoomable page. Its content never exceeds its bounds at the fitted zoom, so a vertical
274 /// drag has nothing to scroll and always reaches the dismiss gesture.
275 private final class T3ImageViewerPage: UIView, UIScrollViewDelegate {
276 let scroll = UIScrollView()
277 let imageView = UIImageView()
278 private let spinner = UIActivityIndicatorView(style: .large)
279 private let failure = UIStackView()
280 private var spinnerDelay: DispatchWorkItem?
281 private var laidOutSize = CGSize.zero
282 private(set) var isFull = false
283 var onRetry: (() -> Void)?
284
285 override init(frame: CGRect) {
286 super.init(frame: frame)
287 scroll.delegate = self
288 scroll.showsVerticalScrollIndicator = false
289 scroll.showsHorizontalScrollIndicator = false
290 scroll.contentInsetAdjustmentBehavior = .never
291 scroll.decelerationRate = .fast
292 scroll.alwaysBounceVertical = false
293 scroll.alwaysBounceHorizontal = false
294 scroll.bouncesZoom = true
295 addSubview(scroll)
296 imageView.contentMode = .scaleAspectFill
297 imageView.clipsToBounds = true
298 imageView.isAccessibilityElement = true
299 imageView.accessibilityTraits = .image
300 scroll.addSubview(imageView)
301 spinner.color = .white
302 spinner.hidesWhenStopped = true
303 addSubview(spinner)
304 configureFailure()
305 }
306
307 @available(*, unavailable)
308 required init?(coder: NSCoder) { nil }
309
310 private func configureFailure() {
311 let icon = UIImageView(image: UIImage(systemName: "exclamationmark.triangle"))
312 icon.tintColor = UIColor(white: 1, alpha: 0.8)
313 icon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 28, weight: .regular)
314 let label = UILabel()
315 label.text = "This image could not be loaded."
316 label.textColor = UIColor(white: 1, alpha: 0.8)
317 label.font = .preferredFont(forTextStyle: .subheadline)
318 label.adjustsFontForContentSizeCategory = true
319 label.textAlignment = .center
320 label.numberOfLines = 0
321 var configuration = UIButton.Configuration.gray()
322 configuration.title = "Try Again"
323 configuration.cornerStyle = .capsule
324 configuration.baseForegroundColor = .white
325 configuration.baseBackgroundColor = UIColor(white: 1, alpha: 0.18)
326 let retry = UIButton(configuration: configuration, primaryAction: UIAction { [weak self] _ in self?.onRetry?() })
327 failure.axis = .vertical
328 failure.alignment = .center
329 failure.spacing = 12
330 failure.isHidden = true
331 for view in [icon, label, retry] { failure.addArrangedSubview(view) }
332 addSubview(failure)
333 }
334
335 var image: UIImage? { imageView.image }
336
337 func setImage(_ image: UIImage, full: Bool) {
338 guard full || !isFull else { return }
339 let previous = imageView.image?.size
340 imageView.image = image
341 isFull = full
342 stopLoading()
343 failure.isHidden = true
344 let ratio = { (size: CGSize) in size.width / max(size.height, 1) }
345 // A sharper copy of the same picture keeps the reader's zoom; a different shape starts over.
346 if previous == nil || abs(ratio(previous ?? .zero) - ratio(image.size)) > 0.01 { laidOutSize = .zero }
347 setNeedsLayout()
348 }
349
350 /// Gives back a far-away page's decoded original, keeping the thumbnail until it returns.
351 func release(to placeholder: UIImage?) {
352 guard isFull else { return }
353 isFull = false
354 imageView.image = placeholder
355 laidOutSize = .zero
356 setNeedsLayout()
357 setLoading()
358 }
359
360 func setLoading() {
361 failure.isHidden = true
362 imageView.alpha = 1
363 guard imageView.image == nil, spinnerDelay == nil else { return }
364 let work = DispatchWorkItem { [weak self] in self?.spinner.startAnimating() }
365 spinnerDelay = work
366 DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work)
367 }
368
369 func setFailed(retryable: Bool) {
370 stopLoading()
371 guard !isFull else { return }
372 failure.arrangedSubviews.last?.isHidden = !retryable
373 failure.isHidden = false
374 // A thumbnail stays visible behind the message, dimmed.
375 imageView.alpha = imageView.image == nil ? 1 : 0.35
376 }
377
378 private func stopLoading() {
379 spinnerDelay?.cancel()
380 spinnerDelay = nil
381 spinner.stopAnimating()
382 imageView.alpha = 1
383 }
384
385 var isZoomed: Bool { scroll.zoomScale > scroll.minimumZoomScale + 0.01 }
386
387 func resetZoom(animated: Bool) { scroll.setZoomScale(scroll.minimumZoomScale, animated: animated) }
388
389 override func layoutSubviews() {
390 super.layoutSubviews()
391 scroll.frame = bounds
392 spinner.center = CGPoint(x: bounds.midX, y: bounds.midY)
393 let width = min(bounds.width - 48, 320)
394 let height = failure.systemLayoutSizeFitting(CGSize(width: width, height: 0),
395 withHorizontalFittingPriority: .required,
396 verticalFittingPriority: .fittingSizeLevel).height
397 failure.frame = CGRect(x: (bounds.width - width) / 2, y: (bounds.height - height) / 2, width: width, height: height)
398 guard bounds.size != laidOutSize, let size = imageView.image?.size, size.width > 0, size.height > 0 else { return }
399 laidOutSize = bounds.size
400 let fit = min(bounds.width / size.width, bounds.height / size.height)
401 scroll.minimumZoomScale = 1
402 scroll.zoomScale = 1
403 imageView.transform = .identity
404 imageView.frame = CGRect(x: 0, y: 0, width: size.width * fit, height: size.height * fit)
405 scroll.contentSize = imageView.frame.size
406 // Enough to fill the screen and then some, or to see the original's pixels.
407 let fill = max(bounds.width / imageView.frame.width, bounds.height / imageView.frame.height)
408 let pixels = 1 / fit / (window?.screen.scale ?? 2)
409 scroll.maximumZoomScale = max(3, fill * 1.5, pixels)
410 centerImage()
411 }
412
413 /// The fitted frame of the image, for the opening transition.
414 func fittedFrame(in view: UIView) -> CGRect {
415 layoutIfNeeded()
416 return imageView.convert(imageView.bounds, to: view)
417 }
418
419 func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
420
421 func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() }
422
423 private func centerImage() {
424 let content = scroll.contentSize
425 imageView.center = CGPoint(x: max(content.width, scroll.bounds.width) / 2,
426 y: max(content.height, scroll.bounds.height) / 2)
427 }
428
429 func toggleZoom(at point: CGPoint) {
430 if isZoomed { resetZoom(animated: true); return }
431 guard imageView.image != nil else { return }
432 let location = convert(point, to: imageView)
433 let fill = max(scroll.bounds.width / imageView.bounds.width, scroll.bounds.height / imageView.bounds.height)
434 let scale = min(scroll.maximumZoomScale, fill > 1.2 ? fill : 2.5)
435 let width = scroll.bounds.width / scale
436 let height = scroll.bounds.height / scale
437 scroll.zoom(to: CGRect(x: location.x - width / 2, y: location.y - height / 2, width: width, height: height),
438 animated: true)
439 }
440 }
441
442 /// System bars, so UIKit places Close, the title, Save and Share: at the top and bottom of an iPhone,
443 /// and in the side bar of an unfolded iPhone Duo.
444 private final class T3ImageViewerNavigation: UINavigationController {
445 init(viewer: T3ImageViewerController) {
446 super.init(rootViewController: viewer)
447 modalPresentationStyle = .overFullScreen
448 modalPresentationCapturesStatusBarAppearance = true
449 overrideUserInterfaceStyle = .dark
450 view.backgroundColor = .clear
451 if #unavailable(iOS 26.0) {
452 // Before iOS 26 bars at the scroll edge are transparent; iOS 26 gives them its edge blur instead.
453 let bar = UINavigationBarAppearance()
454 bar.configureWithDefaultBackground()
455 navigationBar.scrollEdgeAppearance = bar
456 navigationBar.compactScrollEdgeAppearance = bar
457 let tools = UIToolbarAppearance()
458 tools.configureWithDefaultBackground()
459 toolbar.scrollEdgeAppearance = tools
460 toolbar.compactScrollEdgeAppearance = tools
461 }
462 setNavigationBarHidden(true, animated: false)
463 setToolbarHidden(true, animated: false)
464 }
465
466 @available(*, unavailable)
467 required init?(coder: NSCoder) { nil }
468
469 override var childForStatusBarHidden: UIViewController? { topViewController }
470 override var childForStatusBarStyle: UIViewController? { topViewController }
471 override var childForHomeIndicatorAutoHidden: UIViewController? { topViewController }
472 }
473
474 final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
475 var sourceView: (Int) -> UIView? = { _ in nil }
476 var fileForPage: (Int) -> URL? = { _ in nil }
477 var onRetry: (Int) -> Void = { _ in }
478 var onPageChange: (Int) -> Void = { _ in }
479 var onDismissed: () -> Void = {}
480
481 private let titles: [String]
482 private var currentIndex: Int
483 private let backdrop = UIView()
484 private let pager = UIScrollView()
485 private var pages: [T3ImageViewerPage] = []
486 private let titleLabel = UILabel()
487 private let counterLabel = UILabel()
488 private lazy var dismissPan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:)))
489 private var chromeHidden = false
490 private var chromeHiddenBeforeDrag = false
491 private var dragAnchor = CGPoint.zero
492 private var transitioning = true
493 private var closeRequested = false
494 private var closing = false
495 private var revealed = false
496 private var revealWaiters: [CheckedContinuation<Void, Never>] = []
497 private var laidOutSize = CGSize.zero
498 private var isLayingOut = false
499 private lazy var saveItem = UIBarButtonItem(
500 title: "Save to Photos", image: UIImage(systemName: "square.and.arrow.down"),
501 primaryAction: UIAction { [weak self] _ in self?.save() })
502 private lazy var shareItem = UIBarButtonItem(
503 systemItem: .action, primaryAction: UIAction { [weak self] _ in self?.share() })
504 private static let pageGap: CGFloat = 20
505
506 init(titles: [String], selectedIndex: Int) {
507 self.titles = titles
508 currentIndex = selectedIndex
509 super.init(nibName: nil, bundle: nil)
510 }
511
512 @available(*, unavailable)
513 required init?(coder: NSCoder) { nil }
514
515 override var prefersStatusBarHidden: Bool { chromeHidden }
516 override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
517 override var prefersHomeIndicatorAutoHidden: Bool { chromeHidden }
518 override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade }
519
520 override func viewDidLoad() {
521 super.viewDidLoad()
522 view.backgroundColor = .clear
523 backdrop.backgroundColor = .black
524 backdrop.alpha = 0
525 view.addSubview(backdrop)
526 pager.isPagingEnabled = true
527 pager.showsHorizontalScrollIndicator = false
528 pager.showsVerticalScrollIndicator = false
529 pager.contentInsetAdjustmentBehavior = .never
530 pager.alwaysBounceVertical = false
531 pager.delegate = self
532 pager.isHidden = true
533 view.addSubview(pager)
534 for index in titles.indices {
535 let page = T3ImageViewerPage()
536 page.imageView.accessibilityLabel = titles[index]
537 page.onRetry = { [weak self] in self?.onRetry(index) }
538 page.scroll.panGestureRecognizer.require(toFail: dismissPan)
539 page.setLoading()
540 pages.append(page)
541 pager.addSubview(page)
542 }
543 pager.panGestureRecognizer.require(toFail: dismissPan)
544 dismissPan.delegate = self
545 dismissPan.maximumNumberOfTouches = 1
546 view.addGestureRecognizer(dismissPan)
547 let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
548 doubleTap.numberOfTapsRequired = 2
549 pager.addGestureRecognizer(doubleTap)
550 let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap))
551 singleTap.require(toFail: doubleTap)
552 pager.addGestureRecognizer(singleTap)
553 configureChrome()
554 updateTitle()
555 }
556
557 private func configureChrome() {
558 navigationItem.leftBarButtonItem = UIBarButtonItem(
559 systemItem: .close, primaryAction: UIAction { [weak self] _ in self?.close() })
560 if #unavailable(iOS 26.0) {
561 // Before iOS 26 a navigation item has no subtitle, so the count sits under the title by hand.
562 titleLabel.font = .preferredFont(forTextStyle: .headline)
563 counterLabel.font = .preferredFont(forTextStyle: .caption1)
564 counterLabel.textColor = .secondaryLabel
565 for label in [titleLabel, counterLabel] {
566 label.textAlignment = .center
567 label.adjustsFontForContentSizeCategory = true
568 label.lineBreakMode = .byTruncatingMiddle
569 }
570 let titles = UIStackView(arrangedSubviews: [titleLabel, counterLabel])
571 titles.axis = .vertical
572 titles.alignment = .center
573 navigationItem.titleView = titles
574 }
575 toolbarItems = [.flexibleSpace(), saveItem, shareItem]
576 setContentScrollView(pager, for: .top)
577 setContentScrollView(pager, for: .bottom)
578 }
579
580 /// Shows or hides the bars through UIKit, which also moves them out of an iPhone Duo's side bar.
581 private func setBarsVisible(_ visible: Bool) {
582 navigationController?.setNavigationBarHidden(!visible, animated: true)
583 navigationController?.setToolbarHidden(!visible, animated: true)
584 }
585
586 private func updateTitle() {
587 updateActions()
588 let title = titles[safe: currentIndex]
589 let counter = titles.count > 1 ? "\(currentIndex + 1) of \(titles.count)" : nil
590 navigationItem.title = title
591 if #available(iOS 26.0, *) { navigationItem.subtitle = counter }
592 titleLabel.text = title
593 counterLabel.text = counter
594 counterLabel.isHidden = counter == nil
595 }
596
597 override func viewDidLayoutSubviews() {
598 super.viewDidLayoutSubviews()
599 backdrop.frame = view.bounds
600 guard view.bounds.size != laidOutSize else { return }
601 laidOutSize = view.bounds.size
602 // Resizing the pager scrolls it; that must not move the reader to another page.
603 isLayingOut = true
604 defer { isLayingOut = false }
605 // Pages sit a gap apart, like Photos, so the pager is a gap wider than the screen.
606 let pageWidth = view.bounds.width + Self.pageGap
607 pager.frame = CGRect(x: -Self.pageGap / 2, y: 0, width: pageWidth, height: view.bounds.height)
608 for (index, page) in pages.enumerated() {
609 page.transform = .identity
610 page.frame = CGRect(x: CGFloat(index) * pageWidth + Self.pageGap / 2, y: 0,
611 width: view.bounds.width, height: view.bounds.height)
612 }
613 pager.contentSize = CGSize(width: pageWidth * CGFloat(pages.count), height: view.bounds.height)
614 pager.contentOffset = CGPoint(x: CGFloat(currentIndex) * pageWidth, y: 0)
615 }
616
617 func setImage(_ image: UIImage, at index: Int, full: Bool) {
618 guard let page = pages[safe: index] else { return }
619 page.setImage(image, full: full)
620 updateActions()
621 }
622
623 func setLoading(at index: Int) { pages[safe: index]?.setLoading() }
624
625 func release(at index: Int, placeholder: UIImage?) {
626 pages[safe: index]?.release(to: placeholder)
627 updateActions()
628 }
629
630 func setFailed(at index: Int, retryable: Bool) {
631 pages[safe: index]?.setFailed(retryable: retryable)
632 updateActions()
633 }
634
635 /// Save and Share act on the original, so they wait until the current page shows it.
636 private func updateActions() {
637 let ready = pages[safe: currentIndex]?.isFull == true
638 saveItem.isEnabled = ready
639 shareItem.isEnabled = ready
640 }
641
642 // MARK: Transitions
643
644 private var reduceMotion: Bool { UIAccessibility.isReduceMotionEnabled }
645
646 private func visibleSource(_ index: Int) -> UIView? {
647 guard !reduceMotion, let source = sourceView(index), source.window === view.window, !source.isHidden else { return nil }
648 let frame = source.convert(source.bounds, to: view)
649 guard frame.width > 1, frame.height > 1, view.bounds.intersects(frame) else { return nil }
650 return source
651 }
652
653 private static func cornerRadius(of view: UIView) -> CGFloat {
654 var queue = [view]
655 var depth = 0
656 while !queue.isEmpty, depth < 4 {
657 for candidate in queue where candidate.layer.cornerRadius > 0 { return candidate.layer.cornerRadius }
658 queue = queue.flatMap(\.subviews)
659 depth += 1
660 }
661 return 0
662 }
663
664 private func makeTransitionView(_ image: UIImage, frame: CGRect) -> UIImageView {
665 let transition = UIImageView(image: image)
666 transition.contentMode = .scaleAspectFill
667 transition.clipsToBounds = true
668 transition.frame = frame
669 view.addSubview(transition)
670 return transition
671 }
672
673 /// Returns once the open transition has finished and the thumbnails are on screen again.
674 func untilRevealed() async {
675 guard !revealed else { return }
676 await withCheckedContinuation { revealWaiters.append($0) }
677 }
678
679 func animateIn() {
680 view.layoutIfNeeded()
681 let page = pages[currentIndex]
682 let reveal = { [weak self] in
683 guard let self else { return }
684 self.pager.isHidden = false
685 self.transitioning = false
686 self.revealed = true
687 for waiter in self.revealWaiters { waiter.resume() }
688 self.revealWaiters.removeAll()
689 self.setNeedsStatusBarAppearanceUpdate()
690 UIAccessibility.post(notification: .screenChanged, argument: page.imageView)
691 if self.closeRequested { self.close() }
692 }
693 guard let image = page.image, let source = visibleSource(currentIndex) else {
694 pager.isHidden = false
695 pager.alpha = 0
696 setBarsVisible(true)
697 UIView.animate(withDuration: reduceMotion ? 0.2 : 0.25, animations: {
698 self.backdrop.alpha = 1
699 self.pager.alpha = 1
700 }, completion: { _ in reveal() })
701 return
702 }
703 let transition = makeTransitionView(image, frame: source.convert(source.bounds, to: view))
704 transition.layer.cornerRadius = Self.cornerRadius(of: source)
705 let sourceAlpha = source.alpha
706 source.alpha = 0
707 let target = page.fittedFrame(in: view)
708 let animator = UIViewPropertyAnimator(duration: 0.42, dampingRatio: 0.86) {
709 transition.frame = target
710 transition.layer.cornerRadius = 0
711 self.backdrop.alpha = 1
712 }
713 setBarsVisible(true)
714 animator.addCompletion { _ in
715 source.alpha = sourceAlpha
716 transition.removeFromSuperview()
717 reveal()
718 }
719 animator.startAnimation()
720 }
721
722 /// Closes back into the current page's thumbnail, or away in the drag's direction when it is gone.
723 func close(velocity: CGPoint = .zero) {
724 closeRequested = true
725 guard !transitioning, !closing else { return }
726 closing = true
727 transitioning = true
728 setNeedsStatusBarAppearanceUpdate()
729 setBarsVisible(false)
730 let page = pages[currentIndex]
731 guard let image = page.image else {
732 UIView.animate(withDuration: 0.2, animations: { self.view.alpha = 0 }, completion: { _ in self.finishClose() })
733 return
734 }
735 let transition = makeTransitionView(image, frame: page.imageView.convert(page.imageView.bounds, to: view))
736 pager.isHidden = true
737 guard let source = visibleSource(currentIndex) else {
738 let direction: CGFloat = velocity.y < 0 ? -1 : 1
739 let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeIn) {
740 transition.center.y += direction * self.view.bounds.height
741 self.backdrop.alpha = 0
742 if self.reduceMotion { transition.alpha = 0 }
743 }
744 animator.addCompletion { _ in self.finishClose() }
745 animator.startAnimation()
746 return
747 }
748 let sourceAlpha = source.alpha
749 source.alpha = 0
750 let target = source.convert(source.bounds, to: view)
751 let radius = Self.cornerRadius(of: source)
752 let speed = hypot(velocity.x, velocity.y)
753 let distance = hypot(target.midX - transition.center.x, target.midY - transition.center.y)
754 let initial = distance > 0 ? CGVector(dx: velocity.x / distance, dy: velocity.y / distance) : .zero
755 let timing = UISpringTimingParameters(dampingRatio: 0.88, initialVelocity: speed > 0 ? initial : .zero)
756 let animator = UIViewPropertyAnimator(duration: 0.4, timingParameters: timing)
757 animator.addAnimations {
758 transition.frame = target
759 transition.layer.cornerRadius = radius
760 self.backdrop.alpha = 0
761 }
762 animator.addCompletion { _ in
763 source.alpha = sourceAlpha
764 self.finishClose()
765 }
766 animator.startAnimation()
767 }
768
769 private func finishClose() {
770 presentingViewController?.dismiss(animated: false) { [onDismissed] in onDismissed() }
771 }
772
773 // MARK: Gestures
774
775 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
776 guard gestureRecognizer === dismissPan else { return true }
777 guard !transitioning, !pager.isDragging, !pager.isDecelerating,
778 let page = pages[safe: currentIndex], !page.isZoomed
779 else { return false }
780 let velocity = dismissPan.velocity(in: view)
781 return abs(velocity.y) > abs(velocity.x)
782 }
783
784 @objc private func handleDismissPan(_ gesture: UIPanGestureRecognizer) {
785 let page = pages[currentIndex]
786 let translation = gesture.translation(in: view)
787 switch gesture.state {
788 case .began:
789 chromeHiddenBeforeDrag = chromeHidden
790 dragAnchor = gesture.location(in: page)
791 setChromeHidden(true)
792 case .changed:
793 // Shrink around the finger, as Photos does, so the touched spot stays under it.
794 let progress = min(1, abs(translation.y) / (view.bounds.height / 2))
795 let scale = 1 - 0.3 * progress
796 let offset = CGPoint(x: dragAnchor.x - page.bounds.midX, y: dragAnchor.y - page.bounds.midY)
797 page.transform = CGAffineTransform(translationX: translation.x + (1 - scale) * offset.x,
798 y: translation.y + (1 - scale) * offset.y).scaledBy(x: scale, y: scale)
799 backdrop.alpha = 1 - progress
800 case .ended, .cancelled, .failed:
801 let velocity = gesture.velocity(in: view)
802 let flung = abs(velocity.y) > 800 && velocity.y * translation.y > 0
803 if gesture.state == .ended, flung || abs(translation.y) > 120 {
804 close(velocity: velocity)
805 } else {
806 UIViewPropertyAnimator(duration: 0.35, dampingRatio: 0.8) {
807 page.transform = .identity
808 self.backdrop.alpha = 1
809 }.startAnimation()
810 setChromeHidden(chromeHiddenBeforeDrag)
811 }
812 default:
813 break
814 }
815 }
816
817 @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
818 guard !transitioning, let page = pages[safe: currentIndex] else { return }
819 page.toggleZoom(at: gesture.location(in: page))
820 }
821
822 @objc private func handleSingleTap() {
823 guard !transitioning else { return }
824 setChromeHidden(!chromeHidden)
825 }
826
827 private func setChromeHidden(_ hidden: Bool) {
828 guard chromeHidden != hidden else { return }
829 chromeHidden = hidden
830 setBarsVisible(!hidden)
831 UIView.animate(withDuration: 0.2) { self.setNeedsStatusBarAppearanceUpdate() }
832 setNeedsUpdateOfHomeIndicatorAutoHidden()
833 }
834
835 func scrollViewDidScroll(_ scrollView: UIScrollView) {
836 guard scrollView === pager, !transitioning, !isLayingOut, pager.bounds.width > 0 else { return }
837 let index = Int((pager.contentOffset.x / pager.bounds.width).rounded())
838 guard pages.indices.contains(index), index != currentIndex else { return }
839 pages[currentIndex].resetZoom(animated: false)
840 currentIndex = index
841 updateTitle()
842 onPageChange(index)
843 }
844
845 private func scroll(to index: Int) {
846 guard pages.indices.contains(index), !transitioning else { return }
847 pager.setContentOffset(CGPoint(x: CGFloat(index) * pager.bounds.width, y: 0), animated: !reduceMotion)
848 }
849
850 // MARK: Share, keyboard and accessibility
851
852 private func save() {
853 let image = pages[currentIndex].isFull ? pages[currentIndex].image : nil
854 // Original bytes keep the format and metadata; an SVG only has its rendered image. The copy
855 // belongs to this save, since closing the viewer deletes its files before Photos may read them.
856 let original = fileForPage(currentIndex).flatMap { file -> URL? in
857 guard file.pathExtension.lowercased() != "svg", let source = CGImageSourceCreateWithURL(file as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil }
858 let copy = FileManager.default.temporaryDirectory.appendingPathComponent("t3-save-\(UUID().uuidString)")
859 .appendingPathComponent(file.lastPathComponent)
860 do {
861 try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
862 try FileManager.default.copyItem(at: file, to: copy)
863 return copy
864 } catch {
865 return nil
866 }
867 }
868 guard original != nil || image != nil else { return }
869 let cleanUp = { if let original { try? FileManager.default.removeItem(at: original.deletingLastPathComponent()) } }
870 PHPhotoLibrary.requestAuthorization(for: .addOnly) { [weak self] status in
871 guard status == .authorized || status == .limited else {
872 cleanUp()
873 DispatchQueue.main.async { self?.showSaveError("Allow T3 Code to add photos in Settings.") }
874 return
875 }
876 PHPhotoLibrary.shared().performChanges({
877 if let original {
878 PHAssetCreationRequest.forAsset().addResource(with: .photo, fileURL: original, options: nil)
879 } else if let image {
880 PHAssetChangeRequest.creationRequestForAsset(from: image)
881 }
882 }, completionHandler: { saved, error in
883 cleanUp()
884 DispatchQueue.main.async {
885 if saved {
886 self?.confirmSaved()
887 } else {
888 self?.showSaveError(error?.localizedDescription ?? "Photos could not save this image.")
889 }
890 }
891 })
892 }
893 }
894
895 private func confirmSaved() {
896 UINotificationFeedbackGenerator().notificationOccurred(.success)
897 UIAccessibility.post(notification: .announcement, argument: "Saved to Photos")
898 saveItem.image = UIImage(systemName: "checkmark")
899 DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
900 self?.saveItem.image = UIImage(systemName: "square.and.arrow.down")
901 }
902 }
903
904 private func showSaveError(_ message: String) {
905 let alert = UIAlertController(title: "Could not save image", message: message, preferredStyle: .alert)
906 alert.addAction(UIAlertAction(title: "OK", style: .default))
907 present(alert, animated: true)
908 }
909
910 private func share() {
911 let page = pages[currentIndex]
912 let item: Any? = fileForPage(currentIndex) ?? (page.isFull ? page.image : nil)
913 guard let item else { return }
914 let sheet = UIActivityViewController(activityItems: [item], applicationActivities: nil)
915 sheet.popoverPresentationController?.sourceItem = shareItem
916 present(sheet, animated: true)
917 }
918
919 override var canBecomeFirstResponder: Bool { true }
920
921 override func viewDidAppear(_ animated: Bool) {
922 super.viewDidAppear(animated)
923 becomeFirstResponder()
924 }
925
926 override var keyCommands: [UIKeyCommand]? {
927 [
928 UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(handleEscape)),
929 UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(handlePrevious)),
930 UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(handleNext)),
931 ]
932 }
933
934 @objc private func handleEscape() { close() }
935 @objc private func handlePrevious() { scroll(to: currentIndex - 1) }
936 @objc private func handleNext() { scroll(to: currentIndex + 1) }
937
938 override func accessibilityPerformEscape() -> Bool {
939 close()
940 return true
941 }
942
943 override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
944 switch direction {
945 case .left: scroll(to: currentIndex + 1)
946 case .right: scroll(to: currentIndex - 1)
947 default: return false
948 }
949 UIAccessibility.post(notification: .pageScrolled, argument: counterLabel.text)
950 return true
951 }
952 }