ReviewOS

also looking at this

craft-native/craft

iOS Phase 8: the presented pickers — ratchet 58 → 53, last mechanism landed

#90
Merged glennmichael123 wants to merge feat/ios-phase8-ui into main
11 files +5752 -12
packages/zig/src/bridge_mobile_filepicker.zigadded+1950-0
Changes to packages/zig/src/bridge_mobile_filepicker.zig
@@ -0,0 +1,1950 @@
1//! The `mobile` namespace's two file actions: `pickFile` and `saveFile`.
2//!
3//! They look like a pair and are not. `pickFile` presents
4//! `UIDocumentPickerViewController`, so its answer arrives from a delegate
5//! callback long after the dispatch frame is gone and needs an `ios_async`
6//! ticket. `saveFile` presents nothing at all — it writes straight into
7//! `<container>/Documents/<filename>` and resolves the path from inside the
8//! dispatch. The third member of the family, `downloadFile`, is deliberately
9//! left with the Swift shim; see `deliberately_unserved`.
10//!
11//! ## Neither action has any injected JavaScript, so the field names come from
12//! ## the Swift dispatcher
13//!
14//! `window.craft.pickFile` and `window.craft.saveFile` **do not exist** in the
15//! injected iOS bridge. `injectNativeBridge` spans `CraftApp.swift:1164`-`2426`
16//! and contains no occurrence of `file` at all, and `craft-bridge.js` has no
17//! `mobile` surface either (its `saveFile` is `_req('dialog','saveFile',…)` —
18//! the desktop dialog namespace, a different action in a different namespace).
19//! So `test-bridges.html:585` and both README examples are `TypeError`s on the
20//! legacy Swift path, and the dispatcher arms are reachable only through the
21//! Zig envelope `{t:"mobile", a:"pickFile"|"saveFile", d, i}`. That is a
22//! pre-existing bug, the same one `bridge_mobile_motion.zig` records for
23//! `startMotionUpdates`, and it is why the payload field names below are read
24//! off the Swift dispatcher's own `body[...]` reads and cross-checked against
25//! `craft.d.ts` and Android's `CraftBridge.kt.template` rather than off an
26//! injected method that was never written.
27//!
28//! ## The payloads, exactly
29//!
30//! **`pickFile`** reads one optional field, `types`, an array of strings
31//! (`CraftApp.swift:817`). Nothing else is read. Absent or null means Swift's
32//! default of a single `UTTypeItem`.
33//!
34//! **`saveFile`** reads two required fields, `data` and `filename`
35//! (`CraftApp.swift:829-831`). There is no third field: `craft.d.ts:217`
36//! declares a `mimeType` parameter and the README passes one, but neither
37//! Swift nor Android ever reads it. It is a type-declaration fiction, so a
38//! `mimeType` in the payload is accepted and ignored rather than invented into
39//! a field or turned into an error.
40//!
41//! ## The reply shapes, exactly
42//!
43//! **`pickFile` resolves an object** (`CraftApp.swift:4897-4902`):
44//! `{"name":…,"path":…,"data":"data:<mime>;base64,<b64>","mimeType":…}`. The
45//! `data:` URL uses the same derived MIME string, and the base64 is
46//! `-[NSData base64EncodedStringWithOptions:0]` — standard alphabet, padded,
47//! unwrapped. Key order is Swift's literal order; Swift's own is a `Dictionary`
48//! and therefore arbitrary, so one order is fixed here to make the bytes
49//! testable.
50//!
51//! **`pickFile` rejects on cancel.** `documentPickerWasCancelled:` calls
52//! `rejectCallback(pendingCallbackId, error: "Cancelled")`
53//! (`CraftApp.swift:4913`), so a cancel is a rejected promise and not a
54//! distinct resolve — the opposite of the shape a picker often has, and worth
55//! reading twice. An empty `urls` array is likewise a reject
56//! (`"No file selected"`, `CraftApp.swift:4889`).
57//!
58//! **`saveFile` resolves a bare JSON string**, the written path
59//! (`CraftApp.swift:3658` through `resolveCallback`'s `.fragmentsAllowed`).
60//! Not an object. `craft.d.ts:217` types it `Promise<void>`, but Android agrees
61//! with Swift (`file.absolutePath`), and `craft-bridge.js` settles with
62//! `payload || {}` — a non-empty path survives that, and the path can never be
63//! empty here, so there is no truthiness trap.
64//!
65//! ## The config gate Zig cannot see, and why both actions are served anyway
66//!
67//! Swift wraps both arms in `if config.enableFilePicker` /
68//! `if config.enableFileDownload`, each defaulting to **false**
69//! (`CraftApp.swift:206-207`), each with **no `else`**. So with the default
70//! config the Swift path replies *nothing at all* while
71//! `CraftSwiftShim.handleAction` still returns true: the page's promise never
72//! settles. `ios.zig`'s `AppConfig` has no mirror of either flag, and — unlike
73//! motion, where `NSMotionUsageDescription` is an exact proxy — there is no
74//! Info.plist key to read instead: `renderUsageDescriptions`
75//! (`packages/ios/src/index.ts:183-199`) writes nothing from either flag.
76//!
77//! Both are therefore served unconditionally, and an app that set
78//! `enableFilePicker: false` or `enableFileDownload: false` now gets the
79//! behaviour anyway. Restoring the gate means adding the fields to
80//! `AppConfig`, not adding a guess here — the same trade
81//! `bridge_mobile_system.zig` records word for word for `share`.
82//!
83//! Falling through to the shim is not the safe option it was for
84//! `takeScreenshot`, because the shim does not answer these correctly today:
85//! with the flag off it answers with silence, and `ios_dispatch.zig:170-174`
86//! names silence as the one outcome ruled out. `.unavailable` is strictly
87//! worse again — `ios_dispatch.route` only reaches the shim when every module
88//! returns `UnknownAction`, so declaring it would make Zig dispatch and refuse.
89//!
90//! What makes serving them defensible rather than merely better-than-silence:
91//! `pickFile` is user-mediated, so nothing is read without the user tapping a
92//! file, and `saveFile` writes only inside the app's own container, needs no
93//! OS permission and shows no UI.
94//!
95//! ## Five deliberate divergences from Swift
96//!
97//! **1. Security-scoped access is taken around the read.** Swift's
98//! `documentPicker(_:didPickDocumentsAt:)` is a bare `try? Data(contentsOf: url)`
99//! with no `startAccessingSecurityScopedResource` anywhere in the repo. Because
100//! the picker is built with `asCopy == NO`, the URL is a security-scoped
101//! reference to a document outside the container: on a device that read
102//! **fails**, `try?` yields nil, and Swift falls to its degraded branch. In the
103//! simulator the same read usually succeeds, which is why the bug has never
104//! been noticed. This module takes the scope and releases it in a `defer`.
105//! Swift does *not* do this; the claim is only about what this file does.
106//!
107//! **2. A file whose bytes cannot be read is rejected, not resolved.** Swift
108//! resolves `{name, path}` with no `data` and no `mimeType`
109//! (`CraftApp.swift:4903-4906`) — without the field its own `PickedFile` type
110//! declares required and the only in-repo consumer reads
111//! (`test-bridges.html:589` reads `file?.data?.length`). With the scoping fix
112//! above, a failed read is a real failure, and resolving a data-less object for
113//! it is fabricated-adjacent success. It is a rejection here.
114//!
115//! **3. An unmappable `types` entry is refused rather than dropped.** Swift's
116//! `compactMap` silently discards entries it cannot map, and can therefore
117//! produce an *empty* allowed-types array. Dropping a field the page sent is
118//! the failure rule 2 exists for, so an entry that maps to nothing is an
119//! `INVALID_PARAMETER` naming it.
120//!
121//! **4. `+[UTType typeWithIdentifier:]` is tried as a third fallback**, after
122//! Swift's `typeWithMIMEType:` then `typeWithFilenameExtension:`. This is an
123//! intentional improvement, declared rather than slipped in: Swift never tries
124//! it, so a bare type identifier maps to nothing at all there. It never widens
125//! past what the page asked for — an entry that names a declared identifier
126//! becomes exactly that type, and one that names nothing is still refused.
127//!
128//! What it does *not* do is rescue the README's own documented call. Measured
129//! on the host UniformTypeIdentifiers: `public.image` maps by identifier, but
130//! `public.pdf` is not a declared identifier at all (the real one is
131//! `com.adobe.pdf`) and maps by none of the three routes, so
132//! `pickFile(['public.image','public.pdf'])` is refused by divergence 3 — where
133//! Swift silently `compactMap`s both away and presents a picker with an empty
134//! allowed-types array. The refusal is the honest answer; the README is what
135//! needs fixing, and that is not this file's change to make.
136//!
137//! One measured caveat on divergence 3's reach: `typeWithFilenameExtension:`
138//! answers a *dynamic* type (`dyn.…`) for an arbitrary dot-free string, so a
139//! garbage entry like `"notanextension"` is accepted as that dynamic type
140//! rather than refused. Nothing is fabricated — the picker simply matches no
141//! file — and it is exactly what Swift's second `??` arm does too; the refusal
142//! path is reached by dotted non-identifiers, which is where Swift's silent
143//! drop actually bites.
144//!
145//! **5. `filename` is checked before it is joined.** Swift applies
146//! `appendingPathComponent` to an unsanitised page-supplied string
147//! (`CraftApp.swift:3645`), so `"../Library/Preferences/x.plist"` escapes
148//! `Documents`. A name containing `/` or a NUL, an empty name, and the two
149//! names `.` and `..` are refused here. With `/` excluded, `..` can only ever
150//! be the whole name, so those four checks are exhaustive for traversal — and
151//! an ordinary name like `my..notes.txt` still passes.
152//!
153//! And one bug that is simply not reproduced: Swift's `saveFile` reaches
154//! `resolveCallback(callbackId, result: fileURL.path)` even when the data URL
155//! had the wrong number of comma-separated parts or its base64 would not decode
156//! (`CraftApp.swift:3651-3658` — the `if` body just never runs, nothing throws).
157//! `data:text/plain,hello` triggers it: the page is told a file was written
158//! where nothing was. Here both are `INVALID_PARAMETER`.
159//!
160//! ## Dismissal
161//!
162//! `UIDocumentPickerViewController` dismisses itself before calling its
163//! delegate — which is why Swift's two delegate methods contain no `dismiss`
164//! call, in visible contrast to the image picker, which dismisses explicitly at
165//! `CraftApp.swift:2643` and `2662`. Sending an unconditional dismiss would
166//! therefore be a *second* dismiss, and a second dismiss is not a no-op:
167//! `-dismissViewControllerAnimated:completion:` on a controller with nothing
168//! presented forwards up the presentation chain and can tear down something
169//! nobody asked to close.
170//!
171//! So both callbacks dismiss, and both check first: `dismissPicker` reads the
172//! controller's own `presentingViewController` and does nothing when it is nil
173//! (already dismissed itself). When it is non-nil the picker really is still on
174//! screen and is dismissed by sending the message to the picker itself, which
175//! UIKit routes to its presenter. The app cannot end up parked behind a modal,
176//! and nothing unrelated is dismissed either.
177//!
178//! ## The swipe-down belt
179//!
180//! A modal the delegate never hears about is the other half of the problem, and
181//! it is the *page* rather than the app that pays for it. The picker is a sheet,
182//! and an interactive dismissal is widely reported not to send
183//! `documentPickerWasCancelled:` — the same report `bridge_mobile_imagepicker.zig`
184//! and `bridge_mobile_contactpicker.zig` carry belts for, and one this repo
185//! verifies on no device. Without a belt a swipe leaves `pending_pick` set
186//! forever: the call is never answered (silence, which `ios_dispatch.zig:170-174`
187//! rules out) **and** every later `pickFile` is refused for the life of the
188//! process, which is strictly worse than Swift, where only the one promise is
189//! stranded.
190//!
191//! `presentationControllerDidDismiss:` is that belt: it is registered on the
192//! same delegate, and the picker's presentation controller is pointed at that
193//! delegate before presenting and again after, so a swipe *rejects* the call
194//! rather than stranding it. Belt, not fix — UIKit sends it only for a
195//! user-driven dismissal, so it cannot fire after a pick or a Cancel that
196//! already answered, and if the report is wrong it costs two messages. The one
197//! case it does not cover is a presentation controller that already carries a
198//! delegate of its own, which is left alone rather than displaced; that is
199//! logged where it happens rather than assumed away.
200//!
201//! ## One pending pick, refused rather than replaced
202//!
203//! Swift keeps a single `pendingCallbackId` (`CraftApp.swift:383`) shared
204//! across the camera, the image picker, the document picker, the contact
205//! picker, the QR scanner, Apple Sign-In, NFC and Bluetooth, and overwrites it
206//! unconditionally — so two overlapping picks strand the first promise forever.
207//! A picker is modal and serves exactly one call, so this module keeps exactly
208//! one pending ticket for this picker kind, under a mutex, and a second
209//! `pickFile` issued while one is presented is an explicit error to the
210//! *second* caller. The first ticket is never replaced.
211//!
212//! ## Ceilings and simulator caveats
213//!
214//! The whole file crosses the bridge base64-encoded inside one
215//! `evaluateJavaScript` string — about 1.37 bytes of JavaScript source per byte
216//! of file. Swift has exactly the same ceiling; it is noted here rather than
217//! discovered on a 200 MB video.
218//!
219//! `UIDocumentPickerViewController` itself works in the simulator — it is not
220//! camera-class hardware, so the "unavailable on simulator, must reject"
221//! precedent does not apply. What the simulator lacks is content to pick, and
222//! the `zig-slice` fixture cannot tap Cancel or choose a file anyway, so only
223//! `pickFile`'s refusal paths are reachable from that harness. `saveFile` is
224//! fully fixture-testable. Security scoping is invisible in the simulator,
225//! where URLs resolve to ordinary host paths and the read succeeds without it —
226//! a green simulator run proves nothing about divergence 1.
227//!
228//! `objc_getClass("UTType")` may be null in the Zig-only fixture:
229//! `packages/ios/fixtures/zig-slice/build-and-run.sh:65` links only
230//! UIKit/WebKit/Foundation/Security, while the generated app pulls
231//! UniformTypeIdentifiers in through `CraftApp.swift:20`. A null class is a
232//! named error with a log line naming the missing framework — never a silent
233//! fallback to the `[.item]` default, which would quietly widen the file types
234//! the app author asked to restrict.
235
236const std = @import("std");
237const builtin = @import("builtin");
238const capabilities = @import("capabilities.zig");
239const bridge_error = @import("bridge_error.zig");
240const objc_runtime = @import("objc_runtime.zig");
241const ios_async = @import("ios_async.zig");
242const ios_delegate = @import("ios_delegate.zig");
243const bridge_mobile_system = @import("bridge_mobile_system.zig");
244const compat_mutex = @import("compat_mutex.zig");
245
246const objc = objc_runtime.objc;
247const is_darwin = builtin.target.os.tag.isDarwin();
248const BridgeError = bridge_error.BridgeError;
249
250/// The same type as `objc.id` — `?*anyopaque` — spelled locally.
251///
252/// `objc_runtime.objc` is an empty struct off Darwin, and a `callconv(.c)`
253/// fn-pointer *type* is analysed even where a comptime platform guard makes the
254/// surrounding code unreachable, so naming `objc.id` in the delegate signatures
255/// below would break the host build. A single optional pointer, never
256/// `?objc.id`: a double optional is illegal in a `callconv(.c)` signature.
257const Id = ?*anyopaque;
258
259/// The action names, spelled exactly as the Swift `case` labels spell them.
260///
261/// `test/ios_conformance_test.zig` matches this block against those labels in
262/// both directions and fails the build if two modules declare one name. Keep
263/// the doc comments in this block free of quoted text: the scanner takes the
264/// first quoted string on every line it sees between the header and the closing
265/// brace.
266pub const A = struct {
267 pub const pick_file = "pickFile";
268 pub const save_file = "saveFile";
269};
270
271/// The third action of this family, and on purpose not served.
272///
273/// `downloadFile` is out of scope for this round. Recorded as data rather than
274/// prose so a test can hold the two properties the decision rests on: it is not
275/// declared, and it still falls out of `handleMessage` as `UnknownAction` —
276/// the one return `ios_dispatch.route` converts into a Swift-shim hand-off.
277/// Whoever migrates it moves the name into `A` and updates the module comment.
278pub const deliberately_unserved = [_][]const u8{
279 "downloadFile",
280};
281
282/// Both `.result`: each Swift path terminates in exactly one `resolveCallback`
283/// or one `rejectCallback`, and the page awaits both. `.none` on either would
284/// resolve a caller immediately with nothing.
285///
286/// Both `.live`: a refusal here is a specific failure — a cancelled pick, an
287/// unreadable file, a filename that would escape the container, a full async
288/// pool — never the action's normal answer. `.unavailable` is for an action
289/// that dispatches and refuses, which neither of these is.
290pub const capability_actions = [_]capabilities.ActionDecl{
291 .{ .name = A.pick_file, .reply = .result },
292 .{ .name = A.save_file, .reply = .result },
293};
294
295/// Which handler an action selects, split out of `handleMessage` so the
296/// table-versus-dispatch agreement is assertable on a host without UIKit.
297const Route = enum { pick_file, save_file };
298
299fn routeFor(action: []const u8) ?Route {
300 if (std.mem.eql(u8, action, A.pick_file)) return .pick_file;
301 if (std.mem.eql(u8, action, A.save_file)) return .save_file;
302 return null;
303}
304
305pub const FilePickerBridge = struct {
306 allocator: std.mem.Allocator,
307
308 const Self = @This();
309
310 pub fn init(allocator: std.mem.Allocator) Self {
311 return .{ .allocator = allocator };
312 }
313
314 pub fn deinit(_: *Self) void {}
315
316 pub fn handleMessage(self: *Self, action: []const u8, data: []const u8) !void {
317 const route = routeFor(action) orelse return BridgeError.UnknownAction;
318 // Exhaustive, so a `Route` without a handler is a compile error.
319 return switch (route) {
320 .pick_file => self.pickFile(data),
321 .save_file => self.saveFile(data),
322 };
323 }
324
325 /// Present the document picker and answer when the user has chosen or
326 /// cancelled.
327 ///
328 /// Every fallible step runs *before* `ios_async.acquire`, and the only
329 /// thing between publishing the ticket and presenting is the presentation
330 /// itself. A failure after the lease would have to release the slot by
331 /// hand, and a missed release is a permanently narrower pool.
332 fn pickFile(self: *Self, data: []const u8) !void {
333 if (!is_darwin) return error.UnsupportedPlatform;
334
335 const request = try parsePickRequest(self.allocator, data);
336 defer request.deinit(self.allocator);
337
338 // Guarded once, here, for both uses below: the default `public.item`
339 // and every mapped entry need this class. A null answer means the
340 // process has no UniformTypeIdentifiers — the fixture's link line — and
341 // that is an error, never a silent fall back to the default, which
342 // would widen the types the app author asked to restrict.
343 const UTTypeClass = objc.objc_getClass("UTType") orelse {
344 std.log.err(
345 "pickFile: this process has no UTType class, so no content type can be " ++
346 "built; the app or fixture needs -framework UniformTypeIdentifiers",
347 .{},
348 );
349 return BridgeError.NativeCallFailed;
350 };
351
352 const content_types = try buildContentTypes(self.allocator, request, UTTypeClass);
353 const delegate = try ensureDelegate();
354
355 const PickerClass = objc.objc_getClass("UIDocumentPickerViewController") orelse
356 return error.ClassNotFound;
357
358 // `initForOpeningContentTypes:` — the one-argument iOS 14+ form, which
359 // is what Swift's single-label call binds to, i.e. `asCopy == NO`.
360 // Deployment target is 16.0, so its availability is unconditional. The
361 // deprecated `initWithDocumentTypes:inMode:` is not used.
362 const sel_init = try selector("initForOpeningContentTypes:");
363 const sel_set_delegate = try selector("setDelegate:");
364 const sel_set_multi = try selector("setAllowsMultipleSelection:");
365 const sel_present = try selector("presentViewController:animated:completion:");
366 // The swipe-down belt's reads, resolved here with everything else so a
367 // missing selector fails the call rather than silently leaving the only
368 // thing that answers an interactive dismissal unattached.
369 const dismiss_sels = DismissSels{
370 .presentation = try selector("presentationController"),
371 .delegate = try selector("delegate"),
372 .set_delegate = sel_set_delegate,
373 };
374
375 const allocated = try objc.alloc(PickerClass);
376 const InitFn = *const fn (Id, Id, Id) callconv(.c) Id;
377 const init_fn: InitFn = @ptrCast(&objc.objc_msgSend);
378 const picker = init_fn(allocated, sel_init, content_types) orelse
379 return error.NativeCallFailed;
380 // `alloc` gave us +1 and `init` consumed it. The presenter retains the
381 // picker for the life of the presentation, so ours is the reference to
382 // drop — and on the refusal paths below it is the only one there is.
383 defer objc.release(picker);
384
385 // The picker holds its delegate **weakly** (`UIDocumentPickerViewController.h:65`),
386 // which is why `delegate_instance` is a module-level var rather than a
387 // local: dropping it would be a use-after-free the first time the user
388 // taps Cancel.
389 objc.msgSendVoid1(picker, sel_set_delegate, delegate);
390
391 const SetBoolFn = *const fn (Id, Id, bool) callconv(.c) void;
392 const set_bool: SetBoolFn = @ptrCast(&objc.objc_msgSend);
393 // Swift sets this explicitly at `CraftApp.swift:3603` even though false
394 // is the default, and the reply shape has room for exactly one file.
395 set_bool(picker, sel_set_multi, false);
396
397 // Swift presents on `windowScene.windows.first?.rootViewController`
398 // (`CraftApp.swift:3594`), which logs "which is already presenting" and
399 // silently does nothing when anything else is up — leaving the promise
400 // unsettled. This walks `presentedViewController` from the webview's own
401 // window instead. A declared deviation, and strictly the more correct
402 // one. No `anchorPopover` call: the picker's default presentation style
403 // is a form/page sheet, so `popoverPresentationController` is nil and
404 // there is nothing to anchor — unlike `UIActivityViewController`, which
405 // traps without one.
406 const presenter = try bridge_mobile_system.uikit.topmostViewController();
407
408 // Attached before presenting, because that is when a presentation
409 // controller can already exist, and retried after `presentViewController:`
410 // for the case where UIKit only builds one there. Infallible either way:
411 // it reports whether it took and never fails the call.
412 var dismiss_observed = attachDismissObserver(picker, delegate, dismiss_sels);
413
414 const ticket = ios_async.acquire(A.pick_file) orelse return poolFull();
415
416 // Published before the framework call, never after: the delegate can in
417 // principle be reached before `present` returns, and a callback that
418 // arrived at an empty slot would have no ticket to reply with.
419 if (!publishPendingPick(ticket)) {
420 // Swift overwrites its one `pendingCallbackId` here and the first
421 // caller's promise never settles. The second caller is refused
422 // instead; the first keeps the picker and its ticket.
423 ios_async.abandon(ticket);
424 std.log.warn(
425 "pickFile refused: a document picker is already presented and owns the " ++
426 "pending reply; refusing the second call rather than stranding the first",
427 .{},
428 );
429 return BridgeError.InvalidParameter;
430 }
431
432 const PresentFn = *const fn (Id, Id, Id, bool, Id) callconv(.c) void;
433 const present_fn: PresentFn = @ptrCast(&objc.objc_msgSend);
434 present_fn(presenter, sel_present, picker, true, null);
435
436 if (!dismiss_observed) dismiss_observed = attachDismissObserver(picker, delegate, dismiss_sels);
437 if (!dismiss_observed) {
438 std.log.warn(
439 "pickFile: the picker's presentation controller could not be observed " ++
440 "(absent, or already carrying a delegate this file will not displace); " ++
441 "if a swipe-down dismissal does not send documentPickerWasCancelled: " ++
442 "then this call stays unanswered and every later one is refused",
443 .{},
444 );
445 }
446 }
447
448 /// Write `data` into `<container>/Documents/<filename>` and resolve the
449 /// path.
450 ///
451 /// Fully synchronous: Swift presents nothing here — no export-mode picker,
452 /// no temp file, no delegate — so there is no `ios_async` ticket and the
453 /// reply goes out from inside the dispatch frame that holds the request id.
454 fn saveFile(self: *Self, data: []const u8) !void {
455 if (!is_darwin) return error.UnsupportedPlatform;
456
457 const parsed = std.json.parseFromSlice(std.json.Value, self.allocator, data, .{}) catch
458 return BridgeError.InvalidJSON;
459 defer parsed.deinit();
460
461 const root = switch (parsed.value) {
462 .object => |obj| obj,
463 else => return BridgeError.InvalidJSON,
464 };
465
466 const request = try parseSaveRequest(root);
467
468 const bytes = try decodeSaveBytes(self.allocator, request.data);
469 defer self.allocator.free(bytes);
470
471 const directory = try documentsPath(self.allocator);
472 defer self.allocator.free(directory);
473
474 const path = try std.fmt.allocPrint(
475 self.allocator,
476 "{s}/{s}",
477 .{ directory, request.filename },
478 );
479 defer self.allocator.free(path);
480
481 try writeFileAtomically(self.allocator, path, bytes);
482
483 const json = try shapeSavedPath(self.allocator, path);
484 defer self.allocator.free(json);
485
486 bridge_error.sendResultToJS(self.allocator, A.save_file, json);
487 }
488};
489
490/// The answer for a full block pool, in the shape `bridge_mobile_location.zig`
491/// uses: `BridgeError` has no "Busy", `INVALID_PARAMETER` is the migration
492/// notes' designated stand-in, and the point is that the seventeenth concurrent
493/// call gets an explicit rejection instead of a promise that never settles.
494fn poolFull() BridgeError {
495 std.log.warn("pickFile refused: all {d} async slots in flight", .{ios_async.max_in_flight});
496 return BridgeError.InvalidParameter;
497}
498
499fn selector(name: [*:0]const u8) !Id {
500 if (!is_darwin) return error.UnsupportedPlatform;
501 return objc.sel_registerName(name) orelse error.SelectorNotFound;
502}
503
504// =============================================================================
505// Payload parsing. Pure — no Objective-C — so every field the page can send is
506// driven by host tests on every platform.
507// =============================================================================
508
509/// What `pickFile` read out of the payload.
510const PickRequest = struct {
511 /// Null when the page sent no `types`, or sent null — Swift's `[.item]`
512 /// default. Never an empty slice: an empty `types` array is refused at
513 /// parse, so `buildContentTypes` can rely on having at least one entry.
514 types: ?[][]const u8,
515
516 fn deinit(self: PickRequest, allocator: std.mem.Allocator) void {
517 const list = self.types orelse return;
518 for (list) |entry| allocator.free(entry);
519 allocator.free(list);
520 }
521};
522
523/// `types`, and nothing else — Swift reads no other key out of `body` for this
524/// action, and inventing one would create a way for the call to fail that the
525/// shim does not have.
526///
527/// The entries are copied because the caller frees the parsed JSON before the
528/// picker is built.
529fn parsePickRequest(allocator: std.mem.Allocator, data: []const u8) !PickRequest {
530 const parsed = std.json.parseFromSlice(std.json.Value, allocator, data, .{}) catch
531 return BridgeError.InvalidJSON;
532 defer parsed.deinit();
533
534 const root = switch (parsed.value) {
535 .object => |obj| obj,
536 else => return BridgeError.InvalidJSON,
537 };
538
539 const value = root.get("types") orelse return .{ .types = null };
540 const array = switch (value) {
541 // `body["types"] as? [String]` yields nil for JSON null, and nil is
542 // exactly the default case.
543 .null => return .{ .types = null },
544 .array => |items| items,
545 else => {
546 std.log.warn("pickFile refused: types is present but is not an array", .{});
547 return BridgeError.InvalidParameter;
548 },
549 };
550
551 if (array.items.len == 0) {
552 // What `initForOpeningContentTypes:` does with an empty array is not
553 // documented and was not verified, and Swift can reach it by way of a
554 // `compactMap` that dropped everything. Refusing beats presenting a
555 // picker whose behaviour nobody has established.
556 std.log.warn("pickFile refused: types is an empty array", .{});
557 return BridgeError.InvalidParameter;
558 }
559
560 var list = try allocator.alloc([]const u8, array.items.len);
561 var filled: usize = 0;
562 errdefer {
563 for (list[0..filled]) |entry| allocator.free(entry);
564 allocator.free(list);
565 }
566
567 for (array.items) |item| {
568 const text = switch (item) {
569 .string => |s| s,
570 else => {
571 std.log.warn("pickFile refused: types contains a non-string entry", .{});
572 return BridgeError.InvalidParameter;
573 },
574 };
575 list[filled] = try allocator.dupe(u8, text);
576 filled += 1;
577 }
578
579 return .{ .types = list };
580}
581
582/// What `saveFile` read out of the payload. Both slices borrow the parsed JSON,
583/// which the caller keeps alive for the whole write.
584const SaveRequest = struct {
585 data: []const u8,
586 filename: []const u8,
587};
588
589/// `data` and `filename`, both required, and deliberately no third field.
590///
591/// A `mimeType` in the payload is neither read nor refused: `craft.d.ts` and the
592/// README pass one, Swift and Android both ignore it, and erroring on it would
593/// break the documented call for a field that has never meant anything.
594fn parseSaveRequest(root: std.json.ObjectMap) !SaveRequest {
595 const data_value = root.get("data") orelse {
596 std.log.warn("saveFile refused: no data field", .{});
597 return BridgeError.MissingData;
598 };
599 const filename_value = root.get("filename") orelse {
600 std.log.warn("saveFile refused: no filename field", .{});
601 return BridgeError.MissingData;
602 };
603
604 const data = switch (data_value) {
605 .string => |s| s,
606 else => {
607 std.log.warn("saveFile refused: data is not a string", .{});
608 return BridgeError.InvalidParameter;
609 },
610 };
611 const filename = switch (filename_value) {
612 .string => |s| s,
613 else => {
614 std.log.warn("saveFile refused: filename is not a string", .{});
615 return BridgeError.InvalidParameter;
616 },
617 };
618
619 try validateFilename(filename);
620
621 return .{ .data = data, .filename = filename };
622}
623
624/// Refuse a `filename` that would name a file outside `Documents`.
625///
626/// Swift joins the page's string straight on with `appendingPathComponent`, so
627/// `"../Library/Preferences/x.plist"` escapes the directory. Four checks, and
628/// with `/` excluded they are exhaustive for traversal: a `..` component can
629/// then only be the entire name. An ordinary name that merely contains two dots
630/// — `my..notes.txt` — is not refused, because it names nothing but itself.
631fn validateFilename(filename: []const u8) BridgeError!void {
632 if (filename.len == 0) {
633 std.log.warn("saveFile refused: filename is empty", .{});
634 return BridgeError.InvalidParameter;
635 }
636 if (std.mem.indexOfScalar(u8, filename, '/') != null) {
637 std.log.warn("saveFile refused: filename contains a path separator", .{});
638 return BridgeError.InvalidParameter;
639 }
640 if (std.mem.indexOfScalar(u8, filename, 0) != null) {
641 // A NUL would truncate the C string every native path API sees, so the
642 // file written would not be the file named.
643 std.log.warn("saveFile refused: filename contains a NUL byte", .{});
644 return BridgeError.InvalidParameter;
645 }
646 if (std.mem.eql(u8, filename, ".") or std.mem.eql(u8, filename, "..")) {
647 std.log.warn("saveFile refused: filename is a directory reference", .{});
648 return BridgeError.InvalidParameter;
649 }
650}
651
652/// The `data:` prefix Swift tests with `hasPrefix`.
653const data_url_prefix = "data:";
654
655/// The bytes `saveFile` writes, decoded the way Swift decodes them — minus
656/// Swift's two silent no-write paths.
657///
658/// `data:` prefixed: Swift splits on every `","` and requires exactly two parts,
659/// then base64-decodes the second. Both of those can fail, and when either does
660/// Swift writes nothing and *still resolves the path* — the page is told a file
661/// exists where nothing was written, or where a stale earlier file still sits.
662/// Both are `INVALID_PARAMETER` here.
663///
664/// Not `data:` prefixed: the string is written as UTF-8 text, which for bytes
665/// already in hand is a copy. Both branches therefore reduce to "write these
666/// bytes", which is why there is one write path below and not two.
667///
668/// `std.base64.standard.Decoder` has the same strictness as
669/// `Data(base64Encoded:)` with default options: standard alphabet, padding
670/// required, no non-alphabet characters tolerated.
671fn decodeSaveBytes(allocator: std.mem.Allocator, data: []const u8) ![]u8 {
672 if (!std.mem.startsWith(u8, data, data_url_prefix)) {
673 return allocator.dupe(u8, data);
674 }
675
676 if (std.mem.count(u8, data, ",") != 1) {
677 std.log.warn(
678 "saveFile refused: the data URL does not split into exactly two comma-separated " ++
679 "parts, so there is nothing to decode",
680 .{},
681 );
682 return BridgeError.InvalidParameter;
683 }
684
685 const comma = std.mem.indexOfScalar(u8, data, ',').?;
686 const encoded = data[comma + 1 ..];
687
688 const decoder = std.base64.standard.Decoder;
689 const size = decoder.calcSizeForSlice(encoded) catch {
690 std.log.warn("saveFile refused: the data URL payload is not valid base64", .{});
691 return BridgeError.InvalidParameter;
692 };
693
694 const out = try allocator.alloc(u8, size);
695 errdefer allocator.free(out);
696 decoder.decode(out, encoded) catch {
697 std.log.warn("saveFile refused: the data URL payload is not valid base64", .{});
698 return BridgeError.InvalidParameter;
699 };
700 return out;
701}
702
703// =============================================================================
704// Reply shaping. Pure, so the exact bytes the page receives are pinned by host
705// tests on every platform.
706// =============================================================================
707
708/// One picked file, read out of the security-scoped URL. Every field is owned,
709/// including `mime_type` when it is the fallback, so freeing is unconditional.
710const PickedFile = struct {
711 name: []u8,
712 path: []u8,
713 mime_type: []u8,
714 /// The base64 body alone. The `data:` prefix is added by `shapePickedFile`,
715 /// so the bytes are stored once rather than concatenated twice.
716 base64: []u8,
717
718 fn deinit(self: PickedFile, allocator: std.mem.Allocator) void {
719 allocator.free(self.name);
720 allocator.free(self.path);
721 allocator.free(self.mime_type);
722 allocator.free(self.base64);
723 }
724};
725
726/// Swift's fallback when a filename extension maps to no type
727/// (`CraftApp.swift:5081-5083`), used for both the `mimeType` key and the
728/// `data:` prefix, exactly as Swift uses one string for both.
729const default_mime_type = "application/octet-stream";
730
731/// The four-key object `documentPicker(_:didPickDocumentsAt:)` resolves.
732///
733/// Key order is `name`, `path`, `data`, `mimeType` — Swift's literal order.
734/// Swift's own is a `Dictionary` and therefore arbitrary, so no caller can
735/// depend on it, but a test can only pin bytes that are deterministic.
736///
737/// `name`, `path` and `mime_type` are JSON-escaped: filenames are user
738/// controlled and legitimately contain `"` and `\`. The base64 body is appended
739/// raw, because the standard alphabet plus `=` needs no escaping — and that is
740/// *checked* rather than asserted, by the scan below, so a body that somehow
741/// carried anything else is a refusal instead of broken JavaScript in the page.
742fn shapePickedFile(allocator: std.mem.Allocator, file: PickedFile) ![]u8 {
743 if (!isStandardBase64(file.base64)) {
744 // `warn`, not `err`: this is a refusal, which is how every other
745 // refusal in the mobile modules is logged, and the host test below
746 // drives it on purpose.
747 std.log.warn(
748 "pickFile: the encoded body carries a byte outside the base64 alphabet; " ++
749 "refusing rather than emitting a reply that would not parse",
750 .{},
751 );
752 return BridgeError.NativeCallFailed;
753 }
754
755 var out: std.ArrayListUnmanaged(u8) = .empty;
756 errdefer out.deinit(allocator);
757
758 try out.appendSlice(allocator, "{\"name\":\"");
759 try bridge_error.appendJsonEscaped(allocator, &out, file.name);
760 try out.appendSlice(allocator, "\",\"path\":\"");
761 try bridge_error.appendJsonEscaped(allocator, &out, file.path);
762 try out.appendSlice(allocator, "\",\"data\":\"data:");
763 try bridge_error.appendJsonEscaped(allocator, &out, file.mime_type);
764 try out.appendSlice(allocator, ";base64,");
765 try out.appendSlice(allocator, file.base64);
766 try out.appendSlice(allocator, "\",\"mimeType\":\"");
767 try bridge_error.appendJsonEscaped(allocator, &out, file.mime_type);
768 try out.appendSlice(allocator, "\"}");
769
770 return out.toOwnedSlice(allocator);
771}
772
773fn isStandardBase64(s: []const u8) bool {
774 for (s) |c| switch (c) {
775 'A'...'Z', 'a'...'z', '0'...'9', '+', '/', '=' => {},
776 else => return false,
777 };
778 return true;
779}
780
781/// `saveFile`'s reply: the written path as a **bare JSON string**, not an
782/// object.
783///
784/// `resolveCallback` serialises with `.fragmentsAllowed`, so Swift's
785/// `result: fileURL.path` goes on the wire as a bare string, and Android agrees
786/// (`file.absolutePath`). An object here would be a shape nothing is written
787/// for.
788fn shapeSavedPath(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
789 var out: std.ArrayListUnmanaged(u8) = .empty;
790 errdefer out.deinit(allocator);
791
792 try out.append(allocator, '"');
793 try bridge_error.appendJsonEscaped(allocator, &out, path);
794 try out.append(allocator, '"');
795
796 return out.toOwnedSlice(allocator);
797}
798
799// =============================================================================
800// How a delegate callback settles the pending call.
801//
802// The resolve-versus-reject decision is rule 4's, so it lives in one pure
803// function rather than being spelled at each callback: `cancelled` mapping to
804// anything but `reject` is the single most likely way this file could go wrong,
805// and it is pinned by a host test.
806// =============================================================================
807
808/// What a document-picker callback found.
809/// The error code each rejecting outcome deserves.
810///
811/// The distinction was always here — `Outcome` separates a Cancel from an
812/// unreadable file — but there was no channel to carry it, so all four
813/// arrived as NATIVE_CALL_FAILED and the page could not tell "the user said
814/// no" from "something broke". `ios_async.deliverErrorCode` is that channel.
815///
816/// `no_selection` and `dismissed` are cancels in every sense the page cares
817/// about: nothing was picked, and nothing went wrong. Only `unreadable` is a
818/// genuine native failure.
819fn errorFor(outcome: Outcome) bridge_error.BridgeError {
820 return switch (outcome) {
821 .cancelled, .no_selection, .dismissed => bridge_error.BridgeError.Cancelled,
822 .unreadable => bridge_error.BridgeError.NativeCallFailed,
823 .picked => unreachable, // not a rejecting outcome
824 };
825}
826
827const Outcome = enum {
828 /// A file was chosen and its bytes were read.
829 picked,
830 /// The user tapped Cancel — `documentPickerWasCancelled:`.
831 cancelled,
832 /// `didPickDocumentsAtURLs:` with an empty array.
833 no_selection,
834 /// A file was chosen and something about reading or shaping it failed.
835 unreadable,
836 /// The sheet was swiped away — `presentationControllerDidDismiss:`, which
837 /// arrives when `documentPickerWasCancelled:` does not.
838 dismissed,
839};
840
841/// How the page's promise must be settled.
842const Answer = enum { resolve, reject };
843
844/// Swift's mapping, verbatim: only the read-succeeded branch resolves.
845///
846/// `cancelled` is a **reject** (`rejectCallback(pendingCallbackId, error: "Cancelled")`),
847/// not a distinct resolve. `no_selection` is Swift's `"No file selected"`
848/// reject. `unreadable` is this file's divergence 2 — Swift resolves a
849/// data-less `{name, path}` there, which reports success for a file whose
850/// contents nobody read. `dismissed` is a swipe-down: nothing was picked, so
851/// resolving anything would be success for a pick that did not happen.
852fn answerFor(outcome: Outcome) Answer {
853 return switch (outcome) {
854 .picked => .resolve,
855 .cancelled, .no_selection, .unreadable, .dismissed => .reject,
856 };
857}
858
859/// Settle whatever call this picker was serving, and nothing else.
860///
861/// Takes the pending ticket, so a second callback — a late fire, a duplicate —
862/// finds nothing and is a no-op rather than a second reply. `json` is required
863/// for `.resolve` and ignored otherwise; a `.resolve` with no payload is
864/// downgraded to an error rather than resolved empty, because
865/// `craft-bridge.js` settles with `payload || {}` and an empty resolve would
866/// look like success.
867///
868/// Never calls `evaluateJavaScript`: this runs on a framework callback, and the
869/// reply is main-thread-only. `ios_async` owns that hop.
870fn settlePick(outcome: Outcome, json: ?[]const u8) void {
871 const ticket = takePendingPick() orelse {
872 std.log.info(
873 "pickFile: a document-picker callback arrived with no call waiting; ignored",
874 .{},
875 );
876 return;
877 };
878
879 switch (answerFor(outcome)) {
880 .resolve => {
881 const payload = json orelse {
882 std.log.err("pickFile: a resolve was decided with no payload to send", .{});
883 ios_async.deliverError(ticket);
884 return;
885 };
886 ios_async.deliverJson(ticket, payload);
887 },
888 .reject => {
889 // Swift rejects with free text — "Cancelled", "No file selected" —
890 // and `sendErrorToJS` carries an enum, so the exact wording is
891 // still lost. What is no longer lost is the *kind*: `errorFor`
892 // maps a Cancel to CANCELLED and only a genuine read failure to
893 // NATIVE_CALL_FAILED, so a page can tell "the user said no" from
894 // "something broke" without reading a log.
895 ios_async.deliverErrorCode(ticket, errorFor(outcome));
896 },
897 }
898}
899
900// =============================================================================
901// One pending pick, guarded.
902//
903// A picker is modal and serves exactly one call, so there is one slot rather
904// than a pool. It is mutex-guarded even though WebKit delivers the dispatch and
905// UIKit delivers the callbacks on the main thread, because "it should always be
906// the main thread" is not a guard.
907// =============================================================================
908
909var pending_pick: ?ios_async.Ticket = null;
910var pick_mutex: compat_mutex.Mutex = .{};
911
912/// Record the call the delegate will answer. False means one is already
913/// recorded, and the caller must refuse — never replace, which would strand the
914/// first caller's promise forever.
915fn publishPendingPick(ticket: ios_async.Ticket) bool {
916 pick_mutex.lock();
917 defer pick_mutex.unlock();
918 if (pending_pick != null) return false;
919 pending_pick = ticket;
920 return true;
921}
922
923/// Read and clear the slot. Clearing is what makes a second callback a no-op
924/// rather than a second reply, and what lets the next `pickFile` through.
925fn takePendingPick() ?ios_async.Ticket {
926 pick_mutex.lock();
927 defer pick_mutex.unlock();
928 const ticket = pending_pick;
929 pending_pick = null;
930 return ticket;
931}
932
933// =============================================================================
934// The delegate class, built once through `ios_delegate`.
935// =============================================================================
936
937/// Deliberately prefixed, following `bridge_mobile_location.zig`'s
938/// `CraftIOSLocationDelegate`: both this and any desktop registration look a
939/// class up with `objc_getClass` first, so a shared name would let whichever
940/// registered second silently adopt the other's IMPs.
941const delegate_class_name = "CraftIOSDocumentPickerDelegate";
942
943/// The plural, iOS 11+ selector. The deprecated singular
944/// `documentPicker:didPickDocumentAtURL:` is deliberately not registered —
945/// UIKit calls the plural, and registering both would give two answers to one
946/// pick on any OS that still called the old one.
947const sel_did_pick_documents = "documentPicker:didPickDocumentsAtURLs:";
948const sel_was_cancelled = "documentPickerWasCancelled:";
949/// The swipe-down belt, registered on the same delegate. iOS 13+; on anything
950/// older it is never sent. See `attachDismissObserver`.
951const sel_did_dismiss = "presentationControllerDidDismiss:";
952
953/// The delegate instance, held for the life of the process.
954///
955/// `UIDocumentPickerViewController.h:65` declares `delegate` **weak**, and
956/// `ios_delegate.instantiate` does not retain. This var is the strong
957/// reference; without it the first Cancel is a use-after-free.
958var delegate_instance: Id = null;
959
960fn ensureDelegate() !Id {
961 if (!is_darwin) return error.UnsupportedPlatform;
962 if (delegate_instance) |existing| return existing;
963
964 // Plain `fn`, not `export fn`: an exported symbol is process-global and
965 // these names are generic enough to collide with another delegate in the
966 // same binary. `class_addMethod` takes the address either way.
967 const cls = try ios_delegate.defineClass(delegate_class_name, "NSObject", &.{
968 .{
969 .selector = sel_did_pick_documents,
970 .imp = @ptrCast(&documentPickerDidPickDocumentsAtURLs),
971 // `- (void)m:(id)controller :(id)urls`. A wrong encoding still
972 // registers and still dispatches, then reads arguments from the
973 // wrong registers with no crash and no compile error, which is why
974 // the shape is named rather than spelled.
975 .types = ios_delegate.enc.void_two_objects,
976 },
977 .{
978 .selector = sel_was_cancelled,
979 .imp = @ptrCast(&documentPickerWasCancelled),
980 // `- (void)m:(id)controller`.
981 .types = ios_delegate.enc.void_one_object,
982 },
983 .{
984 // `- (void)presentationControllerDidDismiss:(UIPresentationController *)pc`
985 .selector = sel_did_dismiss,
986 .imp = @ptrCast(&documentPickerDidDismissInteractively),
987 .types = ios_delegate.enc.void_one_object,
988 },
989 });
990
991 const instance = (try ios_delegate.instantiate(cls)) orelse return error.NativeCallFailed;
992 delegate_instance = instance;
993 return instance;
994}
995
996/// Dismiss the picker, but only if it is still presented.
997///
998/// `UIDocumentPickerViewController` dismisses itself before calling the
999/// delegate — Swift's two methods contain no `dismiss` call, unlike the image
1000/// picker's. An unconditional dismiss would therefore be a second one, and
1001/// `-dismissViewControllerAnimated:completion:` on a controller with nothing
1002/// presented forwards up the presentation chain and can close something nobody
1003/// asked to close. Reading `presentingViewController` first is what makes this
1004/// safe in both worlds: nil means it has already gone, non-nil means it is
1005/// genuinely still up and the app would otherwise be stuck behind it.
1006fn dismissPicker(controller: Id) void {
1007 if (!is_darwin) return;
1008 if (controller == null) return;
1009
1010 const sel_presenting = objc.sel_registerName("presentingViewController") orelse return;
1011 if (objc.msgSendId(controller, sel_presenting) == null) return;
1012
1013 const sel_dismiss = objc.sel_registerName("dismissViewControllerAnimated:completion:") orelse {
1014 std.log.warn(
1015 "pickFile: no dismissViewControllerAnimated:completion: selector; the document " ++
1016 "picker is still presented",
1017 .{},
1018 );
1019 return;
1020 };
1021 const DismissFn = *const fn (Id, Id, bool, Id) callconv(.c) void;
1022 const dismiss: DismissFn = @ptrCast(&objc.objc_msgSend);
1023 dismiss(controller, sel_dismiss, true, null);
1024}
1025
1026fn documentPickerDidPickDocumentsAtURLs(_: Id, _: Id, controller: Id, urls: Id) callconv(.c) void {
1027 if (!is_darwin) return;
1028
1029 dismissPicker(controller);
1030
1031 const allocator = std.heap.c_allocator;
1032
1033 const sel_first = objc.sel_registerName("firstObject") orelse {
1034 std.log.err("pickFile: no firstObject selector; cannot read the picked URL", .{});
1035 settlePick(.unreadable, null);
1036 return;
1037 };
1038 // `urls.first` in Swift. `firstObject` answers nil for an empty array,
1039 // where `objectAtIndex:0` would raise an uncatchable NSRangeException.
1040 const url = objc.msgSendId(urls, sel_first) orelse {
1041 std.log.warn("pickFile: the document picker returned no URL", .{});
1042 settlePick(.no_selection, null);
1043 return;
1044 };
1045
1046 const file = readPickedFile(allocator, url) catch |err| {
1047 std.log.err(
1048 "pickFile: could not read the picked file ({}); rejecting rather than resolving " ++
1049 "an object with no data, which is what the Swift path does here",
1050 .{err},
1051 );
1052 settlePick(.unreadable, null);
1053 return;
1054 };
1055 defer file.deinit(allocator);
1056
1057 const json = shapePickedFile(allocator, file) catch |err| {
1058 std.log.err("pickFile: could not shape the reply ({})", .{err});
1059 settlePick(.unreadable, null);
1060 return;
1061 };
1062 defer allocator.free(json);
1063
1064 settlePick(.picked, json);
1065}
1066
1067fn documentPickerWasCancelled(_: Id, _: Id, controller: Id) callconv(.c) void {
1068 if (!is_darwin) return;
1069
1070 dismissPicker(controller);
1071
1072 // Swift's `rejectCallback(pendingCallbackId, error: "Cancelled")`. The word
1073 // survives only here — the wire carries a `BridgeError` enum.
1074 std.log.info("pickFile: cancelled by the user", .{});
1075 settlePick(.cancelled, null);
1076}
1077
1078/// The user swiped the sheet away.
1079///
1080/// Nothing is dismissed here: UIKit has already taken the sheet off the screen,
1081/// which is exactly what this callback reports, and sending
1082/// `dismissViewControllerAnimated:` now could close whatever the presenter shows
1083/// next. The only job is to settle the call.
1084///
1085/// Reached with the slot already empty whenever a real callback got there first,
1086/// in which case `settlePick` is a no-op rather than a second answer.
1087fn documentPickerDidDismissInteractively(_: Id, _: Id, _: Id) callconv(.c) void {
1088 if (!is_darwin) return;
1089
1090 std.log.warn(
1091 "pickFile: the picker was dismissed interactively; rejecting the call rather than " ++
1092 "leaving it unanswered on a promise that has no timeout",
1093 .{},
1094 );
1095 settlePick(.dismissed, null);
1096}
1097
1098/// The three selectors the swipe-down belt needs, resolved at dispatch so a
1099/// missing one fails the call rather than silently leaving the only thing that
1100/// answers an interactive dismissal unattached.
1101const DismissSels = struct {
1102 /// `-[UIViewController presentationController]`.
1103 presentation: Id,
1104 /// `-[UIPresentationController delegate]`, read so an existing delegate is
1105 /// never displaced.
1106 delegate: Id,
1107 /// `-[UIPresentationController setDelegate:]` — the same `setDelegate:` the
1108 /// picker's own delegate is installed with.
1109 set_delegate: Id,
1110};
1111
1112/// Point the picker's presentation controller at this module's delegate, so an
1113/// interactive dismissal reaches `presentationControllerDidDismiss:`. Returns
1114/// whether it was attached.
1115///
1116/// `UIDocumentPickerViewController` presents as a form/page sheet, and a
1117/// swipe-down is widely reported not to send `documentPickerWasCancelled:`.
1118/// That report is verified on no device in this repo, so this is a belt and not
1119/// a fix: it costs two messages, and if the report is right it is the only
1120/// thing that ever frees `pending_pick` after a swipe. It matters more here than
1121/// in Swift, because this module *refuses* later calls while one is pending — a
1122/// stranded ticket disables `pickFile` for the life of the process, where Swift
1123/// merely strands the one promise. It is also the same belt
1124/// `bridge_mobile_imagepicker.zig` and `bridge_mobile_contactpicker.zig` carry.
1125///
1126/// A presentation controller that already carries a delegate is left alone and
1127/// reported as not attached: displacing one would change how the picker manages
1128/// its own adaptive presentation, which is a new bug in exchange for a belt.
1129///
1130/// Idempotent against the real cancel. UIKit sends
1131/// `presentationControllerDidDismiss:` only for a user-driven dismissal, never
1132/// for a programmatic one, so it cannot follow a pick or a Cancel that already
1133/// answered — and if it did anyway, `takePendingPick` has already emptied the
1134/// slot and `ios_async`'s generation counter would drop the second delivery.
1135fn attachDismissObserver(picker: Id, delegate: Id, sels: DismissSels) bool {
1136 if (!is_darwin) return false;
1137
1138 const presentation = objc.msgSendId(picker, sels.presentation) orelse return false;
1139 if (objc.msgSendId(presentation, sels.delegate) != null) return false;
1140
1141 objc.msgSendVoid1(presentation, sels.set_delegate, delegate);
1142 return true;
1143}
1144
1145// =============================================================================
1146// Reading the picked file.
1147// =============================================================================
1148
1149/// Read one security-scoped document URL into the four fields the reply needs.
1150///
1151/// The `start`/`stop` pair around the read is the fix described as divergence 1
1152/// in the module comment: the picker was built with `asCopy == NO`, so this URL
1153/// points outside the app container and the read fails on a device without it.
1154/// It is invisible in the simulator, where the URL resolves to an ordinary host
1155/// path and the read succeeds either way — so a green simulator run says
1156/// nothing about this call.
1157fn readPickedFile(allocator: std.mem.Allocator, url: Id) !PickedFile {
1158 if (!is_darwin) return error.UnsupportedPlatform;
1159
1160 const sel_start = try selector("startAccessingSecurityScopedResource");
1161 const sel_stop = try selector("stopAccessingSecurityScopedResource");
1162 const sel_last_component = try selector("lastPathComponent");
1163 const sel_path = try selector("path");
1164 const sel_extension = try selector("pathExtension");
1165 const sel_data_with_url = try selector("dataWithContentsOfURL:");
1166 const sel_base64 = try selector("base64EncodedStringWithOptions:");
1167
1168 // BOOL, and the return matters: the stop must be sent only when the start
1169 // succeeded, because the access counter is balanced.
1170 const scoped = objc.msgSendBool(url, sel_start);
1171 defer if (scoped) objc.msgSend(url, sel_stop);
1172
1173 const name_obj = objc.msgSendId(url, sel_last_component) orelse return error.NativeCallFailed;
1174 const name = try copyNSString(allocator, name_obj);
1175 errdefer allocator.free(name);
1176
1177 const path_obj = objc.msgSendId(url, sel_path) orelse return error.NativeCallFailed;
1178 const path = try copyNSString(allocator, path_obj);
1179 errdefer allocator.free(path);
1180
1181 const extension_obj = objc.msgSendId(url, sel_extension);
1182 const mime_type = try copyMimeType(allocator, extension_obj);
1183 errdefer allocator.free(mime_type);
1184
1185 const NSData = objc.objc_getClass("NSData") orelse return error.ClassNotFound;
1186 // Nil here is Swift's `try?` yielding nil, which is where it resolves an
1187 // object with no `data`. This is the branch that fails on a device without
1188 // the security scope above.
1189 const data_obj = objc.msgSendId1(NSData, sel_data_with_url, url) orelse
1190 return error.FileContentsUnreadable;
1191
1192 // Options 0 — exactly `Data.base64EncodedString()`: standard alphabet,
1193 // padded, no line wrapping.
1194 const base64_obj = objc.msgSendId1(data_obj, sel_base64, @as(c_ulong, 0)) orelse
1195 return error.NativeCallFailed;
1196 const base64 = try copyNSString(allocator, base64_obj);
1197
1198 return .{ .name = name, .path = path, .mime_type = mime_type, .base64 = base64 };
1199}
1200
1201/// `URL.mimeType` from `CraftApp.swift:5078-5085`: the filename extension's
1202/// preferred MIME type, or `application/octet-stream`.
1203///
1204/// A nil at either step is Swift's fallback and not an error — a file with no
1205/// extension, or an extension no type claims, is an ordinary file. The `UTType`
1206/// class *is* looked up again here and a null answer is an error rather than a
1207/// fallback, which is unreachable in practice (`pickFile` refused before
1208/// presenting if the class was absent) but is a guard rather than an assumption.
1209fn copyMimeType(allocator: std.mem.Allocator, extension_obj: Id) ![]u8 {
1210 if (!is_darwin) return error.UnsupportedPlatform;
1211
1212 const fallback = try allocator.dupe(u8, default_mime_type);
1213 errdefer allocator.free(fallback);
1214
1215 if (extension_obj == null) return fallback;
1216
1217 const UTTypeClass = objc.objc_getClass("UTType") orelse return error.ClassNotFound;
1218 const sel_with_extension = try selector("typeWithFilenameExtension:");
1219 const sel_preferred = try selector("preferredMIMEType");
1220
1221 const ut_type = objc.msgSendId1(UTTypeClass, sel_with_extension, extension_obj) orelse
1222 return fallback;
1223 const mime_obj = objc.msgSendId(ut_type, sel_preferred) orelse return fallback;
1224
1225 const mime = try copyNSString(allocator, mime_obj);
1226 allocator.free(fallback);
1227 return mime;
1228}
1229
1230/// The `UTType` array `initForOpeningContentTypes:` takes.
1231///
1232/// Swift's default is `[.item]`, the `UTTypeItem` global. It is built here with
1233/// `+[UTType typeWithIdentifier:@"public.item"]` rather than by `dlsym`-ing the
1234/// `UTType *const` cell: the identifier is documented and stable, and it does
1235/// not depend on the symbol being exported by whatever image loaded the
1236/// framework.
1237///
1238/// Each page-supplied entry is mapped MIME type first and filename extension
1239/// second, as Swift does, and then by identifier — see divergence 4. An entry
1240/// that maps to nothing is refused rather than dropped.
1241///
1242/// `parsePickRequest` refuses an empty `types` array, so the returned array
1243/// always has at least one element.
1244fn buildContentTypes(allocator: std.mem.Allocator, request: PickRequest, UTTypeClass: Id) !Id {
1245 if (!is_darwin) return error.UnsupportedPlatform;
1246
1247 const NSMutableArray = objc.objc_getClass("NSMutableArray") orelse return error.ClassNotFound;
1248 const sel_array = try selector("array");
1249 const sel_add = try selector("addObject:");
1250 const sel_with_identifier = try selector("typeWithIdentifier:");
1251 const sel_with_mime = try selector("typeWithMIMEType:");
1252 const sel_with_extension = try selector("typeWithFilenameExtension:");
1253
1254 const types = objc.msgSendId(NSMutableArray, sel_array) orelse return error.NativeCallFailed;
1255
1256 const listed = request.types orelse {
1257 const ns_item = try objc.createNSString("public.item", allocator);
1258 if (ns_item == null) return error.NativeCallFailed;
1259 const item = objc.msgSendId1(UTTypeClass, sel_with_identifier, ns_item) orelse {
1260 std.log.err("pickFile: UTType has no public.item; cannot build the default", .{});
1261 return BridgeError.NativeCallFailed;
1262 };
1263 objc.msgSendVoid1(types, sel_add, item);
1264 return types;
1265 };
1266
1267 for (listed) |entry| {
1268 const ns_entry = try objc.createNSString(entry, allocator);
1269 if (ns_entry == null) {
1270 std.log.warn("pickFile refused: a types entry is not valid UTF-8", .{});
1271 return BridgeError.InvalidParameter;
1272 }
1273
1274 const mapped =
1275 objc.msgSendId1(UTTypeClass, sel_with_mime, ns_entry) orelse
1276 objc.msgSendId1(UTTypeClass, sel_with_extension, ns_entry) orelse
1277 objc.msgSendId1(UTTypeClass, sel_with_identifier, ns_entry) orelse
1278 {
1279 // Swift's `compactMap` drops this silently and can end up with
1280 // an empty array; dropping a field the page sent is exactly
1281 // what must not happen.
1282 std.log.warn(
1283 "pickFile refused: types entry '{s}' is not a MIME type, a filename " ++
1284 "extension, or a type identifier",
1285 .{entry},
1286 );
1287 return BridgeError.InvalidParameter;
1288 };
1289
1290 // `-[NSMutableArray addObject:]` raises NSInvalidArgumentException on
1291 // nil, which from Zig is an uncatchable crash rather than something the
1292 // page can be told about. `mapped` is non-null by construction above.
1293 objc.msgSendVoid1(types, sel_add, mapped);
1294 }
1295
1296 return types;
1297}
1298
1299// =============================================================================
1300// The Documents directory and the write. Both are the third copy of a chain
1301// `bridge_mobile_db.zig` and `bridge_mobile_locrecording.zig` already carry
1302// file-privately; extracting the shared helper is a change to those two files
1303// and is not made here.
1304// =============================================================================
1305
1306/// `NSDocumentDirectory`.
1307const ns_document_directory: c_ulong = 9;
1308/// `NSUserDomainMask`.
1309const ns_user_domain_mask: c_ulong = 1;
1310/// `NSUTF8StringEncoding`.
1311const ns_utf8_string_encoding: c_ulong = 4;
1312/// `NSDataWritingAtomic`.
1313const ns_data_writing_atomic: c_ulong = 1;
1314
1315/// `NSFileManager` -> `URLsForDirectory:inDomains:` -> `firstObject` -> `path`,
1316/// the chain Swift's `saveFile` runs, with every step guarded.
1317///
1318/// Swift subscripts with `[0]`, which raises `NSRangeException` on an empty
1319/// result; `firstObject` answers nil, and nil here is a named refusal rather
1320/// than an uncatchable SIGABRT.
1321fn documentsPath(allocator: std.mem.Allocator) ![]u8 {
1322 if (!is_darwin) return error.UnsupportedPlatform;
1323
1324 const NSFileManager = objc.objc_getClass("NSFileManager") orelse return error.ClassNotFound;
1325 const sel_default = try selector("defaultManager");
1326 const manager = objc.msgSendId(NSFileManager, sel_default) orelse return error.NativeCallFailed;
1327
1328 const sel_urls = try selector("URLsForDirectory:inDomains:");
1329 // NSUInteger arguments: explicit `c_ulong`, because the variadic msgSend
1330 // cast takes its argument types from what is passed.
1331 const urls = objc.msgSendId2(
1332 manager,
1333 sel_urls,
1334 ns_document_directory,
1335 ns_user_domain_mask,
1336 ) orelse return error.NativeCallFailed;
1337
1338 const sel_first = try selector("firstObject");
1339 const url = objc.msgSendId(urls, sel_first) orelse return error.NotFound;
1340
1341 const sel_path = try selector("path");
1342 const path_obj = objc.msgSendId(url, sel_path) orelse return error.NativeCallFailed;
1343
1344 return copyNSString(allocator, path_obj);
1345}
1346
1347/// Write `bytes` to `path`, atomically.
1348///
1349/// Swift's two branches differ — the base64 one uses `Data.write(to:)` with
1350/// default options (non-atomic) and the text one
1351/// `String.write(to:atomically:true,encoding:.utf8)`. Both are atomic here; the
1352/// difference is observable only in that a crash mid-write leaves the previous
1353/// file intact rather than a truncated one, which is the direction worth being
1354/// wrong in.
1355///
1356/// `writeToFile:options:error:` rather than `writeToFile:atomically:`, purely so
1357/// the `NSError` can be logged: the page's reply carries a `BridgeError` enum
1358/// and the description has nowhere else to go.
1359fn writeFileAtomically(allocator: std.mem.Allocator, path: []const u8, bytes: []const u8) !void {
1360 if (!is_darwin) return error.UnsupportedPlatform;
1361
1362 const NSData = objc.objc_getClass("NSData") orelse return error.ClassNotFound;
1363 const sel_with_bytes = try selector("dataWithBytes:length:");
1364 const sel_write = try selector("writeToFile:options:error:");
1365
1366 const data_obj = objc.msgSendId2(
1367 NSData,
1368 sel_with_bytes,
1369 bytes.ptr,
1370 @as(c_ulong, bytes.len),
1371 ) orelse return error.NativeCallFailed;
1372
1373 const ns_path = try objc.createNSString(path, allocator);
1374 if (ns_path == null) return error.NativeCallFailed;
1375
1376 var write_error: Id = null;
1377 const WriteFn = *const fn (Id, Id, Id, c_ulong, *Id) callconv(.c) bool;
1378 const write_fn: WriteFn = @ptrCast(&objc.objc_msgSend);
1379 const wrote = write_fn(data_obj, sel_write, ns_path, ns_data_writing_atomic, &write_error);
1380
1381 if (!wrote) {
1382 std.log.warn(
1383 "saveFile: could not write '{s}': {s}",
1384 .{ path, readNSString(write_error, "localizedDescription") orelse "(no description)" },
1385 );
1386 return BridgeError.NativeCallFailed;
1387 }
1388}
1389
1390/// An `NSString` as owned bytes, refusing a value `UTF8String` truncated.
1391///
1392/// `-[NSString UTF8String]` is NUL-terminated, so a name or path carrying an
1393/// embedded U+0000 would read back short — and a short path names a *different*
1394/// file. The C-string length is therefore checked against
1395/// `lengthOfBytesUsingEncoding:`, the same check
1396/// `bridge_mobile_locrecording.zig` and `bridge_mobile_notifications.zig` make.
1397fn copyNSString(allocator: std.mem.Allocator, ns_string: Id) ![]u8 {
1398 if (!is_darwin) return error.UnsupportedPlatform;
1399
1400 const cstr = objc.getNSStringUTF8(ns_string) orelse return error.NativeCallFailed;
1401 const bytes = std.mem.span(cstr);
1402
1403 const sel_len = try selector("lengthOfBytesUsingEncoding:");
1404 const LenFn = *const fn (Id, Id, c_ulong) callconv(.c) c_ulong;
1405 const len_fn: LenFn = @ptrCast(&objc.objc_msgSend);
1406 const declared = len_fn(ns_string, sel_len, ns_utf8_string_encoding);
1407
1408 if (declared != bytes.len) {
1409 std.log.warn(
1410 "file picker: a string is {d} UTF-8 bytes but reads back as {d}; refusing rather " ++
1411 "than reporting a truncated name or path",
1412 .{ declared, bytes.len },
1413 );
1414 return error.NativeCallFailed;
1415 }
1416
1417 return allocator.dupe(u8, bytes);
1418}
1419
1420/// A zero-argument `NSString`-returning property, as borrowed bytes. Null for a
1421/// nil object, a nil string, or a selector that will not register — all three
1422/// are "nothing to report". The slice borrows the string's buffer, valid for the
1423/// current autorelease pool; the only caller logs it synchronously.
1424fn readNSString(object: Id, comptime name: [*:0]const u8) ?[]const u8 {
1425 if (!is_darwin) return null;
1426 if (object == null) return null;
1427
1428 const sel = objc.sel_registerName(name) orelse return null;
1429 const value = objc.msgSendId(object, sel) orelse return null;
1430 const utf8 = objc.getNSStringUTF8(value) orelse return null;
1431 return std.mem.span(utf8);
1432}
1433
1434// =============================================================================
1435// Tests - host-only.
1436//
1437// Everything that decides page-visible bytes is pure and pinned here: routing
1438// in both directions, both payloads field by field, the resolve/reject decision
1439// for all four outcomes, the four-key success object and the bare-string save
1440// reply, the base64 and filename guards, and the concurrent-pick refusal.
1441//
1442// Nothing here presents a picker or touches the Documents directory. On a macOS
1443// runner `objc_getClass("UIDocumentPickerViewController")` is null — UIKit is
1444// not loadable there at all — so the UIKit paths are unreachable rather than
1445// merely skipped, and the fixture cannot drive a modal either (it posts raw
1446// envelopes with no way to tap Cancel or choose a file). `saveFile` is the half
1447// that a simulator fixture can drive end to end.
1448// =============================================================================
1449
1450const testing = std.testing;
1451
1452test "the declared actions are the ones the handler serves" {
1453 try testing.expectEqual(@as(usize, 2), capability_actions.len);
1454 try testing.expectEqualStrings(A.pick_file, capability_actions[0].name);
1455 try testing.expectEqualStrings(A.save_file, capability_actions[1].name);
1456
1457 for (capability_actions) |decl| {
1458 // A `.result` whose handler never replies parks the caller until its
1459 // timeout; a `.none` that is awaited resolves immediately and means
1460 // nothing. Swift resolves or rejects both of these.
1461 try testing.expectEqual(capabilities.Reply.result, decl.reply);
1462 try testing.expectEqual(capabilities.ActionStatus.live, decl.status);
1463 // `.live` with a reason would be a contradiction the manifest shows apps.
1464 try testing.expect(decl.reason == null);
1465 }
1466}
1467
1468test "the action names match the Swift case labels exactly" {
1469 try testing.expectEqualStrings("pickFile", A.pick_file);
1470 try testing.expectEqualStrings("saveFile", A.save_file);
1471}
1472
1473test "every declared action is one the dispatcher routes" {
1474 for (capability_actions) |decl| {
1475 if (routeFor(decl.name) == null) {
1476 std.debug.print("declared action '{s}' does not route\n", .{decl.name});
1477 return error.DeclaredActionDoesNotRoute;
1478 }
1479 }
1480}
1481
1482test "every route the dispatcher has is a declared action" {
1483 // The other direction: a route with a handler and no declaration is an
1484 // action the page can call and the manifest denies exists. Each declaration
1485 // must claim a *distinct* route — counting alone would let two rows share
1486 // one route while another went undeclared.
1487 var claimed = std.mem.zeroes([std.enums.values(Route).len]bool);
1488 for (capability_actions) |decl| {
1489 const route = routeFor(decl.name) orelse return error.DeclaredActionDoesNotRoute;
1490 const slot = @backingInt(route);
1491 if (claimed[slot]) {
1492 std.debug.print("two declarations route to {s}\n", .{@tagName(route)});
1493 return error.TwoDeclarationsShareARoute;
1494 }
1495 claimed[slot] = true;
1496 }
1497 for (claimed, 0..) |taken, slot| {
1498 if (!taken) {
1499 std.debug.print(
1500 "route {s} has a handler but no capability_actions row\n",
1501 .{@tagName(@as(Route, @fromBackingInt(@intCast(slot))))},
1502 );
1503 return error.RouteNotDeclared;
1504 }
1505 }
1506}
1507
1508test "the dispatcher reaches both handlers, not just the routing table" {
1509 // The other half of table-versus-dispatch: `routeFor` agreeing with
1510 // `capability_actions` proves nothing if `handleMessage` never calls the
1511 // handler. Both payloads fail early and for their own reason — `saveFile`
1512 // has no `data` field, and `pickFile` finds no UIKit picker class on a
1513 // macOS host — so this is a routing check and not a device test. What it
1514 // rules out is the one silent failure: `UnknownAction`, which
1515 // `ios_dispatch.route` reads as "not mine" and hands to the Swift shim.
1516 var bridge = FilePickerBridge.init(testing.allocator);
1517 defer bridge.deinit();
1518
1519 for (capability_actions) |decl| {
1520 bridge.handleMessage(decl.name, "{}") catch |err| {
1521 try testing.expect(err != BridgeError.UnknownAction);
1522 continue;
1523 };
1524 // Neither can succeed here: `saveFile` is missing its required fields
1525 // and `pickFile` has no picker to present.
1526 std.debug.print("'{s}' unexpectedly succeeded on a host\n", .{decl.name});
1527 return error.HandlerSucceededWithoutADevice;
1528 }
1529}
1530
1531test "an action the namespace does not serve is reported, not ignored" {
1532 var bridge = FilePickerBridge.init(testing.allocator);
1533 defer bridge.deinit();
1534
1535 try testing.expectError(BridgeError.UnknownAction, bridge.handleMessage("noSuchAction", "{}"));
1536
1537 // Casing is how a real typo arrives, and a miss does not fail loudly:
1538 // `ios_dispatch` reads UnknownAction as "not mine" and hands the action to
1539 // the Swift shim, so a typo would silently un-serve the action.
1540 for ([_][]const u8{ "pickfile", "PickFile", "savefile", "SaveFile" }) |typo| {
1541 try testing.expectError(BridgeError.UnknownAction, bridge.handleMessage(typo, "{}"));
1542 }
1543
1544 // The desktop dialog namespace has its own `saveFile`; it is a different
1545 // action reached through a different `t`, and nothing about it belongs here.
1546 try testing.expectError(BridgeError.UnknownAction, bridge.handleMessage("showSaveDialog", "{}"));
1547}
1548
1549test "downloadFile is left with the shim, and left undeclared" {
1550 var bridge = FilePickerBridge.init(testing.allocator);
1551 defer bridge.deinit();
1552
1553 for (deliberately_unserved) |name| {
1554 // `UnknownAction` is the one return `ios_dispatch.route` turns into a
1555 // Swift-shim hand-off. Anything else would take the action away from
1556 // the arm that answers it today.
1557 try testing.expectError(BridgeError.UnknownAction, bridge.handleMessage(name, "{}"));
1558
1559 for (capability_actions) |decl| {
1560 try testing.expect(!std.mem.eql(u8, decl.name, name));
1561 }
1562 try testing.expect(routeFor(name) == null);
1563 }
1564}
1565
1566// -----------------------------------------------------------------------------
1567// pickFile payload.
1568// -----------------------------------------------------------------------------
1569
1570test "pickFile with no types asks for the default single item type" {
1571 // `body[\"types\"] as? [String]` is nil, and Swift's `allowedTypes` stays
1572 // `[.item]`. Null must behave the same as absent, because that is what the
1573 // cast does with a JSON null.
1574 for ([_][]const u8{ "{}", "{\"types\":null}" }) |payload| {
1575 const request = try parsePickRequest(testing.allocator, payload);
1576 defer request.deinit(testing.allocator);
1577 try testing.expect(request.types == null);
1578 }
1579}
1580
1581test "pickFile carries every types entry the page sent, in order" {
1582 const request = try parsePickRequest(
1583 testing.allocator,
1584 "{\"types\":[\"image/png\",\"pdf\",\"public.image\"]}",
1585 );
1586 defer request.deinit(testing.allocator);
1587
1588 const listed = request.types orelse return error.TypesWereDropped;
1589 try testing.expectEqual(@as(usize, 3), listed.len);
1590 try testing.expectEqualStrings("image/png", listed[0]);
1591 try testing.expectEqualStrings("pdf", listed[1]);
1592 try testing.expectEqualStrings("public.image", listed[2]);
1593}
1594
1595test "pickFile refuses a types field it cannot use rather than dropping it" {
1596 // An empty array is what Swift's compactMap can produce, and what
1597 // `initForOpeningContentTypes:` does with one is unverified. A non-array
1598 // and a non-string entry are payloads no page should send, and silently
1599 // treating any of them as the default would widen the types the app asked
1600 // to restrict.
1601 for ([_][]const u8{
1602 "{\"types\":[]}",
1603 "{\"types\":\"image/png\"}",
1604 "{\"types\":42}",
1605 "{\"types\":[\"image/png\",7]}",
1606 "{\"types\":[null]}",
1607 }) |payload| {
1608 try testing.expectError(
1609 BridgeError.InvalidParameter,
1610 parsePickRequest(testing.allocator, payload),
1611 );
1612 }
1613}
1614
1615test "pickFile refuses a payload that is not a JSON object" {
1616 for ([_][]const u8{ "[]", "\"types\"", "not json" }) |payload| {
1617 try testing.expectError(
1618 BridgeError.InvalidJSON,
1619 parsePickRequest(testing.allocator, payload),
1620 );
1621 }
1622}
1623
1624// -----------------------------------------------------------------------------
1625// saveFile payload.
1626// -----------------------------------------------------------------------------
1627
1628/// Parse `json` and hand its root object to `parseSaveRequest`. The request
1629/// borrows the parsed value, so the caller frees them together.
1630fn saveRequestFrom(json: []const u8) !struct {
1631 parsed: std.json.Parsed(std.json.Value),
1632 request: SaveRequest,
1633
1634 fn deinit(self: *@This()) void {
1635 self.parsed.deinit();
1636 }
1637} {
1638 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
1639 errdefer parsed.deinit();
1640 return .{ .parsed = parsed, .request = try parseSaveRequest(parsed.value.object) };
1641}
1642
1643test "saveFile reads data and filename, and nothing else" {
1644 var got = try saveRequestFrom(
1645 "{\"data\":\"hello\",\"filename\":\"notes.txt\",\"mimeType\":\"text/plain\"}",
1646 );
1647 defer got.deinit();
1648
1649 try testing.expectEqualStrings("hello", got.request.data);
1650 try testing.expectEqualStrings("notes.txt", got.request.filename);
1651 // `mimeType` is declared by `craft.d.ts` and passed by the README, and read
1652 // by neither Swift nor Android. Accepting and ignoring it is the only shape
1653 // that neither invents a field nor breaks the documented call.
1654}
1655
1656test "saveFile refuses a payload missing either required field" {
1657 const parsed_a = try std.json.parseFromSlice(
1658 std.json.Value,
1659 testing.allocator,
1660 "{\"filename\":\"a.txt\"}",
1661 .{},
1662 );
1663 defer parsed_a.deinit();
1664 try testing.expectError(BridgeError.MissingData, parseSaveRequest(parsed_a.value.object));
1665
1666 const parsed_b = try std.json.parseFromSlice(
1667 std.json.Value,
1668 testing.allocator,
1669 "{\"data\":\"hello\"}",
1670 .{},
1671 );
1672 defer parsed_b.deinit();
1673 try testing.expectError(BridgeError.MissingData, parseSaveRequest(parsed_b.value.object));
1674}
1675
1676test "saveFile refuses a data or filename of the wrong type" {
1677 for ([_][]const u8{
1678 "{\"data\":7,\"filename\":\"a.txt\"}",
1679 "{\"data\":\"hello\",\"filename\":7}",
1680 "{\"data\":null,\"filename\":\"a.txt\"}",
1681 }) |payload| {
1682 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, payload, .{});
1683 defer parsed.deinit();
1684 try testing.expectError(
1685 BridgeError.InvalidParameter,
1686 parseSaveRequest(parsed.value.object),
1687 );
1688 }
1689}
1690
1691test "a filename that would leave the Documents directory is refused" {
1692 // Swift joins this string on with appendingPathComponent and the write
1693 // lands wherever it points.
1694 for ([_][]const u8{
1695 "",
1696 "..",
1697 ".",
1698 "../Library/Preferences/x.plist",
1699 "sub/dir.txt",
1700 "/etc/passwd",
1701 "a\x00b.txt",
1702 }) |name| {
1703 try testing.expectError(BridgeError.InvalidParameter, validateFilename(name));
1704 }
1705}
1706
1707test "an ordinary filename with dots in it is not refused" {
1708 // The traversal check must not be a substring match on "..": a name with no
1709 // separator cannot name a parent directory whatever dots it contains.
1710 for ([_][]const u8{ "notes.txt", "my..notes.txt", "..hidden", "archive.tar.gz", "a" }) |name| {
1711 try validateFilename(name);
1712 }
1713}
1714
1715// -----------------------------------------------------------------------------
1716// saveFile content decoding.
1717// -----------------------------------------------------------------------------
1718
1719test "a plain string is written as its own bytes" {
1720 const bytes = try decodeSaveBytes(testing.allocator, "hello, world");
1721 defer testing.allocator.free(bytes);
1722 try testing.expectEqualStrings("hello, world", bytes);
1723}
1724
1725test "a base64 data URL is decoded to the bytes it encodes" {
1726 const bytes = try decodeSaveBytes(testing.allocator, "data:text/plain;base64,aGVsbG8=");
1727 defer testing.allocator.free(bytes);
1728 try testing.expectEqualStrings("hello", bytes);
1729}
1730
1731test "an empty base64 body decodes to an empty file, as Swift writes one" {
1732 const bytes = try decodeSaveBytes(testing.allocator, "data:,");
1733 defer testing.allocator.free(bytes);
1734 try testing.expectEqual(@as(usize, 0), bytes.len);
1735}
1736
1737test "a data URL that cannot be decoded is refused, never reported as written" {
1738 // Swift reaches `resolveCallback(callbackId, result: fileURL.path)` for
1739 // every one of these having written nothing: the `if` body just never runs
1740 // and nothing throws. `data:text/plain,hello` is the documented reproducer.
1741 for ([_][]const u8{
1742 "data:text/plain,hello",
1743 "data:",
1744 "data:text/plain;base64",
1745 "data:a,b,c",
1746 "data:text/plain;base64,aGVsbG8",
1747 "data:text/plain;base64,!!!!",
1748 }) |payload| {
1749 try testing.expectError(
1750 BridgeError.InvalidParameter,
1751 decodeSaveBytes(testing.allocator, payload),
1752 );
1753 }
1754}
1755
1756test "a string that merely contains data: is not treated as a data URL" {
1757 // `hasPrefix`, not `contains`.
1758 const bytes = try decodeSaveBytes(testing.allocator, "see data:text/plain,hello");
1759 defer testing.allocator.free(bytes);
1760 try testing.expectEqualStrings("see data:text/plain,hello", bytes);
1761}
1762
1763// -----------------------------------------------------------------------------
1764// Reply shaping.
1765// -----------------------------------------------------------------------------
1766
1767test "a picked file is the four-key object Swift resolves" {
1768 const file = PickedFile{
1769 .name = @constCast("report.pdf"),
1770 .path = @constCast("/private/var/mobile/report.pdf"),
1771 .mime_type = @constCast("application/pdf"),
1772 .base64 = @constCast("aGVsbG8="),
1773 };
1774
1775 const json = try shapePickedFile(testing.allocator, file);
1776 defer testing.allocator.free(json);
1777
1778 try testing.expectEqualStrings(
1779 "{\"name\":\"report.pdf\",\"path\":\"/private/var/mobile/report.pdf\"," ++
1780 "\"data\":\"data:application/pdf;base64,aGVsbG8=\",\"mimeType\":\"application/pdf\"}",
1781 json,
1782 );
1783
1784 // And it is valid JSON with the keys the page reads, not just string-equal.
1785 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
1786 defer parsed.deinit();
1787 try testing.expectEqualStrings("report.pdf", parsed.value.object.get("name").?.string);
1788 try testing.expectEqualStrings(
1789 "data:application/pdf;base64,aGVsbG8=",
1790 parsed.value.object.get("data").?.string,
1791 );
1792}
1793
1794test "a filename carrying quotes and backslashes stays valid JSON" {
1795 // Filenames are user controlled and legitimately contain both. An
1796 // unescaped quote would close the string early and turn the whole reply
1797 // script into a syntax error in the page, with nothing to point at.
1798 const file = PickedFile{
1799 .name = @constCast("we\"ird\\name.txt"),
1800 .path = @constCast("/tmp/we\"ird\\name.txt"),
1801 .mime_type = @constCast("text/plain"),
1802 .base64 = @constCast("QQ=="),
1803 };
1804
1805 const json = try shapePickedFile(testing.allocator, file);
1806 defer testing.allocator.free(json);
1807
1808 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
1809 defer parsed.deinit();
1810 try testing.expectEqualStrings("we\"ird\\name.txt", parsed.value.object.get("name").?.string);
1811 try testing.expectEqualStrings("/tmp/we\"ird\\name.txt", parsed.value.object.get("path").?.string);
1812}
1813
1814test "an encoded body outside the base64 alphabet is refused, not emitted raw" {
1815 // The body is appended without escaping because the standard alphabet needs
1816 // none. This is the check that makes that claim true rather than assumed.
1817 const file = PickedFile{
1818 .name = @constCast("a.txt"),
1819 .path = @constCast("/tmp/a.txt"),
1820 .mime_type = @constCast("text/plain"),
1821 .base64 = @constCast("abc\"def"),
1822 };
1823 try testing.expectError(
1824 BridgeError.NativeCallFailed,
1825 shapePickedFile(testing.allocator, file),
1826 );
1827}
1828
1829test "the saved path goes back as a bare JSON string, not an object" {
1830 // `resolveCallback` serialises with .fragmentsAllowed and Swift resolves
1831 // `fileURL.path`. An object here would be a shape nothing reads.
1832 const json = try shapeSavedPath(testing.allocator, "/var/mobile/Documents/notes.txt");
1833 defer testing.allocator.free(json);
1834
1835 try testing.expectEqualStrings("\"/var/mobile/Documents/notes.txt\"", json);
1836
1837 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
1838 defer parsed.deinit();
1839 try testing.expect(parsed.value == .string);
1840
1841 // And it is truthy: `craft-bridge.js` settles with `payload || {}`, so an
1842 // empty reply would arrive as `{}`. A container path is never empty.
1843 try testing.expect(parsed.value.string.len > 0);
1844}
1845
1846test "a path needing escaping survives the bare-string reply" {
1847 const json = try shapeSavedPath(testing.allocator, "/tmp/we\"ird\\path.txt");
1848 defer testing.allocator.free(json);
1849
1850 const parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
1851 defer parsed.deinit();
1852 try testing.expectEqualStrings("/tmp/we\"ird\\path.txt", parsed.value.string);
1853}
1854
1855// -----------------------------------------------------------------------------
1856// How a callback settles the call.
1857// -----------------------------------------------------------------------------
1858
1859test "a cancel is a rejection, and only a read that succeeded resolves" {
1860 // The single most likely way this file could go wrong, and the one thing
1861 // that cannot be read off a picker in a test: Swift's
1862 // `documentPickerWasCancelled:` calls `rejectCallback(…, \"Cancelled\")`,
1863 // not a resolve, and an empty `urls` array is its `\"No file selected\"`
1864 // reject.
1865 try testing.expectEqual(Answer.resolve, answerFor(.picked));
1866 try testing.expectEqual(Answer.reject, answerFor(.cancelled));
1867 try testing.expectEqual(Answer.reject, answerFor(.no_selection));
1868 // Divergence 2: Swift resolves `{name, path}` here, without the `data` its
1869 // own type declares required.
1870 try testing.expectEqual(Answer.reject, answerFor(.unreadable));
1871 // The swipe-down belt. Nothing was picked, so a resolve would be success
1872 // for a pick that did not happen.
1873 try testing.expectEqual(Answer.reject, answerFor(.dismissed));
1874
1875 // And every outcome is covered: a new one added without a row above would
1876 // otherwise be pinned by nothing.
1877 try testing.expectEqual(@as(usize, 5), std.enums.values(Outcome).len);
1878}
1879
1880test "the swipe-down belt is registered, and only the answer paths reject" {
1881 // Without `presentationControllerDidDismiss:` on the delegate, a sheet the
1882 // user swipes away leaves `pending_pick` set: the call is never answered
1883 // *and* every later pickFile is refused for the life of the process. Two
1884 // sibling picker modules carry the same belt.
1885 try testing.expectEqualStrings("presentationControllerDidDismiss:", sel_did_dismiss);
1886 // `- (void)m:(id)presentationController` — one object, not two.
1887 try testing.expectEqualStrings("v@:@", ios_delegate.enc.void_one_object);
1888}
1889
1890test "the two delegate selectors are the plural pair, with the encodings UIKit calls" {
1891 // A wrong encoding still registers and still dispatches, then reads
1892 // arguments from the wrong registers with no crash and no compile error.
1893 // Naming the shapes is the only defence available, so the pairing is pinned.
1894 try testing.expectEqualStrings("documentPicker:didPickDocumentsAtURLs:", sel_did_pick_documents);
1895 try testing.expectEqualStrings("documentPickerWasCancelled:", sel_was_cancelled);
1896 try testing.expectEqualStrings("v@:@@", ios_delegate.enc.void_two_objects);
1897 try testing.expectEqualStrings("v@:@", ios_delegate.enc.void_one_object);
1898
1899 // And the deprecated singular is not one of them: registering it would give
1900 // two answers to one pick on any OS that still called it.
1901 try testing.expect(!std.mem.eql(u8, sel_did_pick_documents, "documentPicker:didPickDocumentAtURL:"));
1902}
1903
1904test "the delegate class name is this module's own" {
1905 // Both this and any desktop registration look a class up with
1906 // `objc_getClass` first, so a shared name would let whichever registered
1907 // second silently adopt the other's IMPs.
1908 try testing.expectEqualStrings("CraftIOSDocumentPickerDelegate", delegate_class_name);
1909}
1910
1911// -----------------------------------------------------------------------------
1912// One pending pick.
1913// -----------------------------------------------------------------------------
1914
1915test "a second pick while one is presented is refused, never a silent replacement" {
1916 // Swift overwrites its single `pendingCallbackId` and the first caller's
1917 // promise never settles. The refusal is what makes every caller settle.
1918 try testing.expect(takePendingPick() == null);
1919
1920 const first = ios_async.acquire(A.pick_file) orelse return error.PoolUnexpectedlyFull;
1921 defer ios_async.abandon(first);
1922 try testing.expect(publishPendingPick(first));
1923
1924 const second = ios_async.acquire(A.pick_file) orelse return error.PoolUnexpectedlyFull;
1925 defer ios_async.abandon(second);
1926 try testing.expect(!publishPendingPick(second));
1927
1928 // The first ticket is still the one a callback would answer — not the
1929 // second, and not nothing.
1930 const held = takePendingPick() orelse return error.PendingPickWasLost;
1931 try testing.expectEqual(first.index, held.index);
1932 try testing.expectEqual(first.generation, held.generation);
1933
1934 // With the slot free, the next pick takes it.
1935 try testing.expect(publishPendingPick(second));
1936 try testing.expect(takePendingPick() != null);
1937 try testing.expect(takePendingPick() == null);
1938}
1939
1940test "a callback with nothing pending is ignored rather than replying twice" {
1941 // A late fire, or a duplicate: `takePendingPick` cleared the slot on the
1942 // first one, so the second finds nothing. The belt is the ordinary case
1943 // here — UIKit can send `presentationControllerDidDismiss:` after a Cancel
1944 // that already answered, and it must be a no-op, not a second reply.
1945 try testing.expect(takePendingPick() == null);
1946 settlePick(.cancelled, null);
1947 settlePick(.dismissed, null);
1948 settlePick(.picked, "{}");
1949 try testing.expect(takePendingPick() == null);
1950}