@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 272 lines 10.6 KB
Raw
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 var onDismiss: (() -> Void)?
14
15 override func viewDidAppear(_ animated: Bool) {
16 super.viewDidAppear(animated)
17 onAppear?()
18 }
19
20 // Quick Look's own didDismiss callback can lag well behind the screen being tappable again,
21 // so a tap on the thumbnail in that gap would land while JS still thinks the viewer is open.
22 override func viewDidDisappear(_ animated: Bool) {
23 super.viewDidDisappear(animated)
24 if isBeingDismissed { onDismiss?() }
25 }
26 }
27
28 /// A load faster than this zooms straight from the thumbnail without a spinner.
29 private let spinnerDelayNanoseconds: UInt64 = 250_000_000
30
31 /// Quick Look for PDFs and documents; images open in T3NativeImageViewer.
32 final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
33 QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
34 let identifier: String
35 private var controller: FilePreviewController?
36 private let completion: (Error?) -> Void
37 private let onFinish: () -> Void
38 private weak var sources: T3PresentationSources?
39 private let sourceIdentifier: String
40 private var file: URL?
41 private var item: FilePreviewItem?
42 private var download: Task<Void, Never>?
43 private var spinnerDelay: Task<Void, Never>?
44 private var spinner: UIView?
45 private var openError: Error?
46 private var dismissRequested = false
47 private var finished = false
48
49 init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String,
50 onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
51 self.identifier = identifier
52 self.sources = sources
53 self.sourceIdentifier = sourceIdentifier
54 self.onFinish = onFinish
55 self.completion = completion
56 super.init()
57 }
58
59 /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
60 func present(url: URL, title: String, from presenter: UIViewController) {
61 spinnerDelay = Task { @MainActor [self] in
62 try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds)
63 guard !Task.isCancelled else { return }
64 showSpinner()
65 }
66 download = Task { @MainActor [self] in
67 let result: Result<URL, Error>
68 do {
69 result = .success(try await Self.prepareFile(url: url, title: title))
70 } catch {
71 result = .failure(error)
72 }
73 download = nil
74 settle(result, title: title, presenter: presenter)
75 }
76 }
77
78 private func settle(_ result: Result<URL, Error>, title: String, presenter: UIViewController) {
79 guard !finished, controller == nil, !dismissRequested else {
80 if case .success(let file) = result { Self.remove(file) }
81 return
82 }
83 switch result {
84 case .success(let file):
85 // Quick Look knows which formats it renders; refuse before presenting so the caller
86 // can fall back instead of showing an "unsupported format" page.
87 guard QLPreviewController.canPreview(file as NSURL) else {
88 Self.remove(file)
89 openError = NSError(
90 domain: "T3NativePresentation",
91 code: 3,
92 userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
93 )
94 finish()
95 return
96 }
97 self.file = file
98 show(file: file, title: title, presenter: presenter)
99 case .failure(let error):
100 openError = error
101 finish()
102 }
103 }
104
105 private func show(file: URL, title: String, presenter: UIViewController) {
106 cancelLoading()
107 let item = FilePreviewItem()
108 item.previewItemURL = file
109 item.previewItemTitle = title
110 self.item = item
111 let preview = FilePreviewController()
112 preview.delegate = self
113 preview.dataSource = self
114 preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
115 preview.onDismiss = { [weak self] in self?.finish() }
116 controller = preview
117 presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
118 resumePendingDismissal()
119 }
120 preview.presentationController?.delegate = self
121 }
122
123 /// Shows over the tapped thumbnail that a slow open is on its way.
124 private func showSpinner() {
125 guard !finished, controller == nil, spinner == nil,
126 let source = sources?.view(for: sourceIdentifier),
127 let window = source.window
128 else { return }
129 let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
130 backing.backgroundColor = UIColor.black.withAlphaComponent(0.55)
131 backing.layer.cornerRadius = 22
132 backing.isUserInteractionEnabled = false
133 let indicator = UIActivityIndicatorView(style: .medium)
134 indicator.color = .white
135 indicator.center = CGPoint(x: 22, y: 22)
136 indicator.startAnimating()
137 backing.addSubview(indicator)
138 backing.center = source.convert(CGPoint(x: source.bounds.midX, y: source.bounds.midY), to: window)
139 window.addSubview(backing)
140 spinner = backing
141 }
142
143 private func cancelLoading() {
144 download?.cancel()
145 download = nil
146 spinnerDelay?.cancel()
147 spinnerDelay = nil
148 spinner?.removeFromSuperview()
149 spinner = nil
150 }
151
152 func dismiss() {
153 dismissRequested = true
154 guard !finished else { return }
155 guard let controller else { finish(); return }
156 // Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
157 // Starting a second modal transition while UIKit is settling the first can strand it.
158 guard !controller.isBeingPresented, !controller.isBeingDismissed else { return }
159 controller.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [self] in finish() }
160 }
161
162 private func resumePendingDismissal() {
163 // Appearance callbacks run before UIKit has cleared the current transition.
164 DispatchQueue.main.async { [weak self] in
165 if self?.dismissRequested == true { self?.dismiss() }
166 }
167 }
168
169 func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item == nil ? 0 : 1 }
170
171 func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
172 item ?? FilePreviewItem()
173 }
174
175 private var sourceView: UIView? {
176 UIAccessibility.isReduceMotionEnabled ? nil : sources?.view(for: sourceIdentifier)
177 }
178
179 func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
180 sourceView
181 }
182
183 func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem,
184 inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect {
185 guard let source = sourceView else { return .zero }
186 view.pointee = source
187 return source.bounds
188 }
189
190 func previewControllerDidDismiss(_ controller: QLPreviewController) { finish() }
191
192 func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
193
194 private func finish() {
195 guard !finished else { return }
196 finished = true
197 cancelLoading()
198 if let file { Self.remove(file) }
199 file = nil
200 item = nil
201 DispatchQueue.main.async { [completion, openError] in completion(openError) }
202 // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
203 onFinish()
204 }
205
206 private static func remove(_ file: URL) {
207 try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
208 }
209
210 /// Writes the bytes behind a file, data or http(s) URL to `destination`, returning the MIME type it declares.
211 nonisolated private static func copyOriginal(_ url: URL, to destination: URL) async throws -> String? {
212 if url.isFileURL {
213 try FileManager.default.copyItem(at: url, to: destination)
214 return nil
215 }
216 if url.scheme == "data" {
217 try Data(contentsOf: url).write(to: destination, options: .atomic)
218 return url.absoluteString.lowercased().hasPrefix("data:image/svg+xml") ? "image/svg+xml" : nil
219 }
220 guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { throw URLError(.unsupportedURL) }
221 let (temporaryFile, response) = try await URLSession.shared.download(from: url)
222 guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
223 throw URLError(.badServerResponse)
224 }
225 try FileManager.default.moveItem(at: temporaryFile, to: destination)
226 return response.mimeType
227 }
228
229 /// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
230 nonisolated static func prepareFile(url: URL, title: String) async throws -> URL {
231 try Task.checkCancellation()
232 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)")
233 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
234 do {
235 let download = directory.appendingPathComponent("original")
236 let mimeType = try await copyOriginal(url, to: download)
237 try Task.checkCancellation()
238 // Detect images and PDFs by content; preserve other extensions so Quick Look can decide support.
239 let filename = URL(fileURLWithPath: title).lastPathComponent as NSString
240 let originalExtension = filename.pathExtension
241 var type: UTType?
242 if let image = CGImageSourceCreateWithURL(download as CFURL, nil),
243 CGImageSourceGetCount(image) > 0, let imageType = CGImageSourceGetType(image),
244 let detectedType = UTType(imageType as String) {
245 type = detectedType
246 } else if CGPDFDocument(download as CFURL) != nil {
247 type = .pdf
248 } else if originalExtension.lowercased() == "svg" || mimeType == "image/svg+xml" {
249 // ImageIO cannot read SVG, and served images such as QR codes often have no extension.
250 type = .svg
251 }
252 let fileExtension: String
253 if let type {
254 fileExtension = UTType(filenameExtension: originalExtension) == type
255 ? originalExtension : type.preferredFilenameExtension ?? originalExtension
256 } else {
257 fileExtension = originalExtension
258 }
259 let stem = filename.deletingPathExtension
260 var name = String(stem.prefix(60)).components(separatedBy: .controlCharacters).joined(separator: "_")
261 while name.utf8.count > 200 { name.removeLast() }
262 let baseName = name.isEmpty ? "Preview" : name
263 let file = directory.appendingPathComponent(
264 fileExtension.isEmpty ? baseName : "\(baseName).\(fileExtension)")
265 try FileManager.default.moveItem(at: download, to: file)
266 return file
267 } catch {
268 try? FileManager.default.removeItem(at: directory)
269 throw error
270 }
271 }
272 }