also looking at this
feat(android): the app-state trio in Zig — ratchet 59 → 56
#184
6 files
+422
-3
| @@ -0,0 +1,237 @@ | ||
| 1 | //! `startAppStateMonitoring`, `stopAppStateMonitoring` and `getAppState`. | |
| 2 | //! | |
| 3 | //! The second listener shim, and the first migration that moves *state* rather | |
| 4 | //! than working around it. | |
| 5 | //! | |
| 6 | //! ## Why all three, or none | |
| 7 | //! | |
| 8 | //! `getAppState` returns `currentAppState`, a field only the lifecycle | |
| 9 | //! observer writes. Serving the observer from Zig without serving the getter | |
| 10 | //! would leave the Kotlin field frozen at its initial "active" while the real | |
| 11 | //! state moved — the exact failure the flashlight deferral describes, where | |
| 12 | //! one half writes a field the other half reads. | |
| 13 | //! | |
| 14 | //! So the state moves here, and all three actions come with it. That is what | |
| 15 | //! the flashlight row means by "migrating the pair together would need the | |
| 16 | //! state to move too": this is what it looks like when it can. | |
| 17 | //! | |
| 18 | //! Process-global, because `ProcessLifecycleOwner` is: one answer per process, | |
| 19 | //! not per Activity. Atomic, because the observer runs on the main looper and | |
| 20 | //! `getAppState` is called from the WebView's JavaBridge thread. | |
| 21 | //! | |
| 22 | //! ## Only a change is announced | |
| 23 | //! | |
| 24 | //! The observer compares against the current state and does nothing when they | |
| 25 | //! match. `ON_START` immediately after `ON_RESUME` is an ordinary sequence and | |
| 26 | //! both map to "active", so without that check a page would see two | |
| 27 | //! `craftAppStateChange` events for one foregrounding. | |
| 28 | //! | |
| 29 | //! ## Two deliveries, not one | |
| 30 | //! | |
| 31 | //! A change calls `window._craftAppStateCallback(state)` *and* dispatches | |
| 32 | //! `craftAppStateChange`. Both, in that order, because the shim does both — | |
| 33 | //! `onAppStateChange` reads the first and `addEventListener` the second, and a | |
| 34 | //! page may well use either. | |
| 35 | ||
| 36 | const std = @import("std"); | |
| 37 | const events = @import("android_events.zig"); | |
| 38 | const bridge_error = @import("bridge_error.zig"); | |
| 39 | ||
| 40 | pub const A = struct { | |
| 41 | pub const start_app_state_monitoring = "startAppStateMonitoring"; | |
| 42 | pub const stop_app_state_monitoring = "stopAppStateMonitoring"; | |
| 43 | pub const get_app_state = "getAppState"; | |
| 44 | }; | |
| 45 | ||
| 46 | /// The global `onAppStateChange` assigns, and the event name `sendEvent` uses. | |
| 47 | pub const callback_global = "_craftAppStateCallback"; | |
| 48 | pub const event_name = "craftAppStateChange"; | |
| 49 | ||
| 50 | pub const State = enum { | |
| 51 | active, | |
| 52 | inactive, | |
| 53 | background, | |
| 54 | ||
| 55 | pub fn name(self: State) []const u8 { | |
| 56 | return switch (self) { | |
| 57 | .active => "active", | |
| 58 | .inactive => "inactive", | |
| 59 | .background => "background", | |
| 60 | }; | |
| 61 | } | |
| 62 | }; | |
| 63 | ||
| 64 | /// The state a page sees before anything has happened. | |
| 65 | /// | |
| 66 | /// `private var currentAppState = "active"` — so `getAppState` answers "active" | |
| 67 | /// even when monitoring was never started, and that is what a page gets today. | |
| 68 | const initial: State = .active; | |
| 69 | ||
| 70 | var current: std.atomic.Value(u8) = .init(@backingInt(initial)); | |
| 71 | ||
| 72 | /// What the process currently believes. | |
| 73 | pub fn state() State { | |
| 74 | return @fromBackingInt(@intCast(current.load(.acquire))); | |
| 75 | } | |
| 76 | ||
| 77 | /// Put the state back to its process start value. | |
| 78 | /// | |
| 79 | /// For tests. Nothing in the bridge resets it, because nothing in a process | |
| 80 | /// un-launches the app. | |
| 81 | pub fn reset() void { | |
| 82 | current.store(@backingInt(initial), .release); | |
| 83 | } | |
| 84 | ||
| 85 | /// `Lifecycle.Event` to a state, or null where the shim's `when` falls to | |
| 86 | /// `else` and keeps what it had. | |
| 87 | /// | |
| 88 | /// The names are `Lifecycle.Event`'s own — the holder passes `event.name` | |
| 89 | /// rather than an ordinal, because an ordinal is a number that means nothing | |
| 90 | /// on its own and would move if the enum ever gained a member. | |
| 91 | pub fn stateFor(event: []const u8) ?State { | |
| 92 | if (std.mem.eql(u8, event, "ON_START")) return .active; | |
| 93 | if (std.mem.eql(u8, event, "ON_RESUME")) return .active; | |
| 94 | if (std.mem.eql(u8, event, "ON_PAUSE")) return .inactive; | |
| 95 | if (std.mem.eql(u8, event, "ON_STOP")) return .background; | |
| 96 | return null; | |
| 97 | } | |
| 98 | ||
| 99 | /// Apply an event, and say whether it changed anything. | |
| 100 | /// | |
| 101 | /// Null means "announce nothing" — either the event has no state (`ON_CREATE`, | |
| 102 | /// `ON_DESTROY`, `ON_ANY`) or it maps to the state already held. | |
| 103 | pub fn apply(event: []const u8) ?State { | |
| 104 | const next = stateFor(event) orelse return null; | |
| 105 | if (next == state()) return null; | |
| 106 | current.store(@backingInt(next), .release); | |
| 107 | return next; | |
| 108 | } | |
| 109 | ||
| 110 | /// `window._craftAppStateCallback("active")` — the payload, quoted. | |
| 111 | pub fn callbackPayload(allocator: std.mem.Allocator, value: State) ![]u8 { | |
| 112 | var out: std.ArrayListUnmanaged(u8) = .empty; | |
| 113 | errdefer out.deinit(allocator); | |
| 114 | ||
| 115 | try out.append(allocator, '"'); | |
| 116 | try bridge_error.appendJsonEscaped(allocator, &out, value.name()); | |
| 117 | try out.append(allocator, '"'); | |
| 118 | return out.toOwnedSlice(allocator); | |
| 119 | } | |
| 120 | ||
| 121 | /// `{"state":"active"}` — the detail `sendEvent` builds. | |
| 122 | pub fn eventDetail(allocator: std.mem.Allocator, value: State) ![]u8 { | |
| 123 | var out: std.ArrayListUnmanaged(u8) = .empty; | |
| 124 | errdefer out.deinit(allocator); | |
| 125 | ||
| 126 | try out.appendSlice(allocator, "{\"state\":\""); | |
| 127 | try bridge_error.appendJsonEscaped(allocator, &out, value.name()); | |
| 128 | try out.appendSlice(allocator, "\"}"); | |
| 129 | return out.toOwnedSlice(allocator); | |
| 130 | } | |
| 131 | ||
| 132 | /// Announce a change, both ways the shim announces it. | |
| 133 | pub fn announce(allocator: std.mem.Allocator, value: State) !void { | |
| 134 | const payload = try callbackPayload(allocator, value); | |
| 135 | defer allocator.free(payload); | |
| 136 | try events.settle(allocator, callback_global, payload); | |
| 137 | ||
| 138 | const detail = try eventDetail(allocator, value); | |
| 139 | defer allocator.free(detail); | |
| 140 | try events.emitEvent(allocator, event_name, detail); | |
| 141 | } | |
| 142 | ||
| 143 | // ============================================================================= | |
| 144 | // Tests | |
| 145 | // ============================================================================= | |
| 146 | ||
| 147 | const testing = std.testing; | |
| 148 | ||
| 149 | test "every lifecycle event maps where the shim's when maps it" { | |
| 150 | try testing.expectEqual(State.active, stateFor("ON_START").?); | |
| 151 | try testing.expectEqual(State.active, stateFor("ON_RESUME").?); | |
| 152 | try testing.expectEqual(State.inactive, stateFor("ON_PAUSE").?); | |
| 153 | try testing.expectEqual(State.background, stateFor("ON_STOP").?); | |
| 154 | } | |
| 155 | ||
| 156 | test "an event with no state keeps the one already held" { | |
| 157 | // The shim's `else -> currentAppState`. ON_CREATE and ON_DESTROY really do | |
| 158 | // arrive, and ON_ANY is dispatched to observers registered for it. | |
| 159 | try testing.expect(stateFor("ON_CREATE") == null); | |
| 160 | try testing.expect(stateFor("ON_DESTROY") == null); | |
| 161 | try testing.expect(stateFor("ON_ANY") == null); | |
| 162 | ||
| 163 | // And anything unrecognised, which is what a future enum member would be. | |
| 164 | try testing.expect(stateFor("") == null); | |
| 165 | try testing.expect(stateFor("on_start") == null); | |
| 166 | } | |
| 167 | ||
| 168 | test "a process starts active, whether or not anything is monitoring" { | |
| 169 | // `private var currentAppState = "active"`. A page calling getAppState | |
| 170 | // before startAppStateMonitoring gets "active" rather than an error or an | |
| 171 | // empty string, and that is the answer it gets today. | |
| 172 | reset(); | |
| 173 | try testing.expectEqual(State.active, state()); | |
| 174 | try testing.expectEqualStrings("active", state().name()); | |
| 175 | } | |
| 176 | ||
| 177 | test "only a change is announced" { | |
| 178 | reset(); | |
| 179 | ||
| 180 | // Already active: ON_START and ON_RESUME are both no-ops, which is what | |
| 181 | // stops one foregrounding producing two craftAppStateChange events. | |
| 182 | try testing.expect(apply("ON_START") == null); | |
| 183 | try testing.expect(apply("ON_RESUME") == null); | |
| 184 | ||
| 185 | // A real change reports the new state and keeps it. | |
| 186 | try testing.expectEqual(State.inactive, apply("ON_PAUSE").?); | |
| 187 | try testing.expectEqual(State.inactive, state()); | |
| 188 | ||
| 189 | // The same event again changes nothing. | |
| 190 | try testing.expect(apply("ON_PAUSE") == null); | |
| 191 | ||
| 192 | // And on to background, then back. | |
| 193 | try testing.expectEqual(State.background, apply("ON_STOP").?); | |
| 194 | try testing.expectEqual(State.active, apply("ON_START").?); | |
| 195 | reset(); | |
| 196 | } | |
| 197 | ||
| 198 | test "an event with no state does not disturb the one held" { | |
| 199 | reset(); | |
| 200 | _ = apply("ON_PAUSE"); | |
| 201 | try testing.expect(apply("ON_CREATE") == null); | |
| 202 | try testing.expectEqual(State.inactive, state()); | |
| 203 | reset(); | |
| 204 | } | |
| 205 | ||
| 206 | test "the two deliveries carry the same state in two shapes" { | |
| 207 | // `_craftAppStateCallback("active")` and | |
| 208 | // `dispatchEvent(new CustomEvent('craftAppStateChange', {detail: {"state":"active"}}))` | |
| 209 | // — a bare string for the callback, an object for the event. | |
| 210 | const payload = try callbackPayload(testing.allocator, .background); | |
| 211 | defer testing.allocator.free(payload); | |
| 212 | try testing.expectEqualStrings("\"background\"", payload); | |
| 213 | ||
| 214 | const detail = try eventDetail(testing.allocator, .background); | |
| 215 | defer testing.allocator.free(detail); | |
| 216 | try testing.expectEqualStrings("{\"state\":\"background\"}", detail); | |
| 217 | ||
| 218 | var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, detail, .{}); | |
| 219 | defer parsed.deinit(); | |
| 220 | try testing.expectEqualStrings("background", parsed.value.object.get("state").?.string); | |
| 221 | } | |
| 222 | ||
| 223 | test "the state names are the strings the page compares against" { | |
| 224 | // A page writes `state === 'background'`, so these are API rather than | |
| 225 | // internal spelling. | |
| 226 | try testing.expectEqualStrings("active", State.active.name()); | |
| 227 | try testing.expectEqualStrings("inactive", State.inactive.name()); | |
| 228 | try testing.expectEqualStrings("background", State.background.name()); | |
| 229 | } | |
| 230 | ||
| 231 | test "the actions and globals match the shim exactly" { | |
| 232 | try testing.expectEqualStrings("startAppStateMonitoring", A.start_app_state_monitoring); | |
| 233 | try testing.expectEqualStrings("stopAppStateMonitoring", A.stop_app_state_monitoring); | |
| 234 | try testing.expectEqualStrings("getAppState", A.get_app_state); | |
| 235 | try testing.expectEqualStrings("_craftAppStateCallback", callback_global); | |
| 236 | try testing.expectEqualStrings("craftAppStateChange", event_name); | |
| 237 | } | |