|
| 1 | +import ImageIO |
| 2 | +import QuickLook |
| 3 | +import UIKit |
| 4 | +import UniformTypeIdentifiers |
| 5 | + |
| 6 | +private final class FilePreviewItem: NSObject, QLPreviewItem { |
| 7 | + var previewItemURL: URL? |
| 8 | + var previewItemTitle: String? |
| 9 | +} |
| 10 | + |
| 11 | +private 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. |
| 21 | +final 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 | + item.previewItemURL = file |
| 50 | + item.previewItemTitle = title |
| 51 | + let preview = FilePreviewController() |
| 52 | + preview.delegate = self |
| 53 | + preview.dataSource = self |
| 54 | + preview.onAppear = { [weak self] in self?.resumePendingDismissal() } |
| 55 | + controller = preview |
| 56 | + presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in |
| 57 | + resumePendingDismissal() |
| 58 | + } |
| 59 | + preview.presentationController?.delegate = self |
| 60 | + } catch { |
| 61 | + finish(error: error) |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + func dismiss() { |
| 67 | + dismissRequested = true |
| 68 | + loading?.cancel() |
| 69 | + guard !finished else { return } |
| 70 | + guard let controller else { finish(); return } |
| 71 | + // Drain Close from viewDidAppear after opening or cancelling an interactive dismissal. |
| 72 | + // Starting a second modal transition while UIKit is settling the first can strand it. |
| 73 | + guard !controller.isBeingPresented, !controller.isBeingDismissed else { return } |
| 74 | + controller.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [self] in finish() } |
| 75 | + } |
| 76 | + |
| 77 | + private func resumePendingDismissal() { |
| 78 | + // Appearance callbacks run before UIKit has cleared the current transition. |
| 79 | + DispatchQueue.main.async { [weak self] in |
| 80 | + if self?.dismissRequested == true { self?.dismiss() } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item.previewItemURL == nil ? 0 : 1 } |
| 85 | + |
| 86 | + func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { |
| 87 | + item |
| 88 | + } |
| 89 | + |
| 90 | + func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? { |
| 91 | + guard !UIAccessibility.isReduceMotionEnabled else { return nil } |
| 92 | + return sources?.view(for: sourceIdentifier) |
| 93 | + } |
| 94 | + |
| 95 | + func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem, |
| 96 | + inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect { |
| 97 | + guard !UIAccessibility.isReduceMotionEnabled, let source = sources?.view(for: sourceIdentifier) else { return .zero } |
| 98 | + view.pointee = source |
| 99 | + return source.bounds |
| 100 | + } |
| 101 | + |
| 102 | + func previewControllerDidDismiss(_ controller: QLPreviewController) { finish() } |
| 103 | + |
| 104 | + func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() } |
| 105 | + |
| 106 | + private func finish(error: Error? = nil) { |
| 107 | + guard !finished else { return } |
| 108 | + finished = true |
| 109 | + loading?.cancel() |
| 110 | + loading = nil |
| 111 | + if let file = item.previewItemURL { |
| 112 | + try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) |
| 113 | + } |
| 114 | + item.previewItemURL = nil |
| 115 | + DispatchQueue.main.async { [completion] in completion(error) } |
| 116 | + } |
| 117 | + |
| 118 | + /// Copy original bytes so preview and sharing do not mutate a draft or workspace file. |
| 119 | + nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL { |
| 120 | + try Task.checkCancellation() |
| 121 | + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)") |
| 122 | + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) |
| 123 | + do { |
| 124 | + let download = directory.appendingPathComponent("original") |
| 125 | + if url.isFileURL { |
| 126 | + try FileManager.default.copyItem(at: url, to: download) |
| 127 | + } else if url.scheme == "data" { |
| 128 | + try Data(contentsOf: url).write(to: download, options: .atomic) |
| 129 | + } else { |
| 130 | + guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { |
| 131 | + throw URLError(.unsupportedURL) |
| 132 | + } |
| 133 | + let (temporaryFile, response) = try await URLSession.shared.download(from: url) |
| 134 | + guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { |
| 135 | + throw URLError(.badServerResponse) |
| 136 | + } |
| 137 | + try FileManager.default.moveItem(at: temporaryFile, to: download) |
| 138 | + } |
| 139 | + try Task.checkCancellation() |
| 140 | + let type: UTType |
| 141 | + if let image = CGImageSourceCreateWithURL(download as CFURL, nil), |
| 142 | + CGImageSourceGetCount(image) > 0, let imageType = CGImageSourceGetType(image), |
| 143 | + let detectedType = UTType(imageType as String) { |
| 144 | + type = detectedType |
| 145 | + } else if CGPDFDocument(download as CFURL) != nil { |
| 146 | + type = .pdf |
| 147 | + } else { |
| 148 | + throw URLError(.cannotDecodeContentData) |
| 149 | + } |
| 150 | + let filename = URL(fileURLWithPath: title).lastPathComponent as NSString |
| 151 | + let originalExtension = filename.pathExtension |
| 152 | + let fileExtension = UTType(filenameExtension: originalExtension) == type |
| 153 | + ? originalExtension : type.preferredFilenameExtension ?? "png" |
| 154 | + let stem = filename.deletingPathExtension |
| 155 | + var name = String(stem.prefix(60)).components(separatedBy: .controlCharacters).joined(separator: "_") |
| 156 | + while name.utf8.count > 200 { name.removeLast() } |
| 157 | + let file = directory.appendingPathComponent("\(name.isEmpty ? "Preview" : name).\(fileExtension)") |
| 158 | + try FileManager.default.moveItem(at: download, to: file) |
| 159 | + return file |
| 160 | + } catch { |
| 161 | + try? FileManager.default.removeItem(at: directory) |
| 162 | + throw error |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments