diff --git a/.gitignore b/.gitignore index 5f5b3781f..26108052e 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,9 @@ android/key.properties # Local dependency overrides (e.g. a working copy of the maplibre fork). pubspec_overrides.yaml + +# Optional eq-report-pic build outputs (tool/dev/build_report_picture.sh). +/native/eq_report_pic/ +/assets/fonts/report/*.ttf +/assets/fonts/report/third-party-notices.txt +/assets/fonts/report/rust-library-copyright.html diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 50fc291c7..66683e577 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -100,6 +100,71 @@ Each of these is a rule the code is expected to follow, not a description of what it happens to do. They live here so there is one copy: `CLAUDE.md` and `AGENTS.md` point at this file rather than restating it. +## Native report-image renderer + +`ReportPicture` in `lib/shared/seismic/report_picture/` accepts the original +UTF-8 Share Render Input v2 bytes. It checks the ABI (major 1, minor 2 or later) +and the v2 and production 16:9 capability bits before loading fonts. Rust +validates the input and returns a 1920×1080 PNG. The service returns a +`Result` with an app-owned copy or a structured +`ReportPictureFailure`. The upstream Dart bindings copy native bytes and +release the original buffer in the same isolate. Native initialization and +each render run in background isolates. One handle serves the renderer's +queued requests. Await `dispose()` to drain those requests and release the +handle. Ignoring a request Future does not cancel native work. + +### Native build inputs + +The mobile runtime is opt-in. With a local checkout containing eq-report-pic +merge commit `b135d02bd1ba5103cd3d116a951b1b63a710a312` (PR #12), run these +commands from the DPIP repository root. + +```sh +tool/dev/build_report_picture.sh ios ../eq-report-pic +tool/dev/build_report_picture.sh android ../eq-report-pic +shasum -a 256 -c native/eq_report_pic/ios/SHA256SUMS +shasum -a 256 -c native/eq_report_pic/android/SHA256SUMS +``` + +The script archives that commit, checks `Cargo.lock`, and builds offline with +the committed Cargo vendor snapshot and Rust 1.99.1. Install the Rust targets +for the platform you build. + +- **iOS** uses Xcode and `aarch64-apple-ios`, `aarch64-apple-ios-sim`, and + `x86_64-apple-ios`. Runner picks the static XCFramework slice for the SDK. + Linker roots keep all nine ABI symbols through dead stripping for Dart + `DynamicLibrary.process()` lookup. The extensions use their own link settings. +- **Android** uses NDK `28.2.13676358`, API 26, and + `aarch64-linux-android` / `x86_64-linux-android`. Set `ANDROID_HOME` or + `ANDROID_SDK_ROOT` if needed. Gradle includes the ELF files as `jniLibs` + for `arm64-v8a` and `x86_64`. The script checks all nine exports and 16 KiB + ELF segment alignment. DPIP excludes `armeabi-v7a` from its supported set. + Dart opens `libeq_report_pic.so`. + +The generated native libraries, fonts, and notices are local build inputs. +Each platform's `source-revision.txt`, `toolchain.txt`, and `SHA256SUMS` record +what was built and staged. Flutter packages a single set of the original TTFs +with their notices. Standard CI builds omit the optional native inputs. +A missing library or unsupported ABI becomes an ordinary `Failure`. +Distribution of the native runtime also requires clearance for the embedded +basemap and assets. + +### Offline smoke test + +Use the alternate entry point with the original synthetic fixture from +eq-report-pic's `testdata/share-input-v2/synthetic-zero-missing.json`, checked +in here for QA. The `.jcs.json` companion is the canonical comparison payload +and omits fields expected by the renderer. + +```sh +tool/run.sh -d --target tool/qa/report_picture_smoke.dart \ + --dart-define="DPIP_REPORT_PICTURE_FIXTURE=$(base64 < tool/qa/fixtures/report_picture_v2.json | tr -d '\n')" +``` + +Check for `REPORT_PICTURE_SMOKE PASS` and the logged ABI, PNG dimensions and +SHA-256. The harness also accepts `DPIP_REPORT_PICTURE_EXPECT=unavailable` or +`unsupportedAbi` for builds prepared with missing or incompatible libraries. + ## Logging Always log through `Log` (`lib/core/logging/log.dart`): diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index fc9feff48..3386c8049 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -48,6 +48,9 @@ android { compileSdk = flutter.compileSdkVersion ndkVersion = flutter.ndkVersion + // Optional artifacts built by tool/dev/build_report_picture.sh. + sourceSets.getByName("main").jniLibs.srcDir("../../native/eq_report_pic/android") + // Robolectric inflates the Widget's real layouts and resolves its real // resources, so the unit-test run needs the merged resource table — which // is off by default for Android unit tests. diff --git a/assets/fonts/report/OFL.txt b/assets/fonts/report/OFL.txt new file mode 100644 index 000000000..82f730582 --- /dev/null +++ b/assets/fonts/report/OFL.txt @@ -0,0 +1,95 @@ +Gen Shin Gothic Bold +[Source Han Sans] +Copyright © 2014, 2015 Adobe Systems Incorporated (http://www.adobe.com/), +with Reserved Font Name 'Source'. +[M+ OUTLINE FONTS] +Copyright(c) 2015 M+ FONTS PROJECT + +Noto Sans TC Black +(c) 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/report/README.md b/assets/fonts/report/README.md new file mode 100644 index 000000000..432aea8f8 --- /dev/null +++ b/assets/fonts/report/README.md @@ -0,0 +1,25 @@ +# Report-image fonts + +`tool/dev/build_report_picture.sh` stages the fonts below from the pinned +eq-report-pic source. They are loaded from Flutter assets in fallback order +so the app carries one copy across all architectures. + +| File | Family | Licence | +|---|---|---| +| `mplus-2p-bold.ttf` | M+ 2p Bold, Copyright (c) 2019 M+ FONTS PROJECT | Free software, unlimited permission to use, copy and distribute, with or without modification | +| `GenShinGothic-Bold.ttf` | Gen Shin Gothic Bold, based on Source Han Sans, Copyright © 2014, 2015 Adobe Systems Incorporated | SIL Open Font License 1.1 | +| `NotoSansTC-Black.ttf` | Noto Sans TC Black, Copyright (c) 2014–2021 Adobe | SIL Open Font License 1.1 | + +The original notices remain in the TTF name tables. See `OFL.txt` for the +full text that accompanies the Gen Shin Gothic and Noto Sans TC fonts. + +### M+ 2p Bold + +> Copyright(c) 2019 M+ FONTS PROJECT +> +> This font is free software. Unlimited permission is granted to use, copy, +> and distribute it, with or without modification, either commercially or +> noncommercially. THIS FONT IS PROVIDED "AS IS" WITHOUT WARRANTY. + +The build also stages `third-party-notices.txt` for the Rust crates and +`rust-library-copyright.html` for the Rust standard library. diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig index 592ceee85..12237a1d8 100644 --- a/ios/Flutter/Debug.xcconfig +++ b/ios/Flutter/Debug.xcconfig @@ -1 +1,2 @@ #include "Generated.xcconfig" +#include? "../../native/eq_report_pic/ios/link.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig index 592ceee85..12237a1d8 100644 --- a/ios/Flutter/Release.xcconfig +++ b/ios/Flutter/Release.xcconfig @@ -1 +1,2 @@ #include "Generated.xcconfig" +#include? "../../native/eq_report_pic/ios/link.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index cde9fb11e..c154bffcf 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -1391,6 +1391,8 @@ "$(inherited)", "@executable_path/Frameworks", ); + LD_EXPORT_SYMBOLS = YES; + OTHER_LDFLAGS = ("$(inherited)", "$(DPIP_EQR_LINK)"); PRODUCT_BUNDLE_IDENTIFIER = com.exptech.dpip.dpip; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; @@ -1906,6 +1908,8 @@ "$(inherited)", "@executable_path/Frameworks", ); + LD_EXPORT_SYMBOLS = YES; + OTHER_LDFLAGS = ("$(inherited)", "$(DPIP_EQR_LINK)"); PRODUCT_BUNDLE_IDENTIFIER = com.exptech.dpip.dpip; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; @@ -1933,6 +1937,8 @@ "$(inherited)", "@executable_path/Frameworks", ); + LD_EXPORT_SYMBOLS = YES; + OTHER_LDFLAGS = ("$(inherited)", "$(DPIP_EQR_LINK)"); PRODUCT_BUNDLE_IDENTIFIER = com.exptech.dpip.dpip; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; diff --git a/lib/core/error/failure.dart b/lib/core/error/failure.dart index a36b5222f..0f4462fbf 100644 --- a/lib/core/error/failure.dart +++ b/lib/core/error/failure.dart @@ -111,3 +111,21 @@ final class WidgetSnapshotFailure extends Failure { final WidgetSnapshotFailureReason reason; } + +enum ReportPictureFailureReason { + unavailable, + unsupportedAbi, + invalidInput, + unsupportedVersion, + unsupportedFeature, + limitExceeded, + renderFailed, + disposed, +} + +final class ReportPictureFailure extends Failure { + const ReportPictureFailure(this.reason, super.message, {this.nativeStatus}); + + final ReportPictureFailureReason reason; + final int? nativeStatus; +} diff --git a/lib/core/platform/native_library.dart b/lib/core/platform/native_library.dart new file mode 100644 index 000000000..9cd42f07f --- /dev/null +++ b/lib/core/platform/native_library.dart @@ -0,0 +1,85 @@ +import 'dart:ffi'; +import 'dart:io'; + +import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; +import 'package:dpip/core/logging/log.dart'; + +/// A platform whose packaging rules decide how a native library is opened. +enum NativeLibraryHost { android, ios, macos, windows, linux, fuchsia } + +/// The file [name] is packaged as on [host], or null when there is no file. +/// +/// Null is the iOS case: the library is linked into the app as a static +/// library, so its symbols live in the process and are opened with +/// `DynamicLibrary.process`. Every other target ships a file the build copies +/// next to the app. +String? nativeLibraryFileName(String name, NativeLibraryHost host) => + switch (host) { + NativeLibraryHost.ios => null, + NativeLibraryHost.android || + NativeLibraryHost.linux || + NativeLibraryHost.fuchsia => 'lib$name.so', + NativeLibraryHost.macos => 'lib$name.dylib', + NativeLibraryHost.windows => '$name.dll', + }; + +/// Opens the native libraries this app ships over FFI. +/// +/// The app's C ABI lives in a separate repository (`ExpTechTW/eq-report-pic`) +/// and is compiled per platform rather than built by Flutter. That makes +/// "the library is missing" a normal state — a build that has not run the +/// native step, or an ABI the store stripped — so opening one is a [Result], +/// never a throw. A screen that cannot draw its share image still alerts +/// people about an earthquake. +/// +/// [openFile] and [openProcess] exist for tests, which run on a host that has +/// no native artifact; production callers omit them. +abstract final class NativeLibrary { + /// Opens [name] for this device. + /// + /// [host] overrides the detected platform for tests. On iOS the symbols are + /// already in the process, so [openProcess] is used and [openFile] is not + /// called; elsewhere [openFile] receives the packaged file name. + static Result open( + String name, { + NativeLibraryHost? host, + DynamicLibrary Function(String fileName)? openFile, + DynamicLibrary Function()? openProcess, + }) { + final resolvedHost = host ?? _host(); + if (resolvedHost == null) { + return Err( + UnexpectedFailure('FFI is not wired for ${Platform.operatingSystem}'), + ); + } + + final fileName = nativeLibraryFileName(name, resolvedHost); + try { + final library = fileName == null + ? (openProcess ?? DynamicLibrary.process)() + : (openFile ?? DynamicLibrary.open)(fileName); + Log.debug('ffi: opened $name from ${fileName ?? 'the process'}'); + return Ok(library); + } catch (error) { + // The OS message names the file and the reason ("image not found", + // "cannot open shared object file"); keep it, it is the only clue a + // build step is missing. + Log.warning('ffi: $name unavailable on ${resolvedHost.name}: $error'); + return Err( + UnexpectedFailure('Native library "$name" is not available: $error'), + ); + } + } + + /// This device's host, or null when FFI has no mapping for it. + static NativeLibraryHost? _host() => switch (Platform.operatingSystem) { + 'android' => NativeLibraryHost.android, + 'ios' => NativeLibraryHost.ios, + 'macos' => NativeLibraryHost.macos, + 'windows' => NativeLibraryHost.windows, + 'linux' => NativeLibraryHost.linux, + 'fuchsia' => NativeLibraryHost.fuchsia, + _ => null, + }; +} diff --git a/lib/shared/seismic/report_picture/eq_report_pic_bindings.dart b/lib/shared/seismic/report_picture/eq_report_pic_bindings.dart new file mode 100644 index 000000000..1552e5206 --- /dev/null +++ b/lib/shared/seismic/report_picture/eq_report_pic_bindings.dart @@ -0,0 +1,352 @@ +/// Dart binding for the eq_report_pic C ABI (`include/eq_report_pic.h`). +/// +/// Vendored from eq-report-pic b135d02bd1ba5103cd3d116a951b1b63a710a312. +/// DPIP uses NativeLibrary to load it and owns renderer handles in ReportPicture. +library; + +import 'dart:ffi'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; + +final class _EqrRenderer extends Opaque {} + +typedef _NewC = Pointer<_EqrRenderer> Function( + Pointer>, + Pointer, + Size, +); +typedef _NewDart = Pointer<_EqrRenderer> Function( + Pointer>, + Pointer, + int, +); +typedef _FreeC = Void Function(Pointer<_EqrRenderer>); +typedef _FreeDart = void Function(Pointer<_EqrRenderer>); +typedef _RenderC = Int32 Function( + Pointer<_EqrRenderer>, + Pointer, + Size, + Float, + Uint32, + Uint32, + Pointer>, + Pointer, +); +typedef _RenderDart = int Function( + Pointer<_EqrRenderer>, + Pointer, + int, + double, + int, + int, + Pointer>, + Pointer, +); +typedef _AbiInfoC = Uint32 Function(Pointer); +typedef _AbiInfoDart = int Function(Pointer); +typedef _RenderV2C = Int32 Function( + Pointer<_EqrRenderer>, + Pointer, + Size, + Uint32, + Uint32, + Pointer>, + Pointer, +); +typedef _RenderV2Dart = int Function( + Pointer<_EqrRenderer>, + Pointer, + int, + int, + int, + Pointer>, + Pointer, +); +typedef _RenderCall = int Function( + Pointer, + int, + Pointer>, + Pointer, +); + +typedef _BytesFreeC = Void Function(Pointer, Size); +typedef _BytesFreeDart = void Function(Pointer, int); +typedef _StrC = Pointer Function(); + +/// How stations are drawn on the map. The index is the C ABI value. +enum EqMapMode { + /// Squares: the strongest station of each group plus the group's size. + cluster, + + /// Every station as a circle, strongest on top. + stations, + + /// Townships coloured by their strongest station. + towns, +} + +/// Colour theme. The index is the C ABI value. +enum EqTheme { light, dark } + +/// Thrown when the native library reports a failure. +class EqReportPicException implements Exception { + EqReportPicException(this.message); + final String message; + @override + String toString() => 'EqReportPicException: $message'; +} + +/// A machine-readable reason for a v2 share rendering failure. +enum EqShareRenderError { + invalidArgument, + unsupportedVersion, + unsupportedFeature, + limitExceeded, + internal, + unknown, +} + +/// A v2 rendering failure. Also catchable as [EqReportPicException]. +class EqShareRenderException extends EqReportPicException { + EqShareRenderException(super.message, this.reason, {this.nativeStatus}); + + final EqShareRenderError reason; + + /// The exact status from the native render call, if one was made. + /// + /// A missing capability or symbol reports [EqShareRenderError.unsupportedFeature] + /// with a null status; an unsupported input locale reports native status -3. + final int? nativeStatus; +} + +/// The library's functions. Opening is cheap; a [DynamicLibrary] cannot be +/// sent to another isolate, so open it again inside each isolate. +class EqReportPicBindings { + EqReportPicBindings(DynamicLibrary lib) + : _lib = lib, + _new = lib.lookupFunction<_NewC, _NewDart>('eqr_renderer_new'), + _free = lib.lookupFunction<_FreeC, _FreeDart>('eqr_renderer_free'), + _render = lib.lookupFunction<_RenderC, _RenderDart>('eqr_render_png'), + _bytesFree = lib.lookupFunction<_BytesFreeC, _BytesFreeDart>( + 'eqr_bytes_free', + ), + _lastError = lib.lookupFunction<_StrC, _StrC>('eqr_last_error'), + _version = lib.lookupFunction<_StrC, _StrC>('eqr_version'); + + final DynamicLibrary _lib; + final _NewDart _new; + final _FreeDart _free; + final _RenderDart _render; + final _BytesFreeDart _bytesFree; + final Pointer Function() _lastError; + final Pointer Function() _version; + + late final _shareV2 = _discoverShareV2(); + + /// An unavailable v2 renderer has a diagnostic and a null function. + String? get sharePngV2Unavailable => _shareV2.unavailable; + + /// Releases an owned handle after all background calls have returned. + void freeRenderer(int address) => + _free(Pointer<_EqrRenderer>.fromAddress(address)); + + ({_RenderV2Dart? render, String? unavailable}) _discoverShareV2() { + const abiSymbol = 'eqr_abi_info'; + const renderSymbol = 'eqr_render_share_png_v2'; + const shareInputV2 = 1 << 4; + const production16By9 = 1 << 8; + const requiredCapabilities = shareInputV2 | production16By9; + + if (!_lib.providesSymbol(abiSymbol)) { + return (render: null, unavailable: 'Missing $abiSymbol'); + } + final abiInfo = _lib.lookupFunction<_AbiInfoC, _AbiInfoDart>(abiSymbol); + final (abi, capabilities) = using((arena) { + final bits = arena(); + final abi = abiInfo(bits); + return (abi, bits.value); + }); + final major = abi >> 16; + final minor = abi & 0xffff; + if (major != 1 || minor < 2) { + return ( + render: null, + unavailable: 'Unsupported native ABI $major.$minor', + ); + } + if ((capabilities & requiredCapabilities) != requiredCapabilities) { + return ( + render: null, + unavailable: + 'Native ABI needs EQR_CAP_SHARE_INPUT_V2 and ' + 'EQR_CAP_PRODUCTION_16_9', + ); + } + if (!_lib.providesSymbol(renderSymbol)) { + return (render: null, unavailable: 'Missing $renderSymbol'); + } + return ( + render: _lib.lookupFunction<_RenderV2C, _RenderV2Dart>(renderSymbol), + unavailable: null, + ); + } + + EqShareRenderException _shareV2Error(int status) { + // Copy the thread-local diagnostic before making another eqr_* call. + final message = _error('eqr_render_share_png_v2 failed ($status)'); + final reason = switch (status) { + -1 => EqShareRenderError.invalidArgument, + -2 => EqShareRenderError.unsupportedVersion, + -3 => EqShareRenderError.unsupportedFeature, + -4 => EqShareRenderError.limitExceeded, + -5 => EqShareRenderError.internal, + _ => EqShareRenderError.unknown, + }; + return EqShareRenderException(message, reason, nativeStatus: status); + } + + String get version => _version().toDartString(); + + String _error(String fallback) { + final p = _lastError(); + return p == nullptr ? fallback : p.toDartString(); + } +} + +/// A native renderer. Create it once (fonts are parsed and the basemap is +/// decoded here), render many times, [dispose] when done. +/// +/// The native renderer is thread-safe: pass [address] to another isolate and +/// rebuild it there with [EqReportPic.fromAddress]. Only the owner may +/// [dispose], and only after every isolate is done with it. +class EqReportPic { + EqReportPic._(this._b, this._handle, this._owner); + + /// [fonts]: TTF bytes in fallback order — + /// mplus-2p-bold, GenShinGothic-Bold, NotoSansTC-Black. The bytes are copied. + factory EqReportPic.create(EqReportPicBindings b, List fonts) { + final ptrs = malloc>(fonts.length); + final lens = malloc(fonts.length); + final buffers = >[]; + try { + for (var i = 0; i < fonts.length; i++) { + final buf = malloc(fonts[i].length); + buffers.add(buf); + buf.asTypedList(fonts[i].length).setAll(0, fonts[i]); + ptrs[i] = buf; + lens[i] = fonts[i].length; + } + final handle = b._new(ptrs, lens, fonts.length); + if (handle == nullptr) { + throw EqReportPicException(b._error('eqr_renderer_new failed')); + } + return EqReportPic._(b, handle, true); + } finally { + for (final buf in buffers) { + malloc.free(buf); + } + malloc.free(ptrs); + malloc.free(lens); + } + } + + /// A non-owning view of a renderer created elsewhere (e.g. in the main + /// isolate); [dispose] on it does nothing. + factory EqReportPic.fromAddress(EqReportPicBindings b, int address) => + EqReportPic._(b, Pointer<_EqrRenderer>.fromAddress(address), false); + + final EqReportPicBindings _b; + Pointer<_EqrRenderer> _handle; + final bool _owner; + + int get address => _handle.address; + + /// [json]: the body of `/api/v2/eq/report/{id}`. [scale] 1.0 = 1920x1080. + Uint8List renderPng( + Uint8List json, { + double scale = 1.0, + EqMapMode mode = EqMapMode.cluster, + EqTheme theme = EqTheme.light, + }) { + if (_handle == nullptr) throw EqReportPicException('renderer disposed'); + return _renderAndCopy( + json, + (input, length, outPtr, outLen) => _b._render( + _handle, + input, + length, + scale, + mode.index, + theme.index, + outPtr, + outLen, + ), + (_) => EqReportPicException(_b._error('eqr_render_png failed')), + ); + } + + /// Renders original UTF-8 Share Render Input v2 [jsonBytes] to a + /// Dart-owned 1920×1080 PNG. The native library validates the input. + /// + /// Throws [EqShareRenderException] for unsupported native libraries and + /// native rendering failures. There is no synthetic or legacy fallback. + Uint8List renderSharePngV2( + Uint8List jsonBytes, { + required EqMapMode mode, + required EqTheme theme, + }) { + if (_handle == nullptr) { + throw EqShareRenderException( + 'renderer disposed', + EqShareRenderError.invalidArgument, + ); + } + final (:render, :unavailable) = _b._shareV2; + if (render == null) { + throw EqShareRenderException( + unavailable!, + EqShareRenderError.unsupportedFeature, + ); + } + return _renderAndCopy( + jsonBytes, + (input, length, outPtr, outLen) => render( + _handle, + input, + length, + mode.index, + theme.index, + outPtr, + outLen, + ), + _b._shareV2Error, + ); + } + + Uint8List _renderAndCopy( + Uint8List json, + _RenderCall render, + EqReportPicException Function(int) error, + ) => using((arena) { + final input = arena(json.isEmpty ? 1 : json.length); + final outPtr = arena>(); + final outLen = arena(); + input.asTypedList(json.length).setAll(0, json); + final status = render(input, json.length, outPtr, outLen); + if (status != 0) throw error(status); + + final png = outPtr.value; + final pngLength = outLen.value; + try { + return Uint8List.fromList(png.asTypedList(pngLength)); + } finally { + _b._bytesFree(png, pngLength); + } + }); + + void dispose() { + if (_owner && _handle != nullptr) _b._free(_handle); + _handle = nullptr; + } +} diff --git a/lib/shared/seismic/report_picture/report_picture.dart b/lib/shared/seismic/report_picture/report_picture.dart new file mode 100644 index 000000000..1d155d3e1 --- /dev/null +++ b/lib/shared/seismic/report_picture/report_picture.dart @@ -0,0 +1,208 @@ +import 'dart:isolate'; + +import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; +import 'package:dpip/core/platform/native_library.dart'; +import 'package:dpip/shared/seismic/report_picture/eq_report_pic_bindings.dart'; +import 'package:flutter/services.dart'; + +export 'eq_report_pic_bindings.dart' show EqMapMode, EqTheme; + +/// Renders Share Render Input v2 into a Dart-owned, 1920×1080 landscape PNG. +final class ReportPicture { + ReportPicture._(this._address, this._bindings); + + static const libraryName = 'eq_report_pic'; + static const _maxInputBytes = 1024 * 1024; + static const _fontAssets = [ + 'assets/fonts/report/mplus-2p-bold.ttf', + 'assets/fonts/report/GenShinGothic-Bold.ttf', + 'assets/fonts/report/NotoSansTC-Black.ttf', + ]; + + final int _address; + final EqReportPicBindings _bindings; + Future _pending = Future.value(); + Future? _disposal; + + /// Checks native support before loading fonts and creating the renderer. + static Future> open() async { + final probe = _openBindings(); + final bindings = probe.valueOrNull; + if (bindings == null) return Err(probe.failureOrNull!); + + try { + final fonts = []; + for (final asset in _fontAssets) { + final data = await rootBundle.load(asset); + fonts.add( + data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), + ); + } + final address = await _createRenderer(fonts); + return Ok(ReportPicture._(address, bindings)); + } catch (error) { + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + 'The native report renderer could not start: $error', + ), + ); + } + } + + /// Renders the original UTF-8 bytes. Native validation sees the original + /// keys and number spellings, including inputs that JSON decoding would + /// normalize. The caller may reuse or change its buffer after this call. + /// + /// Requests are queued on this renderer to bound the number of live PNG + /// canvases. A failed request leaves the renderer ready for the next one. + Future> renderSharePngV2( + Uint8List json, { + EqMapMode mode = EqMapMode.cluster, + EqTheme theme = EqTheme.light, + }) { + if (_disposal != null) { + return Future.value( + const Err( + ReportPictureFailure( + ReportPictureFailureReason.disposed, + 'The report picture renderer has been disposed', + ), + ), + ); + } + if (json.length > _maxInputBytes) { + return Future.value( + const Err( + ReportPictureFailure( + ReportPictureFailureReason.limitExceeded, + 'Share Render Input v2 exceeds 1 MiB', + ), + ), + ); + } + + final input = Uint8List.fromList(json); + final render = _pending.then( + (_) => _renderRequest(_address, input, mode, theme), + ); + _pending = render.then((_) {}); + return render; + } + + /// Stops accepting work and frees the handle once scheduled calls finish. + /// Dropping a render Future does not cancel its synchronous FFI call. + Future dispose() => + _disposal ??= _pending.then((_) => _bindings.freeRenderer(_address)); +} + +Result _openBindings() { + final probe = NativeLibrary.open(ReportPicture.libraryName); + final library = probe.valueOrNull; + if (library == null) { + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + probe.failureOrNull!.message, + ), + ); + } + try { + // iOS opens the process even when the optional static library is absent. + if (!library.providesSymbol('eqr_renderer_new') && + !library.providesSymbol('eqr_abi_info')) { + return const Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + 'The native report library is not linked into this build', + ), + ); + } + final bindings = EqReportPicBindings(library); + final unavailable = bindings.sharePngV2Unavailable; + if (unavailable != null) { + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unsupportedAbi, + unavailable, + ), + ); + } + return Ok(bindings); + } on ArgumentError catch (error) { + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unsupportedAbi, + 'The native report library does not export the expected symbols: $error', + ), + ); + } +} + +EqReportPicBindings _workerBindings() { + final probe = _openBindings(); + final bindings = probe.valueOrNull; + if (bindings != null) return bindings; + throw probe.failureOrNull!; +} + +// Top-level isolate entry points capture only sendable inputs. The handle +// stays process-local. Only ReportPicture.dispose frees it. +Future _createRenderer(List fonts) => Isolate.run( + () => EqReportPic.create(_workerBindings(), fonts).address, + debugName: 'report-picture-create', +); + +Future _renderInIsolate( + int address, + Uint8List input, + EqMapMode mode, + EqTheme theme, +) => Isolate.run( + () => EqReportPic.fromAddress( + _workerBindings(), + address, + ).renderSharePngV2(input, mode: mode, theme: theme), + debugName: 'report-picture-render', +); + +Future> _renderRequest( + int address, + Uint8List input, + EqMapMode mode, + EqTheme theme, +) async { + try { + return Ok(await _renderInIsolate(address, input, mode, theme)); + } on ReportPictureFailure catch (failure) { + return Err(failure); + } on EqShareRenderException catch (error) { + final reason = switch (error.reason) { + EqShareRenderError.invalidArgument => + ReportPictureFailureReason.invalidInput, + EqShareRenderError.unsupportedVersion => + ReportPictureFailureReason.unsupportedVersion, + EqShareRenderError.unsupportedFeature => + ReportPictureFailureReason.unsupportedFeature, + EqShareRenderError.limitExceeded => + ReportPictureFailureReason.limitExceeded, + EqShareRenderError.internal || + EqShareRenderError.unknown => ReportPictureFailureReason.renderFailed, + }; + return Err( + ReportPictureFailure( + reason, + error.message, + nativeStatus: error.nativeStatus, + ), + ); + } catch (error) { + return Err( + ReportPictureFailure( + ReportPictureFailureReason.renderFailed, + 'The native report renderer failed: $error', + ), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index f35162dd6..fd4f00724 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -281,7 +281,7 @@ packages: source: hosted version: "1.3.3" ffi: - dependency: transitive + dependency: "direct main" description: name: ffi sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" diff --git a/pubspec.yaml b/pubspec.yaml index 3ae6b509e..cea08e142 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -29,6 +29,7 @@ dependencies: # ml_intensity_service.dart). Already in the lock through the SDK tooling. crypto: ^3.0.6 dio: ^5.11.0 + ffi: ^2.2.0 # Firebase pinned deliberately — a newer major bumps the min iOS target and # breaks older-device compatibility. Do not upgrade without checking that. # Pinned to the exact version (not `^`) so a plain `pub upgrade` can't drift @@ -193,6 +194,7 @@ flutter: - shaders/weather/rainbow.frag - shaders/weather/card_water.frag assets: + - assets/fonts/report/ - assets/DPIP.png - assets/box.json.Z - assets/weather/clouds/ diff --git a/test/core/platform/native_library_test.dart b/test/core/platform/native_library_test.dart new file mode 100644 index 000000000..8edcf3739 --- /dev/null +++ b/test/core/platform/native_library_test.dart @@ -0,0 +1,111 @@ +import 'dart:ffi'; + +import 'package:dpip/core/platform/native_library.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('nativeLibraryFileName', () { + test('Android and Linux load the .so by its base name', () { + expect( + nativeLibraryFileName('eq_report_pic', NativeLibraryHost.android), + 'libeq_report_pic.so', + ); + expect( + nativeLibraryFileName('eq_report_pic', NativeLibraryHost.linux), + 'libeq_report_pic.so', + ); + }); + + test('iOS has no file — the symbols are linked into the app', () { + expect( + nativeLibraryFileName('eq_report_pic', NativeLibraryHost.ios), + isNull, + reason: 'DynamicLibrary.process is the only way in on iOS', + ); + }); + + test('desktop uses its own extension', () { + expect( + nativeLibraryFileName('eq_report_pic', NativeLibraryHost.macos), + 'libeq_report_pic.dylib', + ); + expect( + nativeLibraryFileName('eq_report_pic', NativeLibraryHost.windows), + 'eq_report_pic.dll', + ); + }); + }); + + group('NativeLibrary.open', () { + test('a missing file is a Result, not a throw', () { + final result = NativeLibrary.open( + 'dpip_no_such_native_library', + host: NativeLibraryHost.linux, + ); + + expect(result.isOk, isFalse); + expect(result.failureOrNull, isNotNull); + expect(result.failureOrNull!.message, contains('not available')); + }); + + test( + 'the OS message survives — it is the only clue a build step is missing', + () { + final result = NativeLibrary.open( + 'dpip_no_such_native_library', + host: NativeLibraryHost.linux, + ); + + expect( + result.failureOrNull!.message, + contains('dpip_no_such_native_library'), + ); + }, + ); + + test('iOS reads the process and never opens a file', () { + var fileOpens = 0; + final result = NativeLibrary.open( + 'anything', + host: NativeLibraryHost.ios, + openFile: (_) { + fileOpens++; + return DynamicLibrary.process(); + }, + openProcess: DynamicLibrary.process, + ); + + expect(result.isOk, isTrue); + expect(fileOpens, 0); + }); + + test('the packaged file name is what the loader is asked to open', () { + String? opened; + final result = NativeLibrary.open( + 'eq_report_pic', + host: NativeLibraryHost.android, + openFile: (fileName) { + opened = fileName; + return DynamicLibrary.process(); + }, + ); + + expect(result.isOk, isTrue); + expect(opened, 'libeq_report_pic.so'); + }); + + test('a loader that throws is wrapped, keeping its message', () { + final result = NativeLibrary.open( + 'eq_report_pic', + host: NativeLibraryHost.android, + openFile: (_) => throw ArgumentError('cannot open shared object file'), + ); + + expect(result.isOk, isFalse); + expect( + result.failureOrNull!.message, + contains('cannot open shared object file'), + ); + }); + }); +} diff --git a/tool/dev/build_report_picture.sh b/tool/dev/build_report_picture.sh new file mode 100755 index 000000000..e508d5309 --- /dev/null +++ b/tool/dev/build_report_picture.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# Build the optional report-image runtime from a verified local source checkout. +source "$(dirname "${BASH_SOURCE[0]}")/_lib.sh" +root="$(repo_root)" +revision=b135d02bd1ba5103cd3d116a951b1b63a710a312 + +platform="${1:-}" +source_checkout="${2:-}" +if [[ $# -ne 2 || ! $platform =~ ^(ios|android)$ ]]; then + printf 'Usage: %s {ios|android} \n' "$0" >&2 + exit 2 +fi + +if ! git -C "$source_checkout" cat-file -e "$revision^{commit}"; then + printf 'Fetch pinned eq-report-pic revision %s into the source checkout.\n' "$revision" >&2 + exit 1 +fi + +# Build a snapshot of the committed inputs, leaving the source checkout alone. +runtime="$root/native/eq_report_pic" +mkdir -p "$runtime" +scratch="$(mktemp -d "$runtime/.build.XXXXXX")" +trap 'rm -rf "$scratch"' EXIT +mkdir -p "$scratch/source" "$scratch/fonts" +git -C "$source_checkout" archive "$revision" | tar -xf - -C "$scratch/source" +cd "$scratch/source" +shasum -a 256 -c .github/cargo/Cargo.lock.sha256 +tar -xzf .github/cargo/vendor.tar.gz +mkdir -p .cargo +cat > .cargo/config.toml <<'CONFIG' +[source.crates-io] +replace-with = "vendored-sources" + +[source.vendored-sources] +directory = "vendor" +CONFIG + +toolchain="$(sed -n 's/^channel = "\([^"]*\)"$/\1/p' rust-toolchain.toml)" +unset RUSTFLAGS +export CARGO_ENCODED_RUSTFLAGS="--remap-path-prefix=$scratch=/eq-report-pic" +export CARGO_TARGET_DIR="$scratch/target" +build() { + rustup run "$toolchain" cargo build --frozen --release --lib --target "$1" +} + +symbols="$scratch/symbols" +sed -nE 's/^[[:alnum:]_ *]+[ *](eqr_[[:alnum:]_]+)\(.*/\1/p' \ + include/eq_report_pic.h | LC_ALL=C sort > "$symbols" +[[ "$(wc -l < "$symbols" | tr -d ' ')" == 9 ]] + +case "$platform" in + ios) + export IPHONEOS_DEPLOYMENT_TARGET=15.0 + mkdir -p "$scratch/ios" "$scratch/simulator" + build aarch64-apple-ios + build aarch64-apple-ios-sim + build x86_64-apple-ios + xcrun lipo -create \ + "$CARGO_TARGET_DIR/aarch64-apple-ios-sim/release/libeq_report_pic.a" \ + "$CARGO_TARGET_DIR/x86_64-apple-ios/release/libeq_report_pic.a" \ + -output "$scratch/simulator/libeq_report_pic.a" + xcodebuild -create-xcframework \ + -library "$CARGO_TARGET_DIR/aarch64-apple-ios/release/libeq_report_pic.a" \ + -library "$scratch/simulator/libeq_report_pic.a" \ + -output "$scratch/ios/EqReportPic.xcframework" + + # Only Runner consumes these flags. Keep the linker roots even under dead + # stripping so symbols with no native caller are still visible to Dart. + { + printf 'DPIP_EQR_XCFRAMEWORK = $(SRCROOT)/../native/eq_report_pic/ios/EqReportPic.xcframework\n' + printf 'DPIP_EQR_SLICE[sdk=iphoneos*] = ios-arm64\n' + printf 'DPIP_EQR_SLICE[sdk=iphonesimulator*] = ios-arm64_x86_64-simulator\n' + printf 'DPIP_EQR_LINK = "$(DPIP_EQR_XCFRAMEWORK)/$(DPIP_EQR_SLICE)/libeq_report_pic.a"' + while IFS= read -r symbol; do + printf ' -Wl,-u,_%s' "$symbol" + done < "$symbols" + printf '\n' + } > "$scratch/ios/link.xcconfig" + xcodebuild -version > "$scratch/ios/toolchain.txt" + ;; + android) + ndk_version=28.2.13676358 + sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}" + case "$(uname -s)" in + Darwin) host_tag=darwin-x86_64 ;; + Linux) host_tag=linux-x86_64 ;; + *) printf 'The Android report runtime build requires macOS or Linux.\n' >&2; exit 1 ;; + esac + llvm="$sdk/ndk/$ndk_version/toolchains/llvm/prebuilt/$host_tag/bin" + if [[ ! -x $llvm/llvm-readelf ]]; then + printf 'Install Android NDK %s in %s.\n' "$ndk_version" "$sdk" >&2 + exit 1 + fi + for abi in arm64-v8a x86_64; do + case "$abi" in + arm64-v8a) target=aarch64-linux-android ;; + x86_64) target=x86_64-linux-android ;; + esac + linker_var="CARGO_TARGET_$(printf '%s' "$target" | tr 'a-z-' 'A-Z_')_LINKER" + env "$linker_var=$llvm/${target}26-clang" \ + rustup run "$toolchain" cargo build --frozen --release --lib --target "$target" + output="$scratch/android/$abi/libeq_report_pic.so" + mkdir -p "$(dirname "$output")" + "$llvm/llvm-strip" --strip-debug "$CARGO_TARGET_DIR/$target/release/libeq_report_pic.so" -o "$output" + "$llvm/llvm-nm" -D --defined-only "$output" | awk '{print $NF}' \ + | LC_ALL=C sort | diff - "$symbols" + "$llvm/llvm-readelf" --program-headers --wide "$output" \ + | awk '$1 == "LOAD" {n++; if ($NF != "0x4000") exit 1} END {if (!n) exit 1}' + done + "$llvm/clang" --version > "$scratch/android/toolchain.txt" + printf 'NDK %s, API 26\n' "$ndk_version" >> "$scratch/android/toolchain.txt" + ;; +esac + +# Preserve the fonts' embedded licenses and ship the dependency notices with +# the runtime. The native archive and the basemap are not checked into DPIP. +cp assets/fonts/*.ttf "$scratch/fonts/" +sysroot="$(rustup run "$toolchain" rustc --print sysroot)" +cp "$sysroot/share/doc/rust/COPYRIGHT-library.html" "$scratch/fonts/rust-library-copyright.html" +{ + printf 'eq-report-pic source revision: %s\n' "$revision" + find vendor -maxdepth 2 -type f \( -iname 'license*' -o -iname 'copying*' -o -iname 'notice*' \) \ + | LC_ALL=C sort | while IFS= read -r notice; do + printf '\n--- %s ---\n' "$notice" + cat "$notice" + printf '\n' + done +} > "$scratch/fonts/third-party-notices.txt" +rustup run "$toolchain" rustc -Vv >> "$scratch/$platform/toolchain.txt" +printf '%s\n' "$revision" > "$scratch/$platform/source-revision.txt" +mkdir -p "$runtime/$platform" +rsync -a --delete "$scratch/$platform/" "$runtime/$platform/" +cp "$scratch/fonts/"* "$root/assets/fonts/report/" +cd "$root" +{ + find "native/eq_report_pic/$platform" -type f ! -name SHA256SUMS + printf '%s\n' assets/fonts/report/*.ttf assets/fonts/report/OFL.txt \ + assets/fonts/report/README.md assets/fonts/report/third-party-notices.txt \ + assets/fonts/report/rust-library-copyright.html +} | LC_ALL=C sort | while IFS= read -r artifact; do + shasum -a 256 "$artifact" +done | tee "$runtime/$platform/SHA256SUMS" diff --git a/tool/qa/fixtures/report_picture_v2.json b/tool/qa/fixtures/report_picture_v2.json new file mode 100644 index 000000000..3655cb417 --- /dev/null +++ b/tool/qa/fixtures/report_picture_v2.json @@ -0,0 +1,99 @@ +{ + "schema_version": 2, + "source": { + "namespace": "example.synthetic", + "report_id": "modern-42", + "event_id": { + "namespace": "example.events", + "id": "42" + }, + "revision": null, + "publication": { + "issued_at_unix_ms": 1577808100000, + "valid_until_unix_ms": 1577808200000 + }, + "scale_evidence": { + "kind": "dataset_contract", + "reference": "Synthetic fixture scale contract" + } + }, + "locale": "zh-Hant", + "report": { + "origin_time_unix_ms": 1577808000000, + "epicenter": { + "lon_e6": 121560000, + "lat_e6": 23978000 + }, + "location": { + "zh-Hant": "花蓮縣近海", + "en-US": "Offshore \"Hualien\" / East 🗺 é \\ " + }, + "magnitude": { + "kind": "ml", + "centi": 570 + }, + "depth_m": 12100, + "intensity_scale": "cwa-2020", + "published_max_intensity": 0, + "areas": [ + { + "id": "TW-HUA", + "name": { + "zh-Hant": "花蓮縣", + "en-US": "Hualien County" + }, + "intensity": 6 + }, + { + "id": "TW-ILA", + "name": { + "zh-Hant": "宜蘭縣" + }, + "intensity": 0 + }, + { + "id": "TW-CHA", + "name": { + "zh-Hant": "彰化縣" + } + } + ], + "observations": [ + { + "id": "cwa:station:Z02", + "area_id": "TW-HUA", + "name": { + "zh-Hant": "花蓮" + }, + "position": null, + "intensity": 7, + "station_id": { + "namespace": "example.stations", + "id": "42" + } + }, + { + "id": "cwa:station:A01", + "area_id": "TW-ILA", + "name": { + "zh-Hant": "南澳" + }, + "position": { + "lat_e6": 24465000, + "lon_e6": 121801000 + }, + "intensity": null + } + ] + }, + "map": { + "dataset_id": "taiwan-boundaries", + "dataset_revision": "2020.1", + "viewport": { + "west_e6": 119000000, + "south_e6": 22000000, + "east_e6": 123000000, + "north_e6": 26000000 + } + } +} diff --git a/tool/qa/report_picture_smoke.dart b/tool/qa/report_picture_smoke.dart new file mode 100644 index 000000000..261a249fb --- /dev/null +++ b/tool/qa/report_picture_smoke.dart @@ -0,0 +1,206 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:ui' as ui; + +import 'package:crypto/crypto.dart'; +import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; +import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/core/platform/native_library.dart'; +import 'package:dpip/shared/seismic/report_picture/report_picture.dart'; +import 'package:ffi/ffi.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +// Alternate entry point used by tool/run.sh. No app navigation is registered. +Future main() async { + final binding = WidgetsFlutterBinding.ensureInitialized(); + final status = ValueNotifier('RUNNING'); + runApp( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: ValueListenableBuilder( + valueListenable: status, + builder: (context, value, _) => Text('REPORT_PICTURE_SMOKE $value'), + ), + ), + ), + ); + await binding.endOfFrame; + try { + status.value = 'PASS ${await _smoke()}'; + Log.info('REPORT_PICTURE_SMOKE ${status.value}'); + } catch (error, stack) { + status.value = 'FAIL $error'; + Log.error('REPORT_PICTURE_SMOKE FAIL', error, stack); + rethrow; + } +} + +Future _smoke() async { + const expected = String.fromEnvironment( + 'DPIP_REPORT_PICTURE_EXPECT', + defaultValue: 'ready', + ); + final opened = await ReportPicture.open(); + if (expected != 'ready') { + final reason = ReportPictureFailureReason.values.byName(expected); + _requireFailure(opened, reason); + return 'open=$expected'; + } + final picture = _requireValue(opened); + + try { + final abi = _readAbi(); + _check( + abi == (0x00010002, 0x11f), + 'Unexpected native ABI or capabilities: $abi', + ); + + final bytes = base64Decode( + const String.fromEnvironment('DPIP_REPORT_PICTURE_FIXTURE'), + ); + _check( + sha256.convert(bytes).toString() == + '702a04ecdcd5fe7c81a45de86e122296cd3e30014b395a1ae52c351eb797f9f1', + 'Unexpected v2 fixture', + ); + + final first = picture.renderSharePngV2(bytes); + final invalid = picture.renderSharePngV2( + Uint8List.fromList(utf8.encode('{')), + ); + final callerBuffer = Uint8List.fromList(bytes); + final recovered = picture.renderSharePngV2(callerBuffer); + callerBuffer.fillRange(0, callerBuffer.length, 0); + + var completed = false; + unawaited( + first.then((_) { + completed = true; + }), + ); + await Future.delayed(Duration.zero); + _check( + !completed, + 'The root isolate did not yield while the render was pending', + ); + + final dispose = picture.dispose(); + _requireFailure( + await picture.renderSharePngV2(bytes), + ReportPictureFailureReason.disposed, + ); + final png = _requireValue(await first); + _requireFailure( + await invalid, + ReportPictureFailureReason.invalidInput, + nativeStatus: -1, + ); + final nextPng = _requireValue(await recovered); + await dispose; + + // Decode the original result after subsequent renders and native disposal. + _check( + listEquals(png, nextPng), + 'Identical requests returned different PNG bytes', + ); + final codec = await ui.instantiateImageCodec(png); + try { + final frame = await codec.getNextFrame(); + try { + _check( + frame.image.width == 1920 && frame.image.height == 1080, + 'Unexpected decoded dimensions', + ); + } finally { + frame.image.dispose(); + } + } finally { + codec.dispose(); + } + + final reopened = _requireValue(await ReportPicture.open()); + try { + _requireFailure( + await reopened.renderSharePngV2(Uint8List(1024 * 1024 + 1)), + ReportPictureFailureReason.limitExceeded, + ); + final badVersion = utf8 + .decode(bytes) + .replaceFirst('"schema_version": 2', '"schema_version": 3'); + _requireFailure( + await reopened.renderSharePngV2(utf8.encode(badVersion)), + ReportPictureFailureReason.unsupportedVersion, + nativeStatus: -2, + ); + final dark = _requireValue( + await reopened.renderSharePngV2(bytes, theme: EqTheme.dark), + ); + _check(!listEquals(png, dark), 'Dark theme did not change the output'); + _check( + listEquals(png.sublist(0, 8), const [137, 80, 78, 71, 13, 10, 26, 10]), + 'Unexpected PNG signature', + ); + } finally { + await reopened.dispose(); + } + return 'ABI=1.2 caps=0x11f exports=9 decoded=1920x1080 ' + 'bytes=${png.length} sha256=${sha256.convert(png)} ' + 'root-event=responsive invalid=-1 version=-2 retry=pass dispose=pass reopen=pass'; + } finally { + await picture.dispose(); + } +} + +(int, int) _readAbi() { + final library = _requireValue(NativeLibrary.open(ReportPicture.libraryName)); + for (final symbol in const [ + 'eqr_renderer_new', + 'eqr_renderer_free', + 'eqr_render_png', + 'eqr_bytes_free', + 'eqr_last_error', + 'eqr_version', + 'eqr_abi_info', + 'eqr_render_share_png', + 'eqr_render_share_png_v2', + ]) { + _check(library.providesSymbol(symbol), 'Missing $symbol'); + } + final info = library + .lookupFunction< + Uint32 Function(Pointer), + int Function(Pointer) + >('eqr_abi_info'); + return using((arena) { + final capabilities = arena(); + final version = info(capabilities); + return (version, capabilities.value); + }); +} + +T _requireValue(Result result) => result.when( + ok: (value) => value, + err: (failure) => throw StateError(failure.message), +); + +void _requireFailure( + Result result, + ReportPictureFailureReason reason, { + int? nativeStatus, +}) { + final failure = result.failureOrNull; + _check( + failure is ReportPictureFailure && + failure.reason == reason && + failure.nativeStatus == nativeStatus, + 'Expected ${reason.name} ($nativeStatus), got ${failure?.message}', + ); +} + +void _check(bool condition, String message) { + if (!condition) throw StateError(message); +}