| @@ -0,0 +1,541 @@ |
| 1 | +//! The clipboard actions of the `mobile` namespace: `clipboardRead`, |
| 2 | +//! `clipboardWrite`. |
| 3 | +//! |
| 4 | +//! Ported from the two inline arms in `CraftApp.swift`'s dispatcher. The Swift |
| 5 | +//! is eleven lines, and three of its behaviours are deliberately not carried |
| 6 | +//! across: |
| 7 | +//! |
| 8 | +//! 1. **It can leave the caller waiting forever.** Both arms are an `if` with |
| 9 | +//! no `else`, and clipboard is one of the few actions whose promise is built |
| 10 | +//! inline instead of through `_createCallback` — which is the only thing |
| 11 | +//! that installs the 30-second rejection. So a false `enableClipboard`, or a |
| 12 | +//! `text` that is not a string, replies with nothing at all: not resolved, |
| 13 | +//! not rejected, ever. Every path in this file ends in a reply or an error. |
| 14 | +//! 2. **`UIPasteboard.string ?? ""` conflates three different facts.** See |
| 15 | +//! `readClipboard`. |
| 16 | +//! 3. **It reports success for a write it never checked.** See `putString`. |
| 17 | +//! |
| 18 | +//! ## The payload moved, and defaulting it would erase the clipboard |
| 19 | +//! |
| 20 | +//! The Swift-injected `window.craft` posts `text` at the *top level*, a sibling |
| 21 | +//! of `action`. `ios_dispatch` never looks there — it hands a namespace only |
| 22 | +//! the stringified `d`. A page still posting the flat legacy shape therefore |
| 23 | +//! arrives here with `d` absent, which `payloadOf` turns into `{}`. That is why |
| 24 | +//! an absent `text` is `MissingData` rather than a defaulted `""`: defaulting is |
| 25 | +//! precisely how `craft.fs.writeFile` came to write empty files for months, and |
| 26 | +//! here the same mistake would silently *wipe* the user's clipboard and report |
| 27 | +//! success. The page-side call must be |
| 28 | +//! `{t:'mobile', a:'clipboardWrite', d:'{"text":"…"}', i:N}`. |
| 29 | +//! |
| 30 | +//! ## `enableClipboard` is a deliberate behaviour change, recorded here |
| 31 | +//! |
| 32 | +//! The Swift gate reads `config.enableClipboard`, which originates in |
| 33 | +//! TypeScript (`packages/ios/src/index.ts`, defaulting to `false`), is |
| 34 | +//! templated into the Swift `CraftConfig`, and never reaches Zig. Rather than |
| 35 | +//! guess at it or drop it, it is left plumbable: a host can call |
| 36 | +//! `craft_ios_set_clipboard_enabled(false)` at startup. It defaults to |
| 37 | +//! *enabled*, because a default of off would answer every app with |
| 38 | +//! PERMISSION_DENIED until a host that does not exist yet is written. This is a |
| 39 | +//! real change: an app that left `enableClipboard: false` now gets a working |
| 40 | +//! clipboard while the capability object the page reads still says |
| 41 | +//! `clipboard: false`. |
| 42 | + |
| 43 | +const std = @import("std"); |
| 44 | +const builtin = @import("builtin"); |
| 45 | +const capabilities = @import("capabilities.zig"); |
| 46 | +const bridge_error = @import("bridge_error.zig"); |
| 47 | +const objc_runtime = @import("objc_runtime.zig"); |
| 48 | + |
| 49 | +const objc = objc_runtime.objc; |
| 50 | + |
| 51 | +/// The action names, spelled exactly as the Swift `case` labels spell them. |
| 52 | +/// |
| 53 | +/// `test/ios_conformance_test.zig` matches the two lists by string, so a |
| 54 | +/// tidier spelling here does not read as "migrated" — it reads as "Zig serves |
| 55 | +/// an action the spec does not have", and the Swift arm stays live forever. |
| 56 | +pub const A = struct { |
| 57 | + pub const clipboard_read = "clipboardRead"; |
| 58 | + pub const clipboard_write = "clipboardWrite"; |
| 59 | +}; |
| 60 | + |
| 61 | +/// Both `.result`. `clipboardWrite` hands nothing back but is not |
| 62 | +/// fire-and-forget: Swift resolves it with `true`, and `craft.clipboard.write()` |
| 63 | +/// returns a promise the page awaits. Declaring it `.none` would strand that |
| 64 | +/// caller for the whole request timeout. Desktop's `clipboard/writeText` is |
| 65 | +/// `.none` for a reason that does not apply here — `craft-bridge.js` posts it |
| 66 | +/// through `_send`, which resolves on post rather than on an answer. |
| 67 | +pub const capability_actions = [_]capabilities.ActionDecl{ |
| 68 | + .{ .name = A.clipboard_read, .reply = .result }, |
| 69 | + .{ .name = A.clipboard_write, .reply = .result }, |
| 70 | +}; |
| 71 | + |
| 72 | +/// The two literal replies. `clipboardRead` answers a *bare* JSON string and |
| 73 | +/// `clipboardWrite` a bare `true`; `formatResultJS` interpolates whatever it is |
| 74 | +/// given straight into `__craftBridgeResult(...)`, so neither needs wrapping. |
| 75 | +const reply_true = "true"; |
| 76 | +const reply_no_text = "\"\""; |
| 77 | + |
| 78 | +/// NSUTF8StringEncoding, for `-lengthOfBytesUsingEncoding:`. |
| 79 | +const ns_utf8_string_encoding: usize = 4; |
| 80 | + |
| 81 | +/// Whether the app permits clipboard access — the `enableClipboard` gate the |
| 82 | +/// module comment describes. |
| 83 | +/// |
| 84 | +/// A plain `bool`, not an atomic: WebKit delivers |
| 85 | +/// `userContentController:didReceiveScriptMessage:` on the main thread and |
| 86 | +/// `ios_dispatch.handleMessage` runs synchronously from there, so every reader |
| 87 | +/// is the main thread, and the only writer is a host doing this once at startup. |
| 88 | +var clipboard_enabled: bool = true; |
| 89 | + |
| 90 | +pub fn setEnabled(value: bool) void { |
| 91 | + clipboard_enabled = value; |
| 92 | +} |
| 93 | + |
| 94 | +/// Startup hook for a host that wants the Swift gate back, alongside |
| 95 | +/// `craft_ios_deliver_result`. Turning the capability off makes the handlers |
| 96 | +/// *reject* with `PermissionDenied`; it must never reproduce the Swift gate's |
| 97 | +/// actual failure mode, which was silence. |
| 98 | +export fn craft_ios_set_clipboard_enabled(value: bool) callconv(.c) void { |
| 99 | + clipboard_enabled = value; |
| 100 | +} |
| 101 | + |
| 102 | +pub const ClipboardBridge = struct { |
| 103 | + allocator: std.mem.Allocator, |
| 104 | + |
| 105 | + const Self = @This(); |
| 106 | + |
| 107 | + pub fn init(allocator: std.mem.Allocator) Self { |
| 108 | + return .{ .allocator = allocator }; |
| 109 | + } |
| 110 | + |
| 111 | + pub fn deinit(_: *Self) void {} |
| 112 | + |
| 113 | + pub fn handleMessage(self: *Self, action: []const u8, data: []const u8) !void { |
| 114 | + if (std.mem.eql(u8, action, A.clipboard_read)) { |
| 115 | + try self.readClipboard(); |
| 116 | + } else if (std.mem.eql(u8, action, A.clipboard_write)) { |
| 117 | + try self.writeClipboard(data); |
| 118 | + } else { |
| 119 | + return bridge_error.BridgeError.UnknownAction; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + /// Read the pasteboard, and say *which* of the "no text" cases happened. |
| 124 | + /// |
| 125 | + /// The reply is a bare JSON string — `"hello"`, not `{"text":"hello"}`. |
| 126 | + /// That is what the page consumes: `test-bridges.html` does |
| 127 | + /// `'Clipboard: ' + await craft.clipboard.read()`, and an object reply |
| 128 | + /// renders as `[object Object]`. It diverges from desktop |
| 129 | + /// `clipboard/readText`, which answers `{"text":…}`; unifying the two is a |
| 130 | + /// contract change the page has to be rewritten for, so it is not made here |
| 131 | + /// by accident. |
| 132 | + /// |
| 133 | + /// `-hasStrings` is asked first because `-string` on its own cannot tell an |
| 134 | + /// empty pasteboard from a refusal. On iOS 16+ reading contents another app |
| 135 | + /// wrote presents a system confirmation, and a denial yields nil with no |
| 136 | + /// API that reports why. So: no strings at all is answered `""`, which is |
| 137 | + /// true; strings present but `-string` nil is `PermissionDenied`, because |
| 138 | + /// something was there and we were not given it. Swift answered `""` to |
| 139 | + /// both, and to a pasteboard holding an image. |
| 140 | + /// |
| 141 | + /// **This action can put an alert on the screen.** A page that calls it on |
| 142 | + /// load shows the user an unexplained paste prompt. Two things I could not |
| 143 | + /// verify and that want confirming on a device (the simulator never prompts, |
| 144 | + /// because a same-app write never does): that `-hasStrings` is itself |
| 145 | + /// prompt-free, and whether `-string` blocks until the user answers — if it |
| 146 | + /// does, it blocks this whole synchronous dispatch, and the page's |
| 147 | + /// 30-second request timeout can fire before the tap. |
| 148 | + fn readClipboard(self: *Self) !void { |
| 149 | + if (!clipboard_enabled) return bridge_error.BridgeError.PermissionDenied; |
| 150 | + |
| 151 | + const pasteboard = try generalPasteboard(); |
| 152 | + if (!try hasStrings(pasteboard)) { |
| 153 | + bridge_error.sendResultToJS(self.allocator, A.clipboard_read, reply_no_text); |
| 154 | + return; |
| 155 | + } |
| 156 | + |
| 157 | + const text = try pasteboardString(pasteboard) orelse |
| 158 | + return bridge_error.BridgeError.PermissionDenied; |
| 159 | + |
| 160 | + const json = try quoteAsJsonString(self.allocator, text); |
| 161 | + defer self.allocator.free(json); |
| 162 | + bridge_error.sendResultToJS(self.allocator, A.clipboard_read, json); |
| 163 | + } |
| 164 | + |
| 165 | + /// Write `text` to the pasteboard. Requires the field; does not invent it. |
| 166 | + /// |
| 167 | + /// An explicitly-sent empty `text` is written and acknowledged. Clearing the |
| 168 | + /// clipboard is a legitimate request, and `bridge_clipboard.zig`'s |
| 169 | + /// `if (text.len == 0) return;` is a silent drop the caller cannot tell from |
| 170 | + /// a success. Only an *absent* `text` is an error. |
| 171 | + /// |
| 172 | + /// A non-string `text` is `InvalidParameter`, not coerced. The legacy JS |
| 173 | + /// posts whatever the caller passed without a `String(...)` — unlike |
| 174 | + /// `craft-bridge.js:565` — so a page handing in a number reaches here, and |
| 175 | + /// guessing what it meant would put a stringified guess on the user's |
| 176 | + /// clipboard. |
| 177 | + fn writeClipboard(self: *Self, data: []const u8) !void { |
| 178 | + if (!clipboard_enabled) return bridge_error.BridgeError.PermissionDenied; |
| 179 | + |
| 180 | + var parsed = std.json.parseFromSlice(std.json.Value, self.allocator, data, .{}) catch |err| switch (err) { |
| 181 | + // An allocation failure is not a malformed payload, and telling the |
| 182 | + // page INVALID_JSON about its own perfectly good JSON sends whoever |
| 183 | + // debugs it to the wrong side of the bridge. |
| 184 | + error.OutOfMemory => return err, |
| 185 | + else => return bridge_error.BridgeError.InvalidJSON, |
| 186 | + }; |
| 187 | + defer parsed.deinit(); |
| 188 | + |
| 189 | + const text = try requiredText(parsed.value); |
| 190 | + try putString(self.allocator, text); |
| 191 | + bridge_error.sendResultToJS(self.allocator, A.clipboard_write, reply_true); |
| 192 | + } |
| 193 | +}; |
| 194 | + |
| 195 | +/// The `text` field, or the reason it cannot be used. Pure, so the host tests |
| 196 | +/// can pin the three outcomes that the Swift `as? String` collapsed into one |
| 197 | +/// silent fall-through. |
| 198 | +fn requiredText(payload: std.json.Value) ![]const u8 { |
| 199 | + const object = switch (payload) { |
| 200 | + .object => |o| o, |
| 201 | + else => return bridge_error.BridgeError.InvalidJSON, |
| 202 | + }; |
| 203 | + const field = object.get("text") orelse return bridge_error.BridgeError.MissingData; |
| 204 | + return switch (field) { |
| 205 | + .string => |s| s, |
| 206 | + else => bridge_error.BridgeError.InvalidParameter, |
| 207 | + }; |
| 208 | +} |
| 209 | + |
| 210 | +/// Render `s` as a complete JSON string literal, quotes included. |
| 211 | +/// |
| 212 | +/// `bridge_error.appendJsonEscaped` rather than the hand-rolled loop in |
| 213 | +/// `bridge_clipboard.zig:200`, which misses every control byte below 0x20. |
| 214 | +/// Clipboard contents are arbitrary user bytes and this string is interpolated |
| 215 | +/// into JavaScript that `evaluateJavaScript:` then parses as source. |
| 216 | +/// |
| 217 | +/// Allocated rather than built in a stack buffer: unlike a device description, |
| 218 | +/// clipboard text has no ceiling, and a fixed buffer would truncate the paste |
| 219 | +/// into a syntax error in the page. |
| 220 | +fn quoteAsJsonString(allocator: std.mem.Allocator, s: []const u8) ![]u8 { |
| 221 | + var out: std.ArrayListUnmanaged(u8) = .empty; |
| 222 | + errdefer out.deinit(allocator); |
| 223 | + |
| 224 | + try out.append(allocator, '"'); |
| 225 | + try bridge_error.appendJsonEscaped(allocator, &out, s); |
| 226 | + try out.append(allocator, '"'); |
| 227 | + |
| 228 | + return out.toOwnedSlice(allocator); |
| 229 | +} |
| 230 | + |
| 231 | +/// `+[UIPasteboard generalPasteboard]`. |
| 232 | +/// |
| 233 | +/// Both nulls are real conditions and neither is skipped: `objc_getClass` |
| 234 | +/// answers null when UIKit is not in the process, and `generalPasteboard` |
| 235 | +/// answers nil in an app extension, where `UIPasteboard` is unavailable |
| 236 | +/// outright. |
| 237 | +fn generalPasteboard() !objc.id { |
| 238 | + if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform; |
| 239 | + |
| 240 | + const UIPasteboard = objc.objc_getClass("UIPasteboard") orelse return error.ClassNotFound; |
| 241 | + const sel = objc.sel_registerName("generalPasteboard") orelse return error.SelectorNotFound; |
| 242 | + const pasteboard = objc.msgSendId(UIPasteboard, sel); |
| 243 | + if (pasteboard == null) return error.NoPasteboard; |
| 244 | + return pasteboard; |
| 245 | +} |
| 246 | + |
| 247 | +/// `-[UIPasteboard hasStrings]` — whether there is any text to ask for. |
| 248 | +fn hasStrings(pasteboard: objc.id) !bool { |
| 249 | + if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform; |
| 250 | + |
| 251 | + const sel = objc.sel_registerName("hasStrings") orelse return error.SelectorNotFound; |
| 252 | + return objc.msgSendBool(pasteboard, sel); |
| 253 | +} |
| 254 | + |
| 255 | +/// `-[UIPasteboard changeCount]`. |
| 256 | +/// |
| 257 | +/// No helper for this in `objc_runtime.zig`, which stops at id/bool/stret, so |
| 258 | +/// the cast is local. `NSInteger` is 64-bit on every supported iOS target, |
| 259 | +/// hence `isize`. |
| 260 | +fn changeCount(pasteboard: objc.id) !isize { |
| 261 | + if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform; |
| 262 | + |
| 263 | + const sel = objc.sel_registerName("changeCount") orelse return error.SelectorNotFound; |
| 264 | + const Fn = *const fn (objc.id, objc.SEL) callconv(.c) isize; |
| 265 | + const func: Fn = @ptrCast(&objc.objc_msgSend); |
| 266 | + return func(pasteboard, sel); |
| 267 | +} |
| 268 | + |
| 269 | +/// `-[UIPasteboard string]`, borrowed as UTF-8. Null means the pasteboard |
| 270 | +/// returned nil — which the caller, not this function, decides the meaning of. |
| 271 | +/// |
| 272 | +/// The bytes belong to the autoreleased NSString and live until the pool drains |
| 273 | +/// at the end of this run-loop turn; every caller here copies or compares |
| 274 | +/// before returning. |
| 275 | +fn pasteboardString(pasteboard: objc.id) !?[]const u8 { |
| 276 | + if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform; |
| 277 | + |
| 278 | + const sel = objc.sel_registerName("string") orelse return error.SelectorNotFound; |
| 279 | + const ns = objc.msgSendId(pasteboard, sel); |
| 280 | + if (ns == null) return null; |
| 281 | + return try nsStringUTF8(ns); |
| 282 | +} |
| 283 | + |
| 284 | +/// The UTF-8 bytes of an NSString. |
| 285 | +/// |
| 286 | +/// The length comes from `-lengthOfBytesUsingEncoding:` rather than from |
| 287 | +/// scanning for the terminator: an NSString may legitimately contain U+0000, |
| 288 | +/// and `std.mem.span` would truncate there without saying so — the same quiet |
| 289 | +/// data loss as a dropped payload field, on bytes the user chose. A zero length |
| 290 | +/// means empty or not representable as UTF-8, and both answer `""`. |
| 291 | +fn nsStringUTF8(ns: objc.id) ![]const u8 { |
| 292 | + if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform; |
| 293 | + |
| 294 | + const utf8 = objc.getNSStringUTF8(ns) orelse return error.NilString; |
| 295 | + |
| 296 | + const sel_len = objc.sel_registerName("lengthOfBytesUsingEncoding:") orelse |
| 297 | + return error.SelectorNotFound; |
| 298 | + const Fn = *const fn (objc.id, objc.SEL, usize) callconv(.c) usize; |
| 299 | + const func: Fn = @ptrCast(&objc.objc_msgSend); |
| 300 | + const len = func(ns, sel_len, ns_utf8_string_encoding); |
| 301 | + |
| 302 | + return utf8[0..len]; |
| 303 | +} |
| 304 | + |
| 305 | +/// `-[UIPasteboard setString:]`, then evidence that it landed. |
| 306 | +/// |
| 307 | +/// `setString:` returns void, so "the call did not crash" is not evidence, and |
| 308 | +/// replying `true` on that alone is the fabricated success this migration |
| 309 | +/// exists to remove. `-changeCount` is the one real observation available: a |
| 310 | +/// bump means the pasteboard genuinely changed. |
| 311 | +/// |
| 312 | +/// A stationary count is not immediately a failure, though. I could not confirm |
| 313 | +/// that writing text identical to the current contents still bumps the count, |
| 314 | +/// and rejecting a correct "copy pressed twice" would be its own false report — |
| 315 | +/// so no bump falls back to reading the contents back and comparing bytes. Only |
| 316 | +/// *unchanged count and contents that are not what we asked for* is reported as |
| 317 | +/// `NativeCallFailed`. A nil read-back counts as "there is no text on the |
| 318 | +/// pasteboard", which matches a request to write an empty string and nothing |
| 319 | +/// else. |
| 320 | +/// |
| 321 | +/// The fallback read can itself raise the iOS 16+ paste prompt, in the one case |
| 322 | +/// where it runs: the write appears not to have landed, so another app may |
| 323 | +/// still own the contents. That is rare enough to be worth the certainty, and |
| 324 | +/// the alternative is answering with a guess. |
| 325 | +fn putString(allocator: std.mem.Allocator, text: []const u8) !void { |
| 326 | + if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform; |
| 327 | + |
| 328 | + const pasteboard = try generalPasteboard(); |
| 329 | + const before = try changeCount(pasteboard); |
| 330 | + |
| 331 | + // Autoreleased by `+stringWithUTF8String:`; releasing it here would |
| 332 | + // over-release something the pasteboard has retained. |
| 333 | + const ns_text = try objc.createNSString(text, allocator); |
| 334 | + const sel_set = objc.sel_registerName("setString:") orelse return error.SelectorNotFound; |
| 335 | + objc.msgSendVoid1(pasteboard, sel_set, ns_text); |
| 336 | + |
| 337 | + if (try changeCount(pasteboard) != before) return; |
| 338 | + |
| 339 | + const current = try pasteboardString(pasteboard); |
| 340 | + const landed = if (current) |c| std.mem.eql(u8, c, text) else text.len == 0; |
| 341 | + if (!landed) return bridge_error.BridgeError.NativeCallFailed; |
| 342 | +} |
| 343 | + |
| 344 | +const testing = std.testing; |
| 345 | + |
| 346 | +test "the declared actions are the ones the handler serves" { |
| 347 | + try testing.expectEqual(@as(usize, 2), capability_actions.len); |
| 348 | + try testing.expectEqualStrings(A.clipboard_read, capability_actions[0].name); |
| 349 | + try testing.expectEqualStrings(A.clipboard_write, capability_actions[1].name); |
| 350 | + |
| 351 | + // `.result` for both, including the write. A `.none` write would let a |
| 352 | + // page's `await craft.clipboard.write(x)` sit until the request timeout. |
| 353 | + for (capability_actions) |decl| { |
| 354 | + try testing.expectEqual(capabilities.Reply.result, decl.reply); |
| 355 | + try testing.expectEqual(capabilities.ActionStatus.live, decl.status); |
| 356 | + } |
| 357 | +} |
| 358 | + |
| 359 | +test "the action names match the Swift case labels exactly" { |
| 360 | + // The conformance ratchet compares these strings against the labels in |
| 361 | + // `CraftApp.swift`. A prettier spelling here would leave the Swift arm live |
| 362 | + // and register the migration as having served an action nobody asked for. |
| 363 | + try testing.expectEqualStrings("clipboardRead", A.clipboard_read); |
| 364 | + try testing.expectEqualStrings("clipboardWrite", A.clipboard_write); |
| 365 | +} |
| 366 | + |
| 367 | +test "every declared action dispatches to something" { |
| 368 | + // It may well fail for want of UIKit on the host — that is fine and is not |
| 369 | + // what this asserts. What it rules out is a name in the table that |
| 370 | + // `handleMessage` does not compare against, which is the drift the |
| 371 | + // capabilities mechanism exists to prevent. |
| 372 | + var bridge = ClipboardBridge.init(testing.allocator); |
| 373 | + defer bridge.deinit(); |
| 374 | + |
| 375 | + for (capability_actions) |decl| { |
| 376 | + bridge.handleMessage(decl.name, "{}") catch |err| { |
| 377 | + try testing.expect(err != bridge_error.BridgeError.UnknownAction); |
| 378 | + }; |
| 379 | + } |
| 380 | +} |
| 381 | + |
| 382 | +test "an action the namespace does not serve is reported, not ignored" { |
| 383 | + var bridge = ClipboardBridge.init(testing.allocator); |
| 384 | + defer bridge.deinit(); |
| 385 | + |
| 386 | + try testing.expectError( |
| 387 | + bridge_error.BridgeError.UnknownAction, |
| 388 | + bridge.handleMessage("clipboardClear", "{}"), |
| 389 | + ); |
| 390 | + // Near-misses too: the desktop spelling is a different action on a |
| 391 | + // different namespace and must not be quietly accepted here. |
| 392 | + try testing.expectError( |
| 393 | + bridge_error.BridgeError.UnknownAction, |
| 394 | + bridge.handleMessage("writeText", "{\"text\":\"x\"}"), |
| 395 | + ); |
| 396 | +} |
| 397 | + |
| 398 | +test "an absent text field is refused rather than defaulted to empty" { |
| 399 | + // The single highest-risk case in this migration: a page still posting the |
| 400 | + // flat legacy shape (`text` beside `action`, no `d`) arrives as `{}`. A |
| 401 | + // default would wipe the user's clipboard and report success. |
| 402 | + const allocator = testing.allocator; |
| 403 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, "{}", .{}); |
| 404 | + defer parsed.deinit(); |
| 405 | + |
| 406 | + try testing.expectError(bridge_error.BridgeError.MissingData, requiredText(parsed.value)); |
| 407 | +} |
| 408 | + |
| 409 | +test "a legacy top-level text field does not count as the payload" { |
| 410 | + const allocator = testing.allocator; |
| 411 | + var parsed = try std.json.parseFromSlice( |
| 412 | + std.json.Value, |
| 413 | + allocator, |
| 414 | + "{\"action\":\"clipboardWrite\",\"callbackId\":\"cb_1\"}", |
| 415 | + .{}, |
| 416 | + ); |
| 417 | + defer parsed.deinit(); |
| 418 | + |
| 419 | + try testing.expectError(bridge_error.BridgeError.MissingData, requiredText(parsed.value)); |
| 420 | +} |
| 421 | + |
| 422 | +test "text is read from the field the page actually sends" { |
| 423 | + const allocator = testing.allocator; |
| 424 | + var parsed = try std.json.parseFromSlice( |
| 425 | + std.json.Value, |
| 426 | + allocator, |
| 427 | + "{\"text\":\"hello \\\"world\\\"\"}", |
| 428 | + .{}, |
| 429 | + ); |
| 430 | + defer parsed.deinit(); |
| 431 | + |
| 432 | + try testing.expectEqualStrings("hello \"world\"", try requiredText(parsed.value)); |
| 433 | +} |
| 434 | + |
| 435 | +test "an explicitly empty text is a value, not a missing field" { |
| 436 | + // Clearing the clipboard is a legitimate request. `bridge_clipboard.zig` |
| 437 | + // returns early on a zero-length string and acknowledges nothing, which the |
| 438 | + // caller cannot tell from success. |
| 439 | + const allocator = testing.allocator; |
| 440 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, "{\"text\":\"\"}", .{}); |
| 441 | + defer parsed.deinit(); |
| 442 | + |
| 443 | + try testing.expectEqualStrings("", try requiredText(parsed.value)); |
| 444 | +} |
| 445 | + |
| 446 | +test "a non-string text is refused rather than coerced" { |
| 447 | + // The legacy JS posts whatever the caller passed, with no `String(...)`. |
| 448 | + const allocator = testing.allocator; |
| 449 | + for ([_][]const u8{ |
| 450 | + "{\"text\":42}", |
| 451 | + "{\"text\":null}", |
| 452 | + "{\"text\":true}", |
| 453 | + "{\"text\":{\"a\":1}}", |
| 454 | + "{\"text\":[\"a\"]}", |
| 455 | + }) |payload| { |
| 456 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, payload, .{}); |
| 457 | + defer parsed.deinit(); |
| 458 | + try testing.expectError(bridge_error.BridgeError.InvalidParameter, requiredText(parsed.value)); |
| 459 | + } |
| 460 | +} |
| 461 | + |
| 462 | +test "a payload that is not an object is refused" { |
| 463 | + const allocator = testing.allocator; |
| 464 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, "\"hello\"", .{}); |
| 465 | + defer parsed.deinit(); |
| 466 | + |
| 467 | + try testing.expectError(bridge_error.BridgeError.InvalidJSON, requiredText(parsed.value)); |
| 468 | +} |
| 469 | + |
| 470 | +test "malformed payload JSON is reported as such, not as a missing field" { |
| 471 | + var bridge = ClipboardBridge.init(testing.allocator); |
| 472 | + defer bridge.deinit(); |
| 473 | + |
| 474 | + try testing.expectError( |
| 475 | + bridge_error.BridgeError.InvalidJSON, |
| 476 | + bridge.handleMessage(A.clipboard_write, "{\"text\":"), |
| 477 | + ); |
| 478 | +} |
| 479 | + |
| 480 | +test "the read reply is a bare JSON string, not an object" { |
| 481 | + // `test-bridges.html` concatenates the result: `'Clipboard: ' + result`. |
| 482 | + // An object would render as `[object Object]`. |
| 483 | + const allocator = testing.allocator; |
| 484 | + const json = try quoteAsJsonString(allocator, "hello"); |
| 485 | + defer allocator.free(json); |
| 486 | + try testing.expectEqualStrings("\"hello\"", json); |
| 487 | +} |
| 488 | + |
| 489 | +test "read replies survive quotes, backslashes, newlines, and control bytes" { |
| 490 | + // Clipboard contents are arbitrary user bytes and this lands inside |
| 491 | + // JavaScript source. The escape loop in `bridge_clipboard.zig` passes |
| 492 | + // control bytes through untouched, which produces invalid JSON. |
| 493 | + const allocator = testing.allocator; |
| 494 | + const json = try quoteAsJsonString(allocator, "a\"b\\c\nd\te\x01f"); |
| 495 | + defer allocator.free(json); |
| 496 | + try testing.expectEqualStrings("\"a\\\"b\\\\c\\nd\\te\\u0001f\"", json); |
| 497 | + |
| 498 | + // And it is still parseable as the string it started as. |
| 499 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{}); |
| 500 | + defer parsed.deinit(); |
| 501 | + try testing.expectEqualStrings("a\"b\\c\nd\te\x01f", parsed.value.string); |
| 502 | +} |
| 503 | + |
| 504 | +test "an empty clipboard is reported as an empty string, and it parses" { |
| 505 | + const allocator = testing.allocator; |
| 506 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, reply_no_text, .{}); |
| 507 | + defer parsed.deinit(); |
| 508 | + try testing.expectEqualStrings("", parsed.value.string); |
| 509 | +} |
| 510 | + |
| 511 | +test "the write reply is bare true, which is what the page resolves with" { |
| 512 | + const allocator = testing.allocator; |
| 513 | + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, reply_true, .{}); |
| 514 | + defer parsed.deinit(); |
| 515 | + try testing.expect(parsed.value.bool); |
| 516 | +} |
| 517 | + |
| 518 | +test "a disabled clipboard rejects both actions rather than falling silent" { |
| 519 | + // The Swift gate's failure mode was a promise that never settled. Whatever |
| 520 | + // is decided about `enableClipboard`, that must not come back. |
| 521 | + var bridge = ClipboardBridge.init(testing.allocator); |
| 522 | + defer bridge.deinit(); |
| 523 | + |
| 524 | + setEnabled(false); |
| 525 | + defer setEnabled(true); |
| 526 | + |
| 527 | + try testing.expectError( |
| 528 | + bridge_error.BridgeError.PermissionDenied, |
| 529 | + bridge.handleMessage(A.clipboard_read, "{}"), |
| 530 | + ); |
| 531 | + try testing.expectError( |
| 532 | + bridge_error.BridgeError.PermissionDenied, |
| 533 | + bridge.handleMessage(A.clipboard_write, "{\"text\":\"x\"}"), |
| 534 | + ); |
| 535 | +} |
| 536 | + |
| 537 | +test "UIKit work is refused explicitly off Darwin instead of being skipped" { |
| 538 | + if (builtin.target.os.tag.isDarwin()) return error.SkipZigTest; |
| 539 | + try testing.expectError(error.UnsupportedPlatform, generalPasteboard()); |
| 540 | + try testing.expectError(error.UnsupportedPlatform, putString(testing.allocator, "x")); |
| 541 | +} |