| @@ -0,0 +1,355 @@ |
| 1 | +//! `getLocationRecordingState` and `readLocationRecording` on Android. |
| 2 | +//! |
| 3 | +//! Both are the *read* side of `CraftLocationRecordingStore`, which a |
| 4 | +//! foreground service writes while a recording runs. Neither starts, stops or |
| 5 | +//! samples anything — those need the service, and the service needs a |
| 6 | +//! `LocationCallback`, which is a Java interface Zig cannot implement. |
| 7 | +//! |
| 8 | +//! So this migrates the half that is a file and a preferences read, and leaves |
| 9 | +//! the half that is a service alone. |
| 10 | +//! |
| 11 | +//! ## Both return a String rather than answering through the channel |
| 12 | +//! |
| 13 | +//! `fun getLocationRecordingState(): String` — synchronous, like |
| 14 | +//! `clipboardRead`. So a null from the native means "ask the shim" and a |
| 15 | +//! string means "this is the answer", with no promise involved at either end. |
| 16 | +//! |
| 17 | +//! ## A malformed line makes this decline rather than skip |
| 18 | +//! |
| 19 | +//! The store's reader is `forEachLine { if (line.isNotBlank()) runCatching { |
| 20 | +//! result.put(JSONObject(line)) } }` — a line that does not parse is dropped |
| 21 | +//! silently and the rest are kept. |
| 22 | +//! |
| 23 | +//! Zig does not reproduce the dropping. `std.json` is stricter than |
| 24 | +//! `JSONTokener`, so a line one accepts and the other refuses would make the |
| 25 | +//! two disagree about how many samples there are — and `sampleCount` is a |
| 26 | +//! number a page shows to a user. Declining hands the whole read back to the |
| 27 | +//! shim, which drops the line the way it always did. |
| 28 | +//! |
| 29 | +//! ## Lines are passed through, not re-serialized |
| 30 | +//! |
| 31 | +//! The shim parses each line and prints it again, and `append` wrote each line |
| 32 | +//! with the same printer — so re-printing is the identity for every file this |
| 33 | +//! app produced. Passing the bytes through avoids reproducing `org.json`'s |
| 34 | +//! number formatting, which is the `Double.toString` problem the calendar and |
| 35 | +//! database modules both decline to guess at. |
| 36 | + |
| 37 | +const std = ; |
| 38 | +const jni = ; |
| 39 | +const prefs_api = ; |
| 40 | +const bridge_error = ; |
| 41 | + |
| 42 | +const Jni = jni.Jni; |
| 43 | +const jobject = jni.jobject; |
| 44 | + |
| 45 | +pub const A = struct { |
| 46 | + pub const get_location_recording_state = "getLocationRecordingState"; |
| 47 | + pub const read_location_recording = "readLocationRecording"; |
| 48 | +}; |
| 49 | + |
| 50 | +/// `CraftLocationRecordingStore.PREFS` and `FILE`. |
| 51 | +const prefs_name = "craft_location_recording"; |
| 52 | +const file_name = "craft-location-recording.jsonl"; |
| 53 | + |
| 54 | +/// What a recording's preferences hold. |
| 55 | +pub const State = struct { |
| 56 | + /// Absent rather than null when the key has never been written — the |
| 57 | + /// store's `put("id", getString("id", null))` *removes* the mapping. |
| 58 | + id: ?[]const u8, |
| 59 | + active: bool, |
| 60 | + paused: bool, |
| 61 | + /// `getLong("startedAt", 0).takeIf { it > 0 } ?: JSONObject.NULL` — so |
| 62 | + /// zero and every negative become an explicit JSON null, and the key |
| 63 | + /// stays. |
| 64 | + started_at: ?i64, |
| 65 | + sample_count: usize, |
| 66 | +}; |
| 67 | + |
| 68 | +/// `state(context)` as `org.json` would print it. |
| 69 | +/// |
| 70 | +/// The two nulls are not the same null, which is the whole reason this is a |
| 71 | +/// function with a test rather than a format string: a missing `id` has no |
| 72 | +/// key at all, and a missing `startedAt` is present and null. |
| 73 | +pub fn renderState(allocator: std.mem.Allocator, state: State) ![]u8 { |
| 74 | + var out: std.ArrayListUnmanaged(u8) = .empty; |
| 75 | + errdefer out.deinit(allocator); |
| 76 | + |
| 77 | + try out.append(allocator, '{'); |
| 78 | + if (state.id) |id| { |
| 79 | + try out.appendSlice(allocator, "\"id\":\""); |
| 80 | + try bridge_error.appendJsonEscaped(allocator, &out, id); |
| 81 | + try out.appendSlice(allocator, "\","); |
| 82 | + } |
| 83 | + try out.appendSlice(allocator, "\"active\":"); |
| 84 | + try out.appendSlice(allocator, if (state.active) "true" else "false"); |
| 85 | + try out.appendSlice(allocator, ",\"paused\":"); |
| 86 | + try out.appendSlice(allocator, if (state.paused) "true" else "false"); |
| 87 | + |
| 88 | + try out.appendSlice(allocator, ",\"startedAt\":"); |
| 89 | + if (state.started_at) |started_at| { |
| 90 | + try out.print(allocator, "{d}", .{started_at}); |
| 91 | + } else { |
| 92 | + try out.appendSlice(allocator, "null"); |
| 93 | + } |
| 94 | + |
| 95 | + try out.print(allocator, ",\"sampleCount\":{d}}}", .{state.sample_count}); |
| 96 | + return out.toOwnedSlice(allocator); |
| 97 | +} |
| 98 | + |
| 99 | +/// The array and how many samples are in it. |
| 100 | +/// |
| 101 | +/// One function rather than two, so `sampleCount` and the array a page reads |
| 102 | +/// next cannot disagree — that agreement is a property of the code here |
| 103 | +/// rather than something a test has to keep checking. |
| 104 | +pub const Locations = struct { json: []u8, count: usize }; |
| 105 | + |
| 106 | +/// `locations(context)` as a JSON array, or null if any line does not parse. |
| 107 | +/// |
| 108 | +/// The lines are emitted as they were stored — see the note at the top about |
| 109 | +/// why this does not re-serialize them. |
| 110 | +pub fn renderLocations(allocator: std.mem.Allocator, contents: []const u8) !?Locations { |
| 111 | + var out: std.ArrayListUnmanaged(u8) = .empty; |
| 112 | + errdefer out.deinit(allocator); |
| 113 | + |
| 114 | + try out.append(allocator, '['); |
| 115 | + |
| 116 | + var written: usize = 0; |
| 117 | + var lines = std.mem.splitScalar(u8, contents, '\n'); |
| 118 | + while (lines.next()) |raw| { |
| 119 | + // `isNotBlank()` — a line of spaces is skipped, not parsed. Kotlin's |
| 120 | + // definition is "no non-whitespace character", and `\r` from a file |
| 121 | + // written on another platform is whitespace to both. |
| 122 | + const line = std.mem.trim(u8, raw, " \t\r\n"); |
| 123 | + if (line.len == 0) continue; |
| 124 | + |
| 125 | + var parsed = std.json.parseFromSlice(std.json.Value, allocator, line, .{}) catch { |
| 126 | + out.deinit(allocator); |
| 127 | + return null; |
| 128 | + }; |
| 129 | + parsed.deinit(); |
| 130 | + |
| 131 | + if (written != 0) try out.append(allocator, ','); |
| 132 | + try out.appendSlice(allocator, line); |
| 133 | + written += 1; |
| 134 | + } |
| 135 | + |
| 136 | + try out.append(allocator, ']'); |
| 137 | + return Locations{ .json = try out.toOwnedSlice(allocator), .count = written }; |
| 138 | +} |
| 139 | + |
| 140 | +/// The recording file's contents, or an empty slice when it does not exist. |
| 141 | +/// |
| 142 | +/// Read through Java rather than with Zig's own file API, which on this |
| 143 | +/// toolchain needs an `Io` a JNI native has nowhere to get. |
| 144 | +pub fn readFile(j: Jni, allocator: std.mem.Allocator, activity: jobject) ![]u8 { |
| 145 | + try j.pushLocalFrame(16); |
| 146 | + defer _ = j.popLocalFrame(null); |
| 147 | + |
| 148 | + const files_dir = try j.callObjectMethod( |
| 149 | + activity, |
| 150 | + try j.methodId(try j.objectClass(activity), "getFilesDir", "()Ljava/io/File;"), |
| 151 | + ); |
| 152 | + |
| 153 | + const file_cls = try j.findClass("java/io/File"); |
| 154 | + const file = try j.newObjectA( |
| 155 | + file_cls, |
| 156 | + try j.methodId(file_cls, "<init>", "(Ljava/io/File;Ljava/lang/String;)V"), |
| 157 | + &.{ .{ .l = files_dir }, .{ .l = try j.newStringUtf(file_name) } }, |
| 158 | + ); |
| 159 | + |
| 160 | + // `if (!source.exists()) return result` — an empty array rather than an |
| 161 | + // error, because a recording that never started has no file. |
| 162 | + const exists = try j.callBooleanMethodA( |
| 163 | + file, |
| 164 | + try j.methodId(file_cls, "exists", "()Z"), |
| 165 | + &.{}, |
| 166 | + ); |
| 167 | + if (!exists) return allocator.alloc(u8, 0); |
| 168 | + |
| 169 | + const stream_cls = try j.findClass("java/io/FileInputStream"); |
| 170 | + const stream = try j.newObjectA( |
| 171 | + stream_cls, |
| 172 | + try j.methodId(stream_cls, "<init>", "(Ljava/io/File;)V"), |
| 173 | + &.{.{ .l = file }}, |
| 174 | + ); |
| 175 | + const close = try j.methodId(stream_cls, "close", "()V"); |
| 176 | + defer j.callVoidMethodA(stream, close, &.{}) catch {}; |
| 177 | + |
| 178 | + // `readAllBytes` is API 33. `File.length()` plus one `read` is the form |
| 179 | + // that works everywhere this app runs, and a short read is a truncated |
| 180 | + // file rather than an error — which is what `forEachLine` would also see. |
| 181 | + const length = try j.callLongMethod(file, try j.methodId(file_cls, "length", "()J")); |
| 182 | + if (length <= 0) return allocator.alloc(u8, 0); |
| 183 | + |
| 184 | + const buffer = try j.newByteArray(@intCast(length)); |
| 185 | + const read = try j.callIntMethodA( |
| 186 | + stream, |
| 187 | + try j.methodId(stream_cls, "read", "([B)I"), |
| 188 | + &.{.{ .l = buffer }}, |
| 189 | + ); |
| 190 | + if (read <= 0) return allocator.alloc(u8, 0); |
| 191 | + |
| 192 | + const bytes = try j.byteArrayToOwned(allocator, buffer); |
| 193 | + return allocator.realloc(bytes, @intCast(read)); |
| 194 | +} |
| 195 | + |
| 196 | +/// Read the four preference values a state is built from. |
| 197 | +pub fn readState( |
| 198 | + j: Jni, |
| 199 | + allocator: std.mem.Allocator, |
| 200 | + activity: jobject, |
| 201 | + sample_count: usize, |
| 202 | +) !State { |
| 203 | + try j.pushLocalFrame(16); |
| 204 | + defer _ = j.popLocalFrame(null); |
| 205 | + |
| 206 | + const prefs = try prefs_api.open(j, allocator, activity, prefs_name); |
| 207 | + const started_at = try prefs_api.getLong(j, allocator, prefs, "startedAt", 0); |
| 208 | + |
| 209 | + return .{ |
| 210 | + .id = try prefs_api.getString(j, allocator, prefs, "id"), |
| 211 | + .active = try prefs_api.getBoolean(j, allocator, prefs, "active", false), |
| 212 | + .paused = try prefs_api.getBoolean(j, allocator, prefs, "paused", false), |
| 213 | + .started_at = if (started_at > 0) started_at else null, |
| 214 | + .sample_count = sample_count, |
| 215 | + }; |
| 216 | +} |
| 217 | + |
| 218 | +// ============================================================================= |
| 219 | +// Tests |
| 220 | +// ============================================================================= |
| 221 | + |
| 222 | +const testing = std.testing; |
| 223 | + |
| 224 | +test "a state that has never recorded has no id and a null startedAt" { |
| 225 | + // The two nulls the store produces are different nulls: `put("id", null)` |
| 226 | + // removes the mapping, and `startedAt` is set to JSONObject.NULL |
| 227 | + // explicitly, so its key stays. |
| 228 | + const json = try renderState(testing.allocator, .{ |
| 229 | + .id = null, |
| 230 | + .active = false, |
| 231 | + .paused = false, |
| 232 | + .started_at = null, |
| 233 | + .sample_count = 0, |
| 234 | + }); |
| 235 | + defer testing.allocator.free(json); |
| 236 | + |
| 237 | + try testing.expectEqualStrings( |
| 238 | + \\{"active":false,"paused":false,"startedAt":null,"sampleCount":0} |
| 239 | + , json); |
| 240 | +} |
| 241 | + |
| 242 | +test "a running recording carries every field, in the store's order" { |
| 243 | + const json = try renderState(testing.allocator, .{ |
| 244 | + .id = "run-7", |
| 245 | + .active = true, |
| 246 | + .paused = true, |
| 247 | + .started_at = 1_700_000_000_000, |
| 248 | + .sample_count = 42, |
| 249 | + }); |
| 250 | + defer testing.allocator.free(json); |
| 251 | + |
| 252 | + try testing.expectEqualStrings( |
| 253 | + \\{"id":"run-7","active":true,"paused":true,"startedAt":1700000000000,"sampleCount":42} |
| 254 | + , json); |
| 255 | +} |
| 256 | + |
| 257 | +test "startedAt of zero or below is the same null as never having started" { |
| 258 | + // `takeIf { it > 0 } ?: JSONObject.NULL`. A clock that went backwards |
| 259 | + // writes a negative, and the store reports null rather than the number. |
| 260 | + for ([_]?i64{ |
| 261 | + null, |
| 262 | + }) |started_at| { |
| 263 | + const json = try renderState(testing.allocator, .{ |
| 264 | + .id = "run-7", |
| 265 | + .active = true, |
| 266 | + .paused = false, |
| 267 | + .started_at = started_at, |
| 268 | + .sample_count = 1, |
| 269 | + }); |
| 270 | + defer testing.allocator.free(json); |
| 271 | + try testing.expect(std.mem.indexOf(u8, json, "\"startedAt\":null") != null); |
| 272 | + } |
| 273 | +} |
| 274 | + |
| 275 | +test "an id carrying a quote survives as JSON" { |
| 276 | + const json = try renderState(testing.allocator, .{ |
| 277 | + .id = "it's \"run\"", |
| 278 | + .active = false, |
| 279 | + .paused = false, |
| 280 | + .started_at = null, |
| 281 | + .sample_count = 0, |
| 282 | + }); |
| 283 | + defer testing.allocator.free(json); |
| 284 | + |
| 285 | + var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{}); |
| 286 | + defer parsed.deinit(); |
| 287 | + try testing.expectEqualStrings("it's \"run\"", parsed.value.object.get("id").?.string); |
| 288 | +} |
| 289 | + |
| 290 | +test "locations are the file's lines, in order, with the blanks dropped" { |
| 291 | + const contents = |
| 292 | + "{\"latitude\":1,\"longitude\":2}\n" ++ |
| 293 | + "\n" ++ |
| 294 | + " \n" ++ |
| 295 | + "{\"latitude\":3,\"longitude\":4}\n"; |
| 296 | + |
| 297 | + const locations = (try renderLocations(testing.allocator, contents)).?; |
| 298 | + defer testing.allocator.free(locations.json); |
| 299 | + |
| 300 | + try testing.expectEqualStrings( |
| 301 | + \\[{"latitude":1,"longitude":2},{"latitude":3,"longitude":4}] |
| 302 | + , locations.json); |
| 303 | + try testing.expectEqual(@as(usize, 2), locations.count); |
| 304 | +} |
| 305 | + |
| 306 | +test "an empty or missing file is an empty array" { |
| 307 | + const empty = (try renderLocations(testing.allocator, "")).?; |
| 308 | + defer testing.allocator.free(empty.json); |
| 309 | + try testing.expectEqualStrings("[]", empty.json); |
| 310 | + try testing.expectEqual(@as(usize, 0), empty.count); |
| 311 | + |
| 312 | + const blank = (try renderLocations(testing.allocator, "\n\n \n")).?; |
| 313 | + defer testing.allocator.free(blank.json); |
| 314 | + try testing.expectEqualStrings("[]", blank.json); |
| 315 | +} |
| 316 | + |
| 317 | +test "a malformed line makes the whole read decline" { |
| 318 | + // The store drops it and keeps the rest. Zig does not reproduce the |
| 319 | + // dropping, because std.json and JSONTokener disagree about what parses — |
| 320 | + // and disagreeing about how many samples there are is worse than handing |
| 321 | + // the read back. |
| 322 | + try testing.expect(try renderLocations(testing.allocator, "{\"a\":1}\nnot json\n") == null); |
| 323 | + try testing.expect(try renderLocations(testing.allocator, "{oops}\n") == null); |
| 324 | + |
| 325 | + // A truncated final line, which is what a file cut off mid-write looks |
| 326 | + // like — the case most likely to actually happen. |
| 327 | + try testing.expect(try renderLocations(testing.allocator, "{\"a\":1}\n{\"b\":") == null); |
| 328 | +} |
| 329 | + |
| 330 | +test "sampleCount is the length of the array it was counted from" { |
| 331 | + // A page showing `sampleCount` and then reading the samples must not see |
| 332 | + // two different numbers, so the count comes back from the same pass. |
| 333 | + const contents = "{\"a\":1}\n\n{\"b\":2}\n \n{\"c\":3}\n"; |
| 334 | + |
| 335 | + const locations = (try renderLocations(testing.allocator, contents)).?; |
| 336 | + defer testing.allocator.free(locations.json); |
| 337 | + try testing.expectEqual(@as(usize, 3), locations.count); |
| 338 | + |
| 339 | + var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, locations.json, .{}); |
| 340 | + defer parsed.deinit(); |
| 341 | + try testing.expectEqual(locations.count, parsed.value.array.items.len); |
| 342 | +} |
| 343 | + |
| 344 | +test "the store's names are the ones the service writes" { |
| 345 | + // A different preferences file or filename here reads an empty recording |
| 346 | + // and reports it as an empty one, which looks exactly like a recording |
| 347 | + // that has not started. |
| 348 | + try testing.expectEqualStrings("craft_location_recording", prefs_name); |
| 349 | + try testing.expectEqualStrings("craft-location-recording.jsonl", file_name); |
| 350 | +} |
| 351 | + |
| 352 | +test "the actions match the shim exactly" { |
| 353 | + try testing.expectEqualStrings("getLocationRecordingState", A.get_location_recording_state); |
| 354 | + try testing.expectEqualStrings("readLocationRecording", A.read_location_recording); |
| 355 | +} |