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