@c9up/orbit 0.0.0-stage → 0.1.1

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 (105) hide show
  1. package/Cargo.lock +139 -0
  2. package/Cargo.toml +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +320 -2
  5. package/android/orbit.cmake +31 -0
  6. package/android/src/main/cpp/NativeOrbit.cpp +309 -0
  7. package/android/src/main/cpp/NativeOrbit.h +35 -0
  8. package/android/src/main/cpp/orbit_host.h +34 -0
  9. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +286 -0
  10. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +258 -0
  11. package/android/src/main/java/com/c9up/orbit/OrbitImage.kt +346 -0
  12. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +161 -0
  13. package/android/src/main/java/com/c9up/orbit/OrbitPress.kt +110 -0
  14. package/android/src/main/java/com/c9up/orbit/OrbitVector.kt +115 -0
  15. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +362 -0
  16. package/crates/orbit-host/Cargo.toml +14 -0
  17. package/crates/orbit-host/src/gesture.rs +561 -0
  18. package/crates/orbit-host/src/lib.rs +2042 -0
  19. package/crates/orbit-host/src/motion.rs +328 -0
  20. package/crates/orbit-host/src/vector.rs +1173 -0
  21. package/dist/color.d.ts +10 -0
  22. package/dist/color.d.ts.map +1 -0
  23. package/dist/color.js +62 -0
  24. package/dist/color.js.map +1 -0
  25. package/dist/commit.d.ts +77 -0
  26. package/dist/commit.d.ts.map +1 -0
  27. package/dist/commit.js +302 -0
  28. package/dist/commit.js.map +1 -0
  29. package/dist/errors.d.ts +76 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +89 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/host.d.ts +49 -0
  34. package/dist/host.d.ts.map +1 -0
  35. package/dist/host.js +20 -0
  36. package/dist/host.js.map +1 -0
  37. package/dist/index.d.ts +31 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +31 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/motion.d.ts +18 -0
  42. package/dist/motion.d.ts.map +1 -0
  43. package/dist/motion.js +67 -0
  44. package/dist/motion.js.map +1 -0
  45. package/dist/node.d.ts +46 -0
  46. package/dist/node.d.ts.map +1 -0
  47. package/dist/node.js +110 -0
  48. package/dist/node.js.map +1 -0
  49. package/dist/pages.d.ts +56 -0
  50. package/dist/pages.d.ts.map +1 -0
  51. package/dist/pages.js +157 -0
  52. package/dist/pages.js.map +1 -0
  53. package/dist/react-native/index.d.ts +33 -0
  54. package/dist/react-native/index.d.ts.map +1 -0
  55. package/dist/react-native/index.js +71 -0
  56. package/dist/react-native/index.js.map +1 -0
  57. package/dist/report.d.ts +13 -0
  58. package/dist/report.d.ts.map +1 -0
  59. package/dist/report.js +22 -0
  60. package/dist/report.js.map +1 -0
  61. package/dist/server.d.ts +109 -0
  62. package/dist/server.d.ts.map +1 -0
  63. package/dist/server.js +290 -0
  64. package/dist/server.js.map +1 -0
  65. package/dist/stack.d.ts +117 -0
  66. package/dist/stack.d.ts.map +1 -0
  67. package/dist/stack.js +299 -0
  68. package/dist/stack.js.map +1 -0
  69. package/dist/styles.d.ts +138 -0
  70. package/dist/styles.d.ts.map +1 -0
  71. package/dist/styles.js +920 -0
  72. package/dist/styles.js.map +1 -0
  73. package/dist/template.d.ts +27 -0
  74. package/dist/template.d.ts.map +1 -0
  75. package/dist/template.js +1436 -0
  76. package/dist/template.js.map +1 -0
  77. package/dist/textDecoder.d.ts +29 -0
  78. package/dist/textDecoder.d.ts.map +1 -0
  79. package/dist/textDecoder.js +149 -0
  80. package/dist/textDecoder.js.map +1 -0
  81. package/dist/url.d.ts +45 -0
  82. package/dist/url.d.ts.map +1 -0
  83. package/dist/url.js +303 -0
  84. package/dist/url.js.map +1 -0
  85. package/package.json +96 -3
  86. package/scripts/build-android.sh +27 -0
  87. package/scripts/test-styles.mjs +31 -0
  88. package/specs/NativeOrbit.ts +34 -0
  89. package/src/color.ts +68 -0
  90. package/src/commit.ts +373 -0
  91. package/src/errors.ts +178 -0
  92. package/src/host.ts +91 -0
  93. package/src/index.ts +64 -0
  94. package/src/motion.ts +88 -0
  95. package/src/node.ts +133 -0
  96. package/src/pages.ts +207 -0
  97. package/src/react-native/index.ts +115 -0
  98. package/src/react-native/react-native.d.ts +39 -0
  99. package/src/report.ts +25 -0
  100. package/src/server.ts +395 -0
  101. package/src/stack.ts +428 -0
  102. package/src/styles.ts +1021 -0
  103. package/src/template.ts +1681 -0
  104. package/src/textDecoder.ts +162 -0
  105. package/src/url.ts +333 -0
@@ -0,0 +1,309 @@
1
+ #include "NativeOrbit.h"
2
+
3
+ #include <fbjni/fbjni.h>
4
+ #include <jni.h>
5
+
6
+ #include <algorithm>
7
+ #include <cstdint>
8
+ #include <optional>
9
+ #include <string>
10
+ #include <mutex>
11
+ #include <vector>
12
+
13
+ #include "orbit_host.h"
14
+
15
+ namespace facebook::react {
16
+
17
+ namespace {
18
+
19
+ // Cached from OrbitHost.nativeInit, which runs on a Java thread with the app's
20
+ // class loader: a FindClass from the JS thread would see the system loader.
21
+ jclass gHostClass = nullptr;
22
+ jmethodID gApply = nullptr;
23
+ jmethodID gMeasure = nullptr;
24
+ jmethodID gImageBytes = nullptr;
25
+ jmethodID gScroll = nullptr;
26
+
27
+ std::mutex gHandlerMutex;
28
+ std::shared_ptr<OrbitEventHandler> gHandler;
29
+ // The last safe-area size the platform reported (dp), replayed to a handler set later.
30
+ float gViewportWidth = 0;
31
+ float gViewportHeight = 0;
32
+
33
+ std::string takeString(OrbitBuf buf) {
34
+ std::string s(reinterpret_cast<const char*>(buf.ptr), buf.len);
35
+ orbit_buf_free(buf);
36
+ return s;
37
+ }
38
+
39
+ // Called by orbit-host during layout, on the JS thread.
40
+ uint64_t measureText(const uint8_t* spans, size_t len, float maxWidth) {
41
+ if (gHostClass == nullptr) {
42
+ return 0;
43
+ }
44
+ JNIEnv* env = facebook::jni::Environment::current();
45
+ jbyteArray bytes = env->NewByteArray(static_cast<jsize>(len));
46
+ env->SetByteArrayRegion(bytes, 0, static_cast<jsize>(len), reinterpret_cast<const jbyte*>(spans));
47
+ jlong packed = env->CallStaticLongMethod(gHostClass, gMeasure, bytes, static_cast<jfloat>(maxWidth));
48
+ env->DeleteLocalRef(bytes);
49
+ return static_cast<uint64_t>(packed);
50
+ }
51
+
52
+ } // namespace
53
+
54
+ NativeOrbit::NativeOrbit(std::shared_ptr<CallInvoker> jsInvoker)
55
+ : NativeOrbitCxxSpec(std::move(jsInvoker)) {
56
+ orbit_set_measure(&measureText);
57
+ }
58
+
59
+ void NativeOrbit::setViewport(jsi::Runtime&, double width, double height) {
60
+ orbit_set_viewport(static_cast<float>(width), static_cast<float>(height));
61
+ }
62
+
63
+ std::string NativeOrbit::commit(jsi::Runtime& rt, std::string ops) {
64
+ OrbitBuf mountOps{};
65
+ OrbitBuf info{};
66
+ int32_t code = orbit_commit(reinterpret_cast<const uint8_t*>(ops.data()), ops.size(), &mountOps, &info);
67
+ if (code == 0 && mountOps.len > 0 && gHostClass != nullptr) {
68
+ JNIEnv* env = facebook::jni::Environment::current();
69
+ jbyteArray bytes = env->NewByteArray(static_cast<jsize>(mountOps.len));
70
+ env->SetByteArrayRegion(bytes, 0, static_cast<jsize>(mountOps.len), reinterpret_cast<const jbyte*>(mountOps.ptr));
71
+ env->CallStaticVoidMethod(gHostClass, gApply, bytes);
72
+ env->DeleteLocalRef(bytes);
73
+ }
74
+ orbit_buf_free(mountOps);
75
+ std::string report = takeString(info);
76
+ if (code != 0) {
77
+ throw jsi::JSError(rt, report);
78
+ }
79
+ return report;
80
+ }
81
+
82
+ // The bytes of an `<img src=${bytes}>`: a Uint8Array (any typed-array view) or
83
+ // an ArrayBuffer, copied straight into the Kotlin side's memory.
84
+ void NativeOrbit::imageBytes(jsi::Runtime& rt, double tag, jsi::Object bytes) {
85
+ const char* refused = "[orbit] imageBytes expects a Uint8Array or an ArrayBuffer";
86
+ std::optional<jsi::ArrayBuffer> buffer;
87
+ size_t offset = 0;
88
+ size_t length = 0;
89
+ if (bytes.isArrayBuffer(rt)) {
90
+ buffer.emplace(bytes.getArrayBuffer(rt));
91
+ length = buffer->size(rt);
92
+ } else {
93
+ jsi::Value inner = bytes.getProperty(rt, "buffer");
94
+ jsi::Value byteOffset = bytes.getProperty(rt, "byteOffset");
95
+ jsi::Value byteLength = bytes.getProperty(rt, "byteLength");
96
+ if (!inner.isObject() || !byteOffset.isNumber() || !byteLength.isNumber()) {
97
+ throw jsi::JSError(rt, refused);
98
+ }
99
+ jsi::Object object = inner.getObject(rt);
100
+ if (!object.isArrayBuffer(rt) || byteOffset.getNumber() < 0 || byteLength.getNumber() < 0) {
101
+ throw jsi::JSError(rt, refused);
102
+ }
103
+ buffer.emplace(object.getArrayBuffer(rt));
104
+ offset = static_cast<size_t>(byteOffset.getNumber());
105
+ length = static_cast<size_t>(byteLength.getNumber());
106
+ }
107
+ size_t size = buffer->size(rt);
108
+ if (offset > size || length > size - offset || length > static_cast<size_t>(INT32_MAX)) {
109
+ throw jsi::JSError(rt, "[orbit] imageBytes: the view runs past its buffer");
110
+ }
111
+ if (gHostClass == nullptr) {
112
+ return;
113
+ }
114
+ JNIEnv* env = facebook::jni::Environment::current();
115
+ jbyteArray array = env->NewByteArray(static_cast<jsize>(length));
116
+ env->SetByteArrayRegion(
117
+ array, 0, static_cast<jsize>(length), reinterpret_cast<const jbyte*>(buffer->data(rt) + offset));
118
+ env->CallStaticVoidMethod(gHostClass, gImageBytes, static_cast<jint>(tag), array);
119
+ env->DeleteLocalRef(array);
120
+ }
121
+
122
+ // Where nodes were laid out, for a lazy list: a JSON array of tags in, of
123
+ // [x, y, w, h] (dp, root coordinates) or null out.
124
+ std::string NativeOrbit::layout(jsi::Runtime& rt, std::string tags) {
125
+ OrbitBuf out{};
126
+ int32_t code = orbit_layout(reinterpret_cast<const uint8_t*>(tags.data()), tags.size(), &out);
127
+ std::string json = takeString(out);
128
+ if (code != 0) {
129
+ throw jsi::JSError(rt, json);
130
+ }
131
+ return json;
132
+ }
133
+
134
+ // Scroll a scroll view by `by` dp, or to its end: applied on the UI thread
135
+ // after the mount operations already posted, so a lazy list's correction
136
+ // lands with the layout it corrects.
137
+ void NativeOrbit::scroll(jsi::Runtime&, double tag, double by, bool toEnd) {
138
+ if (gHostClass == nullptr) {
139
+ return;
140
+ }
141
+ JNIEnv* env = facebook::jni::Environment::current();
142
+ env->CallStaticVoidMethod(
143
+ gHostClass, gScroll, static_cast<jint>(tag), static_cast<jfloat>(by), static_cast<jboolean>(toEnd));
144
+ }
145
+
146
+ void NativeOrbit::setEventHandler(jsi::Runtime&, OrbitEventHandler handler) {
147
+ std::lock_guard<std::mutex> lock(gHandlerMutex);
148
+ gHandler = std::make_shared<OrbitEventHandler>(std::move(handler));
149
+ // The platform may have reported the safe area before JS listened.
150
+ if (gViewportWidth > 0 && gViewportHeight > 0) {
151
+ gHandler->call(0.0, std::string("topViewport"), gViewportWidth, gViewportHeight, std::string());
152
+ }
153
+ }
154
+
155
+ void NativeOrbit::motionValue(jsi::Runtime&, double tag, double initial) {
156
+ orbit_motion_value(static_cast<int32_t>(tag), initial);
157
+ }
158
+
159
+ void NativeOrbit::motionInterpolate(
160
+ jsi::Runtime&, double tag, double input, std::vector<double> from, std::vector<double> to) {
161
+ size_t len = std::min(from.size(), to.size());
162
+ orbit_motion_interpolate(static_cast<int32_t>(tag), static_cast<int32_t>(input), from.data(), to.data(), len);
163
+ }
164
+
165
+ void NativeOrbit::motionSet(jsi::Runtime&, double tag, double value) {
166
+ orbit_motion_set(static_cast<int32_t>(tag), value);
167
+ }
168
+
169
+ void NativeOrbit::motionStop(jsi::Runtime&, double tag) {
170
+ orbit_motion_stop(static_cast<int32_t>(tag));
171
+ }
172
+
173
+ void NativeOrbit::motionFrames(jsi::Runtime&, double tag, std::vector<double> frames, double to, bool loop) {
174
+ orbit_motion_frames(static_cast<int32_t>(tag), frames.data(), frames.size(), to, loop);
175
+ }
176
+
177
+ void NativeOrbit::motionSpring(jsi::Runtime&, double tag, double to, double stiffness, double damping, double mass) {
178
+ orbit_motion_spring(static_cast<int32_t>(tag), to, stiffness, damping, mass);
179
+ }
180
+
181
+ void NativeOrbit::motionDispose(jsi::Runtime&, double tag) {
182
+ orbit_motion_dispose(static_cast<int32_t>(tag));
183
+ }
184
+
185
+ void NativeOrbit::motionBind(jsi::Runtime&, double view, double prop, double node) {
186
+ orbit_motion_bind(static_cast<int32_t>(view), static_cast<uint8_t>(prop), static_cast<int32_t>(node));
187
+ }
188
+
189
+ void NativeOrbit::motionBindScroll(jsi::Runtime&, double scrollView, double value) {
190
+ orbit_motion_bind_scroll(static_cast<int32_t>(scrollView), static_cast<int32_t>(value));
191
+ }
192
+
193
+ } // namespace facebook::react
194
+
195
+ // UI thread, every vsync: advance orbit-host's animations. Returns the
196
+ // records (i32 view, u8 prop, f32 value), prefixed by one byte: 1 while running.
197
+ extern "C" JNIEXPORT jbyteArray JNICALL Java_com_c9up_orbit_OrbitHost_nativeTick(
198
+ JNIEnv* env, jclass, jlong nowNs, jintArray scrollTags, jfloatArray scrollY) {
199
+ jsize count = env->GetArrayLength(scrollTags);
200
+ std::vector<int32_t> tags(count);
201
+ std::vector<float> ys(count);
202
+ if (count > 0) {
203
+ env->GetIntArrayRegion(scrollTags, 0, count, reinterpret_cast<jint*>(tags.data()));
204
+ env->GetFloatArrayRegion(scrollY, 0, count, ys.data());
205
+ }
206
+ OrbitBuf out{};
207
+ int32_t active = orbit_motion_tick(nowNs, tags.data(), ys.data(), static_cast<size_t>(count), &out);
208
+ jbyteArray result = env->NewByteArray(static_cast<jsize>(out.len + 1));
209
+ jbyte flag = static_cast<jbyte>(active);
210
+ env->SetByteArrayRegion(result, 0, 1, &flag);
211
+ if (out.len > 0) {
212
+ env->SetByteArrayRegion(result, 1, static_cast<jsize>(out.len), reinterpret_cast<const jbyte*>(out.ptr));
213
+ }
214
+ orbit_buf_free(out);
215
+ return result;
216
+ }
217
+
218
+ extern "C" JNIEXPORT void JNICALL Java_com_c9up_orbit_OrbitHost_nativeInit(JNIEnv* env, jclass cls) {
219
+ using namespace facebook::react;
220
+ if (gHostClass == nullptr) {
221
+ gHostClass = static_cast<jclass>(env->NewGlobalRef(cls));
222
+ gApply = env->GetStaticMethodID(cls, "apply", "([B)V");
223
+ gMeasure = env->GetStaticMethodID(cls, "measureText", "([BF)J");
224
+ gImageBytes = env->GetStaticMethodID(cls, "imageBytes", "(I[B)V");
225
+ gScroll = env->GetStaticMethodID(cls, "scroll", "(IFZ)V");
226
+ }
227
+ }
228
+
229
+ extern "C" JNIEXPORT void JNICALL Java_com_c9up_orbit_OrbitHost_nativeDispatch(
230
+ JNIEnv* env, jclass, jint tag, jstring type, jfloat x, jfloat y) {
231
+ using namespace facebook::react;
232
+ std::shared_ptr<OrbitEventHandler> handler;
233
+ {
234
+ std::lock_guard<std::mutex> lock(gHandlerMutex);
235
+ handler = gHandler;
236
+ }
237
+ if (!handler) {
238
+ return;
239
+ }
240
+ const char* chars = env->GetStringUTFChars(type, nullptr);
241
+ std::string name(chars);
242
+ env->ReleaseStringUTFChars(type, chars);
243
+ // Scheduled onto the JS thread by the callback itself.
244
+ handler->call(static_cast<double>(tag), std::move(name), static_cast<double>(x), static_cast<double>(y), std::string());
245
+ }
246
+
247
+
248
+ // A text field's event (`topChange`, `topFocus`, `topBlur`, `topSubmit`) with its text.
249
+ extern "C" JNIEXPORT void JNICALL Java_com_c9up_orbit_OrbitHost_nativeDispatchText(
250
+ JNIEnv* env, jclass, jint tag, jstring type, jstring text) {
251
+ using namespace facebook::react;
252
+ std::shared_ptr<OrbitEventHandler> handler;
253
+ {
254
+ std::lock_guard<std::mutex> lock(gHandlerMutex);
255
+ handler = gHandler;
256
+ }
257
+ if (!handler) {
258
+ return;
259
+ }
260
+ auto read = [env](jstring s) {
261
+ const char* chars = env->GetStringUTFChars(s, nullptr);
262
+ std::string out(chars);
263
+ env->ReleaseStringUTFChars(s, chars);
264
+ return out;
265
+ };
266
+ handler->call(static_cast<double>(tag), read(type), 0.0, 0.0, read(text));
267
+ }
268
+
269
+ namespace {
270
+ jbyteArray toBytes(JNIEnv* env, OrbitBuf buf) {
271
+ jbyteArray result = env->NewByteArray(static_cast<jsize>(buf.len));
272
+ if (buf.len > 0) {
273
+ env->SetByteArrayRegion(result, 0, static_cast<jsize>(buf.len), reinterpret_cast<const jbyte*>(buf.ptr));
274
+ }
275
+ orbit_buf_free(buf);
276
+ return result;
277
+ }
278
+ } // namespace
279
+
280
+ // UI thread: a touch for orbit-host's gesture recognizer; returns its commands.
281
+ extern "C" JNIEXPORT jbyteArray JNICALL Java_com_c9up_orbit_OrbitHost_nativeTouch(
282
+ JNIEnv* env, jclass, jint action, jfloat x, jfloat y, jlong nowNs, jint hit) {
283
+ OrbitBuf out{};
284
+ orbit_touch(static_cast<uint8_t>(action), x, y, nowNs, hit, &out);
285
+ return toBytes(env, out);
286
+ }
287
+
288
+ // UI thread, every vsync: long presses and delayed press feedback.
289
+ extern "C" JNIEXPORT jbyteArray JNICALL Java_com_c9up_orbit_OrbitHost_nativeGestureTick(
290
+ JNIEnv* env, jclass, jlong nowNs) {
291
+ OrbitBuf out{};
292
+ orbit_gesture_tick(nowNs, &out);
293
+ return toBytes(env, out);
294
+ }
295
+
296
+ // The safe area (dp) changed: remembered, and sent to JS if it listens.
297
+ extern "C" JNIEXPORT void JNICALL Java_com_c9up_orbit_OrbitHost_nativeViewport(JNIEnv*, jclass, jfloat width, jfloat height) {
298
+ using namespace facebook::react;
299
+ std::shared_ptr<OrbitEventHandler> handler;
300
+ {
301
+ std::lock_guard<std::mutex> lock(gHandlerMutex);
302
+ gViewportWidth = width;
303
+ gViewportHeight = height;
304
+ handler = gHandler;
305
+ }
306
+ if (handler) {
307
+ handler->call(0.0, std::string("topViewport"), static_cast<double>(width), static_cast<double>(height), std::string());
308
+ }
309
+ }
@@ -0,0 +1,35 @@
1
+ #pragma once
2
+
3
+ #include <AppSpecsJSI.h>
4
+
5
+ #include <memory>
6
+ #include <string>
7
+ #include <vector>
8
+
9
+ namespace facebook::react {
10
+
11
+ using OrbitEventHandler = AsyncCallback<double, std::string, double, double, std::string>;
12
+
13
+ class NativeOrbit : public NativeOrbitCxxSpec<NativeOrbit> {
14
+ public:
15
+ explicit NativeOrbit(std::shared_ptr<CallInvoker> jsInvoker);
16
+
17
+ void setViewport(jsi::Runtime& rt, double width, double height);
18
+ std::string commit(jsi::Runtime& rt, std::string ops);
19
+ void imageBytes(jsi::Runtime& rt, double tag, jsi::Object bytes);
20
+ std::string layout(jsi::Runtime& rt, std::string tags);
21
+ void scroll(jsi::Runtime& rt, double tag, double by, bool toEnd);
22
+ void setEventHandler(jsi::Runtime& rt, OrbitEventHandler handler);
23
+
24
+ void motionValue(jsi::Runtime& rt, double tag, double initial);
25
+ void motionInterpolate(jsi::Runtime& rt, double tag, double input, std::vector<double> from, std::vector<double> to);
26
+ void motionSet(jsi::Runtime& rt, double tag, double value);
27
+ void motionStop(jsi::Runtime& rt, double tag);
28
+ void motionFrames(jsi::Runtime& rt, double tag, std::vector<double> frames, double to, bool loop);
29
+ void motionSpring(jsi::Runtime& rt, double tag, double to, double stiffness, double damping, double mass);
30
+ void motionDispose(jsi::Runtime& rt, double tag);
31
+ void motionBind(jsi::Runtime& rt, double view, double prop, double node);
32
+ void motionBindScroll(jsi::Runtime& rt, double scrollView, double value);
33
+ };
34
+
35
+ } // namespace facebook::react
@@ -0,0 +1,34 @@
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <cstdint>
5
+
6
+ extern "C" {
7
+
8
+ struct OrbitBuf {
9
+ uint8_t* ptr;
10
+ size_t len;
11
+ size_t cap;
12
+ };
13
+
14
+ typedef uint64_t (*OrbitMeasureFn)(const uint8_t* spans, size_t len, float maxWidth);
15
+
16
+ void orbit_set_measure(OrbitMeasureFn measure);
17
+ void orbit_set_viewport(float width, float height);
18
+ int32_t orbit_commit(const uint8_t* ops, size_t len, OrbitBuf* mountOps, OrbitBuf* info);
19
+ int32_t orbit_layout(const uint8_t* tags, size_t len, OrbitBuf* out);
20
+ void orbit_touch(uint8_t action, float x, float y, int64_t nowNs, int32_t hit, OrbitBuf* out);
21
+ void orbit_gesture_tick(int64_t nowNs, OrbitBuf* out);
22
+ void orbit_buf_free(OrbitBuf buf);
23
+
24
+ void orbit_motion_value(int32_t tag, double initial);
25
+ void orbit_motion_interpolate(int32_t tag, int32_t input, const double* from, const double* to, size_t len);
26
+ void orbit_motion_set(int32_t tag, double value);
27
+ void orbit_motion_stop(int32_t tag);
28
+ void orbit_motion_frames(int32_t tag, const double* frames, size_t len, double to, bool looping);
29
+ void orbit_motion_spring(int32_t tag, double to, double stiffness, double damping, double mass);
30
+ void orbit_motion_dispose(int32_t tag);
31
+ void orbit_motion_bind(int32_t view, uint8_t prop, int32_t node);
32
+ void orbit_motion_bind_scroll(int32_t scrollView, int32_t value);
33
+ int32_t orbit_motion_tick(int64_t nowNs, const int32_t* scrollTags, const float* scrollY, size_t count, OrbitBuf* out);
34
+ }
@@ -0,0 +1,286 @@
1
+ package com.c9up.orbit
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.BlurMaskFilter
5
+ import android.graphics.Canvas
6
+ import android.graphics.Paint
7
+ import android.graphics.Path
8
+ import android.graphics.Rect
9
+ import android.graphics.RectF
10
+ import android.graphics.RenderEffect
11
+ import android.graphics.RenderNode
12
+ import android.graphics.Shader
13
+ import android.os.Build
14
+ import android.view.View
15
+ import android.view.ViewGroup
16
+ import android.view.ViewTreeObserver
17
+ import java.util.WeakHashMap
18
+ import kotlin.math.ceil
19
+ import kotlin.math.max
20
+ import kotlin.math.min
21
+ import kotlin.math.roundToInt
22
+
23
+ /** A CSS box shadow, in px: offset, blur radius (CSS's, twice the Gaussian's sigma), spread, colour. */
24
+ class Shadow(val dx: Float, val dy: Float, val blur: Float, val spread: Float, val color: Int)
25
+
26
+ /**
27
+ * What orbit's views draw beyond their box, on the hardware canvas:
28
+ *
29
+ * - box shadows (Android 8+): a parent draws each child's shadow just before
30
+ * the child, outside the child's rounded box — as CSS draws it, so a
31
+ * translucent view does not show its own shadow through itself;
32
+ * - backdrop blur (Android 12+): a glass view records what its parent drew
33
+ * before it (the parent's background and earlier siblings, each a render
34
+ * node already recorded this frame) into a render node blurred by
35
+ * `RenderEffect`, and draws that under its own translucent background.
36
+ * Below Android 12 it keeps the translucent background alone.
37
+ */
38
+ object OrbitEffects {
39
+ private const val BACKDROP_SCALE = 0.25f
40
+ private val shadows = WeakHashMap<View, Shadow>()
41
+ private val radii = WeakHashMap<View, Float>()
42
+ /** Views whose fill is opaque: they hide their own shadow, no clip needed. */
43
+ private val opaque = WeakHashMap<View, Boolean>()
44
+ private val glasses = WeakHashMap<OrbitBox, Boolean>()
45
+ private val path = Path()
46
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
47
+ private val blurs = HashMap<Float, BlurMaskFilter>()
48
+ /** Set while a glass records its backdrop: a glass inside it draws none. */
49
+ private var capturing = false
50
+ private val listened = WeakHashMap<ViewTreeObserver, Boolean>()
51
+
52
+ /** Skia's radius for a Gaussian of `sigma` (what BlurMaskFilter and RenderEffect take). */
53
+ private fun skiaRadius(sigma: Float) = max((sigma - 0.5f) / 0.57735f, 0f)
54
+
55
+ fun setRadius(view: View, radius: Float) {
56
+ radii[view] = radius
57
+ }
58
+
59
+ fun radiusOf(view: View): Float = radii[view] ?: 0f
60
+
61
+ private val fills = WeakHashMap<View, Int>()
62
+
63
+ fun setFill(view: View, fill: Int) {
64
+ fills[view] = fill
65
+ }
66
+
67
+ /** A fill dark enough that a light ripple reads on it. */
68
+ fun isDark(view: View): Boolean {
69
+ val fill = fills[view] ?: return false
70
+ if ((fill ushr 24) < 0x80) return false
71
+ val luminance = 0.2126 * ((fill shr 16) and 0xff) + 0.7152 * ((fill shr 8) and 0xff) + 0.0722 * (fill and 0xff)
72
+ return luminance < 140
73
+ }
74
+
75
+ fun setOpaque(view: View, isOpaque: Boolean) {
76
+ if (isOpaque) opaque[view] = true else opaque.remove(view)
77
+ }
78
+
79
+ /** The view's effects op, sizes already in px. */
80
+ fun apply(view: View, shadow: Shadow?, backdropSigma: Float, clip: Boolean) {
81
+ if (shadow == null || shadow.color ushr 24 == 0) shadows.remove(view) else shadows[view] = shadow
82
+ (view.parent as? View)?.invalidate()
83
+ val box = view as? OrbitBox ?: return
84
+ box.setClip(clip)
85
+ box.backdropSigma = backdropSigma
86
+ if (backdropSigma > 0f) {
87
+ glasses[box] = true
88
+ box.setWillNotDraw(false)
89
+ listen(box)
90
+ } else {
91
+ glasses.remove(box)
92
+ }
93
+ box.invalidate()
94
+ }
95
+
96
+ /** Something under a glass may have moved: scrolled, mounted or animated. */
97
+ fun invalidateBackdrops() {
98
+ for (glass in glasses.keys) glass.invalidate()
99
+ }
100
+
101
+ private fun listen(view: View) {
102
+ val observer = view.viewTreeObserver
103
+ if (!observer.isAlive || listened.containsKey(observer)) return
104
+ listened[observer] = true
105
+ observer.addOnScrollChangedListener { invalidateBackdrops() }
106
+ }
107
+
108
+ /** Called by a parent before it draws `child`. */
109
+ fun drawShadow(canvas: Canvas, child: View) {
110
+ // Not into a backdrop: the blur washes it out, and a blurred shadow drawn
111
+ // into a scaled offscreen layer missed Skia's mask cache every frame
112
+ // (several ms of RenderThread work for nothing visible).
113
+ if (Build.VERSION.SDK_INT < 26 || capturing) return
114
+ val shadow = shadows[child] ?: return
115
+ if (child.visibility != View.VISIBLE || child.alpha <= 0f) return
116
+ val w = child.width.toFloat()
117
+ val h = child.height.toFloat()
118
+ if (w <= 0f || h <= 0f) return
119
+ val radius = min(radii[child] ?: 0f, min(w, h) / 2f)
120
+ canvas.save()
121
+ canvas.translate(child.left + child.translationX, child.top + child.translationY)
122
+ if (child.scaleX != 1f || child.scaleY != 1f) {
123
+ canvas.scale(child.scaleX, child.scaleY, child.pivotX, child.pivotY)
124
+ }
125
+ // CSS paints a shadow outside the border box only. An opaque view covers
126
+ // the part under it anyway, and the clip (a mask per draw on the GPU) is
127
+ // what a list of shadowed cards paid for most: only a translucent view
128
+ // gets it.
129
+ if (opaque[child] != true || child.alpha < 1f) {
130
+ if (radius > 0f) {
131
+ path.reset()
132
+ path.addRoundRect(0f, 0f, w, h, radius, radius, Path.Direction.CW)
133
+ canvas.clipOutPath(path)
134
+ } else {
135
+ canvas.clipOutRect(0f, 0f, w, h)
136
+ }
137
+ }
138
+ paint.color = shadow.color
139
+ paint.alpha = (((shadow.color ushr 24) and 0xff) * child.alpha).toInt()
140
+ val s = shadow.spread
141
+ val r = max(radius + s, 0f)
142
+ val left = -s + shadow.dx
143
+ val top = -s + shadow.dy
144
+ val right = w + s + shadow.dx
145
+ val bottom = h + s + shadow.dy
146
+ // CSS blur radius B is a Gaussian of sigma B / 2.
147
+ val sigma = shadow.blur / 2f
148
+ if (sigma <= 0f) {
149
+ paint.maskFilter = null
150
+ canvas.drawRoundRect(left, top, right, bottom, r, r, paint)
151
+ } else if (!drawSprite(canvas, sprite(r, sigma), left, top, right, bottom)) {
152
+ // Too small for nine slices: blurred directly.
153
+ paint.maskFilter = blurs.getOrPut(sigma) { BlurMaskFilter(skiaRadius(sigma), BlurMaskFilter.Blur.NORMAL) }
154
+ canvas.drawRoundRect(left, top, right, bottom, r, r, paint)
155
+ paint.maskFilter = null
156
+ }
157
+ canvas.restore()
158
+ }
159
+
160
+ /**
161
+ * A blurred rounded rectangle rendered once into an alpha bitmap, drawn as
162
+ * nine slices at any size — what browsers do with box shadows. Blurring per
163
+ * draw cost GPU time on every frame, and missed Skia's mask cache entirely
164
+ * when the shadow was replayed into a scaled layer (a glass's backdrop).
165
+ *
166
+ * In the bitmap's pixels: the shape sits `reach` (3 sigma) in from each
167
+ * side; a corner slice is `corner` = 2 reach + radius square, so the middle
168
+ * row and column, one pixel wide, lie on the shape's straight edges at
169
+ * least 3 sigma from its corners — the profile there is the true edge's.
170
+ */
171
+ private class Sprite(val bitmap: Bitmap, val scale: Float, val corner: Int, val reach: Int)
172
+
173
+ private val sprites = object : LinkedHashMap<String, Sprite>(16, 0.75f, true) {
174
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Sprite>?) = size > 48
175
+ }
176
+ private val spritePaint = Paint(Paint.ANTI_ALIAS_FLAG)
177
+ private val src = Rect()
178
+ private val dst = RectF()
179
+
180
+ private fun sprite(radius: Float, sigma: Float): Sprite {
181
+ // A blurred shape needs little resolution: a few pixels of sigma.
182
+ val scale = min(1f, max(0.25f, 4f / sigma))
183
+ val key = "${(radius * scale).roundToInt()}:${(sigma * scale * 10f).roundToInt()}:$scale"
184
+ sprites[key]?.let { return it }
185
+ val sigmaPx = sigma * scale
186
+ val reach = ceil(3f * sigmaPx).toInt()
187
+ val r = (radius * scale).roundToInt()
188
+ val corner = 2 * reach + r
189
+ val side = 2 * corner + 1
190
+ val bitmap = Bitmap.createBitmap(side, side, Bitmap.Config.ALPHA_8)
191
+ spritePaint.maskFilter = BlurMaskFilter(skiaRadius(sigmaPx), BlurMaskFilter.Blur.NORMAL)
192
+ Canvas(bitmap).drawRoundRect(
193
+ reach.toFloat(), reach.toFloat(), (side - reach).toFloat(), (side - reach).toFloat(),
194
+ r.toFloat(), r.toFloat(), spritePaint,
195
+ )
196
+ return Sprite(bitmap, scale, corner, reach).also { sprites[key] = it }
197
+ }
198
+
199
+ /** Nine slices of `sprite` around the shape [left, top, right, bottom]; false when it is too small. */
200
+ private fun drawSprite(canvas: Canvas, sprite: Sprite, left: Float, top: Float, right: Float, bottom: Float): Boolean {
201
+ val k = sprite.scale
202
+ val reach = sprite.reach / k
203
+ val corner = sprite.corner / k
204
+ val x0 = left - reach
205
+ val y0 = top - reach
206
+ val x3 = right + reach
207
+ val y3 = bottom + reach
208
+ if (x3 - x0 < 2 * corner || y3 - y0 < 2 * corner) return false
209
+ val x1 = x0 + corner
210
+ val x2 = x3 - corner
211
+ val y1 = y0 + corner
212
+ val y2 = y3 - corner
213
+ val c = sprite.corner
214
+ val side = sprite.bitmap.width
215
+ val xs = intArrayOf(0, c, c + 1, side)
216
+ val ys = intArrayOf(0, c, c + 1, side)
217
+ val dx = floatArrayOf(x0, x1, x2, x3)
218
+ val dy = floatArrayOf(y0, y1, y2, y3)
219
+ paint.isFilterBitmap = true
220
+ for (j in 0 until 3) {
221
+ for (i in 0 until 3) {
222
+ src.set(xs[i], ys[j], xs[i + 1], ys[j + 1])
223
+ dst.set(dx[i], dy[j], dx[i + 1], dy[j + 1])
224
+ canvas.drawBitmap(sprite.bitmap, src, dst, paint)
225
+ }
226
+ }
227
+ return true
228
+ }
229
+
230
+ /** Called by a glass before it draws its background. */
231
+ fun drawBackdrop(glass: OrbitBox, canvas: Canvas) {
232
+ if (Build.VERSION.SDK_INT < 31 || capturing || !canvas.isHardwareAccelerated) return
233
+ val parent = glass.parent as? ViewGroup ?: return
234
+ val w = glass.width
235
+ val h = glass.height
236
+ if (w <= 0 || h <= 0) return
237
+ val node = glass.backdropNode as? RenderNode ?: RenderNode("orbit-backdrop").also {
238
+ glass.backdropNode = it
239
+ it.setPivotX(0f)
240
+ it.setPivotY(0f)
241
+ it.setScaleX(1f / BACKDROP_SCALE)
242
+ it.setScaleY(1f / BACKDROP_SCALE)
243
+ }
244
+ // A blurred backdrop needs no resolution: it is recorded and blurred at a
245
+ // quarter of the size (a sixteenth of the pixels), then drawn scaled up.
246
+ val sw = ceil(w * BACKDROP_SCALE).toInt().coerceAtLeast(1)
247
+ val sh = ceil(h * BACKDROP_SCALE).toInt().coerceAtLeast(1)
248
+ node.setPosition(0, 0, sw, sh)
249
+ if (glass.appliedSigma != glass.backdropSigma) {
250
+ val r = skiaRadius(glass.backdropSigma * BACKDROP_SCALE)
251
+ node.setRenderEffect(RenderEffect.createBlurEffect(r, r, Shader.TileMode.CLAMP))
252
+ glass.appliedSigma = glass.backdropSigma
253
+ }
254
+ val recording = node.beginRecording(sw, sh)
255
+ capturing = true
256
+ try {
257
+ recording.scale(BACKDROP_SCALE, BACKDROP_SCALE)
258
+ recording.translate(-(glass.left + glass.translationX), -(glass.top + glass.translationY))
259
+ parent.background?.draw(recording)
260
+ for (i in 0 until parent.childCount) {
261
+ val sibling = parent.getChildAt(i)
262
+ if (sibling === glass) break
263
+ if (sibling.visibility != View.VISIBLE) continue
264
+ recording.save()
265
+ recording.translate(sibling.left + sibling.translationX, sibling.top + sibling.translationY)
266
+ // A scrolling sibling shows only its viewport; its content is offset by its scroll.
267
+ if (sibling is OrbitScroll || (sibling as? ViewGroup)?.clipChildren == true) {
268
+ recording.clipRect(0, 0, sibling.width, sibling.height)
269
+ }
270
+ recording.translate(-sibling.scrollX.toFloat(), -sibling.scrollY.toFloat())
271
+ sibling.draw(recording)
272
+ recording.restore()
273
+ }
274
+ } finally {
275
+ capturing = false
276
+ node.endRecording()
277
+ }
278
+ val radius = min(radii[glass] ?: 0f, min(w, h) / 2f)
279
+ canvas.save()
280
+ path.reset()
281
+ path.addRoundRect(0f, 0f, w.toFloat(), h.toFloat(), radius, radius, Path.Direction.CW)
282
+ canvas.clipPath(path)
283
+ canvas.drawRenderNode(node)
284
+ canvas.restore()
285
+ }
286
+ }