also looking at this
iOS Phase 8: the presented pickers — ratchet 58 → 53, last mechanism landed
#90
11 files
+5752
-12
| @@ -0,0 +1,1689 @@ | ||
| 1 | //! `openCamera` and `pickImage` — the `mobile` namespace's two photo actions. | |
| 2 | //! | |
| 3 | //! They are one picker. Swift serves both from a single | |
| 4 | //! `UIImagePickerController` and a single delegate pair on `Coordinator` | |
| 5 | //! (`CraftApp.swift:376` declares `UIImagePickerControllerDelegate, | |
| 6 | //! UINavigationControllerDelegate`), and they differ in exactly one property: | |
| 7 | //! `sourceType`. The two delegate methods, the success shape, the cancel | |
| 8 | //! shape and the dismissal are shared. So this is one module, one delegate | |
| 9 | //! class, one instance, one pending ticket — and `Source` is both the action | |
| 10 | //! selector and the `UIImagePickerControllerSourceType` raw value. | |
| 11 | //! | |
| 12 | //! ## What crosses the bridge | |
| 13 | //! | |
| 14 | //! **Nothing.** Both injected methods are declared `function()` with zero | |
| 15 | //! parameters (`CraftApp.swift:1574-1590`), and the v1 surface drops its | |
| 16 | //! options on the floor too — `craft.camera.takePicture` is | |
| 17 | //! `function() { return legacyOpenCamera().then(normalizePhoto); }` at | |
| 18 | //! `:2343`, so the `CameraOptions` typed in | |
| 19 | //! `packages/typescript/src/api/mobile.ts:517` never reaches native on iOS. | |
| 20 | //! The Swift dispatcher reads nothing out of `body` either (`:554-563`). | |
| 21 | //! `data` is therefore accepted and ignored, on the | |
| 22 | //! `bridge_mobile_location.getCurrentPosition` precedent: parsing it would | |
| 23 | //! invent a failure mode the shim does not have. There is no field here to | |
| 24 | //! drop. | |
| 25 | //! | |
| 26 | //! ## What goes back | |
| 27 | //! | |
| 28 | //! **Success is a five-key object**, `CraftApp.swift:2647-2654`: | |
| 29 | //! | |
| 30 | //! ```json | |
| 31 | //! {"base64":"…","uri":"data:image/jpeg;base64,…","width":3024,"height":4032,"mimeType":"image/jpeg"} | |
| 32 | //! ``` | |
| 33 | //! | |
| 34 | //! `base64` is the raw encoding and `uri` is the same bytes again behind a | |
| 35 | //! `data:` prefix. The duplication is the contract — `normalizePhoto` | |
| 36 | //! (`:2417`) passes an object straight through onto `PhotoResult` | |
| 37 | //! (`mobile.ts:533-544`), which names all five keys — so it is reproduced | |
| 38 | //! rather than tidied. `mimeType` is the literal `"image/jpeg"` for both | |
| 39 | //! actions always, because the image is re-encoded to JPEG whatever the user | |
| 40 | //! picked. `width`/`height` are `-[UIImage size]` in **points**, and | |
| 41 | //! `JSONSerialization` renders an integral double with no fraction, which is | |
| 42 | //! what `{d}` does too. | |
| 43 | //! | |
| 44 | //! `test-bridges.html:513` reads the result as a string (`image?.length`) and | |
| 45 | //! has therefore printed `Base64 length: 0` against Swift for as long as this | |
| 46 | //! dictionary has existed. That is a pre-existing bug in the test page, not a | |
| 47 | //! reason to reply with a bare string: a string would break `craft.camera.*` | |
| 48 | //! and the SDK, which are written for the object. | |
| 49 | //! | |
| 50 | //! **Cancel is a rejection**, not a resolve and not a distinct result | |
| 51 | //! (`:2661-2665` — `rejectCallback(pendingCallbackId, error: "Cancelled")`). | |
| 52 | //! It has to be: `craft-bridge.js:70` resolves with `payload || {}`, so a | |
| 53 | //! `null` or `false` result would arrive at the page as `{}` and the app's | |
| 54 | //! `catch` would never run. | |
| 55 | //! | |
| 56 | //! ## The one thing this module cannot say | |
| 57 | //! | |
| 58 | //! Swift's cancel carries `code: "CRAFT_ERROR"` and `message: "Cancelled"`. | |
| 59 | //! `ios_async.deliverError` hardcodes `bridge_error.BridgeError.NativeCallFailed` | |
| 60 | //! (`ios_async.zig:258-265`), so the rejection the page receives here says | |
| 61 | //! `NATIVE_CALL_FAILED` / `"Native API call failed"`. The promise still | |
| 62 | //! rejects and the app's `catch` still runs — that half of the contract is | |
| 63 | //! kept — but the stated cause is wrong, and this comment is the only place | |
| 64 | //! that is allowed to say otherwise. | |
| 65 | //! | |
| 66 | //! Calling `bridge_error.sendErrorToJS` from the delegate callback instead is | |
| 67 | //! not an option: it ends in `evaluateJavaScript`, and by then the request id | |
| 68 | //! is gone anyway. The fix is a foundation change — | |
| 69 | //! `ios_async.deliverErrorCode(ticket, err)`, one extra field on `Slot` set | |
| 70 | //! under the same lock — and the document and contact pickers need the | |
| 71 | //! identical thing (`documentPickerWasCancelled` `:4912`, | |
| 72 | //! `contactPickerDidCancel` `:5102` both say `"Cancelled"`). It is recorded | |
| 73 | //! here rather than worked around. | |
| 74 | //! | |
| 75 | //! ## The config gate, and exactly what it stands in for | |
| 76 | //! | |
| 77 | //! Swift wraps both actions in `if config.enableCamera`, which defaults to | |
| 78 | //! **false** (`CraftApp.swift:192`, `packages/ios/src/index.ts:120`). When it | |
| 79 | //! is false the `case` falls off the end and replies *nothing at all*, while | |
| 80 | //! `CraftSwiftShim.handleAction` still returns `true` (`:5247`) so Zig | |
| 81 | //! believes the hand-off succeeded. The injected promise is the hand-built | |
| 82 | //! kind with no timeout. **In a default-config app, `openCamera` and | |
| 83 | //! `pickImage` hang the page forever today.** The "working Swift shim" is | |
| 84 | //! only working for an app that set `enableCamera: true`. | |
| 85 | //! | |
| 86 | //! `enableCamera` has no Zig-reachable channel, so this module gates on the | |
| 87 | //! Info.plist keys `packages/ios/src/index.ts:185-186` writes: | |
| 88 | //! | |
| 89 | //! - **`NSCameraUsageDescription` is an extra gate on `openCamera` only, and | |
| 90 | //! it is a crash guard rather than a config proxy.** Presenting a `.camera` picker in a | |
| 91 | //! process without that key is a TCC termination, not an error anything | |
| 92 | //! could be told about. It is written for | |
| 93 | //! `enableCamera || enableVideoRecording || enableQRScanner || enableAR`. | |
| 94 | //! - **`NSPhotoLibraryUsageDescription` stands in for `config.enableCamera`, | |
| 95 | //! and it is over-broad by `enableVideoRecording`** — it is written for | |
| 96 | //! `enableCamera || enableVideoRecording`, which is the closest proxy | |
| 97 | //! available. It is emphatically **not** a photo-library permission gate: | |
| 98 | //! `UIImagePickerController` with `.photoLibrary` has run out-of-process | |
| 99 | //! since iOS 11 and neither prompts nor requires the key. Refusing on it is | |
| 100 | //! a statement about how the app was configured, never about what the | |
| 101 | //! system would allow. | |
| 102 | //! | |
| 103 | //! So `openCamera` requires *both* keys and `pickImage` requires only the | |
| 104 | //! photo-library one. | |
| 105 | //! | |
| 106 | //! Measured against the shim, that trades three ways. An `enableCamera: true` | |
| 107 | //! app behaves exactly as it does now. A default-config app gets an explicit | |
| 108 | //! `PERMISSION_DENIED` instead of a promise that never settles — strictly | |
| 109 | //! better. And exactly one configuration, `enableVideoRecording: true` with | |
| 110 | //! `enableCamera: false`, gains a capability Swift denies it; that one is a | |
| 111 | //! real widening, it runs in the direction the Info.plist already sanctions | |
| 112 | //! (the usage strings exist, so the user sees a prompt the app declared), and | |
| 113 | //! the cell it widens is otherwise an infinite hang. The alternative was to | |
| 114 | //! leave both actions out of `A` entirely and keep the hang, which is a trade | |
| 115 | //! rather than a free choice. | |
| 116 | //! | |
| 117 | //! `.unavailable` was never on the table: a declared-`.unavailable` action | |
| 118 | //! dispatches and refuses, which would take the working `enableCamera: true` | |
| 119 | //! path away from the shim. `bridge_mobile_misc.zig`'s "Why unserved rather | |
| 120 | //! than `.unavailable`" is the precedent. | |
| 121 | //! | |
| 122 | //! ## Simulator | |
| 123 | //! | |
| 124 | //! `+[UIImagePickerController isSourceTypeAvailable:]` answers `NO` for | |
| 125 | //! `.camera` on every simulator. Presenting anyway shows nothing and the | |
| 126 | //! delegate never fires — a promise that hangs, the single worst outcome — so | |
| 127 | //! `openCamera` asks first and refuses synchronously, before any slot is | |
| 128 | //! leased, exactly as Swift does at `:2616-2619`. `pickImage` has no such | |
| 129 | //! guard in Swift and gets none here: `.photoLibrary` is available on | |
| 130 | //! simulator and device alike, and an empty library still presents a picker | |
| 131 | //! whose only move is Cancel. | |
| 132 | //! | |
| 133 | //! ## One picker, one caller | |
| 134 | //! | |
| 135 | //! A modal serves exactly one call, so there is one `pending` for the module | |
| 136 | //! rather than one per action — both actions present the same kind of sheet | |
| 137 | //! and only one can be up. A second request while one is presented is refused | |
| 138 | //! **for the second caller**, with the first left alone. That is the opposite | |
| 139 | //! of `bridge_mobile_location.getCurrentPosition`, which rejects the | |
| 140 | //! *displaced first* call: there `requestLocation` genuinely cancels the | |
| 141 | //! earlier request so it can never be answered, while here the first picker is | |
| 142 | //! still on screen and will answer. Replacing it would strand its promise | |
| 143 | //! forever. | |
| 144 | //! | |
| 145 | //! The cost of refusing rather than displacing is that a `pending` which is | |
| 146 | //! never taken refuses every later call for the life of the process. Three | |
| 147 | //! callbacks can take it — the pick, the cancel, and | |
| 148 | //! `presentationControllerDidDismiss:` for the swipe-down that has been widely | |
| 149 | //! reported not to fire `imagePickerControllerDidCancel:` since iOS 13. That | |
| 150 | //! third one is a belt, not a proof: if a presentation controller cannot be | |
| 151 | //! reached the module says so in the log and does **not** claim that a cancel | |
| 152 | //! is always delivered. | |
| 153 | //! | |
| 154 | //! ## A Swift bug this deliberately does not inherit | |
| 155 | //! | |
| 156 | //! `startVideoRecording` (`:3731-3749`) reuses the *same* `Coordinator` | |
| 157 | //! delegate and the *same* `pendingCallbackId`, sets `mediaTypes` to | |
| 158 | //! `["public.movie"]`, and then `didFinishPickingMediaWithInfo` reads | |
| 159 | //! `info[.originalImage]` — nil for a movie — so every finished recording | |
| 160 | //! rejects with `"Failed to process image"`. It stays with the shim; because | |
| 161 | //! this module has its own delegate class and its own instance, the crosstalk | |
| 162 | //! disappears rather than getting worse. | |
| 163 | ||
| 164 | const std = @import("std"); | |
| 165 | const builtin = @import("builtin"); | |
| 166 | const capabilities = @import("capabilities.zig"); | |
| 167 | const bridge_error = @import("bridge_error.zig"); | |
| 168 | const objc_runtime = @import("objc_runtime.zig"); | |
| 169 | const ios_async = @import("ios_async.zig"); | |
| 170 | const ios_delegate = @import("ios_delegate.zig"); | |
| 171 | const bridge_mobile_system = @import("bridge_mobile_system.zig"); | |
| 172 | const compat_mutex = @import("compat_mutex.zig"); | |
| 173 | ||
| 174 | const objc = objc_runtime.objc; | |
| 175 | const is_darwin = builtin.target.os.tag.isDarwin(); | |
| 176 | ||
| 177 | /// The same type as `objc.id` — `?*anyopaque` — spelled locally, per the | |
| 178 | /// location/motion precedent: `objc_runtime.objc` is an empty struct off | |
| 179 | /// Darwin and a `callconv(.c)` fn-pointer *type* is analysed even when a | |
| 180 | /// comptime platform guard prunes the body around it. A single optional | |
| 181 | /// pointer, never `?objc.id`: a double optional is illegal in `callconv(.c)`. | |
| 182 | const Id = ?*anyopaque; | |
| 183 | ||
| 184 | /// The action names, spelled exactly as the Swift `case` labels spell them. | |
| 185 | /// `test/ios_conformance_test.zig` matches this block against those labels in | |
| 186 | /// both directions and fails the build if two modules declare one name. | |
| 187 | pub const A = struct { | |
| 188 | pub const open_camera = "openCamera"; | |
| 189 | pub const pick_image = "pickImage"; | |
| 190 | }; | |
| 191 | ||
| 192 | /// `.result`: each Swift path terminates in one `resolveCallback` (the pick) | |
| 193 | /// or one `rejectCallback` (the cancel, or an image that would not encode), | |
| 194 | /// and the page's promise is the hand-built kind with no timeout — `.none` | |
| 195 | /// here would park a caller forever rather than for thirty seconds. | |
| 196 | /// | |
| 197 | /// `.live`: it dispatches and presents. A refusal is a specific failure — the | |
| 198 | /// app was not built with the camera enabled, no camera on this device, the | |
| 199 | /// picker is already up — never the action's normal answer, which is what | |
| 200 | /// `.unavailable` would declare. | |
| 201 | pub const capability_actions = [_]capabilities.ActionDecl{ | |
| 202 | .{ .name = A.open_camera, .reply = .result }, | |
| 203 | .{ .name = A.pick_image, .reply = .result }, | |
| 204 | }; | |
| 205 | ||
| 206 | /// Which picker an action selects — and, because the values are chosen to be, | |
| 207 | /// the `UIImagePickerControllerSourceType` to set. | |
| 208 | /// | |
| 209 | /// `NSInteger`, hence `c_long`: a narrower type passes 0 and 1 correctly by | |
| 210 | /// luck and breaks the day the enum grows. | |
| 211 | /// `UIImagePickerControllerSourceTypeSavedPhotosAlbum = 2` is deliberately | |
| 212 | /// absent — no action posts it. | |
| 213 | const Source = enum(c_long) { | |
| 214 | photo_library = 0, | |
| 215 | camera = 1, | |
| 216 | ||
| 217 | fn actionName(self: Source) []const u8 { | |
| 218 | return switch (self) { | |
| 219 | .camera => A.open_camera, | |
| 220 | .photo_library => A.pick_image, | |
| 221 | }; | |
| 222 | } | |
| 223 | }; | |
| 224 | ||
| 225 | /// Which picker an action selects, split out from `handleMessage` so the | |
| 226 | /// table-versus-dispatch agreement is assertable on a host that has no UIKit. | |
| 227 | fn routeFor(action: []const u8) ?Source { | |
| 228 | if (std.mem.eql(u8, action, A.open_camera)) return .camera; | |
| 229 | if (std.mem.eql(u8, action, A.pick_image)) return .photo_library; | |
| 230 | return null; | |
| 231 | } | |
| 232 | ||
| 233 | /// `image.jpegData(compressionQuality: 0.8)` — Swift's spelling, `:2646`. | |
| 234 | /// Always JPEG, always this quality, for both actions. | |
| 235 | const jpeg_compression_quality: f64 = 0.8; | |
| 236 | ||
| 237 | pub const ImagePickerBridge = struct { | |
| 238 | allocator: std.mem.Allocator, | |
| 239 | ||
| 240 | const Self = @This(); | |
| 241 | ||
| 242 | pub fn init(allocator: std.mem.Allocator) Self { | |
| 243 | return .{ .allocator = allocator }; | |
| 244 | } | |
| 245 | ||
| 246 | pub fn deinit(_: *Self) void {} | |
| 247 | ||
| 248 | pub fn handleMessage(self: *Self, action: []const u8, data: []const u8) !void { | |
| 249 | const source = routeFor(action) orelse return bridge_error.BridgeError.UnknownAction; | |
| 250 | return self.present(source, data); | |
| 251 | } | |
| 252 | ||
| 253 | /// Configure a `UIImagePickerController` for `source`, present it, and let | |
| 254 | /// the delegate answer when the user is done. | |
| 255 | /// | |
| 256 | /// `data` is accepted and ignored — see the module comment; neither JS | |
| 257 | /// surface sends a field and the Swift dispatcher reads none. | |
| 258 | /// | |
| 259 | /// Every fallible step runs *before* `ios_async.acquire`: the config gate, | |
| 260 | /// the class, the camera-availability question, all five delegate | |
| 261 | /// selectors, both `dlsym`s, the delegate class and instance, the | |
| 262 | /// presenter, the picker itself and every selector used to present it. | |
| 263 | /// `bridge_mobile_location.zig` states the rule this follows: no error path | |
| 264 | /// may exist between leasing a slot and handing the request to the | |
| 265 | /// framework, because a missed `abandon` permanently narrows the pool. The | |
| 266 | /// one exception below — `publish` answering `.busy` — releases the lease | |
| 267 | /// by hand on the way out, and is the only path that has to. | |
| 268 | fn present(self: *Self, source: Source, data: []const u8) !void { | |
| 269 | _ = self; | |
| 270 | _ = data; | |
| 271 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 272 | ||
| 273 | const action = source.actionName(); | |
| 274 | ||
| 275 | // The config gate first. It is the only refusal that touches no UIKit | |
| 276 | // at all, and on a host build it is what keeps everything below from | |
| 277 | // running against a runtime that has no picker in it. | |
| 278 | try requireConfigured(source); | |
| 279 | ||
| 280 | // A cheap refusal before any of the expensive work: a modal is on | |
| 281 | // screen, so nothing built here could be presented anyway. `publish` | |
| 282 | // below is the authoritative one — it decides under the lock, so a | |
| 283 | // request that slipped past this read still cannot displace the first. | |
| 284 | if (busyWith()) |holder| return busyRefusal(action, holder); | |
| 285 | ||
| 286 | const PickerClass = objc.objc_getClass("UIImagePickerController") orelse { | |
| 287 | std.log.warn( | |
| 288 | "{s} refused: this process has no UIImagePickerController class, " ++ | |
| 289 | "so UIKit is not loaded here", | |
| 290 | .{action}, | |
| 291 | ); | |
| 292 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 293 | }; | |
| 294 | ||
| 295 | // Swift's `guard UIImagePickerController.isSourceTypeAvailable(.camera)`. | |
| 296 | // Asked, never assumed: on a simulator the answer is NO, and presenting | |
| 297 | // anyway shows nothing and never calls the delegate back. | |
| 298 | if (source == .camera) { | |
| 299 | const sel_available = try selector("isSourceTypeAvailable:"); | |
| 300 | const AvailableFn = *const fn (Id, Id, c_long) callconv(.c) bool; | |
| 301 | const available: AvailableFn = @ptrCast(&objc.objc_msgSend); | |
| 302 | if (!available(PickerClass, sel_available, @backingInt(Source.camera))) { | |
| 303 | std.log.warn( | |
| 304 | "openCamera refused: no camera source is available on this device " ++ | |
| 305 | "(every simulator answers NO)", | |
| 306 | .{}, | |
| 307 | ); | |
| 308 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 309 | } | |
| 310 | } | |
| 311 | ||
| 312 | // Everything the delegate will need to shape a reply, resolved while an | |
| 313 | // error is still deliverable to the caller. | |
| 314 | const work = try Work.resolve(); | |
| 315 | ||
| 316 | const delegate = try ensureDelegate(); | |
| 317 | const presenter = try bridge_mobile_system.uikit.topmostViewController(); | |
| 318 | ||
| 319 | const sel_set_source = try selector("setSourceType:"); | |
| 320 | const sel_set_delegate = try selector("setDelegate:"); | |
| 321 | const sel_present = try selector("presentViewController:animated:completion:"); | |
| 322 | ||
| 323 | const picker = (try objc.allocInit(PickerClass)) orelse return error.NativeCallFailed; | |
| 324 | // +1 from alloc/init. The presenting controller retains the picker for | |
| 325 | // the life of the presentation, so this reference is ours to drop — | |
| 326 | // and on every error path below it is the only one there is. Same | |
| 327 | // shape as `bridge_mobile_system.share`. | |
| 328 | defer objc.release(picker); | |
| 329 | ||
| 330 | const SetSourceFn = *const fn (Id, Id, c_long) callconv(.c) void; | |
| 331 | const set_source: SetSourceFn = @ptrCast(&objc.objc_msgSend); | |
| 332 | set_source(picker, sel_set_source, @backingInt(source)); | |
| 333 | ||
| 334 | // `mediaTypes` and `allowsEditing` are deliberately left alone: Swift | |
| 335 | // sets neither, so the defaults (`["public.image"]` and `NO`) are the | |
| 336 | // contract, and `.originalImage` is the right info key precisely | |
| 337 | // because editing is off. | |
| 338 | objc.msgSendVoid1(picker, sel_set_delegate, delegate); | |
| 339 | ||
| 340 | // If UIKit adapts this presentation to a popover — which it can on a | |
| 341 | // regular size class, i.e. any iPad and iPhone in some multitasking | |
| 342 | // configurations — it raises `NSGenericException` when neither | |
| 343 | // `sourceView` nor `barButtonItem` is set, and an Objective-C exception | |
| 344 | // is an uncatchable crash from Zig. `anchorPopover` reads | |
| 345 | // `popoverPresentationController` and returns immediately when it is | |
| 346 | // nil, which Apple documents it to be unless the modal presentation | |
| 347 | // style is `.popover`. So this either anchors a popover correctly or | |
| 348 | // does nothing at all; which of the two happens is UIKit's decision and | |
| 349 | // is not predicted here. | |
| 350 | try bridge_mobile_system.uikit.anchorPopover(picker, presenter); | |
| 351 | ||
| 352 | var dismiss_observed = attachDismissObserver(picker, delegate, sel_set_delegate); | |
| 353 | ||
| 354 | const PresentFn = *const fn (Id, Id, Id, bool, Id) callconv(.c) void; | |
| 355 | const present_fn: PresentFn = @ptrCast(&objc.objc_msgSend); | |
| 356 | ||
| 357 | const ticket = ios_async.acquire(action) orelse return poolFull(action); | |
| 358 | ||
| 359 | // Published before the framework call, never after: presentation is | |
| 360 | // asynchronous but a delegate callback that reached an empty slot would | |
| 361 | // have no ticket to answer with. | |
| 362 | switch (publish(.{ .ticket = ticket, .source = source, .work = work })) { | |
| 363 | .published => {}, | |
| 364 | .busy => |holder| { | |
| 365 | // Lost a race with another dispatch. The lease is released by | |
| 366 | // hand here because this is the one error path that exists | |
| 367 | // after `acquire`; leaving it would narrow the pool forever. | |
| 368 | ios_async.abandon(ticket); | |
| 369 | return busyRefusal(action, holder); | |
| 370 | }, | |
| 371 | } | |
| 372 | ||
| 373 | present_fn(presenter, sel_present, picker, true, null); | |
| 374 | ||
| 375 | // A presentation controller may only exist once the presentation has | |
| 376 | // begun. Retried here rather than claimed above, because the interactive | |
| 377 | // -dismissal callback is the only thing that can free `pending` when a | |
| 378 | // sheet is swiped away and `imagePickerControllerDidCancel:` does not | |
| 379 | // fire. | |
| 380 | if (!dismiss_observed) dismiss_observed = attachDismissObserver(picker, delegate, sel_set_delegate); | |
| 381 | if (!dismiss_observed) { | |
| 382 | std.log.info( | |
| 383 | "{s}: no presentation controller to observe; a swipe-down dismissal " ++ | |
| 384 | "may leave this call unanswered", | |
| 385 | .{action}, | |
| 386 | ); | |
| 387 | } | |
| 388 | } | |
| 389 | }; | |
| 390 | ||
| 391 | /// The answer for a full slot pool, copied from `bridge_mobile_location`: | |
| 392 | /// `BridgeError` has no "Busy", `INVALID_PARAMETER` is the migration notes' | |
| 393 | /// designated stand-in, and the point is that the caller gets an explicit | |
| 394 | /// rejection instead of a promise that never settles. | |
| 395 | fn poolFull(action: []const u8) bridge_error.BridgeError { | |
| 396 | std.log.warn( | |
| 397 | "{s} refused: all {d} async slots in flight", | |
| 398 | .{ action, ios_async.max_in_flight }, | |
| 399 | ); | |
| 400 | return bridge_error.BridgeError.InvalidParameter; | |
| 401 | } | |
| 402 | ||
| 403 | /// The answer for a second request while a picker is already on screen. | |
| 404 | /// | |
| 405 | /// The *second* caller is refused and the first is left alone, because the | |
| 406 | /// first picker is still up and will answer. Same `INVALID_PARAMETER` | |
| 407 | /// stand-in, for the same reason: `BridgeError` cannot say "busy", and silence | |
| 408 | /// is not an option. | |
| 409 | fn busyRefusal(action: []const u8, holder: Source) bridge_error.BridgeError { | |
| 410 | std.log.warn( | |
| 411 | "{s} refused: {s} already has a picker presented; refusing the second call rather " ++ | |
| 412 | "than replacing the first, whose promise would then never settle", | |
| 413 | .{ action, holder.actionName() }, | |
| 414 | ); | |
| 415 | return bridge_error.BridgeError.InvalidParameter; | |
| 416 | } | |
| 417 | ||
| 418 | // ============================================================================= | |
| 419 | // Reply shaping. Pure — no Objective-C — so the exact bytes the page receives | |
| 420 | // are pinned by host tests on every platform. | |
| 421 | // ============================================================================= | |
| 422 | ||
| 423 | /// One picked image, read into plain values. | |
| 424 | /// | |
| 425 | /// `base64` is the raw encoding, owned by whoever built it. `width`/`height` | |
| 426 | /// are `-[UIImage size]` in points, which is what Swift puts on the wire. | |
| 427 | const Photo = struct { | |
| 428 | base64: []const u8, | |
| 429 | width: f64, | |
| 430 | height: f64, | |
| 431 | }; | |
| 432 | ||
| 433 | /// The five-key object Swift's `didFinishPickingMediaWithInfo` resolves. | |
| 434 | /// | |
| 435 | /// Key order is fixed at base64, uri, width, height, mimeType. Swift's is a | |
| 436 | /// `Dictionary` and therefore arbitrary; a caller cannot depend on it, but a | |
| 437 | /// test can only pin bytes that are deterministic, so one order is chosen and | |
| 438 | /// held. | |
| 439 | /// | |
| 440 | /// The encoded payload is appended **twice** — once raw, once behind the | |
| 441 | /// `data:` prefix — because that is what `PhotoResult` is written for. It is | |
| 442 | /// the single largest cost in this path and it is not this module's to change. | |
| 443 | fn shapePhoto(allocator: std.mem.Allocator, photo: Photo) ![]u8 { | |
| 444 | var out: std.ArrayListUnmanaged(u8) = .empty; | |
| 445 | errdefer out.deinit(allocator); | |
| 446 | ||
| 447 | // Not escaped, and that is checked rather than asserted: the standard | |
| 448 | // base64 alphabet plus its pad character contains no byte JSON must | |
| 449 | // escape. See "the encoded payload needs no JSON escaping" below, which | |
| 450 | // fails if the encoder is ever swapped for one whose alphabet does. | |
| 451 | try out.appendSlice(allocator, "{\"base64\":\""); | |
| 452 | try out.appendSlice(allocator, photo.base64); | |
| 453 | try out.appendSlice(allocator, "\",\"uri\":\""); | |
| 454 | try out.appendSlice(allocator, data_uri_prefix); | |
| 455 | try out.appendSlice(allocator, photo.base64); | |
| 456 | try out.appendSlice(allocator, "\",\"width\":"); | |
| 457 | try appendNumber(allocator, &out, photo.width); | |
| 458 | try out.appendSlice(allocator, ",\"height\":"); | |
| 459 | try appendNumber(allocator, &out, photo.height); | |
| 460 | try out.appendSlice(allocator, ",\"mimeType\":\""); | |
| 461 | try out.appendSlice(allocator, mime_type); | |
| 462 | try out.appendSlice(allocator, "\"}"); | |
| 463 | ||
| 464 | return out.toOwnedSlice(allocator); | |
| 465 | } | |
| 466 | ||
| 467 | /// Swift's `"data:image/jpeg;base64," + base64`. | |
| 468 | const data_uri_prefix = "data:image/jpeg;base64,"; | |
| 469 | ||
| 470 | /// The literal Swift sends for both actions, always — the image is re-encoded | |
| 471 | /// to JPEG, so a PNG or HEIC chosen from the library still arrives as this. | |
| 472 | const mime_type = "image/jpeg"; | |
| 473 | ||
| 474 | /// One `f64` as a JSON number. | |
| 475 | /// | |
| 476 | /// `{d}` renders decimal notation, never scientific, and prints an integral | |
| 477 | /// value with no fraction — `3024`, matching what `JSONSerialization` writes | |
| 478 | /// for the same `CGFloat`. A finite `f64` can need up to | |
| 479 | /// `std.fmt.float.bufferSize(.decimal, f64)` (347) bytes, so the buffer is | |
| 480 | /// sized from the formatter rather than guessed. | |
| 481 | /// | |
| 482 | /// Non-finite is refused rather than printed: `inf` and `nan` are not JSON, | |
| 483 | /// and `JSONSerialization` refuses them too. A refusal reaches the page as a | |
| 484 | /// rejection; printing them would produce a syntax error inside the reply | |
| 485 | /// script with nothing to point at. | |
| 486 | fn appendNumber( | |
| 487 | allocator: std.mem.Allocator, | |
| 488 | out: *std.ArrayListUnmanaged(u8), | |
| 489 | value: f64, | |
| 490 | ) !void { | |
| 491 | if (!std.math.isFinite(value)) return bridge_error.BridgeError.InvalidParameter; | |
| 492 | var buf: [std.fmt.float.bufferSize(.decimal, f64)]u8 = undefined; | |
| 493 | try out.appendSlice(allocator, try std.fmt.bufPrint(&buf, "{d}", .{value})); | |
| 494 | } | |
| 495 | ||
| 496 | /// What a delegate callback decided to send. | |
| 497 | /// | |
| 498 | /// Deciding and sending are separate so the decision is checkable without a | |
| 499 | /// picker: getting `.reject` and `.photo` the wrong way round is the difference | |
| 500 | /// between an app's `catch` running and its `then` running on an image that | |
| 501 | /// does not exist. | |
| 502 | const Answer = union(enum) { | |
| 503 | /// The five-key object, ready to hand to `ios_async.deliverJson`. | |
| 504 | photo: []const u8, | |
| 505 | /// A rejection. Every failure *and* every cancel takes this arm. | |
| 506 | reject, | |
| 507 | }; | |
| 508 | ||
| 509 | /// The two ways this module answers a captured call, and the only two. | |
| 510 | /// | |
| 511 | /// Neither replies directly — `evaluateJavaScript` is main-thread-only and | |
| 512 | /// these run on a framework callback — so both go through `ios_async`, which | |
| 513 | /// hops to the main queue under the request id captured back at dispatch. | |
| 514 | fn settle(call: Pending, answer: Answer) void { | |
| 515 | switch (answer) { | |
| 516 | .photo => |json| ios_async.deliverJson(call.ticket, json), | |
| 517 | // A Cancel is not a native failure — the call worked and the answer | |
| 518 | // is "no" — so it carries the code that says so. | |
| 519 | .reject => ios_async.deliverErrorCode(call.ticket, bridge_error.BridgeError.Cancelled), | |
| 520 | } | |
| 521 | } | |
| 522 | ||
| 523 | /// Swift's `if let image = …, let imageData = … { resolve } else { reject }`. | |
| 524 | /// A reply that could not be built is a rejection, never an object with an | |
| 525 | /// empty payload and zeroed dimensions — `normalizePhoto` would hand the app | |
| 526 | /// exactly that and its `then` would run. | |
| 527 | fn finishAnswer(json: ?[]const u8) Answer { | |
| 528 | return if (json) |bytes| .{ .photo = bytes } else .reject; | |
| 529 | } | |
| 530 | ||
| 531 | /// A cancel is a **rejection**. Swift is | |
| 532 | /// `rejectCallback(pendingCallbackId, error: "Cancelled")`, and | |
| 533 | /// `craft-bridge.js` resolves with `payload || {}`, so any resolved shape — | |
| 534 | /// `null`, `false`, `{}` — would run the app's `then` branch for a picture the | |
| 535 | /// user declined to take. | |
| 536 | const cancel_answer: Answer = .reject; | |
| 537 | ||
| 538 | // ============================================================================= | |
| 539 | // The config gate. See the module comment for what each key does and does not | |
| 540 | // stand for. | |
| 541 | // ============================================================================= | |
| 542 | ||
| 543 | /// Written by `packages/ios/src/index.ts:185` for | |
| 544 | /// `enableCamera || enableVideoRecording || enableQRScanner || enableAR`. | |
| 545 | /// Required before a `.camera` picker may be presented at all. | |
| 546 | const key_camera_usage = "NSCameraUsageDescription"; | |
| 547 | ||
| 548 | /// Written by `packages/ios/src/index.ts:186` for | |
| 549 | /// `enableCamera || enableVideoRecording`. Used here as the closest available | |
| 550 | /// proxy for `config.enableCamera` — **not** as a permission gate; a | |
| 551 | /// `.photoLibrary` picker needs no such key on iOS 11+. | |
| 552 | const key_photo_library_usage = "NSPhotoLibraryUsageDescription"; | |
| 553 | ||
| 554 | fn requireConfigured(source: Source) !void { | |
| 555 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 556 | ||
| 557 | // Checked first, and only for the camera: this one is a crash guard, not a | |
| 558 | // configuration question. Presenting a `.camera` picker in a process | |
| 559 | // without the key is a TCC termination — there is no error to map and | |
| 560 | // nothing left to tell the page. | |
| 561 | if (source == .camera and !try infoPlistHas(key_camera_usage)) { | |
| 562 | std.log.warn( | |
| 563 | "openCamera refused: Info.plist has no {s}, and presenting a camera picker " ++ | |
| 564 | "without it terminates the process rather than failing", | |
| 565 | .{key_camera_usage}, | |
| 566 | ); | |
| 567 | return bridge_error.BridgeError.PermissionDenied; | |
| 568 | } | |
| 569 | ||
| 570 | if (!try infoPlistHas(key_photo_library_usage)) { | |
| 571 | std.log.warn( | |
| 572 | "{s} refused: Info.plist has no {s}, the closest available proxy for " ++ | |
| 573 | "config.enableCamera, so this app was not built with the camera enabled", | |
| 574 | .{ source.actionName(), key_photo_library_usage }, | |
| 575 | ); | |
| 576 | return bridge_error.BridgeError.PermissionDenied; | |
| 577 | } | |
| 578 | } | |
| 579 | ||
| 580 | /// Whether the main bundle's Info.plist carries `key`. | |
| 581 | /// | |
| 582 | /// Errors rather than answering `false` when the runtime itself will not | |
| 583 | /// cooperate: "there is no NSBundle class" and "this app did not enable the | |
| 584 | /// camera" are different facts, and collapsing them would blame the app's | |
| 585 | /// configuration for a broken process. Every runtime result is guarded. | |
| 586 | fn infoPlistHas(comptime key: [*:0]const u8) !bool { | |
| 587 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 588 | ||
| 589 | const NSBundle = objc.objc_getClass("NSBundle") orelse return error.ClassNotFound; | |
| 590 | const sel_main = objc.sel_registerName("mainBundle") orelse return error.SelectorNotFound; | |
| 591 | const bundle = objc.msgSendId(NSBundle, sel_main) orelse return error.NoMainBundle; | |
| 592 | ||
| 593 | const NSString = objc.objc_getClass("NSString") orelse return error.ClassNotFound; | |
| 594 | const sel_string = objc.sel_registerName("stringWithUTF8String:") orelse | |
| 595 | return error.SelectorNotFound; | |
| 596 | const ns_key = objc.msgSendId1(NSString, sel_string, key) orelse return error.NativeCallFailed; | |
| 597 | ||
| 598 | const sel_lookup = objc.sel_registerName("objectForInfoDictionaryKey:") orelse | |
| 599 | return error.SelectorNotFound; | |
| 600 | return objc.msgSendId1(bundle, sel_lookup, ns_key) != null; | |
| 601 | } | |
| 602 | ||
| 603 | // ============================================================================= | |
| 604 | // Everything the delegate needs, resolved while an error is still deliverable. | |
| 605 | // ============================================================================= | |
| 606 | ||
| 607 | fn selector(name: [*:0]const u8) !Id { | |
| 608 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 609 | return objc.sel_registerName(name) orelse error.SelectorNotFound; | |
| 610 | } | |
| 611 | ||
| 612 | /// The five selectors a delegate callback sends. | |
| 613 | /// | |
| 614 | /// Resolved at dispatch for the reason `bridge_mobile_location.Sels` states: a | |
| 615 | /// `sel_registerName` failure inside a callback could only be logged, or worse | |
| 616 | /// turned into a rejection for a picture the user actually took. | |
| 617 | const Sels = struct { | |
| 618 | object_for_key: Id, | |
| 619 | size: Id, | |
| 620 | bytes: Id, | |
| 621 | length: Id, | |
| 622 | /// `-[UIViewController dismissViewControllerAnimated:completion:]`, sent to | |
| 623 | /// the picker; UIKit forwards it to the presenter. Both Swift callbacks | |
| 624 | /// call it, and missing either one leaves the app behind a modal forever. | |
| 625 | dismiss: Id, | |
| 626 | ||
| 627 | fn resolve() !Sels { | |
| 628 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 629 | return .{ | |
| 630 | .object_for_key = try selector("objectForKey:"), | |
| 631 | .size = try selector("size"), | |
| 632 | .bytes = try selector("bytes"), | |
| 633 | .length = try selector("length"), | |
| 634 | .dismiss = try selector("dismissViewControllerAnimated:completion:"), | |
| 635 | }; | |
| 636 | } | |
| 637 | }; | |
| 638 | ||
| 639 | /// `NSData *UIImageJPEGRepresentation(UIImage *, CGFloat)`. | |
| 640 | /// | |
| 641 | /// `CGFloat` is `double` on every 64-bit Apple platform. This is a plain C | |
| 642 | /// function with no Objective-C equivalent — `-jpegData(compressionQuality:)` | |
| 643 | /// is Swift-only sugar over it. | |
| 644 | const JpegFn = *const fn (Id, f64) callconv(.c) Id; | |
| 645 | ||
| 646 | /// Everything a delegate callback needs, captured for the call it will answer. | |
| 647 | const Work = struct { | |
| 648 | sels: Sels, | |
| 649 | /// The value of `UIImagePickerControllerOriginalImage`, the info key Swift | |
| 650 | /// reads. Resolved before presenting, so a UIKit that does not carry it is | |
| 651 | /// a synchronous refusal rather than a picker nobody can read the result of. | |
| 652 | original_image_key: Id, | |
| 653 | jpeg: JpegFn, | |
| 654 | ||
| 655 | fn resolve() !Work { | |
| 656 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 657 | ||
| 658 | // `dlsym` rather than `extern "c"`: the host test binaries link | |
| 659 | // Cocoa/WebKit/CoreGraphics and not UIKit, and `refAllDecls` forces | |
| 660 | // analysis of every declaration, so an `extern "c" fn | |
| 661 | // UIImageJPEGRepresentation` would be an undefined symbol at host link | |
| 662 | // time. The same route `bridge_mobile_location.bestAccuracy` takes for | |
| 663 | // `kCLLocationAccuracyBest`. | |
| 664 | const jpeg_symbol = dlsym(RTLD_DEFAULT, "UIImageJPEGRepresentation") orelse { | |
| 665 | std.log.warn( | |
| 666 | "image picker refused: UIImageJPEGRepresentation is not in this process, " ++ | |
| 667 | "so a picked image could not be encoded", | |
| 668 | .{}, | |
| 669 | ); | |
| 670 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 671 | }; | |
| 672 | ||
| 673 | // `UIImagePickerControllerOriginalImage` is an `extern NSString * const` | |
| 674 | // in UIKit. Read through the symbol rather than rebuilt from its own | |
| 675 | // spelling: the constant's *value* happening to equal its name is | |
| 676 | // undocumented, and a null answer here is the honest "UIKit is not | |
| 677 | // here" rather than a plausible-looking string that matches nothing. | |
| 678 | const key_symbol = dlsym(RTLD_DEFAULT, "UIImagePickerControllerOriginalImage") orelse { | |
| 679 | std.log.warn( | |
| 680 | "image picker refused: UIImagePickerControllerOriginalImage is not in this " ++ | |
| 681 | "process, so a pick could not be read", | |
| 682 | .{}, | |
| 683 | ); | |
| 684 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 685 | }; | |
| 686 | const key_cell: *const Id = @ptrCast(@alignCast(key_symbol)); | |
| 687 | const original_image_key = key_cell.* orelse return error.NativeCallFailed; | |
| 688 | ||
| 689 | return .{ | |
| 690 | .sels = try Sels.resolve(), | |
| 691 | .original_image_key = original_image_key, | |
| 692 | // `@alignCast` because `dlsym` answers with a `*anyopaque`, whose | |
| 693 | // alignment is 1; a function pointer's is 4. The assertion is sound — | |
| 694 | // this address is a function entry point in a loaded image. | |
| 695 | .jpeg = @ptrCast(@alignCast(jpeg_symbol)), | |
| 696 | }; | |
| 697 | } | |
| 698 | }; | |
| 699 | ||
| 700 | extern "c" fn dlsym(handle: ?*anyopaque, symbol: [*:0]const u8) ?*anyopaque; | |
| 701 | ||
| 702 | /// dyld's "search every image" pseudo-handle, `(void *)-2` on Darwin. | |
| 703 | const RTLD_DEFAULT: ?*anyopaque = @ptrFromInt(@as(usize, @bitCast(@as(isize, -2)))); | |
| 704 | ||
| 705 | // ============================================================================= | |
| 706 | // The delegate class, built at runtime. | |
| 707 | // ============================================================================= | |
| 708 | ||
| 709 | /// Deliberately namespaced, on the `CraftIOSLocationDelegate` precedent: a | |
| 710 | /// generic name risks colliding with a desktop class in the same host test | |
| 711 | /// binary, and both sides look their class up with `objc_getClass` first — so | |
| 712 | /// whichever registered second would silently adopt the other's IMPs. | |
| 713 | const delegate_class_name = "CraftIOSImagePickerDelegate"; | |
| 714 | ||
| 715 | /// The delegate instance, held for the life of the process. | |
| 716 | /// | |
| 717 | /// `UIImagePickerController` holds its `delegate` **weakly**, and | |
| 718 | /// `ios_delegate.instantiate` returns +1 while retaining nothing. This var is | |
| 719 | /// the strong reference; without it the first Cancel is a use-after-free. | |
| 720 | var delegate_instance: Id = null; | |
| 721 | ||
| 722 | /// The method table, so the encodings are assertable on a host. | |
| 723 | /// | |
| 724 | /// A wrong encoding string still registers and still dispatches, then reads | |
| 725 | /// arguments out of the wrong registers with no crash and no compile error — | |
| 726 | /// which is why `ios_delegate.enc` names the shapes rather than spelling them. | |
| 727 | /// | |
| 728 | /// A function rather than a `const`: `@ptrCast` from a function pointer to | |
| 729 | /// `*const anyopaque` is a runtime cast, and a container-level initialiser | |
| 730 | /// would ask the compiler to perform it at comptime. | |
| 731 | /// | |
| 732 | /// The three IMPs are plain `fn … callconv(.c)` rather than `export fn`. What | |
| 733 | /// `class_addMethod` needs is the C calling convention and the `(self, _cmd, …)` | |
| 734 | /// parameter order, both of which a plain function has; an exported symbol | |
| 735 | /// would additionally be visible to the linker, which is how the desktop and | |
| 736 | /// iOS location delegates collided once already. | |
| 737 | fn delegateMethods() [3]ios_delegate.Method { | |
| 738 | return .{ | |
| 739 | // - (void)imagePickerController:(UIImagePickerController *)picker | |
| 740 | // didFinishPickingMediaWithInfo:(NSDictionary *)info | |
| 741 | .{ | |
| 742 | .selector = "imagePickerController:didFinishPickingMediaWithInfo:", | |
| 743 | .imp = @ptrCast(&craftIOSImagePickerDidFinish), | |
| 744 | .types = ios_delegate.enc.void_two_objects, | |
| 745 | }, | |
| 746 | // - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker | |
| 747 | .{ | |
| 748 | .selector = "imagePickerControllerDidCancel:", | |
| 749 | .imp = @ptrCast(&craftIOSImagePickerDidCancel), | |
| 750 | .types = ios_delegate.enc.void_one_object, | |
| 751 | }, | |
| 752 | // - (void)presentationControllerDidDismiss:(UIPresentationController *)pc | |
| 753 | // The swipe-down belt. iOS 13+; on anything older it is simply never sent. | |
| 754 | .{ | |
| 755 | .selector = "presentationControllerDidDismiss:", | |
| 756 | .imp = @ptrCast(&craftIOSImagePickerDidDismiss), | |
| 757 | .types = ios_delegate.enc.void_one_object, | |
| 758 | }, | |
| 759 | }; | |
| 760 | } | |
| 761 | ||
| 762 | /// Register the delegate class once, and keep one instance alive. | |
| 763 | /// | |
| 764 | /// `UIImagePickerControllerDelegate`, `UINavigationControllerDelegate` and | |
| 765 | /// `UIAdaptivePresentationControllerDelegate` are deliberately not declared: | |
| 766 | /// UIKit dispatches through `respondsToSelector:`, so conformance is not | |
| 767 | /// required, and Swift implements none of the navigation-delegate methods it | |
| 768 | /// declares at `:376` either. | |
| 769 | fn ensureDelegate() !Id { | |
| 770 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 771 | if (delegate_instance) |existing| return existing; | |
| 772 | ||
| 773 | const methods = delegateMethods(); | |
| 774 | const cls = try ios_delegate.defineClass(delegate_class_name, "NSObject", &methods); | |
| 775 | const instance = (try ios_delegate.instantiate(cls)) orelse return error.NativeCallFailed; | |
| 776 | delegate_instance = instance; | |
| 777 | return instance; | |
| 778 | } | |
| 779 | ||
| 780 | /// Make the picker's presentation controller report an interactive dismissal | |
| 781 | /// to us. Returns whether it was attached. | |
| 782 | /// | |
| 783 | /// A `.photoLibrary` picker has presented as a sheet since iOS 13, and a | |
| 784 | /// swipe-down is widely reported not to call | |
| 785 | /// `imagePickerControllerDidCancel:`. That report is not verified anywhere in | |
| 786 | /// this repo, so this is a belt and not a fix: it costs two messages, and if | |
| 787 | /// the report is right it is the only thing that frees `pending` after a | |
| 788 | /// swipe. This module refuses later calls while one is pending, so a stranded | |
| 789 | /// ticket is worse here than in Swift — it would disable the picker for the | |
| 790 | /// life of the process. | |
| 791 | /// | |
| 792 | /// Idempotent against the real cancel: whichever callback runs first takes | |
| 793 | /// `pending` under the lock, so the second finds nothing, and `ios_async`'s | |
| 794 | /// generation counter would make a second delivery a no-op anyway. | |
| 795 | fn attachDismissObserver(picker: Id, delegate: Id, sel_set_delegate: Id) bool { | |
| 796 | if (!is_darwin) return false; | |
| 797 | ||
| 798 | const sel_presentation = objc.sel_registerName("presentationController") orelse return false; | |
| 799 | const presentation = objc.msgSendId(picker, sel_presentation) orelse return false; | |
| 800 | objc.msgSendVoid1(presentation, sel_set_delegate, delegate); | |
| 801 | return true; | |
| 802 | } | |
| 803 | ||
| 804 | // ============================================================================= | |
| 805 | // One pending call for the whole module, because one modal serves one caller. | |
| 806 | // ============================================================================= | |
| 807 | ||
| 808 | const Pending = struct { | |
| 809 | ticket: ios_async.Ticket, | |
| 810 | source: Source, | |
| 811 | work: Work, | |
| 812 | }; | |
| 813 | ||
| 814 | var pending: ?Pending = null; | |
| 815 | ||
| 816 | /// Guards `pending`. Held even though UIKit delivers these callbacks on the | |
| 817 | /// main thread, because "it should always be the main thread" is not a guard | |
| 818 | /// and the dispatch side is not provably main-thread for every entry point. | |
| 819 | var state_mutex: compat_mutex.Mutex = .{}; | |
| 820 | ||
| 821 | /// `.busy` carries who is holding the picker, so the refusal can name it. | |
| 822 | const PublishResult = union(enum) { published, busy: Source }; | |
| 823 | ||
| 824 | /// Record the call the delegate will answer, refusing rather than replacing. | |
| 825 | /// | |
| 826 | /// The opposite of `bridge_mobile_location.publishPendingFix`, deliberately: | |
| 827 | /// there the framework cancels the earlier request, so the displaced caller | |
| 828 | /// can never be answered and must be rejected. Here the first picker is still | |
| 829 | /// on screen and will answer, so replacing it would strand a promise that was | |
| 830 | /// about to settle. | |
| 831 | fn publish(call: Pending) PublishResult { | |
| 832 | state_mutex.lock(); | |
| 833 | defer state_mutex.unlock(); | |
| 834 | if (pending) |existing| return .{ .busy = existing.source }; | |
| 835 | pending = call; | |
| 836 | return .published; | |
| 837 | } | |
| 838 | ||
| 839 | /// Read and clear. Clearing is what makes a second delegate call — a late | |
| 840 | /// fire, or the dismissal belt after a real cancel — a no-op rather than a | |
| 841 | /// second reply, and it is what frees the picker for the next caller. | |
| 842 | fn takePending() ?Pending { | |
| 843 | state_mutex.lock(); | |
| 844 | defer state_mutex.unlock(); | |
| 845 | const call = pending; | |
| 846 | pending = null; | |
| 847 | return call; | |
| 848 | } | |
| 849 | ||
| 850 | /// Which action is holding the picker, or null when it is free. | |
| 851 | fn busyWith() ?Source { | |
| 852 | state_mutex.lock(); | |
| 853 | defer state_mutex.unlock(); | |
| 854 | return if (pending) |call| call.source else null; | |
| 855 | } | |
| 856 | ||
| 857 | // ============================================================================= | |
| 858 | // The delegate methods. | |
| 859 | // | |
| 860 | // None of them replies directly: `evaluateJavaScript` is main-thread-only and | |
| 861 | // these are framework callbacks, so the finished JSON goes to | |
| 862 | // `ios_async.deliverJson` (or `deliverError`), which hops to the main queue and | |
| 863 | // answers under the request id captured back at dispatch. | |
| 864 | // ============================================================================= | |
| 865 | ||
| 866 | /// `-imagePickerController:didFinishPickingMediaWithInfo:` | |
| 867 | fn craftIOSImagePickerDidFinish(_: Id, _: Id, picker: Id, info: Id) callconv(.c) void { | |
| 868 | if (!is_darwin) return; | |
| 869 | ||
| 870 | const call = takePending(); | |
| 871 | ||
| 872 | // Swift's first line, and unconditional for a reason: a shaping failure | |
| 873 | // below must still take the modal off the screen. A rejected promise is | |
| 874 | // recoverable; an app stuck behind a picker it cannot close is not. | |
| 875 | dismissPresented(picker, if (call) |c| c.work.sels.dismiss else null); | |
| 876 | ||
| 877 | const answering = call orelse { | |
| 878 | std.log.info( | |
| 879 | "image picker: a pick arrived with no call waiting; ignored rather than " ++ | |
| 880 | "answered twice", | |
| 881 | .{}, | |
| 882 | ); | |
| 883 | return; | |
| 884 | }; | |
| 885 | ||
| 886 | const allocator = std.heap.c_allocator; | |
| 887 | ||
| 888 | // Swift's `"Failed to process image"` branch is every failure here: a nil | |
| 889 | // image, a JPEG encode that returned nothing, a reply that would not shape. | |
| 890 | const json: ?[]u8 = buildPhotoReply(info, answering.work, allocator) catch |err| shaped: { | |
| 891 | std.log.err( | |
| 892 | "{s}: could not build the reply for the picked image ({}); rejecting rather " ++ | |
| 893 | "than replying with an image that was not encoded", | |
| 894 | .{ answering.source.actionName(), err }, | |
| 895 | ); | |
| 896 | break :shaped null; | |
| 897 | }; | |
| 898 | defer if (json) |owned| allocator.free(owned); | |
| 899 | ||
| 900 | settle(answering, finishAnswer(json)); | |
| 901 | } | |
| 902 | ||
| 903 | /// Read the pick and shape it, or fail. Split from the callback so the | |
| 904 | /// callback has exactly one reply site. | |
| 905 | fn buildPhotoReply(info: Id, work: Work, allocator: std.mem.Allocator) ![]u8 { | |
| 906 | const photo = try readPhoto(info, work, allocator); | |
| 907 | defer allocator.free(photo.base64); | |
| 908 | return shapePhoto(allocator, photo); | |
| 909 | } | |
| 910 | ||
| 911 | /// `-imagePickerControllerDidCancel:` | |
| 912 | fn craftIOSImagePickerDidCancel(_: Id, _: Id, picker: Id) callconv(.c) void { | |
| 913 | if (!is_darwin) return; | |
| 914 | ||
| 915 | const call = takePending(); | |
| 916 | dismissPresented(picker, if (call) |c| c.work.sels.dismiss else null); | |
| 917 | ||
| 918 | const answering = call orelse { | |
| 919 | std.log.info("image picker: a cancel arrived with no call waiting; ignored", .{}); | |
| 920 | return; | |
| 921 | }; | |
| 922 | ||
| 923 | // A rejection, per `cancel_answer`. The code it carries is | |
| 924 | // `NATIVE_CALL_FAILED` and not Swift's `"Cancelled"`, because | |
| 925 | // `ios_async.deliverError` has no way to name an error — see the module | |
| 926 | // comment, which is the only place that says so. | |
| 927 | settle(answering, cancel_answer); | |
| 928 | } | |
| 929 | ||
| 930 | /// `-presentationControllerDidDismiss:` — the swipe-down belt. | |
| 931 | /// | |
| 932 | /// Nothing is dismissed here: UIKit has already taken the sheet off the | |
| 933 | /// screen, which is precisely what this callback reports. Sending | |
| 934 | /// `dismissViewControllerAnimated:` now could take down whatever the presenter | |
| 935 | /// shows next instead. | |
| 936 | fn craftIOSImagePickerDidDismiss(_: Id, _: Id, _: Id) callconv(.c) void { | |
| 937 | if (!is_darwin) return; | |
| 938 | ||
| 939 | // Empty is the ordinary case: a real cancel or a real pick already took it. | |
| 940 | const answering = takePending() orelse return; | |
| 941 | ||
| 942 | std.log.info( | |
| 943 | "{s}: the picker was dismissed interactively without a delegate callback; " ++ | |
| 944 | "rejecting rather than leaving the call unanswered", | |
| 945 | .{answering.source.actionName()}, | |
| 946 | ); | |
| 947 | settle(answering, cancel_answer); | |
| 948 | } | |
| 949 | ||
| 950 | /// `[picker dismissViewControllerAnimated:YES completion:nil]`. | |
| 951 | /// | |
| 952 | /// `resolved` is the selector captured at dispatch when there is a call to | |
| 953 | /// answer. A stray callback has none, so it registers the selector here — that | |
| 954 | /// is not a reply path, so a failure is loggable rather than something a | |
| 955 | /// caller could be told about either way. | |
| 956 | /// | |
| 957 | /// `?Id` is `??*anyopaque`, and *both* nulls have to reach the registration | |
| 958 | /// below. The outer one is "no call was waiting, so nothing was captured"; the | |
| 959 | /// inner one is a captured `Sels` whose `dismiss` is itself null. A single | |
| 960 | /// `orelse` only unwraps the outer one, and would then hand `objc_msgSend` a | |
| 961 | /// nil selector — a crash on a live picker rather than the miss this branch is | |
| 962 | /// written for. So it is flattened first. | |
| 963 | fn dismissPresented(picker: Id, resolved: ?Id) void { | |
| 964 | if (!is_darwin) return; | |
| 965 | ||
| 966 | const sel = flattenSelector(resolved) orelse | |
| 967 | (objc.sel_registerName("dismissViewControllerAnimated:completion:") orelse { | |
| 968 | std.log.err( | |
| 969 | "image picker: dismissViewControllerAnimated:completion: would not register; " ++ | |
| 970 | "the picker stays on screen", | |
| 971 | .{}, | |
| 972 | ); | |
| 973 | return; | |
| 974 | }); | |
| 975 | ||
| 976 | const DismissFn = *const fn (Id, Id, bool, Id) callconv(.c) void; | |
| 977 | const dismiss: DismissFn = @ptrCast(&objc.objc_msgSend); | |
| 978 | dismiss(picker, sel, true, null); | |
| 979 | } | |
| 980 | ||
| 981 | /// Collapse `??*anyopaque` to `?*anyopaque` so one `orelse` covers both nulls. | |
| 982 | /// | |
| 983 | /// Split out only so the collapse is assertable on a host — the bug it prevents | |
| 984 | /// (a nil selector reaching `objc_msgSend`) has no observable form short of a | |
| 985 | /// device crash. | |
| 986 | fn flattenSelector(resolved: ?Id) Id { | |
| 987 | return if (resolved) |inner| inner else null; | |
| 988 | } | |
| 989 | ||
| 990 | /// `CGSize` — two `CGFloat`s, 16 bytes. | |
| 991 | /// | |
| 992 | /// Spelled locally rather than named from `objc_runtime`, on the | |
| 993 | /// `bridge_mobile_location.Coord` precedent, so the layout is visible at the | |
| 994 | /// call site. Returned through the regular `objc_msgSend`: `objc_msgSend_stret` | |
| 995 | /// is for structs larger than this and does not exist on arm64 at all. | |
| 996 | const Size = extern struct { width: f64, height: f64 }; | |
| 997 | ||
| 998 | /// Turn the picker's info dictionary into the values the reply is built from. | |
| 999 | /// | |
| 1000 | /// The returned `base64` is owned by the caller. Every Objective-C result is | |
| 1001 | /// guarded, and each nil is a distinct error rather than a zero: Swift's | |
| 1002 | /// `else { rejectCallback(…, "Failed to process image") }` covers all of them, | |
| 1003 | /// and a plausible-looking empty photo is exactly the fabrication that must not | |
| 1004 | /// happen. | |
| 1005 | /// | |
| 1006 | /// The `NSData` is autoreleased and consumed synchronously here — encoded | |
| 1007 | /// before this function returns — so no ownership is taken of it. | |
| 1008 | fn readPhoto(info: Id, work: Work, allocator: std.mem.Allocator) !Photo { | |
| 1009 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 1010 | if (info == null) return error.NoPickerInfo; | |
| 1011 | ||
| 1012 | const ObjectForKeyFn = *const fn (Id, Id, Id) callconv(.c) Id; | |
| 1013 | const object_for_key: ObjectForKeyFn = @ptrCast(&objc.objc_msgSend); | |
| 1014 | const image = object_for_key(info, work.sels.object_for_key, work.original_image_key) orelse | |
| 1015 | return error.NoOriginalImage; | |
| 1016 | ||
| 1017 | // Read before the encode, so the dimensions describe the same UIImage the | |
| 1018 | // bytes came from. | |
| 1019 | const SizeFn = *const fn (Id, Id) callconv(.c) Size; | |
| 1020 | const size_fn: SizeFn = @ptrCast(&objc.objc_msgSend); | |
| 1021 | const size = size_fn(image, work.sels.size); | |
| 1022 | ||
| 1023 | const data = work.jpeg(image, jpeg_compression_quality) orelse return error.JpegEncodingFailed; | |
| 1024 | ||
| 1025 | const LengthFn = *const fn (Id, Id) callconv(.c) c_ulong; | |
| 1026 | const length_fn: LengthFn = @ptrCast(&objc.objc_msgSend); | |
| 1027 | const length: usize = @intCast(length_fn(data, work.sels.length)); | |
| 1028 | if (length == 0) return error.EmptyJpegData; | |
| 1029 | ||
| 1030 | const BytesFn = *const fn (Id, Id) callconv(.c) ?[*]const u8; | |
| 1031 | const bytes_fn: BytesFn = @ptrCast(&objc.objc_msgSend); | |
| 1032 | const bytes = bytes_fn(data, work.sels.bytes) orelse return error.EmptyJpegData; | |
| 1033 | ||
| 1034 | // Encoded once, in Zig, over the raw buffer. The alternative, | |
| 1035 | // `-base64EncodedStringWithOptions:`, would allocate a multi-megabyte | |
| 1036 | // `NSString` that then has to be copied out again; this is the one copy in | |
| 1037 | // this path that can actually be removed. | |
| 1038 | const encoder = std.base64.standard.Encoder; | |
| 1039 | const out = try allocator.alloc(u8, encoder.calcSize(length)); | |
| 1040 | errdefer allocator.free(out); | |
| 1041 | _ = encoder.encode(out, bytes[0..length]); | |
| 1042 | ||
| 1043 | return .{ .base64 = out, .width = size.width, .height = size.height }; | |
| 1044 | } | |
| 1045 | ||
| 1046 | // ============================================================================= | |
| 1047 | // Tests — host-only. | |
| 1048 | // | |
| 1049 | // Everything that decides page-visible bytes is pure and pinned here: routing | |
| 1050 | // in both directions, the five keys and their order, the duplicated payload, | |
| 1051 | // integral dimensions, the cancel-is-a-rejection decision, and the concurrency | |
| 1052 | // policy that is the whole reason a modal needs state at all. | |
| 1053 | // | |
| 1054 | // Nothing here presents a picker or touches UIKit. On a macOS runner | |
| 1055 | // `objc_getClass("UIImagePickerController")` is null and the test binary has no | |
| 1056 | // Info.plist, so the config gate refuses first — which is what makes the file | |
| 1057 | // safe to run. The Objective-C paths that *are* exercised for real are the ones | |
| 1058 | // with no device behind them: selector resolution and delegate registration. | |
| 1059 | // ============================================================================= | |
| 1060 | ||
| 1061 | const testing = std.testing; | |
| 1062 | ||
| 1063 | test "the declared actions are the ones the handler serves" { | |
| 1064 | try testing.expectEqual(@as(usize, 2), capability_actions.len); | |
| 1065 | try testing.expectEqualStrings(A.open_camera, capability_actions[0].name); | |
| 1066 | try testing.expectEqualStrings(A.pick_image, capability_actions[1].name); | |
| 1067 | ||
| 1068 | for (capability_actions) |decl| { | |
| 1069 | // A `.result` whose handler never replies parks the caller on an untimed | |
| 1070 | // promise; a `.none` that is awaited resolves immediately and means | |
| 1071 | // nothing. Swift settles both of these, so both are `.result`. | |
| 1072 | try testing.expectEqual(capabilities.Reply.result, decl.reply); | |
| 1073 | try testing.expectEqual(capabilities.ActionStatus.live, decl.status); | |
| 1074 | // `.live` with a reason would be a contradiction the manifest shows apps. | |
| 1075 | try testing.expect(decl.reason == null); | |
| 1076 | } | |
| 1077 | } | |
| 1078 | ||
| 1079 | test "the action names match the Swift case labels exactly" { | |
| 1080 | // The conformance ratchet compares these against the `case "…":` labels in | |
| 1081 | // `CraftApp.swift` in both directions; a prettier spelling would read as | |
| 1082 | // Zig serving an action the spec does not have. | |
| 1083 | try testing.expectEqualStrings("openCamera", A.open_camera); | |
| 1084 | try testing.expectEqualStrings("pickImage", A.pick_image); | |
| 1085 | } | |
| 1086 | ||
| 1087 | test "every declared action is one the dispatcher routes" { | |
| 1088 | for (capability_actions) |decl| { | |
| 1089 | if (routeFor(decl.name) == null) { | |
| 1090 | std.debug.print("declared action '{s}' does not route\n", .{decl.name}); | |
| 1091 | return error.DeclaredActionDoesNotRoute; | |
| 1092 | } | |
| 1093 | } | |
| 1094 | } | |
| 1095 | ||
| 1096 | test "every route the dispatcher has is a declared action" { | |
| 1097 | // The other direction: a route with a handler and no declaration is an | |
| 1098 | // action the page can call and the manifest denies exists. Each declaration | |
| 1099 | // must claim a *distinct* route — counting alone would let two rows share | |
| 1100 | // one route while another went undeclared. | |
| 1101 | const sources = std.enums.values(Source); | |
| 1102 | var claimed = std.mem.zeroes([std.enums.values(Source).len]bool); | |
| 1103 | ||
| 1104 | for (capability_actions) |decl| { | |
| 1105 | const route = routeFor(decl.name) orelse return error.DeclaredActionDoesNotRoute; | |
| 1106 | var slot: usize = sources.len; | |
| 1107 | for (sources, 0..) |candidate, i| { | |
| 1108 | if (candidate == route) slot = i; | |
| 1109 | } | |
| 1110 | if (slot == sources.len) return error.RouteIsNotEnumerated; | |
| 1111 | if (claimed[slot]) { | |
| 1112 | std.debug.print("two declarations route to {s}\n", .{@tagName(route)}); | |
| 1113 | return error.TwoDeclarationsShareARoute; | |
| 1114 | } | |
| 1115 | claimed[slot] = true; | |
| 1116 | } | |
| 1117 | ||
| 1118 | for (claimed, 0..) |taken, slot| { | |
| 1119 | if (!taken) { | |
| 1120 | std.debug.print( | |
| 1121 | "route {s} has a handler but no capability_actions row\n", | |
| 1122 | .{@tagName(sources[slot])}, | |
| 1123 | ); | |
| 1124 | return error.RouteNotDeclared; | |
| 1125 | } | |
| 1126 | } | |
| 1127 | } | |
| 1128 | ||
| 1129 | test "the two actions differ only in the source type they set" { | |
| 1130 | // The whole design of this module in two assertions. The raw values are | |
| 1131 | // UIKit's: PhotoLibrary = 0, Camera = 1, SavedPhotosAlbum = 2 (unused). | |
| 1132 | try testing.expectEqual(Source.camera, routeFor("openCamera").?); | |
| 1133 | try testing.expectEqual(Source.photo_library, routeFor("pickImage").?); | |
| 1134 | try testing.expectEqual(@as(c_long, 1), @backingInt(Source.camera)); | |
| 1135 | try testing.expectEqual(@as(c_long, 0), @backingInt(Source.photo_library)); | |
| 1136 | ||
| 1137 | // And each knows its own name back, because every log line and every | |
| 1138 | // `ios_async.acquire` is keyed on it — a swap here would correlate a reply | |
| 1139 | // to the wrong action. | |
| 1140 | try testing.expectEqualStrings(A.open_camera, Source.camera.actionName()); | |
| 1141 | try testing.expectEqualStrings(A.pick_image, Source.photo_library.actionName()); | |
| 1142 | } | |
| 1143 | ||
| 1144 | test "an action the namespace does not serve is reported, not ignored" { | |
| 1145 | var bridge = ImagePickerBridge.init(testing.allocator); | |
| 1146 | defer bridge.deinit(); | |
| 1147 | ||
| 1148 | try testing.expectError( | |
| 1149 | bridge_error.BridgeError.UnknownAction, | |
| 1150 | bridge.handleMessage("noSuchAction", "{}"), | |
| 1151 | ); | |
| 1152 | ||
| 1153 | // Casing is how a real typo arrives, and a miss does not fail loudly: | |
| 1154 | // `ios_dispatch` reads UnknownAction as "not mine" and hands the action to | |
| 1155 | // the Swift shim, so a typo silently keeps the old implementation. | |
| 1156 | for ([_][]const u8{ "opencamera", "OpenCamera", "pickimage", "PickImage" }) |typo| { | |
| 1157 | try testing.expectError( | |
| 1158 | bridge_error.BridgeError.UnknownAction, | |
| 1159 | bridge.handleMessage(typo, "{}"), | |
| 1160 | ); | |
| 1161 | } | |
| 1162 | ||
| 1163 | // The neighbours that share Swift's Coordinator delegate but are not this | |
| 1164 | // module's. Two modules answering one action would make `ios_dispatch`'s | |
| 1165 | // first-match routing order-dependent — and `startVideoRecording` in | |
| 1166 | // particular must keep reaching the shim, whose delegate crosstalk this | |
| 1167 | // module exists partly to avoid inheriting. | |
| 1168 | for ([_][]const u8{ | |
| 1169 | "startVideoRecording", | |
| 1170 | "stopVideoRecording", | |
| 1171 | "takeScreenshot", | |
| 1172 | "share", | |
| 1173 | }) |action| { | |
| 1174 | try testing.expectError( | |
| 1175 | bridge_error.BridgeError.UnknownAction, | |
| 1176 | bridge.handleMessage(action, "{}"), | |
| 1177 | ); | |
| 1178 | } | |
| 1179 | } | |
| 1180 | ||
| 1181 | // ----------------------------------------------------------------------------- | |
| 1182 | // Reply shaping. | |
| 1183 | // ----------------------------------------------------------------------------- | |
| 1184 | ||
| 1185 | /// A JSON number as an `f64`, whatever variant `std.json` chose for it. The | |
| 1186 | /// variant is a property of the *bytes*: `{d}` renders 3024 as the integer | |
| 1187 | /// token `3024` (`.integer`) and 3024.5 as `3024.5` (`.float`), so reading | |
| 1188 | /// `.float` directly would panic on the first. | |
| 1189 | fn numberOf(value: std.json.Value) !f64 { | |
| 1190 | return switch (value) { | |
| 1191 | .integer => |i| @floatFromInt(i), | |
| 1192 | .float => |f| f, | |
| 1193 | .number_string => |text| try std.fmt.parseFloat(f64, text), | |
| 1194 | else => error.ReplyFieldIsNotANumber, | |
| 1195 | }; | |
| 1196 | } | |
| 1197 | ||
| 1198 | test "the reply is the five-key object Swift resolves, in a fixed order" { | |
| 1199 | const json = try shapePhoto(testing.allocator, .{ | |
| 1200 | .base64 = "aGVsbG8=", | |
| 1201 | .width = 3024, | |
| 1202 | .height = 4032, | |
| 1203 | }); | |
| 1204 | defer testing.allocator.free(json); | |
| 1205 | ||
| 1206 | // The exact bytes, because the shape is the contract and `PhotoResult` | |
| 1207 | // names all five keys. Integral dimensions carry no fraction: Swift's | |
| 1208 | // `JSONSerialization` writes `3024` for the same CGFloat, and `{d}` agrees. | |
| 1209 | try testing.expectEqualStrings( | |
| 1210 | "{\"base64\":\"aGVsbG8=\"," ++ | |
| 1211 | "\"uri\":\"data:image/jpeg;base64,aGVsbG8=\"," ++ | |
| 1212 | "\"width\":3024,\"height\":4032," ++ | |
| 1213 | "\"mimeType\":\"image/jpeg\"}", | |
| 1214 | json, | |
| 1215 | ); | |
| 1216 | ||
| 1217 | // And it really parses as the object the page consumes, rather than merely | |
| 1218 | // looking like one. | |
| 1219 | const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{}); | |
| 1220 | defer parsed.deinit(); | |
| 1221 | const obj = parsed.value.object; | |
| 1222 | try testing.expectEqual(@as(usize, 5), obj.count()); | |
| 1223 | try testing.expectEqualStrings("aGVsbG8=", obj.get("base64").?.string); | |
| 1224 | try testing.expectEqualStrings("image/jpeg", obj.get("mimeType").?.string); | |
| 1225 | try testing.expectEqual(@as(f64, 3024), try numberOf(obj.get("width").?)); | |
| 1226 | try testing.expectEqual(@as(f64, 4032), try numberOf(obj.get("height").?)); | |
| 1227 | } | |
| 1228 | ||
| 1229 | test "the payload is carried twice, raw in base64 and prefixed in uri" { | |
| 1230 | // The duplication is the contract, not an oversight: `normalizePhoto` | |
| 1231 | // passes the object straight through and the SDK's `PhotoResult` reads both | |
| 1232 | // fields. A `uri` that merely repeated `base64` without the prefix, or a | |
| 1233 | // `base64` that carried the prefix, would each break one consumer. | |
| 1234 | const payload = "QUJDREVGRw=="; | |
| 1235 | const json = try shapePhoto(testing.allocator, .{ | |
| 1236 | .base64 = payload, | |
| 1237 | .width = 1, | |
| 1238 | .height = 1, | |
| 1239 | }); | |
| 1240 | defer testing.allocator.free(json); | |
| 1241 | ||
| 1242 | const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{}); | |
| 1243 | defer parsed.deinit(); | |
| 1244 | ||
| 1245 | const base64 = parsed.value.object.get("base64").?.string; | |
| 1246 | const uri = parsed.value.object.get("uri").?.string; | |
| 1247 | ||
| 1248 | try testing.expectEqualStrings(payload, base64); | |
| 1249 | try testing.expectEqualStrings(data_uri_prefix ++ payload, uri); | |
| 1250 | try testing.expect(std.mem.startsWith(u8, uri, "data:image/jpeg;base64,")); | |
| 1251 | try testing.expect(!std.mem.startsWith(u8, base64, "data:")); | |
| 1252 | } | |
| 1253 | ||
| 1254 | test "the mime type is the JPEG literal for both actions, whatever was picked" { | |
| 1255 | // The image is re-encoded at `jpeg_compression_quality`, so a PNG or HEIC | |
| 1256 | // chosen from the library still arrives as JPEG. Sniffing the original | |
| 1257 | // type and reporting it would be a different, and wrong, contract. | |
| 1258 | try testing.expectEqualStrings("image/jpeg", mime_type); | |
| 1259 | try testing.expectEqual(@as(f64, 0.8), jpeg_compression_quality); | |
| 1260 | } | |
| 1261 | ||
| 1262 | test "a fractional dimension keeps its fraction rather than being rounded" { | |
| 1263 | // `UIImage.size` is in points and is a CGFloat, so a scaled or cropped | |
| 1264 | // image can be fractional. Truncating would report a size the image does | |
| 1265 | // not have. | |
| 1266 | const json = try shapePhoto(testing.allocator, .{ | |
| 1267 | .base64 = "", | |
| 1268 | .width = 375.5, | |
| 1269 | .height = 812.25, | |
| 1270 | }); | |
| 1271 | defer testing.allocator.free(json); | |
| 1272 | ||
| 1273 | const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{}); | |
| 1274 | defer parsed.deinit(); | |
| 1275 | try testing.expectEqual(@as(f64, 375.5), try numberOf(parsed.value.object.get("width").?)); | |
| 1276 | try testing.expectEqual(@as(f64, 812.25), try numberOf(parsed.value.object.get("height").?)); | |
| 1277 | } | |
| 1278 | ||
| 1279 | test "a non-finite dimension is refused rather than printed" { | |
| 1280 | // `inf` and `nan` are not JSON. Printing them would put a bare `inf` inside | |
| 1281 | // the reply script and turn the whole `__craftBridgeResult` call into a | |
| 1282 | // syntax error in the page, with nothing to point at. | |
| 1283 | for ([_]f64{ std.math.inf(f64), -std.math.inf(f64), std.math.nan(f64) }) |bad| { | |
| 1284 | try testing.expectError( | |
| 1285 | bridge_error.BridgeError.InvalidParameter, | |
| 1286 | shapePhoto(testing.allocator, .{ .base64 = "", .width = bad, .height = 1 }), | |
| 1287 | ); | |
| 1288 | try testing.expectError( | |
| 1289 | bridge_error.BridgeError.InvalidParameter, | |
| 1290 | shapePhoto(testing.allocator, .{ .base64 = "", .width = 1, .height = bad }), | |
| 1291 | ); | |
| 1292 | } | |
| 1293 | } | |
| 1294 | ||
| 1295 | test "the encoded payload needs no JSON escaping" { | |
| 1296 | // `shapePhoto` appends the payload straight into a JSON string, which is | |
| 1297 | // only safe because of what the encoder can emit. Checked rather than | |
| 1298 | // asserted in a comment: if the encoder is ever swapped for one with a | |
| 1299 | // different alphabet — url-safe uses `-` and `_`, which are also fine, but | |
| 1300 | // a future one might not be — this fails here rather than on a device with | |
| 1301 | // a reply the page cannot parse. | |
| 1302 | const encoder = std.base64.standard.Encoder; | |
| 1303 | for (std.base64.standard_alphabet_chars) |c| { | |
| 1304 | try testing.expect(c != '"' and c != '\\' and c >= 0x20); | |
| 1305 | } | |
| 1306 | try testing.expect(encoder.pad_char != null); | |
| 1307 | const pad = encoder.pad_char.?; | |
| 1308 | try testing.expect(pad != '"' and pad != '\\' and pad >= 0x20); | |
| 1309 | } | |
| 1310 | ||
| 1311 | test "a real encode round-trips into a reply the page can parse" { | |
| 1312 | // The bytes chosen include 0xFF 0xD8 0xFF, a real JPEG SOI, and a run that | |
| 1313 | // forces padding — the two things that make an encoder's output visibly | |
| 1314 | // wrong if the length arithmetic is off. | |
| 1315 | const raw = [_]u8{ 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 'J', 'F', 'I', 'F' }; | |
| 1316 | const encoder = std.base64.standard.Encoder; | |
| 1317 | ||
| 1318 | const encoded = try testing.allocator.alloc(u8, encoder.calcSize(raw.len)); | |
| 1319 | defer testing.allocator.free(encoded); | |
| 1320 | _ = encoder.encode(encoded, &raw); | |
| 1321 | ||
| 1322 | const json = try shapePhoto(testing.allocator, .{ | |
| 1323 | .base64 = encoded, | |
| 1324 | .width = 10, | |
| 1325 | .height = 10, | |
| 1326 | }); | |
| 1327 | defer testing.allocator.free(json); | |
| 1328 | ||
| 1329 | const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{}); | |
| 1330 | defer parsed.deinit(); | |
| 1331 | ||
| 1332 | const decoder = std.base64.standard.Decoder; | |
| 1333 | const field = parsed.value.object.get("base64").?.string; | |
| 1334 | const back = try testing.allocator.alloc(u8, try decoder.calcSizeForSlice(field)); | |
| 1335 | defer testing.allocator.free(back); | |
| 1336 | try decoder.decode(back, field); | |
| 1337 | try testing.expectEqualSlices(u8, &raw, back); | |
| 1338 | } | |
| 1339 | ||
| 1340 | // ----------------------------------------------------------------------------- | |
| 1341 | // Which callback resolves and which rejects. | |
| 1342 | // ----------------------------------------------------------------------------- | |
| 1343 | ||
| 1344 | test "a cancel rejects rather than resolving anything" { | |
| 1345 | // The single most important shape in this file. `craft-bridge.js` resolves | |
| 1346 | // with `payload || {}`, so a `null`, `false` or `{}` result for a cancel | |
| 1347 | // would run the app's `then` branch — `normalizePhoto` would even hand it a | |
| 1348 | // well-formed `PhotoResult` with an empty payload — for a picture the user | |
| 1349 | // declined to take. Swift rejects; so does this. | |
| 1350 | try testing.expect(cancel_answer == .reject); | |
| 1351 | try testing.expect(cancel_answer != .photo); | |
| 1352 | } | |
| 1353 | ||
| 1354 | test "an image that will not encode rejects, and only a complete one resolves" { | |
| 1355 | // Swift's `if let image = …, let imageData = …` — both halves required, | |
| 1356 | // either one missing is `"Failed to process image"`. A reply built from a | |
| 1357 | // missing half would be `{"base64":"","width":0,"height":0,…}`, which is | |
| 1358 | // indistinguishable from a real photo of nothing, and `normalizePhoto` | |
| 1359 | // would pass it straight through to the app's `then`. | |
| 1360 | try testing.expect(finishAnswer(null) == .reject); | |
| 1361 | ||
| 1362 | const shaped = "{\"base64\":\"\",\"uri\":\"data:image/jpeg;base64,\",\"width\":1,\"height\":1,\"mimeType\":\"image/jpeg\"}"; | |
| 1363 | switch (finishAnswer(shaped)) { | |
| 1364 | .photo => |json| try testing.expectEqualStrings(shaped, json), | |
| 1365 | .reject => return error.AShapedReplyWasRejected, | |
| 1366 | } | |
| 1367 | } | |
| 1368 | ||
| 1369 | // ----------------------------------------------------------------------------- | |
| 1370 | // One picker, one caller. | |
| 1371 | // ----------------------------------------------------------------------------- | |
| 1372 | ||
| 1373 | /// A `Work` with nothing resolved. Safe in these tests because none of them | |
| 1374 | /// reaches a delegate callback — they exercise the slot, not the picker. | |
| 1375 | const empty_work = Work{ | |
| 1376 | .sels = .{ | |
| 1377 | .object_for_key = null, | |
| 1378 | .size = null, | |
| 1379 | .bytes = null, | |
| 1380 | .length = null, | |
| 1381 | .dismiss = null, | |
| 1382 | }, | |
| 1383 | .original_image_key = null, | |
| 1384 | .jpeg = &noopJpeg, | |
| 1385 | }; | |
| 1386 | ||
| 1387 | fn noopJpeg(_: Id, _: f64) callconv(.c) Id { | |
| 1388 | return null; | |
| 1389 | } | |
| 1390 | ||
| 1391 | test "the slot hands the delegate its ticket once, and clearing it frees the picker" { | |
| 1392 | _ = takePending(); | |
| 1393 | ||
| 1394 | const ticket = ios_async.Ticket{ .index = 6, .generation = 17 }; | |
| 1395 | try testing.expect(publish(.{ .ticket = ticket, .source = .camera, .work = empty_work }) == .published); | |
| 1396 | ||
| 1397 | const taken = takePending() orelse return error.PublishedCallWentMissing; | |
| 1398 | try testing.expectEqual(@as(u5, 6), taken.ticket.index); | |
| 1399 | try testing.expectEqual(@as(u32, 17), taken.ticket.generation); | |
| 1400 | try testing.expectEqual(Source.camera, taken.source); | |
| 1401 | ||
| 1402 | // Taken means gone: a double-firing delegate must not reply twice, and the | |
| 1403 | // next caller must find the picker free. | |
| 1404 | try testing.expect(takePending() == null); | |
| 1405 | try testing.expect(busyWith() == null); | |
| 1406 | } | |
| 1407 | ||
| 1408 | test "a second request while a picker is presented is refused, and the first is untouched" { | |
| 1409 | // The concurrency policy, and the one place it deliberately differs from | |
| 1410 | // `bridge_mobile_location`: there the framework cancels the earlier request | |
| 1411 | // so the displaced caller *must* be rejected; here the first picker is | |
| 1412 | // still on screen and will answer, so replacing it would strand a promise | |
| 1413 | // that was about to settle. | |
| 1414 | _ = takePending(); | |
| 1415 | ||
| 1416 | const first = ios_async.Ticket{ .index = 2, .generation = 3 }; | |
| 1417 | const second = ios_async.Ticket{ .index = 9, .generation = 4 }; | |
| 1418 | ||
| 1419 | try testing.expect(publish(.{ .ticket = first, .source = .camera, .work = empty_work }) == .published); | |
| 1420 | ||
| 1421 | // The refusal names who is holding it, and it is the *second* caller that | |
| 1422 | // is refused. | |
| 1423 | const refused = publish(.{ .ticket = second, .source = .photo_library, .work = empty_work }); | |
| 1424 | switch (refused) { | |
| 1425 | .published => return error.SecondRequestSilentlyReplacedTheFirst, | |
| 1426 | .busy => |holder| try testing.expectEqual(Source.camera, holder), | |
| 1427 | } | |
| 1428 | try testing.expectEqual(Source.camera, busyWith().?); | |
| 1429 | ||
| 1430 | // And it is a rejection the caller can see, never silence. | |
| 1431 | try testing.expectEqual( | |
| 1432 | bridge_error.BridgeError.InvalidParameter, | |
| 1433 | busyRefusal(A.pick_image, .camera), | |
| 1434 | ); | |
| 1435 | ||
| 1436 | // The survivor is the first, unchanged — the whole point. | |
| 1437 | const survivor = takePending() orelse return error.FirstCallWasDropped; | |
| 1438 | try testing.expectEqual(@as(u5, 2), survivor.ticket.index); | |
| 1439 | try testing.expectEqual(@as(u32, 3), survivor.ticket.generation); | |
| 1440 | try testing.expectEqual(Source.camera, survivor.source); | |
| 1441 | ||
| 1442 | // With the picker free, the next caller is admitted. | |
| 1443 | try testing.expect(publish(.{ .ticket = second, .source = .photo_library, .work = empty_work }) == .published); | |
| 1444 | _ = takePending(); | |
| 1445 | } | |
| 1446 | ||
| 1447 | test "a delegate callback with no call recorded touches no slot" { | |
| 1448 | // A late or duplicate fire must not reach `deliverJson`/`deliverError` at | |
| 1449 | // all. With the slot empty there is no ticket to reply with, and all three | |
| 1450 | // methods return without touching the pool — asserted by the slot staying | |
| 1451 | // empty rather than by observing a reply that must not happen. | |
| 1452 | _ = takePending(); | |
| 1453 | ||
| 1454 | craftIOSImagePickerDidFinish(null, null, null, null); | |
| 1455 | try testing.expect(takePending() == null); | |
| 1456 | ||
| 1457 | craftIOSImagePickerDidCancel(null, null, null); | |
| 1458 | try testing.expect(takePending() == null); | |
| 1459 | ||
| 1460 | craftIOSImagePickerDidDismiss(null, null, null); | |
| 1461 | try testing.expect(takePending() == null); | |
| 1462 | ||
| 1463 | try testing.expect(busyWith() == null); | |
| 1464 | } | |
| 1465 | ||
| 1466 | test "the pool refusal is an error the caller sees, not a dropped call" { | |
| 1467 | try testing.expectEqual( | |
| 1468 | bridge_error.BridgeError.InvalidParameter, | |
| 1469 | poolFull(A.open_camera), | |
| 1470 | ); | |
| 1471 | } | |
| 1472 | ||
| 1473 | // ----------------------------------------------------------------------------- | |
| 1474 | // Platform and gate. | |
| 1475 | // ----------------------------------------------------------------------------- | |
| 1476 | ||
| 1477 | test "off Darwin the handler refuses rather than pretending to present" { | |
| 1478 | if (is_darwin) return error.SkipZigTest; | |
| 1479 | ||
| 1480 | var bridge = ImagePickerBridge.init(testing.allocator); | |
| 1481 | defer bridge.deinit(); | |
| 1482 | ||
| 1483 | for ([_][]const u8{ A.open_camera, A.pick_image }) |action| { | |
| 1484 | try testing.expectError(error.UnsupportedPlatform, bridge.handleMessage(action, "{}")); | |
| 1485 | } | |
| 1486 | try testing.expectError(error.UnsupportedPlatform, requireConfigured(.camera)); | |
| 1487 | try testing.expectError(error.UnsupportedPlatform, requireConfigured(.photo_library)); | |
| 1488 | try testing.expectError(error.UnsupportedPlatform, Sels.resolve()); | |
| 1489 | try testing.expectError(error.UnsupportedPlatform, Work.resolve()); | |
| 1490 | try testing.expectError(error.UnsupportedPlatform, ensureDelegate()); | |
| 1491 | } | |
| 1492 | ||
| 1493 | test "without the usage descriptions the gate refuses before any picker exists" { | |
| 1494 | if (!is_darwin) return error.SkipZigTest; | |
| 1495 | ||
| 1496 | // The host runner is a bare binary with no Info.plist, which is exactly the | |
| 1497 | // "this app was not built with the camera enabled" case the gate is for. It | |
| 1498 | // is also what keeps this file safe to run: everything past the gate would | |
| 1499 | // look for UIKit, and on a runner that had it, present a real picker. | |
| 1500 | if (requireConfigured(.photo_library)) |_| { | |
| 1501 | // A runner that does carry the key (tests hosted inside a real app) | |
| 1502 | // would take the live path below, so skip rather than present. | |
| 1503 | return error.SkipZigTest; | |
| 1504 | } else |err| switch (err) { | |
| 1505 | bridge_error.BridgeError.PermissionDenied => { | |
| 1506 | var bridge = ImagePickerBridge.init(testing.allocator); | |
| 1507 | defer bridge.deinit(); | |
| 1508 | ||
| 1509 | for ([_][]const u8{ A.open_camera, A.pick_image }) |action| { | |
| 1510 | try testing.expectError( | |
| 1511 | bridge_error.BridgeError.PermissionDenied, | |
| 1512 | bridge.handleMessage(action, "{}"), | |
| 1513 | ); | |
| 1514 | } | |
| 1515 | ||
| 1516 | // The refusal happens before a slot is leased and before anything | |
| 1517 | // is published: an unreleased lease narrows the pool for every | |
| 1518 | // later call, and a published call with no picker behind it would | |
| 1519 | // refuse every request for the life of the process. | |
| 1520 | try testing.expect(takePending() == null); | |
| 1521 | try testing.expect(busyWith() == null); | |
| 1522 | }, | |
| 1523 | else => return err, | |
| 1524 | } | |
| 1525 | } | |
| 1526 | ||
| 1527 | test "the payload is ignored, not parsed" { | |
| 1528 | if (!is_darwin) return error.SkipZigTest; | |
| 1529 | // Real dispatches, so this needs the process the gate stops. | |
| 1530 | if (requireConfigured(.photo_library)) |_| return error.SkipZigTest else |_| {} | |
| 1531 | ||
| 1532 | // Both injected methods are declared `function()` and the Swift dispatcher | |
| 1533 | // reads nothing out of `body`, so a payload that is not even JSON must | |
| 1534 | // reach exactly the same outcome as `{}`. If it did not, this module would | |
| 1535 | // have invented a failure the shim does not have. | |
| 1536 | var bridge = ImagePickerBridge.init(testing.allocator); | |
| 1537 | defer bridge.deinit(); | |
| 1538 | ||
| 1539 | for ([_][]const u8{ A.open_camera, A.pick_image }) |action| { | |
| 1540 | const empty = bridge.handleMessage(action, "{}"); | |
| 1541 | const junk = bridge.handleMessage(action, "{not json"); | |
| 1542 | const missing = bridge.handleMessage(action, ""); | |
| 1543 | // The options the SDK types but the page never sends. | |
| 1544 | const options = bridge.handleMessage( | |
| 1545 | action, | |
| 1546 | "{\"quality\":0.5,\"maxWidth\":1024,\"camera\":\"front\",\"allowsEditing\":true}", | |
| 1547 | ); | |
| 1548 | ||
| 1549 | try testing.expectEqual(empty, junk); | |
| 1550 | try testing.expectEqual(empty, missing); | |
| 1551 | try testing.expectEqual(empty, options); | |
| 1552 | ||
| 1553 | if (empty) |_| {} else |err| { | |
| 1554 | try testing.expect(err != bridge_error.BridgeError.InvalidJSON); | |
| 1555 | try testing.expect(err != bridge_error.BridgeError.MissingData); | |
| 1556 | } | |
| 1557 | } | |
| 1558 | ||
| 1559 | try testing.expect(takePending() == null); | |
| 1560 | } | |
| 1561 | ||
| 1562 | test "every selector the delegate needs resolves on a real runtime" { | |
| 1563 | if (!is_darwin) return error.SkipZigTest; | |
| 1564 | ||
| 1565 | // `sel_registerName` interns a name whether or not any class implements it, | |
| 1566 | // so this touches no framework and presents nothing. What it catches is a | |
| 1567 | // typo in one of the five spellings, which would otherwise surface as a | |
| 1568 | // rejected pick — or a picker that cannot be dismissed — on a device. | |
| 1569 | const sels = try Sels.resolve(); | |
| 1570 | inline for (comptime std.meta.fieldNames(Sels)) |name| { | |
| 1571 | if (@field(sels, name) == null) { | |
| 1572 | std.debug.print("selector for Sels.{s} did not resolve\n", .{name}); | |
| 1573 | return error.SelectorDidNotResolve; | |
| 1574 | } | |
| 1575 | } | |
| 1576 | ||
| 1577 | // Distinct, or two different reads would come from one property. | |
| 1578 | try testing.expect(sels.bytes != sels.length); | |
| 1579 | try testing.expect(sels.size != sels.object_for_key); | |
| 1580 | try testing.expect(sels.dismiss != sels.size); | |
| 1581 | } | |
| 1582 | ||
| 1583 | test "the delegate class registers under its own name, idempotently" { | |
| 1584 | if (!is_darwin) return error.SkipZigTest; | |
| 1585 | ||
| 1586 | // No UIKit is involved: this allocates an NSObject subclass and one | |
| 1587 | // instance. It is the load-bearing half of the delegate — a class that does | |
| 1588 | // not register, or that adopts another module's IMPs, is a picker that | |
| 1589 | // never answers. | |
| 1590 | const first = try ensureDelegate(); | |
| 1591 | const second = try ensureDelegate(); | |
| 1592 | ||
| 1593 | // The same live instance, not merely two non-null answers: the instance is | |
| 1594 | // the strong reference `UIImagePickerController`'s weak `delegate` depends | |
| 1595 | // on, and a second one would leave the first free to be released. | |
| 1596 | try testing.expectEqual(first, second); | |
| 1597 | ||
| 1598 | const cls = objc.object_getClass(first) orelse return error.DelegateHasNoClass; | |
| 1599 | try testing.expectEqualStrings(delegate_class_name, std.mem.span(objc.class_getName(cls))); | |
| 1600 | ||
| 1601 | // All three methods attached. UIKit dispatches through | |
| 1602 | // `respondsToSelector:`, so a method that failed to attach is a callback | |
| 1603 | // that is simply never made — silence, on an untimed promise. | |
| 1604 | const sel_responds = objc.sel_registerName("respondsToSelector:") orelse | |
| 1605 | return error.SelectorNotFound; | |
| 1606 | const RespondsFn = *const fn (Id, Id, Id) callconv(.c) bool; | |
| 1607 | const responds: RespondsFn = @ptrCast(&objc.objc_msgSend); | |
| 1608 | ||
| 1609 | for (delegateMethods()) |method| { | |
| 1610 | const sel = objc.sel_registerName(method.selector.ptr) orelse return error.SelectorNotFound; | |
| 1611 | if (!responds(first, sel_responds, sel)) { | |
| 1612 | std.debug.print("the delegate does not respond to {s}\n", .{method.selector}); | |
| 1613 | return error.DelegateMissingMethod; | |
| 1614 | } | |
| 1615 | } | |
| 1616 | } | |
| 1617 | ||
| 1618 | test "the delegate methods carry the encodings their signatures actually have" { | |
| 1619 | // A wrong encoding registers, dispatches, and then reads arguments out of | |
| 1620 | // the wrong registers: no compile error, often no crash, just garbage | |
| 1621 | // pointers. Naming them is the only defence, so the pairing is pinned. | |
| 1622 | const methods = delegateMethods(); | |
| 1623 | try testing.expectEqual(@as(usize, 3), methods.len); | |
| 1624 | ||
| 1625 | try testing.expectEqualStrings( | |
| 1626 | "imagePickerController:didFinishPickingMediaWithInfo:", | |
| 1627 | methods[0].selector, | |
| 1628 | ); | |
| 1629 | // Two object arguments — the picker and the info dictionary. | |
| 1630 | try testing.expectEqualStrings("v@:@@", methods[0].types); | |
| 1631 | ||
| 1632 | try testing.expectEqualStrings( | |
| 1633 | "imagePickerControllerDidCancel:", | |
| 1634 | methods[1].selector, | |
| 1635 | ); | |
| 1636 | // One object argument — the picker. | |
| 1637 | try testing.expectEqualStrings("v@:@", methods[1].types); | |
| 1638 | ||
| 1639 | try testing.expectEqualStrings( | |
| 1640 | "presentationControllerDidDismiss:", | |
| 1641 | methods[2].selector, | |
| 1642 | ); | |
| 1643 | try testing.expectEqualStrings("v@:@", methods[2].types); | |
| 1644 | ||
| 1645 | // Taken from `ios_delegate.enc` rather than spelled here, so a caller | |
| 1646 | // cannot drift from the shared vocabulary. | |
| 1647 | try testing.expectEqualStrings(ios_delegate.enc.void_two_objects, methods[0].types); | |
| 1648 | try testing.expectEqualStrings(ios_delegate.enc.void_one_object, methods[1].types); | |
| 1649 | try testing.expectEqualStrings(ios_delegate.enc.void_one_object, methods[2].types); | |
| 1650 | } | |
| 1651 | ||
| 1652 | test "a captured dismiss selector that is itself null falls through to registration" { | |
| 1653 | // `dismissPresented` takes `?Id`, which is `??*anyopaque`: the callbacks | |
| 1654 | // build it as `if (call) |c| c.work.sels.dismiss else null`, so a stray | |
| 1655 | // callback yields the *outer* null and a call yields `.some(selector)`. | |
| 1656 | // Nothing stops that inner selector from being null — `empty_work` is | |
| 1657 | // exactly that shape — and a lone `orelse` would unwrap `.some(null)` into | |
| 1658 | // a nil selector handed straight to `objc_msgSend`, which is a crash on a | |
| 1659 | // live picker rather than the missing-selector branch. | |
| 1660 | const outer_null: ?Id = null; | |
| 1661 | const inner_null: ?Id = @as(Id, null); | |
| 1662 | ||
| 1663 | // The two really are distinct values at the type level, which is the whole | |
| 1664 | // trap: only one of them is `null` to `orelse`. | |
| 1665 | try testing.expect(outer_null == null); | |
| 1666 | try testing.expect(inner_null != null); | |
| 1667 | try testing.expect(inner_null.? == null); | |
| 1668 | ||
| 1669 | // Flattened, both mean "no selector was captured". | |
| 1670 | try testing.expect(flattenSelector(outer_null) == null); | |
| 1671 | try testing.expect(flattenSelector(inner_null) == null); | |
| 1672 | try testing.expect(flattenSelector(empty_work.sels.dismiss) == null); | |
| 1673 | } | |
| 1674 | ||
| 1675 | test "the delegate class name cannot collide with another module's" { | |
| 1676 | // `bridge_location.zig` registers `CraftLocationDelegate` for the desktop | |
| 1677 | // and `bridge_mobile_location.zig` registers `CraftIOSLocationDelegate`, | |
| 1678 | // and all of them are compiled into the same host test binary. Every one of | |
| 1679 | // these looks its class up with `objc_getClass` first, so whichever | |
| 1680 | // registered second would silently adopt the other's IMPs. | |
| 1681 | try testing.expectEqualStrings("CraftIOSImagePickerDelegate", delegate_class_name); | |
| 1682 | for ([_][]const u8{ | |
| 1683 | "CraftLocationDelegate", | |
| 1684 | "CraftIOSLocationDelegate", | |
| 1685 | "CraftScriptMessageHandler", | |
| 1686 | }) |taken| { | |
| 1687 | try testing.expect(!std.mem.eql(u8, delegate_class_name, taken)); | |
| 1688 | } | |
| 1689 | } | |