Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

T3NativeFilePresentation.swift

185 lines7.6 KB

1import ImageIO
2import QuickLook
3import UIKit
4import UniformTypeIdentifiers
5​
6private final class FilePreviewItem: NSObject, QLPreviewItem {
7 var previewItemURL: URL?
8 var previewItemTitle: String?
9}
10​
11private final class FilePreviewController: QLPreviewController {
12 var onAppear: (() -> Void)?
13​
14 override func viewDidAppear(_ animated: Bool) {
15 super.viewDidAppear(animated)
16 onAppear?()
17 }
19​
20/// Quick Look owns image and document controls, zooming, and source-view transitions.
21final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
22 QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
23 let identifier: String
24 private var controller: UIViewController?
25 private let completion: (Error?) -> Void
26 private weak var sources: T3PresentationSources?
27 private let sourceIdentifier: String
28 private let item = FilePreviewItem()
29 private var loading: Task<Void, Never>?
30 private var dismissRequested = false
31 private var finished = false
32​
33 init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String, completion: @escaping (Error?) -> Void) {
34 self.identifier = identifier
35 self.sources = sources
36 self.sourceIdentifier = sourceIdentifier
37 self.completion = completion
38 super.init()
39 }
40​
41 func present(url: URL, title: String, from presenter: UIViewController) {
42 loading = Task { @MainActor [self] in
43 do {
44 let file = try await Self.prepareFile(url: url, title: title)
45 guard !finished, !Task.isCancelled else {
46 try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
47 return
48 }
49 // Quick Look knows which formats it renders; refuse before presenting so the caller
50 // can fall back instead of showing an "unsupported format" page.
51 guard QLPreviewController.canPreview(file as NSURL) else {
52 try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
53 throw NSError(
54 domain: "T3NativePresentation",
55 code: 3,
56 userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
57 )
58 }
59 item.previewItemURL = file
60 item.previewItemTitle = title
61 let preview = FilePreviewController()
62 preview.delegate = self
63 preview.dataSource = self
64 preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
65 controller = preview
66 presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
67 resumePendingDismissal()
68 }
69 preview.presentationController?.delegate = self
70 } catch {
71 finish(error: error)
72 }
73 }
74 }
75​
76 func dismiss() {
77 dismissRequested = true
78 loading?.cancel()
79 guard !finished else { return }
80 guard let controller else { finish(); return }
81 // Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
82 // Starting a second modal transition while UIKit is settling the first can strand it.
83 guard !controller.isBeingPresented, !controller.isBeingDismissed else { return }
84 controller.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [self] in finish() }
85 }
86​
87 private func resumePendingDismissal() {
88 // Appearance callbacks run before UIKit has cleared the current transition.
89 DispatchQueue.main.async { [weak self] in
90 if self?.dismissRequested == true { self?.dismiss() }
91 }
92 }
93​
94 func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item.previewItemURL == nil ? 0 : 1 }
95​
96 func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
97 item
98 }
99​
100 func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
101 guard !UIAccessibility.isReduceMotionEnabled else { return nil }
102 return sources?.view(for: sourceIdentifier)
103 }
104​
105 func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem,
106 inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect {
107 guard !UIAccessibility.isReduceMotionEnabled, let source = sources?.view(for: sourceIdentifier) else { return .zero }
108 view.pointee = source
109 return source.bounds
110 }
111​
112 func previewControllerDidDismiss(_ controller: QLPreviewController) { finish() }
113​
114 func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
115​
116 private func finish(error: Error? = nil) {
117 guard !finished else { return }
118 finished = true
119 loading?.cancel()
120 loading = nil
121 if let file = item.previewItemURL {
122 try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
123 }
124 item.previewItemURL = nil
125 DispatchQueue.main.async { [completion] in completion(error) }
126 }
127​
128 /// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
129 nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL {
130 try Task.checkCancellation()
131 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)")
132 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
133 do {
134 let download = directory.appendingPathComponent("original")
135 if url.isFileURL {
136 try FileManager.default.copyItem(at: url, to: download)
137 } else if url.scheme == "data" {
138 try Data(contentsOf: url).write(to: download, options: .atomic)
139 } else {
140 guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else {
141 throw URLError(.unsupportedURL)
142 }
143 let (temporaryFile, response) = try await URLSession.shared.download(from: url)
144 guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
145 throw URLError(.badServerResponse)
146 }
147 try FileManager.default.moveItem(at: temporaryFile, to: download)
148 }
149 try Task.checkCancellation()
150 // Pictures and PDFs are identified by content so a misnamed file still opens correctly.
151 // Anything else keeps its own extension: Quick Look decides from that whether it can
152 // render the document (Office, iWork, RTF and more) and refuses before we present.
153 let filename = URL(fileURLWithPath: title).lastPathComponent as NSString
154 let originalExtension = filename.pathExtension
155 var type: UTType?
156 if let image = CGImageSourceCreateWithURL(download as CFURL, nil),
157 CGImageSourceGetCount(image) > 0, let imageType = CGImageSourceGetType(image),
158 let detectedType = UTType(imageType as String) {
159 type = detectedType
160 } else if CGPDFDocument(download as CFURL) != nil {
161 type = .pdf
162 } else if originalExtension.lowercased() == "svg" {
163 type = .svg
164 }
165 let fileExtension: String
166 if let type {
167 fileExtension = UTType(filenameExtension: originalExtension) == type
168 ? originalExtension : type.preferredFilenameExtension ?? originalExtension
169 } else {
170 fileExtension = originalExtension
171 }
172 let stem = filename.deletingPathExtension
173 var name = String(stem.prefix(60)).components(separatedBy: .controlCharacters).joined(separator: "_")
174 while name.utf8.count > 200 { name.removeLast() }
175 let baseName = name.isEmpty ? "Preview" : name
176 let file = directory.appendingPathComponent(
177 fileExtension.isEmpty ? baseName : "\(baseName).\(fileExtension)")
178 try FileManager.default.moveItem(at: download, to: file)
179 return file
180 } catch {
181 try? FileManager.default.removeItem(at: directory)
182 throw error
183 }
184 }