also looking at this
iOS Phase 8: the presented pickers — ratchet 58 → 53, last mechanism landed
#90
11 files
+5752
-12
| @@ -0,0 +1,1809 @@ | ||
| 1 | //! `pickContact` — present `CNContactPickerViewController` and answer with what | |
| 2 | //! the user picked. | |
| 3 | //! | |
| 4 | //! One action, one payload field, and four delegate methods — Swift's three, | |
| 5 | //! plus one belt for a dismissal Swift has no answer to. The Swift | |
| 6 | //! original is `CraftApp.swift:969-973` (dispatch), `4301-4323` (presentation) | |
| 7 | //! and `5088-5136` (the `CNContactPickerDelegate` extension plus | |
| 8 | //! `formatContact`). Everything below is measured against those lines. | |
| 9 | //! | |
| 10 | //! ## The payload: one field, `multiple` | |
| 11 | //! | |
| 12 | //! The injected JS (`CraftApp.swift:1970-1978`) posts | |
| 13 | //! `{action:'pickContact', multiple: options.multiple || false, callbackId: id}`, | |
| 14 | //! so `multiple` is a **top-level** field of `d`. Note what `||` does and does | |
| 15 | //! not do: it is not a boolean coercion, it is a fallback. `pickContact({multiple:1})` | |
| 16 | //! puts the number `1` on the wire and `pickContact({multiple:'yes'})` puts the | |
| 17 | //! string `"yes"`. | |
| 18 | //! | |
| 19 | //! Swift then reads `body["multiple"] as? Bool ?? false`. `as? Bool` on the | |
| 20 | //! bridged `NSNumber` succeeds for exactly `0` and `1` (→ false/true) and | |
| 21 | //! returns nil for `2`, for `0.5`, for a string, for anything else — which the | |
| 22 | //! `?? false` turns into false. `multipleFrom` below is that rule, spelled out, | |
| 23 | //! and it is pinned by tests rather than left to read like a coercion. | |
| 24 | //! | |
| 25 | //! There is **no other field**. `callbackId` is the shim's own correlation and | |
| 26 | //! never reaches a Zig module — `ios_async` owns the request id here. | |
| 27 | //! | |
| 28 | //! **The page's promise has no timeout.** `pickContact` builds its `Promise` | |
| 29 | //! by hand instead of going through `_createCallback` (`CraftApp.swift:1196`, | |
| 30 | //! which carries the 30-second `setTimeout`). An unanswered call parks the page | |
| 31 | //! forever, which is why every path in this file ends in a reply or an error. | |
| 32 | //! | |
| 33 | //! ## The replies, which are three different shapes | |
| 34 | //! | |
| 35 | //! - **one contact** (`contactPicker:didSelectContact:`) resolves a JSON | |
| 36 | //! *object*: `{"id","givenName","familyName","displayName","phoneNumbers", | |
| 37 | //! "emailAddresses"}`, where `phoneNumbers` is an array of | |
| 38 | //! `{"label","number"}` and `emailAddresses` an array of | |
| 39 | //! `{"label","address"}`. Swift builds a `[String: Any]`, whose key order is | |
| 40 | //! a `Dictionary` and therefore arbitrary; one order is fixed here so the | |
| 41 | //! bytes are testable, the same call `bridge_mobile_notifications.zig` | |
| 42 | //! makes. | |
| 43 | //! - **many contacts** (`contactPicker:didSelectContacts:`) resolves a JSON | |
| 44 | //! *array* of those objects. `contacts.map` over an empty selection is `[]`, | |
| 45 | //! and that **resolves** — it is not an error and not a cancel. | |
| 46 | //! `test-bridges.html:1030` reads `contacts?.length`, so it must be an | |
| 47 | //! array. | |
| 48 | //! - **cancel** (`contactPickerDidCancel:`) **rejects**. This is the one | |
| 49 | //! action in this batch where a cancel is an error rather than a distinct | |
| 50 | //! resolve, so there is deliberately no `{"cancelled":true}` here — that | |
| 51 | //! would be a fabricated success for a pick that never happened. | |
| 52 | //! | |
| 53 | //! `packages/typescript/types/craft.d.ts:1157-1164` declares `Contact` with | |
| 54 | //! `phoneNumbers: string[]` / `emailAddresses: string[]`. That matches | |
| 55 | //! `getContacts` (flat `phone.value.stringValue` strings) and is **wrong for | |
| 56 | //! this action**, which emits `{label, number}` / `{label, address}` dicts. The | |
| 57 | //! runtime shape is the contract; `formatContact` is what is mirrored here, not | |
| 58 | //! the type declaration. | |
| 59 | //! | |
| 60 | //! ## What diverges, stated rather than smoothed over | |
| 61 | //! | |
| 62 | //! **The cancel error text and code change.** Swift calls | |
| 63 | //! `rejectCallback(id, error: "Cancelled")` with the default | |
| 64 | //! `code: "CRAFT_ERROR"`, which reaches the page as | |
| 65 | //! `{"error":true,"code":"CRAFT_ERROR",…,"message":"Cancelled"}`. Zig replies | |
| 66 | //! through `ios_async.deliverError`, which is hard-wired to | |
| 67 | //! `BridgeError.NativeCallFailed` → `code:"NATIVE_CALL_FAILED"`, | |
| 68 | //! `message:"Native API call failed"`. The page's `catch` still runs and the | |
| 69 | //! promise still settles, so nothing hangs and nothing is fabricated — but a | |
| 70 | //! page that prints `err.message` (which `test-bridges.html:1022` does) shows | |
| 71 | //! different text, and a page that branches on `err.code` sees a different code. | |
| 72 | //! | |
| 73 | //! This is the honest floor of the available channel, not a preference. | |
| 74 | //! `bridge_error.BridgeError.Cancelled` → `CANCELLED` / | |
| 75 | //! `"Operation was cancelled"` would be *nearer* the truth, and `ios_async` has | |
| 76 | //! no way to send it: `deliverError` sets a `failed` flag and `deliverOnMain` | |
| 77 | //! chooses `NativeCallFailed` for every flagged slot. Closing the gap is a | |
| 78 | //! change to `ios_async.zig` — a `BridgeError` stored on the slot beside | |
| 79 | //! `failed`, and `deliverOnMain` sending that instead of the constant — and it | |
| 80 | //! belongs there rather than in a second reply path built here, because a | |
| 81 | //! module that reached around `ios_async` would also be reaching around the | |
| 82 | //! generation guard that stops a stale callback answering someone else's call. | |
| 83 | //! Until then, "the native call failed" is what a cancel says, and saying so | |
| 84 | //! here is the point. | |
| 85 | //! | |
| 86 | //! **`config.enableContacts` has no Zig mirror.** `ios.zig`'s `AppConfig` has | |
| 87 | //! no such field — the same gap `bridge_mobile_system.zig` records for | |
| 88 | //! `enableShare`. The Info.plist is read instead, and for this flag the mapping | |
| 89 | //! is exact: `packages/ios/src/index.ts:189` writes `NSContactsUsageDescription` | |
| 90 | //! if and only if `config.enableContacts`, with none of the sharing that made | |
| 91 | //! the location keys ambiguous. | |
| 92 | //! | |
| 93 | //! Two things about that gate have to be said plainly. First, the key is **not | |
| 94 | //! a precondition of the API**: `CNContactPickerViewController` runs out of | |
| 95 | //! process and needs no Contacts authorization, so this reads the key purely as | |
| 96 | //! *evidence of the flag*, never as something the framework requires. Second, | |
| 97 | //! the behaviour changes: Swift's `case "pickContact":` has **no `else`**, so an | |
| 98 | //! app built with `enableContacts: false` answers the page with *nothing*, on a | |
| 99 | //! promise with no timeout — a hang for the life of the page. Here it is an | |
| 100 | //! explicit `PERMISSION_DENIED`. Everybody settles, which is strictly better, | |
| 101 | //! and it is a difference a page can observe. | |
| 102 | //! | |
| 103 | //! **No permission is requested, deliberately.** `pickContact` never touches | |
| 104 | //! `CNContactStore` and never calls `requestAccess(for:.contacts)`; only | |
| 105 | //! `getContacts` and `addContact` do. Adding one here would show the user a | |
| 106 | //! prompt the shim never shows. | |
| 107 | //! | |
| 108 | //! **Nothing is dismissed, and that is a decision rather than an omission.** | |
| 109 | //! What is *verified*: `CraftApp.swift` contains exactly five `dismiss(` calls — | |
| 110 | //! `UIImagePickerController` (2643, 2662), the PDF viewer (4288, 4294) and the | |
| 111 | //! data scanner (4873) — and none of them is in the contact-picker path. Swift's | |
| 112 | //! three `CNContactPickerDelegate` methods return without dismissing anything. | |
| 113 | //! What is *reasoned*: `CNContactPickerViewController` is an out-of-process | |
| 114 | //! remote view controller, which is the standard explanation for why it takes | |
| 115 | //! itself down on both Done and Cancel and why its delegate protocol asks for no | |
| 116 | //! dismissal. | |
| 117 | //! | |
| 118 | //! So this file matches the shim exactly, and matching it is the conservative | |
| 119 | //! choice in both directions. Adding a dismissal would be a *second* dismissal | |
| 120 | //! of a controller already dismissing, and sent to the presenter it would take | |
| 121 | //! down whatever else happened to be modal — a new bug, in an action the shim | |
| 122 | //! answers. Omitting it can only reproduce a defect the shim already has. This | |
| 123 | //! is the one place where the generic picker rule "the delegate must dismiss" | |
| 124 | //! does not apply; the image and document pickers are `UIImagePickerController` | |
| 125 | //! and `UIDocumentPickerViewController`, both in-process, both of which do need | |
| 126 | //! it. | |
| 127 | //! | |
| 128 | //! Not verified on a device from here: that the picker really does disappear | |
| 129 | //! without help. If it turns out not to, the fix is one `dismiss` sent to the | |
| 130 | //! *picker* (never the presenter) from each of the picker callbacks. | |
| 131 | //! | |
| 132 | //! **A contact whose keys were not fetched still crashes.** Touching an | |
| 133 | //! unfetched property raises `CNContactPropertyNotFetchedException`, which from | |
| 134 | //! Zig is an uncatchable SIGABRT. Swift cannot catch `NSException` either, so | |
| 135 | //! this is exact parity with the shim rather than a regression — and there is | |
| 136 | //! deliberately no comment below claiming a guard against it, because there | |
| 137 | //! isn't one. | |
| 138 | //! | |
| 139 | //! ## Concurrency: one picker, one ticket, and a refusal that says so | |
| 140 | //! | |
| 141 | //! Swift keeps a single `pendingCallbackId` (line 383) shared by *every* picker | |
| 142 | //! in the coordinator — camera, document, NFC, Bluetooth, contacts. Opening any | |
| 143 | //! second picker overwrites it and the first promise never settles. This module | |
| 144 | //! keeps its own ticket, and when a second `pickContact` arrives while one is on | |
| 145 | //! screen it **refuses the second and leaves the first alone**: the first picker | |
| 146 | //! is still presented and will still answer, so displacing it would strand a | |
| 147 | //! call that was about to succeed. | |
| 148 | //! | |
| 149 | //! What that costs, said rather than hidden: the slot is cleared only by a | |
| 150 | //! delegate callback. A picker that is never presented, or presented and then | |
| 151 | //! never answered, leaves the slot held for the life of the process and refuses | |
| 152 | //! every later call. Two causes are known, and they are not both removed: | |
| 153 | //! | |
| 154 | //! - **Presenting on a controller that is already presenting**, which UIKit | |
| 155 | //! answers by logging and doing nothing. That one is removed: | |
| 156 | //! `bridge_mobile_system.uikit.topmostViewController()`'s walk up | |
| 157 | //! `presentedViewController` is why this file reuses that function rather | |
| 158 | //! than copying Swift's `windows.first?.rootViewController` | |
| 159 | //! (`CraftApp.swift:4303-4304`), which has the bug. | |
| 160 | //! - **A swipe-down dismissal.** The picker is a sheet on iOS 13+, and an | |
| 161 | //! interactive dismissal is widely reported not to call | |
| 162 | //! `contactPickerDidCancel:` — the same report | |
| 163 | //! `bridge_mobile_imagepicker.zig` carries a belt for, and one this repo | |
| 164 | //! verifies on no device. `presentationControllerDidDismiss:` is that belt | |
| 165 | //! here too: it is registered on the delegate, and the picker's | |
| 166 | //! presentation controller is pointed at that delegate before presenting, | |
| 167 | //! so a swipe rejects the call instead of stranding it. Belt, not fix — | |
| 168 | //! UIKit sends it only for a user-driven dismissal, so it cannot fire after | |
| 169 | //! a pick or a Cancel that already answered, and if the report is wrong it | |
| 170 | //! costs two messages. The one case it does not cover is a presentation | |
| 171 | //! controller that already carries a delegate of its own, which is left | |
| 172 | //! alone rather than displaced; that is logged where it happens rather than | |
| 173 | //! assumed away. | |
| 174 | //! | |
| 175 | //! No reply is ever sent from a delegate callback directly. `ios_async` is the | |
| 176 | //! only channel, and the main-queue hop it performs is not merely thread | |
| 177 | //! safety: it is what restores the `request_context` captured at dispatch, so | |
| 178 | //! the reply names the call that is waiting instead of falling back to | |
| 179 | //! action-name matching. | |
| 180 | ||
| 181 | const std = @import("std"); | |
| 182 | const builtin = @import("builtin"); | |
| 183 | const capabilities = @import("capabilities.zig"); | |
| 184 | const bridge_error = @import("bridge_error.zig"); | |
| 185 | const objc_runtime = @import("objc_runtime.zig"); | |
| 186 | const ios_async = @import("ios_async.zig"); | |
| 187 | const ios_delegate = @import("ios_delegate.zig"); | |
| 188 | const bridge_mobile_system = @import("bridge_mobile_system.zig"); | |
| 189 | const compat_mutex = @import("compat_mutex.zig"); | |
| 190 | ||
| 191 | const objc = objc_runtime.objc; | |
| 192 | const is_darwin = builtin.target.os.tag.isDarwin(); | |
| 193 | ||
| 194 | /// The same type as `objc.id` — `?*anyopaque` — spelled locally, per the | |
| 195 | /// location/notifications precedent: `objc_runtime.objc` is an empty struct off | |
| 196 | /// Darwin and a function *signature* is analysed even when a comptime platform | |
| 197 | /// guard prunes the body, so naming `objc.id` in the `callconv(.c)` types below | |
| 198 | /// would break the host build. A single optional pointer, never `?objc.id` — a | |
| 199 | /// double optional is illegal in `callconv(.c)`. | |
| 200 | const Id = ?*anyopaque; | |
| 201 | ||
| 202 | /// The action name, spelled exactly as the Swift `case` label spells it. | |
| 203 | /// `test/ios_conformance_test.zig` matches this block against those labels in | |
| 204 | /// both directions, and fails the build if two modules declare one name. | |
| 205 | pub const A = struct { | |
| 206 | pub const pick_contact = "pickContact"; | |
| 207 | }; | |
| 208 | ||
| 209 | /// `.result`: every Swift path out of this action terminates in exactly one | |
| 210 | /// `resolveCallback` (either `didSelect` overload) or one `rejectCallback` | |
| 211 | /// (cancel). `.none` would be a claim that nothing answers, and on this | |
| 212 | /// particular promise — hand-built, no `setTimeout` — that is a page parked | |
| 213 | /// forever rather than for thirty seconds. | |
| 214 | /// | |
| 215 | /// `.live`, not `.unavailable`: in an app built with `enableContacts` the | |
| 216 | /// picker presents and answers. A refusal here is always a specific condition | |
| 217 | /// (contacts not configured, ContactsUI not linked, a picker already on screen, | |
| 218 | /// the async pool full), never this action's normal answer. | |
| 219 | pub const capability_actions = [_]capabilities.ActionDecl{ | |
| 220 | .{ .name = A.pick_contact, .reply = .result }, | |
| 221 | }; | |
| 222 | ||
| 223 | /// Which handler an action selects, split out from `handleMessage` so the | |
| 224 | /// table-versus-dispatch agreement is assertable on a host without touching | |
| 225 | /// ContactsUI. | |
| 226 | const Route = enum { pick_contact }; | |
| 227 | ||
| 228 | fn routeFor(action: []const u8) ?Route { | |
| 229 | if (std.mem.eql(u8, action, A.pick_contact)) return .pick_contact; | |
| 230 | return null; | |
| 231 | } | |
| 232 | ||
| 233 | pub const ContactPickerBridge = struct { | |
| 234 | allocator: std.mem.Allocator, | |
| 235 | ||
| 236 | const Self = @This(); | |
| 237 | ||
| 238 | pub fn init(allocator: std.mem.Allocator) Self { | |
| 239 | return .{ .allocator = allocator }; | |
| 240 | } | |
| 241 | ||
| 242 | pub fn deinit(_: *Self) void {} | |
| 243 | ||
| 244 | pub fn handleMessage(self: *Self, action: []const u8, data: []const u8) !void { | |
| 245 | const route = routeFor(action) orelse return bridge_error.BridgeError.UnknownAction; | |
| 246 | // Exhaustive, so a `Route` without a handler is a compile error. | |
| 247 | return switch (route) { | |
| 248 | .pick_contact => self.pickContact(data), | |
| 249 | }; | |
| 250 | } | |
| 251 | ||
| 252 | /// Present the contact picker and hand the answer to the delegate. | |
| 253 | /// | |
| 254 | /// Ordering is load-bearing in two places. The payload is parsed *first*, so | |
| 255 | /// a malformed body is reported the same on any platform and before any | |
| 256 | /// framework is consulted. And every fallible step — the Info.plist gate, | |
| 257 | /// both framework classes, every selector a delegate callback or the | |
| 258 | /// swipe-down belt will need, the delegate class, the presenter, the | |
| 259 | /// predicate, the picker itself — runs **before** `ios_async.acquire`. | |
| 260 | /// Exactly one path leaves this function after the lease without presenting | |
| 261 | /// — the concurrency refusal — and it releases the slot with | |
| 262 | /// `ios_async.abandon` on its way out. Every other statement between the | |
| 263 | /// lease and `presentViewController:` is infallible. That is the property | |
| 264 | /// being protected: a lease that escapes without either a presentation or an | |
| 265 | /// `abandon` narrows the pool for the life of the process. | |
| 266 | fn pickContact(self: *Self, data: []const u8) !void { | |
| 267 | const multiple = try parseMultiple(self.allocator, data); | |
| 268 | ||
| 269 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 270 | ||
| 271 | try requireContactsConfigured(); | |
| 272 | ||
| 273 | // ContactsUI first, Contacts second, each guarded on its own: a process | |
| 274 | // that linked Contacts but not ContactsUI is a real configuration, and | |
| 275 | // the fixture (`packages/ios/fixtures/zig-slice/build-and-run.sh:65`) | |
| 276 | // links neither. Naming the missing class beats a generic failure, | |
| 277 | // because the fix is a link line rather than anything in this file. | |
| 278 | const PickerClass = objc.objc_getClass("CNContactPickerViewController") orelse { | |
| 279 | std.log.err( | |
| 280 | "pickContact refused: this process has no CNContactPickerViewController; " ++ | |
| 281 | "ContactsUI.framework is not linked", | |
| 282 | .{}, | |
| 283 | ); | |
| 284 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 285 | }; | |
| 286 | ||
| 287 | const sels = try Sels.resolve(); | |
| 288 | const delegate = try ensureDelegate(); | |
| 289 | ||
| 290 | // The walk up `presentedViewController` is the part Swift is missing — | |
| 291 | // see the module comment. It also matters to the refusal policy: one of | |
| 292 | // the two known ways to leave a ticket unanswered forever is a | |
| 293 | // presentation UIKit silently declines because the target is already | |
| 294 | // presenting, and the walk is what stops this file ever asking for that. | |
| 295 | // The other — a swipe-down that sends no delegate callback — is what | |
| 296 | // `attachDismissObserver` below is for. | |
| 297 | const presenter = try bridge_mobile_system.uikit.topmostViewController(); | |
| 298 | ||
| 299 | const NSPredicate = objc.objc_getClass("NSPredicate") orelse return error.ClassNotFound; | |
| 300 | const sel_predicate_with_value = try selector("predicateWithValue:"); | |
| 301 | const sel_set_delegate = try selector("setDelegate:"); | |
| 302 | const sel_set_enabling = try selector("setPredicateForEnablingContact:"); | |
| 303 | const sel_set_selection = try selector("setPredicateForSelectionOfContact:"); | |
| 304 | const sel_present = try selector("presentViewController:animated:completion:"); | |
| 305 | // The swipe-down belt's two reads, resolved here with everything else: | |
| 306 | // a missing selector then fails the call rather than silently leaving | |
| 307 | // the only thing that answers an interactive dismissal unattached. | |
| 308 | const dismiss_sels = DismissSels{ | |
| 309 | .presentation = try selector("presentationController"), | |
| 310 | .delegate = try selector("delegate"), | |
| 311 | .set_delegate = sel_set_delegate, | |
| 312 | }; | |
| 313 | ||
| 314 | // `+[NSPredicate predicateWithValue:]` takes a `BOOL`, so the cast has | |
| 315 | // to name that argument; `msgSendId1` builds the signature from | |
| 316 | // `@TypeOf(arg1)` and `true` is a Zig `bool`, which is what `B` is on | |
| 317 | // 64-bit Apple platforms. | |
| 318 | const always_true = objc.msgSendId1(NSPredicate, sel_predicate_with_value, true) orelse | |
| 319 | return error.NativeCallFailed; | |
| 320 | ||
| 321 | const picker = (try objc.allocInit(PickerClass)) orelse return error.NativeCallFailed; | |
| 322 | // `allocInit` gave us +1. `presentViewController:` retains the picker for | |
| 323 | // the life of the presentation, so ours is the reference to drop — and | |
| 324 | // on the refusal paths below it is the only one there is. Same shape as | |
| 325 | // the share sheet's `defer objc.release(activity_vc)`. | |
| 326 | defer objc.release(picker); | |
| 327 | ||
| 328 | objc.msgSendVoid1(picker, sel_set_delegate, delegate); | |
| 329 | objc.msgSendVoid1(picker, sel_set_enabling, always_true); | |
| 330 | ||
| 331 | if (multiple) { | |
| 332 | // Swift's `picker.predicateForSelectionOfContact = nil`. The | |
| 333 | // `@as(objc.id, null)` is required: an untyped `null` gives | |
| 334 | // `msgSendVoid1` no argument type to build a signature from. | |
| 335 | objc.msgSendVoid1(picker, sel_set_selection, @as(objc.id, null)); | |
| 336 | } else { | |
| 337 | // Swift builds a second `NSPredicate(value: true)` here. One | |
| 338 | // instance serves both properties identically — `NSPredicate` is | |
| 339 | // immutable and neither property mutates it — so the object graph | |
| 340 | // is the same one Swift assembles in two allocations. | |
| 341 | objc.msgSendVoid1(picker, sel_set_selection, always_true); | |
| 342 | } | |
| 343 | ||
| 344 | // Attached before presenting, because that is when a presentation | |
| 345 | // controller can be configured, and retried after `presentViewController:` | |
| 346 | // for the case where UIKit only builds one there. Infallible either way: | |
| 347 | // it returns whether it took, and never fails the call. | |
| 348 | var dismiss_observed = attachDismissObserver(picker, delegate, dismiss_sels); | |
| 349 | ||
| 350 | const ticket = ios_async.acquire(A.pick_contact) orelse return poolFull(); | |
| 351 | ||
| 352 | // Published *before* the framework call, never after: a delegate that | |
| 353 | // somehow reached an empty slot would have no ticket to reply with. The | |
| 354 | // publish is also the concurrency check, done under one lock so two | |
| 355 | // dispatches cannot both find the slot free. | |
| 356 | if (!publishPending(.{ .ticket = ticket, .sels = sels })) { | |
| 357 | ios_async.abandon(ticket); | |
| 358 | return alreadyPresented(); | |
| 359 | } | |
| 360 | ||
| 361 | const PresentFn = *const fn (Id, Id, Id, bool, Id) callconv(.c) void; | |
| 362 | const present_fn: PresentFn = @ptrCast(&objc.objc_msgSend); | |
| 363 | // Completion handler nil, as Swift's `present(picker, animated: true)` | |
| 364 | // passes none. There is nothing to do on presentation-complete: the | |
| 365 | // answer comes from the delegate. | |
| 366 | present_fn(presenter, sel_present, picker, true, null); | |
| 367 | ||
| 368 | if (!dismiss_observed) dismiss_observed = attachDismissObserver(picker, delegate, dismiss_sels); | |
| 369 | if (!dismiss_observed) { | |
| 370 | std.log.warn( | |
| 371 | "pickContact: the picker's presentation controller could not be observed " ++ | |
| 372 | "(absent, or already carrying a delegate this file will not displace); " ++ | |
| 373 | "if a swipe-down dismissal does not send contactPickerDidCancel: then " ++ | |
| 374 | "this call stays unanswered and every later one is refused", | |
| 375 | .{}, | |
| 376 | ); | |
| 377 | } | |
| 378 | } | |
| 379 | }; | |
| 380 | ||
| 381 | /// The answer for a full block pool, copied from `bridge_mobile_location`: | |
| 382 | /// `BridgeError` has no "Busy", `INVALID_PARAMETER` is the migration notes' | |
| 383 | /// designated stand-in, and the point is that the caller gets an explicit | |
| 384 | /// rejection instead of a promise that never settles. | |
| 385 | fn poolFull() bridge_error.BridgeError { | |
| 386 | std.log.warn( | |
| 387 | "pickContact refused: all {d} async slots are in flight", | |
| 388 | .{ios_async.max_in_flight}, | |
| 389 | ); | |
| 390 | return bridge_error.BridgeError.InvalidParameter; | |
| 391 | } | |
| 392 | ||
| 393 | /// The answer for a second `pickContact` while one is on screen. | |
| 394 | /// | |
| 395 | /// Deliberately *not* displacement. `bridge_mobile_location.zig` rejects the | |
| 396 | /// displaced first caller because CoreLocation's one-shot may genuinely never | |
| 397 | /// answer; a presented picker is the opposite situation — it is on screen, the | |
| 398 | /// user is looking at it, and it will answer. Refusing the newcomer keeps that | |
| 399 | /// promise alive. Swift does neither: it overwrites `pendingCallbackId` and the | |
| 400 | /// first caller waits forever on an untimed promise. | |
| 401 | /// | |
| 402 | /// Same `INVALID_PARAMETER` stand-in as `poolFull`, for the same reason — | |
| 403 | /// `BridgeError` has no word for "busy" — with a log line that says which of | |
| 404 | /// the two happened. | |
| 405 | fn alreadyPresented() bridge_error.BridgeError { | |
| 406 | std.log.warn( | |
| 407 | "pickContact refused: a contact picker is already presented and still waiting for an " ++ | |
| 408 | "answer; the first call is left alone rather than being stranded", | |
| 409 | .{}, | |
| 410 | ); | |
| 411 | return bridge_error.BridgeError.InvalidParameter; | |
| 412 | } | |
| 413 | ||
| 414 | // ============================================================================= | |
| 415 | // Payload parsing. Pure — no Objective-C — so the exact coercion Swift performs | |
| 416 | // is pinned by host tests on every platform. | |
| 417 | // ============================================================================= | |
| 418 | ||
| 419 | /// `multiple`, read the way `body["multiple"] as? Bool ?? false` reads it. | |
| 420 | /// | |
| 421 | /// A malformed or non-object `d` is `InvalidJSON` rather than a silent `false`. | |
| 422 | /// It is a Zig-only failure mode — `WKScriptMessage.body` is always a | |
| 423 | /// dictionary, so Swift never meets it — but guessing `false` for a body that | |
| 424 | /// could not be read would be acting on a default the page did not send. | |
| 425 | fn parseMultiple(allocator: std.mem.Allocator, data: []const u8) !bool { | |
| 426 | const parsed = std.json.parseFromSlice(std.json.Value, allocator, data, .{}) catch | |
| 427 | return bridge_error.BridgeError.InvalidJSON; | |
| 428 | defer parsed.deinit(); | |
| 429 | ||
| 430 | const root = switch (parsed.value) { | |
| 431 | .object => |obj| obj, | |
| 432 | else => return bridge_error.BridgeError.InvalidJSON, | |
| 433 | }; | |
| 434 | ||
| 435 | return multipleFrom(root.get("multiple")); | |
| 436 | } | |
| 437 | ||
| 438 | /// The `as? Bool ?? false` rule, as a total function. | |
| 439 | /// | |
| 440 | /// `options.multiple || false` in the injected JS is a fallback, not a | |
| 441 | /// coercion, so anything truthy reaches the wire unchanged: `1`, `"yes"`, `{}`. | |
| 442 | /// Swift's bridged `NSNumber as? Bool` then succeeds for exactly `0` and `1` | |
| 443 | /// and yields nil for everything else, which `?? false` collapses to false. So | |
| 444 | /// `pickContact({multiple: 2})` and `pickContact({multiple: 'yes'})` both open | |
| 445 | /// a *single*-selection picker, and reproducing that is the contract — reading | |
| 446 | /// them as "truthy, therefore multiple" would open a different picker than the | |
| 447 | /// shim opens for the same call. | |
| 448 | fn multipleFrom(value: ?std.json.Value) bool { | |
| 449 | const v = value orelse return false; | |
| 450 | return switch (v) { | |
| 451 | .bool => |b| b, | |
| 452 | .integer => |i| i == 1, | |
| 453 | // `NSNumber(value: 1.0) as? Bool` is true, `0.5` is nil. Only an exact | |
| 454 | // 1 is a yes. | |
| 455 | .float => |f| f == 1.0, | |
| 456 | // A string, an array, an object, JSON null, or a number too large for | |
| 457 | // an i64 (`number_string`). None of them survive `as? Bool`. | |
| 458 | else => false, | |
| 459 | }; | |
| 460 | } | |
| 461 | ||
| 462 | // ============================================================================= | |
| 463 | // Reply shaping. Pure — no Objective-C — so the exact bytes the page receives | |
| 464 | // are pinned by host tests. | |
| 465 | // ============================================================================= | |
| 466 | ||
| 467 | /// One `CNLabeledValue`, flattened. | |
| 468 | /// | |
| 469 | /// `value` is the phone number's `stringValue` or the email address; which wire | |
| 470 | /// key it lands under — `number` or `address` — is decided by the writer, not | |
| 471 | /// stored here, because `formatContact` uses two different key names for the | |
| 472 | /// same shape and getting them swapped is silent. | |
| 473 | const Labeled = struct { | |
| 474 | label: []const u8, | |
| 475 | value: []const u8, | |
| 476 | }; | |
| 477 | ||
| 478 | /// One contact, exactly as `formatContact` assembles it. | |
| 479 | /// | |
| 480 | /// The strings borrow whatever buffer they were read from. On the native path | |
| 481 | /// that is an `NSString`'s internal UTF-8 buffer, valid for the delegate | |
| 482 | /// callback's autorelease pool, and every one of them is copied into the JSON | |
| 483 | /// before the callback returns. | |
| 484 | const Contact = struct { | |
| 485 | id: []const u8, | |
| 486 | given_name: []const u8, | |
| 487 | family_name: []const u8, | |
| 488 | display_name: []const u8, | |
| 489 | phones: []const Labeled, | |
| 490 | emails: []const Labeled, | |
| 491 | }; | |
| 492 | ||
| 493 | fn appendJsonString( | |
| 494 | allocator: std.mem.Allocator, | |
| 495 | out: *std.ArrayListUnmanaged(u8), | |
| 496 | s: []const u8, | |
| 497 | ) !void { | |
| 498 | try out.append(allocator, '"'); | |
| 499 | // A contact's name, label and number are user data and will contain `"` and | |
| 500 | // `\` in the wild. This reply is replayed into the source | |
| 501 | // `evaluateJavaScript:` parses, so an unescaped quote is a syntax error in | |
| 502 | // the page rather than a wrong field. | |
| 503 | try bridge_error.appendJsonEscaped(allocator, out, s); | |
| 504 | try out.append(allocator, '"'); | |
| 505 | } | |
| 506 | ||
| 507 | fn appendLabeledArray( | |
| 508 | allocator: std.mem.Allocator, | |
| 509 | out: *std.ArrayListUnmanaged(u8), | |
| 510 | items: []const Labeled, | |
| 511 | comptime value_key: []const u8, | |
| 512 | ) !void { | |
| 513 | try out.append(allocator, '['); | |
| 514 | for (items, 0..) |item, i| { | |
| 515 | if (i != 0) try out.append(allocator, ','); | |
| 516 | try out.appendSlice(allocator, "{\"label\":"); | |
| 517 | try appendJsonString(allocator, out, item.label); | |
| 518 | try out.appendSlice(allocator, ",\"" ++ value_key ++ "\":"); | |
| 519 | try appendJsonString(allocator, out, item.value); | |
| 520 | try out.append(allocator, '}'); | |
| 521 | } | |
| 522 | try out.append(allocator, ']'); | |
| 523 | } | |
| 524 | ||
| 525 | /// One contact as a JSON object, in a fixed key order. | |
| 526 | /// | |
| 527 | /// Swift's `[String: Any]` has no order at all; fixing one here is what makes | |
| 528 | /// the bytes testable. The two `value_key` spellings are the part worth | |
| 529 | /// watching: phones are `number`, emails are `address`, and `formatContact` is | |
| 530 | /// the only authority for that. | |
| 531 | fn appendContact( | |
| 532 | allocator: std.mem.Allocator, | |
| 533 | out: *std.ArrayListUnmanaged(u8), | |
| 534 | contact: Contact, | |
| 535 | ) !void { | |
| 536 | try out.appendSlice(allocator, "{\"id\":"); | |
| 537 | try appendJsonString(allocator, out, contact.id); | |
| 538 | try out.appendSlice(allocator, ",\"givenName\":"); | |
| 539 | try appendJsonString(allocator, out, contact.given_name); | |
| 540 | try out.appendSlice(allocator, ",\"familyName\":"); | |
| 541 | try appendJsonString(allocator, out, contact.family_name); | |
| 542 | try out.appendSlice(allocator, ",\"displayName\":"); | |
| 543 | try appendJsonString(allocator, out, contact.display_name); | |
| 544 | try out.appendSlice(allocator, ",\"phoneNumbers\":"); | |
| 545 | try appendLabeledArray(allocator, out, contact.phones, "number"); | |
| 546 | try out.appendSlice(allocator, ",\"emailAddresses\":"); | |
| 547 | try appendLabeledArray(allocator, out, contact.emails, "address"); | |
| 548 | try out.append(allocator, '}'); | |
| 549 | } | |
| 550 | ||
| 551 | /// The `didSelectContact:` reply: a bare object. | |
| 552 | fn shapeContact(allocator: std.mem.Allocator, contact: Contact) ![]u8 { | |
| 553 | var out: std.ArrayListUnmanaged(u8) = .empty; | |
| 554 | errdefer out.deinit(allocator); | |
| 555 | try appendContact(allocator, &out, contact); | |
| 556 | return out.toOwnedSlice(allocator); | |
| 557 | } | |
| 558 | ||
| 559 | /// The `didSelectContacts:` reply: an array of objects. | |
| 560 | /// | |
| 561 | /// An empty selection is `[]`, which **resolves**. `contacts.map` over an empty | |
| 562 | /// array is `[]` in Swift and `test-bridges.html` reads `.length` off it, so | |
| 563 | /// turning "nothing selected" into an error or a cancel would break a path the | |
| 564 | /// shim answers successfully. | |
| 565 | fn shapeContacts(allocator: std.mem.Allocator, contacts: []const Contact) ![]u8 { | |
| 566 | var out: std.ArrayListUnmanaged(u8) = .empty; | |
| 567 | errdefer out.deinit(allocator); | |
| 568 | ||
| 569 | try out.append(allocator, '['); | |
| 570 | for (contacts, 0..) |contact, i| { | |
| 571 | if (i != 0) try out.append(allocator, ','); | |
| 572 | try appendContact(allocator, &out, contact); | |
| 573 | } | |
| 574 | try out.append(allocator, ']'); | |
| 575 | ||
| 576 | return out.toOwnedSlice(allocator); | |
| 577 | } | |
| 578 | ||
| 579 | // ============================================================================= | |
| 580 | // Objective-C: everything looked up once at dispatch, then a walk that cannot | |
| 581 | // look anything up. | |
| 582 | // ============================================================================= | |
| 583 | ||
| 584 | /// The Info.plist key `packages/ios/src/index.ts:189` writes if and only if | |
| 585 | /// `config.enableContacts`. | |
| 586 | const key_contacts_usage = "NSContactsUsageDescription"; | |
| 587 | ||
| 588 | /// `NSUTF8StringEncoding`. Used only to ask a string how long it really is, so | |
| 589 | /// a NUL-truncated read can be told from a short string. | |
| 590 | const ns_utf8_string_encoding: c_ulong = 4; | |
| 591 | ||
| 592 | /// `CNContactFormatterStyleFullName`. A header enum constant with `FullName = 0` | |
| 593 | /// and `PhoneticFullName = 1`, so this one is safe to spell out rather than | |
| 594 | /// `dlsym`. | |
| 595 | const cn_contact_formatter_style_full_name: c_long = 0; | |
| 596 | ||
| 597 | fn selector(name: [*:0]const u8) !Id { | |
| 598 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 599 | return objc.sel_registerName(name) orelse error.SelectorNotFound; | |
| 600 | } | |
| 601 | ||
| 602 | /// The main bundle's Info.plist value for `key`, or null when it has none. | |
| 603 | /// | |
| 604 | /// Errors rather than answering null when the runtime itself will not | |
| 605 | /// cooperate: "there is no NSBundle class" and "this app was not built with | |
| 606 | /// contacts enabled" are different facts, and collapsing them would blame the | |
| 607 | /// app's configuration for a broken process. Same shape as | |
| 608 | /// `bridge_mobile_location.zig`'s gate, which is private to that file. | |
| 609 | fn infoPlistValue(comptime key: [*:0]const u8) !Id { | |
| 610 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 611 | ||
| 612 | const NSBundle = objc.objc_getClass("NSBundle") orelse return error.ClassNotFound; | |
| 613 | const sel_main = objc.sel_registerName("mainBundle") orelse return error.SelectorNotFound; | |
| 614 | const bundle = objc.msgSendId(NSBundle, sel_main) orelse return error.NoMainBundle; | |
| 615 | ||
| 616 | const NSString = objc.objc_getClass("NSString") orelse return error.ClassNotFound; | |
| 617 | const sel_string = objc.sel_registerName("stringWithUTF8String:") orelse | |
| 618 | return error.SelectorNotFound; | |
| 619 | const ns_key = objc.msgSendId1(NSString, sel_string, key) orelse return error.NativeCallFailed; | |
| 620 | ||
| 621 | const sel_lookup = objc.sel_registerName("objectForInfoDictionaryKey:") orelse | |
| 622 | return error.SelectorNotFound; | |
| 623 | return objc.msgSendId1(bundle, sel_lookup, ns_key); | |
| 624 | } | |
| 625 | ||
| 626 | /// Refuse when the app was not built with `enableContacts`. | |
| 627 | /// | |
| 628 | /// Checked first, matching Swift's `if config.enableContacts` guarding the whole | |
| 629 | /// case. The key is evidence of that flag and nothing more — see the module | |
| 630 | /// comment: `CNContactPickerViewController` needs no Contacts authorization, so | |
| 631 | /// this is not the framework's precondition being enforced. | |
| 632 | fn requireContactsConfigured() !void { | |
| 633 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 634 | ||
| 635 | if ((try infoPlistValue(key_contacts_usage)) == null) { | |
| 636 | std.log.warn( | |
| 637 | "pickContact refused: Info.plist has no {s}, so this app was not built with " ++ | |
| 638 | "contacts enabled", | |
| 639 | .{key_contacts_usage}, | |
| 640 | ); | |
| 641 | return bridge_error.BridgeError.PermissionDenied; | |
| 642 | } | |
| 643 | } | |
| 644 | ||
| 645 | /// Everything a delegate callback needs, resolved while a synchronous error can | |
| 646 | /// still reach the page. | |
| 647 | /// | |
| 648 | /// The callbacks run long after the dispatch frame is gone, where a failed | |
| 649 | /// `sel_registerName` could only be logged. Resolving here turns that whole | |
| 650 | /// class of failure into an ordinary rejection. | |
| 651 | /// | |
| 652 | /// Two *class* objects ride along for the same reason. `CNContactFormatter` and | |
| 653 | /// `CNLabeledValue` are used as receivers of class methods | |
| 654 | /// (`stringFromContact:style:`, `localizedStringForLabel:`), so a missing | |
| 655 | /// Contacts.framework has to be found here rather than inside the callback. | |
| 656 | /// They are guarded separately from `CNContactPickerViewController` because | |
| 657 | /// they come from a different framework. | |
| 658 | const Sels = struct { | |
| 659 | // Contacts.framework classes, as receivers of class methods. | |
| 660 | formatter_class: Id, | |
| 661 | labeled_value_class: Id, | |
| 662 | string_class: Id, | |
| 663 | ||
| 664 | // NSArray | |
| 665 | count: Id, | |
| 666 | object_at: Id, | |
| 667 | ||
| 668 | // CNContact | |
| 669 | identifier: Id, | |
| 670 | given_name: Id, | |
| 671 | family_name: Id, | |
| 672 | phone_numbers: Id, | |
| 673 | email_addresses: Id, | |
| 674 | ||
| 675 | // CNContactFormatter (class method) | |
| 676 | string_from_contact: Id, | |
| 677 | ||
| 678 | // CNLabeledValue. One class, not two: the Swift generics | |
| 679 | // `CNLabeledValue<CNPhoneNumber>` and `CNLabeledValue<NSString>` are the | |
| 680 | // same Objective-C class. | |
| 681 | label: Id, | |
| 682 | value: Id, | |
| 683 | localized_string_for_label: Id, | |
| 684 | ||
| 685 | // CNPhoneNumber | |
| 686 | string_value: Id, | |
| 687 | ||
| 688 | // NSString | |
| 689 | empty_string: Id, | |
| 690 | utf8: Id, | |
| 691 | length_of_bytes: Id, | |
| 692 | ||
| 693 | fn resolve() !Sels { | |
| 694 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 695 | ||
| 696 | const formatter = objc.objc_getClass("CNContactFormatter") orelse { | |
| 697 | std.log.err( | |
| 698 | "pickContact refused: this process has no CNContactFormatter; " ++ | |
| 699 | "Contacts.framework is not linked", | |
| 700 | .{}, | |
| 701 | ); | |
| 702 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 703 | }; | |
| 704 | const labeled = objc.objc_getClass("CNLabeledValue") orelse { | |
| 705 | std.log.err( | |
| 706 | "pickContact refused: this process has no CNLabeledValue; " ++ | |
| 707 | "Contacts.framework is not linked", | |
| 708 | .{}, | |
| 709 | ); | |
| 710 | return bridge_error.BridgeError.PlatformNotSupported; | |
| 711 | }; | |
| 712 | const string_class = objc.objc_getClass("NSString") orelse return error.ClassNotFound; | |
| 713 | ||
| 714 | return .{ | |
| 715 | .formatter_class = formatter, | |
| 716 | .labeled_value_class = labeled, | |
| 717 | .string_class = string_class, | |
| 718 | ||
| 719 | .count = try selector("count"), | |
| 720 | .object_at = try selector("objectAtIndex:"), | |
| 721 | ||
| 722 | .identifier = try selector("identifier"), | |
| 723 | .given_name = try selector("givenName"), | |
| 724 | .family_name = try selector("familyName"), | |
| 725 | .phone_numbers = try selector("phoneNumbers"), | |
| 726 | .email_addresses = try selector("emailAddresses"), | |
| 727 | ||
| 728 | .string_from_contact = try selector("stringFromContact:style:"), | |
| 729 | ||
| 730 | .label = try selector("label"), | |
| 731 | .value = try selector("value"), | |
| 732 | .localized_string_for_label = try selector("localizedStringForLabel:"), | |
| 733 | ||
| 734 | .string_value = try selector("stringValue"), | |
| 735 | ||
| 736 | .empty_string = try selector("string"), | |
| 737 | .utf8 = try selector("UTF8String"), | |
| 738 | .length_of_bytes = try selector("lengthOfBytesUsingEncoding:"), | |
| 739 | }; | |
| 740 | } | |
| 741 | }; | |
| 742 | ||
| 743 | /// One `NSString` as bytes, or a refusal. | |
| 744 | /// | |
| 745 | /// The truncation check is why this is not one line. `UTF8String` hands back a | |
| 746 | /// NUL-terminated buffer, so a value containing U+0000 — which | |
| 747 | /// `JSONSerialization` would have preserved on the Swift side — reads back as | |
| 748 | /// its prefix. `lengthOfBytesUsingEncoding:` counts the real encoded bytes, so a | |
| 749 | /// mismatch is exactly that case, and reporting a prefix as the whole name is | |
| 750 | /// the one thing worse than failing. | |
| 751 | /// | |
| 752 | /// The returned slice borrows the string's internal buffer, valid for the | |
| 753 | /// current autorelease pool; every caller copies it into the reply before | |
| 754 | /// returning. | |
| 755 | fn readString(ns: Id, sels: Sels) ![]const u8 { | |
| 756 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 757 | if (ns == null) return error.NilNativeString; | |
| 758 | ||
| 759 | const Utf8Fn = *const fn (Id, Id) callconv(.c) ?[*:0]const u8; | |
| 760 | const utf8: Utf8Fn = @ptrCast(&objc.objc_msgSend); | |
| 761 | const cstr = utf8(ns, sels.utf8) orelse return error.NativeCallFailed; | |
| 762 | const text = std.mem.span(cstr); | |
| 763 | ||
| 764 | const LenFn = *const fn (Id, Id, c_ulong) callconv(.c) c_ulong; | |
| 765 | const len_of: LenFn = @ptrCast(&objc.objc_msgSend); | |
| 766 | if (len_of(ns, sels.length_of_bytes, ns_utf8_string_encoding) != text.len) { | |
| 767 | return error.EmbeddedNulInNativeString; | |
| 768 | } | |
| 769 | ||
| 770 | return text; | |
| 771 | } | |
| 772 | ||
| 773 | /// `[[NSString string]]` — an empty, autoreleased `NSString`. | |
| 774 | /// | |
| 775 | /// Needed because `CNLabeledValue.label` is nullable and Swift passes `""` in | |
| 776 | /// its place (`phone.label ?? ""`) before asking for the localized form. Passing | |
| 777 | /// nil instead would be a different call than the one being ported. | |
| 778 | fn emptyString(sels: Sels) !Id { | |
| 779 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 780 | return objc.msgSendId(sels.string_class, sels.empty_string) orelse error.NativeCallFailed; | |
| 781 | } | |
| 782 | ||
| 783 | /// `+[CNLabeledValue localizedStringForLabel:]` on `labeled.label ?? ""`. | |
| 784 | fn readLocalizedLabel(labeled: Id, sels: Sels) ![]const u8 { | |
| 785 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 786 | ||
| 787 | const raw = objc.msgSendId(labeled, sels.label) orelse try emptyString(sels); | |
| 788 | const localized = objc.msgSendId1(sels.labeled_value_class, sels.localized_string_for_label, raw) orelse | |
| 789 | return error.NativeCallFailed; | |
| 790 | return readString(localized, sels); | |
| 791 | } | |
| 792 | ||
| 793 | /// Which kind of `CNLabeledValue` array is being walked. | |
| 794 | /// | |
| 795 | /// The two differ in exactly one step: a phone's `value` is a `CNPhoneNumber` | |
| 796 | /// and needs `stringValue`, while an email's `value` already *is* an | |
| 797 | /// `NSString`. Sending `stringValue` to an `NSString` would be an unrecognised | |
| 798 | /// selector, which is a SIGABRT rather than an error to map — so this is an | |
| 799 | /// enum rather than an optional selector that could arrive null. | |
| 800 | const LabeledKind = enum { phone, email }; | |
| 801 | ||
| 802 | /// Walk an `NSArray<CNLabeledValue *>` into `Labeled` entries. | |
| 803 | fn readLabeledValues( | |
| 804 | allocator: std.mem.Allocator, | |
| 805 | array: Id, | |
| 806 | sels: Sels, | |
| 807 | comptime kind: LabeledKind, | |
| 808 | ) ![]Labeled { | |
| 809 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 810 | // Both `phoneNumbers` and `emailAddresses` are declared non-null and answer | |
| 811 | // an empty array for a contact with none. A nil here would mean the | |
| 812 | // framework broke its own contract, and "this contact has no numbers" is a | |
| 813 | // claim there would be no basis for. | |
| 814 | if (array == null) return error.NativeCallFailed; | |
| 815 | ||
| 816 | const CountFn = *const fn (Id, Id) callconv(.c) c_ulong; | |
| 817 | const count_of: CountFn = @ptrCast(&objc.objc_msgSend); | |
| 818 | const total = count_of(array, sels.count); | |
| 819 | ||
| 820 | var out: std.ArrayListUnmanaged(Labeled) = .empty; | |
| 821 | errdefer out.deinit(allocator); | |
| 822 | ||
| 823 | var i: c_ulong = 0; | |
| 824 | while (i < total) : (i += 1) { | |
| 825 | const entry = objc.msgSendId1(array, sels.object_at, i) orelse return error.NativeCallFailed; | |
| 826 | ||
| 827 | const label = try readLocalizedLabel(entry, sels); | |
| 828 | ||
| 829 | const raw_value = objc.msgSendId(entry, sels.value) orelse return error.NativeCallFailed; | |
| 830 | const string_value = switch (kind) { | |
| 831 | .phone => objc.msgSendId(raw_value, sels.string_value) orelse | |
| 832 | return error.NativeCallFailed, | |
| 833 | .email => raw_value, | |
| 834 | }; | |
| 835 | ||
| 836 | try out.append(allocator, .{ .label = label, .value = try readString(string_value, sels) }); | |
| 837 | } | |
| 838 | ||
| 839 | return out.toOwnedSlice(allocator); | |
| 840 | } | |
| 841 | ||
| 842 | /// Read one `CNContact` the way `formatContact` reads it. | |
| 843 | /// | |
| 844 | /// `displayName` is the one field where nil is expected and is *not* a failure: | |
| 845 | /// `CNContactFormatter.string(from:style:)` returns `String?` and Swift coalesces | |
| 846 | /// it with `?? ""`. Every other field is declared non-null — `identifier`, | |
| 847 | /// `givenName` and `familyName` answer `@""` for an unset name — so nil there is | |
| 848 | /// a broken read and is refused rather than papered over with an empty string. | |
| 849 | fn readContact(allocator: std.mem.Allocator, contact: Id, sels: Sels) !Contact { | |
| 850 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 851 | if (contact == null) return error.NativeCallFailed; | |
| 852 | ||
| 853 | const FormatFn = *const fn (Id, Id, Id, c_long) callconv(.c) Id; | |
| 854 | const format: FormatFn = @ptrCast(&objc.objc_msgSend); | |
| 855 | const formatted = format( | |
| 856 | sels.formatter_class, | |
| 857 | sels.string_from_contact, | |
| 858 | contact, | |
| 859 | cn_contact_formatter_style_full_name, | |
| 860 | ); | |
| 861 | ||
| 862 | const phones = try readLabeledValues( | |
| 863 | allocator, | |
| 864 | objc.msgSendId(contact, sels.phone_numbers), | |
| 865 | sels, | |
| 866 | .phone, | |
| 867 | ); | |
| 868 | errdefer allocator.free(phones); | |
| 869 | ||
| 870 | const emails = try readLabeledValues( | |
| 871 | allocator, | |
| 872 | objc.msgSendId(contact, sels.email_addresses), | |
| 873 | sels, | |
| 874 | .email, | |
| 875 | ); | |
| 876 | errdefer allocator.free(emails); | |
| 877 | ||
| 878 | return .{ | |
| 879 | .id = try readString(objc.msgSendId(contact, sels.identifier), sels), | |
| 880 | .given_name = try readString(objc.msgSendId(contact, sels.given_name), sels), | |
| 881 | .family_name = try readString(objc.msgSendId(contact, sels.family_name), sels), | |
| 882 | // Swift's `?? ""`, and only here. | |
| 883 | .display_name = if (formatted == null) "" else try readString(formatted, sels), | |
| 884 | .phones = phones, | |
| 885 | .emails = emails, | |
| 886 | }; | |
| 887 | } | |
| 888 | ||
| 889 | /// Release the two slices `readContact` allocated. The strings inside are | |
| 890 | /// borrowed from Objective-C and are not ours to free. | |
| 891 | fn freeContact(allocator: std.mem.Allocator, contact: Contact) void { | |
| 892 | allocator.free(contact.phones); | |
| 893 | allocator.free(contact.emails); | |
| 894 | } | |
| 895 | ||
| 896 | // ============================================================================= | |
| 897 | // The delegate class, built at runtime. | |
| 898 | // ============================================================================= | |
| 899 | ||
| 900 | /// Deliberately distinct from every other class this process registers. The | |
| 901 | /// factory looks a name up before allocating, so two files sharing a name would | |
| 902 | /// mean whichever registered second silently adopts the other's IMPs. | |
| 903 | const delegate_class_name = "CraftIOSContactPickerDelegate"; | |
| 904 | ||
| 905 | /// The delegate instance, held for the life of the process. | |
| 906 | /// | |
| 907 | /// `CNContactPickerViewController` holds its delegate **weakly**; | |
| 908 | /// `ios_delegate.instantiate` hands back a +1 object and does not keep it. This | |
| 909 | /// var is the strong reference, and dropping it would be a use-after-free the | |
| 910 | /// first time the user taps Cancel — not a leak. | |
| 911 | var delegate_instance: Id = null; | |
| 912 | ||
| 913 | /// Every method the delegate class carries, always all of them. | |
| 914 | /// | |
| 915 | /// All three of Swift's `CNContactPickerDelegate` methods are here. | |
| 916 | /// `contactPicker:didSelectContacts:` is the plural selector Swift's | |
| 917 | /// `didSelect contacts: [CNContact]` compiles to and is the entire | |
| 918 | /// `multiple:true` reply path — the runtime dispatches delegate methods through | |
| 919 | /// `respondsToSelector:`, so omitting it would be a silent no-op and a stranded | |
| 920 | /// promise. `presentationControllerDidDismiss:` is the fourth and is not | |
| 921 | /// Swift's: it belongs to `UIAdaptivePresentationControllerDelegate` and is the | |
| 922 | /// swipe-down belt `attachDismissObserver` installs. Neither protocol is | |
| 923 | /// declared on the class, because `respondsToSelector:` is what UIKit actually | |
| 924 | /// asks — the same call `bridge_mobile_imagepicker.zig` records. | |
| 925 | /// | |
| 926 | /// One fixed set rather than a per-call one: `defineClass` is idempotent by | |
| 927 | /// name, so varying the methods would mean inventing a second class. | |
| 928 | fn delegateMethods() [4]ios_delegate.Method { | |
| 929 | return .{ | |
| 930 | // - (void)contactPicker:(CNContactPickerViewController *)picker | |
| 931 | // didSelectContact:(CNContact *)contact | |
| 932 | .{ | |
| 933 | .selector = "contactPicker:didSelectContact:", | |
| 934 | .imp = @ptrCast(&didSelectContact), | |
| 935 | .types = ios_delegate.enc.void_two_objects, | |
| 936 | }, | |
| 937 | // - (void)contactPicker:(CNContactPickerViewController *)picker | |
| 938 | // didSelectContacts:(NSArray<CNContact *> *)contacts | |
| 939 | .{ | |
| 940 | .selector = "contactPicker:didSelectContacts:", | |
| 941 | .imp = @ptrCast(&didSelectContacts), | |
| 942 | .types = ios_delegate.enc.void_two_objects, | |
| 943 | }, | |
| 944 | // - (void)contactPickerDidCancel:(CNContactPickerViewController *)picker | |
| 945 | .{ | |
| 946 | .selector = "contactPickerDidCancel:", | |
| 947 | .imp = @ptrCast(&didCancel), | |
| 948 | .types = ios_delegate.enc.void_one_object, | |
| 949 | }, | |
| 950 | // - (void)presentationControllerDidDismiss:(UIPresentationController *)pc | |
| 951 | // The swipe-down belt. iOS 13+; on anything older it is never sent. | |
| 952 | .{ | |
| 953 | .selector = "presentationControllerDidDismiss:", | |
| 954 | .imp = @ptrCast(&didDismissInteractively), | |
| 955 | .types = ios_delegate.enc.void_one_object, | |
| 956 | }, | |
| 957 | }; | |
| 958 | } | |
| 959 | ||
| 960 | /// Register the class once and keep one instance alive. | |
| 961 | fn ensureDelegate() !Id { | |
| 962 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 963 | if (delegate_instance) |existing| return existing; | |
| 964 | ||
| 965 | const methods = delegateMethods(); | |
| 966 | const cls = try ios_delegate.defineClass(delegate_class_name, "NSObject", &methods); | |
| 967 | ||
| 968 | const instance = (try ios_delegate.instantiate(cls)) orelse return error.NativeCallFailed; | |
| 969 | delegate_instance = instance; | |
| 970 | return instance; | |
| 971 | } | |
| 972 | ||
| 973 | /// The three selectors the swipe-down belt needs, resolved at dispatch. | |
| 974 | const DismissSels = struct { | |
| 975 | /// `-[UIViewController presentationController]`. | |
| 976 | presentation: Id, | |
| 977 | /// `-[UIPresentationController delegate]`, read so an existing delegate is | |
| 978 | /// never displaced. | |
| 979 | delegate: Id, | |
| 980 | /// `-[UIPresentationController setDelegate:]` — the same `setDelegate:` the | |
| 981 | /// picker's own delegate is installed with. | |
| 982 | set_delegate: Id, | |
| 983 | }; | |
| 984 | ||
| 985 | /// Point the picker's presentation controller at this module's delegate, so an | |
| 986 | /// interactive dismissal reaches `presentationControllerDidDismiss:`. Returns | |
| 987 | /// whether it was attached. | |
| 988 | /// | |
| 989 | /// `CNContactPickerViewController` presents as a sheet on iOS 13+, and a | |
| 990 | /// swipe-down is widely reported not to send `contactPickerDidCancel:`. That | |
| 991 | /// report is verified on no device in this repo, so this is a belt and not a | |
| 992 | /// fix: it costs two messages, and if the report is right it is the only thing | |
| 993 | /// that ever frees `pending` after a swipe. It matters more here than in Swift, | |
| 994 | /// because this module *refuses* later calls while one is pending — a stranded | |
| 995 | /// ticket disables `pickContact` for the life of the process, where Swift | |
| 996 | /// merely strands the one promise. | |
| 997 | /// | |
| 998 | /// A presentation controller that already carries a delegate is left alone and | |
| 999 | /// reported as not attached: displacing one would change how the picker manages | |
| 1000 | /// its own adaptive presentation, which is a new bug in exchange for a belt. | |
| 1001 | /// | |
| 1002 | /// Idempotent against the real cancel. UIKit sends | |
| 1003 | /// `presentationControllerDidDismiss:` only for a user-driven dismissal, never | |
| 1004 | /// for a programmatic one, so it cannot follow a pick or a Cancel that already | |
| 1005 | /// answered — and if it did anyway, `takePending` has already emptied the slot | |
| 1006 | /// and `ios_async`'s generation counter would drop the second delivery. | |
| 1007 | fn attachDismissObserver(picker: Id, delegate: Id, sels: DismissSels) bool { | |
| 1008 | if (!is_darwin) return false; | |
| 1009 | ||
| 1010 | const presentation = objc.msgSendId(picker, sels.presentation) orelse return false; | |
| 1011 | if (objc.msgSendId(presentation, sels.delegate) != null) return false; | |
| 1012 | ||
| 1013 | objc.msgSendVoid1(presentation, sels.set_delegate, delegate); | |
| 1014 | return true; | |
| 1015 | } | |
| 1016 | ||
| 1017 | // ============================================================================= | |
| 1018 | // One ticket, one picker, one mutex. | |
| 1019 | // | |
| 1020 | // A picker is modal and serves exactly one call, so unlike the location | |
| 1021 | // one-shot there is never a reason to displace: while `pending` is set the | |
| 1022 | // picker is on screen and the user is looking at it. The mutex is held even | |
| 1023 | // though UIKit delivers these callbacks on the main thread, because "it should | |
| 1024 | // always be the main thread" is not a guard. | |
| 1025 | // ============================================================================= | |
| 1026 | ||
| 1027 | const Pending = struct { | |
| 1028 | ticket: ios_async.Ticket, | |
| 1029 | sels: Sels, | |
| 1030 | }; | |
| 1031 | ||
| 1032 | var pending: ?Pending = null; | |
| 1033 | var pending_mutex: compat_mutex.Mutex = .{}; | |
| 1034 | ||
| 1035 | /// Record the call the delegate will answer. False means one is already | |
| 1036 | /// recorded, and the caller must refuse rather than overwrite — an overwrite | |
| 1037 | /// would strand a promise that was about to be settled. | |
| 1038 | fn publishPending(call: Pending) bool { | |
| 1039 | pending_mutex.lock(); | |
| 1040 | defer pending_mutex.unlock(); | |
| 1041 | if (pending != null) return false; | |
| 1042 | pending = call; | |
| 1043 | return true; | |
| 1044 | } | |
| 1045 | ||
| 1046 | /// Read and clear. Clearing is what makes a second delegate call — a duplicate | |
| 1047 | /// fire, a cancel that races a selection — a no-op rather than a second reply | |
| 1048 | /// to a promise that has already settled. | |
| 1049 | fn takePending() ?Pending { | |
| 1050 | pending_mutex.lock(); | |
| 1051 | defer pending_mutex.unlock(); | |
| 1052 | const call = pending; | |
| 1053 | pending = null; | |
| 1054 | return call; | |
| 1055 | } | |
| 1056 | ||
| 1057 | // ============================================================================= | |
| 1058 | // The delegate methods. | |
| 1059 | // | |
| 1060 | // None replies directly: `evaluateJavaScript` is main-thread-only *and* the | |
| 1061 | // `request_context` that names the waiting call is long gone, so the finished | |
| 1062 | // JSON goes to `ios_async.deliverJson` (or `deliverError`), which hops to the | |
| 1063 | // main queue and answers under the id captured back at dispatch. | |
| 1064 | // | |
| 1065 | // Plain `fn`, never `export`: `@ptrCast(&f)` works either way and an exported | |
| 1066 | // name could collide with a desktop module in the same host-test binary. | |
| 1067 | // | |
| 1068 | // No `dismissViewControllerAnimated:` in any of them. See the module comment — | |
| 1069 | // `CNContactPickerViewController` is a remote view controller that takes itself | |
| 1070 | // down, Swift dismisses it nowhere, and a second dismissal would target | |
| 1071 | // whatever else is modal. `didDismissInteractively` observes a dismissal the | |
| 1072 | // user performed; it never asks for one. | |
| 1073 | // ============================================================================= | |
| 1074 | ||
| 1075 | fn didSelectContact(_: Id, _: Id, _: Id, contact: Id) callconv(.c) void { | |
| 1076 | if (!is_darwin) return; | |
| 1077 | ||
| 1078 | const call = takePending() orelse { | |
| 1079 | std.log.warn( | |
| 1080 | "pickContact: a contact was selected with no request waiting; ignored rather than " ++ | |
| 1081 | "answered to whoever holds the slot next", | |
| 1082 | .{}, | |
| 1083 | ); | |
| 1084 | return; | |
| 1085 | }; | |
| 1086 | ||
| 1087 | const allocator = std.heap.c_allocator; | |
| 1088 | ||
| 1089 | const one = readContact(allocator, contact, call.sels) catch |err| { | |
| 1090 | std.log.err( | |
| 1091 | "pickContact: could not read the selected CNContact ({}); rejecting rather than " ++ | |
| 1092 | "replying with a contact that was not read", | |
| 1093 | .{err}, | |
| 1094 | ); | |
| 1095 | ios_async.deliverError(call.ticket); | |
| 1096 | return; | |
| 1097 | }; | |
| 1098 | defer freeContact(allocator, one); | |
| 1099 | ||
| 1100 | const json = shapeContact(allocator, one) catch |err| { | |
| 1101 | std.log.err("pickContact: could not shape the contact reply ({}); rejecting", .{err}); | |
| 1102 | ios_async.deliverError(call.ticket); | |
| 1103 | return; | |
| 1104 | }; | |
| 1105 | defer allocator.free(json); | |
| 1106 | ||
| 1107 | ios_async.deliverJson(call.ticket, json); | |
| 1108 | } | |
| 1109 | ||
| 1110 | fn didSelectContacts(_: Id, _: Id, _: Id, contacts: Id) callconv(.c) void { | |
| 1111 | if (!is_darwin) return; | |
| 1112 | ||
| 1113 | const call = takePending() orelse { | |
| 1114 | std.log.warn( | |
| 1115 | "pickContact: contacts were selected with no request waiting; ignored rather than " ++ | |
| 1116 | "answered to whoever holds the slot next", | |
| 1117 | .{}, | |
| 1118 | ); | |
| 1119 | return; | |
| 1120 | }; | |
| 1121 | ||
| 1122 | const allocator = std.heap.c_allocator; | |
| 1123 | ||
| 1124 | const list = readContacts(allocator, contacts, call.sels) catch |err| { | |
| 1125 | std.log.err( | |
| 1126 | "pickContact: could not read the selected CNContacts ({}); rejecting rather than " ++ | |
| 1127 | "replying with a selection that was not read", | |
| 1128 | .{err}, | |
| 1129 | ); | |
| 1130 | ios_async.deliverError(call.ticket); | |
| 1131 | return; | |
| 1132 | }; | |
| 1133 | defer { | |
| 1134 | for (list) |one| freeContact(allocator, one); | |
| 1135 | allocator.free(list); | |
| 1136 | } | |
| 1137 | ||
| 1138 | const json = shapeContacts(allocator, list) catch |err| { | |
| 1139 | std.log.err("pickContact: could not shape the contacts reply ({}); rejecting", .{err}); | |
| 1140 | ios_async.deliverError(call.ticket); | |
| 1141 | return; | |
| 1142 | }; | |
| 1143 | defer allocator.free(json); | |
| 1144 | ||
| 1145 | // An empty selection is `[]` and resolves — see `shapeContacts`. | |
| 1146 | ios_async.deliverJson(call.ticket, json); | |
| 1147 | } | |
| 1148 | ||
| 1149 | /// Walk `NSArray<CNContact *>`, reading each contact. | |
| 1150 | /// | |
| 1151 | /// A nil array is refused rather than answered `[]`: the delegate parameter is | |
| 1152 | /// `[CNContact]`, non-optional, so nil would mean the framework broke its own | |
| 1153 | /// contract and "the user selected nothing" is a claim with no basis. | |
| 1154 | fn readContacts(allocator: std.mem.Allocator, contacts: Id, sels: Sels) ![]Contact { | |
| 1155 | if (!is_darwin) return error.UnsupportedPlatform; | |
| 1156 | if (contacts == null) return error.NativeCallFailed; | |
| 1157 | ||
| 1158 | const CountFn = *const fn (Id, Id) callconv(.c) c_ulong; | |
| 1159 | const count_of: CountFn = @ptrCast(&objc.objc_msgSend); | |
| 1160 | const total = count_of(contacts, sels.count); | |
| 1161 | ||
| 1162 | var out: std.ArrayListUnmanaged(Contact) = .empty; | |
| 1163 | errdefer { | |
| 1164 | for (out.items) |one| freeContact(allocator, one); | |
| 1165 | out.deinit(allocator); | |
| 1166 | } | |
| 1167 | ||
| 1168 | var i: c_ulong = 0; | |
| 1169 | while (i < total) : (i += 1) { | |
| 1170 | const contact = objc.msgSendId1(contacts, sels.object_at, i) orelse | |
| 1171 | return error.NativeCallFailed; | |
| 1172 | try out.append(allocator, try readContact(allocator, contact, sels)); | |
| 1173 | } | |
| 1174 | ||
| 1175 | return out.toOwnedSlice(allocator); | |
| 1176 | } | |
| 1177 | ||
| 1178 | /// The user tapped Cancel. | |
| 1179 | /// | |
| 1180 | /// A **rejection**, matching `rejectCallback(pendingCallbackId, error: "Cancelled")` | |
| 1181 | /// — never a resolve. Replying `{"cancelled":true}` here would be a success for | |
| 1182 | /// a pick that did not happen, and the page's `catch` (which is where | |
| 1183 | /// `test-bridges.html` prints the outcome) would never run. | |
| 1184 | /// | |
| 1185 | /// The code and message the page sees are `NATIVE_CALL_FAILED` / | |
| 1186 | /// `"Native API call failed"` rather than Swift's `CRAFT_ERROR` / `"Cancelled"`. | |
| 1187 | /// That is `ios_async.deliverError`'s fixed wording and it is genuinely wrong | |
| 1188 | /// about the cause; the module comment records what it would take to fix, and | |
| 1189 | /// why inventing a second reply path here would be worse. | |
| 1190 | fn didCancel(_: Id, _: Id, _: Id) callconv(.c) void { | |
| 1191 | if (!is_darwin) return; | |
| 1192 | ||
| 1193 | const call = takePending() orelse { | |
| 1194 | std.log.info("pickContact: a cancel arrived with no request waiting; ignored", .{}); | |
| 1195 | return; | |
| 1196 | }; | |
| 1197 | ||
| 1198 | std.log.info( | |
| 1199 | "pickContact: the user cancelled; rejecting the call (as CRAFT_ERROR/\"Cancelled\" in " ++ | |
| 1200 | "Swift, as NATIVE_CALL_FAILED here)", | |
| 1201 | .{}, | |
| 1202 | ); | |
| 1203 | // A Cancel is not a native failure: the call worked and the answer is | |
| 1204 | // "no". Reporting NativeCallFailed sends whoever reads the error looking | |
| 1205 | // for a bug that is not there. | |
| 1206 | ios_async.deliverErrorCode(call.ticket, bridge_error.BridgeError.Cancelled); | |
| 1207 | } | |
| 1208 | ||
| 1209 | /// The user swiped the picker away. | |
| 1210 | /// | |
| 1211 | /// `-presentationControllerDidDismiss:`, and the only thing that answers a | |
| 1212 | /// dismissal `contactPickerDidCancel:` is reported not to follow. A | |
| 1213 | /// **rejection**, for the same reason a Cancel is one: nothing was picked, so | |
| 1214 | /// resolving anything here would be a success for a pick that did not happen. | |
| 1215 | /// | |
| 1216 | /// Reached with the slot already empty whenever a real callback got there first | |
| 1217 | /// — a Cancel that did send, or a pick — in which case this is a no-op rather | |
| 1218 | /// than a second answer. | |
| 1219 | /// | |
| 1220 | /// Same `NATIVE_CALL_FAILED` / `"Native API call failed"` wording as `didCancel` | |
| 1221 | /// and wrong about the cause in the same way; see the module comment for where | |
| 1222 | /// that is fixed. | |
| 1223 | fn didDismissInteractively(_: Id, _: Id, _: Id) callconv(.c) void { | |
| 1224 | if (!is_darwin) return; | |
| 1225 | ||
| 1226 | const call = takePending() orelse { | |
| 1227 | std.log.info( | |
| 1228 | "pickContact: the picker was dismissed with no request waiting; ignored " ++ | |
| 1229 | "(the cancel or the pick already answered)", | |
| 1230 | .{}, | |
| 1231 | ); | |
| 1232 | return; | |
| 1233 | }; | |
| 1234 | ||
| 1235 | std.log.warn( | |
| 1236 | "pickContact: the picker was dismissed interactively without sending " ++ | |
| 1237 | "contactPickerDidCancel:; rejecting the call rather than leaving it unanswered " ++ | |
| 1238 | "on a promise that has no timeout", | |
| 1239 | .{}, | |
| 1240 | ); | |
| 1241 | ios_async.deliverError(call.ticket); | |
| 1242 | } | |
| 1243 | ||
| 1244 | // ============================================================================= | |
| 1245 | // Tests — host-only. | |
| 1246 | // | |
| 1247 | // Everything that decides page-visible bytes is pure and pinned here: routing | |
| 1248 | // in both directions, the `as? Bool ?? false` coercion, the six keys and their | |
| 1249 | // order, the two different value keys for phones and emails, the empty-array | |
| 1250 | // resolve, escaping, and the concurrency rule. | |
| 1251 | // | |
| 1252 | // Nothing here constructs a `CNContactPickerViewController` or presents | |
| 1253 | // anything. On a macOS host that class does not exist at all (macOS has | |
| 1254 | // `CNContactPicker`), and presenting from a test process is not something a | |
| 1255 | // suite should be able to do by accident. | |
| 1256 | // ============================================================================= | |
| 1257 | ||
| 1258 | const testing = std.testing; | |
| 1259 | ||
| 1260 | /// The pending slot is module state, and a test that leaves it set would make | |
| 1261 | /// the next one refuse. Every test that touches it clears it through here. | |
| 1262 | fn resetPendingForTesting() void { | |
| 1263 | pending_mutex.lock(); | |
| 1264 | defer pending_mutex.unlock(); | |
| 1265 | pending = null; | |
| 1266 | } | |
| 1267 | ||
| 1268 | fn fakeTicket(index: u5, generation: u32) ios_async.Ticket { | |
| 1269 | return .{ .index = index, .generation = generation }; | |
| 1270 | } | |
| 1271 | ||
| 1272 | fn fakeSels() Sels { | |
| 1273 | // Every field is a plain `Id`; nothing below dereferences them, and the | |
| 1274 | // concurrency rule under test does not care what they point at. | |
| 1275 | return std.mem.zeroes(Sels); | |
| 1276 | } | |
| 1277 | ||
| 1278 | test "the declared action is the one the handler serves" { | |
| 1279 | try testing.expectEqual(@as(usize, 1), capability_actions.len); | |
| 1280 | try testing.expectEqualStrings(A.pick_contact, capability_actions[0].name); | |
| 1281 | ||
| 1282 | for (capability_actions) |decl| { | |
| 1283 | // A `.result` whose handler never replies parks the caller on a promise | |
| 1284 | // with no timeout; a `.none` that is awaited resolves immediately and | |
| 1285 | // means nothing. Swift resolves or rejects every path, so `.result`. | |
| 1286 | try testing.expectEqual(capabilities.Reply.result, decl.reply); | |
| 1287 | try testing.expectEqual(capabilities.ActionStatus.live, decl.status); | |
| 1288 | // `.live` with a reason would be a contradiction the manifest shows apps. | |
| 1289 | try testing.expect(decl.reason == null); | |
| 1290 | } | |
| 1291 | } | |
| 1292 | ||
| 1293 | test "the action name matches the Swift case label exactly" { | |
| 1294 | // The conformance ratchet compares this against the `case "…":` labels in | |
| 1295 | // `CraftApp.swift` in both directions; a prettier spelling would read as Zig | |
| 1296 | // serving an action the spec does not have. | |
| 1297 | try testing.expectEqualStrings("pickContact", A.pick_contact); | |
| 1298 | } | |
| 1299 | ||
| 1300 | test "every declared action is one the dispatcher routes" { | |
| 1301 | for (capability_actions) |decl| { | |
| 1302 | if (routeFor(decl.name) == null) { | |
| 1303 | std.debug.print("declared action '{s}' does not route\n", .{decl.name}); | |
| 1304 | return error.DeclaredActionDoesNotRoute; | |
| 1305 | } | |
| 1306 | } | |
| 1307 | } | |
| 1308 | ||
| 1309 | test "every route the dispatcher has is a declared action" { | |
| 1310 | // The other direction: a route with a handler and no declaration is an | |
| 1311 | // action the page can call and the manifest denies exists. Each declaration | |
| 1312 | // must claim a *distinct* route — counting alone would let two rows share | |
| 1313 | // one route while another went undeclared. | |
| 1314 | var claimed = std.mem.zeroes([std.enums.values(Route).len]bool); | |
| 1315 | for (capability_actions) |decl| { | |
| 1316 | const route = routeFor(decl.name) orelse return error.DeclaredActionDoesNotRoute; | |
| 1317 | const slot = @backingInt(route); | |
| 1318 | if (claimed[slot]) { | |
| 1319 | std.debug.print("two declarations route to {s}\n", .{@tagName(route)}); | |
| 1320 | return error.TwoDeclarationsShareARoute; | |
| 1321 | } | |
| 1322 | claimed[slot] = true; | |
| 1323 | } | |
| 1324 | for (claimed, 0..) |taken, slot| { | |
| 1325 | if (!taken) { | |
| 1326 | std.debug.print( | |
| 1327 | "route {s} has a handler but no capability_actions row\n", | |
| 1328 | .{@tagName(@as(Route, @fromBackingInt(@intCast(slot))))}, | |
| 1329 | ); | |
| 1330 | return error.RouteNotDeclared; | |
| 1331 | } | |
| 1332 | } | |
| 1333 | } | |
| 1334 | ||
| 1335 | test "an action this module does not serve is refused as UnknownAction" { | |
| 1336 | // Not any other error: `ios_dispatch.route` reads UnknownAction as "not | |
| 1337 | // mine, ask the next module" and anything else as a final answer. Getting | |
| 1338 | // this wrong would make this file swallow another module's action — or the | |
| 1339 | // shim's. | |
| 1340 | var bridge = ContactPickerBridge.init(testing.allocator); | |
| 1341 | defer bridge.deinit(); | |
| 1342 | ||
| 1343 | for ([_][]const u8{ | |
| 1344 | "pickImage", | |
| 1345 | "pickDocument", | |
| 1346 | "getContacts", | |
| 1347 | "addContact", | |
| 1348 | // Casing is how a real typo arrives, and a miss does not fail loudly: | |
| 1349 | // the action would quietly fall through to the Swift shim. | |
| 1350 | "pickcontact", | |
| 1351 | "PickContact", | |
| 1352 | "pickContacts", | |
| 1353 | "", | |
| 1354 | }) |action| { | |
| 1355 | try testing.expectError( | |
| 1356 | bridge_error.BridgeError.UnknownAction, | |
| 1357 | bridge.handleMessage(action, "{}"), | |
| 1358 | ); | |
| 1359 | try testing.expect(routeFor(action) == null); | |
| 1360 | } | |
| 1361 | } | |
| 1362 | ||
| 1363 | test "pickContact routes to its own handler" { | |
| 1364 | try testing.expectEqual(Route.pick_contact, routeFor("pickContact").?); | |
| 1365 | } | |
| 1366 | ||
| 1367 | // --------------------------------------------------------------------------- | |
| 1368 | // Payload parsing | |
| 1369 | // --------------------------------------------------------------------------- | |
| 1370 | ||
| 1371 | test "an absent multiple is false, exactly as Swift's ?? false is" { | |
| 1372 | // `ios_dispatch.payloadOf` hands an absent `d` through as `{}`, which is the | |
| 1373 | // first case here. The page always sends the field today, but a body without | |
| 1374 | // it must not become a multi-select picker. | |
| 1375 | try testing.expect(!try parseMultiple(testing.allocator, "{}")); | |
| 1376 | try testing.expect(!try parseMultiple(testing.allocator, "{\"other\":1}")); | |
| 1377 | } | |
| 1378 | ||
| 1379 | test "a boolean multiple is carried through, both ways" { | |
| 1380 | try testing.expect(try parseMultiple(testing.allocator, "{\"multiple\":true}")); | |
| 1381 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":false}")); | |
| 1382 | } | |
| 1383 | ||
| 1384 | test "the numbers NSNumber-as-Bool accepts are the only numbers accepted" { | |
| 1385 | // `options.multiple || false` is a fallback, not a coercion, so | |
| 1386 | // `pickContact({multiple: 1})` really does put `1` on the wire. Swift's | |
| 1387 | // `as? Bool` succeeds for 0 and 1 and fails for everything else. | |
| 1388 | try testing.expect(try parseMultiple(testing.allocator, "{\"multiple\":1}")); | |
| 1389 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":0}")); | |
| 1390 | try testing.expect(try parseMultiple(testing.allocator, "{\"multiple\":1.0}")); | |
| 1391 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":0.0}")); | |
| 1392 | ||
| 1393 | // 2 is truthy in JavaScript and still opens a single-selection picker, | |
| 1394 | // because `as? Bool` returns nil for it. This is the case a "truthy means | |
| 1395 | // multiple" reading would get wrong. | |
| 1396 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":2}")); | |
| 1397 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":-1}")); | |
| 1398 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":0.5}")); | |
| 1399 | } | |
| 1400 | ||
| 1401 | test "a non-numeric truthy multiple is false, not multi" { | |
| 1402 | // `pickContact({multiple: 'yes'})` puts the string on the wire and Swift | |
| 1403 | // reads it as false. | |
| 1404 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":\"yes\"}")); | |
| 1405 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":\"true\"}")); | |
| 1406 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":[]}")); | |
| 1407 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":{}}")); | |
| 1408 | // `JSON.stringify` keeps an explicit null where it drops an undefined. | |
| 1409 | try testing.expect(!try parseMultiple(testing.allocator, "{\"multiple\":null}")); | |
| 1410 | } | |
| 1411 | ||
| 1412 | test "a body that cannot be read is an error, not a defaulted false" { | |
| 1413 | // Acting on a default for a payload that failed to parse is how a field the | |
| 1414 | // page sent goes missing with success reported anyway. | |
| 1415 | try testing.expectError( | |
| 1416 | bridge_error.BridgeError.InvalidJSON, | |
| 1417 | parseMultiple(testing.allocator, "{\"multiple\":"), | |
| 1418 | ); | |
| 1419 | try testing.expectError( | |
| 1420 | bridge_error.BridgeError.InvalidJSON, | |
| 1421 | parseMultiple(testing.allocator, "[1,2]"), | |
| 1422 | ); | |
| 1423 | try testing.expectError( | |
| 1424 | bridge_error.BridgeError.InvalidJSON, | |
| 1425 | parseMultiple(testing.allocator, "\"multiple\""), | |
| 1426 | ); | |
| 1427 | } | |
| 1428 | ||
| 1429 | // --------------------------------------------------------------------------- | |
| 1430 | // Reply shaping | |
| 1431 | // --------------------------------------------------------------------------- | |
| 1432 | ||
| 1433 | test "one contact is the six-key object formatContact builds, in a fixed order" { | |
| 1434 | const allocator = testing.allocator; | |
| 1435 | const json = try shapeContact(allocator, .{ | |
| 1436 | .id = "AB12-CD34", | |
| 1437 | .given_name = "Ada", | |
| 1438 | .family_name = "Lovelace", | |
| 1439 | .display_name = "Ada Lovelace", | |
| 1440 | .phones = &.{.{ .label = "mobile", .value = "+1 555 0100" }}, | |
| 1441 | .emails = &.{.{ .label = "work", .value = "ada@example.com" }}, | |
| 1442 | }); | |
| 1443 | defer allocator.free(json); | |
| 1444 | ||
| 1445 | try testing.expectEqualStrings( | |
| 1446 | "{\"id\":\"AB12-CD34\",\"givenName\":\"Ada\",\"familyName\":\"Lovelace\"," ++ | |
| 1447 | "\"displayName\":\"Ada Lovelace\"," ++ | |
| 1448 | "\"phoneNumbers\":[{\"label\":\"mobile\",\"number\":\"+1 555 0100\"}]," ++ | |
| 1449 | "\"emailAddresses\":[{\"label\":\"work\",\"address\":\"ada@example.com\"}]}", | |
| 1450 | json, | |
| 1451 | ); | |
| 1452 | } | |
| 1453 | ||
| 1454 | test "phones say number and emails say address" { | |
| 1455 | // The single easiest thing to get backwards, and it is silent: both are | |
| 1456 | // `{label, <string>}` and a swapped key still parses. `formatContact` is the | |
| 1457 | // only authority, and `craft.d.ts` — which declares both as `string[]` — is | |
| 1458 | // wrong for this action and must not be followed. | |
| 1459 | const allocator = testing.allocator; | |
| 1460 | const json = try shapeContact(allocator, .{ | |
| 1461 | .id = "1", | |
| 1462 | .given_name = "", | |
| 1463 | .family_name = "", | |
| 1464 | .display_name = "", | |
| 1465 | .phones = &.{.{ .label = "home", .value = "555" }}, | |
| 1466 | .emails = &.{.{ .label = "home", .value = "a@b.c" }}, | |
| 1467 | }); | |
| 1468 | defer allocator.free(json); | |
| 1469 | ||
| 1470 | const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{}); | |
| 1471 | defer parsed.deinit(); | |
| 1472 | ||
| 1473 | const phone = parsed.value.object.get("phoneNumbers").?.array.items[0].object; | |
| 1474 | try testing.expectEqualStrings("555", phone.get("number").?.string); | |
| 1475 | try testing.expect(phone.get("address") == null); | |
| 1476 | ||
| 1477 | const email = parsed.value.object.get("emailAddresses").?.array.items[0].object; | |
| 1478 | try testing.expectEqualStrings("a@b.c", email.get("address").?.string); | |
| 1479 | try testing.expect(email.get("number") == null); | |
| 1480 | } | |
| 1481 | ||
| 1482 | test "a contact with no numbers and no addresses keeps both keys as empty arrays" { | |
| 1483 | // `formatContact` always assigns both keys, so a page reading | |
| 1484 | // `contact.phoneNumbers.length` must not meet `undefined`. | |
| 1485 | const allocator = testing.allocator; | |
| 1486 | const json = try shapeContact(allocator, .{ | |
| 1487 | .id = "1", | |
| 1488 | .given_name = "Solo", | |
| 1489 | .family_name = "", | |
| 1490 | .display_name = "Solo", | |
| 1491 | .phones = &.{}, | |
| 1492 | .emails = &.{}, | |
| 1493 | }); | |
| 1494 | defer allocator.free(json); | |
| 1495 | ||
| 1496 | try testing.expect(std.mem.indexOf(u8, json, "\"phoneNumbers\":[]") != null); | |
| 1497 | try testing.expect(std.mem.indexOf(u8, json, "\"emailAddresses\":[]") != null); | |
| 1498 | } | |
| 1499 | ||
| 1500 | test "a name that needs escaping stays valid JSON" { | |
| 1501 | // A contact name is user data. Before escaping, a single `"` in it would | |
| 1502 | // close the string literal inside the `evaluateJavaScript:` source and turn | |
| 1503 | // the reply into a syntax error in the page rather than a wrong field. | |
| 1504 | const allocator = testing.allocator; | |
| 1505 | const json = try shapeContact(allocator, .{ | |
| 1506 | .id = "x\\y", | |
| 1507 | .given_name = "Ann \"Annie\"", | |
| 1508 | .family_name = "O'Neil\nJr", | |
| 1509 | .display_name = "Ann\t\"Annie\" O'Neil", | |
| 1510 | .phones = &.{.{ .label = "we\"ird", .value = "+1\\555" }}, | |
| 1511 | .emails = &.{.{ .label = "a\nb", .value = "q\"@example.com" }}, | |
| 1512 | }); | |
| 1513 | defer allocator.free(json); | |
| 1514 | ||
| 1515 | const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{}); | |
| 1516 | defer parsed.deinit(); | |
| 1517 | ||
| 1518 | const obj = parsed.value.object; | |
| 1519 | try testing.expectEqualStrings("x\\y", obj.get("id").?.string); | |
| 1520 | try testing.expectEqualStrings("Ann \"Annie\"", obj.get("givenName").?.string); | |
| 1521 | try testing.expectEqualStrings("O'Neil\nJr", obj.get("familyName").?.string); | |
| 1522 | try testing.expectEqualStrings( | |
| 1523 | "we\"ird", | |
| 1524 | obj.get("phoneNumbers").?.array.items[0].object.get("label").?.string, | |
| 1525 | ); | |
| 1526 | try testing.expectEqualStrings( | |
| 1527 | "q\"@example.com", | |
| 1528 | obj.get("emailAddresses").?.array.items[0].object.get("address").?.string, | |
| 1529 | ); | |
| 1530 | } | |
| 1531 | ||
| 1532 | test "the multiple reply is an array, not an object" { | |
| 1533 | // `test-bridges.html:1030` reads `contacts?.length`, so an object here would | |
| 1534 | // print `undefined contacts` for a selection that worked. | |
| 1535 | const allocator = testing.allocator; | |
| 1536 | const json = try shapeContacts(allocator, &.{ | |
| 1537 | .{ | |
| 1538 | .id = "1", | |
| 1539 | .given_name = "A", | |
| 1540 | .family_name = "One", | |
| 1541 | .display_name = "A One", | |
| 1542 | .phones = &.{}, | |
| 1543 | .emails = &.{}, | |
| 1544 | }, | |
| 1545 | .{ | |
| 1546 | .id = "2", | |
| 1547 | .given_name = "B", | |
| 1548 | .family_name = "Two", | |
| 1549 | .display_name = "B Two", | |
| 1550 | .phones = &.{.{ .label = "mobile", .value = "555" }}, | |
| 1551 | .emails = &.{}, | |
| 1552 | }, | |
| 1553 | }); | |
| 1554 | defer allocator.free(json); | |
| 1555 | ||
| 1556 | try testing.expect(json[0] == '['); | |
| 1557 | ||
| 1558 | const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{}); | |
| 1559 | defer parsed.deinit(); | |
| 1560 | ||
| 1561 | try testing.expectEqual(@as(usize, 2), parsed.value.array.items.len); | |
| 1562 | try testing.expectEqualStrings("1", parsed.value.array.items[0].object.get("id").?.string); | |
| 1563 | try testing.expectEqualStrings( | |
| 1564 | "555", | |
| 1565 | parsed.value.array.items[1].object.get("phoneNumbers").?.array.items[0].object.get("number").?.string, | |
| 1566 | ); | |
| 1567 | } | |
| 1568 | ||
| 1569 | test "an empty multi-selection is an empty array that resolves" { | |
| 1570 | // `contacts.map` over `[]` is `[]` and Swift resolves it. Turning this into | |
| 1571 | // an error, or into a cancel, would fail a call the shim answers. `[]` is | |
| 1572 | // also truthy, so `craft-bridge.js`'s `payload || {}` leaves it intact. | |
| 1573 | const allocator = testing.allocator; | |
| 1574 | const json = try shapeContacts(allocator, &.{}); | |
| 1575 | defer allocator.free(json); | |
| 1576 | ||
| 1577 | try testing.expectEqualStrings("[]", json); | |
| 1578 | ||
| 1579 | const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{}); | |
| 1580 | defer parsed.deinit(); | |
| 1581 | try testing.expectEqual(@as(usize, 0), parsed.value.array.items.len); | |
| 1582 | } | |
| 1583 | ||
| 1584 | test "the single reply is an object rather than an array of one" { | |
| 1585 | // The two `didSelect` overloads resolve genuinely different shapes, and a | |
| 1586 | // page doing `contact.givenName` after a single pick would read `undefined` | |
| 1587 | // off a one-element array. | |
| 1588 | const allocator = testing.allocator; | |
| 1589 | const one = Contact{ | |
| 1590 | .id = "1", | |
| 1591 | .given_name = "A", | |
| 1592 | .family_name = "One", | |
| 1593 | .display_name = "A One", | |
| 1594 | .phones = &.{}, | |
| 1595 | .emails = &.{}, | |
| 1596 | }; | |
| 1597 | ||
| 1598 | const single = try shapeContact(allocator, one); | |
| 1599 | defer allocator.free(single); | |
| 1600 | const many = try shapeContacts(allocator, &.{one}); | |
| 1601 | defer allocator.free(many); | |
| 1602 | ||
| 1603 | try testing.expect(single[0] == '{'); | |
| 1604 | try testing.expect(many[0] == '['); | |
| 1605 | ||
| 1606 | const parsed = try std.json.parseFromSlice(std.json.Value, allocator, single, .{}); | |
| 1607 | defer parsed.deinit(); | |
| 1608 | try testing.expectEqualStrings("A", parsed.value.object.get("givenName").?.string); | |
| 1609 | } | |
| 1610 | ||
| 1611 | test "a cancel is a rejection, and these are the exact bytes it puts on the wire" { | |
| 1612 | // `didCancel` calls `ios_async.deliverError`, which lands in | |
| 1613 | // `deliverOnMain` -> `sendErrorToJS(action, NativeCallFailed)`. This builds | |
| 1614 | // the same envelope that path builds, so the page-visible result of a | |
| 1615 | // cancel is pinned rather than described. | |
| 1616 | // | |
| 1617 | // Two things are being asserted at once. First, `"error":true` — it goes | |
| 1618 | // out through `__craftBridgeError`, which *rejects*. A | |
| 1619 | // `{"cancelled":true}` resolve (the shape the image and document pickers | |
| 1620 | // use) would be a fabricated success for a pick that did not happen, and | |
| 1621 | // the page's `catch` — where `test-bridges.html:1022` prints the outcome — | |
| 1622 | // would never run. | |
| 1623 | // | |
| 1624 | // Second, the divergence, stated in bytes: Swift sends | |
| 1625 | // `code:"CRAFT_ERROR"`, `message:"Cancelled"`. These are what the page gets | |
| 1626 | // instead, and they are wrong about the cause. See the module comment for | |
| 1627 | // why the fix belongs in `ios_async.zig` rather than in a second reply path | |
| 1628 | // built here. | |
| 1629 | const allocator = testing.allocator; | |
| 1630 | var ctx = bridge_error.ErrorContext.init( | |
| 1631 | bridge_error.BridgeError.NativeCallFailed, | |
| 1632 | A.pick_contact, | |
| 1633 | bridge_error.errorMessage(bridge_error.BridgeError.NativeCallFailed), | |
| 1634 | ); | |
| 1635 | ctx.request_id = 11; | |
| 1636 | ||
| 1637 | const json = try ctx.toJSON(allocator); | |
| 1638 | defer allocator.free(json); | |
| 1639 | ||
| 1640 | try testing.expectEqualStrings( | |
| 1641 | "{\"error\":true,\"code\":\"NATIVE_CALL_FAILED\",\"action\":\"pickContact\"," ++ | |
| 1642 | "\"message\":\"Native API call failed\",\"id\":11}", | |
| 1643 | json, | |
| 1644 | ); | |
| 1645 | ||
| 1646 | // And it is not any of the resolve shapes: a rejection carries no contact. | |
| 1647 | try testing.expect(std.mem.indexOf(u8, json, "givenName") == null); | |
| 1648 | } | |
| 1649 | ||
| 1650 | // --------------------------------------------------------------------------- | |
| 1651 | // Concurrency | |
| 1652 | // --------------------------------------------------------------------------- | |
| 1653 | ||
| 1654 | test "a second request while one is presented is refused, and the first is left alone" { | |
| 1655 | resetPendingForTesting(); | |
| 1656 | defer resetPendingForTesting(); | |
| 1657 | ||
| 1658 | const first = fakeTicket(3, 7); | |
| 1659 | try testing.expect(publishPending(.{ .ticket = first, .sels = fakeSels() })); | |
| 1660 | ||
| 1661 | // The refusal. Swift overwrites `pendingCallbackId` here and the first | |
| 1662 | // promise never settles; the picker on screen is about to answer, so the | |
| 1663 | // newcomer is the one that has to be told no. | |
| 1664 | try testing.expect(!publishPending(.{ .ticket = fakeTicket(4, 9), .sels = fakeSels() })); | |
| 1665 | ||
| 1666 | // And the slot still holds the *first* ticket, not the newcomer's — a | |
| 1667 | // refusal that quietly replaced would look identical from the return value. | |
| 1668 | pending_mutex.lock(); | |
| 1669 | defer pending_mutex.unlock(); | |
| 1670 | try testing.expectEqual(first.index, pending.?.ticket.index); | |
| 1671 | try testing.expectEqual(first.generation, pending.?.ticket.generation); | |
| 1672 | } | |
| 1673 | ||
| 1674 | test "the slot is handed over once, so a double-firing delegate cannot reply twice" { | |
| 1675 | resetPendingForTesting(); | |
| 1676 | defer resetPendingForTesting(); | |
| 1677 | ||
| 1678 | const ticket = fakeTicket(1, 2); | |
| 1679 | try testing.expect(publishPending(.{ .ticket = ticket, .sels = fakeSels() })); | |
| 1680 | ||
| 1681 | const taken = takePending() orelse return error.PendingWentMissing; | |
| 1682 | try testing.expectEqual(ticket.index, taken.ticket.index); | |
| 1683 | ||
| 1684 | // A cancel racing a selection, or a duplicate fire. `ios_async` would ignore | |
| 1685 | // the stale generation anyway, but the slot has to be empty here so the | |
| 1686 | // callback never even reaches for a ticket that is already spent. | |
| 1687 | try testing.expect(takePending() == null); | |
| 1688 | } | |
| 1689 | ||
| 1690 | test "the picker is reusable after it answers" { | |
| 1691 | // The refusal above must not be permanent. Once a delegate callback has | |
| 1692 | // taken the slot, the next pickContact publishes normally. | |
| 1693 | resetPendingForTesting(); | |
| 1694 | defer resetPendingForTesting(); | |
| 1695 | ||
| 1696 | try testing.expect(publishPending(.{ .ticket = fakeTicket(0, 1), .sels = fakeSels() })); | |
| 1697 | _ = takePending(); | |
| 1698 | try testing.expect(publishPending(.{ .ticket = fakeTicket(0, 3), .sels = fakeSels() })); | |
| 1699 | } | |
| 1700 | ||
| 1701 | test "a delegate callback with no request waiting takes nothing" { | |
| 1702 | // The stray-callback path every IMP begins with. It has to be a | |
| 1703 | // no-op rather than an answer, because the next thing to occupy the slot | |
| 1704 | // would otherwise receive this picker's result. | |
| 1705 | resetPendingForTesting(); | |
| 1706 | defer resetPendingForTesting(); | |
| 1707 | ||
| 1708 | try testing.expect(takePending() == null); | |
| 1709 | } | |
| 1710 | ||
| 1711 | test "the delegate class name is this module's alone" { | |
| 1712 | // `ios_delegate.defineClass` looks a name up before allocating, so two files | |
| 1713 | // registering one name means whichever ran second silently adopts the | |
| 1714 | // other's IMPs — which read different objects and answer different tickets. | |
| 1715 | try testing.expectEqualStrings("CraftIOSContactPickerDelegate", delegate_class_name); | |
| 1716 | } | |
| 1717 | ||
| 1718 | test "every delegate method is registered at the encoding its selector needs" { | |
| 1719 | // A wrong encoding still registers and still dispatches, then reads | |
| 1720 | // arguments from the wrong registers with no crash and no compile error. The | |
| 1721 | // named constants are the only defence, so the *pairing* is pinned rather | |
| 1722 | // than the constants alone: both `didSelect` selectors take the picker plus | |
| 1723 | // one object, the cancel and the dismissal take one object each. | |
| 1724 | // | |
| 1725 | // The count is asserted too. `contactPicker:didSelectContacts:` is the whole | |
| 1726 | // `multiple:true` reply path and `presentationControllerDidDismiss:` is the | |
| 1727 | // only answer to a swipe-down; UIKit dispatches through | |
| 1728 | // `respondsToSelector:`, so dropping either is a silent no-op and a promise | |
| 1729 | // that never settles. | |
| 1730 | const methods = delegateMethods(); | |
| 1731 | try testing.expectEqual(@as(usize, 4), methods.len); | |
| 1732 | ||
| 1733 | const want = [_]struct { selector: []const u8, types: []const u8 }{ | |
| 1734 | .{ .selector = "contactPicker:didSelectContact:", .types = "v@:@@" }, | |
| 1735 | .{ .selector = "contactPicker:didSelectContacts:", .types = "v@:@@" }, | |
| 1736 | .{ .selector = "contactPickerDidCancel:", .types = "v@:@" }, | |
| 1737 | .{ .selector = "presentationControllerDidDismiss:", .types = "v@:@" }, | |
| 1738 | }; | |
| 1739 | ||
| 1740 | for (methods, 0..) |method, i| { | |
| 1741 | try testing.expectEqualStrings(want[i].selector, method.selector); | |
| 1742 | try testing.expectEqualStrings(want[i].types, method.types); | |
| 1743 | } | |
| 1744 | ||
| 1745 | // And the encodings really are the named ones, not two strings that happen | |
| 1746 | // to match today. | |
| 1747 | try testing.expectEqualStrings(ios_delegate.enc.void_two_objects, methods[0].types); | |
| 1748 | try testing.expectEqualStrings(ios_delegate.enc.void_two_objects, methods[1].types); | |
| 1749 | try testing.expectEqualStrings(ios_delegate.enc.void_one_object, methods[2].types); | |
| 1750 | try testing.expectEqualStrings(ios_delegate.enc.void_one_object, methods[3].types); | |
| 1751 | } | |
| 1752 | ||
| 1753 | test "no two delegate methods share a selector" { | |
| 1754 | // `class_addMethod` for a selector the class already has is a failure the | |
| 1755 | // factory turns into `MethodNotAdded`, so a duplicate would take the whole | |
| 1756 | // registration down — and a typo that made two rows equal would otherwise | |
| 1757 | // read as an extra method rather than a missing one. | |
| 1758 | const methods = delegateMethods(); | |
| 1759 | for (methods, 0..) |a, i| { | |
| 1760 | for (methods[i + 1 ..]) |b| { | |
| 1761 | try testing.expect(!std.mem.eql(u8, a.selector, b.selector)); | |
| 1762 | } | |
| 1763 | } | |
| 1764 | } | |
| 1765 | ||
| 1766 | test "a swipe-down that sends no cancel still empties the slot exactly once" { | |
| 1767 | // The belt's contract, as state rather than as prose: whichever callback | |
| 1768 | // arrives first takes the ticket, and the second finds nothing. Without it a | |
| 1769 | // swipe would leave `pending` set for the life of the process and refuse | |
| 1770 | // every later pickContact — which is worse here than in Swift, where only | |
| 1771 | // the one promise is stranded. | |
| 1772 | resetPendingForTesting(); | |
| 1773 | defer resetPendingForTesting(); | |
| 1774 | ||
| 1775 | try testing.expect(publishPending(.{ .ticket = fakeTicket(2, 5), .sels = fakeSels() })); | |
| 1776 | ||
| 1777 | // The dismissal gets there first: it takes the ticket... | |
| 1778 | const swiped = takePending() orelse return error.PendingWentMissing; | |
| 1779 | try testing.expectEqual(@as(u5, 2), swiped.ticket.index); | |
| 1780 | ||
| 1781 | // ...and a late `contactPickerDidCancel:` for the same picker finds nothing | |
| 1782 | // to answer, so the promise is rejected once rather than twice. | |
| 1783 | try testing.expect(takePending() == null); | |
| 1784 | ||
| 1785 | // The slot is free again, not wedged. | |
| 1786 | try testing.expect(publishPending(.{ .ticket = fakeTicket(2, 7), .sels = fakeSels() })); | |
| 1787 | } | |
| 1788 | ||
| 1789 | test "nothing in this module dismisses the picker" { | |
| 1790 | // `CNContactPickerViewController` is a remote view controller that takes | |
| 1791 | // itself down, and Swift dismisses it in none of its three delegate methods. | |
| 1792 | // A `dismiss` added here would be a second dismissal of a controller already | |
| 1793 | // dismissing — and on the presenter it would take down whatever else is | |
| 1794 | // modal. This is a real difference from the image and document pickers, so | |
| 1795 | // it is asserted rather than left to a comment. | |
| 1796 | // | |
| 1797 | // `presentationControllerDidDismiss:` does not contradict this: it *observes* | |
| 1798 | // a dismissal the user performed and never asks for one. | |
| 1799 | // | |
| 1800 | // The needle is the *call* form — a `selector(` with a dismissal name in it | |
| 1801 | // — rather than the bare selector name, so the prose in this file cannot | |
| 1802 | // match itself and the assertion keeps meaning something. Which is why the | |
| 1803 | // needle is not spelled out in any comment, including this one. | |
| 1804 | const source = @embedFile("bridge_mobile_contactpicker.zig"); | |
| 1805 | try testing.expect(std.mem.indexOf(u8, source, "selector(\"dismiss") == null); | |
| 1806 | // Non-vacuity: the same scan finds the present call, so a needle that | |
| 1807 | // stopped matching anything could not pass unnoticed. | |
| 1808 | try testing.expect(std.mem.indexOf(u8, source, "selector(\"presentViewController") != null); | |
| 1809 | } | |