Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<abi>/`, 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
Expand Down
Binary file added assets/fonts/report/GenShinGothic-Bold.ttf
Binary file not shown.
Binary file added assets/fonts/report/NotoSansTC-Black.ttf
Binary file not shown.
25 changes: 25 additions & 0 deletions assets/fonts/report/README.md
Original file line number Diff line number Diff line change
@@ -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.
Binary file added assets/fonts/report/mplus-2p-bold.ttf
Binary file not shown.
23 changes: 23 additions & 0 deletions lib/core/error/failure.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
85 changes: 85 additions & 0 deletions lib/core/platform/native_library.dart
Original file line number Diff line number Diff line change
@@ -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<DynamicLibrary> 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,
};
}
201 changes: 201 additions & 0 deletions lib/shared/seismic/report_picture/eq_report_pic_bindings.dart
Original file line number Diff line number Diff line change
@@ -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<Uint8>>,
Pointer<Size>,
Size,
);
typedef _NewDart = Pointer<_EqrRenderer> Function(
Pointer<Pointer<Uint8>>,
Pointer<Size>,
int,
);
typedef _FreeC = Void Function(Pointer<_EqrRenderer>);
typedef _FreeDart = void Function(Pointer<_EqrRenderer>);
typedef _RenderC = Int32 Function(
Pointer<_EqrRenderer>,
Pointer<Uint8>,
Size,
Float,
Uint32,
Uint32,
Pointer<Pointer<Uint8>>,
Pointer<Size>,
);
typedef _RenderDart = int Function(
Pointer<_EqrRenderer>,
Pointer<Uint8>,
int,
double,
int,
int,
Pointer<Pointer<Uint8>>,
Pointer<Size>,
);
typedef _BytesFreeC = Void Function(Pointer<Uint8>, Size);
typedef _BytesFreeDart = void Function(Pointer<Uint8>, int);
typedef _StrC = Pointer<Utf8> 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<Utf8> Function() _lastError;
final Pointer<Utf8> 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<Uint8List> fonts) {
final ptrs = malloc<Pointer<Uint8>>(fonts.length);
final lens = malloc<Size>(fonts.length);
final buffers = <Pointer<Uint8>>[];
try {
for (var i = 0; i < fonts.length; i++) {
final buf = malloc<Uint8>(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<Uint8>(json.isEmpty ? 1 : json.length);
final outPtr = malloc<Pointer<Uint8>>();
final outLen = malloc<Size>();
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;
}
}
Loading
Loading