diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 50fc291c7..b28884349 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -352,6 +352,43 @@ radio and takes every other channel with it. prefer platform channels / built-ins over third-party plugins where practical (e.g. `core/platform/` device_info, compass). +### Native libraries (FFI) + +The landscape earthquake-report share image is drawn by a Rust library, +[`ExpTechTW/eq-report-pic`](https://github.com/ExpTechTW/eq-report-pic), called +through `dart:ffi`. It is groundwork, not a shipped feature: no screen calls it +yet, and the repository contains no native binary, so `ReportPicture.open()` +returns `ReportPictureFailure(unavailable)` in every build until the packaging +step below is run. + +The Dart side is `shared/seismic/report_picture/`: a copy of the library's own +binding (keep it in step with the upstream file; the local edits are marked +`DPIP:`), and `ReportPicture`, which owns the native handle and hands each +render to a throwaway isolate. The drawing itself — basemap, clustering, font +layout — is the library's job, which is why it is not reimplemented in Flutter. + +- **Opening** goes through `core/platform/native_library.dart`. iOS links the + library into the app, so the symbols are already in the process + (`DynamicLibrary.process`, and the static archive needs `-force_load` plus + the six `_eqr_*` symbols kept alive in Runner's `OTHER_LDFLAGS`). Every other + target opens a packaged file: `libeq_report_pic.so` on Android/Linux, + `libeq_report_pic.dylib` on macOS, `eq_report_pic.dll` on Windows. +- **A missing library is a `Result`, never a throw.** A build that skipped the + native step must still alert people about an earthquake; it just cannot draw + this one image. +- **Isolates**: a `DynamicLibrary` handle cannot cross an isolate boundary, so + each render isolate opens the library again and adopts the renderer by + address. The native renderer is thread-safe and may be shared that way; only + the isolate that created it frees it. +- **Fonts** are the app's assets (`assets/fonts/report/`), passed once at + creation in fallback order. The library does not embed them: 13.8 MB per + Android ABI is the alternative. The copy keeps the exact three files + cwa-eq-map draws with, so the two render the same image. +- **Packaging** is a build step outside Flutter: `cargo ndk` into + `android/app/src/main/jniLibs//`, and an xcframework whose static + archive is force-loaded into Runner. Nothing in `lib/` builds Rust, so a + missing toolchain cannot break a normal Flutter build. + ## Persistence everything persisted lives in **SQLite**. Flutter's stores are split diff --git a/assets/fonts/report/GenShinGothic-Bold.ttf b/assets/fonts/report/GenShinGothic-Bold.ttf new file mode 100644 index 000000000..dc68e0518 Binary files /dev/null and b/assets/fonts/report/GenShinGothic-Bold.ttf differ diff --git a/assets/fonts/report/NotoSansTC-Black.ttf b/assets/fonts/report/NotoSansTC-Black.ttf new file mode 100644 index 000000000..63487cb1e Binary files /dev/null and b/assets/fonts/report/NotoSansTC-Black.ttf differ diff --git a/assets/fonts/report/README.md b/assets/fonts/report/README.md new file mode 100644 index 000000000..58005f12f --- /dev/null +++ b/assets/fonts/report/README.md @@ -0,0 +1,25 @@ +# Report-image fonts + +The three TTFs here are the fonts the native report-image renderer +(`ExpTechTW/eq-report-pic`, called over FFI) lays text out with. They are the +same files cwa-eq-map uses, so both draw the same image, and they are copied +from that library's `assets/fonts/` rather than sourced separately: the +renderer's fallback order is part of how an image looks, and a different cut of +the same family would move the text. + +| 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 full licence text is in each font's own `name` table (name IDs 13 and 14), +which is where the licence requires it to stay. + +They are **not** embedded in the Rust library: doing that would add 13.8 MB to +every Android ABI. `ReportPicture` loads them from `rootBundle` and hands the +bytes over once, in the order listed above, when the renderer is created. + +When updating them, update `fontAssets` in +`lib/shared/seismic/report_picture/report_picture.dart` and the asset list in +`pubspec.yaml` together — the renderer's fallback order is the list order. diff --git a/assets/fonts/report/mplus-2p-bold.ttf b/assets/fonts/report/mplus-2p-bold.ttf new file mode 100644 index 000000000..9c8aad366 Binary files /dev/null and b/assets/fonts/report/mplus-2p-bold.ttf differ diff --git a/lib/core/error/failure.dart b/lib/core/error/failure.dart index a36b5222f..6e7041cd2 100644 --- a/lib/core/error/failure.dart +++ b/lib/core/error/failure.dart @@ -111,3 +111,26 @@ final class WidgetSnapshotFailure extends Failure { final WidgetSnapshotFailureReason reason; } + +/// Why a native share-image render failed. +enum ReportPictureFailureReason { + /// This build carries no `eq-report-pic` library for the device, or the one + /// it carries does not export the ABI the app was built against. + unavailable, + + /// The library was there and the render itself failed — bad report JSON, or + /// a bug inside the renderer. + renderFailed, +} + +/// A landscape earthquake-report image could not be drawn by the native +/// renderer. +/// +/// Its own type because the recovery differs: a missing library is a build +/// problem and no retry helps, while a failed render can be retried or, if it +/// keeps failing, fall back to the Flutter-drawn card. +final class ReportPictureFailure extends Failure { + const ReportPictureFailure(this.reason, super.message); + + final ReportPictureFailureReason reason; +} 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..29716d77e --- /dev/null +++ b/lib/shared/seismic/report_picture/eq_report_pic_bindings.dart @@ -0,0 +1,201 @@ +/// Dart binding for the eq_report_pic C ABI (`include/eq_report_pic.h`). +/// +/// Copied from ExpTechTW/eq-report-pic `dart/lib/eq_report_pic.dart` at +/// c6d3420, so the app and the library's own CLI read the ABI the same way. +/// Keep it in step with that file; the two local changes are both marked +/// "DPIP:" below. +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 _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'; +} + +/// 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) + : _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'); + + // DPIP: the upstream `open()` factory is gone. `NativeLibrary` in + // `core/platform/native_library.dart` owns the platform-to-file mapping and + // reports a missing library as a `Result` instead of throwing here. + + final _NewDart _new; + final _FreeDart _free; + final _RenderDart _render; + final _BytesFreeDart _bytesFree; + final Pointer Function() _lastError; + final Pointer Function() _version; + + // DPIP: a renderer is created inside the render isolate, but the handle is + // owned by the caller's isolate. This frees it from there; the ABI has no + // isolate affinity, only the `DynamicLibrary` does. + void freeRenderer(int address) => + _free(Pointer<_EqrRenderer>.fromAddress(address)); + + 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'); + final input = malloc(json.isEmpty ? 1 : json.length); + final outPtr = malloc>(); + final outLen = malloc(); + try { + input.asTypedList(json.length).setAll(0, json); + final rc = _b._render( + _handle, + input, + json.length, + scale, + mode.index, + theme.index, + outPtr, + outLen, + ); + if (rc != 0) { + throw EqReportPicException(_b._error('eqr_render_png failed')); + } + final png = Uint8List.fromList(outPtr.value.asTypedList(outLen.value)); + _b._bytesFree(outPtr.value, outLen.value); + return png; + } finally { + malloc.free(input); + malloc.free(outPtr); + malloc.free(outLen); + } + } + + 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..10f75e8af --- /dev/null +++ b/lib/shared/seismic/report_picture/report_picture.dart @@ -0,0 +1,240 @@ +import 'dart:ffi'; +import 'dart:isolate'; + +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/eq_report_pic_bindings.dart'; +import 'package:flutter/services.dart'; + +/// How stations are drawn on the report image's map. +enum ReportPictureMode { cluster, stations, towns } + +/// The report image's colour theme. +enum ReportPictureTheme { light, dark } + +/// A landscape 1920×1080 PNG of one CWA earthquake report. +/// +/// The image is drawn by `ExpTechTW/eq-report-pic`, a pure-Rust library called +/// over `dart:ffi`; it is the same drawing cwa-eq-map's share images use, and +/// one render takes about 60 ms. Keeping it out of Flutter is the point: the +/// map, the clustering and the font layout are the renderer's job, and the UI +/// isolate only receives bytes. +abstract interface class ReportPictureRenderer { + /// Renders [reportJson] — the body of `/api/v2/eq/report/{id}` — to a PNG. + /// + /// [scale] multiplies the 1920×1080 layout, up to 4×. The work happens on a + /// fresh isolate, so this is safe to call from a frame callback and the + /// result can be written straight to the share sheet or the photo library. + Future> render( + Uint8List reportJson, { + double scale = 1.0, + ReportPictureMode mode = ReportPictureMode.cluster, + ReportPictureTheme theme = ReportPictureTheme.light, + }); + + /// Releases the native renderer. Safe to call more than once. + /// + /// Render in flight at the same time must have completed first: the handle + /// is what they are drawing into. + void dispose(); +} + +/// A test seam: production opens the packaged library, tests supply their own +/// answer because the host they run on has no native artifact. +typedef NativeLibraryOpener = Result Function(String name); + +/// Opens the native report-image renderer. +/// +/// This is readiness plumbing, not a feature yet: no screen calls it, and the +/// app ships without the native binary, so [open] answers +/// [ReportPictureFailureReason.unavailable] until a build adds one. See +/// ARCHITECTURE.md → Native libraries. +abstract final class ReportPicture { + /// The native library's base name; [NativeLibrary] adds the platform's file + /// name and extension. + static const String libraryName = 'eq_report_pic'; + + /// TTF bytes in the renderer's fallback order. They are assets of the app, + /// not of the library: embedding them in a `cdylib` would put a 13.8 MB copy + /// in every Android ABI, and the caller must pass them once at creation. + static const List fontAssets = [ + 'assets/fonts/report/mplus-2p-bold.ttf', + 'assets/fonts/report/GenShinGothic-Bold.ttf', + 'assets/fonts/report/NotoSansTC-Black.ttf', + ]; + + /// Creates a renderer, or explains why this build cannot. + /// + /// Parsing the fonts and decoding the embedded basemap happen once and are + /// what makes creation slow (~170 ms); they run on a throwaway isolate so + /// opening the share sheet does not drop frames. + static Future> open({ + NativeLibraryOpener? openLibrary, + }) async { + final probe = (openLibrary ?? NativeLibrary.open)(libraryName); + final library = probe.valueOrNull; + if (library == null) { + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + probe.failureOrNull?.message ?? + 'Native library "$libraryName" is not available', + ), + ); + } + + final EqReportPicBindings bindings; + try { + // Looking the symbols up here, not on first render, is deliberate: a + // library built from an older ABI fails at open, where the caller can + // fall back to the Flutter-drawn card, rather than mid-render. + bindings = EqReportPicBindings(library); + } catch (error) { + Log.warning( + 'report picture: $libraryName does not export the ABI: $error', + ); + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + 'Native library "$libraryName" does not export the expected symbols: $error', + ), + ); + } + + final List fonts; + try { + fonts = await _loadFonts(); + } catch (error) { + Log.warning('report picture: fonts unavailable: $error'); + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + 'Bundled report fonts are missing: $error', + ), + ); + } + + try { + final address = await Isolate.run(() => _createRenderer(fonts)); + return Ok(_NativeReportPictureRenderer(bindings, address)); + } catch (error) { + Log.warning('report picture: renderer creation failed: $error'); + return Err( + ReportPictureFailure( + ReportPictureFailureReason.unavailable, + 'The native report renderer could not start: $error', + ), + ); + } + } + + static Future> _loadFonts() async { + final fonts = []; + for (final asset in fontAssets) { + final data = await rootBundle.load(asset); + fonts.add( + data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), + ); + } + return fonts; + } +} + +/// Runs on the render isolate: `DynamicLibrary` cannot cross an isolate +/// boundary, so each one opens the library itself, then adopts the handle the +/// main isolate owns by address. +int _createRenderer(List fonts) { + final result = NativeLibrary.open(ReportPicture.libraryName); + final library = result.valueOrNull; + if (library == null) throw StateError(result.failureOrNull!.message); + return EqReportPic.create(EqReportPicBindings(library), fonts).address; +} + +/// The render itself, on its own isolate. The native renderer is thread-safe +/// and may be used by several isolates at once; only the owner frees it. +Uint8List _renderInIsolate( + int address, + Uint8List reportJson, + double scale, + int mode, + int theme, +) { + final result = NativeLibrary.open(ReportPicture.libraryName); + final library = result.valueOrNull; + if (library == null) throw StateError(result.failureOrNull!.message); + return EqReportPic.fromAddress( + EqReportPicBindings(library), + address, + ).renderPng( + reportJson, + scale: scale, + mode: EqMapMode.values[mode], + theme: EqTheme.values[theme], + ); +} + +final class _NativeReportPictureRenderer implements ReportPictureRenderer { + _NativeReportPictureRenderer(this._bindings, this._address); + + final EqReportPicBindings _bindings; + int? _address; + + @override + Future> render( + Uint8List reportJson, { + double scale = 1.0, + ReportPictureMode mode = ReportPictureMode.cluster, + ReportPictureTheme theme = ReportPictureTheme.light, + }) async { + final address = _address; + if (address == null) { + return const Err( + ReportPictureFailure( + ReportPictureFailureReason.renderFailed, + 'The report picture renderer has been disposed', + ), + ); + } + + try { + final png = await Isolate.run( + () => _renderInIsolate( + address, + reportJson, + scale.clamp(1.0, 4.0).toDouble(), + mode.index, + theme.index, + ), + ); + return Ok(png); + } catch (error) { + // The ABI turns a panic into an error code and an `eqr_last_error` on + // the isolate that hit it, so the message arrives here as the exception + // text. Keep it: "invalid report" and "renderer bug" look identical + // otherwise. + Log.warning('report picture: render failed: $error'); + return Err( + ReportPictureFailure( + ReportPictureFailureReason.renderFailed, + 'The report picture could not be rendered: $error', + ), + ); + } + } + + @override + void dispose() { + final address = _address; + if (address == null) return; + _address = null; + try { + _bindings.freeRenderer(address); + } catch (error) { + // Losing the free leaks one renderer, which the process gets back on + // exit; throwing here would take down the caller for a bookkeeping slip. + Log.warning('report picture: freeing the renderer failed: $error'); + } + } +} diff --git a/pubspec.lock b/pubspec.lock index 78326b6ca..1fb16c088 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -273,7 +273,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 388a4b3f3..62b4de26c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -41,6 +41,10 @@ dependencies: # (iOS 15.0, minSdk 23). Every later 5.2.x requires a newer firebase_core — # which is the bump the pin above exists to stop. firebase_crashlytics: 5.2.4 + # Direct because the report-image renderer allocates and reads native memory + # itself (`shared/seismic/report_picture`). Already in the lock through the + # SDK tooling; naming it is what makes the import legal. + ffi: ^2.2.0 flutter: sdk: flutter flutter_localizations: @@ -204,6 +208,14 @@ flutter: - assets/map/basemap_seed/ - assets/travel_time.json.gz - assets/astro/ + # Fonts for the native report-image renderer (ExpTechTW/eq-report-pic). + # The library does not embed them — that would put a 13.8 MB copy in every + # Android ABI — so they travel as assets and are handed to it once, in this + # order, when the renderer is created. Same three as cwa-eq-map: M+ 2p for + # the monospaced digits, Gen Shin Gothic and Noto Sans TC for place names. + - assets/fonts/report/mplus-2p-bold.ttf + - assets/fonts/report/GenShinGothic-Bold.ttf + - assets/fonts/report/NotoSansTC-Black.ttf # Weather glyphs Flutter's bundled MaterialIcons font simply does not have — # there is no rain icon in it at all. A 6.7 KB subset of Material Symbols 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/test/shared/seismic/report_picture_test.dart b/test/shared/seismic/report_picture_test.dart new file mode 100644 index 000000000..fc7d8789b --- /dev/null +++ b/test/shared/seismic/report_picture_test.dart @@ -0,0 +1,57 @@ +import 'dart:ffi'; + +import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; +import 'package:dpip/shared/seismic/report_picture/report_picture.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('fonts', () { + test('every font the renderer is given is bundled and non-empty', () async { + expect(ReportPicture.fontAssets, hasLength(3)); + for (final asset in ReportPicture.fontAssets) { + final data = await rootBundle.load(asset); + expect( + data.lengthInBytes, + greaterThan(100 * 1024), + reason: '$asset looks truncated', + ); + } + }); + }); + + group('ReportPicture.open', () { + test('an unavailable library is a Result, not a throw', () async { + final result = await ReportPicture.open( + openLibrary: (_) => const Err(UnexpectedFailure('missing')), + ); + + final failure = result.failureOrNull; + expect(failure, isA()); + expect( + (failure! as ReportPictureFailure).reason, + ReportPictureFailureReason.unavailable, + ); + expect(failure.message, contains('missing')); + }); + + test('a library without the ABI fails at open, not mid-render', () async { + // The host process has no `eqr_*` symbols, so the lookup in the bindings + // is the same thing an older ABI would trigger on a real library. + final result = await ReportPicture.open( + openLibrary: (_) => Ok(DynamicLibrary.process()), + ); + + final failure = result.failureOrNull; + expect(failure, isA()); + expect( + (failure! as ReportPictureFailure).reason, + ReportPictureFailureReason.unavailable, + ); + expect(failure.message, contains('symbols')); + }); + }); +}