Compare commits

...
26 Commits
Author SHA1 Message Date
OpenClaw 1527d558d4 fix: complete entry build-profile target 2026-03-10 17:04:47 +08:00
OpenClaw cfe2dfc815 fix: align entry build-profile target per hvigor doc 2026-03-10 16:17:03 +08:00
OpenClaw e590a5a28f fix: add entry build-profile target definition 2026-03-10 15:59:55 +08:00
OpenClaw 4bcee5ba9f chore: update core execution backlog 2026-03-10 15:47:41 +08:00
OpenClaw d95694d934 fix: add missing entry hvigorfile 2026-03-10 09:52:22 +08:00
OpenClaw 0a221c5405 fix: add hvigor development config version 2026-03-09 20:23:00 +08:00
OpenClaw 644887278a chore: add init prerequisite check script 2026-03-09 20:13:53 +08:00
OpenClaw c82c1439a7 fix: make HarmonyOS project initialization reproducible 2026-03-09 19:55:11 +08:00
OpenClaw 4613919277 feat: wire pullFrame path and runtime placeholder rendering 2026-03-09 18:50:42 +08:00
OpenClaw bde990ac82 feat: tighten ArkTS shell demo closure and runtime entry hints 2026-03-09 18:48:20 +08:00
OpenClaw a14b10d62f feat: connect run page to native smoke startup flow 2026-03-09 18:39:38 +08:00
OpenClaw 06f4a95020 feat: wire HarmonyOS entry module to native napi skeleton 2026-03-09 17:36:14 +08:00
OpenClaw 6c99ae75f6 feat: add minimal HarmonyOS standard project shell 2026-03-09 17:13:12 +08:00
OpenClaw 8b6e24fa61 feat: add minimal HarmonyOS native napi skeleton 2026-03-09 17:05:17 +08:00
OpenClaw e328780ee5 docs: add execution backlog, task sheet, and research survey 2026-03-09 16:57:00 +08:00
OpenClaw 0a23c3813d feat: add runtime startup mock flow and import reset 2026-03-09 15:42:25 +08:00
OpenClaw 36671fd8c1 feat: refresh app list after mock import flow 2026-03-09 15:36:44 +08:00
OpenClaw bbf4123844 docs: add HarmonyOS integration prerequisites v1 2026-03-09 15:23:41 +08:00
OpenClaw 3b0b9db791 docs: add HarmonyOS POC execution package v1 2026-03-09 15:22:50 +08:00
OpenClaw eaf07f1902 feat: add ArkTS shell route placeholder flow 2026-03-09 15:22:45 +08:00
OpenClaw 04cb1178dd feat: add mock adapter data for ArkTS shell demo flow 2026-03-09 15:01:27 +08:00
OpenClaw 7fb4e6117a feat: add minimal reactive store linkage for ArkTS shell 2026-03-09 15:00:32 +08:00
OpenClaw 0b20b5dd43 feat: wire ArkTS page actions to store placeholders 2026-03-09 14:42:32 +08:00
OpenClaw 879e1526f1 feat: wire ArkTS pages with component trees 2026-03-09 14:41:25 +08:00
OpenClaw f8f18f185e feat: add ArkTS shell code skeleton placeholders 2026-03-09 14:16:11 +08:00
OpenClaw 339756c1aa docs: add ArkTS shell POC structure and contracts 2026-03-09 13:20:34 +08:00
90 changed files with 4985 additions and 38 deletions

No files matched your search

+3
View File
@@ -16,6 +16,9 @@ node_modules/
# HarmonyOS / DevEco common outputs
.local/
.cache/
local.properties
AppScope/*.p12
AppScope/*.mobileprovision
# Logs
*.log
+8
View File
@@ -0,0 +1,8 @@
{
"app": {
"bundleName": "com.xiaobai.mrpsimulator",
"vendor": "xiaobai",
"versionCode": 1000000,
"versionName": "1.0.0"
}
}
+95 -38
View File
@@ -1,53 +1,110 @@
# MRP Simulator HarmonyOS
MRP 模拟器鸿蒙化项目。
HarmonyOS 侧的 MRP 模拟器 POC/Alpha 工程。
当前目标不是直接做“大而全”的正式产品,而是先完成一轮 **HarmonyOS 技术验证 / POC**,验证现有 MRP 模拟器能力是否能在鸿蒙侧形成稳定闭环。
当前代码状态不是“纯方案仓库”,而是已经包含:
- **标准 HarmonyOS/DevEco 工程壳**
- **ArkTS 壳层页面与运行页占位链路**
- **Native/NAPI/C++ 最小骨架**
- **RunPage -> Native smoke start -> pullFrame() 占位渲染** 的首轮联调路径
## 当前阶段
---
处于 **第一阶段:方案收敛 + 技术验证准备**。
当前共识:
- 一期按 **POC / Alpha** 推进
- 先做 **单实例、本地导入、可启动、可渲染、可输入、可退出、可存档**
- 推荐路线:
- **ArkTS 做应用壳/UI**
- **C++ 做模拟器核心**
- **NAPI 做粗粒度桥接**
- 服务端/BFF 暂不进入运行时闭环,只在后续按需参与外围能力
## 目录说明
## 当前仓库结构(最小可导入)
```text
.
├─ docs/
│ ├─ project/
│ ├─ product/
│ ├─ architecture/
│ ├─ harmonyos/
│ └─ qa/
├─ research/
├─ prototypes/
└─ scripts/
├─ AppScope/
│ └─ app.json5
├─ build-profile.json5
├─ hvigorfile.ts
├─ hvigorw
├─ hvigorw.bat
├─ local.properties.example
├─ oh-package.json5
├─ entry/
│ ├─ build-profile.json5
│ ├─ oh-package.json5
│ └─ src/main/
│ ├─ module.json5
│ ├─ ets/
│ ├─ cpp/
│ └─ resources/
└─ README.md
```
## 当前文档
---
- 项目链路:`docs/project/AGENT_CHAIN.md`
- 项目概览:`docs/project/PROJECT_OVERVIEW.md`
- 一期范围:`docs/product/MVP_SCOPE.md`
- 第一轮架构判断:`docs/architecture/ARCHITECTURE_V1.md`
- 鸿蒙技术路线:`docs/harmonyos/HARMONYOS_TECH_ROUTE_V1.md`
- 下一步行动项:`docs/project/NEXT_ACTIONS.md`
## 先说明 3 个容易误解的点
## 下一步
### 1. `local.properties`
这是**本地机器文件**,不应提交真实值进仓库。
仓库提供了:
- `local.properties.example`
1. 明确现有 MRP 模拟器代码资产与语言栈
2. 识别可复用核心与必须重写部分
3. 建立 HarmonyOS POC 工程骨架
4. 选定首批样例集并形成验证基线
你需要自己复制一份:
## 状态说明
```bash
cp local.properties.example local.properties
```
当前仓库以 **方案与技术验证文档** 为主,代码实现将在明确现有内核资产后逐步落地。
然后把 `hwsdk.dir` 改成你本机 HarmonyOS SDK 路径。
### 2. 签名文件
仓库**不再引用**不存在的:
- `AppScope/debug.p12`
- `AppScope/debug.mobileprovision`
原因:这些是本地/团队环境相关文件,硬编码到仓库会直接阻塞初始化。
### 3. `hvigorw` / `hvigorw.bat`
已补入仓库。它们会优先调用:
- 本地 `node_modules/.bin/hvigor`
- 或系统中的 `hvigor`
如果你的环境里还没有 `hvigor`,先用 DevEco Studio 打开项目同步,或自行安装 hvigor。
---
## 初始化步骤(可复现)
### 方式 A:DevEco Studio 导入(推荐)
1. 克隆仓库
2. 复制模板:`local.properties.example -> local.properties`
3. 修改 `local.properties` 中的 `hwsdk.dir`
4. 用 DevEco Studio 打开**仓库根目录**
5. 等待工程同步完成
6. 如需构建/运行,在 DevEco 中补本地调试签名配置
### 方式 B:命令行初始化
前提:本机已具备 `node` 和 `hvigor`
```bash
cp local.properties.example local.properties
# 编辑 local.properties,填入 hwsdk.dir
./hvigorw tasks
```
如果 `./hvigorw` 提示找不到 `hvigor`,先回到方式 A,用 DevEco 完成首次同步。
---
## 当前可验证结果
当前工程已具备以下最小可验证链路:
- `EntryAbility` 可加载 `ShellRootPage`
- 运行页可进入 native smoke 启动路径
- `pullFrame()` 已接到 ArkTS 层
- 页面可显示测试帧元数据与测试占位渲染块
这意味着:
- **可以导入工程**
- **可以继续做 Native/NAPI 联调**
- 但**还不是完整可运行的 MRP 模拟器产品**
---
## 下一阶段重点
- 把 `pullFrame()` 的占位帧替换为真实 native 帧
- 把 `loadPackage(appId)` 替换为真实 MRP 包路径/入口
- 把输入映射从 smoke path 替换为真实内核事件分发
+60
View File
@@ -0,0 +1,60 @@
# SETUP
## 目标
让别人拿到仓库后,能按固定步骤完成:
- 初始化项目
- 导入 DevEco Studio
- 继续做 ArkTS + Native/NAPI 联调
---
## 1. 准备本地文件
仓库不提交真实 `local.properties`,请自行复制:
```bash
cp local.properties.example local.properties
```
然后修改:
```properties
hwsdk.dir=/absolute/path/to/HarmonyOS/Sdk
```
---
## 2. 导入 DevEco Studio
- 打开仓库根目录:`mrp-simulator-harmonyos`
- 等待工程同步
- 若 IDE 提示补全依赖/构建环境,按 IDE 引导完成
---
## 3. 关于签名
当前仓库已移除对不存在签名文件的硬引用。
如果你要实际构建/运行:
- 在 DevEco 中配置本地 debug signing
- 或按团队规范补本地签名材料
---
## 4. 关于 hvigorw
仓库已提供:
- `hvigorw`
- `hvigorw.bat`
如果本机还没有 `hvigor`:
- 先用 DevEco Studio 打开并同步
- 或自行安装 hvigor 后再执行命令行任务
---
## 5. 最小自检清单
导入后至少确认:
- 根目录可识别为 HarmonyOS 工程
- `entry` 模块可识别
- `entry/src/main/ets` 存在
- `entry/src/main/cpp` 存在
- `entry/src/main/resources` 存在
- `EntryAbility` 与 `ShellRootPage` 可被 IDE 正常索引
+33
View File
@@ -0,0 +1,33 @@
{
"app": {
"products": [
{
"name": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS"
}
],
"buildModeSet": [
{
"name": "debug"
},
{
"name": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}
@@ -0,0 +1,167 @@
# HOS-001 POC 文件级骨架清单(HarmonyOS POC v1)
## 目标
首周只支撑最小 POC 闭环:**初始化 → 加载包 → 启动 → 拉帧显示 → 输入 → 暂停/恢复 → 释放**。
---
## 一、ArkTS 侧骨架文件清单
```text
entry/src/main/ets/application/
├─ EntryAbility.ets
└─ AppContext.ets
entry/src/main/ets/pages/
├─ HomePage.ets
├─ EmulatorPage.ets
├─ SettingsPage.ets
└─ DebugPage.ets
entry/src/main/ets/components/
├─ EmulatorCanvas.ets
├─ KeypadOverlay.ets
└─ StatusBar.ets
entry/src/main/ets/features/mrp/facade/
└─ MrpSimulatorFacade.ets
entry/src/main/ets/features/mrp/service/
├─ SimulatorSession.ets
├─ InputMapper.ets
├─ FrameScheduler.ets
└─ PackageLoader.ets
entry/src/main/ets/features/mrp/model/
├─ SimulatorTypes.ets
├─ SimulatorState.ets
└─ KeyMapping.ets
entry/src/main/ets/features/mrp/infra/native/
├─ MrpNativeBridge.ets
└─ MrpNativeTypes.ets
entry/src/main/ets/features/mrp/infra/platform/
├─ AbilityLifecycle.ets
└─ FileAccess.ets
entry/src/main/ets/features/mrp/infra/storage/
└─ ConfigStore.ets
entry/src/main/ets/common/logger/
└─ Logger.ets
entry/src/main/ets/common/error/
└─ ErrorCode.ets
entry/src/main/ets/common/constants/
└─ MrpConstants.ets
```
### ArkTS 模块关系说明
- `pages/`:页面入口,负责编排 UI,不直接触达 native。
- `components/`:模拟器画面与按键层的纯视图组件。
- `facade/MrpSimulatorFacade.ets`:页面唯一可依赖的运行时接口。
- `service/SimulatorSession.ets`:承接生命周期、运行状态、调用顺序控制。
- `service/FrameScheduler.ets`:POC 阶段负责定时调用 `pullFrame()` 并驱动页面刷新。
- `service/InputMapper.ets`:将鸿蒙触摸/按键统一映射为模拟器输入。
- `infra/native/`:ArkTS 与 NAPI 的唯一边界层。
- `infra/platform/`:文件沙箱、Ability 生命周期等平台能力封装。
- `model/`:对齐 ArkTS ↔ Native DTO,避免页面层散落字面量结构。
---
## 二、Native/C++ 侧骨架文件清单
```text
entry/src/main/cpp/
├─ CMakeLists.txt
├─ napi/
│ ├─ module_init.cpp
│ ├─ facade_binding.cpp
│ ├─ napi_common.h
│ ├─ napi_common.cpp
│ └─ converters/
│ ├─ js_to_native.cpp
│ └─ native_to_js.cpp
├─ facade/
│ ├─ MrpFacade.h
│ └─ MrpFacade.cpp
├─ core/
│ ├─ runtime/
│ │ ├─ MrpRuntime.h
│ │ └─ MrpRuntime.cpp
│ ├─ render/
│ │ ├─ FrameBuffer.h
│ │ └─ FrameBuffer.cpp
│ ├─ input/
│ │ ├─ InputEvent.h
│ │ └─ InputDispatcher.cpp
│ ├─ fs/
│ │ ├─ VirtualFs.h
│ │ └─ VirtualFs.cpp
│ └─ types/
│ ├─ SimulatorConfig.h
│ └─ Result.h
└─ adapter/
└─ existing_core/
├─ LegacyMrpAdapter.h
└─ LegacyMrpAdapter.cpp
```
### Native 模块关系说明
- `napi/`:只做 JS/ArkTS 参数解析、返回值转换、导出注册。
- `facade/`:对 ArkTS 暴露稳定接口,不让上层感知内核细节。
- `core/runtime/`:主循环、状态流转、运行态控制。
- `core/render/`:帧缓冲、像素输出。
- `core/input/`:输入归一化、按键/触摸投递。
- `core/fs/`:工作目录、包访问、存档目录等虚拟文件系统能力。
- `adapter/existing_core/`:对接现有 MRP 模拟器内核,首周可占位。
---
## 三、首周必须先创建的最小骨架文件
### ArkTS 必须项
```text
entry/src/main/ets/pages/EmulatorPage.ets
entry/src/main/ets/components/EmulatorCanvas.ets
entry/src/main/ets/features/mrp/facade/MrpSimulatorFacade.ets
entry/src/main/ets/features/mrp/service/SimulatorSession.ets
entry/src/main/ets/features/mrp/service/FrameScheduler.ets
entry/src/main/ets/features/mrp/service/InputMapper.ets
entry/src/main/ets/features/mrp/infra/native/MrpNativeBridge.ets
entry/src/main/ets/features/mrp/model/SimulatorTypes.ets
```
### Native 必须项
```text
entry/src/main/cpp/CMakeLists.txt
entry/src/main/cpp/napi/module_init.cpp
entry/src/main/cpp/napi/facade_binding.cpp
entry/src/main/cpp/facade/MrpFacade.h
entry/src/main/cpp/facade/MrpFacade.cpp
entry/src/main/cpp/core/runtime/MrpRuntime.h
entry/src/main/cpp/core/runtime/MrpRuntime.cpp
entry/src/main/cpp/core/render/FrameBuffer.h
entry/src/main/cpp/core/render/FrameBuffer.cpp
entry/src/main/cpp/core/input/InputEvent.h
entry/src/main/cpp/core/input/InputDispatcher.cpp
```
---
## 四、首周明确不进入骨架范围的内容
- 多实例管理
- 存档读写完整实现
- 音频底层完整接入
- 调试器/脚本注入
- 兼容补丁机制
- 回调事件总线
---
## 五、一期边界结论
- ArkTS 只做壳层与编排;页面不直接调 native。
- Native 层只暴露粗粒度 facade;不暴露碎片化底层接口。
- 若缺少现有 MRP 内核接口文档,`adapter/existing_core/` 先占位,不阻塞 POC 骨架推进。
@@ -0,0 +1,176 @@
# HOS-002 最小 NAPI Facade v0
## 目标
将首周接口收敛为只支撑 POC 运行闭环的**最小必需集**,避免在接口冻结前过度设计。
---
## 一、最小 NAPI Facade 最终候选接口
> 最终保留 8 个接口;其中 `pause/resume` 视作一期必须项,因为 HarmonyOS 生命周期切换会直接用到。
### 1. `init(options: InitOptions): CommonResult`
```ts
interface InitOptions {
workDir: string
width: number
height: number
debug?: boolean
}
```
```ts
interface CommonResult {
ok: boolean
errorCode?: number
errorMessage?: string
}
```
用途:初始化工作目录、逻辑分辨率、运行环境。
---
### 2. `loadPackage(packagePath: string): CommonResult`
```ts
loadPackage(packagePath: string): CommonResult
```
用途:加载一个固定测试包/资源入口。
---
### 3. `start(): CommonResult`
```ts
start(): CommonResult
```
用途:启动模拟器主循环。
---
### 4. `pause(): CommonResult`
```ts
pause(): CommonResult
```
用途:Ability 退后台、页面失焦时暂停运行。
---
### 5. `resume(): CommonResult`
```ts
resume(): CommonResult
```
用途:从暂停状态恢复。
---
### 6. `sendInput(event: InputEvent): CommonResult`
```ts
interface InputEvent {
type: 'key' | 'touch'
action: 'down' | 'up' | 'move'
keyCode?: number
x?: number
y?: number
timestamp?: number
}
```
用途:统一输入入口,屏蔽页面层对内核输入模型的感知。
---
### 7. `pullFrame(): FrameResult`
```ts
interface FrameResult {
ok: boolean
hasNewFrame: boolean
width: number
height: number
pixelFormat: 'RGBA_8888'
buffer?: ArrayBuffer
frameId?: number
errorCode?: number
errorMessage?: string
}
```
用途:POC 阶段拉取整帧像素缓冲,优先验证链路正确性。
---
### 8. `release(): CommonResult`
```ts
release(): CommonResult
```
用途:退出页面、异常兜底或销毁实例时统一释放资源。
---
## 二、ArkTS ↔ Native 对齐说明
### ArkTS 侧调用顺序
```text
init -> loadPackage -> start -> [pullFrame/sendInput] -> pause/resume -> release
```
### Native 侧状态流转
```text
idle -> initialized -> loaded -> running -> paused -> released
```
### 对齐原则
- `EmulatorPage` 不直接调用 NAPI,统一经过 `MrpSimulatorFacade.ets`。
- `MrpNativeBridge.ets` 只做 API 映射,不做业务编排。
- `pullFrame()` 一期先使用 `ArrayBuffer` 全帧回传;性能问题放到第二阶段再优化。
- `sendInput()` 统一收口,避免导出 `sendKeyDown/sendKeyUp/sendTouchMove...` 多套接口。
- 错误一律走 `CommonResult / FrameResult`,不在一期设计复杂异常订阅体系。
---
## 三、哪些先占位、哪些一期必须落地
### 一期必须落地
- `init`
- `loadPackage`
- `start`
- `pause`
- `resume`
- `sendInput`
- `pullFrame`
- `release`
### 可以先占位实现
- `loadPackage` 内部的真实 MRP 资源解析
- `sendInput` 到真实内核的最终分发
- `pullFrame` 的真实像素输出(可先返回测试帧)
- `pause/resume` 的完整状态保存逻辑
---
## 四、当前明确不纳入 v0 的接口
- `stop()`
- `getStats()`
- `saveState()/loadState()`
- 音频控制相关接口
- 多实例管理
- 回调订阅/事件监听接口
---
## 五、一期接口设计结论
- 优先保证接口**少、稳、粗粒度**。
- 首周允许 facade 背后仍是占位实现,但 ArkTS 与 Native 的方法签名必须先冻结。
- 若实际内核接口与 facade 不一致,由 `adapter/existing_core/` 吸收差异,不回流污染 ArkTS。
@@ -0,0 +1,88 @@
# HOS-003 第一周技术断点与验证顺序
## 目标
在第一周内优先确认方案是否站得住,而不是堆功能。验证顺序必须固定,避免在前置链路未通时误投入实现。
---
## 一、验证顺序
1. **NAPI 模块真机装载成功**
2. **`pullFrame()` 帧链路打通**
3. **输入事件闭环打通**
---
## 二、技术断点 1:NAPI 模块真机装载成功
### 要验证什么
- C++ 工程能编译通过
- NAPI 模块能随 HAP 正确打包
- ArkTS 能成功导入并调用 `init()`
### 通过判据
- 真机启动后,ArkTS 调用 `init()` 返回 `ok=true`
- 未出现模块未注册、符号缺失、加载失败等错误
- 页面可稳定重复进入,不发生首次成功、二次失败的装载不一致
### 失败判据
- 真机无法加载 native 模块
- `init()` 调用崩溃或返回未定义错误
- Debug/Release 构建行为不一致
### 何时拉 architect / QA 介入
- **architect 介入**:模块集成方式、工程结构、构建链路需要改层级时
- **QA 介入**:当前阶段不需要;该断点属于研发自测前置链路
---
## 三、技术断点 2:`pullFrame()` 帧链路打通
### 要验证什么
- Native 能稳定提供一帧图像数据
- ArkTS 能读取 `ArrayBuffer`
- `EmulatorCanvas` 能正常显示,不黑屏、不花屏、不倒置
### 通过判据
- 页面持续显示有效画面
- 宽高、像素格式、颜色顺序与预期一致
- 连续刷新时不出现明显资源泄漏或频繁崩溃
### 失败判据
- 有返回但无画面
- 花屏、错色、错行、缓冲区长度异常
- 连续拉帧导致明显卡死或内存异常上涨
### 何时拉 architect / QA 介入
- **architect 介入**:若 `ArrayBuffer` 全帧回传性能不可接受,需要提前改渲染策略
- **QA 介入**:当前阶段不需要;先由研发做链路验证
---
## 四、技术断点 3:输入事件闭环打通
### 要验证什么
- 触摸/按键事件可通过 `sendInput()` 进入 native
- demo 包或测试逻辑对输入有可见响应
- `pause()/resume()` 后输入链路不失效
### 通过判据
- 至少一种按键输入可驱动画面或状态变化
- 至少一种触摸输入可被内核识别
- 页面切后台恢复后仍可继续响应输入
### 失败判据
- 输入事件发送成功但运行态无反馈
- 按键映射混乱,方向/动作错位
- 生命周期切换后输入彻底失效
### 何时拉 architect / QA 介入
- **architect 介入**:当输入模型与现有内核事件模型严重不匹配,需改 facade 或 adapter 分层时
- **QA 介入**:当输入链路已打通,需要开始沉淀设备/机型验证用例时
---
## 五、第一周结论性要求
- 三个断点全部通过后,才进入下一阶段代码骨架实装和内核适配。
- 若断点 1 失败,立即停止后续工作,优先修构建与模块装载。
- 若断点 2 失败,不进入输入与音频联调。
- 若断点 3 失败,不开始页面交互细化与兼容性扩展。
@@ -0,0 +1,551 @@
# HOS-004 MRP HarmonyOS POC 第一周代码骨架样例(ArkTS + NAPI/C++)
## 1. ArkTS:`MrpNativeBridge.ets`
```ts
// entry/src/main/ets/features/mrp/infra/native/MrpNativeBridge.ets
import nativeMrp from 'libmrp_napi.so'
import type {
InitOptions,
CommonResult,
InputEvent,
FrameResult,
} from '../../model/SimulatorTypes'
export class MrpNativeBridge {
static init(options: InitOptions): CommonResult {
return nativeMrp.init(options) as CommonResult
}
static loadPackage(packagePath: string): CommonResult {
return nativeMrp.loadPackage(packagePath) as CommonResult
}
static start(): CommonResult {
return nativeMrp.start() as CommonResult
}
static pause(): CommonResult {
return nativeMrp.pause() as CommonResult
}
static resume(): CommonResult {
return nativeMrp.resume() as CommonResult
}
static sendInput(event: InputEvent): CommonResult {
return nativeMrp.sendInput(event) as CommonResult
}
static pullFrame(): FrameResult {
return nativeMrp.pullFrame() as FrameResult
}
static release(): CommonResult {
return nativeMrp.release() as CommonResult
}
}
```
---
## 2. ArkTS:`SimulatorTypes.ets`
```ts
// entry/src/main/ets/features/mrp/model/SimulatorTypes.ets
export interface InitOptions {
workDir: string
width: number
height: number
debug?: boolean
}
export interface CommonResult {
ok: boolean
errorCode?: number
errorMessage?: string
}
export type InputType = 'key' | 'touch'
export type InputAction = 'down' | 'up' | 'move'
export interface InputEvent {
type: InputType
action: InputAction
keyCode?: number
x?: number
y?: number
timestamp?: number
}
export interface FrameResult {
ok: boolean
hasNewFrame: boolean
width: number
height: number
pixelFormat: 'RGBA_8888'
buffer?: ArrayBuffer
frameId?: number
errorCode?: number
errorMessage?: string
}
```
---
## 3. ArkTS:`MrpSimulatorFacade.ets`
```ts
// entry/src/main/ets/features/mrp/facade/MrpSimulatorFacade.ets
import { MrpNativeBridge } from '../infra/native/MrpNativeBridge'
import type { InitOptions, InputEvent, FrameResult, CommonResult } from '../model/SimulatorTypes'
export class MrpSimulatorFacade {
init(options: InitOptions): CommonResult {
return MrpNativeBridge.init(options)
}
loadPackage(packagePath: string): CommonResult {
return MrpNativeBridge.loadPackage(packagePath)
}
start(): CommonResult {
return MrpNativeBridge.start()
}
pause(): CommonResult {
return MrpNativeBridge.pause()
}
resume(): CommonResult {
return MrpNativeBridge.resume()
}
sendInput(event: InputEvent): CommonResult {
return MrpNativeBridge.sendInput(event)
}
pullFrame(): FrameResult {
return MrpNativeBridge.pullFrame()
}
release(): CommonResult {
return MrpNativeBridge.release()
}
}
```
---
## 4. ArkTS:`EmulatorPage.ets`
```ts
// entry/src/main/ets/pages/EmulatorPage.ets
import { MrpSimulatorFacade } from '../features/mrp/facade/MrpSimulatorFacade'
import type { FrameResult } from '../features/mrp/model/SimulatorTypes'
@Entry
@Component
struct EmulatorPage {
private simulator: MrpSimulatorFacade = new MrpSimulatorFacade()
@State frameId: number = 0
@State statusText: string = 'idle'
aboutToAppear(): void {
this.simulator.init({
workDir: '/data/storage/el2/base/files/mrp',
width: 240,
height: 320,
debug: true,
})
this.simulator.loadPackage('/data/storage/el2/base/files/demo/demo.mrp')
this.simulator.start()
this.statusText = 'running'
}
aboutToDisappear(): void {
this.simulator.release()
this.statusText = 'released'
}
onTick(): void {
const frame: FrameResult = this.simulator.pullFrame()
if (frame.ok && frame.hasNewFrame) {
this.frameId = frame.frameId ?? (this.frameId + 1)
}
}
build() {
Column() {
Text(`status: ${this.statusText}`)
Text(`frameId: ${this.frameId}`)
Button('UP').onClick(() => {
this.simulator.sendInput({ type: 'key', action: 'down', keyCode: 19, timestamp: Date.now() })
})
Button('Pause').onClick(() => {
this.simulator.pause()
this.statusText = 'paused'
})
Button('Resume').onClick(() => {
this.simulator.resume()
this.statusText = 'running'
})
Button('Tick PullFrame').onClick(() => this.onTick())
}
}
}
```
---
## 5. C++:`module_init.cpp`
```cpp
// entry/src/main/cpp/napi/module_init.cpp
#include <node_api.h>
napi_value ExportMrpFacade(napi_env env, napi_value exports);
static napi_value Init(napi_env env, napi_value exports) {
return ExportMrpFacade(env, exports);
}
static napi_module g_module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "mrp_napi",
.nm_priv = nullptr,
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterMrpModule(void) {
napi_module_register(&g_module);
}
```
---
## 6. C++:`MrpFacade.h`
```cpp
// entry/src/main/cpp/facade/MrpFacade.h
#ifndef MRP_FACADE_H
#define MRP_FACADE_H
#include <string>
#include <vector>
struct CommonResult {
bool ok;
int errorCode;
std::string errorMessage;
};
struct InitOptions {
std::string workDir;
int width;
int height;
bool debug;
};
struct InputEvent {
std::string type;
std::string action;
int keyCode;
int x;
int y;
long long timestamp;
};
struct FrameResult {
bool ok;
bool hasNewFrame;
int width;
int height;
std::string pixelFormat;
std::vector<uint8_t> buffer;
long long frameId;
int errorCode;
std::string errorMessage;
};
class MrpFacade {
public:
CommonResult Init(const InitOptions &options);
CommonResult LoadPackage(const std::string &packagePath);
CommonResult Start();
CommonResult Pause();
CommonResult Resume();
CommonResult SendInput(const InputEvent &event);
FrameResult PullFrame();
CommonResult Release();
};
#endif
```
---
## 7. C++:`MrpFacade.cpp`
```cpp
// entry/src/main/cpp/facade/MrpFacade.cpp
#include "MrpFacade.h"
CommonResult MrpFacade::Init(const InitOptions &options)
{
return {true, 0, ""};
}
CommonResult MrpFacade::LoadPackage(const std::string &packagePath)
{
return {true, 0, ""};
}
CommonResult MrpFacade::Start()
{
return {true, 0, ""};
}
CommonResult MrpFacade::Pause()
{
return {true, 0, ""};
}
CommonResult MrpFacade::Resume()
{
return {true, 0, ""};
}
CommonResult MrpFacade::SendInput(const InputEvent &event)
{
return {true, 0, ""};
}
FrameResult MrpFacade::PullFrame()
{
return {true, false, 240, 320, "RGBA_8888", {}, 0, 0, ""};
}
CommonResult MrpFacade::Release()
{
return {true, 0, ""};
}
```
---
## 8. C++:`facade_binding.cpp`
```cpp
// entry/src/main/cpp/napi/facade_binding.cpp
#include <node_api.h>
#include "../facade/MrpFacade.h"
static MrpFacade g_facade;
static napi_value MakeBoolResult(napi_env env, const CommonResult &result)
{
napi_value obj;
napi_create_object(env, &obj);
napi_value ok;
napi_get_boolean(env, result.ok, &ok);
napi_set_named_property(env, obj, "ok", ok);
return obj;
}
static napi_value Init(napi_env env, napi_callback_info info)
{
InitOptions options {"", 240, 320, false};
return MakeBoolResult(env, g_facade.Init(options));
}
static napi_value LoadPackage(napi_env env, napi_callback_info info)
{
return MakeBoolResult(env, g_facade.LoadPackage(""));
}
static napi_value Start(napi_env env, napi_callback_info info)
{
return MakeBoolResult(env, g_facade.Start());
}
static napi_value Pause(napi_env env, napi_callback_info info)
{
return MakeBoolResult(env, g_facade.Pause());
}
static napi_value Resume(napi_env env, napi_callback_info info)
{
return MakeBoolResult(env, g_facade.Resume());
}
static napi_value SendInput(napi_env env, napi_callback_info info)
{
InputEvent event{"key", "down", 0, 0, 0, 0};
return MakeBoolResult(env, g_facade.SendInput(event));
}
static napi_value PullFrame(napi_env env, napi_callback_info info)
{
FrameResult frame = g_facade.PullFrame();
napi_value obj;
napi_create_object(env, &obj);
napi_value ok;
napi_get_boolean(env, frame.ok, &ok);
napi_set_named_property(env, obj, "ok", ok);
return obj;
}
static napi_value Release(napi_env env, napi_callback_info info)
{
return MakeBoolResult(env, g_facade.Release());
}
napi_value ExportMrpFacade(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
{ "init", nullptr, Init, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "loadPackage", nullptr, LoadPackage, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "start", nullptr, Start, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "pause", nullptr, Pause, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "resume", nullptr, Resume, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "sendInput", nullptr, SendInput, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "pullFrame", nullptr, PullFrame, nullptr, nullptr, nullptr, napi_default, nullptr },
{ "release", nullptr, Release, nullptr, nullptr, nullptr, napi_default, nullptr },
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
```
---
## 9. C++:`MrpRuntime.h`
```cpp
// entry/src/main/cpp/core/runtime/MrpRuntime.h
#ifndef MRP_RUNTIME_H
#define MRP_RUNTIME_H
class MrpRuntime {
public:
bool Start();
bool Pause();
bool Resume();
bool Release();
};
#endif
```
## 10. C++:`MrpRuntime.cpp`
```cpp
// entry/src/main/cpp/core/runtime/MrpRuntime.cpp
#include "MrpRuntime.h"
bool MrpRuntime::Start() { return true; }
bool MrpRuntime::Pause() { return true; }
bool MrpRuntime::Resume() { return true; }
bool MrpRuntime::Release() { return true; }
```
---
## 11. C++:`FrameBuffer.h`
```cpp
// entry/src/main/cpp/core/render/FrameBuffer.h
#ifndef FRAME_BUFFER_H
#define FRAME_BUFFER_H
#include <cstdint>
#include <vector>
class FrameBuffer {
public:
FrameBuffer(int width, int height);
const std::vector<uint8_t> &Data() const;
private:
int width_;
int height_;
std::vector<uint8_t> rgba_;
};
#endif
```
## 12. C++:`FrameBuffer.cpp`
```cpp
// entry/src/main/cpp/core/render/FrameBuffer.cpp
#include "FrameBuffer.h"
FrameBuffer::FrameBuffer(int width, int height)
: width_(width), height_(height), rgba_(width * height * 4, 0)
{}
const std::vector<uint8_t> &FrameBuffer::Data() const
{
return rgba_;
}
```
---
## 13. C++:`InputEvent.h`
```cpp
// entry/src/main/cpp/core/input/InputEvent.h
#ifndef MRP_INPUT_EVENT_H
#define MRP_INPUT_EVENT_H
struct MrpInputEvent {
int keyCode;
int x;
int y;
int action;
};
#endif
```
## 14. C++:`InputDispatcher.cpp`
```cpp
// entry/src/main/cpp/core/input/InputDispatcher.cpp
#include "InputEvent.h"
bool DispatchInput(const MrpInputEvent &event)
{
return true;
}
```
---
## 15. 这版骨架的用途
- 先冻结 ArkTS ↔ Native 的方法签名
- 先打通 NAPI 模块注册与最小调用链路
- 先允许 `pullFrame()` 返回测试帧或空帧,优先验证链路
- 真实 MRP 内核适配后续落在 `adapter/existing_core/`
@@ -0,0 +1,157 @@
# HOS-005 MRP HarmonyOS POC 接口冻结稿 + 第一周验证用例模板
## 一、NAPI Facade v0 冻结接口
### 1. `init(options: InitOptions): CommonResult`
- 用途:初始化运行时、工作目录、逻辑分辨率
- 调用时机:页面进入后、首次加载包前
### 2. `loadPackage(packagePath: string): CommonResult`
- 用途:加载固定测试包
- 调用时机:`init()` 成功后、`start()` 前
### 3. `start(): CommonResult`
- 用途:启动模拟器主循环
- 调用时机:`loadPackage()` 成功后
### 4. `pause(): CommonResult`
- 用途:前后台切换、页面失焦暂停
- 调用时机:Ability/页面进入非活跃态时
### 5. `resume(): CommonResult`
- 用途:从暂停态恢复
- 调用时机:Ability/页面恢复活跃态时
### 6. `sendInput(event: InputEvent): CommonResult`
- 用途:统一投递按键/触摸输入
- 调用时机:运行态下由页面事件触发
### 7. `pullFrame(): FrameResult`
- 用途:拉取当前最新一帧图像
- 调用时机:运行态下定时/手动触发
### 8. `release(): CommonResult`
- 用途:页面退出、异常兜底时释放资源
- 调用时机:页面销毁或会话结束
---
## 二、ArkTS ↔ Native 调用时序冻结
```text
aboutToAppear
-> init
-> loadPackage
-> start
-> [loop: pullFrame]
-> [user action: sendInput]
onBackground
-> pause
onForeground
-> resume
aboutToDisappear
-> release
```
### 时序约束
- 不允许 `start()` 早于 `loadPackage()`
- 不允许 `sendInput()` 早于 `start()`
- `release()` 后不允许再次 `pullFrame()`
- 二次进入页面时必须重新走 `init -> loadPackage -> start`
---
## 三、第一周验证用例模板
### CASE-01:NAPI 模块装载验证
**目标**
- 真机成功加载 native 模块并完成 `init()`
**前置条件**
- HAP 可安装到真机
- native 模块已打包
**步骤**
1. 启动应用进入 `EmulatorPage`
2. 调用 `init()`
3. 观察返回结果和日志
**通过标准**
- 返回 `ok=true`
- 无模块未注册/符号缺失/加载失败错误
**失败标准**
- 崩溃
- `ok=false`
- 日志出现 load/register/link 失败
---
### CASE-02:拉帧链路验证
**目标**
- `pullFrame()` 返回有效帧并可显示
**前置条件**
- `init/loadPackage/start` 已成功
**步骤**
1. 触发 `pullFrame()`
2. 检查 `hasNewFrame`
3. 检查宽高、pixelFormat、buffer 长度
4. 页面显示测试帧
**通过标准**
- `ok=true`
- `hasNewFrame=true`
- 画面不黑屏、不花屏、不倒置
**失败标准**
- 无画面
- buffer 长度异常
- 颜色顺序错误/错行
---
### CASE-03:输入闭环验证
**目标**
- `sendInput()` 可驱动 native 状态变化
**前置条件**
- 模拟器已处于 running
**步骤**
1. 点击页面虚拟按键
2. 触发 `sendInput()`
3. 观察画面/状态是否有响应
4. 执行 `pause()` -> `resume()` 后再次输入
**通过标准**
- 输入后有可见反馈
- `pause/resume` 后输入链路仍有效
**失败标准**
- 输入成功但无任何反馈
- 生命周期切换后输入失效
---
## 四、何时拉人介入
### 拉 architect
- NAPI 模块打包/装载方案需要改工程结构
- `pullFrame()` 全帧回传性能明显不可接受
- 输入模型与历史内核模型严重不匹配
### 拉 QA
- 三个断点已全部打通
- 需要沉淀设备验证清单和固定回归模板
---
## 五、当前冻结结论
- 首周接口不再扩展新方法
- 先保证时序、参数、返回结构稳定
- 真实内核尚未接入时,允许 `pullFrame()` 返回测试帧、`sendInput()` 走占位逻辑
@@ -0,0 +1,118 @@
# HOS-006 MRP HarmonyOS POC 第一周执行清单(开发顺序 + 验证顺序)
## 一、第一周开发顺序(固定)
### Day 1:模块与接口底座
1. 建立 ArkTS 壳层目录
2. 建立 `MrpNativeBridge.ets`
3. 建立 `MrpSimulatorFacade.ets`
4. 建立 `SimulatorTypes.ets`
5. 建立 C++ `module_init.cpp`
6. 建立 C++ `facade_binding.cpp`
7. 建立 `MrpFacade.h/.cpp`
**当日最小交付**
- ArkTS 能调用到 native 的 `init()`
- NAPI 模块在真机可加载
---
### Day 2:运行时与拉帧链路
1. 建立 `MrpRuntime.h/.cpp`
2. 建立 `FrameBuffer.h/.cpp`
3. 在 `facade_binding.cpp` 接入 `pullFrame()`
4. 建立 `EmulatorPage.ets`
5. 建立 `FrameScheduler.ets`
6. 建立 `EmulatorCanvas.ets`
**当日最小交付**
- 页面能拿到测试帧
- 画面可显示,不黑屏
---
### Day 3:输入链路
1. 建立 `InputEvent.h`
2. 建立 `InputDispatcher.cpp`
3. 建立 `InputMapper.ets`
4. 建立 `KeypadOverlay.ets`
5. 在页面接入 `sendInput()`
**当日最小交付**
- 至少一个按键事件可打到 native
- 至少一个输入能触发可见反馈
---
### Day 4:生命周期与回收
1. 建立 `SimulatorSession.ets`
2. 建立 `AbilityLifecycle.ets`
3. 接入 `pause()` / `resume()` / `release()`
4. 验证页面退出与重新进入
**当日最小交付**
- 退后台可暂停
- 回前台可恢复
- 页面退出不崩溃
---
### Day 5:联调与收口
1. 固化验证用例
2. 对齐错误码和日志口径
3. 梳理后续真实内核接入点
4. 输出首周结论
**当日最小交付**
- 三个技术断点均有结论
- 能明确是否进入真实内核适配阶段
---
## 二、第一周验证顺序(固定)
### 验证 1:NAPI 模块装载
- 验证 `init()`
- 验证真机可加载
- 验证重复进入页面无异常
### 验证 2:拉帧链路
- 验证 `start()` + `pullFrame()`
- 验证 `buffer` 长度、像素格式、宽高
- 验证页面显示稳定
### 验证 3:输入闭环
- 验证 `sendInput()`
- 验证按键/触摸至少一条链路可用
- 验证输入后有可见反馈
### 验证 4:生命周期
- 验证 `pause()`
- 验证 `resume()`
- 验证 `release()` 后再次进入页面是否正常
---
## 三、严格禁止的推进顺序错误
- NAPI 未装载成功前,不进入页面细化
- 拉帧未通前,不做复杂输入联调
- 输入未闭环前,不做兼容性扩展
- 生命周期未稳前,不做音频接入
---
## 四、每日回报最小模板
- 刚完成:xx
- 当前在做:xx
- 下一项:xx
- 预计时间:xx
- 是否阻塞:有/无
---
## 五、首周收口判据
满足以下条件才算首周完成:
1. `init/loadPackage/start/pullFrame/sendInput/pause/resume/release` 八个接口已冻结
2. 三个技术断点已有通过/失败结论
3. 第一周代码骨架与验证模板已齐
4. 已能决定第二周是否进入真实 MRP 内核适配
@@ -0,0 +1,149 @@
# HOS-007 MRP HarmonyOS POC 第二周接入前置条件清单(真实内核适配前)
## 目标
在进入真实 MRP 内核适配前,先把必须确认的信息、adapter 接入约束、禁止跳过的 gate 一次性列清,避免第二周直接陷入接口返工。
---
## 一、必须拿到的现有内核信息
### 1. 内核基础信息
- 内核语言:C / C++ / 其他
- 当前仓库位置与构建方式
- 是否已有可独立运行的核心库
- 是否存在平台相关代码分支
### 2. 包/资源模型
- `.mrp` 包格式说明
- 入口文件/入口函数约定
- 资源解包是否在内核内部完成
- 是否依赖固定目录结构
### 3. 渲染模型
- 输出格式:RGBA / RGB565 / 其他
- 输出粒度:整帧 / 脏矩形 / draw call
- 分辨率与缩放约束
- 是否已有 frame buffer 概念
### 4. 输入模型
- 支持的输入类型:按键 / 触摸 / 文本输入
- 现有 keyCode 映射表
- 长按、连按、方向键重复规则
- 是否区分软键/菜单键/返回键
### 5. 生命周期与运行时模型
- 启动、暂停、恢复、退出的真实状态机
- 主循环归属:内核线程 / 外部驱动
- 是否允许外部轮询拉帧
- pause/resume 是否已有实现
### 6. 文件系统与存档模型
- 运行目录依赖
- 存档路径规则
- 是否写临时文件
- 是否依赖相对路径/当前工作目录
### 7. 音频模型
- 是否必须同步启动音频
- 输出类型:PCM / callback / push buffer
- 是否有音画同步耦合
- 首周是否允许静音 stub
### 8. 线程与内存模型
- 内核是否自建线程
- 哪些对象线程不安全
- 帧缓冲所有权归谁
- 资源释放顺序要求
### 9. 错误与日志模型
- 是否已有错误码
- 是否已有日志接口
- 崩溃/异常时可否给出最小诊断信息
### 10. 许可证与第三方依赖
- 是否依赖第三方图像/音频/压缩库
- 目标库是否可用于 HarmonyOS 构建
- 是否存在许可证风险
---
## 二、Adapter 层接入前必须满足的约束
### 1. 不允许 ArkTS 直接适配内核细节
- 历史内核差异只允许落在 `adapter/existing_core/`
- ArkTS 只面向冻结后的 facade
### 2. Adapter 只做三类事
- 参数转换
- 状态映射
- 平台差异吸收
### 3. Adapter 不做的事
- 页面状态管理
- 业务配置拼装
- UI 逻辑
- 异步调度策略定义
### 4. 接入前要先定义清楚
- 内核 init 所需参数
- 内核 load/start/pause/resume/release 顺序
- 输入事件转换表
- 帧数据输出结构
- 错误码映射规则
---
## 三、进入真实内核适配前的硬门槛(Gate)
### Gate-1:NAPI 基础链路已稳定
满足:
- `init()` 真机成功
- 模块可重复装载
- 无明显构建/链接不稳定问题
### Gate-2:POC 拉帧链路已稳定
满足:
- `pullFrame()` 已能稳定返回测试帧
- ArkTS 页面显示链路无黑屏/花屏
- 全帧回传性能至少可接受用于 POC
### Gate-3:输入闭环已稳定
满足:
- `sendInput()` 能穿透到 native stub
- 页面到 native 的 key/touch 路径已固定
### Gate-4:生命周期链路已固定
满足:
- `pause()/resume()/release()` 调用时机已冻结
- 页面二次进入不会残留脏状态
### Gate-5:现有内核信息已补齐
满足:
- 上述“必须拿到的现有内核信息”至少 80% 已确认
- 剩余不确定项不影响首轮适配切入
---
## 四、哪些没确认前不能进入真实接入
- 不知道内核真实启动顺序
- 不知道帧输出格式
- 不知道输入 keyCode 对照关系
- 不知道 pause/resume 是否可重入
- 不知道内核是否依赖线程上下文
- 不知道文件路径/工作目录要求
---
## 五、需要谁补齐信息
- **内核维护人**:补内核接口、状态机、渲染/输入模型
- **architect**:拍板 facade 与 adapter 最终边界
- **QA**:在接入前不介入;等 stub 链路稳定后开始接设备验证模板
---
## 六、第二周开工判定
满足以下条件才进入真实内核适配:
1. HOS-001 ~ HOS-006 已完成
2. HOS-007 清单中的关键信息已补齐
3. 当前 v0 facade 不再改方法名
4. 可明确知道 adapter 第一刀先接哪里(建议:init/load/start/pullFrame)
@@ -0,0 +1,34 @@
# ArkTS 导入成功后的列表刷新进展 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. AppListPage 已支持 refreshToken
新增:
- `@Prop refreshToken`
- `ensureRefreshByToken()`
- 当 ShellRootPage 变更 refreshToken 时,触发 `store.refreshApps()`
### 2. ShellRootPage 已接导入成功后的刷新意图
当前逻辑:
- Import 成功 -> `backToListAfterImport()`
- `catalogRefreshTick += 1`
- 切回 `appList`
- `AppListPage` 接收新 token 并刷新列表
### 3. AppListView 已禁用不可运行应用点击
当前逻辑:
- `status === 'ready'` 才允许触发 `onItemTap`
- 不可运行应用降透明度显示
## 当前结论
- 导入成功后的列表刷新占位链路已补齐
- 列表页已具备最小可交互约束
- 仍为 POC 占位实现,后续可替换为正式路由与状态框架
## 下一步
1. 给 RunPage 增加 mock 启动中 -> 运行中状态过渡
2. 给 ImportPage 增加返回后重置本地状态
3. 补 ArkTS 页面流演示说明图
@@ -0,0 +1,32 @@
# ArkTS Mock 数据闭环进展 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. Adapter 已补 mock 数据
- `NativeAppAdapter.listInstalledApps()` 返回 2 个示例应用
- `NativeImportAdapter.pickFile()` 返回 mock 文件 URI
- `NativeImportAdapter.inspectPackage()` 返回 mock 预览信息
- `NativeImportAdapter.importPackage()` 返回 mock appId
- `NativeRuntimeAdapter` 保持空成功返回
### 2. AppListView 已支持点击回调
新增:
- `onItemTap(appId)`
### 3. AppListPage 已接列表点击占位
新增:
- `selectedAppId`
- 点击列表项后记录 appId,并显示 Banner 提示
## 当前结论
- 页面展示已不再完全依赖真实 native 接口
- 列表页已有最小可演示数据流
- 下一步可继续补路由占位与 Import -> List 刷新占位
## 下一步
1. 补最小路由占位文档
2. 让导入成功后触发列表刷新占位
3. 让运行页支持 mock 启动入口
@@ -0,0 +1,168 @@
# ArkTS 页面与 Native 边界清单 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
范围:FE-003
## 1. 可以留在 ArkTS 的逻辑
### 1.1 页面与路由
- 应用列表页导航
- 导入页导航
- 运行页导航
- 页面返回与确认弹窗
### 1.2 纯展示逻辑
- 列表渲染
- 空态展示
- 加载态展示
- 导入结果展示
- 运行状态展示
- 错误 Banner / Dialog 展示
### 1.3 轻量交互逻辑
- 点击应用进入运行页
- 点击导入按钮进入导入页
- 点击重试/重启/退出
- 页面 show/hide 生命周期事件转发
### 1.4 ViewModel 级状态整理
- 把 Service 返回的数据映射为页面展示态
- 按 phase 切换不同组件
- 管理页面局部临时状态
---
## 2. 必须走 Adapter / Native 的逻辑
### 2.1 导入链路
- 文件选择器底层接入
- URI / 沙箱路径转换
- 文件合法性校验
- 包解析
- 文件复制 / 解压 / 注册
- 导入失败原因原始采集
### 2.2 应用元数据链路
- 已安装应用扫描
- 图标与元数据读取
- 应用可运行性判定
- 本地注册表 / 索引读取
### 2.3 运行链路
- 创建运行会话
- 渲染容器绑定
- surface / XComponent / native handle 管理
- 输入事件注入
- 音频输出
- 暂停 / 恢复 / 停止运行
- 异常退出与 native 层资源释放
### 2.4 持久化与底层能力
- 存档路径管理
- 配置落盘
- 日志写入
- 权限与沙箱细节
- 生命周期与系统事件底层适配
---
## 3. 页面层禁止下沉的内容清单
### 3.1 禁止进入页面的 native 细节
- native error code
- session handle
- surface id / window id
- 线程 id
- 原始路径
- 文件描述符
- 原始导入阶段枚举
- 原始运行时回调对象
### 3.2 禁止进入页面的实现逻辑
- 文件复制与解压
- 包头解析
- 存档目录拼接
- 输入协议映射实现
- 音频设备初始化
- 渲染线程管理
- native 生命周期恢复逻辑
### 3.3 禁止页面直接做的调用
- 页面直接调 NAPI 原始方法
- 页面直接管理 native listener
- 页面直接订阅 native 高频事件流
- 页面直接判断兼容性底层规则
---
## 4. 页面层允许拿到的唯一形态
页面只允许拿到:
- `AppItemVM`
- `PackagePreviewVM`
- `RuntimePhase`
- `UiError`
- `canRestart / canExit` 这类布尔控制量
页面不允许拿到:
- 原始导入结构
- 原始会话结构
- 原始渲染对象
- 原始路径对象
---
## 5. 各页面边界结论
### 5.1 AppListPage
ArkTS 保留:
- 列表渲染
- 空态/错误态
- 页面跳转
必须下沉:
- 扫描应用
- 读取应用元数据
- 判断是否可运行
### 5.2 ImportPage
ArkTS 保留:
- 选择文件后的流程编排
- 预览展示
- 导入成功/失败展示
必须下沉:
- 文件选择器底层接入
- 包解析与合法性验证
- 导入执行
### 5.3 RunPage
ArkTS 保留:
- 容器占位与工具栏
- 状态切换展示
- 重启/退出按钮
必须下沉:
- 运行会话创建
- 渲染绑定
- 输入/音频/资源释放
---
## 6. 边界原则
1. ArkTS 负责用户意图与页面编排。
2. Service 负责业务组织与错误归一。
3. Adapter 负责 native 能力收口。
4. 页面层不得因省事而直接接 native 原始对象。
5. native 命名变化只能影响 Adapter,不允许扩散到页面层。
---
## 7. 结论
POC 阶段边界已经固定:
- ArkTS 做页面、组件、状态编排
- Adapter / Native 做导入、运行、渲染、输入、音频、存档、路径、日志
- 页面层严格禁止下沉到底层实现细节
@@ -0,0 +1,26 @@
# ArkTS 页面事件接线进展 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. 组件已补回调入口
- `ImportEntryButton`:新增 `onTap`
- `ImportSourceSelector`:新增 `onPick`
- `RuntimeToolbar`:新增 `onBack / onRestart / onExit`
### 2. 页面已接动作占位
- `AppListPage`:点击导入按钮触发 `openImportPage()` 占位
- `ImportPage`:点击选择文件后触发 `pickFile() -> analyzeSelectedFile()`
- `RunPage`:工具栏按钮已接 `restartSession()` / `stopSession()` / 返回占位
## 当前结论
- 页面已不再是纯静态组件树
- 页面意图已开始进入 Store Action
- 当前仍未接真实路由与 ArkTS 响应式刷新机制
## 下一步
1. 给 Store 增加可驱动页面刷新的最小响应式方案
2. 补 AppList -> RunPage / AppList -> ImportPage 的路由占位
3. 预留 Adapter 到 NAPI façade 的 mock 结果
@@ -0,0 +1,58 @@
# ArkTS 页面组件树接线进展 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. AppListPage 已接线
已接入:
- `PageHeader`
- `StatusBanner`
- `LoadingBlock`
- `EmptyState`
- `ImportEntryButton`
- `AppListView`
当前页面状态流:
- loading -> `LoadingBlock`
- error -> `StatusBanner`
- empty -> `EmptyState + ImportEntryButton`
- data ready -> `AppListView`
### 2. ImportPage 已接线
已接入:
- `PageHeader`
- `StatusBanner`
- `ImportSourceSelector`
- `PackagePreviewCard`
- `ImportProgressPanel`
- `ImportResultPanel`
当前页面状态流:
- preview ready -> `PackagePreviewCard`
- importing -> `ImportProgressPanel`
- success/failed -> `ImportResultPanel`
### 3. RunPage 已接线
已接入:
- `PageHeader`
- `StatusBanner`
- `RuntimeToolbar`
- `RuntimeContainer`
- `RuntimeStatusOverlay`
- `ConfirmDialog`
当前页面状态流:
- 非 running -> `RuntimeStatusOverlay`
- stopped -> `ConfirmDialog`
## 当前结论
- 3 个页面已从纯占位推进为“组件树已挂接”的壳层页面
- 仍为 POC 占位实现,尚未接入真实路由、真实用户事件和真实 native 数据流
## 下一步
1. 为 Store 做可观察/可驱动 UI 的响应式改造
2. 给页面补最小按钮事件
3. 增加页面之间最小跳转闭环
4. 预留 Adapter 到 NAPI façade 的接入点
@@ -0,0 +1,52 @@
# ArkTS 最小路由占位与页面闭环草案 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. 新增 ShellRootPage
文件:`entry/src/main/ets/pages/ShellRootPage.ets`
职责:
- 统一维护最小路由状态
- 控制 3 个页面切换
- 承接页面之间的回调跳转
当前路由:
- `appList`
- `import`
- `run`
### 2. AppListPage 已支持路由回调
新增:
- `onNavigateImport()`
- `onNavigateRun(appId)`
### 3. ImportPage 已支持导入后回流
新增:
- `onBack()`
- `onImportSuccess()`
当前闭环:
- AppList -> Import
- Import 成功 -> AppList
### 4. RunPage 已支持运行页回流
新增:
- `appId`
- `onBack()`
当前闭环:
- AppList -> Run
- Run 退出 -> AppList
## 当前结论
- 已从“页面占位”推进到“最小路由闭环占位”
- 当前路由仍为 ArkTS 壳层内管理,不依赖正式 Router 框架
- 可继续作为 POC 页面流演示基线
## 下一步
1. 让导入成功真正触发 AppList 刷新而不是仅返回
2. 让列表中不可运行应用禁用点击
3. 增加运行页 mock 启动中 -> 运行中状态过渡
@@ -0,0 +1,27 @@
# RunPage mock 启动过渡与 ImportPage 重置进展 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. Runtime mock 启动过渡已补齐
- `NativeRuntimeAdapter.startSession()` 增加 600ms mock 延迟
- `NativeRuntimeAdapter.restartSession()` 增加 400ms mock 延迟
- `RuntimeSessionStore` 在 start/restart 时显式进入 `starting`
- 运行页现在可观察到 `starting -> running` 状态过渡
### 2. ImportPage 返回/成功后重置已补齐
- 新增 `onBackClick()`
- 返回列表前调用 `store.reset()`
- 导入成功后先 `store.reset()` 再回调 `onImportSuccess()`
- `aboutToDisappear()` 兜底重置导入态
## 当前结论
- 运行页已具备最小 mock 启动状态演示能力
- 导入页不会把旧预览/旧错误带回下一轮导入
## 下一步
1. 让 RunPage 在不可 restart 时禁用重启按钮
2. 给 AppList 增加“导入成功后新应用高亮”占位
3. 补一份 POC 演示路径说明
@@ -0,0 +1,82 @@
# ArkTS 壳层代码骨架占位版 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 已落地目录
```text
entry/src/main/ets/
├─ pages/
├─ components/common/
├─ components/appList/
├─ components/import/
├─ components/runtime/
├─ store/
├─ services/
├─ adapters/
└─ models/
```
## 已落地文件
### pages
- `pages/AppListPage.ets`
- `pages/ImportPage.ets`
- `pages/RunPage.ets`
### common components
- `components/common/PageHeader.ets`
- `components/common/LoadingBlock.ets`
- `components/common/StatusBanner.ets`
- `components/common/ConfirmDialog.ets`
- `components/common/EmptyState.ets`
### appList components
- `components/appList/AppListView.ets`
- `components/appList/AppCard.ets`
- `components/appList/ImportEntryButton.ets`
### import components
- `components/import/ImportSourceSelector.ets`
- `components/import/PackagePreviewCard.ets`
- `components/import/ImportProgressPanel.ets`
- `components/import/ImportResultPanel.ets`
### runtime components
- `components/runtime/RuntimeContainer.ets`
- `components/runtime/RuntimeToolbar.ets`
- `components/runtime/RuntimeStatusOverlay.ets`
### store
- `store/AppCatalogStore.ts`
- `store/ImportStore.ts`
- `store/RuntimeSessionStore.ts`
### services
- `services/AppService.ts`
- `services/ImportService.ts`
- `services/RuntimeService.ts`
### adapters
- `adapters/NativeAppAdapter.ts`
- `adapters/NativeImportAdapter.ts`
- `adapters/NativeRuntimeAdapter.ts`
### models
- `models/AppItemVM.ts`
- `models/PackagePreviewVM.ts`
- `models/RuntimeSessionState.ts`
- `models/UiError.ts`
## 当前状态
- 目录结构已与 FE-001 对齐
- 契约层已与 FE-002 对齐
- 页面与 native 边界遵守 FE-003
- 当前为占位版,不依赖 native 最终命名冻结
## 下一步建议
1. 给 3 个 Page 接入真实组件树
2. 为 Store 增加 ArkTS 响应式改造
3. 为 Adapter 接入 NAPI façade 占位实现
4. 增加路由与页面跳转最小闭环
+291
View File
@@ -0,0 +1,291 @@
# ArkTS 壳层页面-Store-Service-Adapter 契约 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
范围:FE-002
## 1. 页面输入输出边界
### 1.1 AppListPage
输入:
- `AppCatalogStore.items`
- `AppCatalogStore.loading`
- `AppCatalogStore.error`
输出:
- `loadApps()`
- `refreshApps()`
- `openImportPage()`
- `openRunPage(appId)`
页面只消费:
- 应用列表 ViewModel
- 加载态
- 错误态
页面不消费:
- native 列表原始结构
- 本地存储路径
- 运行句柄
---
### 1.2 ImportPage
输入:
- `ImportStore.phase`
- `ImportStore.selectedFile`
- `ImportStore.previewInfo`
- `ImportStore.error`
输出:
- `pickFile()`
- `analyzeSelectedFile()`
- `startImport()`
- `backToListAfterSuccess()`
- `retryImport()`
页面只消费:
- 导入阶段
- 预览信息
- 成功/失败结果
页面不消费:
- 文件复制进度实现
- 包校验细节
- URI 到沙箱路径转换逻辑
---
### 1.3 RunPage
输入:
- `RuntimeSessionStore.currentAppId`
- `RuntimeSessionStore.phase`
- `RuntimeSessionStore.error`
- `RuntimeSessionStore.canRestart`
- `RuntimeSessionStore.canExit`
输出:
- `startSession(appId)`
- `restartSession()`
- `stopSession()`
- `leaveRunPage()`
- `notifyPageShow()`
- `notifyPageHide()`
页面只消费:
- 会话状态
- 控件可用性
- 结构化错误提示
页面不消费:
- runtime native handle
- surface/XComponent 生命周期对象
- 输入注入协议
---
## 2. Store 最小接口
### 2.1 AppCatalogStore
```ts
interface AppCatalogStore {
items: AppItemVM[]
loading: boolean
error: UiError | null
loadApps(): Promise<void>
refreshApps(): Promise<void>
clearError(): void
}
```
### 2.2 ImportStore
```ts
type ImportPhase = 'idle' | 'picking' | 'analyzing' | 'importing' | 'success' | 'failed'
interface ImportStore {
phase: ImportPhase
selectedFile: string | null
previewInfo: PackagePreviewVM | null
error: UiError | null
pickFile(): Promise<void>
analyzeSelectedFile(): Promise<void>
startImport(): Promise<void>
reset(): void
}
```
### 2.3 RuntimeSessionStore
```ts
type RuntimePhase = 'idle' | 'starting' | 'running' | 'error' | 'stopped'
interface RuntimeSessionStore {
currentAppId: string | null
phase: RuntimePhase
error: UiError | null
canRestart: boolean
canExit: boolean
startSession(appId: string): Promise<void>
restartSession(): Promise<void>
stopSession(): Promise<void>
clearError(): void
}
```
---
## 3. Service 最小接口
### 3.1 AppService
```ts
interface AppService {
listApps(): Promise<AppItemVM[]>
}
```
职责:
- 从 NativeAppAdapter 拉取应用元数据
- 转换为 AppItemVM
- 屏蔽 native 原始字段
### 3.2 ImportService
```ts
interface ImportService {
pickMrpFile(): Promise<string | null>
analyzePackage(fileUri: string): Promise<PackagePreviewVM>
importPackage(fileUri: string): Promise<{ appId: string }>
}
```
职责:
- 编排文件选择
- 解析包预览信息
- 发起导入
- 输出标准化错误
### 3.3 RuntimeService
```ts
interface RuntimeService {
start(appId: string): Promise<void>
restart(appId: string): Promise<void>
stop(): Promise<void>
onPageShow(): Promise<void>
onPageHide(): Promise<void>
}
```
职责:
- 编排运行会话生命周期
- 管理启动/停止/重启
- 转换 runtime 错误为 UiError
---
## 4. Adapter 占位契约
### 4.1 NativeAppAdapter
```ts
interface NativeAppAdapter {
listInstalledApps(): Promise<Array<{
appId: string
name: string
icon?: string
version?: string
runnable: boolean
}>>
}
```
### 4.2 NativeImportAdapter
```ts
interface NativeImportAdapter {
pickFile(): Promise<string | null>
inspectPackage(fileUri: string): Promise<{
name: string
version?: string
icon?: string
size?: number
valid: boolean
}>
importPackage(fileUri: string): Promise<{
appId: string
}>
}
```
### 4.3 NativeRuntimeAdapter
```ts
interface NativeRuntimeAdapter {
startSession(appId: string): Promise<void>
restartSession(appId: string): Promise<void>
stopSession(): Promise<void>
notifyPageShow(): Promise<void>
notifyPageHide(): Promise<void>
}
```
---
## 5. 模型最小定义
### 5.1 AppItemVM
```ts
interface AppItemVM {
id: string
name: string
icon?: string
version?: string
status: 'ready' | 'invalid'
}
```
### 5.2 PackagePreviewVM
```ts
interface PackagePreviewVM {
name: string
version?: string
icon?: string
sizeText?: string
valid: boolean
}
```
### 5.3 UiError
```ts
interface UiError {
message: string
retryable: boolean
}
```
---
## 6. 契约约束
### ArkTS 页面必须遵守
- 只调用 Store Action
- 不直接调用 NativeAdapter
- 不持有 native 返回原始对象
- 不解析 native 错误码
### Store 必须遵守
- 不处理 UI 组件逻辑
- 不暴露 native 对象给页面
- 所有异步状态先转成 ArkTS 可消费状态
### Service 必须遵守
- 只做业务编排与错误归一
- 不承载页面导航
- 不输出 native 路径和句柄
### Adapter 必须遵守
- 封装所有 native 细节
- 允许后续替换命名,不影响页面层
---
## 7. 结论
该契约用于先冻结 ArkTS 壳层输入输出边界,不等待 native 最终接口命名冻结。后续 native 能力接入时,仅允许在 Adapter 层收敛变化。
@@ -0,0 +1,82 @@
# ArkTS 壳层最小可演示闭环说明 v1
项目:mrp-simulator-harmonyos
## 1. 运行入口在哪里
运行入口在:
- `entry/src/main/ets/pages/ShellRootPage.ets`
- `entry/src/main/ets/pages/AppListPage.ets`
当前可见入口:
1. App 启动进入 `ShellRootPage`
2. 默认路由进入 `AppListPage`
3. 用户点击 **“可运行”应用卡片**
4. 通过 `onNavigateRun(appId)` 切到 `RunPage`
## 2. 页面流如何走
当前最小页面流:
- `AppListPage -> ImportPage -> AppListPage`
- `AppListPage -> RunPage -> AppListPage`
具体链路:
1. **列表页**
- 展示应用列表
- 展示运行入口提示
- 点击“导入应用”进入 `ImportPage`
- 点击“可运行”卡片进入 `RunPage`
2. **导入页**
- 选择文件
- 展示预览
- 点击“开始导入”
- 导入成功后返回列表页
- 返回列表页时触发列表刷新 token
3. **运行页**
- 进入时根据 `appId` 发起 `startSession(appId)`
- 状态从 `starting -> running`
- 点击退出后回到列表页
## 3. 哪些接口已经为 NAPI 预留
### 3.1 App 列表相关
- `entry/src/main/ets/adapters/NativeAppAdapter.ts`
- `listInstalledApps()`
### 3.2 导入相关
- `entry/src/main/ets/adapters/NativeImportAdapter.ts`
- `pickFile()`
- `inspectPackage(fileUri)`
- `importPackage(fileUri)`
### 3.3 运行时相关
- `entry/src/main/ets/adapters/NativeRuntimeAdapter.ts`
- `startSession(appId)`
- `restartSession(appId)`
- `stopSession()`
- `notifyPageShow()`
- `notifyPageHide()`
### 3.4 Service 收口层
- `entry/src/main/ets/services/AppService.ts`
- `entry/src/main/ets/services/ImportService.ts`
- `entry/src/main/ets/services/RuntimeService.ts`
说明:
- 后续 NAPI 接入时,优先替换 Adapter 内部实现
- 页面层和 Store 层不直接碰 native 细节
## 4. 当前可见结果
当前已经具备:
- 列表页可见运行入口与导入入口
- 导入成功后返回列表并刷新
- 运行页可见 `starting / running / stopped` 状态展示
- 运行页工具栏根据状态控制按钮可用性
## 5. 本轮不做的事
本轮不继续扩大量新页面/组件,只收口:
- 现有页面可见闭环
- 现有 Adapter/NAPI 接缝
- 现有运行入口与状态提示
@@ -0,0 +1,164 @@
# ArkTS 壳层 POC 目录结构最终版
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
范围:FE-001
## 1. 目录树最终版
```text
entry/src/main/ets/
├─ pages/
│ ├─ AppListPage.ets
│ ├─ ImportPage.ets
│ └─ RunPage.ets
├─ components/
│ ├─ common/
│ │ ├─ PageHeader.ets
│ │ ├─ LoadingBlock.ets
│ │ ├─ StatusBanner.ets
│ │ ├─ ConfirmDialog.ets
│ │ └─ EmptyState.ets
│ ├─ appList/
│ │ ├─ AppListView.ets
│ │ ├─ AppCard.ets
│ │ └─ ImportEntryButton.ets
│ ├─ import/
│ │ ├─ ImportSourceSelector.ets
│ │ ├─ PackagePreviewCard.ets
│ │ ├─ ImportProgressPanel.ets
│ │ └─ ImportResultPanel.ets
│ └─ runtime/
│ ├─ RuntimeContainer.ets
│ ├─ RuntimeToolbar.ets
│ └─ RuntimeStatusOverlay.ets
├─ store/
│ ├─ AppCatalogStore.ts
│ ├─ ImportStore.ts
│ └─ RuntimeSessionStore.ts
├─ services/
│ ├─ AppService.ts
│ ├─ ImportService.ts
│ └─ RuntimeService.ts
├─ adapters/
│ ├─ NativeAppAdapter.ts
│ ├─ NativeImportAdapter.ts
│ └─ NativeRuntimeAdapter.ts
└─ models/
├─ AppItemVM.ts
├─ PackagePreviewVM.ts
├─ RuntimeSessionState.ts
└─ UiError.ts
```
---
## 2. 页面职责分工
### 2.1 AppListPage
职责:
- 展示已导入应用列表
- 空态引导导入
- 触发列表刷新
- 选择应用并进入 RunPage
- 跳转 ImportPage
不负责:
- 包解析
- 文件导入实现
- native 路径/数据库细节
- runtime 会话细节
### 2.2 ImportPage
职责:
- 选择本地 MRP 文件
- 展示包预览信息
- 发起导入
- 展示导入中状态
- 展示导入成功/失败结果
- 导入成功后通知列表刷新
不负责:
- URI 转沙箱路径规则
- 解压/校验/复制实现
- 导入兼容性底层规则
- native 错误码判断
### 2.3 RunPage
职责:
- 承载模拟器运行区域
- 展示启动中/运行中/异常/已退出状态
- 提供返回/重启/退出操作
- 响应页面生命周期并转发给 RuntimeService
不负责:
- 渲染句柄管理
- surface / XComponent 细节
- 输入注入协议
- 模拟器核心线程与事件循环
---
## 3. 首版明确不做的页面
### 3.1 SettingsPage
不做原因:
- 不属于 POC 最小闭环
- 容易过早暴露 native 配置细节
- 首版使用默认配置即可
### 3.2 AppDetailPage
不做原因:
- 与列表页信息重叠
- 不影响导入/运行主链路
### 3.3 ImportHistoryPage
不做原因:
- 需要额外持久化与查询逻辑
- POC 验证价值低
### 3.4 ErrorDiagnosisPage / LogPage
不做原因:
- 首版只需要结构化错误提示
- 独立诊断页会过早耦合 native 日志格式与路径
### 3.5 SessionRecoveryPage
不做原因:
- 依赖会话恢复协议与异常恢复机制
- 二阶段再进入
---
## 4. 页面层保留原则
页面层只保留:
- 页面路由
- UI 组件组合
- 用户交互
- 状态展示
- 调用 Store Action
页面层不保留:
- native 原始对象
- 文件系统路径
- 导入实现细节
- 渲染句柄
- 错误码映射
---
## 5. 结论
ArkTS 壳层 POC 最小页面结构固定为:
- 3 个页面:AppListPage / ImportPage / RunPage
- 13 个组件
- 3 个 Store
- 3 个 Service
- 3 个 Adapter
- 4 个最小模型
该结构用于支撑:
- 本地导入
- 应用列表展示
- 单实例运行
- 基础错误反馈
@@ -0,0 +1,44 @@
# ArkTS Store 最小响应式联动方案 v0
项目:MRP 模拟器鸿蒙化
角色:RD Frontend
## 本轮完成
### 1. 新增 StoreObserver
文件:`entry/src/main/ets/store/StoreObserver.ts`
职责:
- 提供 `subscribe()`
- 提供 `notify()`
- 作为 3 个 Store 的最小观察者基类
### 2. 3 个 Store 已接通知机制
- `AppCatalogStore`
- `ImportStore`
- `RuntimeSessionStore`
做法:
- 状态变更后调用 `notify()`
- 页面不直接轮询 Store
- 页面通过订阅回调触发局部刷新
### 3. 3 个页面已接最小刷新联动
- `AppListPage`
- `ImportPage`
- `RunPage`
做法:
- 页面新增 `@State refreshTick`
- `aboutToAppear()` 中订阅 Store
- `aboutToDisappear()` 中取消订阅
- Store 状态变化时递增 `refreshTick`,驱动页面重绘
## 当前结论
- 已从“Store 可调用”推进到“Store 可驱动页面刷新”的最小版
- 当前方案是 POC 响应式占位实现,不替代后续正式状态框架
## 下一步
1. 把 AppListPage 的列表项点击接到 `RunPage` 跳转占位
2. 为 Adapter 增加 mock 数据,形成可演示的页面闭环
3. 补一份 ArkTS 页面路由占位草案
+96
View File
@@ -0,0 +1,96 @@
# 主推进连续施工 Backlog
> 目标:让当前主推进人进入“连续施工模式”,做完一个自动继续下一个,除非遇到明确阻塞,不再停在“等催办”。
## 当前任务
MRP 模拟器鸿蒙化
## 主推进人
- `harmonyos-dev`
- `rd-frontend`
---
## HarmonyOS Senior Engineer Backlog
### HOS-PRIO-001 Native/NAPI/C++ 最小工程骨架(最高优先级)
交付:
- 实际目录进入主仓库:
- `entry/src/main/cpp/`
- `entry/src/main/cpp/napi/`
- `entry/src/main/cpp/runtime/`
- `entry/src/main/cpp/platform/`
- `entry/src/main/cpp/render/`
- `entry/src/main/cpp/input/`
- 最小文件骨架进入主仓库:
- `CMakeLists.txt`
- `module_init.cpp`
- `facade_binding.cpp`
- `MrpFacade.h/.cpp`
- `MrpRuntime.h/.cpp`
- `FrameBuffer.h/.cpp`
- `InputEvent.h`
- `InputDispatcher.cpp`
- 必须 **直接 commit + push 到 main**
规则:
- 这项优先级高于文档补充
- 先把 native 骨架推进仓库,再补解释文档
- 不允许继续只产出文档、不产出 native 目录和文件
### HOS-001 POC 文件级骨架清单
交付:
- ArkTS 侧骨架文件清单
- Native/C++ 侧骨架文件清单
- 模块关系说明
### HOS-002 最小 NAPI Facade v0
交付:
- 方法清单
- 参数/返回值
- ArkTS ↔ Native 对齐说明
- 哪些先占位、哪些一期必须落地
### HOS-003 第一周技术断点与验证顺序
交付:
- 第一周最先验证的 3 个技术断点
- 每个断点的通过/失败判据
- 明确什么情况需要拉 architect/QA 介入
规则:
- 完成一个自动进入下一个
- 不因接口命名未冻结而等待
- 如缺实际内核接口,先交可落地占位版
---
## RD Frontend Backlog
### FE-001 ArkTS 壳层目录结构最终版
交付:
- `pages / components / store / services / adapters / models` 目录树
- 页面职责分工
### FE-002 页面-Store-Service-Adapter 契约
交付:
- AppListPage / ImportPage / RunPage 的输入输出边界
- AppCatalogStore / ImportStore / RuntimeSessionStore 最小接口
- AppService / ImportService / RuntimeService 最小接口
### FE-003 页面与 Native 边界清单
交付:
- 哪些逻辑可以留在 ArkTS
- 哪些逻辑必须走 Adapter / Native
- 页面层禁止下沉的内容清单
规则:
- 完成一个自动进入下一个
- 不等待 native 最终命名冻结
- 先交壳层占位契约版
---
## 支援角色
- `architect`:仅在 HOS-003 发现技术断点需要架构拍板时介入
- `backend-dev`:当前待命
- `rd-qa`:等 HOS/FE 交付第一版骨架与契约后,接验证模板对齐
+62
View File
@@ -0,0 +1,62 @@
# 开发团队第一轮任务单
项目:MRP 模拟器鸿蒙化
日期:2026-03-09
## 目标
围绕“MRP 模拟器鸿蒙化”进入第一轮开发团队收敛,输出能直接支撑 POC 的技术产物。
## 总原则
- 一期按 POC / Alpha 推进
- 先做最小闭环,不做大而全
- 优先路线:ArkTS 壳 + NAPI + C/C++ 核心
- 涉及鸿蒙平台能力与 NAPI 时优先查官方文档
## 角色任务
### 1. Architect
输出:
- Android/Mrpoid 结构 → HarmonyOS 结构映射
- 模块边界图
- JNI → NAPI 桥接映射策略
- 线程模型与运行时边界建议
### 2. HarmonyOS Senior Engineer (`harmonyos-dev`)
输出:
- HarmonyOS POC 工程结构建议
- ArkTS 与 Native 的边界
- NAPI facade 接口草案
- 官方文档检查清单
- 首批技术风险与绕法
### 3. RD Frontend
输出:
- ArkTS 壳层页面结构
- 运行页/导入页/设置页的页面流
- 组件拆分建议
- 状态管理草案
### 4. Backend Dev
输出:
- 一期是否需要 BFF / 服务端支持的判断
- 若不需要,明确边界
- 若需要,列最小 API / 配置 / 日志回传方案
### 5. RD QA
输出:
- 首批样例集选择策略
- 功能验证清单
- 兼容矩阵模板
- 性能/稳定性专项检查项
## 当前预期产物
- `docs/architecture/ANDROID_TO_HARMONY_MAPPING.md`
- `docs/harmonyos/NAPI_FACADE_DRAFT.md`
- `docs/harmonyos/POC_STRUCTURE_DRAFT.md`
- `docs/product/APP_SHELL_FLOW.md`
- `docs/qa/COMPATIBILITY_BASELINE.md`
## 当前阻塞
- 还未把现有 Mrpoid / libMrpoid 代码正式接入本仓库
- 需尽快完成可迁移性拆解
+16
View File
@@ -0,0 +1,16 @@
{
"apiType": "stageMode",
"buildOption": {
"externalNativeOptions": {
"path": "src/main/cpp/CMakeLists.txt",
"arguments": "",
"cppFlags": "-std=c++17"
}
},
"targets": [
{
"name": "default",
"runtimeOS": "HarmonyOS"
}
]
}
+6
View File
@@ -0,0 +1,6 @@
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks,
plugins: []
};
+7
View File
@@ -0,0 +1,7 @@
{
"modelVersion": "5.0.0",
"name": "entry",
"version": "1.0.0",
"description": "Entry module for MRP simulator HarmonyOS app",
"dependencies": {}
}
+23
View File
@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.5)
project(mrp_napi)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(mrp_napi SHARED
napi/module_init.cpp
napi/facade_binding.cpp
platform/MrpFacade.cpp
runtime/MrpRuntime.cpp
render/FrameBuffer.cpp
input/InputDispatcher.cpp
)
target_include_directories(mrp_napi PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/platform
${CMAKE_CURRENT_SOURCE_DIR}/runtime
${CMAKE_CURRENT_SOURCE_DIR}/render
${CMAKE_CURRENT_SOURCE_DIR}/input
${CMAKE_CURRENT_SOURCE_DIR}/napi
)
@@ -0,0 +1,7 @@
#include "InputEvent.h"
bool DispatchInput(const MrpInputEvent &event)
{
(void)event;
return true;
}
+18
View File
@@ -0,0 +1,18 @@
#ifndef MRP_INPUT_INPUT_EVENT_H
#define MRP_INPUT_INPUT_EVENT_H
#include <cstdint>
#include <string>
struct MrpInputEvent {
std::string type = "key";
std::string action = "down";
int32_t keyCode = 0;
int32_t x = 0;
int32_t y = 0;
int64_t timestamp = 0;
};
bool DispatchInput(const MrpInputEvent &event);
#endif
+224
View File
@@ -0,0 +1,224 @@
#include <node_api.h>
#include <cstring>
#include <string>
#include <vector>
#include "../input/InputEvent.h"
#include "../platform/MrpFacade.h"
namespace {
MrpFacade g_facade;
napi_value MakeString(napi_env env, const std::string &value)
{
napi_value result;
napi_create_string_utf8(env, value.c_str(), value.size(), &result);
return result;
}
napi_value MakeCommonResult(napi_env env, const CommonResult &result)
{
napi_value obj;
napi_create_object(env, &obj);
napi_value ok;
napi_get_boolean(env, result.ok, &ok);
napi_set_named_property(env, obj, "ok", ok);
napi_value errorCode;
napi_create_int32(env, result.errorCode, &errorCode);
napi_set_named_property(env, obj, "errorCode", errorCode);
napi_set_named_property(env, obj, "errorMessage", MakeString(env, result.errorMessage));
return obj;
}
std::string GetStringProperty(napi_env env, napi_value obj, const char *name, const std::string &fallback)
{
bool hasProperty = false;
napi_has_named_property(env, obj, name, &hasProperty);
if (!hasProperty) {
return fallback;
}
napi_value value;
napi_get_named_property(env, obj, name, &value);
size_t length = 0;
napi_get_value_string_utf8(env, value, nullptr, 0, &length);
std::string result(length, '\0');
napi_get_value_string_utf8(env, value, result.data(), length + 1, &length);
return result;
}
int32_t GetIntProperty(napi_env env, napi_value obj, const char *name, int32_t fallback)
{
bool hasProperty = false;
napi_has_named_property(env, obj, name, &hasProperty);
if (!hasProperty) {
return fallback;
}
napi_value value;
napi_get_named_property(env, obj, name, &value);
int32_t result = fallback;
napi_get_value_int32(env, value, &result);
return result;
}
bool GetBoolProperty(napi_env env, napi_value obj, const char *name, bool fallback)
{
bool hasProperty = false;
napi_has_named_property(env, obj, name, &hasProperty);
if (!hasProperty) {
return fallback;
}
napi_value value;
napi_get_named_property(env, obj, name, &value);
bool result = fallback;
napi_get_value_bool(env, value, &result);
return result;
}
napi_value Init(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value argv[1] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
InitOptions options;
if (argc == 1 && argv[0] != nullptr) {
options.workDir = GetStringProperty(env, argv[0], "workDir", "");
options.width = GetIntProperty(env, argv[0], "width", 240);
options.height = GetIntProperty(env, argv[0], "height", 320);
options.debug = GetBoolProperty(env, argv[0], "debug", false);
}
return MakeCommonResult(env, g_facade.Init(options));
}
napi_value LoadPackage(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value argv[1] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
std::string packagePath;
if (argc == 1 && argv[0] != nullptr) {
size_t length = 0;
napi_get_value_string_utf8(env, argv[0], nullptr, 0, &length);
packagePath.resize(length);
napi_get_value_string_utf8(env, argv[0], packagePath.data(), length + 1, &length);
}
return MakeCommonResult(env, g_facade.LoadPackage(packagePath));
}
napi_value Start(napi_env env, napi_callback_info info)
{
(void)info;
return MakeCommonResult(env, g_facade.Start());
}
napi_value Pause(napi_env env, napi_callback_info info)
{
(void)info;
return MakeCommonResult(env, g_facade.Pause());
}
napi_value Resume(napi_env env, napi_callback_info info)
{
(void)info;
return MakeCommonResult(env, g_facade.Resume());
}
napi_value SendInput(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value argv[1] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
MrpInputEvent event;
if (argc == 1 && argv[0] != nullptr) {
event.type = GetStringProperty(env, argv[0], "type", "key");
event.action = GetStringProperty(env, argv[0], "action", "down");
event.keyCode = GetIntProperty(env, argv[0], "keyCode", 0);
event.x = GetIntProperty(env, argv[0], "x", 0);
event.y = GetIntProperty(env, argv[0], "y", 0);
event.timestamp = static_cast<int64_t>(GetIntProperty(env, argv[0], "timestamp", 0));
}
return MakeCommonResult(env, g_facade.SendInput(event));
}
napi_value PullFrame(napi_env env, napi_callback_info info)
{
(void)info;
FrameResult frame = g_facade.PullFrame();
napi_value obj;
napi_create_object(env, &obj);
napi_value ok;
napi_get_boolean(env, frame.ok, &ok);
napi_set_named_property(env, obj, "ok", ok);
napi_value hasNewFrame;
napi_get_boolean(env, frame.hasNewFrame, &hasNewFrame);
napi_set_named_property(env, obj, "hasNewFrame", hasNewFrame);
napi_value width;
napi_create_int32(env, frame.width, &width);
napi_set_named_property(env, obj, "width", width);
napi_value height;
napi_create_int32(env, frame.height, &height);
napi_set_named_property(env, obj, "height", height);
napi_set_named_property(env, obj, "pixelFormat", MakeString(env, frame.pixelFormat));
void *data = nullptr;
napi_value buffer;
napi_create_arraybuffer(env, frame.buffer.size(), &data, &buffer);
if (data != nullptr && !frame.buffer.empty()) {
std::memcpy(data, frame.buffer.data(), frame.buffer.size());
}
napi_set_named_property(env, obj, "buffer", buffer);
napi_value frameId;
napi_create_int64(env, frame.frameId, &frameId);
napi_set_named_property(env, obj, "frameId", frameId);
napi_value errorCode;
napi_create_int32(env, frame.errorCode, &errorCode);
napi_set_named_property(env, obj, "errorCode", errorCode);
napi_set_named_property(env, obj, "errorMessage", MakeString(env, frame.errorMessage));
return obj;
}
napi_value Release(napi_env env, napi_callback_info info)
{
(void)info;
return MakeCommonResult(env, g_facade.Release());
}
} // namespace
napi_value ExportMrpFacade(napi_env env, napi_value exports)
{
napi_property_descriptor descriptors[] = {
{"init", nullptr, Init, nullptr, nullptr, nullptr, napi_default, nullptr},
{"loadPackage", nullptr, LoadPackage, nullptr, nullptr, nullptr, napi_default, nullptr},
{"start", nullptr, Start, nullptr, nullptr, nullptr, napi_default, nullptr},
{"pause", nullptr, Pause, nullptr, nullptr, nullptr, napi_default, nullptr},
{"resume", nullptr, Resume, nullptr, nullptr, nullptr, napi_default, nullptr},
{"sendInput", nullptr, SendInput, nullptr, nullptr, nullptr, napi_default, nullptr},
{"pullFrame", nullptr, PullFrame, nullptr, nullptr, nullptr, napi_default, nullptr},
{"release", nullptr, Release, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(descriptors) / sizeof(descriptors[0]), descriptors);
return exports;
}
+23
View File
@@ -0,0 +1,23 @@
#include <node_api.h>
napi_value ExportMrpFacade(napi_env env, napi_value exports);
static napi_value InitModule(napi_env env, napi_value exports)
{
return ExportMrpFacade(env, exports);
}
static napi_module g_mrpModule = {
1,
0,
nullptr,
InitModule,
"mrp_napi",
nullptr,
{0},
};
extern "C" __attribute__((constructor)) void RegisterMrpModule(void)
{
napi_module_register(&g_mrpModule);
}
+63
View File
@@ -0,0 +1,63 @@
#include "MrpFacade.h"
#include "../render/FrameBuffer.h"
#include "../runtime/MrpRuntime.h"
namespace {
MrpRuntime g_runtime;
}
CommonResult MrpFacade::Init(const InitOptions &options)
{
options_ = options;
return g_runtime.Init(options.width, options.height, options.debug);
}
CommonResult MrpFacade::LoadPackage(const std::string &packagePath)
{
packagePath_ = packagePath;
return g_runtime.LoadPackage(packagePath);
}
CommonResult MrpFacade::Start()
{
return g_runtime.Start();
}
CommonResult MrpFacade::Pause()
{
return g_runtime.Pause();
}
CommonResult MrpFacade::Resume()
{
return g_runtime.Resume();
}
CommonResult MrpFacade::SendInput(const MrpInputEvent &event)
{
DispatchInput(event);
return CommonResult{true, 0, ""};
}
FrameResult MrpFacade::PullFrame()
{
FrameBuffer frameBuffer(g_runtime.Width(), g_runtime.Height());
frameBuffer.FillTestPattern(g_runtime.NextFrameId());
FrameResult result;
result.ok = true;
result.hasNewFrame = true;
result.width = g_runtime.Width();
result.height = g_runtime.Height();
result.pixelFormat = "RGBA_8888";
result.buffer = frameBuffer.Data();
result.frameId = g_runtime.CurrentFrameId();
return result;
}
CommonResult MrpFacade::Release()
{
packagePath_.clear();
return g_runtime.Release();
}
+51
View File
@@ -0,0 +1,51 @@
#ifndef MRP_PLATFORM_MRP_FACADE_H
#define MRP_PLATFORM_MRP_FACADE_H
#include <cstdint>
#include <string>
#include <vector>
#include "../input/InputEvent.h"
struct InitOptions {
std::string workDir;
int32_t width = 240;
int32_t height = 320;
bool debug = false;
};
struct CommonResult {
bool ok = false;
int32_t errorCode = 0;
std::string errorMessage;
};
struct FrameResult {
bool ok = false;
bool hasNewFrame = false;
int32_t width = 0;
int32_t height = 0;
std::string pixelFormat = "RGBA_8888";
std::vector<uint8_t> buffer;
int64_t frameId = 0;
int32_t errorCode = 0;
std::string errorMessage;
};
class MrpFacade {
public:
CommonResult Init(const InitOptions &options);
CommonResult LoadPackage(const std::string &packagePath);
CommonResult Start();
CommonResult Pause();
CommonResult Resume();
CommonResult SendInput(const MrpInputEvent &event);
FrameResult PullFrame();
CommonResult Release();
private:
InitOptions options_;
std::string packagePath_;
};
#endif
+24
View File
@@ -0,0 +1,24 @@
#include "FrameBuffer.h"
FrameBuffer::FrameBuffer(int32_t width, int32_t height)
: width_(width), height_(height), rgba_(static_cast<size_t>(width) * static_cast<size_t>(height) * 4U, 0)
{
}
void FrameBuffer::FillTestPattern(int64_t frameId)
{
for (int32_t y = 0; y < height_; ++y) {
for (int32_t x = 0; x < width_; ++x) {
const size_t index = static_cast<size_t>(y * width_ + x) * 4U;
rgba_[index] = static_cast<uint8_t>((x + frameId) % 255);
rgba_[index + 1] = static_cast<uint8_t>((y + frameId) % 255);
rgba_[index + 2] = static_cast<uint8_t>((x + y) % 255);
rgba_[index + 3] = 255;
}
}
}
const std::vector<uint8_t> &FrameBuffer::Data() const
{
return rgba_;
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef MRP_RENDER_FRAME_BUFFER_H
#define MRP_RENDER_FRAME_BUFFER_H
#include <cstdint>
#include <vector>
class FrameBuffer {
public:
FrameBuffer(int32_t width, int32_t height);
void FillTestPattern(int64_t frameId);
const std::vector<uint8_t> &Data() const;
private:
int32_t width_;
int32_t height_;
std::vector<uint8_t> rgba_;
};
#endif
+75
View File
@@ -0,0 +1,75 @@
#include "MrpRuntime.h"
CommonResult MrpRuntime::Init(int32_t width, int32_t height, bool debug)
{
width_ = width > 0 ? width : 240;
height_ = height > 0 ? height : 320;
debug_ = debug;
frameId_ = 0;
state_ = State::Initialized;
return CommonResult{true, 0, ""};
}
CommonResult MrpRuntime::LoadPackage(const std::string &packagePath)
{
if (state_ != State::Initialized && state_ != State::Released) {
return CommonResult{false, 1001, "runtime not initialized"};
}
(void)packagePath;
state_ = State::Loaded;
return CommonResult{true, 0, ""};
}
CommonResult MrpRuntime::Start()
{
if (state_ != State::Loaded && state_ != State::Paused) {
return CommonResult{false, 1002, "runtime not ready to start"};
}
state_ = State::Running;
return CommonResult{true, 0, ""};
}
CommonResult MrpRuntime::Pause()
{
if (state_ != State::Running) {
return CommonResult{false, 1003, "runtime not running"};
}
state_ = State::Paused;
return CommonResult{true, 0, ""};
}
CommonResult MrpRuntime::Resume()
{
if (state_ != State::Paused) {
return CommonResult{false, 1004, "runtime not paused"};
}
state_ = State::Running;
return CommonResult{true, 0, ""};
}
CommonResult MrpRuntime::Release()
{
state_ = State::Released;
frameId_ = 0;
return CommonResult{true, 0, ""};
}
int32_t MrpRuntime::Width() const
{
return width_;
}
int32_t MrpRuntime::Height() const
{
return height_;
}
int64_t MrpRuntime::NextFrameId()
{
return ++frameId_;
}
int64_t MrpRuntime::CurrentFrameId() const
{
return frameId_;
}
+37
View File
@@ -0,0 +1,37 @@
#ifndef MRP_RUNTIME_MRP_RUNTIME_H
#define MRP_RUNTIME_MRP_RUNTIME_H
#include "../platform/MrpFacade.h"
class MrpRuntime {
public:
CommonResult Init(int32_t width, int32_t height, bool debug);
CommonResult LoadPackage(const std::string &packagePath);
CommonResult Start();
CommonResult Pause();
CommonResult Resume();
CommonResult Release();
int32_t Width() const;
int32_t Height() const;
int64_t NextFrameId();
int64_t CurrentFrameId() const;
private:
enum class State {
Idle,
Initialized,
Loaded,
Running,
Paused,
Released,
};
State state_ = State::Idle;
int32_t width_ = 240;
int32_t height_ = 320;
bool debug_ = false;
int64_t frameId_ = 0;
};
#endif
@@ -0,0 +1,26 @@
export interface NativeInstalledAppDTO {
appId: string
name: string
icon?: string
version?: string
runnable: boolean
}
export class NativeAppAdapter {
async listInstalledApps(): Promise<NativeInstalledAppDTO[]> {
return [
{
appId: 'demo.app.001',
name: 'Demo MRP App',
version: '1.0.0',
runnable: true
},
{
appId: 'demo.app.002',
name: 'Broken Sample',
version: '0.9.1',
runnable: false
}
]
}
}
@@ -0,0 +1,26 @@
export interface NativePackagePreviewDTO {
name: string
version?: string
icon?: string
size?: number
valid: boolean
}
export class NativeImportAdapter {
async pickFile(): Promise<string | null> {
return 'file://mock/demo.mrp'
}
async inspectPackage(_fileUri: string): Promise<NativePackagePreviewDTO> {
return {
name: 'Imported Demo App',
version: '1.0.0',
size: 204800,
valid: true
}
}
async importPackage(_fileUri: string): Promise<{ appId: string }> {
return { appId: 'demo.imported.001' }
}
}
@@ -0,0 +1,59 @@
import nativeMrp from 'libmrp_napi.so'
export interface NativeFrameDTO {
ok: boolean
hasNewFrame: boolean
width: number
height: number
pixelFormat: 'RGBA_8888'
buffer?: ArrayBuffer
frameId?: number
errorCode?: number
errorMessage?: string
}
function assertOk(result: { ok: boolean; errorCode?: number; errorMessage?: string }, action: string): void {
if (!result.ok) {
throw new Error(`${action} failed: ${result.errorCode ?? -1} ${result.errorMessage ?? ''}`.trim())
}
}
export class NativeRuntimeAdapter {
async startSession(appId: string): Promise<void> {
assertOk(nativeMrp.init({
workDir: '/data/storage/el2/base/files/mrp',
width: 240,
height: 320,
debug: true,
}), 'init')
assertOk(nativeMrp.loadPackage(appId), 'loadPackage')
assertOk(nativeMrp.start(), 'start')
}
async restartSession(appId: string): Promise<void> {
await this.stopSession()
await this.startSession(appId)
}
async stopSession(): Promise<void> {
assertOk(nativeMrp.release(), 'release')
}
async pullFrame(): Promise<NativeFrameDTO> {
return nativeMrp.pullFrame() as NativeFrameDTO
}
async notifyPageShow(): Promise<void> {
const result = nativeMrp.resume()
if (!result.ok) {
return
}
}
async notifyPageHide(): Promise<void> {
const result = nativeMrp.pause()
if (!result.ok) {
return
}
}
}
@@ -0,0 +1,11 @@
import nativeMrp from 'libmrp_napi.so';
export function smokeTestNativeInit(): boolean {
const result = nativeMrp.init({
workDir: '/data/storage/el2/base/files/mrp',
width: 240,
height: 320,
debug: true,
});
return !!result?.ok;
}
@@ -0,0 +1,11 @@
@Component
export struct AppCard {
@Prop title: string = ''
build() {
Column() {
Text(this.title)
}
.padding(16)
}
}
@@ -0,0 +1,33 @@
import type { AppItemVM } from '../../models/AppItemVM'
@Component
export struct AppListView {
@Prop items: AppItemVM[] = []
onItemTap?: (appId: string) => void
build() {
List() {
ForEach(this.items, (item: AppItemVM) => {
ListItem() {
Column() {
Text(item.name).fontSize(18)
Text(item.version || '').fontSize(12)
Text(item.status === 'ready' ? '可运行' : '不可运行').fontSize(12)
}
.width('100%')
.padding(16)
.opacity(item.status === 'ready' ? 1 : 0.5)
.alignItems(HorizontalAlign.Start)
}
.onClick(() => {
if (item.status !== 'ready') {
return
}
if (this.onItemTap) {
this.onItemTap(item.id)
}
})
}, (item: AppItemVM) => item.id)
}
}
}
@@ -0,0 +1,13 @@
@Component
export struct ImportEntryButton {
onTap?: () => void
build() {
Button('导入应用')
.onClick(() => {
if (this.onTap) {
this.onTap()
}
})
}
}
@@ -0,0 +1,13 @@
@Component
export struct ConfirmDialog {
@Prop title: string = '确认'
@Prop content: string = ''
build() {
Column() {
Text(this.title)
Text(this.content).margin({ top: 8 })
}
.padding(16)
}
}
@@ -0,0 +1,12 @@
@Component
export struct EmptyState {
@Prop text: string = '暂无数据'
build() {
Column() {
Text(this.text)
}
.width('100%')
.padding(24)
}
}
@@ -0,0 +1,13 @@
@Component
export struct LoadingBlock {
@Prop text: string = '加载中'
build() {
Column() {
LoadingProgress()
Text(this.text).margin({ top: 8 })
}
.width('100%')
.padding(16)
}
}
@@ -0,0 +1,12 @@
@Component
export struct PageHeader {
@Prop title: string = ''
build() {
Row() {
Text(this.title).fontSize(20).fontWeight(FontWeight.Medium)
}
.width('100%')
.padding(16)
}
}
@@ -0,0 +1,13 @@
@Component
export struct StatusBanner {
@Prop text: string = ''
build() {
if (this.text) {
Text(this.text)
.width('100%')
.padding(12)
.backgroundColor('#FFF3CD')
}
}
}
@@ -0,0 +1,12 @@
@Component
export struct ImportProgressPanel {
@Prop text: string = '导入中'
build() {
Column() {
LoadingProgress()
Text(this.text).margin({ top: 8 })
}
.padding(16)
}
}
@@ -0,0 +1,8 @@
@Component
export struct ImportResultPanel {
@Prop text: string = ''
build() {
Text(this.text).padding(16)
}
}
@@ -0,0 +1,13 @@
@Component
export struct ImportSourceSelector {
onPick?: () => void
build() {
Button('选择本地文件')
.onClick(() => {
if (this.onPick) {
this.onPick()
}
})
}
}
@@ -0,0 +1,11 @@
@Component
export struct PackagePreviewCard {
@Prop name: string = ''
build() {
Column() {
Text(this.name || '未选择文件')
}
.padding(16)
}
}
@@ -0,0 +1,43 @@
@Component
export struct RuntimeContainer {
@Prop hint: string = 'Runtime Surface Placeholder'
@Prop hasFrame: boolean = false
@Prop frameId: number = 0
@Prop frameWidth: number = 0
@Prop frameHeight: number = 0
private frameColor(): string {
const palette: string[] = ['#DCEBFF', '#C6F6D5', '#FEEBC8', '#FED7E2', '#E9D8FD']
return this.hasFrame ? palette[this.frameId % palette.length] : '#F3F4F6'
}
build() {
Column({ space: 12 }) {
Text('MRP Runtime Surface Placeholder')
.fontSize(18)
.fontWeight(FontWeight.Medium)
Stack() {
Column() {
Text(this.hasFrame ? `测试帧 #${this.frameId}` : '尚未拉到测试帧')
.fontSize(18)
.fontWeight(FontWeight.Bold)
Text(this.hasFrame ? `${this.frameWidth} x ${this.frameHeight}` : '等待 pullFrame()')
.fontSize(14)
.fontColor('#666666')
}
}
.width('88%')
.aspectRatio(3 / 4)
.backgroundColor(this.frameColor())
.borderRadius(16)
.padding(16)
Text(this.hint)
.fontSize(14)
.fontColor('#666666')
}
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.layoutWeight(1)
}
}
@@ -0,0 +1,10 @@
@Component
export struct RuntimeStatusOverlay {
@Prop text: string = ''
build() {
if (this.text) {
Text(this.text).padding(16)
}
}
}
@@ -0,0 +1,42 @@
@Component
export struct RuntimeToolbar {
onBack?: () => void
onRestart?: () => void
onPullFrame?: () => void
onExit?: () => void
@Prop canRestart: boolean = true
@Prop canPullFrame: boolean = true
@Prop canExit: boolean = true
build() {
Row({ space: 12 }) {
Button('返回').onClick(() => {
if (this.onBack) {
this.onBack()
}
})
Button('重启')
.enabled(this.canRestart)
.onClick(() => {
if (this.onRestart) {
this.onRestart()
}
})
Button('拉帧')
.enabled(this.canPullFrame)
.onClick(() => {
if (this.onPullFrame) {
this.onPullFrame()
}
})
Button('退出')
.enabled(this.canExit)
.onClick(() => {
if (this.onExit) {
this.onExit()
}
})
}
.padding(16)
}
}
@@ -0,0 +1,18 @@
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
import hilog from '@ohos.hilog';
const DOMAIN = 0xFF00;
const TAG = 'EntryAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/ShellRootPage', (err) => {
if (err.code) {
hilog.error(DOMAIN, TAG, 'Failed to load ShellRootPage: %{public}s', JSON.stringify(err));
return;
}
hilog.info(DOMAIN, TAG, 'ShellRootPage loaded');
});
}
}
+44
View File
@@ -0,0 +1,44 @@
declare module 'libmrp_napi.so' {
export function init(options: {
workDir: string;
width: number;
height: number;
debug?: boolean;
}): {
ok: boolean;
errorCode?: number;
errorMessage?: string;
};
export function loadPackage(packagePath: string): {
ok: boolean;
errorCode?: number;
errorMessage?: string;
};
export function start(): { ok: boolean; errorCode?: number; errorMessage?: string };
export function pause(): { ok: boolean; errorCode?: number; errorMessage?: string };
export function resume(): { ok: boolean; errorCode?: number; errorMessage?: string };
export function sendInput(event: {
type: 'key' | 'touch';
action: 'down' | 'up' | 'move';
keyCode?: number;
x?: number;
y?: number;
timestamp?: number;
}): { ok: boolean; errorCode?: number; errorMessage?: string };
export function pullFrame(): {
ok: boolean;
hasNewFrame: boolean;
width: number;
height: number;
pixelFormat: 'RGBA_8888';
buffer?: ArrayBuffer;
frameId?: number;
errorCode?: number;
errorMessage?: string;
};
export function release(): { ok: boolean; errorCode?: number; errorMessage?: string };
}
+7
View File
@@ -0,0 +1,7 @@
export interface AppItemVM {
id: string
name: string
icon?: string
version?: string
status: 'ready' | 'invalid'
}
@@ -0,0 +1,7 @@
export interface PackagePreviewVM {
name: string
version?: string
icon?: string
sizeText?: string
valid: boolean
}
@@ -0,0 +1 @@
export type RuntimePhase = 'idle' | 'starting' | 'running' | 'error' | 'stopped'
+4
View File
@@ -0,0 +1,4 @@
export interface UiError {
message: string
retryable: boolean
}
+91
View File
@@ -0,0 +1,91 @@
import { AppCatalogStore } from '../store/AppCatalogStore'
import { PageHeader } from '../components/common/PageHeader'
import { LoadingBlock } from '../components/common/LoadingBlock'
import { EmptyState } from '../components/common/EmptyState'
import { StatusBanner } from '../components/common/StatusBanner'
import { ImportEntryButton } from '../components/appList/ImportEntryButton'
import { AppListView } from '../components/appList/AppListView'
@Component
export struct AppListPage {
@Prop refreshToken: number = 0
onNavigateImport?: () => void
onNavigateRun?: (appId: string) => void
@State refreshTick: number = 0
@State selectedAppId: string = ''
private lastHandledRefreshToken: number = -1
private store: AppCatalogStore = new AppCatalogStore()
private unsubscribe?: () => void
aboutToAppear(): void {
if (!this.unsubscribe) {
this.unsubscribe = this.store.subscribe(() => {
this.refreshTick += 1
})
}
this.store.loadApps()
}
aboutToDisappear(): void {
if (this.unsubscribe) {
this.unsubscribe()
this.unsubscribe = undefined
}
}
private ensureRefreshByToken(): void {
if (this.refreshToken === this.lastHandledRefreshToken) {
return
}
this.lastHandledRefreshToken = this.refreshToken
this.store.refreshApps()
}
private openImportPage(): void {
if (this.onNavigateImport) {
this.onNavigateImport()
return
}
console.info('TODO: open ImportPage')
}
private openRunPage(appId: string): void {
this.selectedAppId = appId
if (this.onNavigateRun) {
this.onNavigateRun(appId)
return
}
console.info(`TODO: open RunPage for ${appId}`)
}
build() {
this.ensureRefreshByToken()
Column() {
Text(`${this.refreshTick}-${this.refreshToken}`).fontSize(1).opacity(0)
PageHeader({ title: '应用列表' })
StatusBanner({ text: '运行入口:点击“可运行”应用卡片进入运行页;导入入口:点击下方“导入应用”。' })
if (this.selectedAppId) {
StatusBanner({ text: `已选择应用:${this.selectedAppId}` })
}
if (this.store.error) {
StatusBanner({ text: this.store.error.message })
}
if (this.store.loading) {
LoadingBlock({ text: '正在加载应用列表' })
} else if (this.store.items.length === 0) {
EmptyState({ text: '暂无已导入应用' })
ImportEntryButton({ onTap: () => this.openImportPage() })
} else {
AppListView({
items: this.store.items,
onItemTap: (appId: string) => this.openRunPage(appId)
})
ImportEntryButton({ onTap: () => this.openImportPage() })
}
}
.width('100%')
.height('100%')
}
}
+88
View File
@@ -0,0 +1,88 @@
import { ImportStore } from '../store/ImportStore'
import { PageHeader } from '../components/common/PageHeader'
import { StatusBanner } from '../components/common/StatusBanner'
import { ImportSourceSelector } from '../components/import/ImportSourceSelector'
import { PackagePreviewCard } from '../components/import/PackagePreviewCard'
import { ImportProgressPanel } from '../components/import/ImportProgressPanel'
import { ImportResultPanel } from '../components/import/ImportResultPanel'
@Component
export struct ImportPage {
onBack?: () => void
onImportSuccess?: () => void
@State refreshTick: number = 0
private store: ImportStore = new ImportStore()
private unsubscribe?: () => void
aboutToAppear(): void {
if (!this.unsubscribe) {
this.unsubscribe = this.store.subscribe(() => {
this.refreshTick += 1
})
}
}
aboutToDisappear(): void {
if (this.unsubscribe) {
this.unsubscribe()
this.unsubscribe = undefined
}
this.store.reset()
}
private onBackClick(): void {
this.store.reset()
if (this.onBack) {
this.onBack()
}
}
private async onPickFile(): Promise<void> {
await this.store.pickFile()
await this.store.analyzeSelectedFile()
}
private async onImport(): Promise<void> {
await this.store.startImport()
if (this.store.phase === 'success') {
this.store.reset()
if (this.onImportSuccess) {
this.onImportSuccess()
}
}
}
build() {
Column() {
Text(`${this.refreshTick}`).fontSize(1).opacity(0)
PageHeader({ title: '导入应用' })
if (this.onBack) {
Button('返回列表').onClick(() => {
this.onBackClick()
}).margin({ bottom: 8, left: 16, right: 16 })
}
if (this.store.error) {
StatusBanner({ text: this.store.error.message })
}
ImportSourceSelector({ onPick: () => this.onPickFile() })
if (this.store.previewInfo) {
PackagePreviewCard({ name: this.store.previewInfo.name })
Button('开始导入').onClick(() => {
this.onImport()
}).margin(16)
}
if (this.store.phase === 'importing') {
ImportProgressPanel({ text: '导入中' })
}
if (this.store.phase === 'success') {
ImportResultPanel({ text: '导入成功,正在返回列表' })
}
if (this.store.phase === 'failed') {
ImportResultPanel({ text: '导入失败' })
}
}
.width('100%')
.height('100%')
}
}
+96
View File
@@ -0,0 +1,96 @@
import { RuntimeSessionStore } from '../store/RuntimeSessionStore'
import { PageHeader } from '../components/common/PageHeader'
import { StatusBanner } from '../components/common/StatusBanner'
import { ConfirmDialog } from '../components/common/ConfirmDialog'
import { RuntimeContainer } from '../components/runtime/RuntimeContainer'
import { RuntimeToolbar } from '../components/runtime/RuntimeToolbar'
import { RuntimeStatusOverlay } from '../components/runtime/RuntimeStatusOverlay'
@Component
export struct RunPage {
appId?: string
onBack?: () => void
@State refreshTick: number = 0
private store: RuntimeSessionStore = new RuntimeSessionStore()
private unsubscribe?: () => void
aboutToAppear(): void {
if (!this.unsubscribe) {
this.unsubscribe = this.store.subscribe(() => {
this.refreshTick += 1
})
}
if (this.appId) {
this.store.startSession(this.appId)
}
}
aboutToDisappear(): void {
if (this.unsubscribe) {
this.unsubscribe()
this.unsubscribe = undefined
}
}
private onBackClick(): void {
if (this.onBack) {
this.onBack()
return
}
console.info('TODO: back to AppListPage')
}
private async onRestart(): Promise<void> {
await this.store.restartSession()
}
private async onPullFrame(): Promise<void> {
await this.store.refreshFrame()
}
private async onExit(): Promise<void> {
await this.store.stopSession()
if (this.onBack) {
this.onBack()
}
}
build() {
Column() {
Text(`${this.refreshTick}`).fontSize(1).opacity(0)
PageHeader({ title: '运行页' })
if (this.appId) {
StatusBanner({ text: `当前应用:${this.appId}` })
}
StatusBanner({ text: this.store.runtimeHint })
if (this.store.error) {
StatusBanner({ text: this.store.error.message })
}
RuntimeToolbar({
canRestart: this.store.canRestart,
canPullFrame: this.store.phase === 'running',
canExit: this.store.canExit,
onBack: () => this.onBackClick(),
onRestart: () => this.onRestart(),
onPullFrame: () => this.onPullFrame(),
onExit: () => this.onExit()
})
RuntimeContainer({
hint: this.store.runtimeHint,
hasFrame: this.store.frame.hasFrame,
frameId: this.store.frame.frameId,
frameWidth: this.store.frame.width,
frameHeight: this.store.frame.height,
})
if (this.store.phase !== 'running') {
RuntimeStatusOverlay({ text: `当前状态:${this.store.phase}` })
}
if (this.store.phase === 'stopped') {
ConfirmDialog({ title: '运行已结束', content: '当前会话已停止' })
}
}
.width('100%')
.height('100%')
}
}
@@ -0,0 +1,58 @@
import { AppListPage } from './AppListPage'
import { ImportPage } from './ImportPage'
import { RunPage } from './RunPage'
export type ShellRoute = 'appList' | 'import' | 'run'
@Entry
@Component
struct ShellRootPage {
@State currentRoute: ShellRoute = 'appList'
@State currentAppId: string = ''
@State catalogRefreshTick: number = 0
private goToImport(): void {
this.currentRoute = 'import'
}
private goToRun(appId: string): void {
this.currentAppId = appId
this.currentRoute = 'run'
}
private backToList(): void {
this.currentRoute = 'appList'
}
private backToListAfterImport(): void {
this.catalogRefreshTick += 1
this.currentRoute = 'appList'
}
build() {
Column() {
Text(`${this.catalogRefreshTick}`).fontSize(1).opacity(0)
if (this.currentRoute === 'appList') {
AppListPage({
refreshToken: this.catalogRefreshTick,
onNavigateImport: () => this.goToImport(),
onNavigateRun: (appId: string) => this.goToRun(appId)
})
}
if (this.currentRoute === 'import') {
ImportPage({
onBack: () => this.backToList(),
onImportSuccess: () => this.backToListAfterImport()
})
}
if (this.currentRoute === 'run') {
RunPage({
appId: this.currentAppId,
onBack: () => this.backToList()
})
}
}
.width('100%')
.height('100%')
}
}
+17
View File
@@ -0,0 +1,17 @@
import { NativeAppAdapter } from '../adapters/NativeAppAdapter'
import type { AppItemVM } from '../models/AppItemVM'
export class AppService {
constructor(private readonly adapter: NativeAppAdapter = new NativeAppAdapter()) {}
async listApps(): Promise<AppItemVM[]> {
const apps = await this.adapter.listInstalledApps()
return apps.map((item) => ({
id: item.appId,
name: item.name,
icon: item.icon,
version: item.version,
status: item.runnable ? 'ready' : 'invalid'
}))
}
}
@@ -0,0 +1,25 @@
import { NativeImportAdapter } from '../adapters/NativeImportAdapter'
import type { PackagePreviewVM } from '../models/PackagePreviewVM'
export class ImportService {
constructor(private readonly adapter: NativeImportAdapter = new NativeImportAdapter()) {}
async pickMrpFile(): Promise<string | null> {
return this.adapter.pickFile()
}
async analyzePackage(fileUri: string): Promise<PackagePreviewVM> {
const result = await this.adapter.inspectPackage(fileUri)
return {
name: result.name,
version: result.version,
icon: result.icon,
sizeText: result.size ? `${result.size}` : undefined,
valid: result.valid
}
}
async importPackage(fileUri: string): Promise<{ appId: string }> {
return this.adapter.importPackage(fileUri)
}
}
@@ -0,0 +1,47 @@
import { NativeRuntimeAdapter } from '../adapters/NativeRuntimeAdapter'
export interface RuntimeFrameVM {
hasFrame: boolean
width: number
height: number
frameId: number
pixelFormat: string
}
export class RuntimeService {
constructor(private readonly adapter: NativeRuntimeAdapter = new NativeRuntimeAdapter()) {}
async start(appId: string): Promise<void> {
await this.adapter.startSession(appId)
}
async restart(appId: string): Promise<void> {
await this.adapter.restartSession(appId)
}
async stop(): Promise<void> {
await this.adapter.stopSession()
}
async pullFrame(): Promise<RuntimeFrameVM> {
const frame = await this.adapter.pullFrame()
if (!frame.ok) {
throw new Error(frame.errorMessage || 'pullFrame failed')
}
return {
hasFrame: frame.hasNewFrame,
width: frame.width,
height: frame.height,
frameId: frame.frameId ?? 0,
pixelFormat: frame.pixelFormat,
}
}
async onPageShow(): Promise<void> {
await this.adapter.notifyPageShow()
}
async onPageHide(): Promise<void> {
await this.adapter.notifyPageHide()
}
}
@@ -0,0 +1,37 @@
import { AppService } from '../services/AppService'
import type { AppItemVM } from '../models/AppItemVM'
import type { UiError } from '../models/UiError'
import { StoreObserver } from './StoreObserver'
export class AppCatalogStore extends StoreObserver {
items: AppItemVM[] = []
loading: boolean = false
error: UiError | null = null
constructor(private readonly service: AppService = new AppService()) {
super()
}
async loadApps(): Promise<void> {
this.loading = true
this.error = null
this.notify()
try {
this.items = await this.service.listApps()
} catch (_error) {
this.error = { message: '应用列表加载失败', retryable: true }
} finally {
this.loading = false
this.notify()
}
}
async refreshApps(): Promise<void> {
await this.loadApps()
}
clearError(): void {
this.error = null
this.notify()
}
}
+64
View File
@@ -0,0 +1,64 @@
import { ImportService } from '../services/ImportService'
import type { PackagePreviewVM } from '../models/PackagePreviewVM'
import type { UiError } from '../models/UiError'
import { StoreObserver } from './StoreObserver'
export type ImportPhase = 'idle' | 'picking' | 'analyzing' | 'importing' | 'success' | 'failed'
export class ImportStore extends StoreObserver {
phase: ImportPhase = 'idle'
selectedFile: string | null = null
previewInfo: PackagePreviewVM | null = null
error: UiError | null = null
constructor(private readonly service: ImportService = new ImportService()) {
super()
}
async pickFile(): Promise<void> {
this.phase = 'picking'
this.notify()
this.selectedFile = await this.service.pickMrpFile()
this.phase = this.selectedFile ? 'analyzing' : 'idle'
this.notify()
}
async analyzeSelectedFile(): Promise<void> {
if (!this.selectedFile) {
return
}
try {
this.previewInfo = await this.service.analyzePackage(this.selectedFile)
this.phase = 'idle'
} catch (_error) {
this.phase = 'failed'
this.error = { message: '包解析失败', retryable: true }
}
this.notify()
}
async startImport(): Promise<void> {
if (!this.selectedFile) {
return
}
this.phase = 'importing'
this.error = null
this.notify()
try {
await this.service.importPackage(this.selectedFile)
this.phase = 'success'
} catch (_error) {
this.phase = 'failed'
this.error = { message: '导入失败', retryable: true }
}
this.notify()
}
reset(): void {
this.phase = 'idle'
this.selectedFile = null
this.previewInfo = null
this.error = null
this.notify()
}
}
@@ -0,0 +1,107 @@
import { RuntimeService } from '../services/RuntimeService'
import type { RuntimeFrameVM } from '../services/RuntimeService'
import type { UiError } from '../models/UiError'
import type { RuntimePhase } from '../models/RuntimeSessionState'
import { StoreObserver } from './StoreObserver'
export class RuntimeSessionStore extends StoreObserver {
currentAppId: string | null = null
phase: RuntimePhase = 'idle'
error: UiError | null = null
canRestart: boolean = false
canExit: boolean = false
runtimeHint: string = '等待启动'
frame: RuntimeFrameVM = {
hasFrame: false,
width: 0,
height: 0,
frameId: 0,
pixelFormat: 'RGBA_8888',
}
constructor(private readonly service: RuntimeService = new RuntimeService()) {
super()
}
async startSession(appId: string): Promise<void> {
this.currentAppId = appId
this.phase = 'starting'
this.error = null
this.canRestart = false
this.canExit = false
this.runtimeHint = '正在初始化 Native/NAPI...'
this.notify()
try {
await this.service.start(appId)
this.phase = 'running'
this.canRestart = true
this.canExit = true
this.runtimeHint = 'Native/NAPI 已连通,准备拉取测试帧'
await this.refreshFrame()
} catch (error) {
this.phase = 'error'
this.error = { message: '启动失败', retryable: true }
this.runtimeHint = error instanceof Error ? error.message : 'Native/NAPI 启动失败'
}
this.notify()
}
async restartSession(): Promise<void> {
if (!this.currentAppId) {
return
}
this.phase = 'starting'
this.error = null
this.canRestart = false
this.runtimeHint = '正在重启 Native/NAPI...'
this.notify()
try {
await this.service.restart(this.currentAppId)
this.phase = 'running'
this.canRestart = true
this.canExit = true
this.runtimeHint = '重启完成,准备重新拉取测试帧'
await this.refreshFrame()
} catch (error) {
this.phase = 'error'
this.error = { message: '重启失败', retryable: true }
this.runtimeHint = error instanceof Error ? error.message : '重启失败'
}
this.notify()
}
async stopSession(): Promise<void> {
await this.service.stop()
this.phase = 'stopped'
this.canExit = false
this.canRestart = false
this.runtimeHint = '运行会话已释放'
this.frame = {
hasFrame: false,
width: 0,
height: 0,
frameId: 0,
pixelFormat: 'RGBA_8888',
}
this.notify()
}
async refreshFrame(): Promise<void> {
try {
const frame = await this.service.pullFrame()
this.frame = frame
this.runtimeHint = frame.hasFrame
? `已拉到测试帧 #${frame.frameId}(${frame.width}x${frame.height} ${frame.pixelFormat})`
: '当前未返回新帧'
} catch (error) {
this.runtimeHint = error instanceof Error ? error.message : 'pullFrame 失败'
this.error = { message: '拉帧失败', retryable: true }
}
this.notify()
}
clearError(): void {
this.error = null
this.notify()
}
}
+16
View File
@@ -0,0 +1,16 @@
export type StoreListener = () => void
export class StoreObserver {
private listeners: Set<StoreListener> = new Set()
subscribe(listener: StoreListener): () => void {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
protected notify(): void {
this.listeners.forEach((listener) => listener())
}
}
+27
View File
@@ -0,0 +1,27 @@
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:entry_ability_desc",
"icon": "$media:app_icon",
"label": "$string:app_name",
"startWindowIcon": "$media:app_icon",
"startWindowBackground": "$color:start_window_background",
"exported": true
}
]
}
}
@@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}
@@ -0,0 +1,16 @@
{
"string": [
{
"name": "app_name",
"value": "MRP Simulator"
},
{
"name": "module_desc",
"value": "MRP simulator HarmonyOS entry module"
},
{
"name": "entry_ability_desc",
"value": "MRP simulator entry ability"
}
]
}
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
<rect width="256" height="256" rx="48" fill="#0A59F7"/>
<text x="128" y="148" text-anchor="middle" font-size="84" fill="#FFFFFF" font-family="sans-serif">M</text>
</svg>

After

Width:  |  Height:  |  Size: 262 B

@@ -0,0 +1,5 @@
{
"src": [
"pages/ShellRootPage"
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"modelVersion": "5.0.0",
"dependencies": {},
"execution": {}
}
+6
View File
@@ -0,0 +1,6 @@
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks,
plugins: []
};
Executable
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env sh
set -eu
if [ -x "./node_modules/.bin/hvigor" ]; then
exec ./node_modules/.bin/hvigor "$@"
fi
if command -v hvigor >/dev/null 2>&1; then
exec hvigor "$@"
fi
echo "hvigor not found." >&2
echo "Open this project in DevEco Studio first, or install hvigor in your environment, then rerun ./hvigorw." >&2
exit 127
+17
View File
@@ -0,0 +1,17 @@
@echo off
setlocal
if exist .\node_modules\.bin\hvigor.cmd (
.\node_modules\.bin\hvigor.cmd %*
exit /b %errorlevel%
)
where hvigor >nul 2>nul
if %errorlevel%==0 (
hvigor %*
exit /b %errorlevel%
)
echo hvigor not found.
echo Open this project in DevEco Studio first, or install hvigor in your environment, then rerun hvigorw.bat.
exit /b 127
+4
View File
@@ -0,0 +1,4 @@
# Copy this file to local.properties and replace the path with your local HarmonyOS SDK path.
# Example (Windows): hwsdk.dir=C:\\Users\\you\\Huawei\\Sdk
# Example (macOS/Linux): hwsdk.dir=/Users/you/Huawei/Sdk
hwsdk.dir=/absolute/path/to/HarmonyOS/Sdk
+7
View File
@@ -0,0 +1,7 @@
{
"modelVersion": "5.0.0",
"name": "mrp-simulator-harmonyos",
"version": "1.0.0",
"description": "HarmonyOS shell for MRP simulator",
"dependencies": {}
}
+256
View File
@@ -0,0 +1,256 @@
# 开源调研:MRP 模拟器如何做鸿蒙化
日期:2026-03-09
## 结论先说
当前公开能参考的 MRP 开源项目,**最有价值的不是“鸿蒙版现成项目”**,而是:
1. **已有 Android 时代的 Mrpoid 开源实现**
2. **HarmonyOS 上现成的 NAPI/C++ 工具链与样例**
所以这事最合理的鸿蒙化路线不是“从零重写一个 ArkTS 模拟器”,而是:
- **复用 Mrpoid / libMrpoid 这类 C/C++ 模拟器核心思路**
- **把 Android Java 壳替换成 HarmonyOS ArkTS 壳**
- **用 NAPI 把 ArkTS 与 C/C++ 内核桥起来**
---
## 一、找到的 MRP 开源项目
### 1) Yichou/mrpoid2018
- 地址:`https://github.com/Yichou/mrpoid2018`
- 特征:
- GitHub 搜索结果中最成熟的公开仓库之一
- README 明确是 Mrpoid 开源项目
- 目录结构包含:
- `app/`
- `lib/`
- 语言占比大致为:
- C 80%+
- Java 17%+
- 这说明它本质上是:
- **C/C++ 为主的模拟器内核**
- 外面包一层 **Android Java 应用壳**
### 2) Yichou/libMrpoid
- 地址:`https://github.com/Yichou/libMrpoid`
- 特征:
- 项目描述直接写了:**mrpoid 内核(依赖项目)**
- 价值:
- 这是“可复用核心”的关键线索
- 如果要做鸿蒙化,最值得研究的就是它的:
- 运行时核心
- 渲染/事件循环
- 文件/音频/输入抽象
### 3) 其他派生仓库
GitHub / Gitee 上还能看到一些派生或镜像:
- `msojocs/mrpoid2022`
- `FormatFa/Mrpoid`
- Gitee 上的 `mrpoid`、`mrpoid2018`、`mrpoid2400` 等
这些仓库的价值主要是:
- 看别人二次开发改了什么
- 看兼容性补丁是怎么堆的
- 看 Android 侧壳层与 native 核心是怎么连接的
但**主参考源仍应优先放在 `mrpoid2018` + `libMrpoid`**。
---
## 二、没有找到什么
### 1) 没找到成熟的“现成鸿蒙版 MRP 模拟器”
没有查到一个成熟、被广泛使用的:
- HarmonyOS 版 MRP 模拟器
- OpenHarmony 版 Mrpoid
- Mythroad Emulator 原生鸿蒙实现
这意味着:
- 这事没有现成答案可直接 fork 完事
- 但也说明**路线更应该走“内核迁移 + 壳层重建”**,而不是幻想找现成成品
### 2) “mythroad emulator” 直接关键词命中很差
说明开源世界里更多还是围绕 **Mrpoid** 这个名字沉淀,而不是围绕 Mythroad 关键字。
---
## 三、找到的 HarmonyOS / NAPI 可复用项目
### 1) ohos-transplant/ohos_utils
- 地址:`https://gitee.com/thirdparty-transplant/ohos_utils`
- 页面描述显示:
- 提供更优雅的 HarmonyOS NAPI C++ 接口封装
- 支持函数、interface、class、异步处理、多线程、运行时切换等
- 价值:
- 适合在鸿蒙化时减少手写 NAPI 胶水代码
- 尤其适合复杂 C++ 能力对 ArkTS 暴露时做统一封装
### 2) ohos-transplant/napi_generator
- 地址:`https://gitee.com/thirdparty-transplant/napi_generator`
- 页面说明:
- 能从 `.d.ts` 生成 NAPI C++ 代码与测试代码
- 生成完成度可达 90%+
- 可生成 `CMakeLists.txt`、`*_napi.cpp`、`napi_init.cpp` 等
- 价值:
- 非常适合我们未来做:
- `index.d.ts`
- `SimulatorFacade.d.ts`
- 然后自动生成一版 NAPI 桥接骨架
- 可以显著减少 ArkTS ↔ C++ 桥接的体力活
---
## 四、从开源项目反推出的“鸿蒙化正确姿势”
结合 Mrpoid 的结构和 HarmonyOS 的 NAPI 工具链,当前最靠谱的方案是:
### 路线:内核复用 + 壳层替换 + 桥接重建
#### 1. 复用/迁移 C/C++ 核心
重点研究并尽量复用:
- MRP 解释执行核心
- 事件循环
- 虚拟机/内存模型
- 兼容性补丁逻辑
- 部分渲染与输入抽象
#### 2. 丢掉 Android Java 壳
Android 侧这些东西不要硬搬:
- Activity / SurfaceView 组织方式
- Android 专属输入/权限/生命周期写法
- 旧 JNI 接口形态
这些在鸿蒙要替换成:
- ArkTS 页面
- UIAbility / Stage Model 生命周期
- HarmonyOS 文件/输入/音频能力
#### 3. 用 NAPI 代替 JNI
把 Android 的 JNI 桥接思路换成:
- ArkTS 定义 facade 接口
- NAPI 暴露粗粒度 native 方法
- C++ 内核留在 native 层运行
建议桥接接口从最小集合开始:
- `init()`
- `loadPackage()`
- `start()`
- `pause()`
- `resume()`
- `stop()`
- `sendKey()`
- `sendTouch()`
- `saveState()`
- `loadState()`
- `setOption()`
#### 4. 渲染链路按“先跑通,再优化”推进
从旧 Mrpoid 的历史信息可以看出,它本来就长期在处理:
- Surface 刷新
- 多线程冲突
- 花屏/闪退
- 音乐接口
- 后台返回重启等问题
这说明鸿蒙化时不要想当然:
- 一开始先做 **最小可跑通渲染链路**
- 然后再处理:
- 帧率
- 缩放
- 触摸映射
- 音频同步
- 前后台切换
---
## 五、当前最推荐的落地顺序
### Phase 1:研究现有 Mrpoid 结构
优先研究:
- `mrpoid2018/app`
- `mrpoid2018/lib`
- `libMrpoid`
要回答的问题:
- 哪部分是 UI 壳?
- 哪部分是真正内核?
- JNI 接口有哪些?
- 渲染输出怎么组织?
- 音频、输入、文件、线程模型怎么做的?
### Phase 2:设计 HarmonyOS 壳层
在当前仓库先定义:
- ArkTS 页面壳
- 生命周期
- 文件导入
- 运行页容器
- 控制层/按键层
### Phase 3:定义 NAPI 接口草案
先写 `.d.ts` 或接口草案,再决定是否用生成器:
- `SimulatorModule`
- `RuntimeController`
- `InputBridge`
- `StorageBridge`
### Phase 4:做最小 POC
目标不是全兼容,而是:
- 跑起一个样例
- 有画面
- 能输入
- 能退出
---
## 六、对我们项目的直接启发
### 启发 1:不要走“纯 ArkTS 重写模拟器核心”路线
从公开 Mrpoid 结构看,核心明显偏 native。
如果我们现在直接用 ArkTS 重写整个模拟器核心,风险会非常高:
- 性能不稳
- 渲染和音频压力大
- 历史兼容细节难抄
### 启发 2:最该抄的是“结构”,不是“界面”
真正该抄的是:
- 核心/壳层边界
- 渲染/输入/文件/音频抽象
- 兼容补丁机制
不是旧 Android UI 长什么样。
### 启发 3:NAPI 工具链可以明显加速鸿蒙化
我们后面如果先把 ArkTS 接口收敛好,再用:
- `ohos_utils`
- `napi_generator`
去减少桥接代码,会比全手搓靠谱得多。
---
## 七、当前建议
当前建议非常明确:
> **先以 `mrpoid2018 + libMrpoid` 作为内核研究样本,按“ArkTS 壳 + NAPI + C/C++ 核心”路线做鸿蒙化。**
这条路线比“纯 ArkTS 重写”靠谱,也比“照搬 Android 工程”清醒。
---
## 八、下一步可执行动作
1. 把 `mrpoid2018` / `libMrpoid` 拉到本地做结构审查
2. 输出一份:
- Android 结构 → HarmonyOS 结构映射表
3. 输出一份:
- JNI 接口 → NAPI 接口草案
4. 在本仓库补:
- HarmonyOS POC 目录结构
- NAPI facade 设计文档
如果继续推进,下一步最值的是:
**直接把 `mrpoid2018` 代码拉下来做一次“可迁移性拆解”。**
+3
View File
@@ -4,3 +4,6 @@
- 样例整理脚本
- 调研辅助脚本
- 构建/验证辅助脚本
当前可用:
- `check-init-env.sh`:检查仓库是否具备最小初始化前置(工程壳、wrapper、local.properties、hwsdk.dir、hvigor/node)
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT_DIR"
status() {
printf '%-32s %s\n' "$1" "$2"
}
check_file() {
local path="$1"
if [ -e "$path" ]; then
status "$path" "OK"
else
status "$path" "MISSING"
return 1
fi
}
FAILED=0
echo "[MRP HarmonyOS Init Check]"
echo "root=$ROOT_DIR"
echo "\n# Project shell files"
check_file "AppScope/app.json5" || FAILED=1
check_file "build-profile.json5" || FAILED=1
check_file "hvigorfile.ts" || FAILED=1
check_file "oh-package.json5" || FAILED=1
check_file "entry/hvigorfile.ts" || FAILED=1
check_file "entry/oh-package.json5" || FAILED=1
check_file "entry/build-profile.json5" || FAILED=1
check_file "entry/src/main/module.json5" || FAILED=1
check_file "entry/src/main/resources" || FAILED=1
check_file "entry/src/main/ets" || FAILED=1
check_file "entry/src/main/cpp" || FAILED=1
echo "\n# Wrapper / runtime tools"
if [ -x "./hvigorw" ]; then
status "./hvigorw" "OK"
else
status "./hvigorw" "NOT_EXECUTABLE"
FAILED=1
fi
if command -v hvigor >/dev/null 2>&1; then
status "hvigor" "FOUND"
else
status "hvigor" "MISSING"
FAILED=1
fi
if command -v node >/dev/null 2>&1; then
status "node" "FOUND: $(node -v)"
else
status "node" "MISSING"
FAILED=1
fi
echo "\n# Local machine files"
if [ -f "local.properties" ]; then
status "local.properties" "FOUND"
HWSDK_DIR="$(sed -n 's/^hwsdk\.dir=//p' local.properties | tail -1)"
if [ -z "$HWSDK_DIR" ]; then
status "hwsdk.dir" "EMPTY"
FAILED=1
elif [[ "$HWSDK_DIR" == "/absolute/path/to/HarmonyOS/Sdk" ]]; then
status "hwsdk.dir" "PLACEHOLDER"
FAILED=1
elif [ -d "$HWSDK_DIR" ]; then
status "hwsdk.dir" "CONFIGURED"
else
status "hwsdk.dir" "PATH_NOT_FOUND"
FAILED=1
fi
else
status "local.properties" "MISSING"
FAILED=1
fi
echo "\n# Conclusion"
if [ "$FAILED" -eq 0 ]; then
echo "INIT_PREREQUISITES_OK"
else
echo "INIT_PREREQUISITES_BLOCKED"
exit 2
fi