KMP/CMP 鸿蒙社区:CPF-KMP-CMP。

源码:roundfit-kmp 圆屏布局与信息降级库

1. 从一行被圆边切掉的指标说起

在 466 px 的圆屏上,把一行指标固定成 300 px,y 稍微靠下就会出事。y=286 时这行还放得下:圆心在 233,dy=53,弦宽 383.63 px,减掉 24 px 边距仍有 359.63 px。同一行 300 px 的布局如果挪到 y=412,dy=179,弦宽只剩 173.90 px,两边会被表圈切掉。矩形布局里“一行占满”的习惯,在圆上必须改成“每个高度单独算一次可用宽度”。

内存也要逐项算。手表的预算按 KB 记,示例里主值占 9 KB、背景模糊占 12 KB、缩略图占 16 KB;full 档的门槛是 96 KB。预算 64 KB 时引擎连 full 都不会进,预算够了再打开模糊又要多付 12 KB,正好等于两行指标的成本。排版问题到这里变成“先丢哪一块、丢完还剩多少 KB”。

还有一处容易被忽略:截图上的 MEM 31 / 32 KB、"tier": "essential"、"rowsY": [276] 得来自同一份计算结果。ArkTS 若按屏幕尺寸另算一遍,换一个表盘,界面和 JSON 就会不一致。

roundfit-kmp 把弦宽、内存和同一份计算结果收进一个纯 Kotlin Multiplatform 库:commonMain 没有第三方运行时依赖,JVM 测试和 ohosArm64 目标跑的是同一份代码;鸿蒙侧用 ohos-native 编出 libroundfit.so,经 N-API 供 ArkUI 手表 HAP 调用。KMP 负责算出 Plan,绘制留给 ArkUI。

示例固定场景是「今日活动」:主值 8,432 步、目标 10,000、心率 112 bpm、0.84 的弧形进度、主操作「继续」。这些文案和颜色在 RoundFit 的六个实现里是共享 fixture,我只改约束,不改文案。表盘底部的 MEM 胶囊进入「内存实验室」,预算、字号和请求档位各有一组按钮;每次点击都重新跨过 N-API,由 Kotlin 重新算档位、内存和被去掉的槽位。

标题沿用 KMP/CMP 系列的命名;这一篇的实际实现只用 KMP,共享层只到 commonMain,没有引入 Compose Multiplatform,圆屏界面完全由 ArkUI 绘制。

2. 四档预算跑下来的表盘与实验室

第一次装上去,是在 Huawei_Wearable 模拟器上:HarmonyOS 7.0.0.105 / API 26,屏幕 466 × 466 物理像素,density 2.0。设计坐标以 466 px 圆为单位,ArkTS 做 px2vp() 换算后,1 设计像素正好对应 1 物理像素。

默认参数是预算 64 KB、字号 1.00×、请求 compact,引擎算出 40 KB。眉标、标题、主值、1 行指标、弧形进度和一个操作同时存在,底部 MEM 胶囊显示 40 / 64 KB:

compact 档:40/64 KB,一行指标与弧形进度

preview/plan.json 描述的就是这个状态:tier=compact、eyebrowY=86、titleY=122、heroY=222、rowsY=[286]、actionsY=368、arcRadius=208。

点一下底部 MEM 胶囊进入内存实验室,把预算从 64 KB 按两次 − 调到 32 KB,再返回表盘,就得到这张必要档截图。此时预算 32 KB、字号 1.00×、请求档位仍是 compact,最终估算 31 KB。这一档没有眉标、没有弧形进度、没有第二行指标,也没有「暂停」:

essential 档:31/32 KB,无眉标与弧形进度

标题「今日活动」、主值、步 · 目标 10,000、心率 112 bpm 和「继续」都在 Plan 给定的固定 y 上:titleY=140、heroY=208、rowsY=[276]、actionsY=356、memoryY=408。界面没有为“少了几块槽位”重新排版,空出来的位置就空着。固定布局的取舍就在这里:档位只决定哪些槽位存在,存活槽位的坐标不动。

再回到实验室,顶部先显示当前档位和估算值,再往下是三组控件与决策列表:

内存实验室:档位、控件与决策列表

memory.decisions 一共 7 条,屏幕里只放得下前 3 条,其余需要滑动。截图里露出的三行已经给出这一档的全部直接原因:预算 32 KB 落在 32–55 KB,内存上限为必要档;字号 1.0× 低于 1.15×,字号未触发降档;可用高度 360 px ≥ 320 px,高度未触发降档。第 4 条会写出最终档位与 rank,第 5 条记录被去掉的最高优先级槽位和总数,第 6 条给出内存明细与模糊/图片开关,第 7 条给出该行所在高度的弦宽和截断情况。这些文案在引擎生成 Plan 时写入 JSON,渲染器只负责显示。

实验室底部「查看 JSON」打开第三页。它显示的是 N-API 原样返回的文档,ArkTS 只做了 JSON.parse,没有重新序列化:

JSON 页:N-API 原样返回的 Plan

屏幕里能看到文档头部:"eyebrow": null、"accent": "#A78BFA"、"tier": "essential"、"tierRank": 2、"diameter": 466、"safeRadius": 199,以及 "contentRadius": 199、"eyebrowY": null、"titleY": 140、"heroY": 208、"rowsY": [276]、"actionsY": 356。再往下是 hero、rows、arc、actions、memory 和 dropped,需要滑动查看。字号 9 px,行高 12 px,一行放不下就换行,不做语法高亮——字号小是故意的,这一页只拿来核对原始字段。

四档对照

同一台模拟器、同一次前台进程里,用 uinput -T -c x y 点击、snapshot_display 抓 466 × 466 截图,四档都能稳定复现:

操作最终档位估算 / 预算表盘保留
启动默认(64 KB / 1.00× / 请求 compact)compact40 / 64 KB眉标、标题、主值、1 行指标、弧、1 操作
预算加到 128 KB 并请求 fullfull60 / 128 KB眉标、标题、主值、说明、2 行、2 操作、弧、模糊(只进内存账)
预算降到 32 KBessential31 / 32 KB标题、主值、1 行、1 操作,无弧
预算回到 64 KB,字号加到 1.30×essential31 / 64 KB字号上限压档,验证 max()
预算降到 20 KBglance20 / 20 KB只剩主值与一行标签

表格里 full 用 128 KB,是实验室预算按钮的档位之一;96 KB 刚好卡在 memoryCap 的 full 门槛上,128 KB 让 full 的 60 KB 留出 68 KB 余量。essential 用 32 KB,是因为 31 KB 的估算只比门槛少 1 KB,再低一档就掉到 glance;glance 用 20 KB,正好等于估算值,没有余量,也说明它不能再降。

full 档是信息最全的状态:主值下面多出「距目标 1,568 步」,两行指标(心率、消耗)、两个操作(继续、暂停)和弧形进度同时出现。此时内存估算 60 KB,预算 128 KB,blur = true:

full 档:60/128 KB,两行指标与两个操作

实验室在同一个状态下显示 FULL · 60 / 128 KB,首条决策是 预算 128 KB ≥ 96 KB,内存上限为全量档。此时请求 full 与内存上限一致,字号和高度都没有压档:

实验室 full 状态:60/128 KB

glance 档则把能丢的都丢了:没有标题、没有指标行、没有弧、没有操作,只剩主值 8,432 和 步 · 目标 10,000。底部的 MEM 胶囊仍在,因为 memoryY 在四个档位里都有值,它既显示内存占用,也是回到实验室的入口:

glance 档:20/20 KB,只剩主值与标签

四档的估算值可以直接核对(base + 眉标 + 主值 + 指标行 + 弧 + 操作 + 模糊):full 为 14 + 2 + 9 + 12 + 7 + 4 + 12 = 60,compact 为 14 + 2 + 9 + 6 + 7 + 2 = 40,essential 为 14 + 9 + 6 + 2 = 31,glance 为 14 + 6 = 20。这几个和与 Degradation.estimateMemory 的常量一一对应。

3. 环境与目录

编辑器用于查看源码和运行模拟器,Gradle 负责 KMP 编译与测试,鸿蒙 HAP 由 DevEco Studio 自带的 hvigor 打包。复现时先核对 SDK 与 hvigor 的版本,再按表中的 Kotlin、Gradle 和 JDK 安装依赖。模拟器的系统版本以「关于本机」为准。

工程声明的最低兼容版本是 HarmonyOS 6.0.0(API 20),编译版本和目标版本都是 API 26。圆屏效果与四档验证都在 API 26 的 Huawei_Wearable 模拟器上完成。手表只声明 deviceTypes: ["wearable"],没有为手机或平板做多设备布局。

项目本例使用值
编辑器DevEco Studio(内置 hvigor 6.26.4)
构建工具Gradle 8.14.3 wrapper;HAP 用 DevEco 自带 hvigor
SDK26.0.0.105 Release,compile 和 target 为 26.0.0,compatible 为 6.0.0(20)
模拟器Huawei_Wearable,HarmonyOS 7.0.0.105,API 26,466 × 466,density 2.0
设备类型wearable(Stage 模型 HAP)
Gradle / JDK / Node8.14.3 / 21(Zulu 21.50+19)/ 24.12.0
Kotlin2.2.21-1.0.0(KMP + Kotlin/Native ohosArm64)
构建目标jvm() + ohosArm64()
原生链路N-API(libentry.so)+ C ABI(libroundfit.so)
测试44 个 JVM 用例:几何 9、档位 10、Plan 9、契约 8、JSON 6、产物 2
Bundlecom.lqjmac.roundfitkmp

环境表里最容易被忽略的是 hvigor 与 SDK 的绑定:SDK 26.0.0.105 配 DevEco 内置 hvigor 6.26.4,命令行工具 6.21.2 不认识 API 26。Kotlin 2.2.21-1.0.0 是与 ohosArm64 对齐的版本,Gradle 8.14.3 由 wrapper 锁定;这三项任何一项换掉,都要重新跑 jvmTest 和 HAP 构建,不能只看编译通过。

工程目录在 DevEco Studio 里长这样。roundfit 是纯 KMP 库,ohos-native 只做 C ABI 导出,ohos 是跑在手表上的 HAP,docs 与 preview 保存实现说明和可复现的产物:

工程目录:roundfit、ohos-native 与 ohos

roundfit-kmp/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle.properties
├── gradle/libs.versions.toml          # kotlin = 2.2.21-1.0.0
├── roundfit/
│   ├── build.gradle.kts               # explicitApi(); jvm(); ohosArm64()
│   └── src/
│       ├── commonMain/kotlin/com/roundfit/
│       │   ├── geometry/RoundGeometry.kt
│       │   ├── tier/Degradation.kt
│       │   ├── model/WatchContent.kt
│       │   ├── model/Plan.kt
│       │   ├── RoundFitEngine.kt
│       │   └── PlanJson.kt
│       ├── commonTest/kotlin/com/roundfit/
│       └── jvmTest/kotlin/com/roundfit/PreviewArtifactTest.kt
├── example/
│   ├── build.gradle.kts
│   └── jvmMain/kotlin/com/roundfit/example/Main.kt
├── ohos-native/
│   ├── build.gradle.kts               # sharedLib("roundfit") + prepareOhos
│   └── src/ohosArm64Main/
│       ├── kotlin/com/roundfit/ohos/NativeBridge.kt
│       └── linker/roundfit.map        # 只导出 RoundFitPlanJson / RoundFitFree
├── ohos/
│   ├── build-profile.json5
│   ├── AppScope/app.json5
│   └── entry/
│       ├── libs/arm64-v8a/libroundfit.so      # Gradle 生成,不入库
│       └── src/main/
│           ├── cpp/
│           │   ├── CMakeLists.txt
│           │   ├── napi_init.cpp
│           │   ├── include/libroundfit_api.h  # 生成,不入库
│           │   └── types/libentry/index.d.ts
│           └── ets/
│               ├── entryability/EntryAbility.ets
│               ├── pages/Index.ets              # 表盘 / 实验室 / JSON 三页
│               └── roundfit/PlanNative.ets      # Plan 类型与 N-API 封装
├── tool/build_watch_hap.sh
├── preview/plan.json
├── docs/round-contract.md
├── docs/ohos-watch-app.md
├── docs/verification.md
└── docs/screenshots/

目录里有两类生成物需要单独说明。ohos/entry/libs/arm64-v8a/libroundfit.so 和 src/main/cpp/include/libroundfit_api.h 由 :ohos-native:prepareOhos 从同一次 Kotlin/Native 链接复制过来,两者必须成套更新;只替换 .so 却沿用旧头文件,C 侧的参数类型和调用约定可能与实际导出不一致。preview/plan.json 则由 JVM 示例生成,并被 PreviewArtifactTest 按“去掉末尾一个换行后逐字符比对”的方式校验。

4. 共享引擎

roundfit 的公开入口分成四块:几何、档位、引擎与 JSON。它们都是纯函数或不可变数据类,没有 expect/actual,也没有平台 UI 依赖。这样 JVM 测试覆盖的规则就是手表上实际执行的规则,不需要再为 Native 写一套等价测试。代码按几何、档位、引擎、JSON 四块拆开,每块后面写清楚它不做什么;边界比实现本身更容易出错。

几何部分只有一个核心:给定 y,先算该高度的弦宽。圆屏的可用宽度由这个数决定,屏幕宽度本身用不上:

package com.roundfit.geometry

import kotlin.math.floor
import kotlin.math.min
import kotlin.math.sqrt

public object RoundGeometry {
  public const val DIAMETER: Int = 466
  public const val CENTER: Int = 233
  public const val SAFE_RADIUS: Int = 199
  public const val ARC_RADIUS: Int = 208
  public const val ROW_WIDTH: Int = 300
  public const val CHORD_GUTTER: Int = 24
  public const val CJK_WEIGHT: Double = 1.0
  public const val LATIN_WEIGHT: Double = 0.56
  public const val ELLIPSIS: String = "…"

  /**
   * 可见弦宽:`2 * sqrt(max(0, r² - dy²))`;圆外返回 0,不返回负数。
   */
  public fun chordWidth(dy: Double, radius: Double = SAFE_RADIUS.toDouble()): Double {
    require(radius > 0.0) { "Radius must be positive" }
    val squared = radius * radius - dy * dy
    return if (squared <= 0.0) 0.0 else 2.0 * sqrt(squared)
  }

  public fun chordWidthAt(y: Int, radius: Double = SAFE_RADIUS.toDouble()): Double =
    chordWidth(y - CENTER.toDouble(), radius)

  public fun rowWidthLimit(y: Int): Double = chordWidthAt(y) - CHORD_GUTTER.toDouble()

  /** 行宽取 `min(300, limit)`,再向下取整;完全在圆外时返回 0。 */
  public fun rowWidth(y: Int, preferred: Int = ROW_WIDTH): Int {
    require(preferred > 0) { "Preferred width must be positive" }
    val limit = rowWidthLimit(y)
    if (limit < 1.0) return 0
    return floor(min(preferred.toDouble(), limit)).toInt()
  }

  /**
   * 共享文本估算:`Σ (isCJK(codePoint) ? 1.0 : 0.56) * fontSize`。
   * 代理对按一个码点计算,emoji 与 CJK 扩展区不会被算两次。
   */
  public fun textWidth(text: String, fontSize: Double): Double {
    require(fontSize >= 0.0) { "Font size must not be negative" }
    var width = 0.0
    var index = 0
    while (index < text.length) {
      val codePoint = codePointAt(text, index)
      val step = if (codePoint > 0xFFFF) 2 else 1
      width += (if (isCJKCodePoint(codePoint)) CJK_WEIGHT else LATIN_WEIGHT) * fontSize
      index += step
    }
    return width
  }

  /** 截断到“前缀 + …”严格窄于 maxWidth;连省略号都放不下时返回空串。 */
  public fun truncate(text: String, maxWidth: Double, fontSize: Double): String {
    require(maxWidth > 0.0) { "Maximum width must be positive" }
    require(fontSize > 0.0) { "Font size must be positive" }
    if (textWidth(text, fontSize) < maxWidth) return text
    val ellipsisWidth = textWidth(ELLIPSIS, fontSize)
    if (ellipsisWidth >= maxWidth) return ""

    val kept = StringBuilder()
    var width = 0.0
    var index = 0
    while (index < text.length) {
      val codePoint = codePointAt(text, index)
      val step = if (codePoint > 0xFFFF) 2 else 1
      val chunk = text.substring(index, index + step)
      val nextWidth = width + textWidth(chunk, fontSize)
      if (nextWidth + ellipsisWidth >= maxWidth) break
      kept.append(chunk)
      width = nextWidth
      index += step
    }
    return if (kept.isEmpty()) "" else kept.toString() + ELLIPSIS
  }

  public fun isCJKCodePoint(codePoint: Int): Boolean =
    codePoint in 0x2018..0x2019 ||   // ‘ ’
      codePoint in 0x201C..0x201D || // “ ”
      codePoint in 0x2E80..0x2EFF || // CJK 部首补充
      codePoint in 0x3000..0x303F || // CJK 符号与标点
      codePoint in 0x31C0..0x31EF || // CJK 笔画
      codePoint in 0x3300..0x33FF || // CJK 兼容
      codePoint in 0x3400..0x4DBF || // 扩展 A
      codePoint in 0x4E00..0x9FFF || // 统一表意文字
      codePoint in 0xF900..0xFAFF || // 兼容表意文字
      codePoint in 0xFE30..0xFE4F || // 兼容形式
      codePoint in 0xFF00..0xFFEF || // 全角 / 半角形式
      codePoint in 0x20000..0x2FA1F || // 扩展 B–F
      codePoint in 0x30000..0x3134F    // 扩展 G

  private fun codePointAt(text: String, index: Int): Int {
    val first = text[index]
    if (first.isHighSurrogate() && index + 1 < text.length && text[index + 1].isLowSurrogate()) {
      return 0x10000 + ((first.code - 0xD800) shl 10) + (text[index + 1].code - 0xDC00)
    }
    return first.code
  }
}

常量表里,SAFE_RADIUS = 199 是 233 减 34 的内容内缩,ARC_RADIUS = 208 比安全圆大 9 px、弧画在安全区外侧,CHORD_GUTTER = 24 是弦宽两侧各留 12 px。ROW_WIDTH = 300 来自设计稿的固定行宽,弦宽只决定它在什么高度需要被压低;rowWidth 负责做这个上限裁剪。

chordWidth 是行宽计算的起点。r = 199 时,圆心处弦宽为 398,y=286 处的 dy = 53,弦宽 2 × sqrt(199² − 53²) = 383.63;减去 24 px 边距后,行宽上限 359.63,固定行宽 300 是安全的。y=412 处 dy = 179,弦宽只剩 173.90,所以 MEM 胶囊不做固定宽度,只按内容居中。

公式对 dy 的符号不敏感:y=286 和 y=180 只要离圆心一样远,弦宽相同。布局表里 full 的 row1 在 y=272(dy=39),比 compact 的 y=286(dy=53)更靠上,弦宽 390.28 比 383.63 宽,所以 full 的两行都放得下 300。

chordWidth 在 squared <= 0 时返回 0,避开负数与 sqrt 的 NaN;rowWidth 再把这个 0 传成“这一行放不下”。如果这里返回负数,后面的 min(300, limit) 会得到负宽度,ArkUI 的 width() 行为不确定,测试也难断言。

文本估算用了两档字宽:CJK 记 1.0,其余记 0.56。14 px 下「心率」是 28 px,「112 bpm」是 54.88 px。引擎在生成行时先扣掉标签宽度和 12 px 间距,再对值调用 truncate;如果发生截断,第 7 条决策会写出被截断的行标签。truncate 的返回值可能为空串,调用方会把它替换成 …,不会把按估算已经超宽的文本传给渲染器。

0.56 这个系数是经验值,跟字体度量无关:它把拉丁字母、数字和空格按同一档估,遇到 W、m 这类宽字符会低估,遇到 i、l 会高估。引擎用它只是为了在跨平台渲染器之间有一个共同的下界,最终还要靠 ArkUI 的 maxLines(1) 加 Ellipsis 兜底。CJK 按 1.0 算,是因为全角字符在 14 px 字号下基本占满一个 em。

PlanRow.width 记录的是该行保留的单行宽度(固定布局下为 300),跟逐条文本的像素宽度是两回事;文本是否超宽先由 truncate 按估算宽度处理,渲染器再用 Ellipsis 兜底。渲染器按这个宽度画底色和边框,校验器只要求 width <= chord - 24。把这两个概念混在一起,很容易在换文案时误判“宽度字段应该跟着文字变”。

truncate 用严格小于:textWidth(prefix + …) < maxWidth 才保留,等于上限也截。这样渲染器即使把字宽向上取整 1 px,也不会刚好顶到边框。返回空串属于正常分支,调用方 fitValue 会把它换成单个 …;如果连省略号都放不下,这一行实际上已经没有可读内容,引擎宁可留一个省略号,也不留空白。

档位由四个上限里最深的一档决定,和屏幕宽度断点无关。预算、字号、高度和应用请求各算一个 cap,最后取 rank 最大者:

package com.roundfit.tier

/** 从信息最全到最少;ordinal 就是 Plan 契约里的 rank。 */
public enum class Tier(public val rank: Int, public val id: String) {
  FULL(0, "full"),
  COMPACT(1, "compact"),
  ESSENTIAL(2, "essential"),
  GLANCE(3, "glance"),
  ;

  public val label: String
    get() = when (this) {
      FULL -> "全量"
      COMPACT -> "紧凑"
      ESSENTIAL -> "必要"
      GLANCE -> "一瞥"
    }

  public companion object {
    public fun fromRank(rank: Int): Tier {
      require(rank in 0..3) { "Tier rank must be in 0..3" }
      return entries.first { it.rank == rank }
    }

    public fun fromId(id: String): Tier? = entries.firstOrNull { it.id == id }
  }
}

public data class LayoutConstraints(
  val budgetKB: Int,
  val textScale: Double = 1.0,
  val contentHeight: Int = 360,
  val requestedTier: Tier = Tier.FULL,
) {
  init {
    require(budgetKB >= 0) { "Memory budget must not be negative" }
    require(textScale > 0.0 && textScale.isFinite()) { "Text scale must be finite and positive" }
    require(contentHeight >= 0) { "Content height must not be negative" }
  }
}

public object Degradation {
  public const val FULL_MIN_BUDGET_KB: Int = 96
  public const val COMPACT_MIN_BUDGET_KB: Int = 56
  public const val ESSENTIAL_MIN_BUDGET_KB: Int = 32
  public const val ESSENTIAL_TEXT_SCALE: Double = 1.30
  public const val COMPACT_TEXT_SCALE: Double = 1.15
  public const val ESSENTIAL_HEIGHT_PX: Int = 260
  public const val COMPACT_HEIGHT_PX: Int = 320

  public fun memoryCap(budgetKB: Int): Tier = when {
    budgetKB >= FULL_MIN_BUDGET_KB -> Tier.FULL
    budgetKB >= COMPACT_MIN_BUDGET_KB -> Tier.COMPACT
    budgetKB >= ESSENTIAL_MIN_BUDGET_KB -> Tier.ESSENTIAL
    else -> Tier.GLANCE
  }

  public fun textScaleCap(textScale: Double): Tier = when {
    textScale >= ESSENTIAL_TEXT_SCALE -> Tier.ESSENTIAL
    textScale >= COMPACT_TEXT_SCALE -> Tier.COMPACT
    else -> Tier.FULL
  }

  public fun heightCap(contentHeight: Int): Tier = when {
    contentHeight < ESSENTIAL_HEIGHT_PX -> Tier.ESSENTIAL
    contentHeight < COMPACT_HEIGHT_PX -> Tier.COMPACT
    else -> Tier.FULL
  }

  /** 最终档位:四个 cap 取 rank 最大者,请求只能加深、不能升级。 */
  public fun resolveTier(constraints: LayoutConstraints): Tier {
    val caps = listOf(
      memoryCap(constraints.budgetKB),
      textScaleCap(constraints.textScale),
      heightCap(constraints.contentHeight),
      constraints.requestedTier,
    )
    return caps.maxByOrNull { it.rank } ?: Tier.FULL
  }

  public fun rowCapacity(tier: Tier): Int = when (tier) {
    Tier.FULL -> 2
    Tier.COMPACT, Tier.ESSENTIAL -> 1
    Tier.GLANCE -> 0
  }

  public fun actionCapacity(tier: Tier): Int = when (tier) {
    Tier.FULL -> 2
    Tier.COMPACT, Tier.ESSENTIAL -> 1
    Tier.GLANCE -> 0
  }
}

边界值按“大于等于”处理:预算 96 是 full、95 是 compact、56 是 compact、55 是 essential、32 是 essential、31 是 glance。字号 1.30× 压到 essential,1.15× 压到 compact;高度 259 压到 essential,260 只压到 compact,320 不压档。requestedTier 参与 max(),所以 64 KB 预算请求 full 仍是 compact;反过来,40 KB 预算请求 full 也只能到 essential。

resolveTier 用 maxByOrNull { it.rank },省掉手写 if 链,四个 cap 的优先级只由 rank 决定;以后加第五个 cap 只要保证 Tier 的顺序不变。Tier.fromRank 在越界时 require,C 侧传 4 会直接抛异常,由 response 包成错误 JSON。

固定布局是一张纯数据表,y 值不随文本长度变化。full 的标题在 116、compact 在 122,因为 full 上方要留眉标、下方要留两行指标;essential 去掉眉标后标题反而下移到 140,主值上移到 208,空出来的空间不重新分配。四个档位的 memoryY 都压在 408–412,MEM 胶囊的位置基本不动,它既显示内存占用,也是入口,不能跟着内容移动。

  public fun layout(tier: Tier): TierLayout = when (tier) {
    Tier.FULL -> TierLayout(
      eyebrowY = 84,
      titleY = 116,
      heroY = 214,
      rowsY = listOf(272, 318),
      actionsY = 364,
      memoryY = 412,
      arcRadius = 208,
    )

    Tier.COMPACT -> TierLayout(
      eyebrowY = 86,
      titleY = 122,
      heroY = 222,
      rowsY = listOf(286),
      actionsY = 368,
      memoryY = 412,
      arcRadius = 208,
    )

    Tier.ESSENTIAL -> TierLayout(
      eyebrowY = null,
      titleY = 140,
      heroY = 208,
      rowsY = listOf(276),
      actionsY = 356,
      memoryY = 408,
      arcRadius = null,
    )

    Tier.GLANCE -> TierLayout(
      eyebrowY = null,
      titleY = null,
      heroY = 218,
      rowsY = emptyList(),
      actionsY = null,
      memoryY = 412,
      arcRadius = null,
    )
  }
字段fullcompactessentialglance
eyebrowY8486nullnull
titleY116122140null
heroY214222208218
rowsY[272, 318][286][276][]
actionsY364368356null
memoryY412412408412
arcRadius208208nullnull

固定 y 的代价是文案变长时不能靠换行解决,只能截断;收益是同一份 Plan 在六种渲染器上位置完全一致,截图可以逐像素对比。rowsY 只列实际保留的行,所以 compact 是 [286]、glance 是 [];titleY 在 glance 是 null,这里没有标题,也就不留备用坐标。

内存估算按槽位逐项相加,单位 KB。它不读设备 RSS,按固定单价累加,好处是六种实现能用同一把尺子比较降级策略:同一份内容在 Kotlin、Flutter、RN 上算出的 estimatedKB 必须相等。

/** 逐项内存估算,总量由 totalKB 汇总。 */
public data class MemoryBreakdown(
  val baseKB: Int,
  val eyebrowKB: Int,
  val heroKB: Int,
  val rowsKB: Int,
  val arcKB: Int,
  val actionsKB: Int,
  val blurKB: Int,
  val imageKB: Int,
) {
  public val totalKB: Int
    get() = baseKB + eyebrowKB + heroKB + rowsKB + arcKB + actionsKB + blurKB + imageKB
}

public object Degradation {
  public const val BASE_MEMORY_KB: Int = 14
  public const val EYEBROW_MEMORY_KB: Int = 2
  public const val HERO_MEMORY_KB: Int = 9
  public const val GLANCE_HERO_MEMORY_KB: Int = 6
  public const val ROW_MEMORY_KB: Int = 6
  public const val ARC_MEMORY_KB: Int = 7
  public const val ACTION_MEMORY_KB: Int = 2
  public const val BLUR_MEMORY_KB: Int = 12
  public const val IMAGE_MEMORY_KB: Int = 16

  /**
   * 共享内存公式。模糊与图片只在 full 生效;非 full 调用方必须传 false。
   */
  public fun estimateMemory(
    tier: Tier,
    eyebrowVisible: Boolean,
    rowCount: Int,
    arcVisible: Boolean,
    actionCount: Int,
    blur: Boolean,
    image: Boolean,
  ): MemoryBreakdown {
    require(rowCount in 0..2) { "Row count must be in 0..2" }
    require(actionCount in 0..2) { "Action count must be in 0..2" }
    require(!eyebrowVisible || tier.rank <= 1) { "Eyebrow is not allowed below compact" }
    require(!arcVisible || tier.rank <= 1) { "Arc is not allowed below compact" }
    require(!blur || tier == Tier.FULL) { "Blur is only allowed at full" }
    require(!image || tier == Tier.FULL) { "Image is only allowed at full" }
    return MemoryBreakdown(
      baseKB = BASE_MEMORY_KB,
      eyebrowKB = if (eyebrowVisible) EYEBROW_MEMORY_KB else 0,
      heroKB = if (tier == Tier.GLANCE) GLANCE_HERO_MEMORY_KB else HERO_MEMORY_KB,
      rowsKB = rowCount * ROW_MEMORY_KB,
      arcKB = if (arcVisible) ARC_MEMORY_KB else 0,
      actionsKB = actionCount * ACTION_MEMORY_KB,
      blurKB = if (blur) BLUR_MEMORY_KB else 0,
      imageKB = if (image) IMAGE_MEMORY_KB else 0,
    )
  }
}

estimateMemory 的 require 会直接抛异常。它把“非 full 不允许模糊/图片”写成了运行时契约,绕过引擎直接调用估算函数时也会抛异常。full 档的 60 KB 里,模糊 12 KB 与两行指标 12 KB 占比最大;compact 档把模糊关掉、行数减到 1、操作减到 1,于是 14 + 2 + 9 + 6 + 7 + 2 = 40。

glance 的主值单价降到 6 KB,是公式里唯一按档位变的单价;其余项都由槽位是否存在决定。图片的 16 KB 在示例里始终是 0,因为 RoundFitScenarios.workout() 的 showImage = false;这项成本只在打开缩略图时计入。

base 14 KB 是固定开销,四档都付;hero 在 glance 降到 6 KB,actions 按个数算,full 两个 4 KB,compact 一个 2 KB。把这些单价写进代码而不是文档,测试才能逐项断言。

引擎的职责很窄:解析档位、按容量挑选槽位、算内存,再把结果装进 Plan。它不会改写场景文案,也不会为了放下内容调整 y;唯一会动文字的地方是按可用宽度截断指标值,并记录到决策里:

// RoundFitEngine.kt:档位解析与槽位选择(package 与 import 在文件头部)
public object RoundFitEngine {
  private const val ROW_FONT_SIZE: Double = 14.0
  private const val ROW_LABEL_GAP: Double = 12.0

  public fun plan(content: WatchContent, constraints: LayoutConstraints): RoundFitPlan {
    val tier = Degradation.resolveTier(constraints)
    return planAtTier(content, constraints, tier)
  }

  private fun planAtTier(
    content: WatchContent,
    constraints: LayoutConstraints,
    tier: Tier,
  ): RoundFitPlan {
    val layout = Degradation.layout(tier)
    val eyebrowVisible = tier.rank <= 1
    val titleVisible = tier.rank <= 2
    val detailVisible = tier == Tier.FULL
    val arcVisible = tier.rank <= 1 && content.arc != null
    val blur = tier == Tier.FULL && content.allowBlur
    val image = tier == Tier.FULL && content.showImage

    if (tier == Tier.FULL) {
      require(content.rows.size == 2) { "Full tier needs two metric rows" }
      require(content.actions.size == 2) { "Full tier needs two actions" }
      require(content.arc != null) { "Full tier needs arc progress" }
    }
    require(tier.rank > 1 || content.arc != null) { "Full/compact tiers need arc progress" }

    val selectedRowIndices = content.rows.indices.filter { index ->
      index < Degradation.rowCapacity(tier) && slotForRow(index).survives(tier)
    }
    val selectedActionIndices = content.actions.indices.filter { index ->
      index < Degradation.actionCapacity(tier) && Slot.ACTIONS.survives(tier)
    }

    val dropped = mutableListOf<String>()
    val dropCandidates = mutableListOf<DropCandidate>()

    fun drop(id: String, displayName: String, priority: Int) {
      dropped += id
      dropCandidates += DropCandidate(displayName = displayName, priority = priority)
    }

    if (!eyebrowVisible) drop("eyebrow", "眉标", priority = 30)
    if (!titleVisible) drop("title", "场景标题", priority = 90)
    if (!detailVisible) drop("hero.detail", "主值说明", priority = 50)
    content.rows.indices
      .filter { it !in selectedRowIndices }
      .forEach { index ->
        drop(
          id = "row[$index]",
          displayName = "指标「${content.rows[index].label}」",
          priority = if (index == 0) 80 else 60,
        )
      }
    if (content.arc != null && !arcVisible) drop("arc", "弧形进度", priority = 70)
    if (selectedActionIndices.size < content.actions.size) {
      if (selectedActionIndices.isEmpty()) {
        drop("actions", "全部操作", priority = 40)
      } else {
        (selectedActionIndices.size until content.actions.size).forEach { index ->
          drop(
            id = "action[$index]",
            displayName = "操作「${content.actions[index].label}」",
            priority = 40,
          )
        }
      }
    }
    if (content.allowBlur && !blur) drop("blur", "背景模糊", priority = 20)
    if (content.showImage && !image) drop("image", "图片缩略图", priority = 10)

    val truncatedRows = mutableListOf<String>()
    val rows = selectedRowIndices.map { index ->
      val source = content.rows[index]
      val y = layout.rowsY[index]
      val width = RoundGeometry.rowWidth(y)
      require(width > 0) { "Row at y=$y is outside the safe circle" }
      val fitted = fitValue(source.value, source.label, width)
      if (fitted != source.value) truncatedRows += source.label
      PlanRow(label = source.label, value = fitted, y = y, width = width)
    }

    val actions = selectedActionIndices.map { index ->
      val action = content.actions[index]
      PlanAction(label = action.label, kind = action.kind)
    }

    val arc = if (arcVisible) {
      val source = requireNotNull(content.arc)
      PlanArc(
        progress = source.progress,
        cap = source.cap,
        label = source.label,
        radius = requireNotNull(layout.arcRadius),
      )
    } else {
      null
    }

    val memory = Degradation.estimateMemory(
      tier = tier,
      eyebrowVisible = eyebrowVisible,
      rowCount = rows.size,
      arcVisible = arc != null,
      actionCount = actions.size,
      blur = blur,
      image = image,
    )
    require(memory.totalKB <= constraints.budgetKB) {
      "Estimated ${memory.totalKB} KB exceeds the ${constraints.budgetKB} KB budget; " +
        "the glance tier cannot degrade further"
    }

    val decisions = buildDecisions(
      content = content,
      constraints = constraints,
      tier = tier,
      memory = memory,
      dropped = dropped,
      dropCandidates = dropCandidates,
      rows = rows,
      truncatedRows = truncatedRows,
    )

    val planLayout = PlanLayout(
      contentRadius = RoundGeometry.SAFE_RADIUS,
      eyebrowY = if (eyebrowVisible) layout.eyebrowY else null,
      titleY = if (titleVisible) layout.titleY else null,
      heroY = layout.heroY,
      rowsY = rows.map { it.y },
      actionsY = if (actions.isEmpty()) null else layout.actionsY,
      memoryY = layout.memoryY,
      arcRadius = if (arc == null) null else layout.arcRadius,
    )

    return RoundFitPlan(
      schema = RoundFitMetadata.SCHEMA,
      framework = RoundFitMetadata.FRAMEWORK,
      frameworkKey = RoundFitMetadata.FRAMEWORK_KEY,
      library = RoundFitMetadata.LIBRARY,
      scenarioId = content.scenarioId,
      scenario = content.scenario,
      eyebrow = if (eyebrowVisible) content.eyebrow else null,
      accent = content.theme.accent,
      accentDim = content.theme.accentDim,
      surface = content.theme.surface,
      tier = tier,
      diameter = RoundFitMetadata.DIAMETER,
      safeRadius = RoundFitMetadata.SAFE_RADIUS,
      layout = planLayout,
      hero = PlanHero(
        value = content.heroValue,
        label = content.heroLabel,
        detail = if (detailVisible) content.heroDetail else null,
      ),
      rows = rows,
      arc = arc,
      actions = actions,
      memory = PlanMemory(
        budgetKB = constraints.budgetKB,
        estimatedKB = memory.totalKB,
        blur = blur,
        image = image,
        decisions = decisions,
      ),
      dropped = dropped,
    )
  }

  private fun fitValue(value: String, label: String, rowWidth: Int): String {
    val available = rowWidth - RoundGeometry.textWidth(label, ROW_FONT_SIZE) - ROW_LABEL_GAP
    if (available <= 0.0) return "…"
    val fitted = RoundGeometry.truncate(value, available, ROW_FONT_SIZE)
    return if (fitted.isEmpty()) "…" else fitted
  }
}

buildDecisions 输出的是面向用户的文案,但它仍然是纯函数:输入是约束、档位、内存和被去掉的槽位,输出固定 7 条字符串。七个 decisions += 只把 cap、档位、内存和 dropped 转成中文文案,不再改 Plan 的内容:

// RoundFitEngine.kt:buildDecisions(固定 7 条)
  private fun buildDecisions(
    content: WatchContent,
    constraints: LayoutConstraints,
    tier: Tier,
    memory: MemoryBreakdown,
    dropped: List<String>,
    dropCandidates: List<DropCandidate>,
    rows: List<PlanRow>,
    truncatedRows: List<String>,
  ): List<String> {
    val decisions = mutableListOf<String>()

    decisions += when (Degradation.memoryCap(constraints.budgetKB)) {
      Tier.FULL -> "预算 ${constraints.budgetKB} KB ≥ 96 KB,内存上限为全量档"
      Tier.COMPACT -> "预算 ${constraints.budgetKB} KB 落在 56–95 KB,内存上限为紧凑档"
      Tier.ESSENTIAL -> "预算 ${constraints.budgetKB} KB 落在 32–55 KB,内存上限为必要档"
      Tier.GLANCE -> "预算 ${constraints.budgetKB} KB < 32 KB,内存上限为一瞥档"
    }

    val scale = formatScale(constraints.textScale)
    decisions += when (Degradation.textScaleCap(constraints.textScale)) {
      Tier.ESSENTIAL -> "字号 ${scale}× ≥ 1.30×,字号上限压到必要档"
      Tier.COMPACT -> "字号 ${scale}× ≥ 1.15×,字号上限压到紧凑档"
      Tier.FULL -> "字号 ${scale}× 低于 1.15×,字号未触发降档"
      Tier.GLANCE -> "字号 ${scale}× 触发一瞥档"
    }

    decisions += when (Degradation.heightCap(constraints.contentHeight)) {
      Tier.ESSENTIAL -> "可用高度 ${constraints.contentHeight} px < 260 px,高度上限压到必要档"
      Tier.COMPACT -> "可用高度 ${constraints.contentHeight} px < 320 px,高度上限压到紧凑档"
      Tier.FULL -> "可用高度 ${constraints.contentHeight} px ≥ 320 px,高度未触发降档"
      Tier.GLANCE -> "可用高度 ${constraints.contentHeight} px 触发一瞥档"
    }

    decisions += "应用请求 ${constraints.requestedTier.id} 档,最终档位 ${tier.id}(rank ${tier.rank})"

    decisions += if (dropped.isEmpty()) {
      "全量内容全部保留,dropped 为空"
    } else {
      val highest = dropCandidates.maxByOrNull { it.priority }
      "去掉最高优先级的${highest?.displayName ?: "内容槽位"},共 ${dropped.size} 个槽位被移除"
    }

    val blurDecision = when {
      memory.blurKB > 0 -> "启用背景模糊(${memory.blurKB} KB)"
      content.allowBlur -> "关闭背景模糊(省 ${Degradation.BLUR_MEMORY_KB} KB)"
      else -> "背景模糊未申请(0 KB)"
    }
    val imageDecision = when {
      memory.imageKB > 0 -> "启用图片缩略图(${memory.imageKB} KB)"
      content.showImage -> "关闭图片缩略图(省 ${Degradation.IMAGE_MEMORY_KB} KB)"
      else -> "图片缩略图未启用(0 KB)"
    }
    decisions += "估算 ${memory.totalKB} KB ≤ 预算 ${constraints.budgetKB} KB;$blurDecision,$imageDecision"

    decisions += if (rows.isEmpty()) {
      "一瞥档不渲染指标行,无弦宽截断"
    } else {
      val row = rows.first()
      val chord = floor(RoundGeometry.chordWidthAt(row.y)).toInt()
      val limit = floor(RoundGeometry.rowWidthLimit(row.y)).toInt()
      val truncation = if (truncatedRows.isEmpty()) {
        "未触发截断"
      } else {
        "已截断 ${truncatedRows.joinToString("、")}"
      }
      "y=${row.y} 处弦宽 $chord px,行宽 ${row.width} px ≤ $limit px 可用上限,$truncation"
    }

    return decisions
  }

dropped 为空只可能出现在 full,其余档位至少去掉一个槽位,所以非 full 的 dropped 一定非空。highest 只用于文案,实际保留集合早在 selectedRowIndices、selectedActionIndices 里定好了,优先级不会反向影响渲染。

第 7 条只取 rows.first() 报弦宽,而 truncatedRows 收的是所有被截断的行。full 的第二行在 y=318,弦宽 359.87,比首行 y=272 的 390.28 更窄;如果第二行被截断,这条决策会写“已截断”,但前面的弦宽数字仍是首行的。契约只要求给出“该行所在高度的弦宽和截断情况”,逐行报告没做。这是当前实现的缺口,换长文案时应先补上。

引擎里的顺序也在契约里:先算 memory,再 require(memory.totalKB <= budget),最后才拼 PlanMemory 和 decisions。如果先拼 Plan 再检查,超预算的 Plan 已经构造出来,异常路径上还得解释这个半成品;现在抛异常时没有返回对象。

selectedRowIndices 的选取要同时满足容量和槽位存活。compact 的 row[1] 在槽位表里 maxRank = 1,仍属“可存活”,但行容量只有 1,于是 row[1] 被写入 dropped。这解释了契约里看起来矛盾的地方:maxRank 表示“最多能活到哪一档”,容量表示“这一档实际留几个”。优先级只影响决策文案里“去掉最高优先级的谁”,不影响最终集合。

selectedActionIndices 的筛选条件只有两个:容量够、且 Slot.ACTIONS 在这一档存活。操作没有“第二个操作单独降级”的规则,要么两个都在 full,要么只剩第一个;dropped 里写 action[1],不写 action[0]。

「今日活动」的固定 fixture 在 WatchContent.kt 里,颜色、文案、两行指标、两个操作和 0.84 的弧都在这里。RoundFitScenarios.WORKOUT_CONSTRAINTS 固定为 64 KB、1.00×、360 px、请求 compact,因此 JVM 示例、preview/plan.json 和设备默认态必须是同一份 Plan。

Plan 的数据模型与 JSON 字段一一对应,tierRank 由 Tier.rank 计算,不手写常量:

public data class RoundFitPlan(
  val schema: String,
  val framework: String,
  val frameworkKey: String,
  val library: String,
  val scenarioId: String,
  val scenario: String,
  val eyebrow: String?,
  val accent: String,
  val accentDim: String,
  val surface: String,
  val tier: Tier,
  val diameter: Int,
  val safeRadius: Int,
  val layout: PlanLayout,
  val hero: PlanHero,
  val rows: List<PlanRow>,
  val arc: PlanArc?,
  val actions: List<PlanAction>,
  val memory: PlanMemory,
  val dropped: List<String>,
) {
  /** full=0, compact=1, essential=2, glance=3。 */
  public val tierRank: Int
    get() = tier.rank
}

RoundFitPlan 与 wire 字段一一对应,连顺序都按契约排;tierRank 走 tier.rank,避免手写 0/1/2/3 和枚举脱节。eyebrow、arc、layout.actionsY、layout.arcRadius 用可空类型,降档时传 null,序列化层才知道该写 null 还是整个字段不输出。

Plan 里没有字号、字重、行高,也没有槽位的 x 坐标;水平位置由圆对称性决定,渲染器按圆心居中,纵向才需要逐档调。这个分工让六种实现能共用坐标,但字号和字距仍留在各自渲染器里,截图能对齐并不等于排版代码可以复用。

序列化由 PlanJson 手写完成,没有 kotlinx.serialization,也没有第三方 JSON 库。字段顺序、空值位置和转义规则都由代码固定:

// PlanJson.kt:encode、quote 与 appendPlan
public object PlanJson {
  public fun encode(plan: RoundFitPlan): String = buildString { appendPlan(plan) }

  public fun quote(value: String): String = buildString {
    append('"')
    value.forEach { character ->
      when (character) {
        '"' -> append("\\\"")
        '\\' -> append("\\\\")
        '\b' -> append("\\b")
        '\u000C' -> append("\\f")
        '\n' -> append("\\n")
        '\r' -> append("\\r")
        '\t' -> append("\\t")
        else -> if (character < ' ') {
          append("\\u")
          append(character.code.toString(16).padStart(4, '0'))
        } else {
          append(character)
        }
      }
    }
    append('"')
  }

  private fun StringBuilder.appendPlan(plan: RoundFitPlan) {
    append("{\n")
    append("  \"schema\": ").append(quote(plan.schema)).append(",\n")
    append("  \"framework\": ").append(quote(plan.framework)).append(",\n")
    append("  \"frameworkKey\": ").append(quote(plan.frameworkKey)).append(",\n")
    append("  \"library\": ").append(quote(plan.library)).append(",\n")
    append("  \"scenarioId\": ").append(quote(plan.scenarioId)).append(",\n")
    append("  \"scenario\": ").append(quote(plan.scenario)).append(",\n")
    append("  \"eyebrow\": ").append(plan.eyebrow?.let { quote(it) } ?: "null").append(",\n")
    append("  \"accent\": ").append(quote(plan.accent)).append(",\n")
    append("  \"accentDim\": ").append(quote(plan.accentDim)).append(",\n")
    append("  \"surface\": ").append(quote(plan.surface)).append(",\n")
    append("  \"tier\": ").append(quote(plan.tier.id)).append(",\n")
    append("  \"tierRank\": ").append(plan.tierRank).append(",\n")
    append("  \"diameter\": ").append(plan.diameter).append(",\n")
    append("  \"safeRadius\": ").append(plan.safeRadius).append(",\n")

    append("  \"layout\": {\n")
    append("    \"contentRadius\": ").append(plan.layout.contentRadius).append(",\n")
    append("    \"eyebrowY\": ").append(plan.layout.eyebrowY.nullableInt()).append(",\n")
    append("    \"titleY\": ").append(plan.layout.titleY.nullableInt()).append(",\n")
    append("    \"heroY\": ").append(plan.layout.heroY).append(",\n")
    append("    \"rowsY\": [").append(plan.layout.rowsY.joinToString(", ")).append("],\n")
    append("    \"actionsY\": ").append(plan.layout.actionsY.nullableInt()).append(",\n")
    append("    \"memoryY\": ").append(plan.layout.memoryY).append(",\n")
    append("    \"arcRadius\": ").append(plan.layout.arcRadius.nullableInt()).append("\n")
    append("  },\n")

    append("  \"hero\": {\n")
    append("    \"value\": ").append(quote(plan.hero.value)).append(",\n")
    append("    \"label\": ").append(quote(plan.hero.label))
    val detail = plan.hero.detail
    if (detail == null) {
      append("\n")
    } else {
      append(",\n    \"detail\": ").append(quote(detail)).append("\n")
    }
    append("  },\n")

    append("  \"rows\": ")
    appendRows(plan.rows)
    append(",\n")

    append("  \"arc\": ")
    appendArc(plan.arc)
    append(",\n")

    append("  \"actions\": ")
    appendActions(plan)
    append(",\n")

    append("  \"memory\": ")
    appendMemory(plan.memory)
    append(",\n")

    append("  \"dropped\": ")
    appendStrings(plan.dropped, empty = "[]")
    append("\n}")
  }
}

quote 转义双引号、反斜杠、\b、\f、\n、\r、\t 和全部 U+0000–U+001F 控制字符,中文不转义,按 UTF-8 输出。手写序列化换来的确定性,比省一个依赖更重要:appendPlan 按固定顺序拼接,appendRows、appendArc、appendActions、appendMemory 各自处理数组和 null;数字直接 append,只有字符串走 quote。eyebrow、arc、actionsY、arcRadius 在降档后写 null,hero.detail 在非 full 档是整个字段不出现,所以 ArkTS 的类型里它是可选的 detail?: string。这些规则由 PlanJsonTest 逐条覆盖,包括“空槽位变 null”“缺省字段不出现”和“重复编码结果一致”。

手写 JSON 的另一个边界是浮点:progress 先 round(value * 1000) / 1000,整数输出不带 .0。这样 0.84 不会变成 0.8400000000000001,跨语言比对时不用容忍浮点尾数。decimal 只用于 arc,其他数字都是整数。

preview/plan.json 是引擎的默认输出,共 1674 字节。为了便于阅读,这里把 hero、arc、rows、actions 和 dropped 压成了紧凑的几行,layout 与 memory 仍按字段展开;实际输出是两空格缩进的多行文档。关键字段如下:

{
  "schema": "roundfit.plan/v1",
  "framework": "Kotlin Multiplatform",
  "frameworkKey": "kotlin",
  "library": "roundfit-kmp",
  "scenarioId": "workout",
  "scenario": "今日活动",
  "eyebrow": "ROUND FIT · KOTLIN",
  "accent": "#A78BFA",
  "accentDim": "#2A2140",
  "surface": "#0B0912",
  "tier": "compact",
  "tierRank": 1,
  "diameter": 466,
  "safeRadius": 199,
  "layout": {
    "contentRadius": 199,
    "eyebrowY": 86,
    "titleY": 122,
    "heroY": 222,
    "rowsY": [286],
    "actionsY": 368,
    "memoryY": 412,
    "arcRadius": 208
  },
  "hero": { "value": "8,432", "label": "步 · 目标 10,000" },
  "rows": [
    { "label": "心率", "value": "112 bpm", "y": 286, "width": 300 }
  ],
  "arc": { "progress": 0.84, "cap": "84%", "label": "目标", "radius": 208 },
  "actions": [
    { "label": "继续", "kind": "primary" }
  ],
  "memory": {
    "budgetKB": 64,
    "estimatedKB": 40,
    "blur": false,
    "image": false,
    "decisions": [
      "预算 64 KB 落在 56–95 KB,内存上限为紧凑档",
      "字号 1.0× 低于 1.15×,字号未触发降档",
      "可用高度 360 px ≥ 320 px,高度未触发降档",
      "应用请求 compact 档,最终档位 compact(rank 1)",
      "去掉最高优先级的指标「消耗」,共 4 个槽位被移除",
      "估算 40 KB ≤ 预算 64 KB;关闭背景模糊(省 12 KB),图片缩略图未启用(0 KB)",
      "y=286 处弦宽 383 px,行宽 300 px ≤ 359 px 可用上限,未触发截断"
    ]
  },
  "dropped": ["hero.detail", "row[1]", "action[1]", "blur"]
}

默认档去掉的四项与内存估算可以逐项对上:主值说明、第二行「消耗」、第二个操作「暂停」、背景模糊。compact 仍保留眉标、标题、主值、一行心率、弧和一个「继续」,所以 estimatedKB = 40。eyebrowY = 86、heroY = 222、rowsY = [286]、actionsY = 368 与截图里 compact 档的位置一致。

1674 字节是 wc -c 的实测值,包含缩进和末尾换行;PreviewArtifactTest 比对时去掉末尾那一个换行,所以文件末尾有没有换行不会造成假失败。JSON 里 decisions 的七段文案占了大部分字节,字符串没有做额外压缩,换文案时字节数会跟着变。

字段顺序固定还有一个副作用:git diff 只会在实际改值的地方出现一行,不会因为 map 遍历顺序整段重排。

decisions 是 List<String>,PlanJson 逐条 quote 并逗号分隔,最后一行不带逗号;这个细节让 JSON 可以被 JSON.parse 直接解析,也避免手写序列化最常见的尾逗号错误。

JVM 测试共有 44 个用例,其中 9 个几何、10 个档位、9 个 Plan、8 个契约、6 个 JSON、2 个产物。几何用例直接断言 chordWidth(0) = 398、圆边为 0、圆外不为负;档位用例覆盖预算 128/96/95/56/55/32/31/0 与字号 1.30/1.15、高度 259/260/319/320;契约用例逐个 Plan 检查 rowsY.length == rows.length、row.width <= chord - 24、full 的 dropped 为空、非 full 的 dropped 非空。PlanContractTest 对 decisions 只断言 3…8 条,没有固定 7 条;实现当前是 7 条,文档也写 7 条,测试留了余量。

5. 原生表盘与实验室

鸿蒙侧的宿主只有一个 @Entry 组件 Index,三个页面由 @State page 切换:face、lab、json。它们共享同一个 Plan 状态,所以从实验室返回表盘时不需要重新请求,表盘直接读当前 Plan 的坐标与槽位。

PlanNative.ets 是 ArkTS 与 N-API 的边界。它只做两件事:声明 roundfit.plan/v1 的类型镜像,把四个数字传给原生并解析返回的 JSON。字段名与契约的 wire name 完全一致,ArkTS 不重算任何布局:

import { planJson as nativePlanJson } from 'libentry.so';

export interface PlanLayout {
  contentRadius: number;
  eyebrowY: number | null;
  titleY: number | null;
  heroY: number;
  rowsY: number[];
  actionsY: number | null;
  memoryY: number;
  arcRadius: number | null;
}

export interface PlanHero {
  value: string;
  label: string;
  detail?: string;
}

export interface PlanRow {
  label: string;
  value: string;
  y: number;
  width: number;
}

export interface PlanArc {
  progress: number;
  cap?: string;
  label?: string;
  radius: number;
}

export interface PlanAction {
  label: string;
  kind: string;
}

export interface PlanMemory {
  budgetKB: number;
  estimatedKB: number;
  blur: boolean;
  image: boolean;
  decisions: string[];
}

export interface RoundFitPlan {
  schema: string;
  framework: string;
  frameworkKey: string;
  library: string;
  scenarioId: string;
  scenario: string;
  eyebrow: string | null;
  accent: string;
  accentDim: string;
  surface: string;
  tier: string;
  tierRank: number;
  diameter: number;
  safeRadius: number;
  layout: PlanLayout;
  hero: PlanHero;
  rows: PlanRow[];
  arc: PlanArc | null;
  actions: PlanAction[];
  memory: PlanMemory;
  dropped: string[];
  /** 只有 Kotlin 侧拒绝约束时才会出现。 */
  error?: string;
}

/** 原始 JSON 与解析结果一起保存,JSON 页显示原文。 */
export class PlanSnapshot {
  readonly json: string;
  readonly plan: RoundFitPlan;

  constructor(json: string, plan: RoundFitPlan) {
    this.json = json;
    this.plan = plan;
  }
}

export function requestSnapshot(
  budgetKB: number,
  textScale: number,
  contentHeight: number,
  requestedRank: number
): PlanSnapshot {
  const json: string = nativePlanJson(budgetKB, textScale, contentHeight, requestedRank);
  const plan: RoundFitPlan = JSON.parse(json) as RoundFitPlan;
  if (plan.error !== undefined) {
    throw new Error(plan.error);
  }
  return new PlanSnapshot(json, plan);
}

类型镜像里特意保留了 error?: string,因为 Kotlin 侧的 response 会把异常包成 JSON 错误对象;ArkTS 在 requestSnapshot 里检查这个字段并抛错。PlanSnapshot 同时保存 json 和 plan,JSON 页显示原文,表盘读解析后的对象,两边不会因为二次序列化产生差异。类型定义里没有任何布局常量,D=466 和 C=233 是渲染器自己的画布参数,不属于 Plan。

requestSnapshot 不忽略异常。预算小于 20 KB 时,Kotlin 侧会返回 {"error": ...},这里抛出 Error,页面把红字写进 errorText,不会静默沿用上一个 Plan。这样“预算不可表示”和“渲染失败”在界面上是两件事。

Index.ets 的入口状态很少:当前 Plan、原始 JSON、页面名、错误文本,以及预算/字号/请求三个索引。文件顶部先放 Plan 类型导入、画布常量和一组深色 token:

import { EMPTY_PLAN, PlanAction, PlanRow, RoundFitPlan, requestSnapshot } from '../roundfit/PlanNative';

/** 466 px 设计画布;手表是 466 × 466 物理像素、density 2。 */
const D: number = 466;
const C: number = 233;

const SURFACE_DEEP: string = '#050409';
const PANEL: string = '#151022';
const TEXT_PRIMARY: string = '#F3EFFB';
const TEXT_SECONDARY: string = '#B7A9D6';
const TEXT_MUTED: string = '#6F6388';
const DIVIDER: string = '#2A2140';
const TRANSPARENT: string = '#00000000';

每次按钮点击都调用 refresh(),重新跨过 N-API:

@Entry
@Component
struct Index {
  @State plan: RoundFitPlan = EMPTY_PLAN;
  @State rawJson: string = '';
  @State page: string = 'face';
  @State errorText: string = '';
  @State budgetIndex: number = 3;
  @State scaleIndex: number = 0;
  @State requestFull: boolean = false;

  private budgets: number[] = [20, 32, 56, 64, 96, 128];
  private scales: number[] = [1.0, 1.15, 1.30];

  aboutToAppear(): void {
    this.refresh();
  }

  private refresh(): void {
    try {
      const snapshot = requestSnapshot(
        this.budgets[this.budgetIndex],
        this.scales[this.scaleIndex],
        360,
        this.requestFull ? 0 : 1
      );
      this.plan = snapshot.plan;
      this.rawJson = snapshot.json;
      this.errorText = '';
    } catch (error) {
      this.errorText = (error as Error).message;
    }
  }

  /** 设计 px → vp;density 2 时 1 px = 0.5 vp。 */
  private v(px: number): number {
    return px2vp(px);
  }

  private hasArc(): boolean {
    return this.plan.arc !== null;
  }

  private arcProgress(): number {
    return this.plan.arc === null ? 0 : this.plan.arc.progress;
  }

  private arcRadius(): number {
    return this.plan.arc === null ? 0 : this.plan.arc.radius;
  }

  private hasEyebrow(): boolean {
    return this.plan.eyebrow !== null && this.plan.layout.eyebrowY !== null;
  }

  private eyebrowY(): number {
    return this.plan.layout.eyebrowY === null ? 0 : this.plan.layout.eyebrowY;
  }

  private titleY(): number {
    return this.plan.layout.titleY === null ? 0 : this.plan.layout.titleY;
  }

  private actionsY(): number {
    return this.plan.layout.actionsY === null ? 0 : this.plan.layout.actionsY;
  }

  /** 主值字号按档位取,glance 最大,full 次之。 */
  private heroSize(): number {
    if (this.plan.tier === 'glance') {
      return 62;
    }
    if (this.plan.tier === 'full') {
      return 58;
    }
    return 56;
  }

  /** Plan 给的是主值中心,说明行按档位偏移。 */
  private sublineY(): number {
    if (this.plan.tier === 'full') {
      return this.plan.layout.heroY + 38;
    }
    if (this.plan.tier === 'compact') {
      return this.plan.layout.heroY + 43;
    }
    if (this.plan.tier === 'essential') {
      return this.plan.layout.heroY + 44;
    }
    return this.plan.layout.heroY + 48;
  }

refresh() 是唯一改 Plan 的入口,三组控件和 aboutToAppear 都走它;budgetIndex=3 对应 64 KB,scaleIndex=0 对应 1.00×,requestFull=false 对应请求 compact。初始状态和 preview/plan.json 的 fixture 必须一致,否则第一张截图就对不上。plan 整体替换,不拆成几十个 @State 字段,为的是让“一次 N-API 调用对应一帧”在代码里看得见。

字号不在 Plan 里:heroSize() 按档位给 56/58/62 px,sublineY() 按档位给 +38/43/44/48;glance 的主值最大、位置 218,因为没有标题和指标行,full 的主值 58,要给下方的说明和两行指标让位。这是渲染器的职责,Plan 只保证槽位和 y。换一个渲染器(Flutter、RN)时这些值要各自对齐,不能从 Plan 推出来;改版式时也容易只改一边,截图对不上时先看这两个数。

表盘的主要元素都由一个 faceView 构建器绘制。Plan 直接提供 accent、accentDim 和 surface,分别用于主值/弧/主操作、弧轨道与底色;次级文字色则是渲染器补充的深色 token(TEXT_SECONDARY、TEXT_MUTED)。弧用 Progress(ProgressType.Ring),不自己画 Canvas;arc === null 时这段组件根本不会创建:

  @Builder
  faceView() {
    if (this.hasArc()) {
      Progress({ value: this.arcProgress() * 100, total: 100, type: ProgressType.Ring })
        .width(this.v(this.arcRadius() * 2))
        .height(this.v(this.arcRadius() * 2))
        .position({ x: this.v(C - this.arcRadius()), y: this.v(C - this.arcRadius()) })
        .color(this.plan.accent)
        .backgroundColor(this.plan.accentDim)
        .style({ strokeWidth: this.v(6), enableSmoothEffect: false })
        .hitTestBehavior(HitTestMode.None)
    }

    if (this.hasEyebrow()) {
      this.lineOf(this.plan.eyebrow ?? '', this.eyebrowY(), 12, 1.2, TEXT_SECONDARY, FontWeight.Medium, 1.4)
    }
    if (this.plan.layout.titleY !== null) {
      this.lineOf(this.plan.scenario, this.titleY(), 20, 1.1, TEXT_PRIMARY, FontWeight.Medium, 0.2)
    }

    this.lineOf(
      this.plan.hero.value,
      this.plan.layout.heroY,
      this.heroSize(),
      0.95,
      this.plan.accent,
      FontWeight.Bold,
      -0.6
    )

    Row() {
      Text(this.plan.hero.label)
        .fontSize(this.v(13))
        .maxFontScale(1)
        .fontColor(TEXT_SECONDARY)
        .maxLines(1)
      if (this.plan.hero.detail !== undefined) {
        Text(' · ')
          .fontSize(this.v(12))
          .maxFontScale(1)
          .fontColor(TEXT_MUTED)
          .maxLines(1)
        Text(this.plan.hero.detail)
          .fontSize(this.v(12))
          .maxFontScale(1)
          .fontColor(TEXT_MUTED)
          .maxLines(1)
      }
    }
    .width(this.v(D))
    .height(this.v(20))
    .justifyContent(FlexAlign.Center)
    .position({ x: 0, y: this.v(this.sublineY()) - this.v(10) })

    ForEach(this.plan.rows, (row: PlanRow) => {
      Row() {
        Text(row.label)
          .fontSize(this.v(13))
          .maxFontScale(1)
          .fontColor(TEXT_SECONDARY)
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .layoutWeight(3)
        Text(row.value)
          .fontSize(this.v(14))
          .maxFontScale(1)
          .fontColor(TEXT_PRIMARY)
          .fontWeight(FontWeight.Bold)
          .maxLines(1)
          .textAlign(TextAlign.End)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .layoutWeight(5)
      }
      .width(this.v(row.width))
      .height(this.v(24))
      .padding({ left: this.v(14), right: this.v(14) })
      .backgroundColor(PANEL)
      .borderRadius(this.v(12))
      .border({ width: this.v(0.8), color: DIVIDER })
      .position({ x: this.v(C) - this.v(row.width) / 2, y: this.v(row.y) - this.v(12) })
    }, (row: PlanRow, index: number) => `${index}-${row.y}`)

    if (this.plan.layout.actionsY !== null) {
      Row() {
        ForEach(this.plan.actions, (action: PlanAction) => {
          Text(action.label)
            .fontSize(this.v(13))
            .maxFontScale(1)
            .fontColor(action.kind === 'primary' ? this.plan.surface : TEXT_PRIMARY)
            .fontWeight(FontWeight.Medium)
            .width(this.v(this.plan.actions.length === 1 ? 112 : 96))
            .height(this.v(34))
            .lineHeight(this.v(34))
            .textAlign(TextAlign.Center)
            .backgroundColor(action.kind === 'primary' ? this.plan.accent : TRANSPARENT)
            .borderRadius(this.v(17))
            .border({ width: this.v(1), color: action.kind === 'primary' ? this.plan.accent : DIVIDER })
            .margin({ left: this.v(5), right: this.v(5) })
        }, (action: PlanAction, index: number) => `${index}-${action.label}`)
      }
      .width(this.v(D))
      .height(this.v(34))
      .justifyContent(FlexAlign.Center)
      .position({ x: 0, y: this.v(this.actionsY()) - this.v(17) })
    }
  }

弧的圆心是 (233,233),半径 208,比安全圆 199 大 9 px,所以弧压在安全圆外侧;hitTestBehavior(HitTestMode.None) 让弧不拦截点击,否则它盖住整个表盘,MEM 胶囊和按钮都点不到。Progress 的 value 用 0–100,Plan 里的 progress 是 0–1,乘 100 只在调用处做一次。

指标行的外框宽度用 row.width(300),里面两段文字按 3:5 分,标签和值都 maxLines(1) 加 Ellipsis。引擎已经按可用宽度截过值,这里的 Ellipsis 是第二道校验;如果它真的生效,说明 truncate 的估算和 ArkUI 的实际字宽有偏差。行的 position 用 y - 12,把 24 px 高的行框中心对到 Plan 的 y 上。

这里有一处口径差:引擎的 fitValue 按 300 减标签宽度和 12 px 间距算可用宽度,渲染器却先把 300 减去左右各 14 px padding,再按 3:5 分给标签和值。两边算的是两套宽度,正常 fixture 没触发截断,但换成长文案时 ArkUI 的 Ellipsis 可能先于 truncate 生效。要彻底对齐,应该让引擎知道 padding 和权重,或者让渲染器按引擎算出的可用宽度排。

faceView 末尾还有一枚 MEM 胶囊。它的文字直接来自 plan.memory,位置只用了 memoryY 一个 y;因为这一行所在的弦宽只有 173.90 px,胶囊不做固定宽度,靠左右 padding 撑开,点击切到实验室:

    Row() {
      Text(`MEM ${this.plan.memory.estimatedKB} / ${this.plan.memory.budgetKB} KB ›`)
        .fontSize(this.v(10))
        .maxFontScale(1)
        .fontColor(TEXT_MUTED)
        .letterSpacing(this.v(1.1))
        .height(this.v(22))
        .lineHeight(this.v(22))
        .padding({ left: this.v(12), right: this.v(12) })
        .borderRadius(this.v(11))
        .border({ width: this.v(0.8), color: DIVIDER })
    }
    .width(this.v(D))
    .height(this.v(22))
    .justifyContent(FlexAlign.Center)
    .position({ x: 0, y: this.v(this.plan.layout.memoryY) - this.v(11) })
    .onClick(() => {
      this.page = 'lab';
    })

胶囊只有 22 px 高、视觉宽度不到 174 px,点击区域偏小;示例把 onClick 挂在整行 466 px 宽的 Row 上,实际可点范围比胶囊大。正式接入时按最小触控尺寸调整。

lineOf 按“行框中心”定位,不用“文字顶部”,和 Plan 的 y 语义一致。行高取 size × lineHeight + 4,再把整个容器上移半个容器高度。这样同一个 y 在 20 px 标题和 56 px 主值上表示的都是视觉中心,不会因为字号改变而偏移。换渲染器时这个锚点要一起对齐,否则同一份 Plan 在 ArkUI 和 Flutter 上会差半行:

  @Builder
  lineOf(text: string, y: number, size: number, lineHeight: number, color: string, weight: FontWeight, spacing: number) {
    Column() {
      Text(text)
        .fontSize(this.v(size))
        .maxFontScale(1)
        .lineHeight(this.v(size * lineHeight))
        .fontColor(color)
        .fontWeight(weight)
        .letterSpacing(this.v(spacing))
        .maxLines(1)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .textAlign(TextAlign.Center)
        .width('100%')
    }
    .width(this.v(D))
    .height(this.v(size * lineHeight + 4))
    .justifyContent(FlexAlign.Center)
    .position({ x: 0, y: this.v(y) - this.v(size * lineHeight + 4) / 2 })
  }

maxFontScale(1) 是必须的。系统的字体倍率会把 20 px 标题放大,固定布局会立刻越界;这里让字号由 Plan 决定,不受系统设置影响。代价是用户的无障碍字号偏好在这个演示里不生效,正式产品应该把它换成第二套约束——比如把系统倍率作为 textScale 传进引擎,让 max() 去降档,避免文字直接超出布局。

实验室页的控件都按 466 px 坐标绝对定位。预算在 [20, 32, 56, 64, 96, 128] 间步进,字号在 [1.00, 1.15, 1.30] 间步进,请求档位在 compact 与 full 之间切换,每次点击都调用同一个 refresh():

  @Builder
  labView() {
    // 实验室页:档位行,y=158
    Text(`${this.plan.tier.toUpperCase()} · ${this.plan.memory.estimatedKB} / ${this.plan.memory.budgetKB} KB`)
      .fontSize(this.v(20))
      .maxFontScale(1)
      .fontColor(this.plan.accent)
      .fontWeight(FontWeight.Bold)
      .textAlign(TextAlign.Center)
      .width(this.v(D))
      .height(this.v(28))
      .position({ x: 0, y: this.v(158) - this.v(14) })

    Row() {
      Text('预算').fontSize(this.v(12)).fontColor(TEXT_SECONDARY).width(this.v(70))
      Text('−')
        .fontSize(this.v(18)).fontColor(TEXT_PRIMARY).textAlign(TextAlign.Center)
        .width(this.v(40)).height(this.v(32)).lineHeight(this.v(32))
        .borderRadius(this.v(16)).backgroundColor(PANEL)
        .border({ width: this.v(1), color: DIVIDER })
        .onClick(() => {
          if (this.budgetIndex > 0) {
            this.budgetIndex -= 1;
            this.refresh();
          }
        })
      Text(`${this.budgets[this.budgetIndex]} KB`)
        .fontSize(this.v(14)).fontColor(TEXT_PRIMARY).fontWeight(FontWeight.Bold)
        .textAlign(TextAlign.Center).width(this.v(96))
      Text('+')
        .fontSize(this.v(18)).fontColor(TEXT_PRIMARY).textAlign(TextAlign.Center)
        .width(this.v(40)).height(this.v(32)).lineHeight(this.v(32))
        .borderRadius(this.v(16)).backgroundColor(PANEL)
        .border({ width: this.v(1), color: DIVIDER })
        .onClick(() => {
          if (this.budgetIndex < this.budgets.length - 1) {
            this.budgetIndex += 1;
            this.refresh();
          }
        })
    }
    .width(this.v(268))
    .height(this.v(32))
    .justifyContent(FlexAlign.SpaceBetween)
    .position({ x: this.v(C) - this.v(134), y: this.v(196) - this.v(16) })

    Row() {
      Text('字号').fontSize(this.v(12)).fontColor(TEXT_SECONDARY).width(this.v(70))
      Text('−')
        .fontSize(this.v(18)).fontColor(TEXT_PRIMARY).textAlign(TextAlign.Center)
        .width(this.v(40)).height(this.v(32)).lineHeight(this.v(32))
        .borderRadius(this.v(16)).backgroundColor(PANEL)
        .border({ width: this.v(1), color: DIVIDER })
        .onClick(() => {
          if (this.scaleIndex > 0) {
            this.scaleIndex -= 1;
            this.refresh();
          }
        })
      Text(`${this.scales[this.scaleIndex].toFixed(2)}×`)
        .fontSize(this.v(14)).fontColor(TEXT_PRIMARY).fontWeight(FontWeight.Bold)
        .textAlign(TextAlign.Center).width(this.v(96))
      Text('+')
        .fontSize(this.v(18)).fontColor(TEXT_PRIMARY).textAlign(TextAlign.Center)
        .width(this.v(40)).height(this.v(32)).lineHeight(this.v(32))
        .borderRadius(this.v(16)).backgroundColor(PANEL)
        .border({ width: this.v(1), color: DIVIDER })
        .onClick(() => {
          if (this.scaleIndex < this.scales.length - 1) {
            this.scaleIndex += 1;
            this.refresh();
          }
        })
    }
    .width(this.v(268))
    .height(this.v(32))
    .justifyContent(FlexAlign.SpaceBetween)
    .position({ x: this.v(C) - this.v(134), y: this.v(234) - this.v(16) })

    Text(this.requestFull ? '请求 full ›' : '请求 compact ›')
      .fontSize(this.v(12))
      .fontColor(TEXT_PRIMARY)
      .textAlign(TextAlign.Center)
      .width(this.v(200))
      .height(this.v(30))
      .lineHeight(this.v(30))
      .borderRadius(this.v(15))
      .backgroundColor(PANEL)
      .border({ width: this.v(1), color: this.plan.accentDim })
      .position({ x: this.v(C) - this.v(100), y: this.v(270) - this.v(15) })
      .onClick(() => {
        this.requestFull = !this.requestFull;
        this.refresh();
      })

    Scroll() {
      Column() {
        ForEach(this.plan.memory.decisions, (decision: string, index: number) => {
          Text(`${index + 1}. ${decision}`)
            .fontSize(this.v(12))
            .maxFontScale(1)
            .fontColor(TEXT_SECONDARY)
            .lineHeight(this.v(17))
            .width('100%')
            .margin({ bottom: this.v(6) })
        }, (decision: string, index: number) => `${index}-${decision}`)
      }
      .width('100%')
      .alignItems(HorizontalAlign.Start)
    }
    .width(this.v(290))
    .height(this.v(64))
    .position({ x: this.v(88), y: this.v(296) })
    .scrollBar(BarState.Off)

    Row() {
      Text('查看 JSON')
        .fontSize(this.v(12)).fontColor(TEXT_PRIMARY).textAlign(TextAlign.Center)
        .width(this.v(86)).height(this.v(28)).lineHeight(this.v(28))
        .borderRadius(this.v(14)).backgroundColor(PANEL)
        .border({ width: this.v(1), color: this.plan.accentDim })
        .onClick(() => {
          this.page = 'json';
        })
      Text('重置')
        .fontSize(this.v(12)).fontColor(TEXT_SECONDARY).textAlign(TextAlign.Center)
        .width(this.v(86)).height(this.v(28)).lineHeight(this.v(28))
        .borderRadius(this.v(14))
        .border({ width: this.v(1), color: DIVIDER })
        .onClick(() => {
          this.budgetIndex = 3;
          this.scaleIndex = 0;
          this.requestFull = false;
          this.refresh();
        })
    }
    .width(this.v(180))
    .height(this.v(28))
    .justifyContent(FlexAlign.SpaceBetween)
    .position({ x: this.v(C) - this.v(90), y: this.v(386) - this.v(14) })
  }

上面的 labView 为了把链式调用压成一段,Text 的样式写成了单行;实际每个 Text 都带 .maxFontScale(1),少了这一行,系统字号会把固定布局撑开。

决策列表的 Scroll 高 64 px,一行 17 px 行高加 6 px 底距,屏幕里大约露出 3 条,7 条要滑动才能看全。这个高度是设计稿定的,不会按内容自适应,所以决策文案变长时会先换行再撑高,滚动区高度不变。

JSON 页更简单:一个 Scroll 里放 Text(this.rawJson),字号 9 px、行高 12 px、宽 180 px、高 270 px,位置在 x=143、y=130。点击整个滚动区返回实验室,左上角另有一个返回键:

  @Builder
  jsonView() {
    Stack({ alignContent: Alignment.Center }) {
      Text('‹')
        .fontSize(this.v(26))
        .maxFontScale(1)
        .fontColor(this.plan.accent)
    }
    .width(this.v(40))
    .height(this.v(40))
    .borderRadius(this.v(20))
    .border({ width: this.v(1), color: DIVIDER })
    .position({ x: this.v(130), y: this.v(96) - this.v(20) })
    .onClick(() => {
      this.page = 'lab';
    })

    Scroll() {
      Text(this.rawJson)
        .fontSize(this.v(9))
        .maxFontScale(1)
        .fontColor(TEXT_SECONDARY)
        .lineHeight(this.v(12))
        .width('100%')
    }
    .width(this.v(180))
    .height(this.v(270))
    .position({ x: this.v(143), y: this.v(130) })
    .scrollBar(BarState.Off)
    .onClick(() => {
      this.page = 'lab';
    })
  }

JSON 页不做语法高亮,也不格式化:rawJson 是 requestSnapshot 原样保存的字符串,JSON.parse 只用于生成 plan,不会回写。JSON 页显示的就是 N-API 返回的字节内容,字段缺失或 null 都能直接看到。9 px 字号在 466 px 屏上偏小,但它的用途是核对字段,没打算让人读正文;一行放不下就换行,Scroll 只纵向滚动,不做横向滚动。

三个页面最终都叠在同一个 Stack 里。底层是 466 px 圆角 Column,颜色来自 plan.surface;上面再叠一个 398 px 的安全圆描边,只用于观察内容边界:

  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Column()
        .width(this.v(D))
        .height(this.v(D))
        .backgroundColor(this.plan.surface)
        .borderRadius(this.v(D) / 2)
        .clip(true)

      Column()
        .width(this.v(this.plan.safeRadius * 2))
        .height(this.v(this.plan.safeRadius * 2))
        .borderRadius(this.v(this.plan.safeRadius))
        .border({ width: this.v(0.7), color: DIVIDER })
        .opacity(0.55)
        .position({ x: this.v(C - this.plan.safeRadius), y: this.v(C - this.plan.safeRadius) })

      if (this.page === 'face') {
        this.faceView()
      } else if (this.page === 'lab') {
        this.labView()
      } else {
        this.jsonView()
      }
    }
    .width('100%')
    .height('100%')
    .backgroundColor(SURFACE_DEEP)
  }
}

Stack 最外层是 466 × 466 的圆角 Column,clip(true) 把内容裁进圆里;安全圆描边只用于观察,opacity(0.55),不参与命中。三个页面共用这一个 Stack,切页只换 page,Plan 状态不重建。

首帧的 plan 是 EMPTY_PLAN,y 不是 0 就是空,aboutToAppear 里的 refresh() 会立刻用真实 Plan 替换它。EMPTY_PLAN 只用于让 @State 有一个完整类型,不参与布局;如果 N-API 调用失败,页面保留上一个 Plan 并显示红字,不会回到空对象。

模拟器上的点击坐标按 466 × 466 物理像素记,入口与按钮都落在固定位置:

(233, 412)  表盘底部 MEM 胶囊 → 内存实验室
(140,  92)  实验室返回表盘
(196, 196)  预算 −        (347, 196)  预算 +
(196, 234)  字号 −        (347, 234)  字号 +
(233, 270)  请求档位切换
( 88, 296)-(378, 360) 决策列表(可滑动)
(186, 386)  查看 JSON     (280, 386)  重置
(150,  96)  JSON 页返回实验室

坐标是从实际点击记录里抄的,跟设计推导没关系。它们只用于自动化验收;正式页面应该用组件布局,由 ArkUI 的命中测试处理“点击哪里”。

6. 双向桥接

整条链路是同步单向调用:ArkTS 传四个数字,Kotlin 返回一段 UTF-8 JSON。没有回调注册,也没有线程安全函数,因此比“宿主发请求、原生回推结果”的浮层桥简单得多。但内存所有权仍然要交代清楚:

Index.ets  @State 预算 / 字号 / 请求档位
        │
        ▼
roundfit/PlanNative.ets                 requestSnapshot(budget, scale, height, rank)
        │  N-API(libentry.so)
        ▼
cpp/napi_init.cpp                       PlanJson:校验 4 个有限数字
        │  C ABI(libroundfit.so)
        ▼
ohos-native/.../NativeBridge.kt         @CName RoundFitPlanJson
        │
        ▼
roundfit/commonMain/.../RoundFitEngine  Degradation + RoundGeometry + PlanJson
        │  UTF-8 JSON,nativeHeap 分配,调用方释放
        ▼
ArkTS JSON.parse → 按 Plan 的 layout 渲染

Kotlin/Native 侧只暴露两个 C 函数。RoundFitPlanJson 接收四个原始参数,构造 LayoutConstraints 后调用同一个 RoundFitEngine;RoundFitFree 释放 nativeHeap 上的字符串。返回值是裸指针,C 侧拿不到 Kotlin 对象,所以不需要理解 Kotlin 的内存模型:

@file:OptIn(kotlin.experimental.ExperimentalNativeApi::class, kotlinx.cinterop.ExperimentalForeignApi::class)

package com.roundfit.ohos

import com.roundfit.PlanJson
import com.roundfit.RoundFitEngine
import com.roundfit.model.RoundFitScenarios
import com.roundfit.tier.LayoutConstraints
import com.roundfit.tier.Tier
import kotlinx.cinterop.*

/** 把字符串写成以 0 结尾的 UTF-8 缓冲区,由调用方通过 RoundFitFree 释放。 */
private fun textBuffer(text: String): CPointer<ByteVar> {
  val bytes = text.encodeToByteArray()
  val buffer = nativeHeap.allocArray<ByteVar>(bytes.size + 1)
  bytes.forEachIndexed { index, byte -> buffer[index] = byte }
  buffer[bytes.size] = 0
  return buffer
}

/** 出错时返回 JSON 错误对象,而不是让 ArkTS 线程崩溃。 */
private inline fun response(block: () -> String): CPointer<ByteVar> = try {
  textBuffer(block())
} catch (error: Throwable) {
  textBuffer("{\"error\":${PlanJson.quote(error.message ?: "Native error")}}")
}

/**
 * 按给定约束生成 roundfit.plan/v1 JSON。
 *
 * @param budgetKB 内存预算,本 fixture 最低 20。
 * @param textScale 系统字体倍率,例如 1.0 或 1.3。
 * @param contentHeight 可用内容高度,单位 px。
 * @param requestedRank 应用请求的档位 rank,范围 0..3。
 */
@CName("RoundFitPlanJson")
public fun planJson(
  budgetKB: Int,
  textScale: Double,
  contentHeight: Int,
  requestedRank: Int,
): CPointer<ByteVar> = response {
  val constraints = LayoutConstraints(
    budgetKB = budgetKB,
    textScale = textScale,
    contentHeight = contentHeight,
    requestedTier = Tier.fromRank(requestedRank),
  )
  RoundFitEngine.planJson(RoundFitScenarios.workout(), constraints)
}

@CName("RoundFitFree")
public fun freeNative(pointer: CPointer<ByteVar>?) {
  if (pointer != null) nativeHeap.free(pointer.rawValue)
}

textBuffer 分配 bytes.size + 1 并在末尾补 0,是因为 napi_create_string_utf8 配 NAPI_AUTO_LENGTH 时按 C 字符串读;不补 0 会读到堆上的下一个字节。response 捕获 Throwable 后仍返回合法 JSON,ArkTS 侧才能用同一个 JSON.parse 路径处理成功和失败。

nativeHeap.allocArray 分配的内存不受 Kotlin GC 管理,必须和 RoundFitFree 配对。如果 C 侧忘了调用(比如 napi_create_string_utf8 之前抛错),就会漏;当前代码在创建后立即释放,创建失败也释放。

链接脚本把其余符号全部隐藏,只留下两个入口。这样 libroundfit.so 的导出表可以被 nm 直接核对,也避免了 Kotlin 运行时符号与宿主冲突:

{
  global:
    RoundFitPlanJson;
    RoundFitFree;
  local: *;
};

头文件里和桥接有关的有两个 extern 声明,其余是 Kotlin/Native 的定宽类型、kref 结构和运行时服务表。libroundfit_KInt 就是 int,libroundfit_KDouble 是 double,所以 napi_init.cpp 里能直接 static_cast<libroundfit_KInt>;返回值声明成 void*,因为 C 侧不假设 Kotlin 字符串的内存布局。

// ohos/entry/src/main/cpp/include/libroundfit_api.h:67-68
extern void RoundFitFree(void* pointer);
extern void* RoundFitPlanJson(libroundfit_KInt budgetKB, libroundfit_KDouble textScale,
                              libroundfit_KInt contentHeight, libroundfit_KInt requestedRank);

libroundfit_symbols() 和一组 createNullable* 服务函数也在头文件里,但链接脚本把它们都归到 local,实际导出只有这两个入口;那组服务函数是 Kotlin/Native 的运行时接口,C 侧不需要调用。nm 的 T 列表就是证据。#ifdef __cplusplus 把这两个声明包在 extern "C" 里,所以 C++ 的 napi_init.cpp 能直接 include;换成 C 编译器时,libroundfit_KBoolean 的 typedef 走 _Bool 分支。这个头文件和 .so 必须来自同一次链接,prepareOhos 负责成对复制。

napi_init.cpp 负责参数校验和拷贝。它先确认四个参数都是有限数字,再调用 C ABI;返回的指针在 napi_create_string_utf8 之后立即释放,不让 Kotlin 内存参与 ArkTS 生命周期管理:

#include "napi/native_api.h"
#include "libroundfit_api.h"

#include <cmath>
#include <cstdint>

static bool ReadNumber(napi_env env, napi_value value, double &output) {
  napi_valuetype type = napi_undefined;
  if (napi_typeof(env, value, &type) != napi_ok || type != napi_number) {
    return false;
  }
  return napi_get_value_double(env, value, &output) == napi_ok && std::isfinite(output);
}

/** 调用 Kotlin/Native 引擎并返回其 UTF-8 Plan JSON。 */
static napi_value PlanJson(napi_env env, napi_callback_info info) {
  size_t argc = 4;
  napi_value args[4] = {nullptr, nullptr, nullptr, nullptr};
  if (napi_get_cb_info(env, info, &argc, args, nullptr, nullptr) != napi_ok || argc < 4) {
    napi_throw_type_error(
        env, nullptr, "planJson requires budgetKB, textScale, contentHeight and requestedRank");
    return nullptr;
  }

  double budgetKB = 0;
  double textScale = 0;
  double contentHeight = 0;
  double requestedRank = 0;
  if (!ReadNumber(env, args[0], budgetKB) || !ReadNumber(env, args[1], textScale) ||
      !ReadNumber(env, args[2], contentHeight) || !ReadNumber(env, args[3], requestedRank)) {
    napi_throw_type_error(env, nullptr, "planJson arguments must be finite numbers");
    return nullptr;
  }

  void *payload = RoundFitPlanJson(static_cast<libroundfit_KInt>(budgetKB), textScale,
                                   static_cast<libroundfit_KInt>(contentHeight),
                                   static_cast<libroundfit_KInt>(requestedRank));
  if (payload == nullptr) {
    napi_throw_error(env, nullptr, "Kotlin roundfit engine returned no plan");
    return nullptr;
  }

  napi_value result = nullptr;
  napi_status status = napi_create_string_utf8(
      env, static_cast<const char *>(payload), NAPI_AUTO_LENGTH, &result);
  RoundFitFree(payload);
  if (status != napi_ok) {
    napi_throw_error(env, nullptr, "Unable to create the plan JSON string");
    return nullptr;
  }
  return result;
}

static napi_value Init(napi_env env, napi_value exports) {
  napi_property_descriptor methods[] = {
      {"planJson", nullptr, PlanJson, nullptr, nullptr, nullptr, napi_default, nullptr},
  };
  if (napi_define_properties(env, exports, 1, methods) != napi_ok) {
    napi_throw_error(env, nullptr, "Unable to register roundfit exports");
    return nullptr;
  }
  return exports;
}

static napi_module roundfitModule = {1, 0, nullptr, Init, "entry", nullptr, {0}};

extern "C" __attribute__((constructor)) void RegisterRoundFitModule() {
  napi_module_register(&roundfitModule);
}

RoundFitFree(payload) 放在 napi_create_string_utf8 之后:N-API 需要读取指针内容来创建字符串,提前释放会让结果变成悬空数据。反过来,创建失败时也必须释放,否则每次异常都漏一块 nativeHeap。这两句的顺序不能调换。

napi_create_string_utf8 会把 C 字符串拷贝进 JS 字符串,所以 RoundFitFree 可以紧跟着调用;如果换成零拷贝的外部字符串接口,释放时机就要跟 JS 生命周期绑定,是另一套所有权模型。这里选择拷贝,C 侧可以在返回后立即释放,不需要回调。

参数范围目前在 ArkTS 侧限制:预算来自固定数组 [20, 32, 56, 64, 96, 128],字号来自 [1.00, 1.15, 1.30],高度固定 360,rank 只取 0/1。C 侧只检查有限性,static_cast<libroundfit_KInt> 会把小数截断;如果以后开放任意预算,应在边界层补范围与取整规则。

参数从 double 转 int 时,C++ 的 static_cast 直接截断小数;1.9 会变成 1,这里用截断,不做四舍五入。当前 UI 只传整数,所以没暴露;开放任意输入时要在 ArkTS 或 C 侧先取整。

CMake 把 libroundfit.so 作为 IMPORTED 目标导入,再把 N-API 桥编成 entry。头文件来自 prepareOhos 复制进 include/ 的那一份,不使用仓库里手写的声明:

cmake_minimum_required(VERSION 3.16)
project(roundfit_ohos_entry)

# Kotlin/Native 共享库,由 :ohos-native:prepareOhos 复制到 libs/arm64-v8a。
add_library(roundfit SHARED IMPORTED)
set_target_properties(roundfit PROPERTIES
  IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/arm64-v8a/libroundfit.so")

add_library(entry SHARED napi_init.cpp)
target_include_directories(entry PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(entry PRIVATE roundfit libace_napi.z.so)

IMPORTED 目标不让 CMake 参与 Kotlin/Native 的构建,Gradle 仍是 .so 的唯一生产者;CMake 只负责把 napi_init.cpp 编成 entry,并在链接时找到 libroundfit.so 和系统的 libace_napi.z.so。target_include_directories 指向 include/,用的是 prepareOhos 复制过来的头文件,仓库里没有手写副本。

libace_napi.z.so 是系统库,不在 HAP 里打包;libroundfit.so 是本地导入,最后会随 HAP 一起进 libs/arm64-v8a。CMake 只负责链接,不负责把 .so 复制进 HAP,复制由 prepareOhos 做。

ArkTS 的类型声明只需要一个函数。libentry.so 在 OHPM 里是一个本地包,types 指向同目录的 index.d.ts:

export const planJson: (
  budgetKB: number,
  textScale: number,
  contentHeight: number,
  requestedRank: number
) => string;
{
  "name": "libentry.so",
  "version": "1.0.0",
  "types": "./index.d.ts"
}

ohos-native/build.gradle.kts 负责把产物放进 HAP 工程。prepareOhos 是一个 Copy 任务:.so 进 entry/libs/arm64-v8a,生成的 libroundfit_api.h 进 entry/src/main/cpp/include。它依赖 linkDebugSharedOhosArm64,所以每次改引擎都要先跑它,再跑 hvigor:

plugins {
  kotlin("multiplatform")
}

group = "com.roundfit"
version = "1.0.0"

kotlin {
  jvmToolchain(21)
  ohosArm64 {
    binaries.sharedLib {
      baseName = "roundfit"
      linkerOpts("--entry=0", "--version-script=${project.file("src/ohosArm64Main/linker/roundfit.map")}")
    }
  }

  sourceSets {
    commonMain.dependencies { implementation(project(":roundfit")) }
  }
}

/**
 * Builds the Kotlin/Native shared library and stages it inside the HarmonyOS
 * app: `.so` into `entry/libs/arm64-v8a`, generated C header into the N-API
 * module's include directory.
 */
val prepareOhos by tasks.registering(Copy::class) {
  dependsOn("linkDebugSharedOhosArm64")
  from(layout.buildDirectory.dir("bin/ohosArm64/debugShared")) {
    include("libroundfit.so")
    into("libs/arm64-v8a")
  }
  from(layout.buildDirectory.dir("bin/ohosArm64/debugShared")) {
    include("libroundfit_api.h")
    into("src/main/cpp/include")
  }
  into(rootProject.layout.projectDirectory.dir("ohos/entry"))
}

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink>().configureEach {
  inputs.file("src/ohosArm64Main/linker/roundfit.map")
}

inputs.file 这行让 Gradle 在链接脚本变化时重跑链接;没有它,改导出表可能被判定 up-to-date,nm 看到的还是旧符号。--entry=0 不设置可执行入口,--version-script 指定导出表。调试版 .so 是 7,574,696 字节,HAP 里 strip 后约 2.15 MB;同一个 HAP 还带 52,472 字节的 libentry.so、1,262,504 字节的 libc++_shared.so 和 69,708 字节的 ets/modules.abc。HAP 总大小 3,574,725 字节。strip 去掉的主要是符号和调试信息,不是代码逻辑;libc++_shared.so 是随 HAP 打包的 C++ 标准库。

prepareOhos 的 Copy 只覆盖同名文件,不会删除旧产物;如果某次链接没有生成头文件,entry/src/main/cpp/include/ 里会留着上一次的版本,C 侧仍能编过。升级 Kotlin/Native 或改导出签名时,先把 entry/libs/arm64-v8a/ 和 include/ 清掉再跑 prepareOhos。

导出符号可以在本机直接核对:

$ nm -gU libroundfit.so | grep RoundFit
000000000011d5bc T RoundFitFree
000000000011d6b0 T RoundFitPlanJson

只有两个 T,没有别的 Kotlin 符号泄漏。nm 只看导出表,不看参数类型;头文件里的签名是 void* RoundFitPlanJson(int, double, int, int) 与 void RoundFitFree(void*),和 napi_init.cpp 的调用是否一致,要靠重新生成头文件并编译来保证。升级 Kotlin/Native 之后 .so 的 ABI 可能变,头文件和 static_cast 的写法都要重新核对。

7. 编译运行

KMP 侧的版本只有 Kotlin 一个变量,Gradle 版本由 wrapper 固定,JDK 由 gradle.properties 指向本机的 Zulu 21:

[versions]
kotlin = "2.2.21-1.0.0"

[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlin.code.style=official
kotlin.native.enableKlibsCrossCompilation=true
org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8
org.gradle.parallel=true
kotlin.native.distribution.downloadFromMaven=true

# 本机 JDK 21(Zulu)。下面是本机示例路径,换机器时改成自己的,或删掉这行用 JAVA_HOME。
org.gradle.java.home=/path/to/zulu21/Contents/Home

org.gradle.java.home 指向本机 Zulu 21,换机器时这行最容易忘;忘了会退回系统 JDK,而 jvmToolchain(21) 要求 21,版本对不上时 Gradle 会直接报错。kotlin.native.enableKlibsCrossCompilation=true 打开 klib 跨平台编译,downloadFromMaven=true 从 Maven 拉 Kotlin/Native 工具链;本机工具链已缓存,所以命令都带 --offline。

settings.gradle.kts 只包含三个子工程。仓库地址保留了一个内网 Maven 镜像,公网复现时可以换成 mavenCentral();插件解析里也保留了 Gradle Plugin Portal:

pluginManagement {
  repositories {
    google()
    mavenCentral()
    gradlePluginPortal()
    maven("https://maven.eazytec-cloud.com/nexus/repository/maven-public/")
  }
}

dependencyResolutionManagement {
  repositories {
    google()
    mavenCentral()
    mavenLocal()
    maven("https://maven.eazytec-cloud.com/nexus/repository/maven-public/")
  }
}

rootProject.name = "roundfit-kmp"

include("roundfit")
include("example")
include("ohos-native")

roundfit/build.gradle.kts 声明 explicitApi(),公开类型必须显式写 public;jvm() 供测试和示例,ohosArm64() 供手表。JVM 测试通过系统属性拿到仓库根目录和共享校验器路径:

// roundfit/build.gradle.kts
plugins {
  kotlin("multiplatform")
  `maven-publish`
}

group = "com.roundfit"
version = "1.0.0"

kotlin {
  explicitApi()
  jvm()
  jvmToolchain(21)
  ohosArm64()

  sourceSets {
    commonTest.dependencies { implementation(kotlin("test")) }
  }
}

tasks.withType<Test>().configureEach {
  // The JVM-only artifact test locates the repository and the shared validator via these.
  systemProperty("roundfit.root", rootProject.projectDir.absolutePath)
  systemProperty(
    "roundfit.validator",
    rootProject.projectDir.parentFile.resolve("tools/validate_plan.mjs").absolutePath,
  )
}

// Local publications can be consumed without uploading to an external repository.
publishing {
  publications.withType<MavenPublication>().configureEach {
    pom {
      name.set("RoundFit KMP")
      description.set(
        "Kotlin Multiplatform geometry, information degradation and Plan JSON for round wearable screens",
      )
      licenses {
        license {
          name.set("Apache-2.0")
          url.set("https://www.apache.org/licenses/LICENSE-2.0")
        }
      }
    }
  }
}

先跑 JVM 测试和示例,确认契约没漂移:

export JAVA_HOME="/path/to/zulu21/Contents/Home"

./gradlew :roundfit:jvmTest --offline --console=plain
./gradlew -q :example:run --offline --args="--scenario=workout" > preview/plan.json
node ../tools/validate_plan.mjs preview/plan.json

实际输出摘要:

> Task :roundfit:jvmTest
BUILD SUCCESSFUL in 1s
5 actionable tasks: 5 executed

✓ Kotlin Multiplatform 今日活动   compact      40/64 KB  preview/plan.json

1 plan(s) valid

-q 只抑制 Gradle 的 > Task ... 生命周期行,示例程序仍把 JSON 写到 stdout。不加 -q 时重定向文件会混入这些日志行,PreviewArtifactTest 的逐字符比对会失败。这个问题在验证记录里有完整记录。

--offline 是因为这台机器已经缓存了 Kotlin/Native 2.2.21 和 Gradle 依赖;换一台没缓存的机器,第一次要去掉 --offline,让 Gradle 下载工具链。

--args 还支持 --budget=、--requested=、--text-scale= 和 --height=。例如 --args="--scenario=workout --budget=32" 会生成 essential 的 Plan,--requested=glance 会强制一瞥档;默认值就是本项目的固定 fixture,所以不加参数时输出与 preview/plan.json 一致。

接着编 Kotlin/Native 共享库,再把 .so 与头文件放进 HAP 工程:

./gradlew :ohos-native:prepareOhos --offline

prepareOhos 会先跑 linkDebugSharedOhosArm64,后者不在 assemble 的依赖里,单独跑 assembleHap 不会触发 Gradle;tool/build_watch_hap.sh 把两段串起来。构建 HAP 用 DevEco Studio 自带的 hvigor;命令行工具 6.21.2 不认识 API 26,必须设置 NODE_HOME 与 DEVECO_SDK_HOME:

export NODE_HOME="<DevEco Node 目录>"
export DEVECO_SDK_HOME="<DevEco SDK 路径>"
cd ohos
hvigorw \
  --mode module -p product=default -p module=entry@default assembleHap --no-daemon

实际输出摘要:

> hvigor Finished :entry:default@BuildNativeWithCmake... after 658 ms
> hvigor Finished :entry:default@CompileArkTS... after 1 s 464 ms
> hvigor Finished :entry:default@PackageHap... after 192 ms
> hvigor WARN: No signingConfig found for product default
> hvigor BUILD SUCCESSFUL in 3 s 983 ms

这次构建里,BuildNativeWithCmake 只编 entry 里的 napi_init.cpp,Kotlin 库不在 hvigor 里生成;所以 prepareOhos 必须先跑,且 libroundfit.so 已经在 entry/libs/arm64-v8a/。把 Gradle 和 hvigor 拆成两段,是为了让 Kotlin/Native 的链接仍由 Gradle 管,hvigor 只负责 ArkTS 和打包。

产物是未签名的 entry-default-unsigned.hap。本机的 Huawei_Wearable 模拟器是 log 调试镜像,hdc install 直接接受 unsigned HAP;换到真机或正式镜像需要补签名配置:

HDC=hdc
$HDC -t 127.0.0.1:5555 install -r \
  ohos/entry/build/default/outputs/default/entry-default-unsigned.hap
$HDC -t 127.0.0.1:5555 shell "aa force-stop com.lqjmac.roundfitkmp"
$HDC -t 127.0.0.1:5555 shell "aa start -a EntryAbility -b com.lqjmac.roundfitkmp"

安装与启动的实际输出:

$ hdc -t 127.0.0.1:5555 install -r entry-default-unsigned.hap
[Info]App install path:... msg:install bundle successfully.
AppMod finish

$ hdc -t 127.0.0.1:5555 shell "aa start -a EntryAbility -b com.lqjmac.roundfitkmp"
start ability successfully.

$ hdc -t 127.0.0.1:5555 shell "aa dump -l" | grep -A5 roundfitkmp
bundle name [com.lqjmac.roundfitkmp]
ability type [PAGE]
state #FOREGROUND
app state #FOREGROUND

aa dump -l 里看到 state #FOREGROUND 才算启动成功;hdc install 成功只代表包装上了,不代表 Ability 起来了。这两个状态分开看,能省掉一轮“为什么桌面没有图标”的排查。

也可以直接跑封装脚本,它在 prepareOhos 之后调用 hvigor,--install 还会安装并启动:

./tool/build_watch_hap.sh
./tool/build_watch_hap.sh --install 127.0.0.1:5555

鸿蒙工程的根配置把 compile 与 target 都设为 26,compatible 保持 6.0.0(20)。signingConfigs 为空,所以只能装 log 镜像;strictMode 打开大小写与 normalized OHM URL 检查:

{
  "app": {
    "signingConfigs": [],
    "products": [
      {
        "name": "default",
        "compileSdkVersion": "26.0.0",
        "compatibleSdkVersion": "6.0.0(20)",
        "targetSdkVersion": "26.0.0",
        "runtimeOS": "HarmonyOS",
        "buildOption": {
          "strictMode": {
            "caseSensitiveCheck": true,
            "useNormalizedOHMUrl": true
          }
        }
      }
    ],
    "buildModeSet": [
      { "name": "debug" },
      { "name": "release" }
    ]
  },
  "modules": [
    {
      "name": "entry",
      "srcPath": "./entry",
      "targets": [
        {
          "name": "default",
          "applyToProducts": ["default"]
        }
      ]
    }
  ]
}

entry/build-profile.json5 只编 arm64-v8a,因为手表模拟器与真机都是 ARM64:

{
  "apiType": "stageMode",
  "buildOption": {
    "externalNativeOptions": {
      "path": "./src/main/cpp/CMakeLists.txt",
      "arguments": "",
      "cppFlags": "",
      "abiFilters": ["arm64-v8a"]
    }
  },
  "targets": [{ "name": "default" }]
}

module.json5 声明 deviceTypes: ["wearable"],入口是 EntryAbility,图标和启动色都走资源表。这里没有申请任何权限,也没有后台任务或传感器:

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": ["wearable"],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "$string:EntryAbility_desc",
        "icon": "$media:app_icon",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:app_icon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["ohos.want.action.home"]
          }
        ]
      }
    ]
  }
}

entry/oh-package.json5 只把 libentry.so 声明为本地依赖,类型声明在同一目录:

{
  "name": "entry",
  "version": "1.0.0",
  "description": "RoundFit KMP wearable entry: N-API bridge to the Kotlin/Native plan engine",
  "main": "",
  "author": "RoundFit",
  "license": "Apache-2.0",
  "dependencies": {
    "libentry.so": "file:./src/main/cpp/types/libentry"
  }
}

EntryAbility 只有两个动作:把应用固定为深色,加载 pages/Index。圆屏效果不依赖窗口模式,所以没有设置全屏或沉浸式参数:

import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';

const DOMAIN: number = 0x5246;
const TAG: string = 'RoundFitKmp';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
    hilog.info(DOMAIN, TAG, 'EntryAbility onCreate');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.loadContent('pages/Index', (error) => {
      if (error.code) {
        hilog.error(DOMAIN, TAG, 'Failed to load pages/Index: %{public}s', JSON.stringify(error));
        return;
      }
      hilog.info(DOMAIN, TAG, 'RoundFit watch page loaded');
    });
  }
}

构建日志里有三种预期告警:px2vp 已废弃、libentry.so 的 N-API 类型声明需要 .d.ts(本工程已提供)、setColorMode 在旧系统上可能抛异常。它们不影响产物。

8. 问题处理

表盘第一次跑起来时,元素整体比预期低了一截,MEM 胶囊直接跑出了屏幕。我一开始以为是 heroY 或 memoryY 写错了,把 Plan 里的 y 和截图逐个对,才发现数值没错,错在单位:Plan 的 y 是 466 px 设计坐标,ArkTS 必须用 px2vp(y) 换算;模拟器 density 2.0,1 px 正好 0.5 vp。直接把 y 当 vp 用,所有元素会按 density 放大一倍、跑到屏幕外;先把设计坐标除以 2 再传给 px2vp,元素又只剩一半大小。两种错误都不会报错,只会让表盘看起来“放大溢出”或“缩在左上角”。后来我把 v() 固定成唯一的换算入口,位置、字号、圆角都走它,才不再混用。

切换档位后文字不刷新,但档位行和内存数字变了,这个我踩过两次。一次是把档位文字作为参数传进 @Builder,@State plan 整体替换后构建器没有重新求值;改成在 labView() 里直接写 Text 才跟上。另一次是 ForEach 只用 index 做 key,决策文案换了却被当成同一项,列表停在旧内容;key 改成 ${index}-${decision} 后正常。这两处都不会报错,只表现为“点了按钮但某一块没动”,所以排查时要把档位数字、决策列表和表盘槽位分开看。

系统字号调大后布局会被撑开,得靠每个 Text 的 maxFontScale(1) 压住。实验室的「字号」按钮不会直接改渲染字号,它把 1.00/1.15/1.30 作为 textScale 传给引擎,由 textScaleCap 决定是否降档;会把固定布局撑开的是系统字体倍率。示例把渲染字号限制为 1,代价是系统字号很大的用户看到的是不放大、可能更小的字。

预算压到 20 KB 以下时(例如改 budgets 数组或从 JVM 调用),引擎会在 require(memory.totalKB <= constraints.budgetKB) 处抛出 IllegalArgumentException,经 response 包成 {"error": ...},实验室显示一行红字。实验室的预算按钮下限是 20 KB,正常点击不会走到这条路径,errorText 是给越界调用与原生失败留的。

行被圆边裁掉时,PlanRow.width 和该高度的弦宽会先暴露矛盾。示例的 width 固定为 300,y=286 处弦宽 383.63,减 24 后上限 359.63,所以 300 是安全的;如果把行放到 y=380,dy=147,弦宽 268.27,上限 244.27,仍按 300 画就会被裁。引擎的 rowWidth 此时返回 244,行框跟着缩窄,文本再按估算宽度截断;排障时把行框宽度和文本宽度分开看。

最隐蔽的一次是 HAP 编译通过、启动却找不到 libroundfit.so。prepareOhos 在 hvigor 之前跑过,entry/libs/arm64-v8a/ 里的 .so 还得和 entry/src/main/cpp/include/libroundfit_api.h 来自同一次链接。只更新 .so 会留下旧头文件;只更新头文件会让 C 侧按新签名调用旧库。两种情况下 hvigor 都可能成功,问题要到运行时才出现。升级 Kotlin/Native 后应重新生成整套产物,而不是只替换一个文件。

还有一次报“不认识 API 26”,换 hvigor 才好。命令行工具 6.21.2 的 SDK 定义落后于 API 26;DevEco Studio 内置的 hvigor 6.26.4 才能识别。脚本里显式设置 NODE_HOME 和 DEVECO_SDK_HOME,不要依赖 shell 里残留的环境变量。

43/44 那次,失败信息是 missing validator,跟断言无关,先看错误类型再决定要不要改代码。失败项是 PreviewArtifactTest.sharedValidatorAcceptsPreview,原因是六实现共享的 ../tools/validate_plan.mjs 不在当前 checkout 中;previewIsGeneratedByTheEngine 与其余 42 个用例仍然通过。这是环境缺失,契约没漂移,不能靠改断言“修好”。在完整工作区里把校验器放回仓库上一级的 tools/,再按第 7 节的命令运行确认。

unsigned HAP 装真机失败,先看镜像类型。log 调试镜像接受 unsigned HAP;正式镜像或真机需要证书与 profile,signingConfigs 不能为空。示例的 hdc install 成功记录只对本机模拟器有效,不能当作发布配置。

收尾时核对数据。设备默认态应与 preview/plan.json 一致:compact、40/64 KB、eyebrowY=86、titleY=122、heroY=222、rowsY=[286]、actionsY=368、memoryY=412、arcRadius=208,dropped 为 hero.detail、row[1]、action[1]、blur。如果设备的默认态与文件不一致,先查 WORKOUT_CONSTRAINTS 是否被改动,再查 ArkTS 的 requestedRank 与初始索引是否被改(budgetIndex=3 对应 64 KB,requestedRank=1 对应 compact)。

9. 交付边界:哪些已经验证,哪些还没有

roundfit 是纯 KMP 的圆屏布局与降级库,ohos 是跑在手表上的 HAP。几何、档位、内存和 Plan JSON 都在 commonMain 里,HAP 里的 ArkUI 只按 Plan 的坐标和槽位绘制。表盘上的 MEM 31 / 32 KB、实验室里的 ESSENTIAL · 31 / 32 KB 和 JSON 页里的 "tier": "essential" 来自同一次 Kotlin 调用;换档时这三个值一起变,链路才算没断。

如果要把这套做法用到现有项目,我会先保留普通 ArkUI 组件路径,让“四个参数进、JSON 出”的链路跑通,再接 Plan 驱动的固定布局;然后替换 WatchContent 的 fixture、补齐业务字段,并保留 PlanJson 的确定性输出,让设备、JVM 示例和预览产物可以逐字符对照。档位阈值最后再按真实设备的弦宽和内存预算调。

其他边界:其他表盘尺寸、release 链接、系统字体倍率真实生效、签名与发布。ohosArm64 在 466 × 466 / API 26 的 Huawei_Wearable 模拟器上跑过,低内存压力和多后台场景没有单独测;只声明了 wearable,HAP 未签名,glance 以下没有更低的档位。本机最后一次 JVM 复跑是 43/44,缺的是共享校验器,契约本身没问题。

参考资料:AtomGit 源码仓库、Kotlin/Native C interop、Node.js N-API、HarmonyOS 开发者文档。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐