| 5 |
| #include "display_list.h" |
| 6 | #include "renderer.h" |
| 7 | #include "twidget/widget_host.h" |
| 8 | #include <algorithm> |
| 9 | #include <atomic> |
| 10 | #include <chrono> |
| 11 | #include <cmath> |
| 12 | #include <cstring> |
| 13 | #include <jni.h> |
| 14 | #include <map> |
| 15 | #include <mutex> |
| 16 | #include <optional> |
| 17 | #include <stdexcept> |
| 18 | #include <string_view> |
| 19 | #include <unordered_map> |
| 20 | #ifdef __ANDROID__ |
| 21 | #include <android/trace.h> |
| 22 | #endif |
| 23 |
| 24 | namespace { |
| 25 | // Debug: the conformance runner (WidgetConformanceRunner) reads each widget's `data-conformance` verdict. |
| 26 | std::atomic<bool> conformanceReports{false}; |
| 27 | // Debug (the stress kit's measure pass, packages/stress/CLIENTS.md): limits every new session takes instead of the |
| 28 | // defaults, as JSON {"policy","cpuQuotaMs","cpuQuotaWindowMs","mainThreadQuotaMs","maxTimers","memoryLimitBytes"}. |
| 29 | std::mutex limitsMutex; |
| 30 | std::string limitsOverride; |
| 31 | // Debug: the attack runner (WidgetAttackRunner) hears of every URL that could reach the network (signal 10). |
| 32 | std::atomic<bool> attackScan{false}; |
| 33 |
| 34 | // widget-sandbox's attack check (packages/desktop/harness/main.cpp, `twidget-run --attacks`) on the ops this |
| 35 | // renderer gets: anything but data: and #fragment URLs in them is a leak. A URL inside a data: payload is inert |
| 36 | // (an image may not fetch), and in CSS only the url() family and @import can fetch. |
| 37 | bool mentionsNetwork(std::string l) { |
| 38 | std::transform(l.begin(), l.end(), l.begin(), [](unsigned char c) { return char(std::tolower(c)); }); |
| 39 | return l.find("127.0.0.1") != std::string::npos || l.find("http://") != std::string::npos || |
| 40 | l.find("https://") != std::string::npos || l.find("ws://") != std::string::npos || |
| 41 | l.find("wss://") != std::string::npos || l.rfind("//", 0) == 0; |
| 42 | } |
| 43 |
| 44 | void scanCss(const std::string &where, const std::string &css, std::vector<std::string> &leaks) { |
| 45 | std::string l = css; |
| 46 | std::transform(l.begin(), l.end(), l.begin(), [](unsigned char c) { return char(std::tolower(c)); }); |
| 47 | if (l.find("@import") != std::string::npos) |
| 48 | leaks.push_back(where + ": @import survived: " + css.substr(0, 160)); |
| 49 | static const char *const fns[] = {"url(", "image-set(", "image(", "src(", "cross-fade("}; |
| 50 | for (const char *fn : fns) { |
| 51 | size_t len = std::strlen(fn); |
| 52 | for (size_t pos = l.find(fn); pos != std::string::npos; pos = l.find(fn, pos + len)) { |
| 53 | if (pos > 0 && (std::isalnum((unsigned char)l[pos - 1]) || l[pos - 1] == '-')) |
| 54 | continue; |
| 55 | size_t a = pos + len; |
| 56 | while (a < l.size() && (l[a] == ' ' || l[a] == '\t' || l[a] == '\n' || l[a] == '"' || l[a] == '\'')) |
| 57 | a++; |
| 58 | std::string arg = l.substr(a, 12); |
| 59 | if (arg.rfind("data:", 0) == 0 || arg.rfind("#", 0) == 0) |
| 60 | continue; |
| 61 | if (std::strcmp(fn, "image-set(") == 0 && (arg.rfind("url(", 0) == 0 || arg.rfind("image(", 0) == 0)) |
| 62 | continue; |
| 63 | leaks.push_back(where + ": " + css.substr(pos, 160)); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 |
| 68 | void scanOp(const twidget::Json &op, std::vector<std::string> &leaks) { |
| 69 | const std::string &kind = op["op"].asString(); |
| 70 | auto attr = [&](const std::string &where, const std::string &value) { |
| 71 | if (value.rfind("data:", 0) != 0 && mentionsNetwork(value)) |
| 72 | leaks.push_back(where + ": " + value.substr(0, 160)); |
| 73 | }; |
| 74 | if (kind == "el") { |
| 75 | for (const auto &pair : op["attrs"].arr()) { |
| 76 | const std::string &name = pair[size_t(0)].asString(); |
| 77 | if (name == "style") |
| 78 | scanCss("el.style", pair[size_t(1)].asString(), leaks); |
| 79 | else |
| 80 | attr("el." + name, pair[size_t(1)].asString()); |
| 81 | } |
| 82 | } else if (kind == "attr") { |
| 83 | if (op["name"].asString() == "style") |
| 84 | scanCss("attr style", op["value"].asString(), leaks); |
| 85 | else |
| 86 | attr("attr " + op["name"].asString(), op["value"].asString()); |
| 87 | } else if (kind == "style") { |
| 88 | scanCss("style " + op["name"].asString(), op["value"].asString(), leaks); |
| 89 | } else if (kind == "css") { |
| 90 | scanCss("css", op["text"].asString(), leaks); |
| 91 | } else if (kind == "canvas") { |
| 92 | for (const auto &cmd : op["cmds"].arr()) |
| 93 | for (const auto &a : cmd.arr()) |
| 94 | if (a.isString()) { |
| 95 | scanCss("canvas", a.asString(), leaks); |
| 96 | attr("canvas", a.asString()); |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | JavaVM *vm = nullptr; |
| 101 |
| 102 | // Systrace sections (API 23, the client's minimum). |
| 103 | struct TraceScope { |
| 104 | explicit TraceScope(const char *name) { |
| 105 | #ifdef __ANDROID__ |
| 106 | ATrace_beginSection(name); |
| 107 | #endif |
| 108 | } |
| 109 | ~TraceScope() { |
| 110 | #ifdef __ANDROID__ |
| 111 | ATrace_endSection(); |
| 112 | #endif |
| 113 | } |
| 114 | }; |
| 115 |
| 116 | struct ThreadEnv { |
| 117 | JNIEnv *env = nullptr; |
| 118 | bool attached = false; |
| 119 | ThreadEnv() { |
| 120 | if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) { |
| 121 | #ifdef __ANDROID__ |
| 122 | attached = vm->AttachCurrentThread(&env, nullptr) == JNI_OK; |
| 123 | #else |
| 124 | attached = vm->AttachCurrentThread(reinterpret_cast<void **>(&env), nullptr) == JNI_OK; |
| 125 | #endif |
| 126 | } |
| 127 | } |
| 128 | ~ThreadEnv() { |
| 129 | if (attached) |
| 130 | vm->DetachCurrentThread(); |
| 131 | } |
| 132 | }; |
| 133 | JNIEnv *env() { |
| 134 | thread_local ThreadEnv thread; |
| 135 | return thread.env; |
| 136 | } |
| 137 |
| 138 | std::string bytes(JNIEnv *e, jbyteArray value) { |
| 139 | if (!value) |
| 140 | return {}; |
| 141 | std::string result(e->GetArrayLength(value), '\0'); |
| 142 | e->GetByteArrayRegion(value, 0, result.size(), reinterpret_cast<jbyte *>(result.data())); |
| 143 | return result; |
| 144 | } |
| 145 | jbyteArray bytes(JNIEnv *e, const std::string &value) { |
| 146 | jbyteArray result = e->NewByteArray(value.size()); |
| 147 | if (result) |
| 148 | e->SetByteArrayRegion(result, 0, value.size(), reinterpret_cast<const jbyte *>(value.data())); |
| 149 | return result; |
| 150 | } |
| 151 | void check(JNIEnv *e) { |
| 152 | if (!e->ExceptionCheck()) |
| 153 | return; |
| 154 | e->ExceptionDescribe(); |
| 155 | e->ExceptionClear(); |
| 156 | throw std::runtime_error("Android renderer callback failed"); |
| 157 | } |
| 158 |
| 159 | // A canvas batch for WidgetCanvas#run as int words, floats by their bits, in place of twlite::to_json: JSON took most of |
| 160 | // a canvas batch on a weak phone. One op: its kind, its clips (but Reset and PutImage), then by kind, as written here. |
| 161 | void putFloat(std::vector<jint> &out, float value) { |
| 162 | jint bits; |
| 163 | std::memcpy(&bits, &value, sizeof(bits)); |
| 164 | out.push_back(bits); |
| 165 | } |
| 166 |
| 167 | jint argbOf(const twlite::Color &c) { |
| 168 | return jint((uint32_t(c.a) << 24) | (uint32_t(c.r) << 16) | (uint32_t(c.g) << 8) | c.b); |
| 169 | } |
| 170 |
| 171 | void putGeometry(std::vector<jint> &out, const twlite::Geometry &path) { |
| 172 | out.push_back(jint(path.ops.size())); |
| 173 | out.push_back(jint(path.points.size())); |
| 174 | for (auto op : path.ops) |
| 175 | out.push_back(jint(op)); |
| 176 | for (float point : path.points) |
| 177 | putFloat(out, point); |
| 178 | } |
| 179 |
| 180 | // Bytes, little-endian in each word, after their count. |
| 181 | void putBytes(std::vector<jint> &out, const uint8_t *bytes, size_t size) { |
| 182 | out.push_back(jint(size)); |
| 183 | size_t at = out.size(); |
| 184 | out.resize(at + (size + 3) / 4, 0); |
| 185 | if (size) |
| 186 | std::memcpy(out.data() + at, bytes, size); |
| 187 | } |
| 188 |
| 189 | void encodeCanvasOp(std::vector<jint> &out, const twlite::CanvasOp &op) { |
| 190 | using Op = twlite::CanvasOp; |
| 191 | out.push_back(jint(op.kind)); |
| 192 | if (op.kind == Op::Reset) |
| 193 | return; |
| 194 | if (op.kind == Op::PutImage) { |
| 195 | putFloat(out, op.dx); |
| 196 | putFloat(out, op.dy); |
| 197 | out.push_back(op.w); |
| 198 | out.push_back(op.h); |
| 199 | putBytes(out, op.rgba ? op.rgba->data() : nullptr, op.rgba ? op.rgba->size() : 0); |
| 200 | return; |
| 201 | } |
| 202 | out.push_back(op.clips ? jint(op.clips->size()) : 0); |
| 203 | if (op.clips) { |
| 204 | for (const auto &clip : *op.clips) { |
| 205 | putGeometry(out, clip.path); |
| 206 | out.push_back(clip.evenodd); |
| 207 | } |
| 208 | } |
| 209 | if (op.kind == Op::Fill || op.kind == Op::Stroke || op.kind == Op::Clear) |
| 210 | putGeometry(out, op.path); |
| 211 | if (op.kind == Op::Clear) |
| 212 | return; |
| 213 | out.push_back(op.evenodd); |
| 214 | for (float value : op.matrix) |
| 215 | putFloat(out, value); |
| 216 | putFloat(out, op.alpha); |
| 217 | out.push_back(jint(op.composite)); |
| 218 | out.push_back(op.has_shadow()); |
| 219 | if (op.has_shadow()) { |
| 220 | out.push_back(argbOf(op.shadow_color)); |
| 221 | putFloat(out, op.shadow_x); |
| 222 | putFloat(out, op.shadow_y); |
| 223 | putFloat(out, op.shadow_blur); |
| 224 | } |
| 225 | if (op.kind == Op::Fill || op.kind == Op::Stroke || op.kind == Op::Text) { |
| 226 | out.push_back(jint(op.paint.kind)); |
| 227 | if (op.paint.kind == twlite::CanvasPaint::Solid) { |
| 228 | out.push_back(argbOf(op.paint.color)); |
| 229 | } else { |
| 230 | for (float value : op.paint.args) |
| 231 | putFloat(out, value); |
| 232 | out.push_back(jint(op.paint.stops.size())); |
| 233 | for (const auto &stop : op.paint.stops) { |
| 234 | putFloat(out, stop.offset); |
| 235 | out.push_back(argbOf(stop.color)); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | if (op.kind == Op::Text) { |
| 240 | out.push_back(op.font); |
| 241 | putBytes(out, reinterpret_cast<const uint8_t *>(op.text.data()), op.text.size()); |
| 242 | for (float value : {op.x, op.y, op.scale_x, op.text_dx}) |
| 243 | putFloat(out, value); |
| 244 | out.push_back(op.stroke_text); |
| 245 | } |
| 246 | if (op.kind == Op::Stroke || (op.kind == Op::Text && op.stroke_text)) { |
| 247 | putFloat(out, op.line_width); |
| 248 | out.push_back(op.line_cap); |
| 249 | out.push_back(op.line_join); |
| 250 | putFloat(out, op.miter_limit); |
| 251 | out.push_back(jint(op.dashes.size())); |
| 252 | for (float dash : op.dashes) |
| 253 | putFloat(out, dash); |
| 254 | putFloat(out, op.dash_offset); |
| 255 | } |
| 256 | if (op.kind == Op::Image) { |
| 257 | out.push_back(op.canvas); |
| 258 | out.push_back(op.image); |
| 259 | for (float value : {op.sx, op.sy, op.sw, op.sh, op.dx, op.dy, op.dw, op.dh}) |
| 260 | putFloat(out, value); |
| 261 | out.push_back(op.smoothing); |
| 262 | } |
| 263 | } |
| 264 |
| 265 | // A display list for WidgetDisplayList (Java) as little-endian int words, floats by their bits, in place of |
| 266 | // twlite::to_json: the frame's JSON and its parse in Java cost more than the frame itself on a weak phone. Keep in step |
| 267 | // with WidgetDisplayList, which reads it as untrusted input. |
| 268 | // header: 'TWDL', version 1, command count, flags (1: a Backdrop), word offset of the string table |
| 269 | // command: kind | present << 8 (1 rect, 2 radii, 4 clip); [rect 4f] [radii 8f] [clip 4f]; then by kind: |
| 270 | // FillRect, FillEllipse: argb · StrokeRect, StrokeEllipse: argb, width · Text: argb, font, x, y, string |
| 271 | // Image: canvas (0/1), id · Linear, Radial, Conic: ax, ay, bx, by, stops · ClipPush: has path, [path] |
| 272 | // Path: has path, [path, svg] · GroupPush: matrix 6f, opacity, hidden · Shadow: argb, ax, ay, bx, by, inset |
| 273 | // FilterPush, Backdrop: filters · the pops: nothing |
| 274 | // stops: n, n × (offset, argb) · filters: n, n × (kind, amount, x, y, argb) |
| 275 | // path: op count, point count, ops a byte each (four to a word), points, evenodd |
| 276 | // svg: flags (1 fill, 2 stroke); fill: gradient kind, then argb (0) or 7f and stops (1 linear, 2 radial); |
| 277 | // stroke: argb, gradient kind [7f, stops], width, cap, join, miter, dash count, dashes, dash offset |
| 278 | // string table: count, then each string as its byte length and UTF-8 bytes, padded to a word |
| 279 | std::string encodeDisplayList(const twlite::DisplayList &list) { |
| 280 | using twlite::Cmd; |
| 281 | std::vector<jint> out; |
| 282 | out.reserve(list.size() * 10 + 8); |
| 283 | out.insert(out.end(), {jint(0x4C445754), 1, jint(list.size()), 0, 0}); |
| 284 | std::vector<const std::string *> strings; |
| 285 | std::unordered_map<std::string_view, jint> known; |
| 286 | bool backdrop = false; |
| 287 | auto stops = [&](const std::vector<twlite::Stop> &list) { |
| 288 | out.push_back(jint(list.size())); |
| 289 | for (const auto &stop : list) { |
| 290 | putFloat(out, stop.offset); |
| 291 | out.push_back(argbOf(stop.color)); |
| 292 | } |
| 293 | }; |
| 294 | auto geometry = [&](const twlite::Path &path) { |
| 295 | out.push_back(jint(path.ops.size())); |
| 296 | out.push_back(jint(path.points.size())); |
| 297 | size_t at = out.size(); |
| 298 | out.resize(at + (path.ops.size() + 3) / 4, 0); |
| 299 | auto *bytes = reinterpret_cast<uint8_t *>(out.data() + at); |
| 300 | for (size_t i = 0; i < path.ops.size(); i++) |
| 301 | bytes[i] = uint8_t(path.ops[i]); |
| 302 | for (float point : path.points) |
| 303 | putFloat(out, point); |
| 304 | out.push_back(path.evenodd); |
| 305 | }; |
| 306 | auto gradient = [&](int kind, const float *args, const std::vector<twlite::Stop> &list) { |
| 307 | out.push_back(kind); |
| 308 | for (int i = 0; i < 7; i++) |
| 309 | putFloat(out, args[i]); |
| 310 | stops(list); |
| 311 | }; |
| 312 | for (const auto &c : list) { |
| 313 | bool rect = c.kind != Cmd::ClipPop && c.kind != Cmd::GroupPop && c.kind != Cmd::FilterPop && |
| 314 | c.kind != Cmd::Text && c.kind != Cmd::Path; |
| 315 | bool radii = c.radii.any(); |
| 316 | out.push_back(jint(int(c.kind) | ((rect ? 1 : 0) | (radii ? 2 : 0) | (c.has_clip ? 4 : 0)) << 8)); |
| 317 | if (rect) |
| 318 | for (float v : {c.rect.x, c.rect.y, c.rect.w, c.rect.h}) |
| 319 | putFloat(out, v); |
| 320 | if (radii) |
| 321 | for (float v : {c.radii.tlx, c.radii.tly, c.radii.trx, c.radii.try_, c.radii.brx, c.radii.bry, c.radii.blx, |
| 322 | c.radii.bly}) |
| 323 | putFloat(out, v); |
| 324 | if (c.has_clip) |
| 325 | for (float v : {c.clip.x, c.clip.y, c.clip.w, c.clip.h}) |
| 326 | putFloat(out, v); |
| 327 | switch (c.kind) { |
| 328 | case Cmd::FillRect: |
| 329 | case Cmd::FillEllipse: |
| 330 | out.push_back(argbOf(c.color)); |
| 331 | break; |
| 332 | case Cmd::StrokeRect: |
| 333 | case Cmd::StrokeEllipse: |
| 334 | out.push_back(argbOf(c.color)); |
| 335 | putFloat(out, c.width); |
| 336 | break; |
| 337 | case Cmd::Text: { |
| 338 | out.push_back(argbOf(c.color)); |
| 339 | out.push_back(c.font); |
| 340 | putFloat(out, c.x); |
| 341 | putFloat(out, c.y); |
| 342 | auto found = known.find(c.text); |
| 343 | if (found == known.end()) { |
| 344 | found = known.emplace(std::string_view(c.text), jint(strings.size())).first; |
| 345 | strings.push_back(&c.text); |
| 346 | } |
| 347 | out.push_back(found->second); |
| 348 | break; |
| 349 | } |
| 350 | case Cmd::Image: |
| 351 | out.push_back(c.canvas ? 1 : 0); |
| 352 | out.push_back(c.canvas ? c.canvas : c.image); |
| 353 | break; |
| 354 | case Cmd::Linear: |
| 355 | case Cmd::Radial: |
| 356 | case Cmd::Conic: |
| 357 | for (float v : {c.ax, c.ay, c.bx, c.by}) |
| 358 | putFloat(out, v); |
| 359 | stops(c.stops); |
| 360 | break; |
| 361 | case Cmd::ClipPush: |
| 362 | out.push_back(c.path ? 1 : 0); |
| 363 | if (c.path) |
| 364 | geometry(*c.path); |
| 365 | break; |
| 366 | case Cmd::Path: { |
| 367 | out.push_back(c.path ? 1 : 0); |
| 368 | if (!c.path) |
| 369 | break; |
| 370 | const twlite::Path &p = *c.path; |
| 371 | geometry(p); |
| 372 | out.push_back((p.fill ? 1 : 0) | (p.stroke ? 2 : 0)); |
| 373 | if (p.fill) { |
| 374 | if (p.gradient != 0 && p.stops.size() >= 2) { |
| 375 | const float args[] = {p.x1, p.y1, p.x2, p.y2, p.r, p.fx, p.fy}; |
| 376 | gradient(p.gradient, args, p.stops); |
| 377 | } else { |
| 378 | out.push_back(0); |
| 379 | out.push_back(argbOf(p.fill_color)); |
| 380 | } |
| 381 | } |
| 382 | if (p.stroke) { |
| 383 | out.push_back(argbOf(p.stroke_color)); |
| 384 | if (p.stroke_gradient != 0 && p.stroke_stops.size() >= 2) |
| 385 | gradient(p.stroke_gradient, p.sg, p.stroke_stops); |
| 386 | else |
| 387 | out.push_back(0); |
| 388 | putFloat(out, p.stroke_width); |
| 389 | out.push_back(p.line_cap); |
| 390 | out.push_back(p.line_join); |
| 391 | putFloat(out, p.miter_limit); |
| 392 | out.push_back(jint(p.dashes.size())); |
| 393 | for (float dash : p.dashes) |
| 394 | putFloat(out, dash); |
| 395 | putFloat(out, p.dash_offset); |
| 396 | } |
| 397 | break; |
| 398 | } |
| 399 | case Cmd::GroupPush: |
| 400 | for (float v : c.matrix) |
| 401 | putFloat(out, v); |
| 402 | putFloat(out, c.opacity); |
| 403 | out.push_back(c.hidden); |
| 404 | break; |
| 405 | case Cmd::Shadow: |
| 406 | out.push_back(argbOf(c.color)); |
| 407 | for (float v : {c.ax, c.ay, c.bx, c.by}) |
| 408 | putFloat(out, v); |
| 409 | out.push_back(c.inset); |
| 410 | break; |
| 411 | case Cmd::FilterPush: |
| 412 | case Cmd::Backdrop: |
| 413 | backdrop |= c.kind == Cmd::Backdrop; |
| 414 | out.push_back(c.filter ? jint(c.filter->size()) : 0); |
| 415 | if (c.filter) { |
| 416 | for (const auto &f : *c.filter) { |
| 417 | out.push_back(jint(f.kind)); |
| 418 | putFloat(out, f.amount); |
| 419 | putFloat(out, f.x); |
| 420 | putFloat(out, f.y); |
| 421 | out.push_back(argbOf(f.color)); |
| 422 | } |
| 423 | } |
| 424 | break; |
| 425 | case Cmd::ClipPop: |
| 426 | case Cmd::GroupPop: |
| 427 | case Cmd::FilterPop: |
| 428 | break; |
| 429 | } |
| 430 | } |
| 431 | out[3] = backdrop ? 1 : 0; |
| 432 | out[4] = jint(out.size()); |
| 433 | out.push_back(jint(strings.size())); |
| 434 | for (const std::string *text : strings) |
| 435 | putBytes(out, reinterpret_cast<const uint8_t *>(text->data()), text->size()); |
| 436 | return std::string(reinterpret_cast<const char *>(out.data()), out.size() * sizeof(jint)); |
| 437 | } |
| 438 |
| 439 | class AndroidBackend final : public twlite::Backend { |
| 440 | public: |
| 441 | AndroidBackend(JNIEnv *e, jobject value) : object_(e->NewGlobalRef(value)) { |
| 442 | jclass type = e->GetObjectClass(value); |
| 443 | font_ = e->GetMethodID(type, "createFont", "([BFIZ[B)[F"); |
| 444 | delete_ = e->GetMethodID(type, "deleteFont", "(I)V"); |
| 445 | width_ = e->GetMethodID(type, "textWidth", "(I[B)F"); |
| 446 | image_ = e->GetMethodID(type, "loadImage", "(I[B)[F"); |
| 447 | record_ = e->GetMethodID(type, "record", "([B[BDIIFFII)V"); |
| 448 | signal_ = e->GetMethodID(type, "signal", "(I[B)V"); |
| 449 | intl_ = e->GetMethodID(type, "formatIntl", "([B)[B"); |
| 450 | canvas_run_ = e->GetMethodID(type, "canvasRun", "(III[I)V"); |
| 451 | canvas_read_ = e->GetMethodID(type, "canvasRead", "(IIIII)[B"); |
| 452 | canvas_release_ = e->GetMethodID(type, "canvasRelease", "(I)V"); |
| 453 | layer_ = e->GetMethodID(type, "recordLayer", "(II[B)V"); |
| 454 | text_ = e->GetMethodID(type, "selectableText", "([B)V"); |
| 455 | e->DeleteLocalRef(type); |
| 456 | check(e); |
| 457 | } |
| 458 | #ifdef WIDGET_SANDBOX_TESTING |
| 459 | jobject test_object(JNIEnv *e) { return e->NewLocalRef(object_); } |
| 460 | #endif |
| 461 | ~AndroidBackend() override { env()->DeleteGlobalRef(object_); } |
| 462 | int create_font(const std::string &families, float size, int weight, bool italic, |
| 463 | const std::string &features, twlite::FontMetrics &out) override { |
| 464 | auto *e = env(); |
| 465 | auto text = bytes(e, families); |
| 466 | // OpenType features as `tag=value` pairs (`tnum=1,zero=1`), empty for the font's defaults. |
| 467 | auto settings = bytes(e, features); |
| 468 | auto values = static_cast<jfloatArray>( |
| 469 | e->CallObjectMethod(object_, font_, text, size, weight, jboolean(italic), settings)); |
| 470 | e->DeleteLocalRef(text); |
| 471 | e->DeleteLocalRef(settings); |
| 472 | check(e); |
| 473 | if (!values) |
| 474 | return 0; |
| 475 | jfloat data[6] = {}; |
| 476 | e->GetFloatArrayRegion(values, 0, 6, data); |
| 477 | e->DeleteLocalRef(values); |
| 478 | out = {data[1], data[2], data[3], data[4], data[5]}; |
| 479 | return int(data[0]); |
| 480 | } |
| 481 | void delete_font(int id) override { |
| 482 | auto *e = env(); |
| 483 | e->CallVoidMethod(object_, delete_, id); |
| 484 | // Called from document destructors: never let an exception escape. |
| 485 | if (e->ExceptionCheck()) { |
| 486 | e->ExceptionDescribe(); |
| 487 | e->ExceptionClear(); |
| 488 | } |
| 489 | } |
| 490 | float text_width(int id, const std::string &value) override { |
| 491 | auto *e = env(); |
| 492 | auto text = bytes(e, value); |
| 493 | float result = e->CallFloatMethod(object_, width_, id, text); |
| 494 | e->DeleteLocalRef(text); |
| 495 | check(e); |
| 496 | return result; |
| 497 | } |
| 498 | bool load_image(int id, const std::string &url, float &w, float &h) override { |
| 499 | // The backend loads data: URLs only; with the validator in front no other may come here. |
| 500 | if (attackScan && url.rfind("data:", 0) != 0) |
| 501 | signal(10, "renderer asked for " + url.substr(0, 160)); |
| 502 | auto *e = env(); |
| 503 | auto text = bytes(e, url); |
| 504 | auto values = static_cast<jfloatArray>(e->CallObjectMethod(object_, image_, id, text)); |
| 505 | e->DeleteLocalRef(text); |
| 506 | check(e); |
| 507 | if (!values) |
| 508 | return false; |
| 509 | jfloat data[2] = {}; |
| 510 | e->GetFloatArrayRegion(values, 0, 2, data); |
| 511 | e->DeleteLocalRef(values); |
| 512 | w = data[0]; |
| 513 | h = data[1]; |
| 514 | return w > 0 && h > 0; |
| 515 | } |
| 516 | std::string intl(const std::string &request) { |
| 517 | auto *e = env(); |
| 518 | auto text = bytes(e, request); |
| 519 | auto result = static_cast<jbyteArray>(e->CallObjectMethod(object_, intl_, text)); |
| 520 | e->DeleteLocalRef(text); |
| 521 | check(e); |
| 522 | auto value = bytes(e, result); |
| 523 | if (result) |
| 524 | e->DeleteLocalRef(result); |
| 525 | return value; |
| 526 | } |
| 527 | void signal(int kind, const std::string &value = {}) { |
| 528 | auto *e = env(); |
| 529 | auto text = bytes(e, value); |
| 530 | e->CallVoidMethod(object_, signal_, kind, text); |
| 531 | e->DeleteLocalRef(text); |
| 532 | check(e); |
| 533 | } |
| 534 | void canvas_run(int id, int w, int h, const std::vector<twlite::CanvasOp> &ops) override { |
| 535 | auto *e = env(); |
| 536 | canvasWords_.clear(); |
| 537 | for (const auto &op : ops) |
| 538 | encodeCanvasOp(canvasWords_, op); |
| 539 | auto data = e->NewIntArray(jsize(canvasWords_.size())); |
| 540 | if (!data) { |
| 541 | check(e); |
| 542 | return; |
| 543 | } |
| 544 | e->SetIntArrayRegion(data, 0, jsize(canvasWords_.size()), canvasWords_.data()); |
| 545 | e->CallVoidMethod(object_, canvas_run_, id, w, h, data); |
| 546 | e->DeleteLocalRef(data); |
| 547 | check(e); |
| 548 | } |
| 549 | bool canvas_read(int id, int x, int y, int w, int h, std::vector<uint8_t> &rgba) override { |
| 550 | auto *e = env(); |
| 551 | auto data = static_cast<jbyteArray>(e->CallObjectMethod(object_, canvas_read_, id, x, y, w, h)); |
| 552 | check(e); |
| 553 | if (!data) |
| 554 | return false; |
| 555 | size_t size = e->GetArrayLength(data); |
| 556 | bool ok = w > 0 && h > 0 && size == size_t(w) * size_t(h) * 4; |
| 557 | if (ok) { |
| 558 | rgba.resize(size); |
| 559 | e->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte *>(rgba.data())); |
| 560 | } |
| 561 | e->DeleteLocalRef(data); |
| 562 | return ok; |
| 563 | } |
| 564 | void canvas_release(int id) override { |
| 565 | auto *e = env(); |
| 566 | e->CallVoidMethod(object_, canvas_release_, id); |
| 567 | // Called while the document is torn down: never let an exception escape. |
| 568 | if (e->ExceptionCheck()) { |
| 569 | e->ExceptionDescribe(); |
| 570 | e->ExceptionClear(); |
| 571 | } |
| 572 | } |
| 573 | // The text the widget made selectable (Renderer::selectable_text_json), before the frame it belongs to. |
| 574 | void selectable_text(const std::string &runs) { |
| 575 | auto *e = env(); |
| 576 | auto text = bytes(e, runs); |
| 577 | e->CallVoidMethod(object_, text_, text); |
| 578 | e->DeleteLocalRef(text); |
| 579 | check(e); |
| 580 | } |
| 581 | // A layer's content, recorded by the backend before the frame that names it. |
| 582 | void layer(int index, int version, const std::string &list) { |
| 583 | auto *e = env(); |
| 584 | auto text = bytes(e, list); |
| 585 | e->CallVoidMethod(object_, layer_, index, version, text); |
| 586 | e->DeleteLocalRef(text); |
| 587 | check(e); |
| 588 | } |
| 589 | void record(const std::string &list, const std::string &composition, double clock, int w, int h, float dpr, |
| 590 | const twlite::BuildStats &stats) { |
| 591 | auto *e = env(); |
| 592 | auto text = bytes(e, list); |
| 593 | auto layers = bytes(e, composition); |
| 594 | e->CallVoidMethod(object_, record_, text, layers, clock, w, h, dpr, float(stats.parse_ms), stats.passes, |
| 595 | stats.builds); |
| 596 | e->DeleteLocalRef(text); |
| 597 | e->DeleteLocalRef(layers); |
| 598 | check(e); |
| 599 | } |
| 600 |
| 601 | private: |
| 602 | jobject object_; |
| 603 | std::vector<jint> canvasWords_; |
| 604 | jmethodID font_, delete_, width_, image_, record_, signal_, intl_, canvas_run_, canvas_read_, canvas_release_, text_, |
| 605 | layer_; |
| 606 | }; |
| 607 |
| 608 | // Android ICU through Java; what it cannot answer (API < 24, ListFormatter < 26) the engine's own |
| 609 | // BasicIntl formats, English-style, rather than leaving the widget without a value. |
| 610 | class AndroidIntl final : public twidget::IntlProvider { |
| 611 | public: |
| 612 | explicit AndroidIntl(std::shared_ptr<AndroidBackend> backend) : backend_(std::move(backend)) {} |
| 613 | std::string format(const twidget::Json &request) override { |
| 614 | std::string answer; |
| 615 | try { |
| 616 | answer = backend_->intl(request.dump()); |
| 617 | } catch (...) { |
| 618 | } |
| 619 | return answer.empty() ? basic_.format(request) : answer; |
| 620 | } |
| 621 |
| 622 | private: |
| 623 | std::shared_ptr<AndroidBackend> backend_; |
| 624 | twidget::BasicIntl basic_; |
| 625 | }; |
| 626 |
| 627 | class AndroidRenderer final : public twidget::Renderer { |
| 628 | public: |
| 629 | AndroidRenderer(std::shared_ptr<AndroidBackend> backend, const std::string &theme, float width, float dpr) |
| 630 | : backend_(std::move(backend)), document_(width, dpr, theme == "dark", *backend_) { |
| 631 | // Transform and opacity animations become RenderNode layers the UI thread plays without native work. |
| 632 | document_.set_compositing(true); |
| 633 | } |
| 634 | void load() override { |
| 635 | guard([&] { |
| 636 | if (onMessage) |
| 637 | onMessage("{\"type\":\"ready\"}"); |
| 638 | dirty(); |
| 639 | }); |
| 640 | } |
| 641 | void send(const std::string &json) override { |
| 642 | guard([&] { |
| 643 | auto message = twidget::Json::parse(json); |
| 644 | if (!message) |
| 645 | return; |
| 646 | if ((*message)["type"].asString() == "requestFrame") { |
| 647 | backend_->signal(1); |
| 648 | return; |
| 649 | } |
| 650 | if ((*message)["type"].asString() == "frozen") |
| 651 | frozen_ = true; |
| 652 | if (conformanceReports) |
| 653 | reportConformance(*message); |
| 654 | TraceScope trace("WidgetSandbox:ReceiveLayout"); |
| 655 | double started = nowMs(); |
| 656 | if (frameSentAt_ > 0 && !(*message)["ops"].arr().empty()) { |
| 657 | opsLatencyMs_ += started - frameSentAt_; |
| 658 | opsLatencies_++; |
| 659 | frameSentAt_ = 0; |
| 660 | } |
| 661 | dispatch(document_.receive(*message)); |
| 662 | receiveMs_ += nowMs() - started; |
| 663 | dirty(); |
| 664 | }); |
| 665 | } |
| 666 | // The conformance set's widgets publish their verdict in the root's `data-conformance` attribute |
| 667 | // (packages/conformance/CLIENTS.md): every new value goes to the backend as signal 9. |
| 668 | // The stress kit's widgets publish `data-stress` the same way (signal 16), and its runner counts the validated ops |
| 669 | // of every batch (signal 17). |
| 670 | void reportConformance(const twidget::Json &message) { |
| 671 | const auto &ops = message["ops"].arr(); |
| 672 | if (!ops.empty()) |
| 673 | backend_->signal(17, std::to_string(ops.size())); |
| 674 | for (const auto &op : ops) { |
| 675 | for (const char *name : {"data-conformance", "data-stress"}) { |
| 676 | const twidget::Json *value = nullptr; |
| 677 | if (op["name"].asString() == name) |
| 678 | value = op.find("value"); |
| 679 | else if (const auto *attrs = op.find("attrs")) |
| 680 | for (const auto &kv : attrs->arr()) |
| 681 | if (kv[size_t(0)].asString() == name) |
| 682 | value = &kv[size_t(1)]; |
| 683 | if (value && value->isString()) |
| 684 | backend_->signal(name[5] == 'c' ? 9 : 16, value->asString()); |
| 685 | } |
| 686 | } |
| 687 | } |
| 688 | void setTheme(const std::string &theme) override { |
| 689 | guard([&] { |
| 690 | std::vector<twidget::Json> out; |
| 691 | document_.set_theme(theme == "dark", out); |
| 692 | dispatch(out); |
| 693 | dirty(); |
| 694 | }); |
| 695 | } |
| 696 | void setWidth(double width) override { |
| 697 | guard([&] { |
| 698 | std::vector<twidget::Json> out; |
| 699 | TraceScope trace("WidgetSandbox:ResizeLayout"); |
| 700 | document_.set_width(width, out); |
| 701 | dispatch(out); |
| 702 | dirty(); |
| 703 | }); |
| 704 | } |
| 705 | void destroy() override { destroyed_ = true; } |
| 706 | void repaint() { |
| 707 | guard([&] { |
| 708 | // The UI lost its display lists: layers are recorded again too. |
| 709 | repaintNeeded_ = true; |
| 710 | layerVersions_.clear(); |
| 711 | backend_->signal(2); |
| 712 | }); |
| 713 | } |
| 714 | // A mouse sends no touch events; `modifiers` bit0 alt, bit1 ctrl, bit2 meta, bit3 shift; `button` 2 the secondary. |
| 715 | void touch(int action, float x, float y, int pointer, bool primary, bool mouse, int modifiers, int button) { |
| 716 | guard([&] { |
| 717 | // TwidgetCore keeps the finger rule itself (widget-sandbox v0.3.0, twidget 710bb77): a finger's pointerdown |
| 718 | // and mousedown are untrusted, a mouse keeps its press. |
| 719 | dispatch(document_.touch(action, x, y, pointer, primary, mouse, modifiers, button)); |
| 720 | // The primary press ended: the host's haptic gate counts its 5 s after a touch from here (widget-sandbox |
| 721 | // v0.2.2), as the framework's renderer core reports it; TwidgetCore sends only the press's start (`gesture`). |
| 722 | if (primary && (action == 2 || action == 3) && onMessage) |
| 723 | onMessage("{\"type\":\"release\"}"); |
| 724 | if (mouse) |
| 725 | cursor(); |
| 726 | dirty(); |
| 727 | }); |
| 728 | } |
| 729 | // A mouse over the widget with no button down (0) or leaving it (1): :hover and the over/out events. |
| 730 | void hover(int action, float x, float y, int modifiers) { |
| 731 | guard([&] { |
| 732 | dispatch(document_.hover(action, x, y, modifiers)); |
| 733 | cursor(); |
| 734 | dirty(); |
| 735 | }); |
| 736 | } |
| 737 | void tick(float ms, bool frame, bool animate, bool paint) { |
| 738 | guard([&] { |
| 739 | ticks_++; |
| 740 | if (frame && !frozen_ && onMessage) { |
| 741 | frameSentAt_ = nowMs(); |
| 742 | framesSent_++; |
| 743 | onMessage(twidget::Json::object().set("type", "frame").set("time", double(ms)).dump()); |
| 744 | } |
| 745 | if (animate) { |
| 746 | TraceScope trace("WidgetSandbox:Animate"); |
| 747 | double started = nowMs(); |
| 748 | dispatch(document_.tick()); |
| 749 | animateMs_ += nowMs() - started; |
| 750 | dirty(); |
| 751 | } |
| 752 | if (!paint || (!document_.dirty() && !repaintNeeded_)) |
| 753 | return; |
| 754 | // One frame is recorded at a time: while the recorder works, this one waits (it asks for the tick that |
| 755 | // paints it when it is done). The host thread meanwhile receives the widget's next ops. |
| 756 | if (recording_) { |
| 757 | paintWaiting_ = true; |
| 758 | return; |
| 759 | } |
| 760 | TraceScope trace("WidgetSandbox:Paint"); |
| 761 | double paintStarted = nowMs(); |
| 762 | auto job = std::make_shared<RecordJob>(); |
| 763 | job->list = document_.paint(); |
| 764 | job->paintMs = nowMs() - paintStarted; |
| 765 | // Layer contents go first; the frame that names them follows. Unchanged contents are reused, so only the |
| 766 | // changed ones are copied for the recorder (a layer's content is a whole display list). Every field of |
| 767 | // twlite::Layer but `content` is copied below: keep it in step with compositor.h. |
| 768 | const twlite::Composition &composition = document_.composition(); |
| 769 | job->composition.version = composition.version; |
| 770 | job->composition.layers.resize(composition.layers.size()); |
| 771 | std::unordered_map<int64_t, uint64_t> versions; |
| 772 | for (size_t i = 0; i < composition.layers.size(); i++) { |
| 773 | const auto &layer = composition.layers[i]; |
| 774 | auto © = job->composition.layers[i]; |
| 775 | copy.id = layer.id; |
| 776 | copy.bounds = layer.bounds; |
| 777 | copy.content_version = layer.content_version; |
| 778 | copy.raster_scale = layer.raster_scale; |
| 779 | copy.has_clip = layer.has_clip; |
| 780 | copy.clip = layer.clip; |
| 781 | copy.clip_radii = layer.clip_radii; |
| 782 | copy.track_version = layer.track_version; |
| 783 | copy.track = layer.track; |
| 784 | copy.parent = layer.parent; |
| 785 | versions[layer.id] = layer.content_version; |
| 786 | auto known = layerVersions_.find(layer.id); |
| 787 | if (known == layerVersions_.end() || known->second != layer.content_version) { |
| 788 | copy.content = layer.content; |
| 789 | job->layers.push_back(int(i)); |
| 790 | } |
| 791 | } |
| 792 | layerVersions_ = std::move(versions); |
| 793 | // The selectable text changes only with a layout; it goes out when it differs. |
| 794 | if (document_.layouts() != textLayouts_) { |
| 795 | textLayouts_ = document_.layouts(); |
| 796 | std::string text = document_.selectable_text_json(); |
| 797 | if (text != lastText_) { |
| 798 | lastText_ = text; |
| 799 | job->text = std::move(text); |
| 800 | job->hasText = true; |
| 801 | } |
| 802 | } |
| 803 | job->clock = twlite::Renderer::clock(); |
| 804 | job->width = document_.px_width(); |
| 805 | job->height = document_.px_height(); |
| 806 | job->dpr = document_.dpr(); |
| 807 | job->stats = document_.stats(); |
| 808 | if (conformanceReports) { |
| 809 | job->work = twidget::Json::object() |
| 810 | .set("receive", receiveMs_) |
| 811 | .set("animate", animateMs_) |
| 812 | .set("paint", job->paintMs) |
| 813 | .set("ticks", double(ticks_)) |
| 814 | .set("framesSent", double(framesSent_)) |
| 815 | .set("opsLatency", opsLatencies_ ? opsLatencyMs_ / opsLatencies_ : -1.0); |
| 816 | } |
| 817 | receiveMs_ = animateMs_ = opsLatencyMs_ = 0; |
| 818 | ticks_ = framesSent_ = opsLatencies_ = 0; |
| 819 | recording_ = true; |
| 820 | recorder_.async([this, job] { record(*job); }); |
| 821 | repaintNeeded_ = false; |
| 822 | }); |
| 823 | try { |
| 824 | backend_->signal(6); |
| 825 | } catch (...) { |
| 826 | } |
| 827 | } |
| 828 |
| 829 | private: |
| 830 | // A painted frame on its way to Java (WidgetSandboxBackend#record): the list, the layers it names and their |
| 831 | // contents that changed, the selectable text when it changed. |
| 832 | struct RecordJob { |
| 833 | twlite::DisplayList list; |
| 834 | twlite::Composition composition; |
| 835 | std::vector<int> layers; |
| 836 | std::string text; |
| 837 | bool hasText = false; |
| 838 | double clock = 0, paintMs = 0; |
| 839 | int width = 0, height = 0; |
| 840 | float dpr = 1; |
| 841 | twlite::BuildStats stats; |
| 842 | twidget::Json work; |
| 843 | }; |
| 844 | // The recorder thread: serialises the frame and records it into a RenderNode in Java, so the host thread is |
| 845 | // free for the widget's next ops meanwhile. |
| 846 | void record(RecordJob &job) { |
| 847 | if (!destroyed_) { |
| 848 | try { |
| 849 | TraceScope trace("WidgetSandbox:Record"); |
| 850 | double serializeMs = 0; |
| 851 | for (int i : job.layers) { |
| 852 | const auto &layer = job.composition.layers[size_t(i)]; |
| 853 | double started = nowMs(); |
| 854 | std::string content = encodeDisplayList(layer.content); |
| 855 | serializeMs += nowMs() - started; |
| 856 | backend_->layer(i, int(layer.content_version), content); |
| 857 | } |
| 858 | if (job.hasText) |
| 859 | backend_->selectable_text(job.text); |
| 860 | double started = nowMs(); |
| 861 | std::string listBytes = encodeDisplayList(job.list), compositionJson = twlite::to_json(job.composition); |
| 862 | serializeMs += nowMs() - started; |
| 863 | if (job.work.isObject()) |
| 864 | backend_->signal(18, job.work.set("serialize", serializeMs).dump()); |
| 865 | backend_->record(listBytes, compositionJson, job.clock, job.width, job.height, job.dpr, job.stats); |
| 866 | } catch (const std::exception &error) { |
| 867 | if (onDiag) |
| 868 | onDiag("android-renderer", error.what()); |
| 869 | } |
| 870 | } |
| 871 | recording_ = false; |
| 872 | // A frame painted while this one was recording waited for it: ask for the tick that paints it. |
| 873 | if (paintWaiting_.exchange(false) && !destroyed_) { |
| 874 | try { |
| 875 | backend_->signal(2); |
| 876 | } catch (...) { |
| 877 | } |
| 878 | } |
| 879 | } |
| 880 |
| 881 | template <class F> void guard(F body) { |
| 882 | if (destroyed_) |
| 883 | return; |
| 884 | try { |
| 885 | body(); |
| 886 | } catch (const std::exception &error) { |
| 887 | if (onDiag) |
| 888 | onDiag("android-renderer", error.what()); |
| 889 | } |
| 890 | } |
| 891 | void dirty() { |
| 892 | if (document_.dirty()) |
| 893 | backend_->signal(2); |
| 894 | schedule(); |
| 895 | } |
| 896 | // Tells the View when the next tick is due: every frame, after a delay, or never. |
| 897 | void schedule() { |
| 898 | double delay = -1; |
| 899 | if (document_.wants_tick()) |
| 900 | delay = 0; |
| 901 | else { |
| 902 | double next = document_.next_tick_in(); |
| 903 | if (std::isfinite(next)) |
| 904 | delay = std::max(1.0, next * 1000); |
| 905 | } |
| 906 | if (delay == scheduled_ && delay != 0) |
| 907 | return; |
| 908 | if (delay == 0 && scheduled_ == 0) |
| 909 | return; |
| 910 | scheduled_ = delay; |
| 911 | backend_->signal(7, std::to_string(delay)); |
| 912 | } |
| 913 | // The CSS cursor where the mouse is, to the View when it changes (signal 11). |
| 914 | void cursor() { |
| 915 | auto now = document_.cursor(); |
| 916 | if (now == cursor_) |
| 917 | return; |
| 918 | cursor_ = now; |
| 919 | backend_->signal(11, now); |
| 920 | } |
| 921 | void dispatch(const std::vector<twidget::Json> &output) { |
| 922 | for (const auto &message : output) { |
| 923 | auto kind = message["type"].asString(); |
| 924 | if (kind == "violation" && onDiag) |
| 925 | onDiag("renderer-violation", message["detail"].asString()); |
| 926 | if (!onMessage) |
| 927 | continue; |
| 928 | onMessage(message.dump()); |
| 929 | } |
| 930 | } |
| 931 | std::shared_ptr<AndroidBackend> backend_; |
| 932 | twlite::Renderer document_; |
| 933 | std::unordered_map<int64_t, uint64_t> layerVersions_; |
| 934 | uint64_t textLayouts_ = ~0ull; |
| 935 | std::string lastText_ = "[]"; |
| 936 | std::string cursor_ = "auto"; |
| 937 | double scheduled_ = -1; |
| 938 | // The native work since the last recorded frame, ms (the stress runner's breakdown). |
| 939 | double receiveMs_ = 0, animateMs_ = 0; |
| 940 | // The frame pipeline since the last recorded frame: ticks, rAF frames sent to the widget, and how long the widget |
| 941 | // took from a frame to the ops it answered with. |
| 942 | double frameSentAt_ = 0, opsLatencyMs_ = 0; |
| 943 | int ticks_ = 0, framesSent_ = 0, opsLatencies_ = 0; |
| 944 | static double nowMs() { |
| 945 | return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); |
| 946 | } |
| 947 | std::atomic<bool> destroyed_{false}; |
| 948 | bool frozen_ = false, repaintNeeded_ = false; |
| 949 | std::atomic<bool> recording_{false}, paintWaiting_{false}; |
| 950 | // Last, so it stops (and finishes its job) before anything it uses goes. |
| 951 | twidget::JSThread recorder_{"widget-record"}; |
| 952 | }; |
| 953 |
| 954 | // {"colorScheme","params":{key:"#rrggbb"},"button":{...},"text":{...}} from WidgetSandboxTheme (docs/sdk-v1.md §2.3, §2.4). |
| 955 | twidget::WidgetTheme parseTheme(const std::string &json) { |
| 956 | twidget::WidgetTheme theme; |
| 957 | auto value = twidget::Json::parse(json); |
| 958 | if (!value) |
| 959 | return theme; |
| 960 | theme.colorScheme = (*value)["colorScheme"].asString() == "dark" ? "dark" : "light"; |
| 961 | for (const auto &[key, color] : (*value)["params"].obj()) |
| 962 | if (color.isString()) |
| 963 | theme.params[key] = color.asString(); |
| 964 | const auto &button = (*value)["button"]; |
| 965 | auto text = [&](const char *key) -> std::optional<std::string> { |
| 966 | const auto &v = button[key]; |
| 967 | return v.isString() ? std::optional<std::string>(v.asString()) : std::nullopt; |
| 968 | }; |
| 969 | auto number = [&](const char *key) -> std::optional<double> { |
| 970 | const auto &v = button[key]; |
| 971 | return v.isNumber() ? std::optional<double>(v.asNumber()) : std::nullopt; |
| 972 | }; |
| 973 | theme.button.bg = text("bg"); |
| 974 | theme.button.text = text("text"); |
| 975 | theme.button.radius = text("radius"); |
| 976 | theme.button.font = text("font"); |
| 977 | theme.button.padding = text("padding"); |
| 978 | theme.button.height = text("height"); |
| 979 | theme.button.pressedOpacity = number("pressedOpacity"); |
| 980 | theme.button.disabledOpacity = number("disabledOpacity"); |
| 981 | const auto &text_tokens = (*value)["text"]; |
| 982 | if (text_tokens["fontSize"].isNumber()) |
| 983 | theme.text.fontSize = text_tokens["fontSize"].asNumber(); |
| 984 | if (text_tokens["lineHeight"].isNumber()) |
| 985 | theme.text.lineHeight = text_tokens["lineHeight"].asNumber(); |
| 986 | if (text_tokens["padding"].isString()) |
| 987 | theme.text.padding = text_tokens["padding"].asString(); |
| 988 | return theme; |
| 989 | } |
| 990 | // The widget's state and where it is (docs/sdk-v1.md §5.11), as WidgetMedia builds it: |
| 991 | // {"data":{"chatData","publicData"},"context":{"isCopy","canQuery","backgroundQuery","chatType","viewer":{"id", |
| 992 | // "firstName","lastName","username","isPremium"},"preview","wallet"}}; absent or null fields are none. |
| 993 | twidget::WidgetData parseData(const twidget::Json &value) { |
| 994 | twidget::WidgetData data; |
| 995 | if (value["chatData"].isString()) |
| 996 | data.chatData = value["chatData"].asString(); |
| 997 | if (value["publicData"].isString()) |
| 998 | data.publicData = value["publicData"].asString(); |
| 999 | return data; |
| 1000 | } |
| 1001 | twidget::WidgetContext parseContext(const twidget::Json &value) { |
| 1002 | twidget::WidgetContext context; |
| 1003 | context.isCopy = value["isCopy"].asBool(); |
| 1004 | context.canQuery = value["canQuery"].asBool(); |
| 1005 | context.backgroundQuery = value["backgroundQuery"].asBool(); |
| 1006 | context.preview = value["preview"].asBool(); |
| 1007 | // Gram Wallet for this user (docs/sdk-v1.md §5.13): the widget gets TelegramWidget.wallet where it may ask the bot. |
| 1008 | context.wallet = value["wallet"].asBool(); |
| 1009 | if (value["chatType"].isString()) |
| 1010 | context.chatType = value["chatType"].asString(); |
| 1011 | const auto &viewer = value["viewer"]; |
| 1012 | if (viewer["id"].isNumber()) { |
| 1013 | twidget::WidgetViewer v; |
| 1014 | v.id = int64_t(viewer["id"].asNumber()); |
| 1015 | if (viewer["firstName"].isString()) |
| 1016 | v.firstName = viewer["firstName"].asString(); |
| 1017 | if (viewer["lastName"].isString()) |
| 1018 | v.lastName = viewer["lastName"].asString(); |
| 1019 | if (viewer["username"].isString()) |
| 1020 | v.username = viewer["username"].asString(); |
| 1021 | v.isPremium = viewer["isPremium"].asBool(); |
| 1022 | context.viewer = v; |
| 1023 | } |
| 1024 | return context; |
| 1025 | } |
| 1026 | // {"top","right","bottom","left","cornerLeft","cornerRight"} in CSS px (docs/sdk-v1.md §2.17); a missing one is 0. |
| 1027 | twidget::WidgetContentSafeArea parseSafeArea(const twidget::Json &value) { |
| 1028 | twidget::WidgetContentSafeArea area; |
| 1029 | auto get = [&](const char *name) { return value[name].isNumber() ? value[name].asNumber() : 0.0; }; |
| 1030 | area.top = get("top"); |
| 1031 | area.right = get("right"); |
| 1032 | area.bottom = get("bottom"); |
| 1033 | area.left = get("left"); |
| 1034 | area.cornerLeft = get("cornerLeft"); |
| 1035 | area.cornerRight = get("cornerRight"); |
| 1036 | return area; |
| 1037 | } |
| 1038 | // {"local":{k:v},"session":{k:v}} as WidgetSandboxStorage keeps it. |
| 1039 | twidget::WidgetStorage parseStorage(const std::string &json) { |
| 1040 | twidget::WidgetStorage storage; |
| 1041 | auto value = twidget::Json::parse(json); |
| 1042 | if (!value) |
| 1043 | return storage; |
| 1044 | for (const auto &[key, v] : (*value)["local"].obj()) |
| 1045 | storage.local[key] = v.asString(); |
| 1046 | for (const auto &[key, v] : (*value)["session"].obj()) |
| 1047 | storage.session[key] = v.asString(); |
| 1048 | return storage; |
| 1049 | } |
| 1050 |
| 1051 | struct Session { |
| 1052 | // Owner commands serialize here. Waiting for the host thread never blocks UI. |
| 1053 | twidget::JSThread control{"widget-control"}; |
| 1054 | std::shared_ptr<AndroidBackend> backend; |
| 1055 | std::unique_ptr<twidget::WidgetHost> host; |
| 1056 | std::atomic<bool> closing{false}; |
| 1057 | // The widget's requests and wallet calls the client is answering (WidgetSandboxNative#answerRequest), by id. |
| 1058 | std::mutex requestsMutex; |
| 1059 | std::unordered_map<int64_t, std::function<void(const twidget::WidgetRequestOutcome &)>> requests; |
| 1060 | int64_t nextRequest = 1; |
| 1061 | void shutdown() { |
| 1062 | if (closing.exchange(true)) |
| 1063 | return; |
| 1064 | control.join(); |
| 1065 | host.reset(); // upstream destructor joins engine/validator/host threads |
| 1066 | backend.reset(); |
| 1067 | } |
| 1068 | ~Session() { shutdown(); } |
| 1069 | template <class F> void input(F body) { |
| 1070 | if (closing) |
| 1071 | return; |
| 1072 | control.async([this, body] { |
| 1073 | if (!host || closing) |
| 1074 | return; |
| 1075 | host->onHostThread([&] { body(static_cast<AndroidRenderer &>(host->renderer())); }); |
| 1076 | }); |
| 1077 | } |
| 1078 | }; |
| 1079 | std::mutex registryMutex; |
| 1080 | std::unordered_map<jlong, std::shared_ptr<Session>> sessions; |
| 1081 | std::atomic<jlong> nextId{1}; |
| 1082 | std::shared_ptr<Session> get(jlong id) { |
| 1083 | std::lock_guard lock(registryMutex); |
| 1084 | auto it = sessions.find(id); |
| 1085 | return it == sessions.end() ? nullptr : it->second; |
| 1086 | } |
| 1087 | std::mutex resourcesMutex; |
| 1088 | std::unordered_map<std::string, std::shared_ptr<twidget::SandboxResources>> resourceCache; |
| 1089 | std::shared_ptr<twidget::SandboxResources> resources(const std::string &path) { |
| 1090 | std::lock_guard lock(resourcesMutex); |
| 1091 | auto &value = resourceCache[path]; |
| 1092 | if (!value) |
| 1093 | value = twidget::SandboxResources::fromDirectory(path); |
| 1094 | return value; |
| 1095 | } |
| 1096 | } // namespace |
| 1097 |
| 1098 | // The bundles as bytes under `key`, which create then takes as its directory: the isolated process |
| 1099 | // (WidgetEngineService) reads them from the APK's assets and has no files of its own to put them in. |
| 1100 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_registerResources( |
| 1101 | JNIEnv *e, jclass, jbyteArray key, jbyteArray sandbox, jbyteArray validator, jbyteArray renderer, |
| 1102 | jbyteArray sandboxBytecode, jbyteArray validatorBytecode) { |
| 1103 | auto value = std::make_shared<twidget::SandboxResources>(); |
| 1104 | value->sandboxBundle = bytes(e, sandbox); |
| 1105 | value->validatorBundle = bytes(e, validator); |
| 1106 | value->rendererBundle = bytes(e, renderer); |
| 1107 | auto binary = [e](jbyteArray array) { |
| 1108 | std::string data = bytes(e, array); |
| 1109 | return std::vector<uint8_t>(data.begin(), data.end()); |
| 1110 | }; |
| 1111 | value->sandboxBytecode = binary(sandboxBytecode); |
| 1112 | value->validatorBytecode = binary(validatorBytecode); |
| 1113 | std::lock_guard lock(resourcesMutex); |
| 1114 | resourceCache[bytes(e, key)] = std::move(value); |
| 1115 | } |
| 1116 |
| 1117 | extern "C" JNIEXPORT jlong JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_create( |
| 1118 | JNIEnv *e, jclass, jbyteArray path, jbyteArray html, jbyteArray theme, jfloat width, jfloat dpr, |
| 1119 | jint cpuMultiplier, jbyteArray locale, jbyteArray storage, jbyteArray sdk, jbyteArray stoppedLabel, |
| 1120 | jboolean visible, jobject backend) { |
| 1121 | try { |
| 1122 | auto session = std::make_shared<Session>(); |
| 1123 | session->backend = std::make_shared<AndroidBackend>(e, backend); |
| 1124 | twidget::WidgetHostOptions options; |
| 1125 | // The widget's first task runs as shown or hidden from the start: a hidden widget's timers wait at |
| 1126 | // least a second and its frames not at all, so a shown one must not boot hidden. |
| 1127 | options.visible = visible; |
| 1128 | options.devicePixelRatio = dpr; |
| 1129 | options.features = {"webAnimations"}; |
| 1130 | options.locale = bytes(e, locale); |
| 1131 | options.storage = parseStorage(bytes(e, storage)); |
| 1132 | if (auto value = twidget::Json::parse(bytes(e, sdk))) { |
| 1133 | options.data = parseData((*value)["data"]); |
| 1134 | options.context = parseContext((*value)["context"]); |
| 1135 | // The client's time over the widget's corner at boot, so the first height already has its band. |
| 1136 | options.contentSafeArea = parseSafeArea((*value)["contentSafeArea"]); |
| 1137 | } |
| 1138 | options.cpuLimitMs *= cpuMultiplier; |
| 1139 | options.cpuQuotaMs *= cpuMultiplier; |
| 1140 | options.mainThreadQuotaMs *= cpuMultiplier; |
| 1141 | { |
| 1142 | std::lock_guard lock(limitsMutex); |
| 1143 | if (auto limits = twidget::Json::parse(limitsOverride); limits && limits->isObject()) { |
| 1144 | const auto &l = *limits; |
| 1145 | if (l["policy"].isString()) |
| 1146 | options.policy = l["policy"].asString(); |
| 1147 | if (l["cpuQuotaMs"].isNumber()) |
| 1148 | options.cpuQuotaMs = l["cpuQuotaMs"].asNumber(); |
| 1149 | if (l["cpuQuotaWindowMs"].isNumber()) |
| 1150 | options.cpuQuotaWindowMs = l["cpuQuotaWindowMs"].asNumber(); |
| 1151 | if (l["mainThreadQuotaMs"].isNumber()) |
| 1152 | options.mainThreadQuotaMs = l["mainThreadQuotaMs"].asNumber(); |
| 1153 | if (l["maxTimers"].isNumber()) |
| 1154 | options.maxTimers = l["maxTimers"].asInt(); |
| 1155 | if (l["memoryLimitBytes"].isNumber()) |
| 1156 | options.memoryLimitBytes = size_t(l["memoryLimitBytes"].asNumber()); |
| 1157 | } |
| 1158 | } |
| 1159 | auto factory = [b = session->backend, dpr](auto, const std::string &theme, double w) { |
| 1160 | return std::make_unique<AndroidRenderer>(b, theme, float(w), dpr); |
| 1161 | }; |
| 1162 | session->host = std::make_unique<twidget::WidgetHost>( |
| 1163 | bytes(e, html), parseTheme(bytes(e, theme)), width, options, resources(bytes(e, path)), factory, |
| 1164 | std::make_shared<AndroidIntl>(session->backend)); |
| 1165 | session->host->stoppedLabel = bytes(e, stoppedLabel); |
| 1166 | auto target = session->backend; |
| 1167 | session->host->onChange = [target](const twidget::WidgetDiagnostics &d) { |
| 1168 | auto j = twidget::Json::object(); |
| 1169 | j.set("loaded", d.loaded) |
| 1170 | .set("rendered", d.rendered) |
| 1171 | .set("nodes", d.nodes) |
| 1172 | .set("jsMs", d.stats.jsMs) |
| 1173 | .set("tasks", d.stats.tasks); |
| 1174 | j.set("queries", d.stats.queries) |
| 1175 | .set("queryMs", d.stats.queryMs) |
| 1176 | .set("throttled", d.stats.throttledTasks); |
| 1177 | j.set("memoryBytes", double(d.stats.memoryBytes)).set("height", d.height); |
| 1178 | // The edge that stays put when the height changes (docs/sdk-v1.md §2.12): set before the size it anchors. |
| 1179 | j.set("resizeAnchor", d.resizeAnchor); |
| 1180 | j.set("dead", d.dead.value_or("")).set("error", d.lastError.value_or("")); |
| 1181 | if (!d.diags.empty()) { |
| 1182 | auto last = d.diags.rbegin(); |
| 1183 | j.set("diagnostic", |
| 1184 | last->first + ": " + (last->second.second.empty() ? "" : last->second.second.back())); |
| 1185 | } |
| 1186 | try { |
| 1187 | target->signal(4, j.dump()); |
| 1188 | } catch (...) { |
| 1189 | } |
| 1190 | }; |
| 1191 | // A request to the bot, checked (docs/sdk-v1.md §5.11): the client answers it with |
| 1192 | // messages.getBotWidgetQueryAnswer through WidgetSandboxNative#answerRequest (signal 12, {"id","data","wallet"}; |
| 1193 | // `wallet`: the server attaches the user's wallet card, §5.13). |
| 1194 | std::weak_ptr<Session> weak = session; |
| 1195 | session->host->onRequest = [target, weak](const twidget::WidgetRequest &request, |
| 1196 | std::function<void(const twidget::WidgetRequestOutcome &)> respond) { |
| 1197 | auto owner = weak.lock(); |
| 1198 | if (!owner) |
| 1199 | return; |
| 1200 | int64_t id; |
| 1201 | { |
| 1202 | std::lock_guard lock(owner->requestsMutex); |
| 1203 | id = owner->nextRequest++; |
| 1204 | owner->requests[id] = std::move(respond); |
| 1205 | } |
| 1206 | try { |
| 1207 | target->signal(12, twidget::Json::object() |
| 1208 | .set("id", double(id)) |
| 1209 | .set("data", request.data) |
| 1210 | .set("wallet", request.wallet) |
| 1211 | .dump()); |
| 1212 | } catch (...) { |
| 1213 | } |
| 1214 | }; |
| 1215 | // A wallet call, checked (docs/sdk-v1.md §5.13; only with context.wallet): the client shows its wallet window, |
| 1216 | // sends the outcome to the bot and answers with the bot's answer through WidgetSandboxNative#answerRequest |
| 1217 | // (signal 19, {"id","call":{"method","transaction"|"payload","data"}}, TON Connect's field names). |
| 1218 | session->host->onWallet = [target, weak](const twidget::WalletCall &call, |
| 1219 | std::function<void(const twidget::WidgetRequestOutcome &)> respond) { |
| 1220 | auto owner = weak.lock(); |
| 1221 | if (!owner) |
| 1222 | return; |
| 1223 | int64_t id; |
| 1224 | { |
| 1225 | std::lock_guard lock(owner->requestsMutex); |
| 1226 | id = owner->nextRequest++; |
| 1227 | owner->requests[id] = std::move(respond); |
| 1228 | } |
| 1229 | try { |
| 1230 | target->signal(19, twidget::Json::object().set("id", double(id)).set("call", call.toJson()).dump()); |
| 1231 | } catch (...) { |
| 1232 | } |
| 1233 | }; |
| 1234 | // TelegramWidget.copyText on a tap: the client copies it and shows it (signal 13). |
| 1235 | session->host->onCopyText = [target](const std::string &text) { |
| 1236 | try { |
| 1237 | target->signal(13, text); |
| 1238 | } catch (...) { |
| 1239 | } |
| 1240 | }; |
| 1241 | // TelegramWidget.watchPublicData() / unwatchPublicData(): poll a shared widget's public_data while on (signal 14). |
| 1242 | session->host->onWatchPublicData = [target](bool on) { |
| 1243 | try { |
| 1244 | target->signal(14, on ? "1" : "0"); |
| 1245 | } catch (...) { |
| 1246 | } |
| 1247 | }; |
| 1248 | // What the widget asks the client to do, already checked (docs/sdk-v1.md §5.2, §5.3). |
| 1249 | session->host->onAction = [target](const twidget::WidgetAction &action) { |
| 1250 | try { |
| 1251 | target->signal(5, action.toJson().dump()); |
| 1252 | } catch (...) { |
| 1253 | } |
| 1254 | }; |
| 1255 | // The new full content of a Web Storage area (docs/sdk-v1.md §5.4). |
| 1256 | session->host->onStorageCommit = [target](const std::string &area, |
| 1257 | const std::map<std::string, std::string> &values) { |
| 1258 | auto content = twidget::Json::object(); |
| 1259 | for (const auto &[key, value] : values) |
| 1260 | content.set(key, value); |
| 1261 | try { |
| 1262 | target->signal(8, twidget::Json::object().set("area", area).set("values", content).dump()); |
| 1263 | } catch (...) { |
| 1264 | } |
| 1265 | }; |
| 1266 | // What the widget claims of this touch: horizontal drags and holds; `y` is always false since v0.1.3 (docs/sdk-v1.md §5.5). |
| 1267 | session->host->onGesture = [target](const twidget::WidgetGestureClaim &claim) { |
| 1268 | try { |
| 1269 | target->signal(3, twidget::Json::object().set("x", claim.x).set("y", claim.y).set("hold", claim.hold).dump()); |
| 1270 | } catch (...) { |
| 1271 | } |
| 1272 | }; |
| 1273 | if (attackScan) |
| 1274 | session->host->onRenderOps = [target](const std::string &clean) { |
| 1275 | std::vector<std::string> leaks; |
| 1276 | if (auto ops = twidget::Json::parse(clean)) |
| 1277 | for (const auto &op : ops->arr()) |
| 1278 | scanOp(op, leaks); |
| 1279 | for (const auto &leak : leaks) { |
| 1280 | try { |
| 1281 | target->signal(10, "ops " + leak); |
| 1282 | } catch (...) { |
| 1283 | } |
| 1284 | } |
| 1285 | }; |
| 1286 | jlong id = nextId.fetch_add(1); |
| 1287 | { |
| 1288 | std::lock_guard lock(registryMutex); |
| 1289 | sessions[id] = session; |
| 1290 | } |
| 1291 | session->host->start(); |
| 1292 | return id; |
| 1293 | } catch (const std::exception &error) { |
| 1294 | jclass type = e->FindClass("java/lang/IllegalStateException"); |
| 1295 | e->ThrowNew(type, error.what()); |
| 1296 | e->DeleteLocalRef(type); |
| 1297 | return 0; |
| 1298 | } |
| 1299 | } |
| 1300 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_destroy(JNIEnv *, |
| 1301 | jclass, |
| 1302 | jlong id) { |
| 1303 | std::shared_ptr<Session> session; |
| 1304 | { |
| 1305 | std::lock_guard lock(registryMutex); |
| 1306 | auto it = sessions.find(id); |
| 1307 | if (it == sessions.end()) |
| 1308 | return; |
| 1309 | session = std::move(it->second); |
| 1310 | sessions.erase(it); |
| 1311 | } |
| 1312 | session->shutdown(); |
| 1313 | } |
| 1314 | extern "C" JNIEXPORT void JNICALL |
| 1315 | Java_org_telegram_utils_twidget_WidgetSandboxNative_visible(JNIEnv *, jclass, jlong id, jboolean visible) { |
| 1316 | auto s = get(id); |
| 1317 | if (s) |
| 1318 | s->input([owner = s.get(), visible](auto &) { owner->host->setVisible(visible); }); |
| 1319 | } |
| 1320 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_theme(JNIEnv *e, jclass, |
| 1321 | jlong id, |
| 1322 | jbyteArray theme) { |
| 1323 | auto s = get(id); |
| 1324 | if (s) |
| 1325 | s->input([owner = s.get(), value = parseTheme(bytes(e, theme))](auto &) { owner->host->setTheme(value); }); |
| 1326 | } |
| 1327 | // What the client draws over the widget changed with the bubble's layout (docs/sdk-v1.md §2.17): the full area, as |
| 1328 | // `contentSafeArea` of the sdk JSON. Never per frame. |
| 1329 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_safeArea(JNIEnv *e, jclass, |
| 1330 | jlong id, |
| 1331 | jbyteArray area) { |
| 1332 | auto s = get(id); |
| 1333 | if (!s) |
| 1334 | return; |
| 1335 | auto value = twidget::Json::parse(bytes(e, area)); |
| 1336 | if (value) |
| 1337 | s->input([owner = s.get(), inset = parseSafeArea(*value)](auto &) { owner->host->setContentSafeArea(inset); }); |
| 1338 | } |
| 1339 | // The widget's state changed (updateMessageWidgetData, a polled public_data): the full state, `data` of the sdk JSON. |
| 1340 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_data(JNIEnv *e, jclass, |
| 1341 | jlong id, |
| 1342 | jbyteArray data) { |
| 1343 | auto s = get(id); |
| 1344 | if (!s) |
| 1345 | return; |
| 1346 | auto value = twidget::Json::parse(bytes(e, data)); |
| 1347 | if (value) |
| 1348 | s->input([owner = s.get(), state = parseData(*value)](auto &) { owner->host->setData(state); }); |
| 1349 | } |
| 1350 | // The client's answer to request or wallet call `request` (signal 12, 19): `failure` 0 answered (`result`, null for |
| 1351 | // none), 1 timeout, 2 rate limited, 3 failed; a wallet call's also 4 rejected (the user declined), 5 bad request (the |
| 1352 | // wallet refused it). Once; an unknown or answered id is ignored. |
| 1353 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_answerRequest( |
| 1354 | JNIEnv *e, jclass, jlong id, jlong request, jint failure, jbyteArray result) { |
| 1355 | auto s = get(id); |
| 1356 | if (!s) |
| 1357 | return; |
| 1358 | std::function<void(const twidget::WidgetRequestOutcome &)> respond; |
| 1359 | { |
| 1360 | std::lock_guard lock(s->requestsMutex); |
| 1361 | auto it = s->requests.find(request); |
| 1362 | if (it == s->requests.end()) |
| 1363 | return; |
| 1364 | respond = std::move(it->second); |
| 1365 | s->requests.erase(it); |
| 1366 | } |
| 1367 | twidget::WidgetRequestOutcome outcome; |
| 1368 | outcome.failure = failure == 1 ? twidget::WidgetRequestFailure::Timeout |
| 1369 | : failure == 2 ? twidget::WidgetRequestFailure::RateLimited |
| 1370 | : failure == 3 ? twidget::WidgetRequestFailure::Failed |
| 1371 | : failure == 4 ? twidget::WidgetRequestFailure::Rejected |
| 1372 | : failure == 5 ? twidget::WidgetRequestFailure::BadRequest |
| 1373 | : twidget::WidgetRequestFailure::None; |
| 1374 | if (outcome.failure == twidget::WidgetRequestFailure::None && result) |
| 1375 | outcome.answer.result = bytes(e, result); |
| 1376 | respond(outcome); |
| 1377 | } |
| 1378 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_width(JNIEnv *, jclass, |
| 1379 | jlong id, |
| 1380 | jfloat width) { |
| 1381 | auto s = get(id); |
| 1382 | if (s) |
| 1383 | s->input([width](auto &r) { r.setWidth(width); }); |
| 1384 | } |
| 1385 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_tick( |
| 1386 | JNIEnv *, jclass, jlong id, jfloat ms, jboolean frame, jboolean animate, jboolean paint) { |
| 1387 | auto s = get(id); |
| 1388 | if (s) |
| 1389 | s->input([=](auto &r) { r.tick(ms, frame, animate, paint); }); |
| 1390 | } |
| 1391 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_repaint(JNIEnv *, |
| 1392 | jclass, |
| 1393 | jlong id) { |
| 1394 | auto s = get(id); |
| 1395 | if (s) |
| 1396 | s->input([](auto &r) { r.repaint(); }); |
| 1397 | } |
| 1398 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_touch( |
| 1399 | JNIEnv *, jclass, jlong id, jint action, jfloat x, jfloat y, jint pointer, jboolean primary, jboolean mouse, |
| 1400 | jint modifiers, jint button) { |
| 1401 | auto s = get(id); |
| 1402 | if (s) |
| 1403 | s->input([=](auto &r) { r.touch(action, x, y, pointer, primary, mouse, modifiers, button); }); |
| 1404 | } |
| 1405 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_hover( |
| 1406 | JNIEnv *, jclass, jlong id, jint action, jfloat x, jfloat y, jint modifiers) { |
| 1407 | auto s = get(id); |
| 1408 | if (s) |
| 1409 | s->input([=](auto &r) { r.hover(action, x, y, modifiers); }); |
| 1410 | } |
| 1411 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_conformance(JNIEnv *, jclass, |
| 1412 | jboolean enabled) { |
| 1413 | conformanceReports = enabled; |
| 1414 | } |
| 1415 |
| 1416 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_limits(JNIEnv *e, jclass, |
| 1417 | jbyteArray json) { |
| 1418 | std::lock_guard lock(limitsMutex); |
| 1419 | limitsOverride = json ? bytes(e, json) : std::string(); |
| 1420 | } |
| 1421 |
| 1422 | extern "C" JNIEXPORT void JNICALL Java_org_telegram_utils_twidget_WidgetSandboxNative_attackScan(JNIEnv *, jclass, |
| 1423 | jboolean enabled) { |
| 1424 | attackScan = enabled; |
| 1425 | } |
| 1426 |
| 1427 | #ifdef WIDGET_SANDBOX_TESTING |
| 1428 | extern "C" JNIEXPORT jobject JNICALL |
| 1429 | Java_org_telegram_ui_Components_WidgetSandboxTestNative_backend(JNIEnv *e, jclass, jlong id) { |
| 1430 | auto s = get(id); |
| 1431 | return s && !s->closing ? s->backend->test_object(e) : nullptr; |
| 1432 | } |
| 1433 | // Host harness only; Android release builds expose no arbitrary JS evaluation |
| 1434 | // API. |
| 1435 | extern "C" JNIEXPORT jbyteArray JNICALL |
| 1436 | Java_org_telegram_ui_Components_WidgetSandboxTestNative_probe(JNIEnv *e, jclass, jlong id, jbyteArray code) { |
| 1437 | auto s = get(id); |
| 1438 | return bytes(e, s && !s->closing ? s->host->probe(bytes(e, code)) : "closed"); |
| 1439 | } |
| 1440 | extern "C" JNIEXPORT jint JNICALL |
| 1441 | Java_org_telegram_ui_Components_WidgetSandboxTestNative_liveSessions(JNIEnv *, jclass) { |
| 1442 | std::lock_guard lock(registryMutex); |
| 1443 | return sessions.size(); |
| 1444 | } |
| 1445 | #endif |
| 1446 |
| 1447 | extern "C" bool registerTwidgetNatives(JNIEnv *e) { |
| 1448 | if (!e || e->GetJavaVM(&vm) != JNI_OK) |
| 1449 | return false; |
| 1450 | jclass type = e->FindClass("org/telegram/utils/twidget/WidgetSandboxNative"); |
| 1451 | if (!type) |
| 1452 | return false; |
| 1453 | #define BIND(name, signature) \ |
| 1454 | { \ |
| 1455 | const_cast<char *>(#name), const_cast<char *>(signature), \ |
| 1456 | reinterpret_cast<void *>(Java_org_telegram_utils_twidget_WidgetSandboxNative_##name) \ |
| 1457 | } |
| 1458 | const JNINativeMethod methods[] = { |
| 1459 | BIND(create, "([B[B[BFFI[B[B[B[BZLjava/lang/Object;)J"), |
| 1460 | BIND(registerResources, "([B[B[B[B[B[B)V"), |
| 1461 | BIND(destroy, "(J)V"), |
| 1462 | BIND(visible, "(JZ)V"), |
| 1463 | BIND(theme, "(J[B)V"), |
| 1464 | BIND(width, "(JF)V"), |
| 1465 | BIND(data, "(J[B)V"), |
| 1466 | BIND(safeArea, "(J[B)V"), |
| 1467 | BIND(answerRequest, "(JJI[B)V"), |
| 1468 | BIND(repaint, "(J)V"), |
| 1469 | BIND(tick, "(JFZZZ)V"), |
| 1470 | BIND(touch, "(JIFFIZZII)V"), |
| 1471 | BIND(hover, "(JIFFI)V"), |
| 1472 | BIND(conformance, "(Z)V"), |
| 1473 | BIND(attackScan, "(Z)V")}; |
| 1474 | #undef BIND |
| 1475 | int status = e->RegisterNatives(type, methods, sizeof(methods) / sizeof(methods[0])); |
| 1476 | e->DeleteLocalRef(type); |
| 1477 | return status == JNI_OK; |
| 1478 | } |
| 1479 |