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

T3NativeControlsModule.swift

219 lines8.0 KB

1import ExpoModulesCore
2import Security
3import UIKit
4​
5// Expo Modules 2.0: plain members marked @JS are bound by the macro, while the
6// views and main-queue presenters stay in definition(). Both are merged.
7@ExpoModule("T3NativeControls")
8public final class T3NativeControlsModule: Module {
9 private let presentationSources = T3PresentationSources()
10 private var videoPresentation: T3NativeVideoPresentation?
11 private var filePresentation: T3NativeFilePresentation?
12​
13 public func definition() -> ModuleDefinition {
14 AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
15 try self.presentVideo(
16 url: url,
17 title: title,
18 sourceIdentifier: sourceIdentifier,
19 identifier: identifier,
20 promise: promise
21 )
22 }.runOnQueue(.main)
23​
24 AsyncFunction("presentFile") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
25 try self.presentFile(url: url, title: title, sourceIdentifier: sourceIdentifier,
26 identifier: identifier, promise: promise)
27 }.runOnQueue(.main)
28​
29 OnDestroy {
30 let presentation = self.videoPresentation
31 let file = self.filePresentation
32 DispatchQueue.main.async {
33 presentation?.dismiss()
34 file?.dismiss()
35 }
36 }
37​
38 View(T3PresentationSourceView.self) {
39 ViewName("PresentationSource")
40 Prop("identifier") { (view: T3PresentationSourceView, identifier: String) in
41 view.sources = self.presentationSources
42 view.identifier = identifier
43 }
44 }
45​
46 View(T3ContextSheetSizeView.self) {
47 ViewName("ContextSheetSize")
48 Prop("contentHeight") { (view: T3ContextSheetSizeView, height: Double) in
49 view.contentHeight = CGFloat(height)
50 }
51 }
52​
53 AsyncFunction("shareFileFromSource") { (url: URL, title: String, identifier: String, promise: Promise) in
54 try self.shareFile(url: url, title: title, sourceIdentifier: identifier, promise: promise)
55 }.runOnQueue(.main)
56 }
57​
58 // UIKit presenters are main-actor isolated rather than run on the JS thread
59 // the macro would otherwise pick.
60 @JS
61 @MainActor
62 func dismissVideo(identifier: String) async {
63 dismissVideoPresentation(identifier: identifier)
64 }
65​
66 @JS
67 @MainActor
68 func dismissFile(identifier: String) async {
69 dismissFilePresentation(identifier: identifier)
70 }
71​
72 // Rotates the interface without Simulator menu UI scripting, which CI
73 // runners cannot perform (osascript is denied Accessibility access there).
74 @JS
75 @MainActor
76 func applyShowcaseOrientation(orientation: String) async {
77 let mask: UIInterfaceOrientationMask = orientation == "landscape" ? .landscapeRight : .portrait
78 for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
79 windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: mask)) { error in
80 NSLog("T3NativeControls applyShowcaseOrientation(\(orientation)) failed: \(error)")
81 }
82 for window in windowScene.windows {
83 window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
84 }
85 }
86 }
87​
88 // The geometry request above can fail transiently (for example before the
89 // scene is foreground-active), so callers poll this until it settles.
90 // Screen bounds — not the scene's interface orientation — decide the
91 // answer because they match the captured framebuffer: with iPadOS
92 // windowing active, a floating landscape window still reports a portrait
93 // screen, and screenshots would come out portrait.
94 @JS
95 @MainActor
96 func getInterfaceOrientation() async -> String {
97 guard
98 let windowScene = UIApplication.shared.connectedScenes
99 .compactMap({ $0 as? UIWindowScene })
100 .first
101 else {
102 return "unknown"
103 }
104 let bounds = windowScene.screen.coordinateSpace.bounds
105 return bounds.width > bounds.height ? "landscape" : "portrait"
106 }
107​
108 private func launchArgument(_ flag: String) -> String? {
109 let arguments = ProcessInfo.processInfo.arguments
110 guard
111 let flagIndex = arguments.firstIndex(of: flag),
112 arguments.indices.contains(flagIndex + 1)
113 else {
114 return nil
115 }
116 return arguments[flagIndex + 1]
117 }
118​
119 @JS
120 func getShowcasePairingUrl() -> String? {
121 launchArgument("--showcasePairingUrl")
122 }
123​
124 @JS
125 func getShowcaseScene() -> String? {
126 let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
127 if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
128 .trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
129 return storedScene
130 }
131 return launchArgument("--showcaseScene")
132 }
133​
134 // The palette is fixed for the whole capture, so it only ever arrives as a
135 // launch argument — unlike the scene, which the runner rewrites in place.
136 @JS
137 func getShowcaseTheme() -> String? {
138 launchArgument("--showcaseTheme")
139 }
140​
141 @JS
142 func getShowcaseOrientation() -> String? {
143 launchArgument("--showcaseOrientation")
144 }
145​
146 @JS
147 func prepareShowcaseCapture() {
148 for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
149 SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
150 }
151 }
152​
153 @JS(.concurrent)
154 func markShowcaseReady(scene: String) async {
155 let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
156 try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
157 }
158​
159 private func presentVideo(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws {
160 let isPlayableURL = url.isFileURL
161 ? FileManager.default.isReadableFile(atPath: url.path)
162 : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)
163 guard videoPresentation == nil, filePresentation == nil,
164 let presenter = appContext?.utilities?.currentViewController(),
165 isPlayableURL
166 else {
167 throw NSError(
168 domain: "T3NativeVideo",
169 code: 2,
170 userInfo: [NSLocalizedDescriptionKey: "The video preview is no longer available."]
171 )
172 }
173 let presentation = T3NativeVideoPresentation(identifier: identifier, url: url, title: title) { [weak self] error in
174 self?.videoPresentation = nil
175 if let error { promise.reject(error) } else { promise.resolve(nil) }
176 }
177 videoPresentation = presentation
178 presentation.present(from: presenter, sources: presentationSources, sourceIdentifier: sourceIdentifier)
179 }
180​
181 private func dismissVideoPresentation(identifier: String) {
182 if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
183 }
184​
185 private func presentFile(url: URL, title: String, sourceIdentifier: String,
186 identifier: String, promise: Promise) throws {
187 guard filePresentation == nil, videoPresentation == nil,
188 let presenter = appContext?.utilities?.currentViewController()
189 else { throw URLError(.cannotLoadFromNetwork) }
190 let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
191 sourceIdentifier: sourceIdentifier) { [weak self] error in
192 self?.filePresentation = nil
193 if let error { promise.reject(error) } else { promise.resolve(nil) }
194 }
195 filePresentation = file
196 file.present(url: url, title: title, from: presenter)
197 }
198​
199 private func dismissFilePresentation(identifier: String) {
200 if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
201 }
202​
203 private func shareFile(url: URL, title: String, sourceIdentifier: String, promise: Promise) throws {
204 guard let presenter = appContext?.utilities?.currentViewController() else {
205 throw NSError(
206 domain: "T3NativePresentation",
207 code: 2,
208 userInfo: [NSLocalizedDescriptionKey: "The presenting screen is no longer open."]
209 )
210 }
211 try presentFileShare(
212 url: url,
213 title: title,
214 source: presentationSources.view(for: sourceIdentifier),
215 presenter: presenter,
216 promise: promise
217 )
218 }