ReviewOS

also looking at this

craft-native/craft

feat(android): getCalendarEvents and createCalendarEvent in Zig — ratchet 86 → 84

#158
Merged glennmichael123 wants to merge feat/android-calendar-events into main
7 files +1167 -20

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

packages/android/templates/CraftBridge.kt.templatemodified+4-0
Changes to packages/android/templates/CraftBridge.kt.template
@@ -2331,6 +2331,10 @@ class CraftBridge(
23312331
23322332 @JavascriptInterface
23332333 fun createCalendarEvent(eventJson: String) {
2334 // Zig answers through the reply channel, so returning here is what
2335 // stops the promise being settled twice.
2336 if (CraftNative.createCalendarEvent(activity, eventJson)) return
2337
23342338 if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR)
23352339 != PackageManager.PERMISSION_GRANTED) {
23362340 ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.WRITE_CALENDAR), REQUEST_CALENDAR)
packages/android/templates/CraftNative.kt.templatemodified+18-0
Changes to packages/android/templates/CraftNative.kt.template
@@ -109,6 +109,7 @@ object CraftNative {
109109 private external fun nativeCancelAllNotifications(activity: Activity): Boolean
110110 private external fun nativeDeleteCalendarEvent(activity: Activity, eventId: String): Boolean
111111 private external fun nativeGetCalendarEvents(activity: Activity, startDateMs: Long, endDateMs: Long): Boolean
112 private external fun nativeCreateCalendarEvent(activity: Activity, eventJson: String): Boolean
112113
113114 /**
114115 * `getDeviceInfo`, or null to use the Kotlin implementation.
@@ -367,4 +368,21 @@ object CraftNative {
367368 false
368369 }
369370 }
371
372 /**
373 * Returns whether Zig took the action.
374 *
375 * A false here is routine rather than exceptional: Zig serves the shape
376 * `NewCalendarEvent` declares and hands anything else back, because
377 * `org.json` coerces where a strict parser refuses. The Kotlin below is
378 * what answers those.
379 */
380 fun createCalendarEvent(activity: Activity, eventJson: String): Boolean {
381 if (!isAvailable) return false
382 return try {
383 nativeCreateCalendarEvent(activity, eventJson)
384 } catch (e: UnsatisfiedLinkError) {
385 false
386 }
387 }
370388}
packages/zig/src/android_dispatch.zigmodified+71-1
Changes to packages/zig/src/android_dispatch.zig
@@ -72,6 +72,9 @@ const backing = std.heap.page_allocator;
7272/// asked for.
7373const request_calendar: i32 = 1005;
7474
75/// The shim's default event length: `System.currentTimeMillis() + 3600000`.
76const one_hour_ms: i64 = 60 * 60 * 1000;
77
7578/// The VM, captured at load so a later callback on a framework thread can ask
7679/// it for that thread's `JNIEnv`.
7780///
@@ -240,6 +243,11 @@ const natives = [_]jni.JNINativeMethod{
240243 .signature = "(Landroid/app/Activity;JJ)Z",
241244 .fnPtr = @ptrCast(&nativeGetCalendarEvents),
242245 },
246 .{
247 .name = "nativeCreateCalendarEvent",
248 .signature = "(Landroid/app/Activity;Ljava/lang/String;)Z",
249 .fnPtr = @ptrCast(&nativeCreateCalendarEvent),
250 },
243251};
244252
245253/// How binding went. A value rather than a log line, so every path is
@@ -719,6 +727,68 @@ fn nativeGetCalendarEvents(
719727 return jni.JNI_TRUE;
720728}
721729
730/// `nativeCreateCalendarEvent(activity, eventJson)`.
731///
732/// Returns false — leaving the shim to serve it — for any payload outside the
733/// shape `NewCalendarEvent` declares. `org.json` coerces a `startDate` sent as
734/// a string and a `title` sent as a number, and the string forms it produces
735/// for a `Double` are not something to reproduce from memory. Declining is
736/// cheap here because nothing has been sent yet.
737fn nativeCreateCalendarEvent(
738 env: jni.JNIEnv,
739 _: jni.jobject,
740 activity: jni.jobject,
741 event_json: jni.jstring,
742) callconv(.c) jni.jboolean {
743 const j = Jni.init(env);
744 var arena = std.heap.ArenaAllocator.init(backing);
745 defer arena.deinit();
746 const allocator = arena.allocator();
747
748 const granted = permissions.isGranted(j, activity, permissions.write_calendar) catch |err| {
749 std.log.warn("craft: createCalendarEvent fell through to the shim ({s})", .{@errorName(err)});
750 return jni.JNI_FALSE;
751 };
752
753 if (!granted) {
754 permissions.request(j, activity, permissions.write_calendar, request_calendar) catch |err| {
755 std.log.warn("craft: createCalendarEvent fell through to the shim ({s})", .{@errorName(err)});
756 return jni.JNI_FALSE;
757 };
758 events.settle(allocator, calendar.create_reject_global, "\"Permission denied\"") catch return jni.JNI_FALSE;
759 return jni.JNI_TRUE;
760 }
761
762 const text = j.stringToUtf8(allocator, event_json) catch return jni.JNI_FALSE;
763
764 // `JSONTokener` is lenient where `std.json` is strict — unquoted keys,
765 // single quotes, a trailing comma. Everything strict JSON accepts it
766 // accepts too, so the difference only ever sends work back to the shim.
767 var parsed = std.json.parseFromSlice(std.json.Value, allocator, text, .{}) catch
768 return jni.JNI_FALSE;
769 defer parsed.deinit();
770
771 const start_default = calendar.currentTimeMillis(j) catch return jni.JNI_FALSE;
772 const end_default = calendar.currentTimeMillis(j) catch return jni.JNI_FALSE;
773 const event = calendar.parseNewEvent(
774 parsed.value,
775 start_default,
776 end_default +% one_hour_ms,
777 ) orelse return jni.JNI_FALSE;
778
779 const id = calendar.insertEvent(j, allocator, activity, event) catch |err| {
780 // The shim catches here and rejects with the exception's message. The
781 // throwable was described to logcat and cleared by `Jni.check` before
782 // this point, so the error name is what is left to say.
783 calendar.rejectOn(allocator, calendar.create_reject_global, @errorName(err)) catch {};
784 return jni.JNI_TRUE;
785 };
786
787 const payload = calendar.jsonString(allocator, id) catch return jni.JNI_FALSE;
788 events.settle(allocator, calendar.create_resolve_global, payload) catch return jni.JNI_FALSE;
789 return jni.JNI_TRUE;
790}
791
722792// =============================================================================
723793// Tests
724794// =============================================================================
@@ -830,7 +900,7 @@ test "the registered natives name methods the Kotlin actually declares" {
830900 // A descriptor is checked by the JVM at registration, so a wrong one fails
831901 // at load rather than at call — but only if the *name* matches something.
832902 // These two strings are the contract with CraftBridge.kt.
833 try testing.expectEqual(@as(usize, 18), natives.len);
903 try testing.expectEqual(@as(usize, 19), natives.len);
834904 try testing.expectEqualStrings("nativeGetDeviceInfo", std.mem.span(natives[0].name));
835905
836906 // And the class they bind to is the fixed one, not the templated bridge.
packages/zig/src/bridge_android_calendar.zigmodified+394-10
Changes to packages/zig/src/bridge_android_calendar.zig
@@ -41,6 +41,7 @@ const jobject = jni.jobject;
4141pub const A = struct {
4242 pub const delete_calendar_event = "deleteCalendarEvent";
4343 pub const get_calendar_events = "getCalendarEvents";
44 pub const create_calendar_event = "createCalendarEvent";
4445};
4546
4647/// The globals the injected JS assigns for each action.
@@ -52,6 +53,8 @@ pub const resolve_global = "_craftDeleteEventResolve";
5253pub const reject_global = "_craftDeleteEventReject";
5354pub const list_resolve_global = "_craftCalendarResolve";
5455pub const list_reject_global = "_craftCalendarReject";
56pub const create_resolve_global = "_craftCreateEventResolve";
57pub const create_reject_global = "_craftCreateEventReject";
5558
5659/// `Long.parseLong(text)`, or null where Java would throw.
5760///
@@ -122,25 +125,26 @@ pub fn deleteEvent(j: Jni, activity: jobject, id: i64) !void {
122125/// call being inline — `events.settle` sends the payload as written, so a raw
123126/// message would emit a script that does not parse. See the module comment.
124127pub fn rejectWith(allocator: std.mem.Allocator, message: []const u8) !void {
125 const payload = try rejectPayload(allocator, message);
126 defer allocator.free(payload);
127 try events.settle(allocator, reject_global, payload);
128 try rejectOn(allocator, reject_global, message);
128129}
129130
130/// `message` as a JSON string, quotes included.
131/// `text` as a JSON string, quotes included.
132///
133/// Used for a rejection message and for the id `createCalendarEvent` resolves
134/// with, both of which are page-visible text that has to survive a quote.
131135///
132136/// Split out so the test exercises this rather than a copy of it. An earlier
133/// version inlined the escaping here and asserted on the same three lines
134/// rewritten in the test — which passed happily when the escaping was removed
135/// from the code, because the test was not calling the code.
136pub fn rejectPayload(allocator: std.mem.Allocator, message: []const u8) ![]u8 {
137/// version inlined the escaping at the call site and asserted on the same
138/// three lines rewritten in the test — which passed happily when the escaping
139/// was removed from the code, because the test was not calling the code.
140pub fn jsonString(allocator: std.mem.Allocator, text: []const u8) ![]u8 {
137141 var payload: std.ArrayListUnmanaged(u8) = .empty;
138142 errdefer payload.deinit(allocator);
139143
140144 // The quotes are this caller's job: `appendJsonEscaped` escapes the
141145 // contents and writes no delimiters.
142146 try payload.append(allocator, '"');
143 try bridge_error.appendJsonEscaped(allocator, &payload, message);
147 try bridge_error.appendJsonEscaped(allocator, &payload, text);
144148 try payload.append(allocator, '"');
145149
146150 return payload.toOwnedSlice(allocator);
@@ -416,6 +420,243 @@ fn columnText(
416420 return try j.stringToUtf8(allocator, value);
417421}
418422
423// =============================================================================
424// createCalendarEvent
425// =============================================================================
426//
427// ## Which payloads this serves, and which it hands back
428//
429// The shim reads the event through `org.json`, whose accessors coerce: a
430// `startDate` sent as the string "1700000000000" is a number to `optLong`, a
431// `title` sent as `1.5` is the string "1.5" to `optString`, and reproducing
432// `Double.toString` exactly is not something to guess at.
433//
434// So the rule here is narrow and stated rather than approximated: Zig serves
435// the shape `NewCalendarEvent` declares — strings for the text, numbers for
436// the dates, a boolean for the flag — plus absent keys and explicit nulls. A
437// payload of any other shape makes `parseNewEvent` return null, the native
438// returns false, and the shim reads it with the coercions it already has. The
439// page sees no difference; nothing has been settled at that point.
440//
441// The one coercion that *is* reproduced is the surprising one. `optString` on
442// an explicit JSON null returns the four characters "null", because
443// `JSONObject.NULL.toString()` is "null" and `JSON.toString` reaches for
444// `toString` on anything that is not already a String. `{"location":null}` is
445// an ordinary thing for `JSON.stringify` to produce, so this is a live path
446// and not a curiosity.
447
448/// `CalendarContract.Events.CALENDAR_ID`, `EVENT_TIMEZONE` — the two columns
449/// the shim fills without being asked.
450const col_calendar_id = "calendar_id";
451const col_event_timezone = "eventTimezone";
452
453/// The shim writes calendar 1 unconditionally.
454///
455/// Not the primary calendar, not the first visible one — the row whose `_id`
456/// is 1, whatever that happens to be on the device. Reproduced because it is
457/// what the shim does, and because an event landing in a different calendar
458/// than before would be a behaviour change nobody asked for.
459const default_calendar_id: i32 = 1;
460
461/// The event to insert, in the shape `NewCalendarEvent` declares.
462pub const NewEvent = struct {
463 title: []const u8,
464 notes: []const u8,
465 location: []const u8,
466 start_date: i64,
467 end_date: i64,
468 all_day: bool,
469};
470
471/// Read the declared shape, or null where only `org.json`'s coercions would.
472///
473/// `default_start` and `default_end` are the shim's two separate
474/// `System.currentTimeMillis()` calls — separate because Kotlin evaluates each
475/// argument as its `put` runs, so the default end really can be a millisecond
476/// more than `start + 3600000`.
477pub fn parseNewEvent(value: std.json.Value, default_start: i64, default_end: i64) ?NewEvent {
478 const object = switch (value) {
479 .object => |o| o,
480 else => return null,
481 };
482
483 return .{
484 .title = optString(object, "title") orelse return null,
485 .notes = optString(object, "notes") orelse return null,
486 .location = optString(object, "location") orelse return null,
487 .start_date = optLong(object, "startDate", default_start) orelse return null,
488 .end_date = optLong(object, "endDate", default_end) orelse return null,
489 .all_day = optBoolean(object, "isAllDay") orelse return null,
490 };
491}
492
493/// `event.optString(name, "")`, for the shapes this serves.
494///
495/// Outer null means "a shape the shim would coerce and this will not".
496fn optString(object: std.json.ObjectMap, name: []const u8) ?[]const u8 {
497 const value = object.get(name) orelse return "";
498 return switch (value) {
499 .string => |text| text,
500 // `JSONObject.NULL.toString()`. Not a typo and not a fallback: the
501 // shim really does store the four characters.
502 .null => "null",
503 else => null,
504 };
505}
506
507/// `event.optLong(name, fallback)`, for the shapes this serves.
508fn optLong(object: std.json.ObjectMap, name: []const u8, fallback: i64) ?i64 {
509 const value = object.get(name) orelse return fallback;
510 return switch (value) {
511 .integer => |n| n,
512 // `JSON.toLong(NULL)` is null, so the fallback wins — unlike
513 // `optString`, where the same null becomes text.
514 .null => fallback,
515 else => null,
516 };
517}
518
519/// `event.optBoolean(name, false)`, for the shapes this serves.
520fn optBoolean(object: std.json.ObjectMap, name: []const u8) ?bool {
521 const value = object.get(name) orelse return false;
522 return switch (value) {
523 .bool => |b| b,
524 .null => false,
525 else => null,
526 };
527}
528
529/// `contentResolver.insert(Events.CONTENT_URI, values)`, and the id it lands at.
530///
531/// Returns `uri?.lastPathSegment ?: ""` — so a provider that refuses the insert
532/// resolves the page's promise with an empty string rather than rejecting,
533/// which is the shim's answer and not an improvement on it.
534pub fn insertEvent(j: Jni, allocator: std.mem.Allocator, activity: jobject, event: NewEvent) ![]u8 {
535 try j.pushLocalFrame(32);
536 defer _ = j.popLocalFrame(null);
537
538 const values_cls = try j.findClass("android/content/ContentValues");
539 const values = try j.newObjectA(values_cls, try j.methodId(values_cls, "<init>", "()V"), &.{});
540
541 // `ContentValues.put` is overloaded on the *boxed* types, so each number
542 // has to be boxed before it can be put.
543 const put_string = try j.methodId(values_cls, "put", "(Ljava/lang/String;Ljava/lang/String;)V");
544 const put_long = try j.methodId(values_cls, "put", "(Ljava/lang/String;Ljava/lang/Long;)V");
545 const put_int = try j.methodId(values_cls, "put", "(Ljava/lang/String;Ljava/lang/Integer;)V");
546
547 try putString(j, allocator, values, put_string, col_title, event.title);
548 try putString(j, allocator, values, put_string, col_description, event.notes);
549 try putString(j, allocator, values, put_string, col_event_location, event.location);
550 try putLong(j, values, put_long, col_dtstart, event.start_date);
551 try putLong(j, values, put_long, col_dtend, event.end_date);
552 try putInt(j, values, put_int, col_all_day, if (event.all_day) 1 else 0);
553 try putInt(j, values, put_int, col_calendar_id, default_calendar_id);
554
555 // `TimeZone.getDefault().id`. The provider needs one, and an event
556 // inserted without it reads back at the wrong hour.
557 const timezone_cls = try j.findClass("java/util/TimeZone");
558 const timezone = try j.callStaticObjectMethodA(
559 timezone_cls,
560 try j.staticMethodId(timezone_cls, "getDefault", "()Ljava/util/TimeZone;"),
561 &.{},
562 );
563 const timezone_id = try j.callObjectMethod(
564 timezone,
565 try j.methodId(try j.objectClass(timezone), "getID", "()Ljava/lang/String;"),
566 );
567 try j.callVoidMethodA(values, put_string, &.{
568 .{ .l = try j.newStringUtf(col_event_timezone) },
569 .{ .l = timezone_id },
570 });
571
572 const events_cls = try j.findClass("android/provider/CalendarContract$Events");
573 const content_uri = try j.staticObjectField(
574 events_cls,
575 try j.staticFieldId(events_cls, "CONTENT_URI", "Landroid/net/Uri;"),
576 );
577
578 const activity_cls = try j.objectClass(activity);
579 const resolver = try j.callObjectMethod(
580 activity,
581 try j.methodId(activity_cls, "getContentResolver", "()Landroid/content/ContentResolver;"),
582 );
583
584 const uri = try j.callObjectMethodA(
585 resolver,
586 try j.methodId(
587 try j.objectClass(resolver),
588 "insert",
589 "(Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;",
590 ),
591 &.{ .{ .l = content_uri }, .{ .l = values } },
592 );
593
594 if (uri == null) return allocator.dupe(u8, "");
595
596 const segment = try j.callObjectMethod(
597 uri,
598 try j.methodId(try j.objectClass(uri), "getLastPathSegment", "()Ljava/lang/String;"),
599 );
600 if (segment == null) return allocator.dupe(u8, "");
601 return j.stringToUtf8(allocator, segment);
602}
603
604fn putString(
605 j: Jni,
606 allocator: std.mem.Allocator,
607 values: jobject,
608 put: jni.jmethodID,
609 column: [:0]const u8,
610 text: []const u8,
611) !void {
612 try j.pushLocalFrame(4);
613 defer _ = j.popLocalFrame(null);
614
615 // `NewStringUTF` needs a NUL terminator, and a title is arbitrary page
616 // text — so it is copied rather than pointed at.
617 const terminated = try allocator.allocSentinel(u8, text.len, 0);
618 defer allocator.free(terminated);
619 @memcpy(terminated, text);
620
621 try j.callVoidMethodA(values, put, &.{
622 .{ .l = try j.newStringUtf(column) },
623 .{ .l = try j.newStringUtf(terminated.ptr) },
624 });
625}
626
627fn putLong(j: Jni, values: jobject, put: jni.jmethodID, column: [:0]const u8, value: i64) !void {
628 try j.pushLocalFrame(4);
629 defer _ = j.popLocalFrame(null);
630
631 const long_cls = try j.findClass("java/lang/Long");
632 const boxed = try j.callStaticObjectMethodA(
633 long_cls,
634 try j.staticMethodId(long_cls, "valueOf", "(J)Ljava/lang/Long;"),
635 &.{.{ .j = value }},
636 );
637 try j.callVoidMethodA(values, put, &.{ .{ .l = try j.newStringUtf(column) }, .{ .l = boxed } });
638}
639
640fn putInt(j: Jni, values: jobject, put: jni.jmethodID, column: [:0]const u8, value: i32) !void {
641 try j.pushLocalFrame(4);
642 defer _ = j.popLocalFrame(null);
643
644 const integer_cls = try j.findClass("java/lang/Integer");
645 const boxed = try j.callStaticObjectMethodA(
646 integer_cls,
647 try j.staticMethodId(integer_cls, "valueOf", "(I)Ljava/lang/Integer;"),
648 &.{.{ .i = value }},
649 );
650 try j.callVoidMethodA(values, put, &.{ .{ .l = try j.newStringUtf(column) }, .{ .l = boxed } });
651}
652
653/// `message` as a JSON string, for whichever reject global the caller owns.
654pub fn rejectOn(allocator: std.mem.Allocator, global: []const u8, message: []const u8) !void {
655 const payload = try jsonString(allocator, message);
656 defer allocator.free(payload);
657 try events.settle(allocator, global, payload);
658}
659
419660// =============================================================================
420661// Tests
421662// =============================================================================
@@ -450,7 +691,7 @@ test "a rejection message with a quote is escaped rather than emitted raw" {
450691 // The bug that used to be one line away. Before #154 the shim turned an id
451692 // of `1'x` into `…Reject('For input string: "1'x"')`, which does not parse
452693 // — so evaluateJavascript ran nothing and the promise never settled.
453 const payload = try rejectPayload(testing.allocator, "For input string: \"1'x\"");
694 const payload = try jsonString(testing.allocator, "For input string: \"1'x\"");
454695 defer testing.allocator.free(payload);
455696
456697 // Valid JSON, and it round-trips to exactly the original message.
@@ -623,3 +864,146 @@ test "getCalendarEvents names its action and globals as the shim does" {
623864 try testing.expectEqualStrings("_craftCalendarResolve", list_resolve_global);
624865 try testing.expectEqualStrings("_craftCalendarReject", list_reject_global);
625866}
867
868// --- createCalendarEvent ---------------------------------------------------
869
870fn parseEvent(json: []const u8, default_start: i64, default_end: i64) !?NewEvent {
871 var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
872 defer parsed.deinit();
873
874 // The strings borrow from `parsed`, so anything a caller keeps has to be
875 // read before this returns. Every test below asserts inside its own call.
876 const event = parseNewEvent(parsed.value, default_start, default_end) orelse return null;
877 return NewEvent{
878 .title = try testing.allocator.dupe(u8, event.title),
879 .notes = try testing.allocator.dupe(u8, event.notes),
880 .location = try testing.allocator.dupe(u8, event.location),
881 .start_date = event.start_date,
882 .end_date = event.end_date,
883 .all_day = event.all_day,
884 };
885}
886
887fn freeEvent(event: NewEvent) void {
888 testing.allocator.free(event.title);
889 testing.allocator.free(event.notes);
890 testing.allocator.free(event.location);
891}
892
893test "the declared shape reads straight through" {
894 const event = (try parseEvent(
895 \\{"title":"Standup","notes":"daily","location":"Room 2",
896 \\ "startDate":1700000000000,"endDate":1700000900000,"isAllDay":false}
897 , 1, 2)).?;
898 defer freeEvent(event);
899
900 try testing.expectEqualStrings("Standup", event.title);
901 try testing.expectEqualStrings("daily", event.notes);
902 try testing.expectEqualStrings("Room 2", event.location);
903 try testing.expectEqual(@as(i64, 1700000000000), event.start_date);
904 try testing.expectEqual(@as(i64, 1700000900000), event.end_date);
905 try testing.expect(!event.all_day);
906}
907
908test "absent keys take the shim's defaults" {
909 // `optString(name, "")`, `optLong(name, now)`, `optBoolean(name, false)`.
910 // The two date defaults are separate arguments because the shim calls
911 // System.currentTimeMillis() twice, once per put.
912 const event = (try parseEvent("{}", 111, 222)).?;
913 defer freeEvent(event);
914
915 try testing.expectEqualStrings("", event.title);
916 try testing.expectEqualStrings("", event.notes);
917 try testing.expectEqualStrings("", event.location);
918 try testing.expectEqual(@as(i64, 111), event.start_date);
919 try testing.expectEqual(@as(i64, 222), event.end_date);
920 try testing.expect(!event.all_day);
921}
922
923test "an explicit null is text to optString and a fallback to optLong" {
924 // The org.json quirk, and the reason it is worth a test rather than a
925 // comment: `JSONObject.NULL.toString()` is "null", so `optString` hands
926 // back four characters where every other accessor hands back the default.
927 // `JSON.stringify({location: null})` produces this every day.
928 const event = (try parseEvent(
929 \\{"title":null,"notes":null,"location":null,"startDate":null,"endDate":null,"isAllDay":null}
930 , 111, 222)).?;
931 defer freeEvent(event);
932
933 try testing.expectEqualStrings("null", event.title);
934 try testing.expectEqualStrings("null", event.notes);
935 try testing.expectEqualStrings("null", event.location);
936 try testing.expectEqual(@as(i64, 111), event.start_date);
937 try testing.expectEqual(@as(i64, 222), event.end_date);
938 try testing.expect(!event.all_day);
939}
940
941test "a shape only org.json would coerce is handed back rather than guessed at" {
942 // Each of these is something `optString`/`optLong`/`optBoolean` reads
943 // happily and this does not. Returning null sends the native down its
944 // false path, the shim reads it, and the page cannot tell — which is the
945 // whole reason the rule can be this narrow.
946 for ([_][]const u8{
947 // A number where NewCalendarEvent declares a string: optString would
948 // give "1.5", and reproducing Double.toString is not a guess to make.
949 \\{"title":1.5}
950 ,
951 \\{"title":7}
952 ,
953 \\{"location":true}
954 ,
955 // A string where it declares a number: optLong parses it as a double
956 // and truncates, so "1.9" is 1.
957 \\{"startDate":"1700000000000"}
958 ,
959 \\{"endDate":"1.9"}
960 ,
961 // A float where it declares a number: optLong truncates toward zero.
962 \\{"startDate":1.9}
963 ,
964 // optBoolean reads "true" and "false" case-insensitively.
965 \\{"isAllDay":"true"}
966 ,
967 \\{"isAllDay":1}
968 ,
969 // Not an object at all.
970 \\[]
971 ,
972 \\"title"
973 ,
974 }) |payload| {
975 const event = try parseEvent(payload, 1, 2);
976 if (event) |kept| {
977 freeEvent(kept);
978 std.debug.print("payload was served rather than handed back: {s}\n", .{payload});
979 return error.CoercedShapeAccepted;
980 }
981 }
982}
983
984test "the columns createCalendarEvent fills are the shim's" {
985 try testing.expectEqualStrings("calendar_id", col_calendar_id);
986 try testing.expectEqualStrings("eventTimezone", col_event_timezone);
987
988 // The shim writes calendar 1 unconditionally — not the primary calendar,
989 // the row whose _id is 1. Written down because it looks like a bug and is
990 // instead a faithful port of one.
991 try testing.expectEqual(@as(i32, 1), default_calendar_id);
992}
993
994test "createCalendarEvent names its action and globals as the shim does" {
995 try testing.expectEqualStrings("createCalendarEvent", A.create_calendar_event);
996 try testing.expectEqualStrings("_craftCreateEventResolve", create_resolve_global);
997 try testing.expectEqualStrings("_craftCreateEventReject", create_reject_global);
998}
999
1000test "an id carrying a quote resolves as JSON rather than breaking the reply" {
1001 // `uri.lastPathSegment` is provider-controlled text, and it goes to the
1002 // page through the same channel a rejection does.
1003 const payload = try jsonString(testing.allocator, "17'x");
1004 defer testing.allocator.free(payload);
1005
1006 var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, payload, .{});
1007 defer parsed.deinit();
1008 try testing.expectEqualStrings("17'x", parsed.value.string);
1009}
packages/zig/test/android_conformance_test.zigmodified+2-2
Changes to packages/zig/test/android_conformance_test.zig
@@ -65,8 +65,8 @@ const zig_sources = [_][]const u8{
6565/// notification cancels; 86 with deleteCalendarEvent, the first to answer
6666/// through the reply channel rather than by returning; 85 with
6767/// getCalendarEvents, the first to send the page a payload it built rather
68/// than a constant.
69const max_not_yet_migrated: usize = 85;
68/// than a constant; 84 with createCalendarEvent, the first to read one.
69const max_not_yet_migrated: usize = 84;
7070
7171/// Every `@JavascriptInterface fun <name>(` in the Kotlin bridge.
7272///