@h1r-ai/croche-react-native 0.5.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -0,0 +1,162 @@
1
+ package dev.croche.android
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.BitmapFactory
5
+ import android.graphics.Matrix
6
+ import dev.croche.CrocheError
7
+ import dev.croche.DecodedImageCodec
8
+ import dev.croche.NativeImagePal
9
+ import dev.croche.ffi.CancelToken
10
+ import dev.croche.ffi.PalDecodedImage
11
+ import dev.croche.ffi.PalImageDecodeOptions
12
+ import dev.croche.ffi.PalImageFormat
13
+ import dev.croche.ffi.PalImageRenderRequest
14
+ import java.io.ByteArrayOutputStream
15
+ import java.util.UUID
16
+ import kotlin.math.roundToInt
17
+
18
+ /** Android effects, not a preparation policy. Core chooses frame, orientation, dimensions,
19
+ * format and quality. Private immutable pixels are leased; release fences without waiting.
20
+ */
21
+ internal class BitmapDecodedImageCodec(
22
+ private val decodedForTests: () -> Unit = {},
23
+ private val renderedForTests: () -> Unit = {},
24
+ ) : DecodedImageCodec {
25
+ private class Entry(val bitmap: Bitmap) {
26
+ var leases = 0
27
+ var retired = false
28
+ }
29
+ private val lock = Any()
30
+ private val entries = mutableMapOf<String, Entry>()
31
+ private var closed = false
32
+
33
+ override fun decode(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken): PalDecodedImage {
34
+ NativeImagePal.check(cancel)
35
+ if (options.frame != 0u) invalid("Only frame zero can be decoded")
36
+ var owned: Bitmap? = null
37
+ try {
38
+ // BitmapFactory decodes the first frame; no animated drawable is retained.
39
+ val decoded = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply {
40
+ inPreferredConfig = Bitmap.Config.ARGB_8888
41
+ inScaled = false
42
+ }) ?: invalid("The platform could not decode the image bytes")
43
+ owned = decoded
44
+ decodedForTests()
45
+ NativeImagePal.check(cancel) // OS decode is uninterruptible; do not publish after cancel.
46
+ val bitmap = if (options.applyOrientation) orient(decoded, bitmapOrientation(bytes)) else decoded
47
+ if (bitmap !== decoded) decoded.recycle()
48
+ owned = bitmap
49
+ val alpha = transparentPixel(bitmap, cancel)
50
+ return synchronized(lock) {
51
+ NativeImagePal.check(cancel)
52
+ if (closed) throw CrocheError("closed", "The image codec is closed")
53
+ val handle = UUID.randomUUID().toString()
54
+ entries[handle] = Entry(bitmap)
55
+ owned = null // The private table owns the pixels from this point.
56
+ PalDecodedImage(handle, bitmap.width.toUInt(), bitmap.height.toUInt(), alpha)
57
+ }
58
+ } finally {
59
+ owned?.recycle()
60
+ }
61
+ }
62
+
63
+ override fun render(request: PalImageRenderRequest, cancel: CancelToken): ByteArray {
64
+ NativeImagePal.check(cancel)
65
+ val entry = synchronized(lock) {
66
+ val entry = entries[request.handle] ?: unsupported("The decoded image handle is unavailable")
67
+ entry.leases++
68
+ entry
69
+ }
70
+ var scaled: Bitmap? = null
71
+ try {
72
+ val width = dimension(request.width)
73
+ val height = dimension(request.height)
74
+ val format = when (request.format) {
75
+ PalImageFormat.PNG -> Bitmap.CompressFormat.PNG
76
+ PalImageFormat.JPEG -> Bitmap.CompressFormat.JPEG
77
+ }
78
+ val quality = when (request.format) {
79
+ PalImageFormat.PNG -> {
80
+ if (request.quality != null) unsupported("PNG does not take a quality argument")
81
+ 100 // Android ignores this parameter for PNG.
82
+ }
83
+ PalImageFormat.JPEG -> {
84
+ val value = request.quality ?: unsupported("JPEG requires a quality argument")
85
+ if (!value.isFinite() || value < 0 || value > 1) unsupported("JPEG quality is outside its range")
86
+ (value * 100).roundToInt()
87
+ }
88
+ }
89
+ NativeImagePal.check(cancel)
90
+ scaled = Bitmap.createScaledBitmap(entry.bitmap, width, height, true)
91
+ NativeImagePal.check(cancel)
92
+ val output = ByteArrayOutputStream()
93
+ if (!scaled.compress(format, quality, output)) unsupported("The platform could not encode the image")
94
+ renderedForTests()
95
+ NativeImagePal.check(cancel)
96
+ return synchronized(lock) {
97
+ if (entry.retired) unsupported("The decoded image handle was released")
98
+ output.toByteArray() // An owned encoded buffer, never JSON/base64.
99
+ }
100
+ } finally {
101
+ if (scaled !== entry.bitmap) scaled?.recycle()
102
+ synchronized(lock) {
103
+ entry.leases--
104
+ if (entry.retired && entry.leases == 0) entry.bitmap.recycle()
105
+ }
106
+ }
107
+ }
108
+
109
+ override fun release(handle: String) {
110
+ synchronized(lock) {
111
+ val entry = entries.remove(handle) ?: return
112
+ entry.retired = true
113
+ if (entry.leases == 0) entry.bitmap.recycle()
114
+ }
115
+ }
116
+
117
+ override fun close() {
118
+ synchronized(lock) {
119
+ closed = true
120
+ entries.values.forEach { entry ->
121
+ entry.retired = true
122
+ if (entry.leases == 0) entry.bitmap.recycle()
123
+ }
124
+ entries.clear()
125
+ }
126
+ }
127
+
128
+ private fun transparentPixel(bitmap: Bitmap, cancel: CancelToken): Boolean {
129
+ val row = IntArray(bitmap.width)
130
+ for (y in 0 until bitmap.height) {
131
+ NativeImagePal.check(cancel)
132
+ bitmap.getPixels(row, 0, bitmap.width, 0, y, bitmap.width, 1)
133
+ if (row.any { (it ushr 24) != 255 }) return true
134
+ }
135
+ return false
136
+ }
137
+
138
+ private fun orient(bitmap: Bitmap, orientation: Int): Bitmap {
139
+ val matrix = Matrix().apply {
140
+ when (orientation) {
141
+ 2 -> postScale(-1f, 1f)
142
+ 3 -> postRotate(180f)
143
+ 4 -> postScale(1f, -1f)
144
+ 5 -> { postRotate(90f); postScale(-1f, 1f) }
145
+ 6 -> postRotate(90f)
146
+ 7 -> { postRotate(270f); postScale(-1f, 1f) }
147
+ 8 -> postRotate(270f)
148
+ else -> return bitmap
149
+ }
150
+ }
151
+ return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
152
+ }
153
+
154
+ private fun dimension(value: UInt): Int {
155
+ if (value == 0u || value > Int.MAX_VALUE.toUInt()) unsupported("Image dimension cannot be represented by the platform")
156
+ return value.toInt()
157
+ }
158
+
159
+ private fun unsupported(detail: String): Nothing = throw CrocheError("image_unsupported", detail)
160
+
161
+ private fun invalid(detail: String): Nothing = throw CrocheError("invalid_input", detail)
162
+ }
@@ -0,0 +1,15 @@
1
+ @file:JvmName("BitmapImageInput")
2
+ package dev.croche
3
+
4
+ import android.graphics.Bitmap
5
+ import java.io.ByteArrayOutputStream
6
+
7
+ /** An Android Bitmap as a send input: snapshotted now as lossless PNG bytes (the Bitmap is already
8
+ * upright and may be recycled after this returns). Core and the native PAL size and encode it. */
9
+ fun ImageInput(bitmap: Bitmap, alt: String? = null): ImageInput {
10
+ if (bitmap.isRecycled) throw CrocheError("image_unsupported", "The image could not be prepared.")
11
+ val bytes = ByteArrayOutputStream().also {
12
+ if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) throw CrocheError("image_unsupported", "The image could not be prepared.")
13
+ }.toByteArray()
14
+ return ImageInput(bytes, alt)
15
+ }
@@ -0,0 +1,40 @@
1
+ package dev.croche.android
2
+
3
+ import android.media.ExifInterface
4
+ import java.io.ByteArrayInputStream
5
+
6
+ /** Shared platform EXIF read: WebP needs the existing RIFF reader on older Android releases. */
7
+ internal fun bitmapOrientation(bytes: ByteArray): Int = webpOrientation(bytes) ?: try {
8
+ ExifInterface(ByteArrayInputStream(bytes)).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
9
+ } catch (_: Exception) { ExifInterface.ORIENTATION_NORMAL }
10
+
11
+ /** A WebP's EXIF orientation (RIFF `EXIF` chunk, TIFF IFD0 tag 0x0112), or null when it is not a
12
+ * WebP or has none. */
13
+ private fun webpOrientation(bytes: ByteArray): Int? {
14
+ fun u8(i: Int) = bytes[i].toInt() and 0xFF
15
+ fun fourcc(i: Int) = String(bytes, i, 4, Charsets.US_ASCII)
16
+ if (bytes.size < 12 || fourcc(0) != "RIFF" || fourcc(8) != "WEBP") return null
17
+ var at = 12
18
+ while (at + 8 <= bytes.size) {
19
+ val size = u8(at + 4) or (u8(at + 5) shl 8) or (u8(at + 6) shl 16) or (u8(at + 7) shl 24)
20
+ if (size < 0 || at + 8 + size > bytes.size) return null
21
+ if (fourcc(at) == "EXIF") {
22
+ var tiff = at + 8
23
+ if (size >= 6 && fourcc(tiff) == "Exif" && u8(tiff + 4) == 0 && u8(tiff + 5) == 0) tiff += 6
24
+ val end = at + 8 + size
25
+ if (tiff + 8 > end) return null
26
+ val little = u8(tiff) == 0x49
27
+ fun u16(i: Int) = if (i + 2 > end) -1 else if (little) u8(i) or (u8(i + 1) shl 8) else (u8(i) shl 8) or u8(i + 1)
28
+ fun u32(i: Int) = if (i + 4 > end) -1L else if (little) (u16(i).toLong() or (u16(i + 2).toLong() shl 16)) else ((u16(i).toLong() shl 16) or u16(i + 2).toLong())
29
+ val ifd = tiff + u32(tiff + 4).toInt()
30
+ val count = u16(ifd)
31
+ for (entry in 0 until maxOf(0, count)) {
32
+ val e = ifd + 2 + entry * 12
33
+ if (u16(e) == 0x0112) return u16(e + 8).takeIf { it in 1..8 } ?: 1
34
+ }
35
+ return 1
36
+ }
37
+ at += 8 + size + (size and 1)
38
+ }
39
+ return null
40
+ }
@@ -0,0 +1,66 @@
1
+ package dev.croche.android
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.BitmapFactory
5
+ import android.graphics.Matrix
6
+ import android.media.ExifInterface
7
+ import dev.croche.PalImageCodec
8
+ import java.io.ByteArrayOutputStream
9
+
10
+ /**
11
+ * The native image PAL's Android decoder (found by name by `NativeImagePal`; no app setup). The
12
+ * header is read with inJustDecodeBounds, pixels are decoded at the largest power-of-two sample
13
+ * that stays at or above the target (inSampleSize), turned upright by EXIF and scaled to the exact
14
+ * size, then encoded as PNG and, without an alpha channel, JPEG at quality 70 (as TypeScript). GIF decodes
15
+ * its first frame.
16
+ */
17
+ internal class BitmapPalCodec : PalImageCodec {
18
+ override fun open(bytes: ByteArray, maxPixels: Long): PalImageCodec.Opened? {
19
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
20
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
21
+ val storedWidth = bounds.outWidth; val storedHeight = bounds.outHeight
22
+ if (storedWidth <= 0 || storedHeight <= 0 || storedWidth.toLong() * storedHeight > maxPixels) return null
23
+ // android.media.ExifInterface misses a WebP EXIF chunk on some API levels (API 30), so WebP is
24
+ // read here first; JPEG, PNG and the rest go through ExifInterface.
25
+ val orientation = bitmapOrientation(bytes)
26
+ val swaps = orientation in 5..8
27
+ return object : PalImageCodec.Opened {
28
+ override val width = if (swaps) storedHeight else storedWidth
29
+ override val height = if (swaps) storedWidth else storedHeight
30
+ override val reoriented = orientation in 2..8
31
+ override fun render(width: Int, height: Int): PalImageCodec.Rendered {
32
+ val targetWidth = if (swaps) height else width; val targetHeight = if (swaps) width else height
33
+ var sample = 1
34
+ while (storedWidth / (sample * 2) >= targetWidth && storedHeight / (sample * 2) >= targetHeight) sample *= 2
35
+ val decoded = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply {
36
+ inSampleSize = sample; inPreferredConfig = Bitmap.Config.ARGB_8888
37
+ }) ?: throw IllegalStateException("decode")
38
+ val matrix = Matrix().apply {
39
+ postScale(targetWidth.toFloat() / decoded.width, targetHeight.toFloat() / decoded.height)
40
+ when (orientation) {
41
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> postScale(-1f, 1f)
42
+ ExifInterface.ORIENTATION_ROTATE_180 -> postRotate(180f)
43
+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> postScale(1f, -1f)
44
+ ExifInterface.ORIENTATION_TRANSPOSE -> { postRotate(90f); postScale(-1f, 1f) }
45
+ ExifInterface.ORIENTATION_ROTATE_90 -> postRotate(90f)
46
+ ExifInterface.ORIENTATION_TRANSVERSE -> { postRotate(270f); postScale(-1f, 1f) }
47
+ ExifInterface.ORIENTATION_ROTATE_270 -> postRotate(270f)
48
+ }
49
+ }
50
+ var bitmap = Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
51
+ if (bitmap !== decoded) decoded.recycle()
52
+ if (bitmap.width != width || bitmap.height != height) {
53
+ // Float rounding in the matrix can land one pixel off; Core's plan size is exact.
54
+ bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true)
55
+ }
56
+ try {
57
+ fun encode(format: Bitmap.CompressFormat, quality: Int) =
58
+ ByteArrayOutputStream().also { if (!bitmap.compress(format, quality, it)) throw IllegalStateException("encode") }.toByteArray()
59
+ val png = encode(Bitmap.CompressFormat.PNG, 100)
60
+ return PalImageCodec.Rendered(png, if (bitmap.hasAlpha()) null else encode(Bitmap.CompressFormat.JPEG, 70))
61
+ } finally { bitmap.recycle() }
62
+ }
63
+ }
64
+ }
65
+
66
+ }
@@ -12,8 +12,8 @@ import androidx.work.WorkInfo
12
12
  import androidx.work.WorkManager
13
13
  import androidx.work.Worker
14
14
  import androidx.work.WorkerParameters
15
- import dev.croche.CrocheException
16
- import dev.croche.CrocheRuntime
15
+ import dev.croche.CrocheError
16
+ import dev.croche.LegacyAgentEngine
17
17
  import dev.croche.RuntimeCancellation
18
18
  import dev.croche.RuntimeScheduler
19
19
  import java.util.concurrent.TimeUnit
@@ -27,7 +27,7 @@ import java.util.concurrent.TimeUnit
27
27
 
28
28
  /**
29
29
  * Registers the earliest pending note as one `OneTimeWorkRequest`, tagged with `name`, whose
30
- * worker runs `deliverDue()`. Pass it to `CrocheRuntime.create(..., scheduler = ...)`, and call
30
+ * worker runs `deliverDue()`. Pass it to `LegacyAgentEngine.create(..., scheduler = ...)`, and call
31
31
  * `WorkManagerScheduler.install(application, name)` once in `Application.onCreate` so a run can
32
32
  * reach that Runtime.
33
33
  *
@@ -37,7 +37,7 @@ import java.util.concurrent.TimeUnit
37
37
  * through the Runtime installed for that name; a second open Runtime with the same name is
38
38
  * refused (`scheduler_conflict`), including a second Runtime given this same object.
39
39
  */
40
- class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) : RuntimeScheduler {
40
+ internal class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) : RuntimeScheduler {
41
41
  private val context = context.applicationContext
42
42
 
43
43
  override fun schedule(earliestAtMs: Long) = synchronized(lockFor(name)) {
@@ -70,7 +70,7 @@ class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) :
70
70
 
71
71
  private fun manager(): WorkManager = try { WorkManager.getInstance(context) }
72
72
  // The app turned WorkManager's initializer off without providing a Configuration.
73
- catch (_: IllegalStateException) { throw CrocheException("not_configured", "WorkManager is not initialized in this app") }
73
+ catch (_: IllegalStateException) { throw CrocheError("not_configured", "WorkManager is not initialized in this app") }
74
74
 
75
75
  companion object {
76
76
  const val DEFAULT_NAME = "croche.schedule"
@@ -78,7 +78,7 @@ class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) :
78
78
  private val claims = dev.croche.SchedulerClaims("WorkManager name")
79
79
  private val locks = java.util.concurrent.ConcurrentHashMap<String, Any>()
80
80
  private fun lockFor(name: String) = locks.getOrPut(name) { Any() }
81
- internal val providers = java.util.concurrent.ConcurrentHashMap<String, (Context) -> CrocheRuntime?>()
81
+ internal val providers = java.util.concurrent.ConcurrentHashMap<String, (Context) -> LegacyAgentEngine?>()
82
82
 
83
83
  /** The tag that marks `name`'s requests. */
84
84
  fun tag(name: String) = "dev.croche.schedule:$name"
@@ -91,14 +91,14 @@ class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) :
91
91
  /** What `name`'s WorkManager runs deliver through: the app's Runtime, opened if need be,
92
92
  * or null when there is none to reach (the run ends; the next open delivers). A run never
93
93
  * closes it. */
94
- fun deliverThrough(name: String = DEFAULT_NAME, runtime: (Context) -> CrocheRuntime?) { providers[name] = runtime }
94
+ fun deliverThrough(name: String = DEFAULT_NAME, runtime: (Context) -> LegacyAgentEngine?) { providers[name] = runtime }
95
95
 
96
96
  /**
97
97
  * `deliverThrough(name, runtime)`, and a delivery at each return to the foreground (the
98
98
  * first activity started), off the main thread. Call once per name in
99
99
  * `Application.onCreate`.
100
100
  */
101
- fun install(application: Application, name: String = DEFAULT_NAME, runtime: (Context) -> CrocheRuntime) {
101
+ fun install(application: Application, name: String = DEFAULT_NAME, runtime: (Context) -> LegacyAgentEngine) {
102
102
  deliverThrough(name, runtime)
103
103
  application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
104
104
  private var started = 0
@@ -0,0 +1,30 @@
1
+ package dev.croche.android.pal
2
+
3
+ import android.content.Context
4
+ import android.content.pm.ApplicationInfo
5
+ import dev.croche.CrocheError
6
+ import java.io.File
7
+ import java.io.FileNotFoundException
8
+ import java.io.IOException
9
+ import java.net.URI
10
+
11
+ internal class AndroidAssetPal(context: Context) {
12
+ private val assets = context.applicationContext.assets
13
+ fun readAsset(path: String): ByteArray? = try {
14
+ if (path.startsWith("file:")) File(URI(path)).inputStream().use { it.readBytes() }
15
+ else assets.open(path).use { it.readBytes() }
16
+ } catch (e: FileNotFoundException) {
17
+ // FileInputStream also uses FileNotFoundException for denied access: only absence is null.
18
+ if (path.startsWith("file:") && File(URI(path)).exists())
19
+ throw CrocheError("asset_read_failed", "App asset could not be read")
20
+ null
21
+ } catch (_: IOException) { throw CrocheError("asset_read_failed", "App asset could not be read") }
22
+ catch (_: SecurityException) { throw CrocheError("asset_read_failed", "App asset could not be read") }
23
+ catch (_: Exception) { throw CrocheError("internal", "Unexpected app asset failure") }
24
+ }
25
+
26
+ /** The application, not this library's BuildConfig, supplies Android's debuggable fact. */
27
+ internal data class AndroidPlatformFacts(val debuggable: Boolean)
28
+ internal fun androidPlatformFacts(context: Context) = AndroidPlatformFacts(
29
+ (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0,
30
+ )
@@ -0,0 +1,35 @@
1
+ package dev.croche.android.pal
2
+
3
+ import android.content.Context
4
+ import com.google.gson.JsonObject
5
+ import dev.croche.ffi.CoreAgent
6
+ import dev.croche.ffi.CoreCroche
7
+ import dev.croche.ffi.CoreStoragePal
8
+ import dev.croche.ffi.CoreToolRegistration
9
+ import dev.croche.ffi.HostStreamPlatform
10
+ import dev.croche.ffi.HostPal
11
+ import dev.croche.s7.CoreFactoryCalls
12
+ import dev.croche.s7.CoreOptionsEncoding
13
+
14
+ /** Internal platform entry for Kotlin/RN: real PALs, one Core owner, no successful fallback.
15
+ * This binds the ABI. The pinned Core factory still fails closed until its owner is complete.
16
+ */
17
+ internal class AndroidCoreFactory(context: Context, private val reactNative: Boolean = false) {
18
+ private val platformStorage = AndroidStoragePal(context.applicationContext)
19
+ private val context = context.applicationContext
20
+
21
+ suspend fun open(
22
+ options: JsonObject,
23
+ registrations: List<CoreToolRegistration>? = null,
24
+ customStorage: CoreStoragePal? = null,
25
+ ): CoreCroche {
26
+ val encoded = CoreOptionsEncoding.encode(options, registrations, platformStorage, customStorage)
27
+ val android = AndroidCoreHost(context, encoded.storage)
28
+ val host = if (!reactNative) android else object : HostPal by android {
29
+ override fun streamPlatform() = HostStreamPlatform.REACT_NATIVE
30
+ }
31
+ return CoreFactoryCalls.open(encoded.optionsJson, encoded.registrations, encoded.storage, host)
32
+ }
33
+
34
+ fun agent(owner: CoreCroche, id: String, scopeJson: String?): CoreAgent = owner.agent(id, scopeJson)
35
+ }
@@ -0,0 +1,121 @@
1
+ package dev.croche.android.pal
2
+
3
+ import android.content.Context
4
+ import android.net.Uri
5
+ import com.google.gson.JsonParser
6
+ import dev.croche.android.AndroidBackgroundWake
7
+ import dev.croche.CrocheError
8
+ import dev.croche.NativeImagePal
9
+ import dev.croche.ResponseSink
10
+ import dev.croche.RuntimeCancellation
11
+ import dev.croche.android.BitmapDecodedImageCodec
12
+ import dev.croche.ffi.*
13
+ import dev.croche.s7.attached
14
+ import dev.croche.s7.effectCallback
15
+ import dev.croche.s7.pal.DirectHttpPal
16
+ import java.io.ByteArrayOutputStream
17
+ import java.util.TimeZone
18
+ import java.util.UUID
19
+
20
+ /** Platform effects for the one S1 factory. No legacy project open, record routing or registry. */
21
+ internal class AndroidCoreHost(
22
+ context: Context,
23
+ private val storage: CoreStoragePal,
24
+ ) : HostPal {
25
+ private val context = context.applicationContext
26
+ private val assets = AndroidAssetPal(this.context)
27
+ private val http = DirectHttpPal()
28
+ private val codec = BitmapDecodedImageCodec()
29
+ private val captures = NativeImagePal()
30
+ override fun streamPlatform() = HostStreamPlatform.OTHER
31
+ override fun platformFacts() = PalPlatformFacts(PalTargetKind.ANDROID, androidPlatformFacts(context).debuggable,
32
+ context.resources.configuration.locales[0]?.toLanguageTag(), "android-play-integrity", false)
33
+ override fun imageCodecAvailable() = true
34
+ override fun decodeImage(bytes: ByteArray, options: PalImageDecodeOptions, cancel: CancelToken) =
35
+ effectCallback { codec.decode(bytes, options, cancel) }
36
+ override fun renderImage(request: PalImageRenderRequest, cancel: CancelToken) =
37
+ effectCallback { codec.render(request, cancel) }
38
+ override fun releaseDecodedImage(handle: String) = codec.release(handle)
39
+ override fun prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) =
40
+ effectCallback { captures.prepare(source, plan, cancel) }
41
+ override fun releaseImage(capture: String) = captures.release(capture)
42
+
43
+ override fun readImage(request: PalImageReadRequest, cancel: CancelToken): ByteArray = effectCallback {
44
+ if (request.source is PalImageReadSource.Capture) return@effectCallback captures.readBytes(request, cancel)
45
+ NativeImagePal.check(cancel)
46
+ val uri = (request.source as PalImageReadSource.Local).uri
47
+ try {
48
+ val input = if (Uri.parse(uri).scheme == null) context.assets.open(uri)
49
+ else context.contentResolver.openInputStream(Uri.parse(uri))
50
+ val bytes = input?.use { source ->
51
+ val output = ByteArrayOutputStream()
52
+ val buffer = ByteArray(8192)
53
+ while (true) {
54
+ NativeImagePal.check(cancel)
55
+ val count = source.read(buffer)
56
+ if (count < 0) break
57
+ if (output.size().toULong() + count.toULong() > request.maxBytes)
58
+ throw CrocheError("image_fetch_failed", "Image source exceeds the requested byte bound")
59
+ output.write(buffer, 0, count)
60
+ }
61
+ NativeImagePal.check(cancel)
62
+ output.toByteArray()
63
+ } ?: throw CrocheError("image_fetch_failed", "The image source is missing")
64
+ // Core sniffs and hashes these owned bytes; no JS/base64 or host metadata.
65
+ bytes
66
+ } catch (error: CrocheError) { throw error }
67
+ catch (_: java.io.IOException) { throw CrocheError("image_fetch_failed", "The image source could not be read") }
68
+ catch (_: SecurityException) { throw CrocheError("image_fetch_failed", "The image source could not be read") }
69
+ }
70
+
71
+ override fun http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) = effectCallback {
72
+ http.http(request, object : ResponseSink {
73
+ override fun head(status: Int, headers: List<PalHeader>) = sink.head(status.toUShort(), headers)
74
+ override fun chunk(bytes: ByteArray) = sink.chunk(bytes)
75
+ }, signal(cancel))
76
+ }
77
+ override fun resolve(host: String, cancel: CancelToken) = effectCallback { http.resolve(host, signal(cancel)) }
78
+ override fun readAsset(path: String) = effectCallback { assets.readAsset(path) }
79
+
80
+ // Transitional HostPal storage members are the SAME physical PAL, not a snapshot adapter.
81
+ // S1 composes the separately supplied CoreStoragePal for its actual storage operations.
82
+ override fun read(key: String) = storage.read(key)
83
+ override fun write(key: String, value: String) = storage.write(key, value)
84
+ override fun remove(key: String) = storage.remove(key)
85
+ override fun list(prefix: String) = storage.list(prefix)
86
+ override fun readSecret(key: String) = storage.readSecret(key)
87
+ override fun writeSecret(key: String, value: String) = storage.writeSecret(key, value)
88
+ override fun removeSecret(key: String) = storage.removeSecret(key)
89
+ override fun lock(key: String) = storage.lock(key)
90
+ override fun unlock(key: String) = storage.unlock(key)
91
+ override fun storeIdentity() = context.noBackupFilesDir.canonicalPath
92
+ override fun storageCapability() = StorageCapability.KEYED
93
+ override fun nowMs() = System.currentTimeMillis().toDouble()
94
+ override fun utcOffsetMinutes(atMs: Double) = TimeZone.getDefault().getOffset(atMs.toLong()).toLong() / 60_000
95
+ override fun random() = UUID.randomUUID().toString()
96
+
97
+ // CORE-GAP: factory Runtime.tick must be driven by Core's owned loop. There is no
98
+ // factory tick export at this pin; deliverDue is NOT a substitute for maintenance.
99
+ override fun wake(atMs: Double?) = Unit
100
+ override fun registerBackground(identifier: String, wake: CoreBackgroundWake) =
101
+ AndroidBackgroundWake.install(context, identifier, wake)
102
+ override fun schedule(entries: String) {
103
+ val earliest = JsonParser.parseString(entries).asJsonArray.map { java.time.Instant.parse(it.asJsonObject.get("at").asString).toEpochMilli() }.minOrNull()
104
+ AndroidBackgroundWake.schedule(earliest, System.currentTimeMillis())
105
+ }
106
+ override fun tool(invocation: String, cancel: CancelToken): ToolOutput =
107
+ throw CorePalException.Failure("capability_unsupported", "S1 uses registered Core tool definitions")
108
+ override fun attest(request: String, timeoutMs: ULong): String =
109
+ throw CorePalException.Failure("attestation_unsupported", "No attestation provider is attached")
110
+ override fun archiveAppendLine(entry: String, line: String): Unit = legacyArchive()
111
+ override fun archiveReadLines(entry: String): List<String> = legacyArchive()
112
+ override fun archiveReplaceLines(entry: String, lines: List<String>): Unit = legacyArchive()
113
+ override fun archiveRemove(entry: String): Unit = legacyArchive()
114
+ override fun archiveEntries(prefix: String): List<ArchiveEntry> = legacyArchive()
115
+ private fun legacyArchive(): Nothing = throw CoreStorageFailure.Failure("Snapshot archive callbacks were removed; Core owns keyed records")
116
+
117
+ private fun signal(cancel: CancelToken) = RuntimeCancellation().also { signal ->
118
+ if (cancel.isCancelled()) signal.cancel()
119
+ cancel.onCancel(attached(object : CancelCallback { override fun cancelled() = signal.cancel() }))
120
+ }
121
+ }
@@ -0,0 +1,17 @@
1
+ package dev.croche.android.pal
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import kotlinx.coroutines.CoroutineDispatcher
6
+ import java.util.concurrent.RejectedExecutionException
7
+ import kotlin.coroutines.CoroutineContext
8
+
9
+ /** The platform UI executor, not another event queue. Core owns event order and delivery gates.
10
+ * Uses Android itself; the common SDK does not require a coroutines-android dependency. */
11
+ internal object AndroidMainDispatcher : CoroutineDispatcher() {
12
+ private val handler by lazy { Handler(Looper.getMainLooper()) }
13
+ override fun isDispatchNeeded(context: CoroutineContext) = Looper.myLooper() != Looper.getMainLooper()
14
+ override fun dispatch(context: CoroutineContext, block: Runnable) {
15
+ if (!handler.post(block)) throw RejectedExecutionException("The Android main looper is unavailable")
16
+ }
17
+ }
@@ -0,0 +1,17 @@
1
+ package dev.croche.android.pal
2
+
3
+ import android.content.Context
4
+ import dev.croche.ffi.CoreStoragePal
5
+ import dev.croche.s7.NativePlatformPals
6
+ import dev.croche.s7.NativePlatformProvider
7
+ import dev.croche.s7.backgroundStorage
8
+
9
+ /** Loaded by the common facade; the app's Context remains an opaque platform handle. */
10
+ internal class AndroidPublicPlatform : NativePlatformProvider {
11
+ override fun create(platform: Any?, storage: CoreStoragePal?): NativePlatformPals {
12
+ val context = (platform as Context).applicationContext
13
+ val (pal, platformStorage) = backgroundStorage(storage) { AndroidStoragePal(context) }
14
+ val host = AndroidCoreHost(context, pal)
15
+ return NativePlatformPals(pal, host, AndroidMainDispatcher, platformStorage)
16
+ }
17
+ }
@@ -0,0 +1,14 @@
1
+ package dev.croche.android.pal
2
+
3
+ import android.content.Context
4
+ import dev.croche.s7.pal.DirectHttpPal
5
+
6
+ /** Android effects for S2. No admission policy, record layout or wiki cache lives here.
7
+ * AndroidCoreHost composes these same implementations through the generated callbacks.
8
+ * The old public host is deliberately not used as a fallback for the partial S1 factory. */
9
+ internal class AndroidS2Pal(context: Context) {
10
+ val storage = AndroidStoragePal(context)
11
+ val assets = AndroidAssetPal(context)
12
+ val http = DirectHttpPal()
13
+ val platformFacts = androidPlatformFacts(context)
14
+ }