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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
65 changes: 65 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8List>` 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 <simulator-or-emulator-id> --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`):
Expand Down
3 changes: 3 additions & 0 deletions android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
95 changes: 95 additions & 0 deletions assets/fonts/report/OFL.txt
Original file line number Diff line number Diff line change
@@ -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.
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

`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.
1 change: 1 addition & 0 deletions ios/Flutter/Debug.xcconfig
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#include "Generated.xcconfig"
#include? "../../native/eq_report_pic/ios/link.xcconfig"
1 change: 1 addition & 0 deletions ios/Flutter/Release.xcconfig
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#include "Generated.xcconfig"
#include? "../../native/eq_report_pic/ios/link.xcconfig"
6 changes: 6 additions & 0 deletions ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand Down
18 changes: 18 additions & 0 deletions lib/core/error/failure.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Comment on lines +126 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
ReportPictureFailure 的設計與 NativeLibrary.open 回傳的錯誤類型存在斷層。NativeLibrary.open 目前僅回傳通用的 UnexpectedFailure,這使得業務層在捕獲錯誤時,難以精確地將其轉換為 ReportPictureFailureReason(例如辨別是 unavailable 還是其他原因),建議在錯誤處理流程中加入更明確的錯誤分類機制。

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',
};
Comment on lines +17 to +25

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · low
nativeLibraryFileName 的映射邏輯目前依賴於手動維護各平台的檔名規範,建議未來若增加更多平台時,能更嚴謹地檢查各平台的動態庫命名規範,以確保擴展性。


/// 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);
Comment on lines +59 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
NativeLibrary.open 中的 openProcess 處理邏輯存在潛在的 Runtime Bug。當 openProcess 為 null 時,程式碼會嘗試執行 DynamicLibrary.process(),但 DynamicLibrary.process 是一個 getter 而非函數,這會導致 NoSuchMethodError。建議將 fallback 改為 () => DynamicLibrary.process 以確保類型一致性。

Suggestion:

Suggested change
final library = fileName == null
? (openProcess ?? DynamicLibrary.process)()
: (openFile ?? DynamicLibrary.open)(fileName);
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,
};
}
Loading
Loading