diff --git a/openless-all/android/IME_UI_REWRITE.md b/openless-all/android/IME_UI_REWRITE.md new file mode 100644 index 000000000..a76266cfa --- /dev/null +++ b/openless-all/android/IME_UI_REWRITE.md @@ -0,0 +1,258 @@ +# Android 输入法 UI 重写设计与实施记录 + +> 状态:本地重写与自动化回归已进入手机验收阶段。最初的设计目标与后续实现、验证证据分节记录,不能把设计提案当成已实现功能。 +> 基线:仓库 `2d9fba66`。前半部分保留改造前的静态定位,后半部分记录实际实施与测试。历史行号不是当前源码行号;源码规模不作为质量判断。 + +## 1. 目标与非目标 + +**目标**:让输入法的展示、手势、候选呈现、模式切换、尺寸主题、生命周期状态可独立测试与替换,同时不改变用户已依赖的输入行为与数据。 + +**非目标**:滑行输入、皮肤商店;词库/Rime 引擎改造;词建议质量提升。**不把技术栈迁移作为本次目标**——暂沿现有 Kotlin Views 实现以减少变量,是否迁移另行评估。 + +**外部参考的性质**:下列项目只作"功能声明"级别的参考,README 不能证明其实现成熟或经过验证,本规格不转述其代码细节。 + +- [HeliBoard](https://github.com/Helium314/HeliBoard):可定制布局、单手模式、明暗主题; +- [FlorisBoard](https://github.com/florisboard/florisboard):剪贴板面板、主题机制;**其词建议仍在开发,不作为基线**; +- [Fcitx5 for Android](https://github.com/fcitx5-android/fcitx5-android):按键弹出预览、长按符号、展开候选; +- [Trime](https://github.com/osfans/trime):Rime 引擎与前端渲染分离。 + +## 2. 改造前现状(历史静态抽样,非穷尽审计) + +| 事实 | 依据 | +|---|---| +| 主界面主要由单个 `InputMethodService` 构建 | [OpenLessImeService.kt](kotlin/OpenLessImeService.kt)(6591 行) | +| 笔画面板由其控制器参与构建 | [StrokeInputController.kt](kotlin/StrokeInputController.kt) `buildStrokeView` L129 | +| 四模式:语音/笔画/剪贴板/英文 | `OpenLessImeService.kt` L36 | +| 英文三层:字母/数字/符号 | 同上 L39–L42 | +| 拉丁双语义:英文直通 / 拼音走 Rime | 同上 L48–L53 | +| 语音状态是字符串 `idle/speaking/thinking/done/error` | 同上 L305;多处字面量比较 L4041、L4596、L4773 | +| 面板高度已有统一来源 | 同上 L6411–L6437:220–420dp(默认 300)、抬升 0–120dp | +| 主题:`theme_mode` 覆盖系统,颜色逐处 `tone(dark, light)` | 同上 L424–L435 | +| 英文候选**长按 = 遗忘自定义词** | 同上 L3311、L3355;[EnglishCandidateProvider.kt](kotlin/EnglishCandidateProvider.kt) L76–L81 | +| 语音命令现为 `start/stop/cancel/cloud`,**无翻译/发送命令** | 同上 L63、L102–L128、L209 | + +据此判断需要动的是:状态表达、手势组织、候选呈现、模式切换、尺寸/主题 token 化、生命周期清理。高度**不是**无真源,现状应沿用 `panelHeight*` 并扩展,而不是新建第二套。 + +## 3. 体验规格 + +### 3.1 双体验 + +- `voiceFocused`:默认落在语音页,可切到打字/剪贴板/笔画; +- `singleKeyboard`:默认落在键盘页,空格长按起语音。 +- 两者共享面板高度。本版不新增第二份“体验”偏好:沿用本地模式记忆,用户停在语音页即为语音优先,停在键盘页并用空格按住说话即为单键盘路径;不会写入宿主的共享配置来覆盖本地模式。 +- 初次默认语音页,后续记住用户主动选择;密码/数字/电话/日期字段只做临时适配,不覆盖该偏好。独立体验锁定开关仍是后续产品选项,不宣称本版已提供。 + +### 3.2 状态机与宿主协同目标 + +``` +ImePhase = Idle | Starting | Listening | Processing | AwaitingInsertion | Done | Cancelled | Error +ImeAvailability = Unresponsive | NeedsActivation | Preparing | Busy | Ready +``` + +- **S1** `Starting/Listening/Processing/AwaitingInsertion` 为 busy;busy 时默认不开放会破坏当前会话的操作。 +- **S2** UI 呈现由单一 `render(snapshot)` 产生,回调里不再散改文案/可见性。 +- **S3** 宿主状态带时间戳;过期即视为 `Unresponsive`,"能否开始"与 UI 共用判断。 +- **S4** 目标冻结:记录 `documentId + selectionRevision`;回调时代码校验目标未变,否则拒绝而不是改投。 +- **S5** 两段式启动:请求 → 下一主循环校验(目标未变、输入法可见)→ 提交;期间取消必须可中断。 +- **S6** 生命周期:`onStartInput` 重置目标并**隔离过期回调**(旧 requestId、旧 `InputConnection` 身份一律丢弃);`onFinishInput`/`onFinishInputView` 取消进行中会话与定时器。**不自动提交半成品组合**——保留现有"候选上屏/明确结束时才提交"的策略。 +- **S7** busy 中用户切模式:允许"先显式取消当前会话,再切换",不要求绝对禁用切换。 + +**本版实现边界**:实际 UI 阶段为 `Idle/Starting/Recording/Processing/Submitting/Done/Cancelled/Error`,通过纯投影与能力资格集中渲染;等待本入口文字结果时维持 Processing 所有权。云笔记网络提交阶段不伪装成可取消录音,可按原契约开始下一次听写。身份隔离基于 editor session epoch、requestId 与真实 backend sessionId。S3 的完整带时效可用性租约、S4 的跨宿主 documentId/selectionRevision 协议与 S5 的完整两阶段宿主启动是 iOS 对照设计目标,未在本轮更改既有 Android 后端协议来实现,不把它们列为已验证。 + +### 3.3 手势 + +| 手势 | 行为 | +|---|---| +| 空格轻点 | 输入空格;有组合先上屏组合 | +| 空格长按 | 开始语音,进入按住说话覆盖层 | +| 按住+滑动 | 覆盖层内选择"松手输入 / 取消";翻译与发送见 §5(当前协议不支持,仅扩展提案) | +| 松手 | 以**终点坐标**判定;两识别器同时结束时延迟一帧取终点 | +| 左右滑动头部 | 切换模式,带方向动画;字母键区域不竞争此手势 | +| 删除长按 | 连发删除,沿用现有节奏 | +| 笔画输入 | 沿用现有控制器与交互 | + +- **G1** 手势→动作由纯函数 `GestureResolver` 完成(手势 + 几何 + 状态 → 动作),可在 JVM 单测。 +- **G2** 取消永远可用,不得被"开始中"状态吞掉。 +- **G3** 触控目标优先 **48dp**(Android 惯例);密集字母键按可达性与真机验证确定具体尺寸,**不强制每个字母横向 48dp**。 + +### 3.4 候选呈现 + +- 候选条:单行滚动,首项高亮,末尾展开入口。 +- 展开面板:多行网格,覆盖键盘区但不改变面板总高度;关闭后恢复原视图。 +- **长按语义保持现状**:英文候选长按 = 遗忘自定义词,必须保留。中文/拼音是否新增长按行为需单独立项,**本次不要求"长按松手上屏"**。 +- 符号面板:保留现有三层切换。 +- Rime:前端只消费候选列表,不解析输入串(**C1** 候选渲染用结构化比较,相同则跳过重建;**C2** 抑制我方写入触发的 `onUpdateSelection` 回环)。 + +### 3.5 尺寸与主题 + +- 尺寸沿用 `panelHeightDp/Px`、`raiseHeightDp/Px` 单一来源,仅扩展(landscape、体验差异),任何模式切换不改变总高度。 +- 主题提炼 `ImePalette` 语义 token(surface/key/auxiliary/accent/warn/text/separator,各含 dark/light);`theme_mode` 保持 light/dark/system 三态。 +- 主题切换更新颜色相关内容,但保留系统 IME 根视图、编辑器对象与业务状态,不通过反复 `setInputView` 替换窗口;不宣称所有子 View 原地变色。 +- 单手模式为可选后续项,不阻塞本期。 + +### 3.6 语音可视化与反馈 + +- 波形/音量来自真实电平(现有静音阈值 0.02),无样本即静音,不用合成动画。 +- 触觉三档:按键 / 开始 / 错误;文案由 `render(snapshot)` 单一来源输出。 + +### 3.7 无障碍 + +- 每个可交互控件有稳定描述;候选展开/收起后更新可访问性状态; +- 状态变化发送内容变更通知(仅在无障碍焦点时); +- 动效可关(系统动画缩放为 0 或无障碍选项);TalkBack 下候选/预览文本可读。 + +## 4. 架构方向 + +``` +OpenLessImeService 生命周期绑定 + 组装(不放具体布局逻辑) +presentation/ 纯 Kotlin,可 JVM 单测,不 import android.* + ImeStateMachine · GestureResolver · CandidateRenderState · ImePalette · ImeDimens +views/ Android Views 组件,无业务逻辑 + VoicePanel · Waveform · CandidateBar · CandidatePanel · EnglishKeyboard + · ClipboardPanel · ModeSwitch · PanelHost +adapter/ 外部契约适配 + NativeImeBridge · RimeCandidateSource · EnglishPredictionSource · ClipboardSource +``` + +约束:`views/` 不直接调用 native;`presentation/` 不依赖 Android 框架;服务不出现具体布局代码;可继续程序化构建,布局参数来自 `ImeDimens`/布局数据类。 + +**视觉迁移策略**:P0 允许"等价搬迁、像素不变"作为过渡手段;**这不是最终要求**,后续按本规格实现并允许有意调整。 + +## 5. 外部契约与可移动实现 + +**必须保持的外部契约**(实现位置可移动,行为不可变): + +- JNI 方法签名与语义(`nativeImeCommand`、`nativeAsrRoute`、词汇表相关方法、`nativeHasRegisteredActivityContext`); +- 语音命令动作与 JSON 字段(`start/stop/cancel/cloud`)及宿主回调解析; +- Rime 引擎接口与候选输出格式; +- 存储格式与偏好键(`openless_ime_ui`、宿主共享偏好);**用户词、频次、剪贴板历史升级后不丢**; +- 隐私与输入正确性保护(草稿替换、粘贴校验、学习策略、隐私判定)行为不变。 + +**可自由重构的**:视图实现、状态存放位置、测试方式。现有基于源码正则匹配的契约测试,可替换为**等价行为保护**(不绑定实现细节)。 + +**协议扩展(仅提案,不在本次 UI 重写中强制)**:翻译、发送等动作当前协议无对应命令;若产品需要,须与宿主同步定义命令与状态,UI 侧不单方面假设可用。 + +## 6. 分期与验收 + +- **P0**:状态机、手势解析、候选渲染状态、palette/dimens 骨架 + JVM 单测;服务接线;视觉等价迁移。 +- **P1**:候选条与展开面板、符号面板、语音面板与真实波形、模式切页。 +- **P2**:模式记忆覆盖两种使用路径、主题/尺寸语义化、无障碍完善;独立体验开关、单手模式是后续可选项。 + +**验收条目**(均可观察/可自动化,不依赖未核验行为): + +- AC-01 状态迁移单测覆盖:取消、丢焦点、目标变化、超时、busy 切模式。 +- AC-02 手势解析单测覆盖:空格轻点/长按/滑动/松手判定、删除连发。 +- AC-03 现有 Android 契约测试通过(或替换为等价行为保护)。 +- AC-04 英文候选长按仍执行"遗忘自定义词"。 +- AC-05 展开候选不改变面板总高度,关闭后恢复。 +- AC-06 静音时波形无动画。 +- AC-07 半成品组合不被自动提交;切换输入框后旧回调不生效。 +- AC-08 `theme_mode` 三态切换更新呈现,普通刷新不替换系统输入视图根与编辑器对象。 +- AC-09 高度 220/300/420dp 与 landscape 无裁切、无按键重叠(真机)。 +- AC-10 TalkBack 可遍历按键与候选,状态变化有播报。 +- AC-11 升级后用户词、频次、剪贴板历史、偏好保留。 +- AC-12 宿主未启动/弱网时,可用性文案与禁用态正确。 + +**真机清单**(每期执行,无法自动化):微信/QQ/短信上屏与粘贴;密码框与数字框;横屏/分屏/折叠展开;冷启动(杀进程后拉起);宿主未启动。 + +## 7. 风险与限制 + +| 风险 | 说明 | 缓解 | +|---|---|---| +| 静态审查局限 | 本文件与 iOS 依据均未实机验证 | 真机清单 + 逐期对照验收 | +| 状态迁移漏改 | 现有大量字符串比较,易漏 | 先加兼容层,逐步替换并用单测锁定 | +| 重建丢状态 | 现有刷新会重建视图树 | 状态外置,重建只重建 View | +| Rime 组合态 | 前端重写可能与组合态不同步 | 组合态由引擎持有,前端只渲染 | +| 隐私回归 | 剪贴板面板/预览可能新增读取点 | 复用现有隐私判定,新增读取点需评审 | +| 性能未知 | 无帧率/启动时延数据 | 后续补基准,目标值需实测校准 | +| 外部参考 | README 仅证明功能声明 | 不据此推断成熟度,也不照搬实现 | + +## 8. 参考 + +**iOS 基线(本仓库,静态阅读)**:[KeyboardViewController.swift](../ios/Keyboard/KeyboardViewController.swift)(生命周期 L232–330、布局 L425–816、空格手势 L1682–1806、状态映射 L2388–2546、插入 L2316–2379)、[KeyboardPresentation.swift](../ios/Packages/OpenLessShared/Sources/OpenLessShared/KeyboardPresentation.swift)(尺寸 L3–16、偏好独立 L18–30)、[KeyboardVoiceAvailability.swift](../ios/Packages/OpenLessShared/Sources/OpenLessShared/KeyboardVoiceAvailability.swift)(L4–20)、[SpaceVoiceOverlay.swift](../ios/PlatformShared/SpaceVoiceOverlay.swift)(L137–219)、[KeyboardStyle.swift](../ios/Keyboard/KeyboardStyle.swift)(L9–32)。iOS 同样未经本次实机验证。 + +**Android 现状**:[OpenLessImeService.kt](kotlin/OpenLessImeService.kt)、[StrokeInputController.kt](kotlin/StrokeInputController.kt)、[RimePinyinController.kt](kotlin/RimePinyinController.kt)、[EnglishCandidateProvider.kt](kotlin/EnglishCandidateProvider.kt)、[OpenLessNative.kt](kotlin/OpenLessNative.kt)、[ImePrivacyPolicy.kt](kotlin/ImePrivacyPolicy.kt)、[ImeDraftReplacement.kt](kotlin/ImeDraftReplacement.kt)、[OpenLessPasteVerification.kt](kotlin/OpenLessPasteVerification.kt);契约测试见 [app/scripts](../app/scripts)(`android-*.test.mjs`)。 + +**外部**:HeliBoard / FlorisBoard / Fcitx5 for Android / Trime(链接见 §1)。 + +## 9. 官网 APK 对照与当前实现检查点(2026-11-27) + +从正常 TLS 校验的官网链接取得两份安装包,仅做离线资源与类索引分析,未安装或运行竞品。包内签名验证通过,但没有取得官方独立公布的证书指纹,因此不把签名自洽等同于独立的发行身份鉴定。 + +| 样本 | 官网入口 | 版本 / 包名 | SHA-256 | +|---|---|---|---| +| 微信输入法 | → 腾讯 CDN | 4.0.2 / `com.tencent.wetype` | `f26190b30627eab5ac636c04f459618cd3211b92c5c6364d858dd9f47d3d8f29` | +| 讯飞输入法 | → 官网下载入口 → voicecloud CDN | 15.0.26 / `com.iflytek.inputmethod` | `9a5ad7d957e92e506d3536a27f9aa0509e8d7d0592fea0c721759831439a63e9` | + +原始包与研究证据保存在本地 `/data-win/openless-cache/agent/scratch/android-ime-commercial-research-20261127/`,不进入 Git,也不把闭源代码、布局文件、图标、词库或模型复制到本项目。 + +可直接观察到、而非凭类名猜测的设计: + +- 微信键盘的 JSON 配置将行、按键、长按提示、动作与主题属性分开描述;横竖屏有不同的行高配置。 +- 讯飞的 INI 配置将候选带与键盘带分成独立区域,并有竖屏/横屏配置和多种候选行配置。 +- 这些证据支持我们采用“布局数据 + 独立渲染组件 + 语义主题”的方向;不证明竞品性能更好,也不能仅凭资源数量推断成熟度或运行期架构。 +- 两者可能混合使用数据布局、XML 和代码视图;不作“微信纯代码、讯飞纯 XML”的绝对判断。未知字段不作为实现依据。 + +当前已接线的组件:[布局/主题模型]()、[打字/候选面板]()、[语音面板]()、[可访问的模式栏]()、[可测手势仲裁]()。语音会话、Rime、学习与文本提交仍由现有宿主适配,未复制竞品实现。 + +**尚不能宣称整体验收通过**:笔画/编辑子面板的进一步解耦、横屏/大屏专项布局、主题无整树重建、双体验设置,以及完整真机交互和性能验证仍须按第 6 节逐项完成。首个可安装检查点不是“成熟输入法已全部完成”的结论。 + +首版检查点验证:38 项 JVM 模型/手势测试、19 项 Android 契约检查通过;arm64 debug APK 与 AndroidTest APK 构建通过,并安装到华为 LYA-AL00(Android 10 / API 29)。手机上运行了 29 项 View/手势仪器测试,全部通过;这不是实际麦克风、ASR/润色与跨应用上屏的端到端验证。启动成功,默认输入法未修改,也未自动授予麦克风/无障碍权限。启动时出现的电池优化授权由设备主人决定。此包约 667 MiB,包含调试符号,不作为最终发行体积基线。 + +## 10. 首版之后的本地改造(尚未推送手机) + +- 新增 [通用动作键]()、[共享候选条]()、[笔画/数字符号面板]()、[编辑/剪贴板面板]()。 +- [笔画控制器]() 只保留组合、查询、学习、提交和组件装配,不再包含逐键布局与绘制代码;文字输入引擎和持久化格式未改。 +- 打字与笔画使用同一候选组件,复用相同标签的控件但始终更新回调;旧候选、关闭的展开项和阻断态不能误提交。 +- 编辑/剪贴板提供明确的收藏、词典、删除入口,不再使用旧的“滑动取消事件也可能提交删除”的行手势;粘贴成功后才更新最近历史。 +- 保留笔画分词、繁简、1–9 上滑数字、空格长按语音、数字/符号页的退格/回车/语音;翻页按最新数据派发字符,避免只更新标签却输入旧值。 +- 普通的分词/候选、编辑选择、历史分类切换局部渲染,不替换整个 IME 根视图;草稿开关纳入根布局标识,且只由实际重建确认新标识。 + +这一批组件的独立 Kotlin 编译和 38 项 JVM 回归已通过,19 项 Android 契约检查继续通过。另新增 25 项剩余面板仪器测试;本地 Robolectric 适配只改测试框架,不改断言、使用空 Application 隔离 JNI,也不操作手机。首次完整 View 测试当时仍在准备依赖;后续结果见第 11 节。手机仍保留首版归档包,不把这一批本地源码当成已安装版本。 + +## 11. 本地行为验证与旧实现清理 + +后续 Robolectric 运行保持 SDK 29、空 Application 隔离 JNI,测试体与 Android 仪器版本相同。首轮 53 项发现两处失败:按键在 UP 时过早清掉“曾越界”标记,导致移出又移回后误点击;以及测试错误地从候选条本身而非其独立展开层查找节点。修正生产代码与真实视图层级夹具后,最新 **54 项全部通过(25 剩余面板 + 19 打字面板 + 10 语音面板,0 skipped / 0 failure / 0 error)**,Android 主模块编译也通过。 + +- 原 Service 中未再使用的 `keyboardKey`、旧候选浮层、画布键帽、旧滑动容器等实现已删除;Node 检查改为新组件边界与测试装配守卫,不再对死代码片段声称“手势通过”。 +- 新增 [共享头部](),设置入口、后端指示动画与头部导航交互由 View 组件拥有;导航手势限定头部,不与字母键拖动竞争。 +- [语音 UI 投影]() 将阶段、模式、电平与可取消/可启动能力集中表达,且不回写业务 flags。SDK-free 模型回归累计 **64 项通过**(含投影、所有权匹配与帧策略/资格原型)。 +- 悬浮球仅镜像其他入口的录音帧,不因该帧自动提升麦克风前台服务或在提升失败时取消其他入口的录音;主动全局停止/取消行为保留。启动意图 guard 的 **6 项单元测试通过**,不把它宣称为强会话绑定。 + +**R2 发现的会话来源缺口**:Core 胶囊负载有 sessionId,但当时 Android 桥没有透传,仅有“自己发起了请求”的标记不足以判断每一帧来源。后续兼容接线和验证见第 12 节。Core 的重复 stop 在处理中会返回 Busy,不能通过重复发 stop 来补取别的入口已经结束的结果。未收到本入口结果时不得宣称已上屏或擅自补写。 + +以上为本地源码和模拟环境结果;本节改动尚未安装到手机,首版真机的 29 项结果不能冒充最新源码的端到端验证。 + +## 12. 会话元数据与原生接线验证 + +- Core 胶囊出口现把原有 `payload.session_id` 传到新增的 Android UI 回调;旧三参数回调保留。新增 descriptor 为 `(Ljava/lang/String;Ljava/lang/String;FLjava/lang/String;)V`,编译后 Java 静态方法与重编原生库均已核对。现有 IME start/stop/cancel 命令和 ASR 协议未改。 +- [会话帧门禁]() 按当前 request/epoch 与 started 确认的真实 sessionId 工作。早帧只做有界缓存并仅补投匹配 id,其他 id、无 id、已退休 id 不改自有录音状态或电平。结束、取消、旧 owner、新 owner 与重复 started 均有保护。 +- started 到达时若缓冲帧已进入整理或终态,不再补发排队的模式/stop 命令;停采集后仍保留本入口结果所有权,避免过早开放新录音而丢掉旧结果。 +- 新增桥接兼容测试与 [Service 实际接线测试](),后者只附隔离 Context、不运行 onCreate、不发 Native/ASR 命令、不接触编辑器,只调用实际帧处理路径。 + +验证:**97 项 SDK-free 测试、65 项本地 View/Service/桥接兼容测试、23 项 Android 架构/契约检查通过**。另完成完整 Android Rust + Kotlin APK 构建,未用旧 `.so` 跳过原生验证。编译/构建仍有既有弃用与 Rust 警告,不能称零警告。 + +本地新调试包经签名与 zip 内容核验,约 667 MiB。增量打包曾留下约一份旧原生库大小的无效空间,已将该未发布产物保存在 scratch,再重新生成紧凑包;未清除共享构建缓存,测试库也未混入主 APK。新归档 SHA-256 为 `c00ab27c3fa0e58aa5089bcfcec9045ef156b7800b895079b1f0dae58e00f80a`,手机仍保留最初的 `1530c30d` 体验包,未覆盖。 + +限制:JNI 元数据接线已编译和 ABI 检查,本地测试不等同于实际麦克风/ASR/润色/跨应用上屏端到端测试。其他入口结束 IME 发起的录音时,现有后端未必发送本入口的文字回调,UI 不自动猜测或补写结果;这不是修改 provider、存储或 Core stop 语义。后续布局与手机检查结果见第 13 节。 + +## 13. 第一版重写交付与手机验证(2026-11-28) + +本版采用稳定的 [输入视图根](),普通模式/主题/草稿刷新只替换展示内容,不重复 `setInputView`;[尺寸策略]() 使长草稿在独立区域滚动,受限空间先压缩抬升区再压键盘,不从每个 EXACT 测量结果反复扣减边距。实际 Service 的主题刷新、草稿重挂文本/选区保持和重复测量不缩小均有测试。 + +- [草稿栏]() 独立于业务:复用同一 EditText,Service 保留 DraftConnection、提交/替换/丢弃语义;提交中按钮禁用,旧聚焦请求不能抢新栏。 +- [连发策略]() 统一沿用旧偏好的 30–200ms 范围与 60ms 默认值。打字、语音 footer、笔画和编辑按键接入反馈 hook,DOWN/UP 不双重反馈,同值策略不取消触摸,策略变化取消旧 timer。 +- [设置预览]() 使用真实新版打字组件,不再是三行假键;预览屏蔽输入事件和虚假的可访问性动作,不请求语音或输入引擎。 +- [字段适配]() 为数字/电话/日期字段临时选数字页,不覆盖用户本地模式偏好;缓存页面也会刷新当前层。 +- [选区策略]() 使用绝对 UTF-16 偏移,处理 extracted text 的 startOffset,未知选区不猜 0;range 与退格按 codepoint 保护 surrogate pair。只承诺 codepoint,不宣称完整 ZWJ/grapheme 编辑。 +- 补齐父面板禁用的 clear/candidate 传播、稀疏符号页变满后的槽可用性,以及语音 footer 动作后重新校验再续排 timer。 + +**最终自动化证据**:123 项纯 JVM 测试、98 项本地 SDK 29 View/Service 测试、24 项 Android 架构/契约检查通过。主 APK、AndroidTest APK 构建通过;R3 已完整重编匹配的 Android Rust/JNI 库,后续仅 Kotlin 改动复用该库。仍有既有弃用/Rust 警告,不宣称零警告或性能基准达标。 + +经用户明确确认后,在华为 LYA-AL00 / Android 10 API 29 上执行 `adb install -r -t` 安装主包及测试包,均 Success,未卸载或清数据。安装前系统未列出此包,故不能把本次安装声称为已有用户词库的实测迁移;存储格式与相关存储实现未修改。手机上指定 10 个 UI/宿主测试类执行 **OK (98 tests)**,用时 4.145s,退出成功。没有运行会初始化真实 Rime/ASR 或改真实用户偏好的其他测试类。 + +已安装包 SHA-256:`ae865bfe82fe1528cac242c57f012c9adf94864303fa9e5a991d6c69644e2ce9`,大小 699,453,401 bytes(约 667 MiB,含调试符号),签名 v2 校验通过。原体验包及各阶段产物仍在机械盘 scratch;未清除构建缓存。 + +启动检查:应用进程存在,启动进入系统“忽略电池优化”请求,是否允许由设备主人决定,未代点。默认输入法仍是华为输入法,未自动启用 OpenLess、未授予麦克风或无障碍权限。实际日常输入、TalkBack 朗读、麦克风/ASR/润色及跨应用上屏仍需设备主人配置权限与服务后体验,不把上述 98 项 fake-callback/View 测试当成这些场景的端到端结果。 + +**搜狗样本范围**:本次再次尝试官网首页、手机版落地页与官方旧手机版入口,正常 TLS 获取官方页面并在 scratch 留下 URL/headers/hash,但未取得可信 APK 直链;未转向第三方镜像或绕过反爬。实际 APK 离线研究样本为微信与讯飞两份,不宣称已分析搜狗 APK。 diff --git a/openless-all/android/kotlin/ImeActionButton.kt b/openless-all/android/kotlin/ImeActionButton.kt new file mode 100644 index 000000000..cf053da05 --- /dev/null +++ b/openless-all/android/kotlin/ImeActionButton.kt @@ -0,0 +1,352 @@ +package com.openless.app + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.graphics.drawable.StateListDrawable +import android.os.Handler +import android.os.Looper +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.widget.TextView +import kotlin.math.abs + +/** + * 通用动作键(剪贴板 / 笔画 / 语音 footer 共用)。 + * + * 交互契约: + * - 轻点(UP 在当前边界内)→ [onAction] 恰好一次。 + * - 按住超过 [holdDelayMs] → 有 [onHold] 时触发一次;否则 [repeatOnHold] 时按固定间隔重复 + * [onAction]。hold / repeat 一旦触发,本次 UP 不再 [onAction](互斥)。 + * - 有 [onSwipeUp] 的键:明确的向上手势允许终点越出**上边界**(横向需在合理范围内), + * 中途即取消 hold timer,UP 时按当前终点解析:仍满足上滑 → 只触发 [onSwipeUp]; + * 终点不再满足 → 不操作(不会退化成点击)。 + * - 无 [onSwipeUp] 的普通功能键:一旦移出边界,UP 不操作。 + * - ACTION_CANCEL / 多指:只清理手势,绝不执行任何动作。 + * - 未附着窗口时不启动/不续排定时器;detach 时清理全部定时器与待处理输入事件。 + * - performClick / performLongClick 供无障碍使用,与触摸路径共享同一互斥语义; + * 若框架在触摸 tracking 中调用 performLongClick,会停掉 timer 并置 holdFired, + * 避免随后的 UP 再次点击。 + * + * 只做展示与手势分派:不读 Service/JNI/偏好,也不主动播放触觉或声音。 + */ +internal class ImeActionButton( + context: Context, + private val palette: ImePalette, + label: String, + description: String = label, + accent: Boolean = false, + private val onAction: () -> Unit, + private val onHold: (() -> Unit)? = null, + private val repeatOnHold: Boolean = false, + private val onSwipeUp: (() -> Unit)? = null, + private val holdDelayMs: Long = 500L, + private val onFeedback: () -> Unit = {}, + interactionPolicy: ImeInteractionPolicy = ImeInteractionPolicy.DEFAULT, +) : TextView(context) { + + private val handler = Handler(Looper.getMainLooper()) + private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop + + private var tracking = false + private var pointerId = -1 + private var downX = 0f + private var downY = 0f + private var movedOutside = false + private var swipeArmed = false + private var holdFired = false + private var repeating = false + private var policy = interactionPolicy + + private val holdRunnable = object : Runnable { + override fun run() { + if (!tracking || !isAttachedToWindow || !isShown || !isEnabled) return + if (repeatOnHold) { + repeating = true + holdFired = true + onAction() + onFeedback() + if (tracking && isAttachedToWindow && isShown && isEnabled) handler.postDelayed(this, policy.repeatIntervalMs) + } else { + val hold = onHold ?: return + holdFired = true + onFeedback() + hold() + } + } + } + + init { + text = label + textSize = 17f + gravity = Gravity.CENTER + includeFontPadding = false + maxLines = 1 + setTextColor(if (accent) WHITE else palette.text) + background = stateBackground(accent) + setPadding(dp(3), 0, dp(3), 0) + isClickable = true + isLongClickable = onHold != null || repeatOnHold + isFocusable = true + contentDescription = description + } + + private val customMainPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER } + private val customSubPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER } + + override fun onDraw(canvas: Canvas) { + val raw = text?.toString().orEmpty() + if ('\n' !in raw || width <= 0 || height <= 0) { + super.onDraw(canvas) + return + } + // Custom centered two-line rendering (e.g. "1\n一", "历史\n长按编辑") so + // RelativeSizeSpan line metrics never push the main glyph off-center. + background?.apply { + setBounds(0, 0, width, height) + draw(canvas) + } + val split = raw.indexOf('\n') + val first = raw.substring(0, split) + val second = raw.substring(split + 1) + val isDigitHint = first.length == 1 && first[0].isDigit() + val w = width.toFloat() + val h = height.toFloat() + val cx = w / 2f + + if (isDigitHint) { + customSubPaint.color = palette.secondaryText + customSubPaint.alpha = 190 + customSubPaint.textSize = minOf(dpf(10f), h * 0.22f).coerceAtLeast(dpf(8f)) + val sfm = customSubPaint.fontMetrics + canvas.drawText(first, cx, dpf(3f) - sfm.ascent, customSubPaint) + + customMainPaint.color = currentTextColor + customMainPaint.typeface = typeface ?: Typeface.DEFAULT + val baseSize = minOf(textSize, h * 0.42f).coerceAtLeast(dpf(11f)) + customMainPaint.textSize = fitWidth(customMainPaint, second, baseSize, w - dpf(6f)) + val fm = customMainPaint.fontMetrics + val cy = h * 0.58f + canvas.drawText(second, cx, cy - (fm.ascent + fm.descent) / 2f, customMainPaint) + } else { + val baseMain = minOf(textSize, h * 0.34f).coerceAtLeast(dpf(10f)) + customMainPaint.color = currentTextColor + customMainPaint.typeface = typeface ?: Typeface.DEFAULT + customMainPaint.textSize = fitWidth(customMainPaint, first, baseMain, w - dpf(6f)) + val mfm = customMainPaint.fontMetrics + + val baseSub = minOf(dpf(10f), h * 0.22f).coerceAtLeast(dpf(8f)) + customSubPaint.color = palette.secondaryText + customSubPaint.alpha = 220 + customSubPaint.textSize = fitWidth(customSubPaint, second, baseSub, w - dpf(6f)) + val sfm = customSubPaint.fontMetrics + + val gap = dpf(2f) + val totalH = (mfm.descent - mfm.ascent) + gap + (sfm.descent - sfm.ascent) + val top = (h - totalH) / 2f + canvas.drawText(first, cx, top - mfm.ascent, customMainPaint) + canvas.drawText(second, cx, top + (mfm.descent - mfm.ascent) + gap - sfm.ascent, customSubPaint) + } + } + + private fun fitWidth(paint: Paint, label: String, startSize: Float, maxWidth: Float): Float { + paint.textSize = startSize + val measured = paint.measureText(label) + if (measured <= maxWidth || measured <= 0f || maxWidth <= 0f) return startSize + return (startSize * (maxWidth / measured)).coerceAtLeast(dpf(8f)) + } + + private fun dpf(value: Float): Float = value * resources.displayMetrics.density + + private fun stateBackground(accent: Boolean): StateListDrawable { + val normal = GradientDrawable().apply { + cornerRadius = dp(6).toFloat() + setColor(if (accent) palette.accent else palette.key) + } + val pressed = GradientDrawable().apply { + cornerRadius = dp(6).toFloat() + setColor(if (accent) palette.accent else palette.pressed) + } + val disabled = GradientDrawable().apply { + cornerRadius = dp(6).toFloat() + setColor(palette.auxiliary) + } + return StateListDrawable().apply { + addState(intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled), pressed) + addState(intArrayOf(android.R.attr.state_enabled), normal) + addState(intArrayOf(), disabled) + } + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (event.pointerCount != 1) { + cancelInteraction() + return true + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + if (!isEnabled) { + cancelInteraction() + return true + } + cancelInteraction() + tracking = true + pointerId = event.getPointerId(0) + downX = event.x + downY = event.y + movedOutside = false + swipeArmed = false + holdFired = false + repeating = false + isPressed = true + onFeedback() + if (isAttachedToWindow) handler.postDelayed(holdRunnable, holdDelayMs) + return true + } + + MotionEvent.ACTION_MOVE -> { + if (!tracking || event.getPointerId(0) != pointerId) return true + val dx = event.x - downX + val dy = event.y - downY + if (inside(event.x, event.y)) { + if (!movedOutside && !swipeArmed) isPressed = true + return true + } + // 越界:有上滑能力且仍是明确向上手势时,允许越出上边界并取消 hold。 + if (onSwipeUp != null && qualifiesSwipe(dx, dy)) { + swipeArmed = true + isPressed = false + handler.removeCallbacks(holdRunnable) + } else { + movedOutside = true + isPressed = false + handler.removeCallbacks(holdRunnable) + } + return true + } + + MotionEvent.ACTION_UP -> { + if (!tracking || event.getPointerId(0) != pointerId) { + cancelInteraction() + return true + } + val dx = event.x - downX + val dy = event.y - downY + val wasHold = holdFired + val wasRepeat = repeating + val wasOutside = movedOutside + val wasSwipeArmed = swipeArmed + cancelInteraction() + if (!isEnabled) return true + if (wasHold || wasRepeat) return true + val swipe = onSwipeUp + if (!wasOutside && swipe != null && qualifiesSwipe(dx, dy)) { + swipe() + return true + } + if (wasOutside || wasSwipeArmed) return true + if (!inside(event.x, event.y)) return true + commitClick(withFeedback = false) + return true + } + + MotionEvent.ACTION_CANCEL -> { + cancelInteraction() + return true + } + } + return super.onTouchEvent(event) + } + + override fun performClick(): Boolean { + // 框架/无障碍可能在手指仍按下时调用 click:先结束当前手势,避免 UP 再提交一次。 + val wasTracking = tracking + if (wasTracking) cancelInteraction() + if (!isEnabled) return false + // 触摸路径的 DOWN 已反馈过;无障碍 click 没有 DOWN,这里补一次反馈。 + commitClick(withFeedback = !wasTracking) + return true + } + + override fun performLongClick(): Boolean { + if (!isEnabled) return false + val wasTracking = tracking + // 框架/无障碍可能在手指仍按下时调用长按:停 timer 并标记,避免 UP 再 click。 + if (wasTracking) handler.removeCallbacks(holdRunnable) + return commitHold(withFeedback = !wasTracking) + } + + /** 统一点击提交:触摸路径 DOWN 已反馈,故 withFeedback=false;无障碍路径补一次。 */ + private fun commitClick(withFeedback: Boolean) { + // 保留 TextView 自身的 click 语义(点击提示音等),再分发动作。 + super.performClick() + if (withFeedback) onFeedback() + onAction() + } + + /** 统一长按提交;触摸路径 DOWN 已反馈,故不重复,无障碍路径补一次。 */ + private fun commitHold(withFeedback: Boolean): Boolean { + val hold = onHold + if (hold != null) { + if (tracking) holdFired = true + if (withFeedback) onFeedback() + hold() + return true + } + if (repeatOnHold) { + if (tracking) holdFired = true + if (withFeedback) onFeedback() + onAction() + return true + } + return false + } + + /** 下发统一互动策略:值变化时先中止旧计时器/当前触摸;相同值不动进行中的交互。 */ + fun applyInteractionPolicy(policy: ImeInteractionPolicy) { + if (policy == this.policy) return + cancelInteraction() + this.policy = policy + } + + /** 取消当前手势与全部定时器(模式切换、父容器重建等场景调用)。 */ + fun cancelInteraction() { + handler.removeCallbacksAndMessages(null) + tracking = false + pointerId = -1 + movedOutside = false + swipeArmed = false + holdFired = false + repeating = false + isPressed = false + } + + override fun onDetachedFromWindow() { + cancelInteraction() + super.onDetachedFromWindow() + } + + private fun inside(x: Float, y: Float): Boolean = x >= 0f && y >= 0f && x < width && y < height + + /** + * 明确向上:纵向主导、超过阈值,且横向偏移仍在合理范围。 + * 允许终点越出上边界(y<0),但左右不能飘太远。 + */ + private fun qualifiesSwipe(dx: Float, dy: Float): Boolean { + val threshold = swipeThreshold() + val horizontalLimit = maxOf(width.toFloat(), dp(72).toFloat()) + return dy < -threshold && abs(dy) > abs(dx) && abs(dx) <= horizontalLimit + } + + private fun swipeThreshold(): Float = maxOf(touchSlop * 2f, dp(28).toFloat()) + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + private companion object { + const val WHITE = 0xFFFFFFFF.toInt() + } +} diff --git a/openless-all/android/kotlin/ImeCandidateStrip.kt b/openless-all/android/kotlin/ImeCandidateStrip.kt new file mode 100644 index 000000000..aede10b0c --- /dev/null +++ b/openless-all/android/kotlin/ImeCandidateStrip.kt @@ -0,0 +1,747 @@ +package com.openless.app + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.text.TextUtils +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.HorizontalScrollView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView + +/** + * 通用候选条:横向候选 + 快捷粘贴胶囊 + 网格化展开面板(支持全部/单字筛选)。 + * + * 契约: + * - 条本身高度由父布局给定(约 42dp),候选子 View 严格贴合父高度,绝不垂直溢出。 + * - 展开层通过 [expandedView] 暴露,由调用方叠加到 body(FrameLayout)里,不改变键盘总高度。 + * - [submit] 复用 label 与 forget 能力相同的原 View,并更新最新回调;被替换/移除的旧 View 不再生效。 + * - 展开按钮使用 Canvas 矢量箭头,不受各厂商字体基线偏差影响。 + * - 全程只做展示与回调,不读 Service/JNI/偏好。 + */ +internal class ImeCandidateStrip( + context: Context, + private val palette: ImePalette, + private val englishUi: Boolean, + private val onExpansionChanged: (Boolean) -> Unit = {}, +) : LinearLayout(context) { + + data class Item( + val label: String, + val select: () -> Unit, + val forget: (() -> Unit)? = null, + ) + + /** 展开层:真实 ScrollView + 筛选栏 + 4 列网格候选,调用方负责添加进 body。 */ + val expandedView: View + + private class Slot(val index: Int) { + var item: Item? = null + var view: TextView? = null + } + + private val scroll = HorizontalScrollView(context) + private val row = LinearLayout(context) + private val expand = ExpandChevronButton(context) + private val expandedContent = LinearLayout(context) + private val filterBar = LinearLayout(context) + private val filterAll = TextView(context) + private val filterSingle = TextView(context) + private val grid = CandidateGrid(context) + private val expandedScroll = ScrollView(context) + + private val rowSlots = mutableListOf() + private val expandedSlots = mutableListOf() + private var preeditView: TextView? = null + private var hintView: TextView? = null + private var chipContainer: LinearLayout? = null + + private var items: List = emptyList() + private var preedit: CharSequence? = null + private var emptyHintText: String? = null + private var quickChipLabel: String? = null + private var quickChipPaste: (() -> Unit)? = null + private var quickChipDismiss: (() -> Unit)? = null + private var singleCharOnly = false + private var isBlocked = false + private var interactionDisabled = false + private var isExpanded = false + private var hadItems = false + + init { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(6), 0, dp(2), 0) + minimumHeight = dp(40) + clipChildren = false + clipToPadding = false + + row.orientation = HORIZONTAL + row.gravity = Gravity.CENTER_VERTICAL + scroll.apply { + isHorizontalScrollBarEnabled = false + isFillViewport = true + overScrollMode = View.OVER_SCROLL_NEVER + addView(row, ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + addView(scroll, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + + expand.apply { + tag = "ime-cand-expand" + contentDescription = expandDescription(false) + isClickable = true + isFocusable = true + isEnabled = false + alpha = 0.35f + setOnClickListener { + if (!isBlocked && !interactionDisabled) setExpanded(!isExpanded) + } + } + addView(expand, LayoutParams(dp(44), LayoutParams.MATCH_PARENT)) + + styleFilterTab(filterAll, if (englishUi) "All" else "全部", selected = true) { + if (singleCharOnly) { + singleCharOnly = false + updateFilterTabs() + reconcileExpanded() + } + } + styleFilterTab(filterSingle, if (englishUi) "Single" else "单字", selected = false) { + if (!singleCharOnly) { + singleCharOnly = true + updateFilterTabs() + reconcileExpanded() + } + } + filterBar.apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(8), dp(4), dp(8), dp(4)) + addView(filterAll, LayoutParams(LayoutParams.WRAP_CONTENT, dp(30)).apply { marginEnd = dp(8) }) + addView(filterSingle, LayoutParams(LayoutParams.WRAP_CONTENT, dp(30))) + } + expandedContent.apply { + orientation = VERTICAL + addView(filterBar, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + addView(View(context).apply { setBackgroundColor(palette.separator) }, LayoutParams(LayoutParams.MATCH_PARENT, dp(1))) + addView(grid, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + } + + expandedScroll.apply { + visibility = GONE + isClickable = true + isFillViewport = true + setBackgroundColor(palette.surface) + addView(expandedContent, ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + } + expandedView = expandedScroll + } + + // --- 对外 API --- + + fun submit(items: List, preedit: CharSequence? = null, emptyHint: String? = null) { + this.items = items + this.preedit = preedit + if (emptyHint != null) emptyHintText = emptyHint + interactionDisabled = false + if (items.isEmpty()) singleCharOnly = false + + val wasEmpty = !hadItems + renderRow() + hadItems = items.isNotEmpty() + if (wasEmpty && items.isNotEmpty()) scroll.scrollTo(0, 0) + + if (isExpanded) { + if (items.isEmpty() || isBlocked) setExpanded(false) else { + updateFilterTabs() + reconcileExpanded() + } + } + applyInteractiveStates() + } + + fun setEmptyHint(text: String) { + emptyHintText = text + if (items.isEmpty() && preedit.isNullOrEmpty()) updateHint() + } + + fun setQuickChip(label: String?, onPaste: () -> Unit, onDismiss: () -> Unit) { + quickChipLabel = label?.takeIf { it.isNotBlank() } + quickChipPaste = if (quickChipLabel != null) onPaste else null + quickChipDismiss = if (quickChipLabel != null) onDismiss else null + if (items.isEmpty() && preedit.isNullOrEmpty()) updateHint() + } + + fun setBlocked(blocked: Boolean) { + if (isBlocked == blocked) return + isBlocked = blocked + if (blocked) { + setExpanded(false) + row.isPressed = false + expand.isPressed = false + cancelPendingInputEvents() + cancelPendingOn(row) + cancelPendingOn(grid) + } + applyInteractiveStates() + } + + fun closeExpanded() { + setExpanded(false) + } + + fun cancelInteractions() { + setExpanded(false) + interactionDisabled = true + row.isPressed = false + expand.isPressed = false + cancelPendingInputEvents() + cancelPendingOn(row) + cancelPendingOn(grid) + applyInteractiveStates() + } + + // --- 行渲染(槽位复用) --- + + private fun renderRow() { + updatePreedit() + reconcileRow() + updateHint() + } + + private fun updatePreedit() { + val text = preedit + val existing = preeditView + if (text.isNullOrEmpty()) { + if (existing != null) { + row.removeView(existing) + preeditView = null + } + return + } + if (existing != null) { + existing.text = text + existing.contentDescription = text.toString() + return + } + val view = preeditTextView(text) + preeditView = view + row.addView(view, 0, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + + private fun reconcileRow() { + while (rowSlots.size > items.size) { + val slot = rowSlots.removeAt(rowSlots.lastIndex) + slot.view?.let { row.removeView(it) } + slot.item = null + slot.view = null + } + items.forEachIndexed { index, item -> + val slot = rowSlots.getOrNull(index) + if (slot == null) { + val created = Slot(index) + created.item = item + created.view = createCandidateView(created, expanded = false) + row.addView(created.view, rowCandidateParams()) + rowSlots.add(created) + } else { + val reusable = slot.view != null && slot.item?.label == item.label && + (slot.item?.forget != null) == (item.forget != null) + if (reusable) { + slot.item = item + updateCandidateView(slot, expanded = false) + } else { + slot.view?.let { row.removeView(it) } + slot.item = item + slot.view = createCandidateView(slot, expanded = false) + row.addView(slot.view, rowCandidateParams()) + } + } + } + reorderRow() + } + + private fun rowCandidateParams(): LayoutParams = LayoutParams( + LayoutParams.WRAP_CONTENT, + LayoutParams.MATCH_PARENT, + ).apply { + topMargin = dp(4) + bottomMargin = dp(4) + marginEnd = dp(2) + } + + private fun reorderRow() { + var expected = if (preeditView != null) 1 else 0 + rowSlots.forEach { slot -> + val view = slot.view ?: return@forEach + if (row.indexOfChild(view) != expected) { + row.removeView(view) + row.addView(view, expected, rowCandidateParams()) + } + expected++ + } + } + + private fun updateHint() { + val show = items.isEmpty() && preedit.isNullOrEmpty() + if (!show) { + hintView?.let { row.removeView(it) } + hintView = null + chipContainer?.let { row.removeView(it) } + chipContainer = null + return + } + val chipLabel = quickChipLabel + if (chipLabel != null) { + hintView?.let { row.removeView(it) } + hintView = null + chipContainer?.let { row.removeView(it) } + val container = buildQuickChipView(chipLabel) + chipContainer = container + row.addView(container, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + return + } + chipContainer?.let { row.removeView(it) } + chipContainer = null + val text = emptyHintText ?: defaultHint() + val existing = hintView + if (existing == null) { + val view = hintTextView(text) + hintView = view + row.addView(view, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } else { + existing.text = text + } + } + + private fun buildQuickChipView(label: String): LinearLayout { + val pill = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(10), 0, dp(4), 0) + background = GradientDrawable().apply { + cornerRadius = dp(14).toFloat() + setColor(palette.auxiliary) + } + } + val pasteBtn = TextView(context).apply { + text = label + textSize = 13f + gravity = Gravity.CENTER_VERTICAL + includeFontPadding = false + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + maxWidth = dp(220) + setTextColor(palette.accent) + setTypeface(Typeface.DEFAULT, Typeface.BOLD) + tag = "ime-cand-quick-chip" + contentDescription = label + isClickable = true + isFocusable = true + setOnClickListener { + if (!isBlocked && !interactionDisabled) quickChipPaste?.invoke() + } + } + val closeBtn = TextView(context).apply { + text = "✕" + textSize = 11f + gravity = Gravity.CENTER + includeFontPadding = false + setTextColor(palette.secondaryText) + setPadding(dp(8), 0, dp(6), 0) + contentDescription = if (englishUi) "Dismiss suggestion" else "关闭快捷粘贴" + isClickable = true + isFocusable = true + setOnClickListener { + if (!isBlocked && !interactionDisabled) quickChipDismiss?.invoke() + } + } + pill.addView(pasteBtn, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + pill.addView(closeBtn, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + return LinearLayout(context).apply { + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(4), dp(5), dp(4), dp(5)) + addView(pill, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + } + + private fun updateCandidateView(slot: Slot, expanded: Boolean) { + val view = slot.view ?: return + val item = slot.item ?: return + view.text = item.label + view.tag = if (expanded) "ime-cand-expanded-${slot.index}" else "ime-cand-${slot.index}" + view.contentDescription = item.label + val isPrimary = slot.index == 0 && !expanded + view.setTextColor(if (isPrimary) palette.accent else palette.text) + view.setTypeface(Typeface.DEFAULT, if (isPrimary) Typeface.BOLD else Typeface.NORMAL) + view.background = if (isPrimary) { + GradientDrawable().apply { + cornerRadius = dp(8).toFloat() + setColor(Color.argb(30, Color.red(palette.accent), Color.green(palette.accent), Color.blue(palette.accent))) + } + } else null + applyCandidateInteractive(view, slot, expanded) + } + + private fun createCandidateView(slot: Slot, expanded: Boolean): TextView { + val view = TextView(context).apply { + textSize = if (expanded) 17f else 18f + gravity = Gravity.CENTER + includeFontPadding = false + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + setPadding(dp(12), 0, dp(12), 0) + minWidth = dp(42) + isClickable = true + isFocusable = true + } + view.setOnClickListener { + if (!isSlotActive(slot, view, expanded)) return@setOnClickListener + slot.item?.select() + } + view.setOnLongClickListener { + if (!isSlotActive(slot, view, expanded)) return@setOnLongClickListener true + val forget = slot.item?.forget + if (forget != null) { + forget() + true + } else { + false + } + } + updateCandidateView(slot.apply { this.view = view }, expanded) + return view + } + + // --- 展开层 --- + + private fun filteredExpandedItems(): List> { + val indexed = items.mapIndexed { index, item -> index to item } + if (!singleCharOnly) return indexed + val singles = indexed.filter { (_, item) -> item.label.codePointCount(0, item.label.length) == 1 } + return singles.ifEmpty { indexed } + } + + private fun reconcileExpanded() { + val visible = filteredExpandedItems() + val hasSingleChars = items.any { it.label.codePointCount(0, it.label.length) == 1 } + val hasMultiChars = items.any { it.label.codePointCount(0, it.label.length) > 1 } + filterBar.visibility = if (hasSingleChars && hasMultiChars) VISIBLE else GONE + + while (expandedSlots.size > visible.size) { + val slot = expandedSlots.removeAt(expandedSlots.lastIndex) + slot.view?.let { grid.removeView(it) } + slot.item = null + slot.view = null + } + visible.forEachIndexed { pos, (originalIndex, item) -> + val slot = expandedSlots.getOrNull(pos) + if (slot == null) { + val created = Slot(originalIndex) + created.item = item + created.view = createCandidateView(created, expanded = true) + grid.addView(created.view) + expandedSlots.add(created) + } else { + val reusable = slot.index == originalIndex && slot.view != null && slot.item?.label == item.label && + (slot.item?.forget != null) == (item.forget != null) + if (reusable) { + slot.item = item + updateCandidateView(slot, expanded = true) + } else { + slot.view?.let { grid.removeView(it) } + val replacement = Slot(originalIndex) + replacement.item = item + replacement.view = createCandidateView(replacement, expanded = true) + expandedSlots[pos] = replacement + grid.addView(replacement.view) + } + } + } + reorderGrid() + applyInteractiveStates() + } + + private fun reorderGrid() { + expandedSlots.forEachIndexed { pos, slot -> + val view = slot.view ?: return@forEachIndexed + if (grid.indexOfChild(view) != pos) { + grid.removeView(view) + grid.addView(view, pos) + } + } + } + + private fun styleFilterTab(tab: TextView, label: String, selected: Boolean, onClick: () -> Unit) { + tab.apply { + text = label + textSize = 12f + gravity = Gravity.CENTER + includeFontPadding = false + setPadding(dp(12), 0, dp(12), 0) + isClickable = true + isFocusable = true + setOnClickListener { onClick() } + } + applyFilterTabVisual(tab, selected) + } + + private fun updateFilterTabs() { + applyFilterTabVisual(filterAll, !singleCharOnly) + applyFilterTabVisual(filterSingle, singleCharOnly) + } + + private fun applyFilterTabVisual(tab: TextView, selected: Boolean) { + tab.setTextColor(if (selected) Color.WHITE else palette.secondaryText) + tab.setTypeface(Typeface.DEFAULT, if (selected) Typeface.BOLD else Typeface.NORMAL) + tab.background = GradientDrawable().apply { + cornerRadius = dp(14).toFloat() + setColor(if (selected) palette.accent else palette.auxiliary) + } + } + + // --- 状态 --- + + private fun applyInteractiveStates() { + val enabled = !isBlocked && !interactionDisabled + expand.isEnabled = items.isNotEmpty() && enabled + expand.alpha = if (expand.isEnabled) 1f else 0.35f + expand.importantForAccessibility = if (enabled) { + IMPORTANT_FOR_ACCESSIBILITY_YES + } else { + IMPORTANT_FOR_ACCESSIBILITY_NO + } + rowSlots.forEach { slot -> slot.view?.let { applyCandidateInteractive(it, slot, false) } } + expandedSlots.forEach { slot -> slot.view?.let { applyCandidateInteractive(it, slot, true) } } + } + + private fun applyCandidateInteractive(view: TextView, slot: Slot, expanded: Boolean) { + val enabled = !isBlocked && !interactionDisabled + view.isEnabled = enabled + view.isClickable = enabled + view.isLongClickable = enabled && slot.item?.forget != null + view.alpha = if (enabled) 1f else 0.4f + view.importantForAccessibility = if (enabled) { + IMPORTANT_FOR_ACCESSIBILITY_YES + } else { + IMPORTANT_FOR_ACCESSIBILITY_NO + } + if (!enabled) view.isPressed = false + if (expanded) view.tag = "ime-cand-expanded-${slot.index}" + } + + private fun isSlotActive(slot: Slot, view: View, expanded: Boolean): Boolean { + if (isBlocked || interactionDisabled) return false + if (slot.view !== view) return false + if (expanded) { + if (!isExpanded || expandedScroll.visibility != View.VISIBLE) return false + if (view.parent !== grid) return false + } else if (view.parent !== row) { + return false + } + val current = slot.item ?: return false + return items.getOrNull(slot.index) === current + } + + private fun setExpanded(show: Boolean) { + val wanted = show && !isBlocked && !interactionDisabled && items.isNotEmpty() + if (wanted == isExpanded) return + isExpanded = wanted + expandedScroll.visibility = if (wanted) View.VISIBLE else View.GONE + expand.expanded = wanted + expand.contentDescription = expandDescription(wanted) + if (wanted) { + updateFilterTabs() + reconcileExpanded() + expandedScroll.scrollTo(0, 0) + } else { + cancelPendingOn(grid) + } + applyInteractiveStates() + onExpansionChanged(wanted) + } + + // --- 小工具 --- + + private fun preeditTextView(value: CharSequence): TextView = TextView(context).apply { + text = value + textSize = 14f + gravity = Gravity.CENTER_VERTICAL + includeFontPadding = false + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + maxWidth = dp(160) + setTextColor(palette.accent) + setPadding(dp(8), 0, dp(8), 0) + tag = "ime-cand-preedit" + contentDescription = value.toString() + } + + private fun hintTextView(value: String): TextView = TextView(context).apply { + text = value + textSize = 13f + gravity = Gravity.CENTER_VERTICAL + includeFontPadding = false + maxLines = 1 + setTextColor(palette.secondaryText) + setPadding(dp(10), 0, dp(10), 0) + tag = "ime-cand-hint" + } + + private fun defaultHint(): String = if (englishUi) "Hold space to speak" else "按住空格说话" + + private fun expandDescription(expanded: Boolean): String = when { + englishUi && expanded -> "Collapse candidates" + englishUi -> "Expand candidates" + expanded -> "收起候选" + else -> "展开候选" + } + + private fun cancelPendingOn(group: ViewGroup) { + for (index in 0 until group.childCount) { + val child = group.getChildAt(index) + child.isPressed = false + child.cancelPendingInputEvents() + if (child is ViewGroup) cancelPendingOn(child) + } + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + private fun dpf(value: Float): Float = value * resources.displayMetrics.density + + /** Canvas-drawn expand/collapse chevron so alignment never depends on OEM Unicode glyphs. */ + private inner class ExpandChevronButton(context: Context) : View(context) { + var expanded: Boolean = false + set(value) { + if (field != value) { + field = value + invalidate() + } + } + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = palette.secondaryText + style = Paint.Style.STROKE + strokeCap = Paint.Cap.ROUND + strokeJoin = Paint.Join.ROUND + } + private val chevron = Path() + + override fun onDraw(canvas: Canvas) { + val cx = width / 2f + val cy = height / 2f + val halfW = dpf(6f) + val halfH = dpf(3.2f) + paint.strokeWidth = dpf(2f) + paint.color = if (isEnabled) palette.secondaryText else palette.separator + chevron.reset() + if (expanded) { + chevron.moveTo(cx - halfW, cy + halfH) + chevron.lineTo(cx, cy - halfH) + chevron.lineTo(cx + halfW, cy + halfH) + } else { + chevron.moveTo(cx - halfW, cy - halfH) + chevron.lineTo(cx, cy + halfH) + chevron.lineTo(cx + halfW, cy - halfH) + } + canvas.drawPath(chevron, paint) + } + } + + /** 展开层的 4 列整齐网格布局:长词自动跨 2/4 列,带柔和分隔线。 */ + private inner class CandidateGrid(context: Context) : ViewGroup(context) { + private val columns = 4 + private val dividerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = palette.separator + strokeWidth = dpf(0.6f) + } + private val cellSpans = ArrayList() + private var rowCount = 0 + + init { + setWillNotDraw(false) + } + + private fun rowHeightPx(): Int = dp(46) + + private fun spanFor(child: View, colWidth: Int): Int { + child.measure( + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), + MeasureSpec.makeMeasureSpec(rowHeightPx(), MeasureSpec.EXACTLY), + ) + val desired = child.measuredWidth + return when { + desired <= colWidth -> 1 + desired <= colWidth * 2 -> 2 + else -> columns + } + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val available = MeasureSpec.getSize(widthMeasureSpec).coerceAtLeast(columns) + val colWidth = available / columns + val rowH = rowHeightPx() + cellSpans.clear() + var col = 0 + var rows = if (childCount == 0) 0 else 1 + for (index in 0 until childCount) { + val child = getChildAt(index) + val span = spanFor(child, colWidth).coerceAtMost(columns) + if (col + span > columns) { + rows++ + col = 0 + } + cellSpans.add(span) + child.measure( + MeasureSpec.makeMeasureSpec(colWidth * span, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(rowH, MeasureSpec.EXACTLY), + ) + col += span + } + rowCount = rows + setMeasuredDimension(available, resolveSize(rows * rowH, heightMeasureSpec)) + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + val colWidth = width / columns + val rowH = rowHeightPx() + var col = 0 + var rowIdx = 0 + for (index in 0 until childCount) { + val child = getChildAt(index) + val span = cellSpans.getOrElse(index) { 1 } + if (col + span > columns) { + rowIdx++ + col = 0 + } + val x = col * colWidth + val y = rowIdx * rowH + val w = if (col + span == columns) width - x else colWidth * span + child.layout(x, y, x + w, y + rowH) + col += span + } + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val rowH = rowHeightPx().toFloat() + for (r in 1..rowCount) { + val y = r * rowH + canvas.drawLine(0f, y, width.toFloat(), y, dividerPaint) + } + for (index in 0 until childCount) { + val child = getChildAt(index) + if (child.right < width - dp(2)) { + val x = child.right.toFloat() + canvas.drawLine(x, child.top + dpf(10f), x, child.bottom - dpf(10f), dividerPaint) + } + } + } + } +} diff --git a/openless-all/android/kotlin/ImeClipboardPanel.kt b/openless-all/android/kotlin/ImeClipboardPanel.kt new file mode 100644 index 000000000..5e4dc7631 --- /dev/null +++ b/openless-all/android/kotlin/ImeClipboardPanel.kt @@ -0,0 +1,263 @@ +package com.openless.app + +import android.content.Context +import android.graphics.drawable.GradientDrawable +import android.text.TextUtils +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView + +/** Local editing and clipboard presentation. Storage and editor access belong to the adapter. */ +internal class ImeClipboardPanel( + context: Context, + private val palette: ImePalette, + header: View, + private val englishUi: Boolean, + private val onCommand: (String) -> Unit, + private val onCategory: (String) -> Unit, + private val onFeedback: () -> Unit = {}, + interactionPolicy: ImeInteractionPolicy = ImeInteractionPolicy.DEFAULT, +) : LinearLayout(context) { + data class Item( + val text: String, + val favorite: Boolean, + val inDictionary: Boolean, + val select: () -> Unit, + val toggleFavorite: () -> Unit, + val remove: () -> Unit, + val toggleDictionary: () -> Unit, + ) + + private val content = FrameLayout(context) + private val editing = LinearLayout(context) + private val history = LinearLayout(context) + private val recentRows = LinearLayout(context) + private val historyRows = LinearLayout(context) + private val filters = LinearLayout(context) + private val historyScroll = ScrollView(context) + private val selectionKeys = ArrayList() + private var generation = 0L + private var blocked = false + private var targetToken: Long? = null + private var policy = interactionPolicy + + init { + orientation = VERTICAL + setBackgroundColor(palette.surface) + addView(header, LayoutParams(LayoutParams.MATCH_PARENT, dp(40))) + editing.orientation = VERTICAL + val grid = LinearLayout(context).apply { orientation = VERTICAL } + val commands = listOf( + listOf("range", "left", "right", "up", "down"), + listOf("all", "copy", "paste", "history", "backspace"), + ) + commands.forEach { rowCommands -> + val row = LinearLayout(context) + rowCommands.forEach { command -> + val key = ImeActionButton( + context, palette, commandLabel(command), commandDescription(command), + onAction = { if (!blocked) onCommand(command) }, + onHold = if (command == "history") ({ if (!blocked) onCommand("edit") }) else null, + repeatOnHold = command == "backspace" || command in listOf("left", "right", "up", "down"), + onFeedback = onFeedback, + interactionPolicy = policy, + ).apply { + tag = "ime-edit-$command" + textSize = if (command == "history") 13f else 17f + maxLines = 2 + if (command in listOf("range", "left", "right", "up", "down")) selectionKeys += this + } + row.addView(key, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { setMargins(dp(3), dp(3), dp(3), dp(3)) }) + } + grid.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + editing.addView(grid, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + recentRows.orientation = VERTICAL + editing.addView(recentRows, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + content.addView(editing, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + + history.orientation = VERTICAL + filters.gravity = Gravity.CENTER_VERTICAL + val filterScroll = HorizontalScrollView(context).apply { + isHorizontalScrollBarEnabled = false + addView(filters, ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + val toolbar = LinearLayout(context) + toolbar.addView(filterScroll, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + toolbar.addView(button(ui("清空", "Clear"), "ime-history-clear") { onCommand("clear_history") }, LayoutParams(dp(56), LayoutParams.MATCH_PARENT)) + toolbar.addView(button("✕", "ime-history-close") { onCommand("close_history") }.apply { + contentDescription = ui("关闭剪贴板历史", "Close clipboard history") + }, LayoutParams(dp(44), LayoutParams.MATCH_PARENT)) + history.addView(toolbar, LayoutParams(LayoutParams.MATCH_PARENT, dp(42))) + historyRows.orientation = VERTICAL + historyScroll.apply { + isFillViewport = true + addView(historyRows, ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + } + history.addView(historyScroll, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + content.addView(history, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + + fun render( + editorToken: Long, + historyVisible: Boolean, + selection: Boolean, + category: String, + entries: List, + recent: List, + ) { + if (targetToken != editorToken) cancelInteractions() + targetToken = editorToken + val token = ++generation + editing.visibility = if (historyVisible) GONE else VISIBLE + history.visibility = if (historyVisible) VISIBLE else GONE + selectionKeys.forEach { key -> + key.isSelected = selection + key.setTextColor(if (selection) palette.accent else palette.text) + } + recentRows.removeAllViews() + for (index in 0 until 3) { + val item = recent.getOrNull(index) + val row = if (item == null) TextView(context).apply { + text = if (index == 0) ui("暂无剪贴板记录", "No clipboard history") else "" + gravity = Gravity.CENTER_VERTICAL + setTextColor(palette.secondaryText) + textSize = 13f + setPadding(dp(12), 0, dp(12), 0) + } else button("${index + 1} ${item.text.take(1000)}", "ime-clip-recent-$index") { + if (token == generation) item.select() + }.apply { + gravity = Gravity.CENTER_VERTICAL + textSize = 15f + setSingleLine(true) + ellipsize = TextUtils.TruncateAt.END + } + recentRows.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + if (!historyVisible) { setBlocked(blocked); return } + filters.removeAllViews() + listOf("ALL" to ui("全部", "All"), "RECENT" to ui("最近", "Recent"), "TEXT" to ui("文本", "Text"), + "NUMBER" to ui("数字", "Number"), "LINK" to ui("链接", "Link")).forEach { (id, label) -> + filters.addView(button(label, "ime-clip-filter-$id") { if (token == generation) onCategory(id) }.apply { + isSelected = id == category + setTextColor(if (isSelected) palette.accent else palette.secondaryText) + minWidth = dp(52) + setPadding(dp(10), 0, dp(10), 0) + }, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + val oldScroll = historyScroll.scrollY + historyRows.removeAllViews() + if (entries.isEmpty()) historyRows.addView(TextView(context).apply { + text = ui("暂无剪贴板记录", "No clipboard history") + gravity = Gravity.CENTER + setTextColor(palette.secondaryText) + setPadding(0, dp(20), 0, 0) + }) + entries.forEachIndexed { index, item -> + val card = LinearLayout(context).apply { + orientation = VERTICAL + background = GradientDrawable().apply { cornerRadius = dp(8).toFloat(); setColor(palette.key) } + } + card.addView(button(item.text.take(2000), "ime-clip-item-$index") { + if (token == generation) item.select() + }.apply { + maxLines = 2 + ellipsize = TextUtils.TruncateAt.END + textSize = 15f + gravity = Gravity.START or Gravity.CENTER_VERTICAL + }, LayoutParams(LayoutParams.MATCH_PARENT, dp(48))) + val actions = LinearLayout(context) + listOf( + Triple(if (item.favorite) ui("★ 已收藏", "★ Saved") else ui("☆ 收藏", "☆ Save"), "favorite", item.toggleFavorite), + Triple(if (item.inDictionary) ui("移出词典", "Remove word") else ui("加入词典", "Add word"), "dictionary", item.toggleDictionary), + Triple(ui("删除", "Delete"), "delete", item.remove), + ).forEach { (label, actionId, action) -> + actions.addView(button(label, "ime-clip-$actionId-$index") { if (token == generation) action() }.apply { + textSize = 12f + if (actionId == "delete") setTextColor(palette.error) + }, LayoutParams(0, dp(38), 1f)) + } + card.addView(actions) + historyRows.addView(card, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { + setMargins(dp(6), dp(3), dp(6), dp(3)) + }) + } + historyScroll.post { if (token == generation) historyScroll.scrollTo(0, oldScroll) } + setBlocked(blocked) + } + + /** 下发统一互动策略:值变化时先中止旧触摸/计时器,再更新已存在与后续新建的全部按键。 */ + fun applyInteractionPolicy(policy: ImeInteractionPolicy) { + if (policy == this.policy) return + cancelInteractions() + this.policy = policy + walk(content) { view -> + if (view is ImeActionButton) view.applyInteractionPolicy(policy) + } + } + + fun setBlocked(value: Boolean) { + blocked = value + if (value) walk(content) { if (it is ImeActionButton) it.cancelInteraction() } + walk(content) { view -> + if (view is ImeActionButton) { + view.isEnabled = !value + view.alpha = if (value) 0.45f else 1f + } + } + } + + fun cancelInteractions() { + ++generation + walk(content) { if (it is ImeActionButton) it.cancelInteraction() } + } + + override fun onDetachedFromWindow() { + cancelInteractions() + super.onDetachedFromWindow() + } + + private fun button(label: String, id: String, action: () -> Unit) = ImeActionButton( + context, palette, label, onAction = { if (!blocked) action() }, + onFeedback = onFeedback, + interactionPolicy = policy, + ).apply { + tag = id + textSize = 13f + setPadding(dp(10), 0, dp(10), 0) + } + + private fun walk(view: View, action: (View) -> Unit) { + action(view) + if (view is ViewGroup) for (index in 0 until view.childCount) walk(view.getChildAt(index), action) + } + + private fun commandLabel(id: String): String = when (id) { + "range" -> ui("选择", "Range") + "left" -> "←" + "right" -> "→" + "up" -> "↑" + "down" -> "↓" + "all" -> ui("全选", "All") + "copy" -> ui("复制", "Copy") + "paste" -> ui("粘贴", "Paste") + "history" -> ui("历史\n长按编辑", "History\nHold to edit") + else -> "⌫" + } + private fun commandDescription(id: String): String = when (id) { + "left" -> ui("光标左移", "Move cursor left") + "right" -> ui("光标右移", "Move cursor right") + "up" -> ui("光标上移", "Move cursor up") + "down" -> ui("光标下移", "Move cursor down") + "backspace" -> ui("退格", "Backspace") + else -> commandLabel(id).replace('\n', ' ') + } + private fun ui(zh: String, en: String) = if (englishUi) en else zh + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() +} diff --git a/openless-all/android/kotlin/ImeDraftBar.kt b/openless-all/android/kotlin/ImeDraftBar.kt new file mode 100644 index 000000000..8b1eaf19d --- /dev/null +++ b/openless-all/android/kotlin/ImeDraftBar.kt @@ -0,0 +1,231 @@ +package com.openless.app + +import android.content.Context +import android.graphics.drawable.GradientDrawable +import android.text.TextUtils +import android.view.Gravity +import android.view.ViewGroup +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.TextView + +/** + * 草稿编辑栏(纯展示/交互外壳)。 + * + * 内容、选区与提交逻辑全部归宿主(Service/DraftConnection):本栏**不创建** editText、 + * **不 setText**、不改选区、不读写偏好、不碰 JNI/InputConnection/网络。 + * [editor] 由宿主传入并在重挂(模式/主题重建)时原样换父节点,因此文本与选区自然保留。 + * + * 交互约束: + * - confirm/cancel 为普通 [TextView] + 原生 `setOnClickListener`,不依赖共享 ActionButton + * 正在演进的 interaction-policy 参数; + * - `submitting=true` 时两个按钮真正 `isEnabled=false`,并取消挂起触摸,点击不会回调; + * - 每次有效点击先回调 [onFeedback] 一次(触感由宿主决定),再回调业务; + * - 编辑框只拿 View focus(`requestFocus`),绝不请求窗口焦点、不调用 showSoftInput; + * 聚焦 post 会校验"editor 仍属于本栏且已附着窗口",旧栏 detach 后不能抢新栏焦点; + * - 控件统一走 [ImePalette],错误态用 `palette.error` 且写入可读 contentDescription。 + * + * 尺寸:整体 wrap_content,尊重父布局的 AT_MOST 约束;过高的草稿由宿主外层 ScrollView + * 限高,本栏不主动占屏。 + */ +internal class ImeDraftBar( + context: Context, + private val palette: ImePalette, + private val editor: EditText, + private val onCancel: () -> Unit, + private val onConfirm: () -> Unit, + private val onFeedback: () -> Unit = {}, +) : LinearLayout(context) { + + val status: TextView = TextView(context) + val cancel: TextView = TextView(context) + val confirm: TextView = TextView(context) + + private var submitting = false + private var focusToken = 0 + private var pendingFocus: Runnable? = null + + init { + orientation = VERTICAL + setPadding(dp(16), dp(10), dp(16), dp(8)) + setBackgroundColor(palette.surface) + // Swallow stray touches in the bar so they cannot reach the app underneath. + isClickable = true + + // Re-attach the host-owned editor without creating a second instance; its + // text/selection belong to the host and are never touched here. + (editor.parent as? ViewGroup)?.removeView(editor) + styleEditor(editor) + addView( + editor, + LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT), + ) + + stylePill(cancel, fill = palette.auxiliary, textColor = palette.text) + // Fixed default labels; the host may relabel through the public `cancel`/`confirm` + // fields when it rebuilds for its own locale, without the bar reading preferences. + cancel.text = "取消" + cancel.contentDescription = "取消草稿" + + status.apply { + textSize = 13f + gravity = Gravity.CENTER + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + setTextColor(palette.secondaryText) + } + + stylePill(confirm, fill = palette.accent, textColor = palette.surface) + confirm.text = "确认" + confirm.contentDescription = "确认草稿" + + cancel.setOnClickListener { onCancelClicked() } + confirm.setOnClickListener { onConfirmClicked() } + + val row = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL } + row.addView(cancel, LayoutParams(dp(84), dp(36))) + row.addView( + status, + LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f).apply { + marginStart = dp(8) + marginEnd = dp(8) + }, + ) + row.addView(confirm, LayoutParams(dp(84), dp(36))) + addView( + row, + LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { + topMargin = dp(8) + }, + ) + } + + /** + * 更新状态文案与按钮可用性;不触碰 editor 内容/选区。 + * + * @param message 状态文案(宿主提供;本栏只显示,不记录) + * @param isError 错误态:用 `palette.error` 着色并写入可读 contentDescription + * @param submitting 提交中:两个按钮真正禁用,且取消挂起触摸 + * @param confirmAccent 确认按钮填色(宿主按云笔记/普通听写选择) + */ + fun render( + message: String, + isError: Boolean, + submitting: Boolean, + confirmAccent: Int = palette.accent, + ) { + this.submitting = submitting + status.text = message + status.setTextColor(if (isError) palette.error else palette.secondaryText) + status.contentDescription = message.takeIf { isError && it.isNotBlank() } + status.importantForAccessibility = if (isError && message.isNotBlank()) { + IMPORTANT_FOR_ACCESSIBILITY_YES + } else { + IMPORTANT_FOR_ACCESSIBILITY_AUTO + } + stylePill(confirm, fill = confirmAccent, textColor = palette.surface) + setControlsEnabled(!submitting) + } + + /** + * 取消挂起交互:作废未执行的聚焦 post、移除回调、清 pressed 与未决输入事件。 + * 不触碰 editor 内容/选区。 + */ + fun cancelInteractions() { + invalidatePendingFocus() + cancel.isPressed = false + confirm.isPressed = false + cancel.cancelPendingInputEvents() + confirm.cancelPendingInputEvents() + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + postEditorFocus() + } + + override fun onDetachedFromWindow() { + // Must run before the platform tears the view hierarchy down: an old bar that + // is detached can never re-focus the editor after it has been re-attached + // elsewhere. + invalidatePendingFocus() + super.onDetachedFromWindow() + } + + private fun onCancelClicked() { + if (submitting || !cancel.isEnabled) return + onFeedback() + onCancel() + } + + private fun onConfirmClicked() { + if (submitting || !confirm.isEnabled) return + onFeedback() + onConfirm() + } + + private fun postEditorFocus() { + invalidatePendingFocus() + val token = focusToken + val runnable = Runnable { + // Only the newest bar that still owns this editor may take View focus. + if (token != focusToken) return@Runnable + if (!isAttachedToWindow) return@Runnable + if (editor.parent !== this) return@Runnable + editor.requestFocus() + } + pendingFocus = runnable + editor.post(runnable) + } + + private fun invalidatePendingFocus() { + focusToken++ + pendingFocus?.let { runnable -> + editor.removeCallbacks(runnable) + pendingFocus = null + } + } + + private fun setControlsEnabled(enabled: Boolean) { + cancel.isEnabled = enabled + confirm.isEnabled = enabled + cancel.alpha = if (enabled) 1f else 0.45f + confirm.alpha = if (enabled) 1f else 0.45f + if (!enabled) { + // Stop any touch that was already tracking one of the buttons so a + // pending UP cannot deliver a click while submitting. + cancel.isPressed = false + confirm.isPressed = false + cancel.cancelPendingInputEvents() + confirm.cancelPendingInputEvents() + } + } + + private fun styleEditor(edit: EditText) { + edit.setTextColor(palette.text) + edit.background = GradientDrawable().apply { + shape = GradientDrawable.RECTANGLE + cornerRadius = dp(10).toFloat() + setColor(palette.key) + setStroke(dp(1), palette.separator) + } + edit.setPadding(dp(12), dp(8), dp(12), dp(8)) + } + + private fun stylePill(view: TextView, fill: Int, textColor: Int) { + view.apply { + textSize = 15f + gravity = Gravity.CENTER + setTextColor(textColor) + setTypeface(typeface, android.graphics.Typeface.BOLD) + background = GradientDrawable().apply { + shape = GradientDrawable.RECTANGLE + cornerRadius = dp(18).toFloat() + setColor(fill) + } + isClickable = true + } + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() +} diff --git a/openless-all/android/kotlin/ImeEditorFieldPolicy.kt b/openless-all/android/kotlin/ImeEditorFieldPolicy.kt new file mode 100644 index 000000000..7ad8f100f --- /dev/null +++ b/openless-all/android/kotlin/ImeEditorFieldPolicy.kt @@ -0,0 +1,9 @@ +package com.openless.app + +/** Android InputType class bits; flags/variations do not turn numeric fields into voice pages. */ +internal object ImeEditorFieldPolicy { + fun prefersNumeric(inputType: Int): Boolean = when (inputType and 0x0000000f) { + 0x2, 0x3, 0x4 -> true // TYPE_CLASS_NUMBER / PHONE / DATETIME + else -> false + } +} diff --git a/openless-all/android/kotlin/ImeGestureSession.kt b/openless-all/android/kotlin/ImeGestureSession.kt new file mode 100644 index 000000000..61669ae79 --- /dev/null +++ b/openless-all/android/kotlin/ImeGestureSession.kt @@ -0,0 +1,103 @@ +package com.openless.app + +import kotlin.math.abs + +/** + * One pointer sequence, one owner, at most one committed action. + * + * Android adapters own event delivery and hit testing; this class deliberately + * has no View/Service dependency so cancellation and axis arbitration can be + * replayed in JVM tests. A cancelled or multi-pointer sequence must call + * [cancel], never [release]. Child scroll regions can disable either axis at + * [begin], before an ancestor gets its first interception opportunity. + */ +internal class ImeGestureSession( + private val touchSlop: Float, + private val axisDominance: Float = 1.5f, +) { + enum class Axis { NONE, HORIZONTAL, VERTICAL } + enum class Direction { LEFT, RIGHT, UP, DOWN } + + var axis: Axis = Axis.NONE + private set + private var active = false + private var startX = 0f + private var startY = 0f + private var horizontalAllowed = false + private var upAllowed = false + private var downAllowed = false + + init { + require(touchSlop.isFinite() && touchSlop >= 0f) + require(axisDominance.isFinite() && axisDominance >= 1f) + } + + fun begin( + x: Float, + y: Float, + horizontal: Boolean = false, + up: Boolean = false, + down: Boolean = false, + ) { + cancel() + if (!x.isFinite() || !y.isFinite()) return + active = true + startX = x + startY = y + horizontalAllowed = horizontal + upAllowed = up + downAllowed = down + } + + /** Once an axis wins, crossing a diagonal cannot transfer ownership. */ + fun move(x: Float, y: Float, allowDown: Boolean = true): Axis { + if (!active) return Axis.NONE + if (!x.isFinite() || !y.isFinite()) { + cancel() + return Axis.NONE + } + if (axis != Axis.NONE) return axis + val dx = x - startX + val dy = y - startY + axis = when { + horizontalAllowed && abs(dx) > touchSlop && abs(dx) > abs(dy) * axisDominance -> Axis.HORIZONTAL + ((dy < 0f && upAllowed) || (dy > 0f && downAllowed && allowDown)) && + abs(dy) > touchSlop && abs(dy) > abs(dx) * axisDominance -> Axis.VERTICAL + else -> Axis.NONE + } + return axis + } + + /** Only a completed UP event may commit; release also ends ownership. */ + fun release( + x: Float, + y: Float, + horizontalThreshold: Float, + verticalThreshold: Float, + ): Direction? { + val result = if (!active || !x.isFinite() || !y.isFinite() || + !horizontalThreshold.isFinite() || horizontalThreshold < 0f || + !verticalThreshold.isFinite() || verticalThreshold < 0f + ) null else { + val dx = x - startX + val dy = y - startY + when { + axis == Axis.HORIZONTAL && abs(dx) > horizontalThreshold -> + if (dx < 0f) Direction.LEFT else Direction.RIGHT + axis == Axis.VERTICAL && dy < -verticalThreshold && upAllowed -> Direction.UP + axis == Axis.VERTICAL && dy > verticalThreshold && downAllowed -> Direction.DOWN + else -> null + } + } + cancel() + return result + } + + fun cancel() { + active = false + axis = Axis.NONE + horizontalAllowed = false + upAllowed = false + downAllowed = false + } +} diff --git a/openless-all/android/kotlin/ImeInteractionPolicy.kt b/openless-all/android/kotlin/ImeInteractionPolicy.kt new file mode 100644 index 000000000..3612b7fff --- /dev/null +++ b/openless-all/android/kotlin/ImeInteractionPolicy.kt @@ -0,0 +1,26 @@ +package com.openless.app + +/** + * 统一互动策略(按键连发节奏)。 + * + * 只承载"多久连发一次"这一展示/交互参数,不读偏好、不做 I/O、不依赖 Android; + * 存储侧(settings/adapter)负责把用户偏好值转换成策略,再通过各 View 的 + * `applyInteractionPolicy()` 下发。 + */ +@ConsistentCopyVisibility +internal data class ImeInteractionPolicy private constructor( + val repeatIntervalMs: Long, +) { + companion object { + private const val MIN_REPEAT_MS = 30L + private const val MAX_REPEAT_MS = 200L + private const val DEFAULT_REPEAT_MS = 60L + + /** 默认连发间隔(60ms),与旧硬编码 65/66ms 的体感保持一致。 */ + val DEFAULT = ImeInteractionPolicy(DEFAULT_REPEAT_MS) + + /** 把持久化值收敛到受支持区间 [30, 200]ms;越界按边界值处理。 */ + fun fromStoredRepeat(value: Long): ImeInteractionPolicy = + ImeInteractionPolicy(value.coerceIn(MIN_REPEAT_MS, MAX_REPEAT_MS)) + } +} diff --git a/openless-all/android/kotlin/ImeKeyboardHeader.kt b/openless-all/android/kotlin/ImeKeyboardHeader.kt new file mode 100644 index 000000000..7b6c58e7e --- /dev/null +++ b/openless-all/android/kotlin/ImeKeyboardHeader.kt @@ -0,0 +1,179 @@ +package com.openless.app + +import android.animation.ObjectAnimator +import android.animation.ValueAnimator +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Color +import android.graphics.PorterDuff +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView + +/** Shared chrome. Navigation gestures are confined to the header, never letter keys. */ +internal class ImeKeyboardHeader( + context: Context, + private val palette: ImePalette, + modeBar: View, + bitmap: Bitmap?, + onSettings: () -> Unit, + onKeyboardSettings: () -> Unit, + private val onModeStep: (Int) -> Unit, + private val onHide: () -> Unit, +) : LinearLayout(context) { + val indicator: View + private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat() + private val gesture = ImeGestureSession(touchSlop) + private var dispatchGeneration = 0L + private var pulse: ObjectAnimator? = null + private var ready = true + + init { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(10), dp(1), dp(6), dp(1)) + val brand = LinearLayout(context).apply { + gravity = Gravity.CENTER_VERTICAL + isFocusable = true + contentDescription = "OpenLess 设置 / OpenLess settings" + setOnClickListener { onSettings() } + setOnLongClickListener { onKeyboardSettings(); true } + } + if (bitmap != null) { + val height = dp(19) + brand.addView(ImageView(context).apply { + setImageBitmap(bitmap) + setColorFilter(palette.text, PorterDuff.Mode.SRC_IN) + scaleType = ImageView.ScaleType.FIT_CENTER + }, LayoutParams((height.toFloat() * bitmap.width / bitmap.height.coerceAtLeast(1)).toInt(), height)) + } else { + brand.addView(TextView(context).apply { + text = "OpenLess" + textSize = 16f + setTypeface(Typeface.DEFAULT, Typeface.BOLD) + setTextColor(palette.text) + }) + } + indicator = View(context).apply { + importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO + background = GradientDrawable().apply { shape = GradientDrawable.OVAL } + } + brand.addView(indicator, LayoutParams(dp(9), dp(9)).apply { marginStart = dp(5) }) + addView(brand, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT).apply { marginEnd = dp(8) }) + addView(modeBar, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + } + + fun renderLink(color: Int, healthy: Boolean) { + ready = healthy + (indicator.background as GradientDrawable).apply { + setColor(color) + // The local/raw white status dot needs contrast on the light canvas. + setStroke(if (Color.luminance(color) > 0.75 && Color.luminance(palette.surface) > 0.5) dp(1) else 0, palette.separator) + } + pulse?.duration = if (ready) 1800L else 900L + ensurePulse() + } + + private fun ensurePulse() { + if (!isAttachedToWindow || !isShown || !ValueAnimator.areAnimatorsEnabled()) { + pulse?.cancel() + pulse = null + indicator.alpha = 1f + return + } + if (pulse?.isRunning == true) return + pulse = ObjectAnimator.ofFloat(indicator, View.ALPHA, 1f, 0.4f).apply { + duration = if (ready) 1800L else 900L + repeatMode = ValueAnimator.REVERSE + repeatCount = ValueAnimator.INFINITE + start() + } + } + + override fun onInterceptTouchEvent(event: MotionEvent): Boolean { + if (event.pointerCount != 1 || event.actionMasked == MotionEvent.ACTION_CANCEL) { + cancelInteractions() + return false + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + ++dispatchGeneration + gesture.begin(event.x, event.y, horizontal = true, down = true) + } + MotionEvent.ACTION_MOVE -> if (gesture.move(event.x, event.y) != ImeGestureSession.Axis.NONE) { + parent?.requestDisallowInterceptTouchEvent(true) + } + } + return gesture.axis != ImeGestureSession.Axis.NONE + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (event.pointerCount != 1 || event.actionMasked == MotionEvent.ACTION_CANCEL) { + cancelInteractions() + return true + } + when (event.actionMasked) { + MotionEvent.ACTION_MOVE -> gesture.move(event.x, event.y) + MotionEvent.ACTION_UP -> { + val direction = gesture.release(event.x, event.y, maxOf(width / 3f, touchSlop), dp(100).toFloat()) + val generation = dispatchGeneration + // Finish Android dispatch before changing panels; a hidden, detached + // or target-invalidated header cannot run a queued navigation action. + post { + if (generation == dispatchGeneration && isAttachedToWindow && isShown) { + when (direction) { + ImeGestureSession.Direction.LEFT -> onModeStep(1) + ImeGestureSession.Direction.RIGHT -> onModeStep(-1) + ImeGestureSession.Direction.DOWN -> onHide() + else -> Unit + } + } + } + } + } + return true + } + + fun cancelInteractions() { + ++dispatchGeneration + gesture.cancel() + pulse?.cancel() + pulse = null + indicator.alpha = 1f + fun cancel(view: View) { + view.isPressed = false + view.cancelPendingInputEvents() + view.cancelLongPress() + if (view is ViewGroup) for (index in 0 until view.childCount) cancel(view.getChildAt(index)) + } + cancel(this) + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + ensurePulse() + } + + override fun onWindowVisibilityChanged(visibility: Int) { + super.onWindowVisibilityChanged(visibility) + // Android may call this during the View constructor; animation state is nullable. + if (visibility != VISIBLE) { pulse?.cancel(); pulse = null } + else if (isAttachedToWindow) ensurePulse() + } + + override fun onDetachedFromWindow() { + cancelInteractions() + pulse?.cancel() + pulse = null + super.onDetachedFromWindow() + } + + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() +} diff --git a/openless-all/android/kotlin/ImeKeyboardModels.kt b/openless-all/android/kotlin/ImeKeyboardModels.kt new file mode 100644 index 000000000..a86e5d246 --- /dev/null +++ b/openless-all/android/kotlin/ImeKeyboardModels.kt @@ -0,0 +1,299 @@ +package com.openless.app + +// 纯 Kotlin 键盘布局与主题模型:不依赖 Android,不持有 Service/View 引用, +// 仅供 IME 展示层消费,可在 JVM 单测中直接断言。 +// +// 约定(未经真机验证,接线时需按实际交互确认): +// - `rows()` 只返回真实按键;字母第二行两侧各 0.5 键宽的留白由 View 侧加 inset, +// 模型不生成虚假 spacer key。 +// - 层切换动作按"相对当前层"解释,由状态机保证结果唯一: +// ToggleNumbers: LETTERS→NUMBERS、NUMBERS/SYMBOLS→LETTERS(底行 ABC) +// ToggleSymbols: NUMBERS→SYMBOLS、SYMBOLS→NUMBERS(仅数字/符号层) +// 底行键在 LETTERS 显示 "123",其余层显示 "ABC";第三行切换键在 NUMBERS +// 显示 "#+="、在 SYMBOLS 显示 "123"(与现有键盘一致)。 +// - 语言键为显式按钮,标签表示**当前**输入语言(拼音 "中" / 英文 "EN"), +// 点击切换;不再依赖空格长按。 +// - `auxiliary` 标记功能键(Shift/Backspace/层切换/语言),供 View 选择辅助色。 +// - 字母键 `action.value` 已按 `letterCase` 应用大小写;`label` 与之一致。 + +internal enum class ImeKeyboardLayer { LETTERS, NUMBERS, SYMBOLS } + +internal enum class ImeLetterCase { LOWER, SHIFT, CAPS_LOCK } + +internal enum class ImeTypingLanguage { ENGLISH, PINYIN } + +internal sealed class ImeKeyAction { + data class Text(val value: String) : ImeKeyAction() + data object Shift : ImeKeyAction() + data object Backspace : ImeKeyAction() + data object Space : ImeKeyAction() + data object Language : ImeKeyAction() + data object ToggleNumbers : ImeKeyAction() + data object ToggleSymbols : ImeKeyAction() + data object Enter : ImeKeyAction() +} + +internal data class ImeKeySpec( + val id: String, + val label: String, + val action: ImeKeyAction, + val weight: Float = 1f, + val secondary: String? = null, + val auxiliary: Boolean = false, +) + +internal object ImeKeyboardLayouts { + private const val SHIFT_WEIGHT = 1.5f + private const val BACKSPACE_WEIGHT = 1.5f + private const val ROW_TOGGLE_WEIGHT = 1.5f + private const val BOTTOM_MODE_WEIGHT = 1.3f + private const val LANGUAGE_WEIGHT = 1.1f + private const val BOTTOM_PUNCT_WEIGHT = 0.9f + private const val SPACE_WEIGHT = 3.5f + private const val SPACE_WIDE_WEIGHT = 4.6f + private const val ENTER_WEIGHT = 1.8f + + private val LETTER_ROW_1 = listOf("q", "w", "e", "r", "t", "y", "u", "i", "o", "p") + private val LETTER_ROW_1_SECONDARY = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0") + private val LETTER_ROW_2 = listOf("a", "s", "d", "f", "g", "h", "j", "k", "l") + private val LETTER_ROW_2_SECONDARY = listOf("~", "@", "#", "!", "%", "&", "*", "(", ")") + private val LETTER_ROW_3 = listOf("z", "x", "c", "v", "b", "n", "m") + private val LETTER_ROW_3_SECONDARY = listOf("'", "/", "-", "_", ":", ";", "?") + + // 数字/符号层沿用现有键盘排布。 + private val NUMBER_ROW_1 = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0") + private val NUMBER_ROW_2 = listOf("-", "/", ":", ";", "(", ")", "$", "&", "@", "\"") + private val NUMBER_ROW_3 = listOf(".", ",", "?", "!", "'") + private val SYMBOL_ROW_1 = listOf("[", "]", "{", "}", "#", "%", "^", "*", "+", "=") + private val SYMBOL_ROW_2 = listOf("_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•") + private val SYMBOL_ROW_3 = listOf(".", ",", "?", "!", "'") + + fun rows( + layer: ImeKeyboardLayer, + language: ImeTypingLanguage, + letterCase: ImeLetterCase, + enterLabel: String, + ): List> { + val content = when (layer) { + ImeKeyboardLayer.LETTERS -> lettersRows(letterCase) + ImeKeyboardLayer.NUMBERS -> numbersRows() + ImeKeyboardLayer.SYMBOLS -> symbolsRows() + } + return content + listOf(bottomRow(layer, language, enterLabel)) + } + + private fun lettersRows(letterCase: ImeLetterCase): List> { + val upper = letterCase != ImeLetterCase.LOWER + val row1 = LETTER_ROW_1.mapIndexed { index, key -> + letterKey("letters_r1_c${index + 1}", key, upper, LETTER_ROW_1_SECONDARY[index]) + } + val row2 = LETTER_ROW_2.mapIndexed { index, key -> + letterKey("letters_r2_c${index + 1}", key, upper, LETTER_ROW_2_SECONDARY[index]) + } + val row3 = buildList { + add( + ImeKeySpec( + id = "shift", + label = if (letterCase == ImeLetterCase.CAPS_LOCK) "⇪" else "⇧", + action = ImeKeyAction.Shift, + weight = SHIFT_WEIGHT, + auxiliary = true, + ), + ) + LETTER_ROW_3.forEachIndexed { index, key -> + add(letterKey("letters_r3_c${index + 1}", key, upper, LETTER_ROW_3_SECONDARY[index])) + } + add(backspaceKey()) + } + return listOf(row1, row2, row3) + } + + private fun numbersRows(): List> { + val row1 = NUMBER_ROW_1.mapIndexed { index, value -> + ImeKeySpec(id = "numbers_r1_c${index + 1}", label = value, action = ImeKeyAction.Text(value)) + } + val row2 = NUMBER_ROW_2.mapIndexed { index, value -> + ImeKeySpec(id = "numbers_r2_c${index + 1}", label = value, action = ImeKeyAction.Text(value)) + } + val row3 = buildList { + add( + ImeKeySpec( + id = "mode_symbols", + label = "#+=", + action = ImeKeyAction.ToggleSymbols, + weight = ROW_TOGGLE_WEIGHT, + auxiliary = true, + ), + ) + addAll(numberActionKeys()) + add(backspaceKey()) + } + return listOf(row1, row2, row3) + } + + private fun symbolsRows(): List> { + val row1 = SYMBOL_ROW_1.mapIndexed { index, value -> + ImeKeySpec(id = "symbols_r1_c${index + 1}", label = value, action = ImeKeyAction.Text(value)) + } + val row2 = SYMBOL_ROW_2.mapIndexed { index, value -> + ImeKeySpec(id = "symbols_r2_c${index + 1}", label = value, action = ImeKeyAction.Text(value)) + } + val row3 = buildList { + add( + ImeKeySpec( + id = "mode_numbers_row3", + label = "123", + action = ImeKeyAction.ToggleSymbols, + weight = ROW_TOGGLE_WEIGHT, + auxiliary = true, + ), + ) + addAll(numberActionKeys()) + add(backspaceKey()) + } + return listOf(row1, row2, row3) + } + + /** 数字/符号层第三行的 `. , ? ! '`,两层共用同一排布。 */ + private fun numberActionKeys(): List = NUMBER_ROW_3.mapIndexed { index, value -> + ImeKeySpec( + id = "punct_r3_c${index + 1}", + label = value, + action = ImeKeyAction.Text(value), + ) + } + + private fun bottomRow( + layer: ImeKeyboardLayer, + language: ImeTypingLanguage, + enterLabel: String, + ): List = buildList { + add( + ImeKeySpec( + id = "mode_numbers", + // 底行在 LETTERS 显示 123;数字/符号层显示 ABC 以回到字母层。 + label = if (layer == ImeKeyboardLayer.LETTERS) "123" else "ABC", + action = ImeKeyAction.ToggleNumbers, + weight = BOTTOM_MODE_WEIGHT, + auxiliary = true, + ), + ) + add( + ImeKeySpec( + id = "language", + // 标签表示当前输入语言;点击切换(显式按钮,不依赖空格长按)。 + label = if (language == ImeTypingLanguage.PINYIN) "中" else "EN", + action = ImeKeyAction.Language, + weight = LANGUAGE_WEIGHT, + auxiliary = true, + ), + ) + if (layer == ImeKeyboardLayer.LETTERS) { + val comma = if (language == ImeTypingLanguage.PINYIN) "," else "," + add( + ImeKeySpec( + id = "bottom_comma", + label = comma, + action = ImeKeyAction.Text(comma), + weight = BOTTOM_PUNCT_WEIGHT, + auxiliary = true, + ), + ) + } + add( + ImeKeySpec( + id = "space", + label = "Space", + action = ImeKeyAction.Space, + weight = if (layer == ImeKeyboardLayer.LETTERS) SPACE_WEIGHT else SPACE_WIDE_WEIGHT, + ), + ) + if (layer == ImeKeyboardLayer.LETTERS) { + val period = if (language == ImeTypingLanguage.PINYIN) "。" else "." + add( + ImeKeySpec( + id = "bottom_period", + label = period, + action = ImeKeyAction.Text(period), + weight = BOTTOM_PUNCT_WEIGHT, + auxiliary = true, + ), + ) + } + add( + ImeKeySpec( + id = "enter", + label = enterLabel, + action = ImeKeyAction.Enter, + weight = ENTER_WEIGHT, + ), + ) + } + + private fun letterKey( + id: String, + key: String, + upper: Boolean, + secondary: String?, + ): ImeKeySpec { + val value = if (upper) key.uppercase() else key + return ImeKeySpec( + id = id, + label = value, + action = ImeKeyAction.Text(value), + secondary = secondary, + ) + } + + private fun backspaceKey(): ImeKeySpec = ImeKeySpec( + id = "backspace", + label = "⌫", + action = ImeKeyAction.Backspace, + weight = BACKSPACE_WEIGHT, + auxiliary = true, + ) +} + +/** + * 键盘语义色(ARGB)。参照 iOS 键盘的语义分层,accent 为蓝色强调而非整片红色; + * error 仅用于错误态。所有值不透明。 + */ +internal data class ImePalette( + val surface: Int, + val key: Int, + val auxiliary: Int, + val accent: Int, + val text: Int, + val secondaryText: Int, + val separator: Int, + val pressed: Int, + val error: Int, +) { + companion object { + fun resolve(dark: Boolean): ImePalette = if (dark) { + ImePalette( + surface = 0xFF1C1C1EL.toInt(), + key = 0xFF41454CL.toInt(), + auxiliary = 0xFF2F333BL.toInt(), + accent = 0xFF709EFFL.toInt(), + text = 0xFFFFFFFFL.toInt(), + secondaryText = 0xFF9FA5AEL.toInt(), + separator = 0xFF3A3A3CL.toInt(), + pressed = 0xFF5A6069L.toInt(), + error = 0xFFFF453AL.toInt(), + ) + } else { + ImePalette( + surface = 0xFFD5D8DEL.toInt(), + key = 0xFFFFFFFFL.toInt(), + auxiliary = 0xFFD1D9E3L.toInt(), + accent = 0xFF2B5EEDL.toInt(), + text = 0xFF000000L.toInt(), + secondaryText = 0xFF6B7280L.toInt(), + separator = 0xFFB9BEC7L.toInt(), + pressed = 0xFFE5E7EBL.toInt(), + error = 0xFFD70015L.toInt(), + ) + } + } +} diff --git a/openless-all/android/kotlin/ImeKeyboardPreview.kt b/openless-all/android/kotlin/ImeKeyboardPreview.kt new file mode 100644 index 000000000..d2f068688 --- /dev/null +++ b/openless-all/android/kotlin/ImeKeyboardPreview.kt @@ -0,0 +1,49 @@ +package com.openless.app + +import android.content.Context +import android.view.Gravity +import android.view.MotionEvent +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.TextView + +/** The actual typing component in a non-interactive, backend-free settings preview. */ +internal class ImeKeyboardPreview(context: Context, palette: ImePalette, englishUi: Boolean) : FrameLayout(context) { + init { + tag = "ime-keyboard-preview" + // The surrounding size caption is accessible. Do not expose fake keys/actions. + importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + val header = LinearLayout(context).apply { + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(10), 0, dp(6), 0) + addView(TextView(context).apply { + text = "OpenLess" + textSize = 16f + setTextColor(palette.text) + }, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT).apply { marginEnd = dp(10) }) + addView(ImeModeBar( + context, palette, + if (englishUi) listOf("Voice", "Stroke", "Edit", "Keys") else listOf("语音", "笔画", "编辑", "键盘"), + 3, + ) {}, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)) + } + val panel = ImeTypingPanel( + context, palette, header, + onAction = {}, onFeedback = {}, onVoiceStart = { false }, onVoiceEnd = {}, + interfaceEnglish = englishUi, + ) + panel.renderKeyboard( + ImeKeyboardLayer.LETTERS, + if (englishUi) ImeTypingLanguage.ENGLISH else ImeTypingLanguage.PINYIN, + ImeLetterCase.LOWER, if (englishUi) "Return" else "换行", englishUi, + ) + val words = if (englishUi) listOf("Hello", "keyboard", "preview") else listOf("你好", "输入法", "预览") + panel.submitCandidates(words.map { ImeTypingPanel.Candidate(it, select = {}) }, if (englishUi) null else "nihao") + addView(panel, LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + } + + override fun onInterceptTouchEvent(event: MotionEvent): Boolean = true + override fun onTouchEvent(event: MotionEvent): Boolean = true + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() +} diff --git a/openless-all/android/kotlin/ImeModeBar.kt b/openless-all/android/kotlin/ImeModeBar.kt new file mode 100644 index 000000000..7e0b4d09c --- /dev/null +++ b/openless-all/android/kotlin/ImeModeBar.kt @@ -0,0 +1,60 @@ +package com.openless.app + +import android.content.Context +import android.graphics.Color +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.view.Gravity +import android.view.View +import android.view.accessibility.AccessibilityNodeInfo +import android.widget.LinearLayout +import android.widget.TextView + +/** Each mode is a real accessible control, rather than one canvas hit region. */ +internal class ImeModeBar( + context: Context, + palette: ImePalette, + labels: List, + selectedIndex: Int, + onSelect: (Int) -> Unit, +) : LinearLayout(context) { + init { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + val density = resources.displayMetrics.density + val inset = (3 * density).toInt() + setPadding(inset, inset, inset, inset) + background = GradientDrawable().apply { + cornerRadius = 18 * density + setColor(palette.auxiliary) + } + labels.forEachIndexed { index, label -> + val selected = index == selectedIndex + addView(TextView(context).apply { + text = label + textSize = 12f + gravity = Gravity.CENTER + includeFontPadding = false + setSingleLine(true) + setTextColor(if (selected) palette.text else palette.secondaryText) + setTypeface(Typeface.DEFAULT, if (selected) Typeface.BOLD else Typeface.NORMAL) + background = GradientDrawable().apply { + cornerRadius = 15 * density + setColor(if (selected) palette.key else Color.TRANSPARENT) + } + isSelected = selected + isFocusable = true + contentDescription = label + tag = "ime-mode-$index" + accessibilityDelegate = object : View.AccessibilityDelegate() { + override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) { + super.onInitializeAccessibilityNodeInfo(host, info) + info.className = "android.widget.Button" + info.isSelected = selected + } + } + setOnClickListener { if (!selected) onSelect(index) } + }, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + } + } +} diff --git a/openless-all/android/kotlin/ImeScopedFrameGate.kt b/openless-all/android/kotlin/ImeScopedFrameGate.kt new file mode 100644 index 000000000..a9b26703d --- /dev/null +++ b/openless-all/android/kotlin/ImeScopedFrameGate.kt @@ -0,0 +1,194 @@ +package com.openless.app + +/** + * 胶囊状态帧(由桥/Service 原样传入)。`sessionId` 可为 null 或空/空白, + * 表示"该帧未携带真实会话标识";非空 id 一律按 **opaque 原样**使用(不 trim、不改写、不 casefold)。 + */ +internal data class ImeCapsuleFrame( + val sessionId: String?, + val state: String, + val message: String?, + val level: Float, +) + +/** 一帧的归属判定结果。 */ +internal enum class ImeFrameDisposition { + /** 与当前 owner 已绑定 id 精确一致:只有这种帧可以改自己的业务 flags/RMS。 */ + OWNED, + + /** 无 owner:帧来自外部(其他入口/悬浮球/热键),不得授权本入口动作。 */ + EXTERNAL, + + /** 有 owner 但尚未 bind:按 id 保留最新帧(有界),等 started 后 bind 再 flush。 */ + BUFFERED, + + /** 有 owner 且已绑定另一个 id:别的会话的帧,不得影响本入口。 */ + FOREIGN, + + /** 有 owner 但帧不带 id:无法归属,不得据此改 flags/RMS。 */ + UNIDENTIFIED, + + /** 该 id 已退休(本入口结束/取消过,或外部已知结束):迟到帧,丢弃。 */ + STALE, +} + +/** + * IME 会话帧门禁:把"胶囊全局广播帧"收敛为"只属于本入口当前请求"的帧。 + * + * 生命周期(由 Service 适配层驱动): + * 1. 发 start 前 [begin]:绑定当前 `epoch/requestId`,但**此时还不知道真实 sessionId**; + * 2. started 前到达的真实帧按 id 有界缓存(只保留每个 id 的最新帧),不会授权任何动作; + * 3. 收到 ack/started 后调用 [bind]:只接受同 owner、非空、非退休的 id; + * 首次 bind 返回该 id 在缓存里的最后一帧(随后清空全部缓存),供适配层补投; + * 4. 之后的帧按 [accept] 判定,只有 [ImeFrameDisposition.OWNED] 才允许驱动本入口状态; + * 5. 结束/取消时 [finish]:只对匹配 owner 生效,并退休已知绑定 id,拦住晚到帧; + * 6. 外部已知结束/取消的 id 可用 [retire] 提前退休。 + * + * 保护性约定: + * - 无 owner 的帧一律 [ImeFrameDisposition.EXTERNAL];空白 id 视为"无 id"; + * - [retire] 对**当前 active 绑定 id** 直接 no-op(误调用不误伤活跃会话): + * 活跃会话只由 [finish] 结束;[begin] 也会在切换时退休上一位 owner 的旧绑定 id; + * - [finish] 传入 null 不做任何事(避免无主清理误伤新 owner);过期 owner 的 + * [bind]/[finish] 都不能影响新 owner; + * - 有界:缓存按"最久未更新"逐出,退休表按插入顺序逐出;上限至少为 1; + * - 纯内存结构,不做日志/I/O。 + */ +internal class ImeScopedFrameGate( + bufferLimit: Int = 4, + retiredLimit: Int = 8, +) { + private val bufferLimit: Int = bufferLimit.coerceAtLeast(1) + private val retiredLimit: Int = retiredLimit.coerceAtLeast(1) + + private val buffer = LinkedHashMap() + private val retired = LinkedHashSet() + + private var owner: ImeRequestOwner? = null + private var boundSessionId: String? = null + + /** 当前缓存的不同 id 帧数(每个 id 只保留最新一帧)。 */ + val bufferedCount: Int get() = buffer.size + + /** 当前退休 id 数(有界)。 */ + val retiredCount: Int get() = retired.size + + /** 开始一次新请求:清理旧 owner/缓存,并退休旧绑定 id 防旧帧夺权。 */ + fun begin(owner: ImeRequestOwner) { + retireInternal(boundSessionId) + boundSessionId = null + buffer.clear() + this.owner = owner + } + + /** + * 收到真实 sessionId 后绑定当前 owner。 + * + * 只接受:同 owner、非空、非退休 id,且不得从已绑定 id 改绑到另一个 id。 + * 重复 bind 同一 owner/id 是幂等的(保留绑定,不会丢目标)。 + * + * @return 缓存中该 id 的最后一帧(若有),调用后完整清空缓存;拒绝时返回 null 且不改状态。 + */ + fun bind(owner: ImeRequestOwner, sessionId: String): ImeCapsuleFrame? { + val current = this.owner ?: return null + if (current != owner) return null + if (!isKnownId(sessionId)) return null + if (isRetired(sessionId)) return null + val existing = boundSessionId + if (existing != null && existing != sessionId) return null + boundSessionId = sessionId + val frame = buffer[sessionId] + buffer.clear() + return frame + } + + /** + * 只读确认:当前是否已把 [owner] 精确绑定到该非空、未退休 id。 + * + * 用于区分 [bind] 返回 null 的两种情况:**拒绝绑定**(false)与**绑定成功但缓存无帧**(true)。 + * Service 可只在 `bind` 后 `isBound` 为 true 时才接收 started/进入录音态,不必伪造帧探测。 + */ + fun isBound(owner: ImeRequestOwner, sessionId: String): Boolean { + if (owner != this.owner) return false + if (!isKnownId(sessionId)) return false + if (isRetired(sessionId)) return false + return boundSessionId == sessionId + } + + /** 判定一帧归属;只有 [ImeFrameDisposition.OWNED] 才允许改本入口业务状态。 */ + fun accept(frame: ImeCapsuleFrame): ImeFrameDisposition { + val sessionId = frame.sessionId + if (isKnownId(sessionId) && isRetired(sessionId!!)) return ImeFrameDisposition.STALE + + val current = owner ?: return ImeFrameDisposition.EXTERNAL + if (!isKnownId(sessionId)) return ImeFrameDisposition.UNIDENTIFIED + + val id = sessionId!! + val bound = boundSessionId + return when { + bound == null -> { + bufferFrame(id, frame) + ImeFrameDisposition.BUFFERED + } + bound == id -> ImeFrameDisposition.OWNED + else -> ImeFrameDisposition.FOREIGN + } + } + + /** + * 结束会话:仅当 [owner] 与当前 owner 完全一致时生效;退休已知绑定 id 并清缓存。 + * 传入 null 或过期 owner 都是无操作(过期 owner 不能结束新 owner)。 + */ + fun finish(owner: ImeRequestOwner?) { + if (owner == null) return + if (owner != this.owner) return + retireInternal(boundSessionId) + boundSessionId = null + buffer.clear() + this.owner = null + } + + /** + * 外部已知结束/取消的 id:提前退休以拦截晚到帧,并移除其缓存帧。 + * + * 若传入的正是**当前 active 绑定 id**,直接 no-op:误调用不得把活跃会话的帧 + * 变成 STALE(等价屏蔽活跃 UI)。结束活跃会话只能走 [finish](内部退休旧绑定); + * 切换会话由 [begin] 负责退休上一位 owner 的绑定 id。 + * 空白 id 忽略;不做 trim/casefold。 + */ + fun retire(sessionId: String) { + if (!isKnownId(sessionId)) return + if (sessionId == boundSessionId) return + retireInternal(sessionId) + buffer.remove(sessionId) + } + + private fun bufferFrame(id: String, frame: ImeCapsuleFrame) { + // 更新视为"最近使用":先移除再插入,逐出最旧。 + buffer.remove(id) + buffer[id] = frame + while (buffer.size > bufferLimit) { + val iterator = buffer.keys.iterator() + if (!iterator.hasNext()) break + iterator.next() + iterator.remove() + } + } + + private fun retireInternal(sessionId: String?) { + if (!isKnownId(sessionId)) return + val id = sessionId!! + retired.remove(id) + retired.add(id) + while (retired.size > retiredLimit) { + val iterator = retired.iterator() + if (!iterator.hasNext()) break + iterator.next() + iterator.remove() + } + } + + private fun isRetired(sessionId: String): Boolean = retired.contains(sessionId) + + /** 空白/空串一律视为"无 id";非空 id 原样保留(不 trim、不改写)。 */ + private fun isKnownId(sessionId: String?): Boolean = sessionId != null && sessionId.isNotBlank() +} diff --git a/openless-all/android/kotlin/ImeSelectionPolicy.kt b/openless-all/android/kotlin/ImeSelectionPolicy.kt new file mode 100644 index 000000000..d5c745ac2 --- /dev/null +++ b/openless-all/android/kotlin/ImeSelectionPolicy.kt @@ -0,0 +1,107 @@ +package com.openless.app + +/** + * 输入法编辑区间(绝对 UTF-16 偏移)。 + * + * `anchor` 是扩展起点(保持不动),`active` 是随方向移动的一端;两者顺序不保证 + * `anchor <= active`(反向选择是合法的)。 + */ +internal data class ImeSelectionRange(val anchor: Int, val active: Int) + +/** + * Range 选区的纯策略:只做 UTF-16/codepoint 级别的单步扩展。 + * + * 关键约束: + * - `text` 为 `CharSequence?`,返回**绝对**偏移;`null`、负 `startOffset`、 + * 未知/越界 `selectionStart/End`、Int 溢出、非法 `direction` 一律返回 `null`, + * 绝不猜测 0; + * - `selectionStart/End` 是相对 extracted text 的局部偏移,必须加上 `startOffset` + * 才是绝对位置; + * - `previous` 只有其 `min/max` 与当前快照的绝对 selection **完全一致**才复用, + * 否则用当前 live selection 重新建立(外部移动 caret 不沿用旧 anchor); + * - `active` 按 [Character.offsetByCodePoints] 跨一个完整 codepoint,不切 surrogate + * pair;到达 0 / text.length 边界时保持原 range; + * - 校验 `start/end/active` 不落在合法 surrogate pair 中间,否则返回 `null`。 + * + * 注意:这里只承诺 **codepoint** 粒度,不承诺完整 grapheme cluster;ZWJ 序列 + * (如 👨‍👩‍👧)会按 codepoint 单步推进,不保证一次跳过整个可视字形。 + * 纯函数:无 Native/JNI/IO/偏好,可直接 JVM 测试。 + */ +internal object ImeSelectionPolicy { + + fun extend( + text: CharSequence?, + startOffset: Int, + selectionStart: Int, + selectionEnd: Int, + previous: ImeSelectionRange?, + direction: Int, + ): ImeSelectionRange? { + if (text == null) return null + if (direction != -1 && direction != 1) return null + if (startOffset < 0) return null + if (selectionStart < 0 || selectionEnd < 0) return null + + val spanLength = text.length + // All absolute offsets are Int-based in the public API; a window whose end + // would not fit cannot be represented without overflow. + val maxAbsolute = startOffset.toLong() + spanLength.toLong() + if (maxAbsolute < 0L || maxAbsolute > Int.MAX_VALUE.toLong()) return null + + val liveStartAbsolute = startOffset.toLong() + selectionStart.toLong() + val liveEndAbsolute = startOffset.toLong() + selectionEnd.toLong() + if (liveStartAbsolute < 0L || liveStartAbsolute > maxAbsolute) return null + if (liveEndAbsolute < 0L || liveEndAbsolute > maxAbsolute) return null + + // Local offsets index into `text`; only these may be used with Character/text APIs. + val liveStartLocal = (liveStartAbsolute - startOffset).toInt() + val liveEndLocal = (liveEndAbsolute - startOffset).toInt() + if (isInsideSurrogatePair(text, liveStartLocal) || isInsideSurrogatePair(text, liveEndLocal)) { + return null + } + + val liveMin = minOf(liveStartAbsolute, liveEndAbsolute) + val liveMax = maxOf(liveStartAbsolute, liveEndAbsolute) + val reusable = previous != null && + minOf(previous.anchor, previous.active).toLong() == liveMin && + maxOf(previous.anchor, previous.active).toLong() == liveMax + + val anchor: Int + val baseActiveLocal: Int + if (reusable) { + val kept = previous + // The stored range is what gets handed back, so validate it as well. + if (kept.anchor < startOffset || kept.anchor > maxAbsolute) return null + if (kept.active < startOffset || kept.active > maxAbsolute) return null + val keptAnchorLocal = kept.anchor - startOffset + val keptActiveLocal = kept.active - startOffset + if (isInsideSurrogatePair(text, keptAnchorLocal) || + isInsideSurrogatePair(text, keptActiveLocal) + ) { + return null + } + anchor = kept.anchor + baseActiveLocal = keptActiveLocal + } else { + // External caret movement (or first use) re-bases on the live selection. + anchor = liveStartAbsolute.toInt() + baseActiveLocal = liveEndLocal + } + + val nextLocal = when (direction) { + 1 -> if (baseActiveLocal >= spanLength) baseActiveLocal + else Character.offsetByCodePoints(text, baseActiveLocal, 1) + else -> if (baseActiveLocal <= 0) baseActiveLocal + else Character.offsetByCodePoints(text, baseActiveLocal, -1) + } + val nextAbsolute = startOffset.toLong() + nextLocal.toLong() + if (nextAbsolute < 0L || nextAbsolute > maxAbsolute) return null + return ImeSelectionRange(anchor, nextAbsolute.toInt()) + } + + /** `index` 是否恰好落在合法 high/low surrogate pair 的中间。 */ + private fun isInsideSurrogatePair(text: CharSequence, index: Int): Boolean { + if (index <= 0 || index >= text.length) return false + return Character.isHighSurrogate(text[index - 1]) && Character.isLowSurrogate(text[index]) + } +} diff --git a/openless-all/android/kotlin/ImeStrokePanel.kt b/openless-all/android/kotlin/ImeStrokePanel.kt new file mode 100644 index 000000000..1340f18a3 --- /dev/null +++ b/openless-all/android/kotlin/ImeStrokePanel.kt @@ -0,0 +1,607 @@ +package com.openless.app + +import android.content.Context +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.text.SpannableString +import android.text.Spanned +import android.text.style.RelativeSizeSpan +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.TextView + +/** + * 笔画 / 数字 / 符号面板(独立 View 组件)。 + * + * 纯展示与手势:不读 Service、JNI、InputConnection、SharedPreferences; + * 所有业务动作都通过 [onCommand] / [onText] / [onPunctuationPage] 回调交给 root + * (StrokeInputController 适配层)决定。命令字面量与 root 侧约定: + * `h,s,p,n,z,*,segment,script,space,voice,symbols,numbers,backspace,enter,clear,back,prev,next,toggle_symbols`; + * 标点/冒号/分号/数字等直接上屏内容走 [onText]。 + * + * 几何结构(与旧 StrokeInputController 语义一致): + * - 主面板:左标点 rail(上一组/下一组 + 当前组标点)、中间 4×3 九键、右动作列; + * - 数字页:4×5(@ 1 2 3 退格 / : 4 5 6 回车 / , 7 8 9 语音 / + 0 . 符号 返回); + * - 符号页:12 项符号分 3 行 4 列 + 第 4 行 上一页/页码/下一页/数字/返回(页码不可点)。 + * + * 候选区使用共享 [ImeCandidateStrip](固定高度区域),展开视图叠加在 body 之上, + * 不挤压键盘高度;展开时隐藏下方网格/rail 的无障碍节点。 + */ +internal class ImeStrokePanel( + context: Context, + private val palette: ImePalette, + header: View, + private val englishUi: Boolean, + private val onCommand: (String) -> Unit, + private val onText: (String) -> Unit, + private val onPunctuationPage: (Int) -> Unit, + private val onFeedback: () -> Unit = {}, + interactionPolicy: ImeInteractionPolicy = ImeInteractionPolicy.DEFAULT, +) : LinearLayout(context) { + + internal data class Candidate(val label: String, val select: () -> Unit) + + private enum class Geometry { STROKE, NUMBER, SYMBOL } + + private var policy = interactionPolicy + private val strip = ImeCandidateStrip(context, palette, englishUi) { expanded -> setExpandedOverlay(expanded) } + private val clearPreedit = ImeActionButton( + context, + palette, + "✕", + description = ui("清除输入", "Clear input"), + onAction = { onCommand("clear") }, + onFeedback = onFeedback, + interactionPolicy = policy, + ).apply { + textSize = 15f + setTextColor(palette.secondaryText) + } + private val divider = View(context).apply { setBackgroundColor(palette.separator) } + private val bodyHost = FrameLayout(context) + private val body = LinearLayout(context).apply { orientation = VERTICAL } + + private var geometry = Geometry.STROKE + private var preeditText: CharSequence = "" + private var traditional = false + private var symbolPage = 0 + private var symbolPageCount = 1 + private var symbols: List = emptyList() + private var punctuation: List = emptyList() + private var blocked = false + private var expandedOverlay: View? = null + private var lastCandidates: List = emptyList() + + private val keys = mutableListOf() + private var punctuationKeys = emptyList() + private var symbolKeys = emptyList() + private var symbolPageLabel: TextView? = null + private var scriptKey: ImeActionButton? = null + + init { + orientation = VERTICAL + setBackgroundColor(palette.surface) + setPadding(dp(4), dp(4), dp(4), dp(4)) + addView(header, LayoutParams(LayoutParams.MATCH_PARENT, dp(40))) + + val candidateRow = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL } + candidateRow.addView(strip, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + clearPreedit.visibility = INVISIBLE + candidateRow.addView(clearPreedit, LayoutParams(dp(38), LayoutParams.MATCH_PARENT)) + addView(candidateRow, LayoutParams(LayoutParams.MATCH_PARENT, dp(42))) + addView(divider, LayoutParams(LayoutParams.MATCH_PARENT, dp(1))) + + bodyHost.addView(body, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + addView(bodyHost, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + + strip.setEmptyHint(ui("候选显示在这里", "Candidates appear here")) + rebuildBody() + } + + /** + * 单一渲染入口。同一几何形态下只更新标签/选中态/候选与 preedit, + * 不重建键盘;形态切换(笔画↔数字↔符号)或标点页容量变化时先取消旧触摸再重建。 + */ + fun render( + preedit: CharSequence, + traditional: Boolean, + numberMode: Boolean, + symbolMode: Boolean, + symbolPage: Int, + symbolPageCount: Int, + symbols: List, + punctuation: List, + ) { + val nextGeometry = when { + symbolMode -> Geometry.SYMBOL + numberMode -> Geometry.NUMBER + else -> Geometry.STROKE + } + val punctuationCapacityChanged = + nextGeometry == Geometry.STROKE && punctuation.size != this.punctuation.size + + this.preeditText = preedit + this.traditional = traditional + this.symbolPage = symbolPage + this.symbolPageCount = symbolPageCount.coerceAtLeast(1) + this.symbols = symbols + this.punctuation = punctuation + + if (nextGeometry != geometry || punctuationCapacityChanged) { + cancelInteractions() + geometry = nextGeometry + rebuildBody() + } else { + updateDynamicContent() + } + updatePreedit() + updateScriptState() + refreshStrip() + refreshBlockedVisuals() + } + + /** 候选列表由 root 查询得到,这里只负责呈现;不触发键盘重建。 */ + fun submitCandidates(items: List) { + lastCandidates = items + refreshStrip() + } + + /** 下发统一互动策略:值变化时先中止旧触摸/计时器,再更新已存在与后续新建的全部按键。 */ + fun applyInteractionPolicy(policy: ImeInteractionPolicy) { + if (policy == this.policy) return + cancelInteractions() + this.policy = policy + keys.forEach { it.applyInteractionPolicy(policy) } + clearPreedit.applyInteractionPolicy(policy) + scriptKey?.applyInteractionPolicy(policy) + } + + /** 取消所有进行中的触摸/长按/重复动作(设置变化、面板重建、隐藏前调用)。 */ + fun cancelInteractions() { + keys.forEach { it.cancelInteraction() } + clearPreedit.cancelInteraction() + strip.cancelInteractions() + } + + /** 屏蔽/恢复全部交互(例如正在录音、字段敏感或输入连接失效时)。 */ + fun setBlocked(blocked: Boolean) { + this.blocked = blocked + if (blocked) { + closeExpandedOverlay() + keys.forEach { it.cancelInteraction() } + clearPreedit.cancelInteraction() + } + refreshBlockedVisuals() + if (!blocked) updateDynamicContent() + } + + // ---- 几何构建 ---- + + private fun rebuildBody() { + closeExpandedOverlay() + keys.clear() + punctuationKeys = emptyList() + symbolKeys = emptyList() + symbolPageLabel = null + scriptKey = null + body.removeAllViews() + when (geometry) { + Geometry.STROKE -> buildStrokeBody() + Geometry.NUMBER -> buildNumberBody() + Geometry.SYMBOL -> buildSymbolBody() + } + } + + private fun buildStrokeBody() { + val row = LinearLayout(context).apply { gravity = Gravity.CENTER } + row.addView(buildPunctuationRail(), LayoutParams(0, LayoutParams.MATCH_PARENT, 0.16f)) + row.addView(buildStrokeGrid(), LayoutParams(0, LayoutParams.MATCH_PARENT, 0.65f)) + row.addView(buildStrokeActions(), LayoutParams(0, LayoutParams.MATCH_PARENT, 0.19f)) + body.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + } + + private fun buildPunctuationRail(): LinearLayout { + val rail = LinearLayout(context).apply { + orientation = VERTICAL + gravity = Gravity.CENTER + setPadding(dp(1), dp(1), dp(1), dp(1)) + background = rounded(palette.auxiliary, dp(6)) + } + rail.addView( + commandKey("▲", ui("上一组标点", "Previous punctuation set"), "", labelSize = 12f, explicitAction = { onPunctuationPage(-1) }), + LayoutParams(LayoutParams.MATCH_PARENT, dp(20)), + ) + val marks = punctuationList() + val buttons = marks.mapIndexed { index, mark -> + keyButton( + label = mark, + description = ui("标点 $mark", "Punctuation $mark"), + onAction = { punctuationList().getOrNull(index)?.let(onText) }, + labelSize = 17f, + ).also { key -> + rail.addView(key, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } + } + punctuationKeys = buttons + rail.addView( + commandKey("▼", ui("下一组标点", "Next punctuation set"), "", labelSize = 12f, explicitAction = { onPunctuationPage(1) }), + LayoutParams(LayoutParams.MATCH_PARENT, dp(20)), + ) + return rail + } + + private fun buildStrokeGrid(): LinearLayout { + val grid = LinearLayout(context).apply { + orientation = VERTICAL + gravity = Gravity.CENTER + } + val rows = listOf( + listOf( + commandKey("1\n一", ui("横", "Horizontal stroke"), "h", swipeDigit = "1"), + commandKey("2\n丨", ui("竖", "Vertical stroke"), "s", swipeDigit = "2"), + commandKey("3\n丿", ui("撇", "Left falling stroke"), "p", swipeDigit = "3"), + ), + listOf( + commandKey("4\n丶", ui("点", "Dot stroke"), "n", swipeDigit = "4"), + commandKey("5\n乙", ui("折", "Turning stroke"), "z", swipeDigit = "5"), + commandKey("6\n通配", ui("通配符", "Wildcard"), "*", swipeDigit = "6"), + ), + listOf( + commandKey("7\n分词", ui("分词", "Segment word"), "segment", swipeDigit = "7"), + textKey("8\n:", ui("冒号", "Colon"), ":", swipeDigit = "8"), + textKey("9\n;", ui("分号", "Semicolon"), ";", swipeDigit = "9"), + ), + listOf( + scriptButton(), + spaceButton(), + commandKey("符号", ui("符号", "Symbols"), "symbols", labelSize = 15f), + ), + ) + rows.forEach { rowKeys -> + val row = LinearLayout(context).apply { gravity = Gravity.CENTER } + rowKeys.forEach { key -> + row.addView(key, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } + grid.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + return grid + } + + private fun buildStrokeActions(): LinearLayout { + val actions = LinearLayout(context).apply { + orientation = VERTICAL + gravity = Gravity.CENTER + } + val cells = listOf( + commandKey("←", ui("退格", "Backspace"), "backspace", repeat = true, labelSize = 22f), + commandKey("↵", ui("回车", "Enter"), "enter", labelSize = 22f), + commandKey("清除", ui("清除笔画编码", "Clear stroke code"), "clear", labelSize = 15f), + commandKey("123", ui("数字与符号", "Numbers and symbols"), "numbers", labelSize = 15f), + ) + cells.forEach { key -> + actions.addView(key, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } + return actions + } + + private fun buildNumberBody() { + val column = LinearLayout(context).apply { orientation = VERTICAL } + val rows = listOf( + listOf("@", "1", "2", "3") to commandKey("退格", ui("退格", "Backspace"), "backspace", repeat = true, labelSize = 15f), + listOf(":", "4", "5", "6") to commandKey("回车", ui("回车", "Enter"), "enter", labelSize = 15f), + listOf(",", "7", "8", "9") to commandKey("语音", ui("语音输入", "Voice input"), "voice", labelSize = 15f), + listOf("+", "0", ".") to commandKey("符号", ui("符号", "Symbols"), "toggle_symbols", labelSize = 15f), + ) + rows.forEach { (content, last) -> + val row = LinearLayout(context).apply { gravity = Gravity.CENTER } + content.forEach { label -> + row.addView( + textKey(label, ui("输入 $label", "Type $label"), label, labelSize = 20f), + LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { setMargins(dp(1), dp(1), dp(1), dp(1)) }, + ) + } + val trailing = if (content.size == 3) { + // 最后一行是「+ 0 . 符号 返回」,符号之后还有返回键。 + listOf(last, commandKey("返回", ui("返回笔画", "Back to stroke"), "back", labelSize = 15f)) + } else { + listOf(last) + } + trailing.forEach { key -> + row.addView(key, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } + column.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + body.addView(column, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + } + + private fun buildSymbolBody() { + val column = LinearLayout(context).apply { orientation = VERTICAL } + val items = symbolItems() + val built = mutableListOf() + for (rowIndex in 0 until 3) { + val row = LinearLayout(context).apply { gravity = Gravity.CENTER } + for (columnIndex in 0 until 4) { + val index = rowIndex * 4 + columnIndex + val label = items.getOrNull(index).orEmpty() + val key = keyButton( + label = label, + description = if (label.isEmpty()) "" else ui("输入 $label", "Type $label"), + onAction = { symbolItems().getOrNull(index)?.takeIf { it.isNotEmpty() }?.let(onText) }, + labelSize = 19f, + ).apply { + if (label.isEmpty()) { + visibility = INVISIBLE + isEnabled = false + } + } + built.add(key) + row.addView(key, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } + val command = listOf("backspace", "enter", "voice")[rowIndex] + val label = listOf("退格", "回车", "语音")[rowIndex] + row.addView(commandKey(label, label, command, repeat = rowIndex == 0, labelSize = 14f), + LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { setMargins(dp(1), dp(1), dp(1), dp(1)) }) + column.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + symbolKeys = built + + val navRow = LinearLayout(context).apply { gravity = Gravity.CENTER } + val navCells = listOf( + commandKey("▲", ui("上一页", "Previous page"), "prev", labelSize = 13f), + null, + commandKey("▼", ui("下一页", "Next page"), "next", labelSize = 13f), + commandKey("数字", ui("数字", "Numbers"), "toggle_symbols", labelSize = 14f), + commandKey("返回", ui("返回笔画", "Back to stroke"), "back", labelSize = 14f), + ) + navCells.forEach { key -> + if (key != null) { + navRow.addView(key, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } else { + symbolPageLabel = TextView(context).apply { + text = pageIndicatorText() + gravity = Gravity.CENTER + setTextColor(palette.secondaryText) + textSize = 13f + isClickable = false + isFocusable = false + contentDescription = pageIndicatorDescription() + } + navRow.addView(symbolPageLabel, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { + setMargins(dp(1), dp(1), dp(1), dp(1)) + }) + } + } + column.addView(navRow, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + body.addView(column, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + } + + // ---- 动态更新 ---- + + private fun updateDynamicContent() { + when (geometry) { + Geometry.STROKE -> { + val marks = punctuationList() + punctuationKeys.forEachIndexed { index, key -> + val label = marks.getOrNull(index).orEmpty() + key.text = label + key.contentDescription = if (label.isEmpty()) "" else ui("标点 $label", "Punctuation $label") + key.visibility = if (label.isEmpty()) INVISIBLE else VISIBLE + key.isEnabled = label.isNotEmpty() && isEnabled && !blocked + } + } + Geometry.NUMBER -> Unit + Geometry.SYMBOL -> { + val items = symbolItems() + symbolKeys.forEachIndexed { index, key -> + val label = items.getOrNull(index).orEmpty() + key.text = label + key.contentDescription = if (label.isEmpty()) "" else ui("输入 $label", "Type $label") + key.visibility = if (label.isEmpty()) INVISIBLE else VISIBLE + // 稀疏页 -> 更满页(同 geometry 不重建)时,新出现的非空槽必须恢复可点。 + key.isEnabled = label.isNotEmpty() && isEnabled && !blocked + } + symbolPageLabel?.let { indicator -> + indicator.text = pageIndicatorText() + indicator.contentDescription = pageIndicatorDescription() + } + } + } + } + + private fun updatePreedit() { + clearPreedit.visibility = if (preeditText.isEmpty()) INVISIBLE else VISIBLE + } + + private fun updateScriptState() { + scriptKey?.let { key -> + key.isSelected = traditional + key.setTextColor(if (traditional) palette.accent else palette.text) + key.setTypeface(key.typeface, if (traditional) Typeface.BOLD else Typeface.NORMAL) + key.contentDescription = if (traditional) { + ui("繁体输出,已开启", "Traditional output, on") + } else { + ui("简体输出,点击切换繁体", "Simplified output, tap for traditional") + } + } + } + + private fun refreshStrip() { + strip.submit( + lastCandidates.map { ImeCandidateStrip.Item(it.label, it.select) }, + if (preeditText.isEmpty()) null else preeditText, + ) + } + + /** + * 单一交互可用性入口:父级 `isEnabled`、`blocked`、以及"空槽不可点"三者同时生效。 + * 供 setEnabled / setBlocked / render 后统一调用。 + */ + private fun refreshBlockedVisuals() { + val interactive = isEnabled && !blocked + keys.forEach { key -> + key.isEnabled = interactive && key.text.isNotEmpty() + key.alpha = if (interactive) 1f else 0.45f + } + clearPreedit.isEnabled = interactive + clearPreedit.alpha = if (interactive) 1f else 0.45f + strip.setBlocked(!interactive) + } + + // ---- 候选展开叠加 ---- + + private fun setExpandedOverlay(expanded: Boolean) { + body.importantForAccessibility = if (expanded) { + IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + } else { + IMPORTANT_FOR_ACCESSIBILITY_AUTO + } + if (expanded) { + val overlay = strip.expandedView + if (expandedOverlay !== overlay) { + expandedOverlay?.let { bodyHost.removeView(it) } + overlay.layoutParams = FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) + bodyHost.addView(overlay) + expandedOverlay = overlay + } else { + overlay.bringToFront() + } + } else if (expandedOverlay != null) { + expandedOverlay?.let { bodyHost.removeView(it) } + expandedOverlay = null + } + } + + private fun closeExpandedOverlay() { + if (expandedOverlay != null) setExpandedOverlay(false) + strip.closeExpanded() + } + + // ---- 小组件 ---- + + private fun commandKey( + label: String, + description: String, + command: String, + swipeDigit: String? = null, + repeat: Boolean = false, + labelSize: Float = 16f, + explicitAction: (() -> Unit)? = null, + ): ImeActionButton = keyButton( + label = label, + description = description, + onAction = explicitAction ?: { if (command.isNotEmpty()) onCommand(command) }, + onSwipeUp = swipeDigit?.let { digit -> { onText(digit) } }, + repeat = repeat, + labelSize = labelSize, + ) + + private fun textKey(label: String, description: String, text: String, swipeDigit: String? = null, labelSize: Float = 16f): ImeActionButton = + keyButton( + label = label, + description = description, + onAction = { onText(text) }, + onSwipeUp = swipeDigit?.let { digit -> { onText(digit) } }, + labelSize = labelSize, + ) + + private fun scriptButton(): ImeActionButton { + val key = keyButton( + label = "繁", + description = ui("简体输出,点击切换繁体", "Simplified output, tap for traditional"), + onAction = { onCommand("script") }, + labelSize = 17f, + ) + scriptKey = key + return key + } + + private fun spaceButton(): ImeActionButton = keyButton( + label = ui("空格", "space"), + description = ui("空格,长按说话", "Space, hold to speak"), + onAction = { onCommand("space") }, + onSwipeUp = { onText("0") }, + onHold = { onCommand("voice") }, + holdDelay = 900L, + labelSize = 15f, + ) + + private fun keyButton( + label: String, + description: String, + onAction: () -> Unit, + onSwipeUp: (() -> Unit)? = null, + onHold: (() -> Unit)? = null, + repeat: Boolean = false, + holdDelay: Long = 500L, + labelSize: Float = 16f, + ): ImeActionButton { + val button = ImeActionButton( + context, + palette, + label, + description = description, + onAction = onAction, + onHold = onHold, + repeatOnHold = repeat, + onSwipeUp = onSwipeUp, + holdDelayMs = holdDelay, + onFeedback = onFeedback, + interactionPolicy = policy, + ) + button.textSize = labelSize + if ('\n' in label) { + button.maxLines = 2 + button.text = SpannableString(label).apply { + setSpan(RelativeSizeSpan(0.5f), 0, label.indexOf('\n'), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + } + } + button.setTextColor(palette.text) + keys.add(button) + return button + } + + private fun punctuationList(): List = + punctuation.ifEmpty { listOf(",", "°", "?", "!", "~") } + + private fun symbolItems(): List = symbols + + private fun pageIndicatorText(): String = "${(symbolPage + 1).coerceAtMost(symbolPageCount)}/$symbolPageCount" + + private fun pageIndicatorDescription(): String = + ui("第 ${symbolPage + 1} 页,共 $symbolPageCount 页", "Page ${symbolPage + 1} of $symbolPageCount") + + private fun rounded(color: Int, radius: Int): GradientDrawable = GradientDrawable().apply { + setColor(color) + cornerRadius = radius.toFloat() + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + private fun ui(zh: String, en: String): String = if (englishUi) en else zh + + override fun setEnabled(enabled: Boolean) { + super.setEnabled(enabled) + // 父级禁用必须同时收起子交互:只 enable 非空槽,并同步 clearPreedit 与候选条。 + refreshBlockedVisuals() + } + + override fun onDetachedFromWindow() { + cancelInteractions() + super.onDetachedFromWindow() + } +} diff --git a/openless-all/android/kotlin/ImeSurfaceHost.kt b/openless-all/android/kotlin/ImeSurfaceHost.kt new file mode 100644 index 000000000..c2410bb27 --- /dev/null +++ b/openless-all/android/kotlin/ImeSurfaceHost.kt @@ -0,0 +1,92 @@ +package com.openless.app + +import android.content.Context +import android.view.View +import android.view.ViewGroup +import android.widget.ScrollView + +/** Stable system input-view root; only its presentation children are replaced. */ +internal class ImeSurfaceHost(context: Context) : ViewGroup(context) { + private val draftScroll = ScrollView(context).apply { + isFillViewport = false + isVerticalScrollBarEnabled = true + visibility = GONE + tag = "ime-draft-scroll" + } + private var keyboard: View? = null + private var draft: View? = null + private var draftKey: Any? = null + private var resetDraftScroll = false + + init { + clipChildren = true + addView(draftScroll, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + tag = "ime-surface-host" + } + + fun render(keyboard: View, draft: View?, draftKey: Any? = draft) { + if (this.keyboard !== keyboard) { + this.keyboard?.let(::removeView) + (keyboard.parent as? ViewGroup)?.removeView(keyboard) + this.keyboard = keyboard + addView(keyboard, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + } + if (this.draft !== draft) { + draftScroll.removeAllViews() + if (draft != null) { + (draft.parent as? ViewGroup)?.removeView(draft) + draftScroll.addView(draft, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) + } + this.draft = draft + } + resetDraftScroll = resetDraftScroll || this.draftKey !== draftKey + this.draftKey = draftKey + draftScroll.visibility = if (draft == null) GONE else VISIBLE + requestLayout() + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) + val requestedLimit = MeasureSpec.getSize(heightMeasureSpec) + val screenLimit = resources.displayMetrics.heightPixels.coerceAtLeast(1) + val limit = if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED || requestedLimit == 0) { + screenLimit + } else requestedLimit + // Reserve editor space against the screen, not this measured window. + // Subtracting it from every EXACT pass would shrink a wrap-content IME + // repeatedly as WindowManager acknowledges the previous measured size. + val editorMargin = minOf(dp(48), screenLimit / 5) + val available = minOf(limit, (screenLimit - editorMargin).coerceAtLeast(0)) + val widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY) + val keys = keyboard + if (keys == null) { + setMeasuredDimension(width, 0) + return + } + keys.measure(widthSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) + val preferredKeys = keys.measuredHeight + val draftBudget = (available - minOf(preferredKeys, dp(220))).coerceAtLeast(0) + val desiredDraft = if (draft != null) { + draftScroll.measure(widthSpec, MeasureSpec.makeMeasureSpec(draftBudget, MeasureSpec.AT_MOST)) + draftScroll.measuredHeight + } else 0 + val size = ImeSurfaceLayout.resolve(preferredKeys, desiredDraft, available, dp(220)) + if (keys.measuredHeight != size.keyboard) keys.measure(widthSpec, MeasureSpec.makeMeasureSpec(size.keyboard, MeasureSpec.EXACTLY)) + if (draft != null && draftScroll.measuredHeight != size.draft) { + draftScroll.measure(widthSpec, MeasureSpec.makeMeasureSpec(size.draft, MeasureSpec.EXACTLY)) + } + setMeasuredDimension(width, keys.measuredHeight + if (draft != null) draftScroll.measuredHeight else 0) + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + val draftHeight = if (draft != null) draftScroll.measuredHeight else 0 + if (draft != null) draftScroll.layout(0, 0, width, draftHeight) + keyboard?.let { it.layout(0, draftHeight, width, draftHeight + it.measuredHeight) } + if (resetDraftScroll) { + draftScroll.scrollTo(0, 0) + resetDraftScroll = false + } + } + + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() +} diff --git a/openless-all/android/kotlin/ImeSurfaceLayout.kt b/openless-all/android/kotlin/ImeSurfaceLayout.kt new file mode 100644 index 000000000..6cd180892 --- /dev/null +++ b/openless-all/android/kotlin/ImeSurfaceLayout.kt @@ -0,0 +1,22 @@ +package com.openless.app + +/** Pixel-only sizing policy. Long drafts scroll instead of covering the keys. */ +internal data class ImeSurfaceSize(val keyboard: Int, val draft: Int) { + val total: Int get() = keyboard + draft +} + +internal object ImeSurfaceLayout { + fun resolve( + preferredKeyboard: Int, + desiredDraft: Int, + available: Int, + minimumKeyboard: Int, + ): ImeSurfaceSize { + val limit = available.coerceAtLeast(0) + val preferred = preferredKeyboard.coerceAtLeast(0).coerceAtMost(limit) + val reservedKeys = minimumKeyboard.coerceAtLeast(0).coerceAtMost(preferred) + val draft = desiredDraft.coerceAtLeast(0).coerceAtMost(limit - reservedKeys) + val keyboard = preferred.coerceAtMost(limit - draft) + return ImeSurfaceSize(keyboard, draft) + } +} diff --git a/openless-all/android/kotlin/ImeTypingPanel.kt b/openless-all/android/kotlin/ImeTypingPanel.kt new file mode 100644 index 000000000..521cba0c8 --- /dev/null +++ b/openless-all/android/kotlin/ImeTypingPanel.kt @@ -0,0 +1,944 @@ +package com.openless.app + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.os.Handler +import android.os.Looper +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import android.widget.LinearLayout +import android.widget.TextView +import kotlin.math.abs + +/** Presentation-only input surface: no service, engine, JNI or preferences. */ +internal class ImeTypingPanel( + context: Context, + private val palette: ImePalette, + header: View, + private val onAction: (ImeKeyAction) -> Unit, + private val onFeedback: () -> Unit, + private val onVoiceStart: () -> Boolean, + private val onVoiceEnd: (cancelled: Boolean) -> Unit, + interfaceEnglish: Boolean = false, + interactionPolicy: ImeInteractionPolicy = ImeInteractionPolicy.DEFAULT, + private val onClearPreedit: () -> Unit = {}, + private val onCommitRawPreedit: () -> Unit = {}, + private val onCursorMove: (Int) -> Unit = {}, + private val onDeleteWord: () -> Unit = {}, +) : LinearLayout(context) { + internal data class Candidate( + val label: String, + val select: () -> Unit, + val forget: (() -> Unit)? = null, + ) + + private var policy = interactionPolicy + private val topSlot = FrameLayout(context) + private val preeditBar = LinearLayout(context) + private val preeditScroll = HorizontalScrollView(context) + private val preeditLabel = label("", 15f) + private val preeditClear = label("✕", 14f) + private val preview = PreviewBubble(context) + private val body = FrameLayout(context) + private val grid = KeyGrid(context) + private var candidateExpanded = false + private val candidateStrip = ImeCandidateStrip(context, palette, interfaceEnglish) { expanded -> + candidateExpanded = expanded + updateGridAccessibility() + } + private val voiceSheet = LinearLayout(context) + private val voiceMessage = label("", 16f) + private val voiceWaveform = LevelView(context) + private val voiceHint = label("", 13f) + private val voiceCancel = label("取消 / Cancel", 15f) + private var candidates = emptyList() + private var candidatePreedit: String? = null + private var english = interfaceEnglish + private var currentLanguage = ImeTypingLanguage.ENGLISH + private var currentLetterCase = ImeLetterCase.LOWER + private var listening = false + private var processing = false + private var holdingVoice = false + private var voiceCancelled = false + private var lastLayout: List>? = null + + init { + orientation = VERTICAL + setBackgroundColor(palette.surface) + clipChildren = false + clipToPadding = false + + // Child 0 stays anchored during mode-switch slide animations. + topSlot.addView(header, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + preeditLabel.apply { + gravity = Gravity.CENTER_VERTICAL or Gravity.START + setTextColor(palette.accent) + setTypeface(Typeface.DEFAULT, Typeface.BOLD) + setPadding(dp(12), 0, dp(12), 0) + tag = "ime-cand-preedit" + isClickable = true + isFocusable = true + setOnClickListener { + if (!listening && !processing && !candidatePreedit.isNullOrEmpty()) { + onFeedback() + onCommitRawPreedit() + } + } + } + preeditScroll.apply { + isHorizontalScrollBarEnabled = false + overScrollMode = View.OVER_SCROLL_NEVER + addView(preeditLabel, ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + preeditClear.apply { + setTextColor(palette.secondaryText) + tag = "ime-preedit-clear" + contentDescription = if (english) "Clear pinyin" else "清除编码" + isClickable = true + isFocusable = true + setOnClickListener { + if (!listening && !processing) { + onFeedback() + onClearPreedit() + } + } + } + preeditBar.apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setBackgroundColor(palette.surface) + isClickable = true + visibility = GONE + addView(preeditScroll, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + addView(preeditClear, LayoutParams(dp(42), LayoutParams.MATCH_PARENT)) + } + topSlot.addView(preeditBar, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + addView(topSlot, LayoutParams(LayoutParams.MATCH_PARENT, dp(40))) + + addView(candidateStrip, LayoutParams(LayoutParams.MATCH_PARENT, dp(42))) + addView(View(context).apply { setBackgroundColor(palette.separator) }, LayoutParams(LayoutParams.MATCH_PARENT, dp(1))) + + body.addView(grid, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + body.addView(candidateStrip.expandedView, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + voiceSheet.apply { + orientation = VERTICAL + gravity = Gravity.CENTER + setPadding(dp(16), dp(8), dp(16), dp(8)) + setBackgroundColor(palette.surface) + isClickable = true + visibility = GONE + addView(voiceMessage, LayoutParams(LayoutParams.MATCH_PARENT, dp(36))) + addView(voiceWaveform, LayoutParams(dp(200), 0, 1f)) + addView(voiceHint, LayoutParams(LayoutParams.MATCH_PARENT, dp(30))) + addView(voiceCancel.apply { + setTextColor(palette.error) + background = GradientDrawable().apply { + cornerRadius = dp(18).toFloat() + setColor(palette.auxiliary) + } + setOnClickListener { grid.cancelTouch(); onVoiceEnd(true) } + }, LayoutParams(dp(132), dp(38)).apply { topMargin = dp(4) }) + } + body.addView(voiceSheet, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + body.clipChildren = false + body.clipToPadding = false + preview.visibility = GONE + body.addView(preview, FrameLayout.LayoutParams(dp(54), dp(64))) + addView(body, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + } + + /** 下发统一互动策略:值变化时先中止旧触摸/计时器;相同值不影响进行中的交互。 */ + fun applyInteractionPolicy(policy: ImeInteractionPolicy) { + if (policy == this.policy) return + grid.cancelTouch() + this.policy = policy + } + + fun renderKeyboard( + layer: ImeKeyboardLayer, + language: ImeTypingLanguage, + letterCase: ImeLetterCase, + enterLabel: String, + englishUi: Boolean, + ) { + english = englishUi + currentLanguage = language + currentLetterCase = letterCase + preeditClear.contentDescription = if (english) "Clear pinyin" else "清除编码" + val layout = ImeKeyboardLayouts.rows(layer, language, letterCase, enterLabel) + if (layout != lastLayout) { + lastLayout = layout + grid.setKeys(layout, layer == ImeKeyboardLayer.LETTERS) + } else { + grid.refreshKeyVisuals() + } + if (candidates.isEmpty() && candidatePreedit.isNullOrEmpty()) { + candidateStrip.setEmptyHint(if (english) "Hold space to speak" else "按住空格说话") + } + } + + fun submitCandidates(items: List, preedit: String?, statusHint: String? = null) { + candidates = items + candidatePreedit = preedit + val hasPreedit = !preedit.isNullOrEmpty() + preeditBar.visibility = if (hasPreedit) VISIBLE else GONE + if (hasPreedit) { + preeditLabel.text = preedit + preeditLabel.contentDescription = preedit + preeditScroll.post { preeditScroll.fullScroll(View.FOCUS_RIGHT) } + } + candidateStrip.submit( + items.map { ImeCandidateStrip.Item(it.label, it.select, it.forget) }, + preedit = null, + emptyHint = statusHint ?: if (english) "Hold space to speak" else "按住空格说话", + ) + candidateStrip.setBlocked(listening || processing) + } + + fun setClipboardSuggestion(label: String?, onPaste: () -> Unit, onDismiss: () -> Unit) { + candidateStrip.setQuickChip(label, onPaste, onDismiss) + } + + fun renderVoice(message: String, recording: Boolean, busy: Boolean, level: Float? = null, cancellable: Boolean = recording || busy) { + listening = recording + processing = busy + voiceCancel.isEnabled = cancellable + voiceCancel.alpha = if (cancellable) 1f else 0.4f + voiceCancel.text = if (english) "Cancel" else "取消" + voiceMessage.text = message + if (!recording && !busy && !holdingVoice && message.isNotBlank() && candidates.isEmpty() && candidatePreedit.isNullOrEmpty()) { + candidateStrip.setEmptyHint(message) + } + voiceSheet.visibility = if (holdingVoice || recording || busy) VISIBLE else GONE + voiceHint.text = when { + holdingVoice && voiceCancelled -> if (english) "Release to cancel" else "松开取消" + holdingVoice -> if (english) "Release to insert · Slide up to cancel" else "松开输入 · 上滑取消" + busy -> if (english) "Processing…" else "正在处理…" + else -> "" + } + voiceHint.setTextColor(if (voiceCancelled) palette.error else palette.secondaryText) + if (level != null) voiceWaveform.push(if (recording && level.isFinite()) level.coerceIn(0f, 1f) else 0f) + if (!recording) voiceWaveform.clear() + candidateStrip.setBlocked(recording || busy) + updateGridAccessibility() + } + + fun closeTransientUi() { + grid.cancelTouch() + candidateStrip.cancelInteractions() + } + + private fun updateGridAccessibility() { + grid.importantForAccessibility = if (candidateExpanded || holdingVoice || listening || processing) { + IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + } else IMPORTANT_FOR_ACCESSIBILITY_AUTO + } + + private fun label(value: String, size: Float) = TextView(context).apply { + text = value + textSize = size + gravity = Gravity.CENTER + setTextColor(palette.text) + includeFontPadding = false + maxLines = 1 + } + + private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt() + private fun dpf(value: Float) = value * resources.displayMetrics.density + + /** Floating popup preview rendered with exact FontMetrics centering. */ + private inner class PreviewBubble(context: Context) : View(context) { + private var glyph: String = "" + private var accentHighlight: Boolean = false + private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + } + private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + typeface = Typeface.DEFAULT_BOLD + } + private val rect = RectF() + + init { + isClickable = false + importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO + elevation = dpf(8f) + } + + fun show(value: String, accented: Boolean) { + glyph = value + accentHighlight = accented + invalidate() + } + + override fun onDraw(canvas: Canvas) { + val radius = dpf(10f) + val pad = dpf(1f) + rect.set(pad, pad, width - pad, height - pad) + bgPaint.color = if (accentHighlight) palette.accent else palette.key + canvas.drawRoundRect(rect, radius, radius, bgPaint) + borderPaint.color = palette.separator + borderPaint.strokeWidth = dpf(1f) + canvas.drawRoundRect(rect, radius, radius, borderPaint) + + textPaint.color = if (accentHighlight) Color.WHITE else palette.text + textPaint.textSize = if (glyph.length > 1) dpf(20f) else dpf(30f) + val fm = textPaint.fontMetrics + val baseline = height / 2f - (fm.ascent + fm.descent) / 2f + canvas.drawText(glyph, width / 2f, baseline, textPaint) + } + } + + /** + * Custom Canvas-drawn keycap extending TextView so existing tests/accessibility + * can read `.text`, while rendering stays mathematically centered regardless of + * OEM fonts or system font scale. + */ + private inner class KeyCapView(context: Context, var spec: ImeKeySpec) : TextView(context) { + var cursorSlideActive = false + set(value) { + if (field != value) { + field = value + invalidate() + } + } + var activeOverride: String? = null + set(value) { + if (field != value) { + field = value + invalidate() + } + } + + private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val primaryPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + } + private val secondaryPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.RIGHT + } + private val iconPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + strokeCap = Paint.Cap.ROUND + strokeJoin = Paint.Join.ROUND + } + private val rect = RectF() + private val path = Path() + + init { + setWillNotDraw(false) + isFocusable = true + isClickable = true + gravity = Gravity.CENTER + includeFontPadding = false + maxLines = 1 + syncMetadata() + } + + fun updateSpec(next: ImeKeySpec) { + spec = next + activeOverride = null + syncMetadata() + invalidate() + } + + fun syncMetadata() { + tag = "ime-key-${spec.id}" + text = when { + spec.action == ImeKeyAction.Space && !english -> "空格" + else -> spec.label + } + contentDescription = accessibilityLabel(spec) + } + + override fun setPressed(pressed: Boolean) { + val changed = isPressed != pressed + super.setPressed(pressed) + if (changed) invalidate() + } + + override fun onDraw(canvas: Canvas) { + val w = width.toFloat() + val h = height.toFloat() + if (w <= 0f || h <= 0f) return + + val isEnter = spec.action == ImeKeyAction.Enter + val isShiftActive = spec.action == ImeKeyAction.Shift && currentLetterCase != ImeLetterCase.LOWER + val radius = dpf(6f) + val shadowHeight = dpf(1.2f) + + // Subtle bottom keycap rim for crisp visual separation. + shadowPaint.color = palette.separator + rect.set(0f, shadowHeight, w, h) + canvas.drawRoundRect(rect, radius, radius, shadowPaint) + + val normalColor = when { + isEnter -> palette.accent + isShiftActive -> palette.key + spec.auxiliary -> palette.auxiliary + else -> palette.key + } + fillPaint.color = when { + isPressed && isEnter -> blendPressed(palette.accent) + isPressed -> palette.pressed + else -> normalColor + } + rect.set(0f, 0f, w, (h - shadowHeight).coerceAtLeast(1f)) + canvas.drawRoundRect(rect, radius, radius, fillPaint) + + val cx = w / 2f + val cy = rect.centerY() + + when (spec.action) { + ImeKeyAction.Backspace -> { + drawBackspaceIcon(canvas, cx, cy, minOf(w, h)) + return + } + ImeKeyAction.Shift -> { + drawShiftIcon(canvas, cx, cy, minOf(w, h)) + return + } + ImeKeyAction.Language -> { + drawLanguageBadge(canvas, cx, cy, w, h) + return + } + else -> Unit + } + + val displayText = when { + cursorSlideActive && spec.action == ImeKeyAction.Space -> if (english) "◀ Cursor ▶" else "◀ 移动光标 ▶" + activeOverride != null -> activeOverride!! + spec.action == ImeKeyAction.Space -> if (english) "Space" else "空格" + else -> spec.label + } + + // Secondary hint drawn independently in upper-right corner (never pushes main glyph off-center). + val secondary = if (activeOverride == null) spec.secondary else null + if (secondary != null && h >= dpf(28f)) { + secondaryPaint.color = palette.secondaryText + secondaryPaint.alpha = 185 + secondaryPaint.textSize = minOf(dpf(9.5f), h * 0.21f).coerceAtLeast(dpf(7.5f)) + val sfm = secondaryPaint.fontMetrics + canvas.drawText(secondary, w - dpf(4.5f), dpf(2.8f) - sfm.ascent, secondaryPaint) + } + + primaryPaint.color = when { + isEnter -> Color.WHITE + cursorSlideActive && spec.action == ImeKeyAction.Space -> palette.accent + else -> palette.text + } + primaryPaint.typeface = if (isEnter || spec.action == ImeKeyAction.Space) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + val isSingleChar = displayText.length == 1 && !spec.auxiliary && spec.action !is ImeKeyAction.Space + val baseSize = when { + isSingleChar -> minOf(dpf(21f), h * 0.46f) + displayText.length <= 2 -> minOf(dpf(16f), h * 0.36f) + else -> minOf(dpf(14f), h * 0.32f) + }.coerceAtLeast(dpf(10.5f)) + primaryPaint.textSize = baseSize + + // Shrink horizontally if needed so wide labels ("123", "Return", "下一项") never clip. + val maxTextWidth = (w - dpf(8f)).coerceAtLeast(dpf(10f)) + val measured = primaryPaint.measureText(displayText) + if (measured > maxTextWidth && measured > 0f) { + primaryPaint.textSize = (baseSize * (maxTextWidth / measured)).coerceAtLeast(dpf(9.5f)) + } + + val fm = primaryPaint.fontMetrics + val opticalShift = if (secondary != null) dpf(2.2f) else 0f + val baseline = cy + opticalShift - (fm.ascent + fm.descent) / 2f + canvas.drawText(displayText, cx, baseline, primaryPaint) + } + + private fun drawBackspaceIcon(canvas: Canvas, cx: Float, cy: Float, side: Float) { + val scale = (side * 0.22f).coerceIn(dpf(7f), dpf(11.5f)) + iconPaint.color = palette.text + iconPaint.style = Paint.Style.STROKE + iconPaint.strokeWidth = dpf(1.8f) + path.reset() + path.moveTo(cx - scale * 1.15f, cy) + path.lineTo(cx - scale * 0.45f, cy - scale * 0.78f) + path.lineTo(cx + scale * 1.15f, cy - scale * 0.78f) + path.lineTo(cx + scale * 1.15f, cy + scale * 0.78f) + path.lineTo(cx - scale * 0.45f, cy + scale * 0.78f) + path.close() + canvas.drawPath(path, iconPaint) + + val xOff = scale * 0.34f + val xCenter = cx + scale * 0.30f + canvas.drawLine(xCenter - xOff, cy - xOff, xCenter + xOff, cy + xOff, iconPaint) + canvas.drawLine(xCenter + xOff, cy - xOff, xCenter - xOff, cy + xOff, iconPaint) + } + + private fun drawShiftIcon(canvas: Canvas, cx: Float, cy: Float, side: Float) { + val s = (side * 0.21f).coerceIn(dpf(7f), dpf(11f)) + val filled = currentLetterCase != ImeLetterCase.LOWER + val caps = currentLetterCase == ImeLetterCase.CAPS_LOCK + val yOffset = if (caps) -dpf(1.8f) else 0f + val center = cy + yOffset + path.reset() + path.moveTo(cx, center - s * 1.05f) + path.lineTo(cx + s * 1.05f, center + s * 0.05f) + path.lineTo(cx + s * 0.48f, center + s * 0.05f) + path.lineTo(cx + s * 0.48f, center + s * 0.88f) + path.lineTo(cx - s * 0.48f, center + s * 0.88f) + path.lineTo(cx - s * 0.48f, center + s * 0.05f) + path.lineTo(cx - s * 1.05f, center + s * 0.05f) + path.close() + iconPaint.color = if (filled) palette.accent else palette.text + iconPaint.style = if (filled) Paint.Style.FILL_AND_STROKE else Paint.Style.STROKE + iconPaint.strokeWidth = dpf(1.7f) + canvas.drawPath(path, iconPaint) + if (caps) { + iconPaint.style = Paint.Style.STROKE + iconPaint.strokeWidth = dpf(2.2f) + canvas.drawLine(cx - s * 0.65f, center + s * 1.32f, cx + s * 0.65f, center + s * 1.32f, iconPaint) + } + } + + private fun drawLanguageBadge(canvas: Canvas, cx: Float, cy: Float, w: Float, h: Float) { + val pinyin = currentLanguage == ImeTypingLanguage.PINYIN + val main = if (pinyin) "中" else "英" + val sub = if (pinyin) "/英" else "/中" + val mainSize = minOf(dpf(15.5f), h * 0.36f, w * 0.36f).coerceAtLeast(dpf(10.5f)) + val subSize = (mainSize * 0.72f).coerceAtLeast(dpf(8.5f)) + + primaryPaint.textAlign = Paint.Align.LEFT + primaryPaint.typeface = Typeface.DEFAULT_BOLD + primaryPaint.color = palette.text + primaryPaint.textSize = mainSize + val mainW = primaryPaint.measureText(main) + + secondaryPaint.textAlign = Paint.Align.LEFT + secondaryPaint.alpha = 255 + secondaryPaint.color = palette.secondaryText + secondaryPaint.textSize = subSize + val subW = secondaryPaint.measureText(sub) + + val totalW = mainW + subW + val startX = cx - totalW / 2f + val fm = primaryPaint.fontMetrics + val baseline = cy - (fm.ascent + fm.descent) / 2f + canvas.drawText(main, startX, baseline, primaryPaint) + canvas.drawText(sub, startX + mainW, baseline, secondaryPaint) + + // Restore alignments for subsequent uses. + primaryPaint.textAlign = Paint.Align.CENTER + secondaryPaint.textAlign = Paint.Align.RIGHT + } + + private fun blendPressed(color: Int): Int { + val r = ((Color.red(color) * 85) / 100).coerceIn(0, 255) + val g = ((Color.green(color) * 85) / 100).coerceIn(0, 255) + val b = ((Color.blue(color) * 85) / 100).coerceIn(0, 255) + return Color.argb(255, r, g, b) + } + } + + private fun accessibilityLabel(spec: ImeKeySpec): String = when (spec.action) { + ImeKeyAction.Backspace -> if (english) "Backspace" else "退格" + ImeKeyAction.Shift -> if (spec.label == "⇪") { + if (english) "Caps lock" else "大写锁定" + } else if (english) "Shift" else "大小写" + ImeKeyAction.Space -> if (english) "Space, hold to speak" else "空格,按住说话" + ImeKeyAction.Language -> if (english) "Switch language" else "切换中英文" + else -> spec.label + } + + /** Owns key hit testing, multi-touch rollover, swipe gestures, timers; children remain accessible buttons. */ + private inner class KeyGrid(context: Context) : ViewGroup(context) { + private val handler = Handler(Looper.getMainLooper()) + private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat() + private var rows = emptyList>() + private val keys = linkedMapOf() + private fun specOf(view: KeyCapView?): ImeKeySpec? = if (view == null) null else keys[view] + private var insetSecondRow = false + private var pressed: KeyCapView? = null + private var downX = 0f + private var downY = 0f + private var longPressed = false + private var swipeUpSecondary = false + private var cursorSliding = false + private var cursorAnchorX = 0f + private var backspaceSwiping = false + private var repeating = false + private var pointerActive = false + private var voiceRejected = false + private var activePointer = -1 + private val repeat = object : Runnable { + override fun run() { + if (pointerActive && specOf(pressed)?.action == ImeKeyAction.Backspace && !backspaceSwiping && isAttachedToWindow) { + repeating = true + onAction(ImeKeyAction.Backspace) + onFeedback() + handler.postDelayed(this, policy.repeatIntervalMs) + } + } + } + private val hold = Runnable { + val spec = specOf(pressed) + if (pointerActive && spec?.action == ImeKeyAction.Space && !cursorSliding && isAttachedToWindow) { + longPressed = true + // Set before invoking the host, whose callbacks may render synchronously. + holdingVoice = true + voiceRejected = !onVoiceStart() + if (voiceRejected) { + holdingVoice = false + android.widget.Toast.makeText(context, voiceMessage.text, android.widget.Toast.LENGTH_SHORT).show() + } + renderVoice(voiceMessage.text.toString(), listening, processing) + } else if (pointerActive && spec?.secondary != null && !swipeUpSecondary && isAttachedToWindow) { + longPressed = true + pressed?.activeOverride = spec.secondary + showPreview(pressed, spec.secondary, accented = true) + onFeedback() + } + } + + init { + clipChildren = false + clipToPadding = false + } + + fun refreshKeyVisuals() { + for (i in 0 until childCount) { + (getChildAt(i) as? KeyCapView)?.apply { + syncMetadata() + invalidate() + } + } + } + + fun setKeys(layout: List>, inset: Boolean) { + val sameGeometry = insetSecondRow == inset && + rows.map { row -> row.map { it.id to it.weight } } == layout.map { row -> row.map { it.id to it.weight } } + if (sameGeometry && childCount == layout.sumOf { it.size }) { + rows = layout + layout.flatten().forEachIndexed { index, spec -> + val key = getChildAt(index) as KeyCapView + keys[key] = spec + val preserveSecondary = key === pressed && (longPressed || swipeUpSecondary) && spec.secondary != null + key.updateSpec(spec) + if (preserveSecondary) key.activeOverride = spec.secondary + } + if (pressed != null && !longPressed && !swipeUpSecondary) showPreview(pressed) + return + } + cancelTouch() + removeAllViews() + keys.clear() + rows = layout + insetSecondRow = inset + layout.flatten().forEach { spec -> + val key = KeyCapView(context, spec).apply { + setOnClickListener { + if (!listening && !processing) keys[this]?.let { onAction(it.action) } + } + } + keys[key] = spec + addView(key) + } + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) + val height = MeasureSpec.getSize(heightMeasureSpec) + val rowHeight = height.toFloat() / rows.size.coerceAtLeast(1) + var index = 0 + rows.forEachIndexed { rowIndex, row -> + val unit = width.toFloat() / (row.sumOf { it.weight.toDouble() }.toFloat() + if (insetSecondRow && rowIndex == 1) 1f else 0f) + row.forEach { spec -> + val key = getChildAt(index++) + val keyWidth = (unit * spec.weight - dp(5)).toInt().coerceAtLeast(1) + val keyHeight = (rowHeight - dp(7)).toInt().coerceAtLeast(1) + key.measure( + MeasureSpec.makeMeasureSpec(keyWidth, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(keyHeight, MeasureSpec.EXACTLY), + ) + } + } + setMeasuredDimension(width, height) + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + val rowHeight = height.toFloat() / rows.size.coerceAtLeast(1) + var index = 0 + rows.forEachIndexed { rowIndex, row -> + val inset = insetSecondRow && rowIndex == 1 + val unit = width.toFloat() / (row.sumOf { it.weight.toDouble() }.toFloat() + if (inset) 1f else 0f) + var x = if (inset) unit / 2 else 0f + row.forEach { spec -> + val key = getChildAt(index++) + val keyLeft = (x + dp(2)).toInt() + val keyTop = (rowIndex * rowHeight + dp(3)).toInt() + key.layout(keyLeft, keyTop, keyLeft + key.measuredWidth, keyTop + key.measuredHeight) + x += unit * spec.weight + } + } + } + + override fun onInterceptTouchEvent(event: MotionEvent) = true + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (event.actionMasked == MotionEvent.ACTION_CANCEL) { + cancelTouch() + return true + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + cancelTouch() + if (listening || processing) return true + beginPointer(event.getPointerId(0), event.x, event.y) + } + MotionEvent.ACTION_POINTER_DOWN -> { + if (listening || processing || holdingVoice) return true + // Multi-touch rollover: commit the held text key immediately and track the new finger. + val newIndex = event.actionIndex + val newPointerId = event.getPointerId(newIndex) + val newX = event.getX(newIndex) + val newY = event.getY(newIndex) + val prevSpec = specOf(pressed) + val prevSecondary = swipeUpSecondary || longPressed + val prevCanRollover = pointerActive && !cursorSliding && !backspaceSwiping && !repeating && + !voiceRejected && prevSpec != null && prevSpec.action is ImeKeyAction.Text + if (prevCanRollover) { + finishTouch() + if (prevSecondary && prevSpec.secondary != null) { + onAction(ImeKeyAction.Text(prevSpec.secondary)) + } else { + onAction(prevSpec.action) + } + beginPointer(newPointerId, newX, newY) + } else if (!cursorSliding && !backspaceSwiping) { + cancelTouch() + } + } + MotionEvent.ACTION_MOVE -> { + if (!pointerActive) return true + val index = event.findPointerIndex(activePointer) + if (index < 0) return true + val x = event.getX(index) + val y = event.getY(index) + val spec = specOf(pressed) + + if (holdingVoice) { + voiceCancelled = downY - y > dp(48) + renderVoice(voiceMessage.text.toString(), listening, processing) + } else if (spec?.action == ImeKeyAction.Space) { + val dx = x - downX + val dy = y - downY + if (!cursorSliding && !longPressed && abs(dx) > maxOf(touchSlop * 1.4f, dpf(14f)) && abs(dx) > abs(dy) * 1.2f) { + handler.removeCallbacks(hold) + cursorSliding = true + cursorAnchorX = downX + pressed?.cursorSlideActive = true + } + if (cursorSliding) { + val step = dpf(14f).coerceAtLeast(1f) + while (x - cursorAnchorX >= step) { + cursorAnchorX += step + onCursorMove(1) + onFeedback() + } + while (cursorAnchorX - x >= step) { + cursorAnchorX -= step + onCursorMove(-1) + onFeedback() + } + } + } else if (spec?.action == ImeKeyAction.Backspace) { + val dx = x - downX + val dy = y - downY + if (!repeating && !backspaceSwiping && -dx > dpf(38f) && abs(dx) > abs(dy) * 1.3f) { + handler.removeCallbacks(repeat) + backspaceSwiping = true + onFeedback() + } + } else if (!longPressed && !repeating) { + val dx = x - downX + val dy = y - downY + if (spec?.secondary != null && -dy > maxOf(dpf(26f), touchSlop * 1.8f) && abs(dy) > abs(dx) * 1.15f) { + if (!swipeUpSecondary) { + handler.removeCallbacks(hold) + swipeUpSecondary = true + pressed?.activeOverride = spec.secondary + showPreview(pressed, spec.secondary, accented = true) + onFeedback() + } + } else if (swipeUpSecondary) { + if (-dy < dpf(14f)) { + swipeUpSecondary = false + pressed?.activeOverride = null + showPreview(pressed) + } + } else { + val target = hit(x, y) + if (target != pressed) { + handler.removeCallbacks(hold) + handler.removeCallbacks(repeat) + pressed?.isPressed = false + pressed?.activeOverride = null + // Only letter-to-letter drags retarget; functional-key drags cancel. + pressed = if (specOf(pressed)?.action is ImeKeyAction.Text && specOf(target)?.action is ImeKeyAction.Text) target else null + pressed?.isPressed = true + showPreview(pressed) + } + } + } + } + MotionEvent.ACTION_POINTER_UP -> { + val liftedIndex = event.actionIndex + val liftedId = event.getPointerId(liftedIndex) + if (pointerActive && liftedId == activePointer) { + completeActivePointer(event.getX(liftedIndex), event.getY(liftedIndex)) + } + } + MotionEvent.ACTION_UP -> { + if (!pointerActive) return true + val index = event.findPointerIndex(activePointer) + if (index < 0) { + finishTouch() + return true + } + completeActivePointer(event.getX(index), event.getY(index)) + } + } + return true + } + + private fun beginPointer(pointerId: Int, x: Float, y: Float) { + activePointer = pointerId + pointerActive = true + downX = x + downY = y + pressed = hit(x, y) + pressed?.isPressed = true + showPreview(pressed) + parent?.requestDisallowInterceptTouchEvent(true) + onFeedback() + when (specOf(pressed)?.action) { + ImeKeyAction.Backspace -> handler.postDelayed(repeat, ViewConfiguration.getLongPressTimeout().toLong()) + ImeKeyAction.Space -> handler.postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()) + is ImeKeyAction.Text -> if (specOf(pressed)?.secondary != null) { + handler.postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()) + } + else -> Unit + } + } + + private fun completeActivePointer(x: Float, y: Float) { + val spec = specOf(pressed) + val wasVoice = holdingVoice + val cancelled = voiceCancelled + val didRepeat = repeating + val wasLongPress = longPressed + val wasSwipeSecondary = swipeUpSecondary + val wasCursorSlide = cursorSliding + val wasBackspaceSwipe = backspaceSwiping + val rejected = voiceRejected + val terminal = hit(x, y) + val hadTarget = terminal == pressed && pressed != null + finishTouch() + when { + wasVoice -> onVoiceEnd(cancelled) + wasCursorSlide -> Unit + wasBackspaceSwipe -> onDeleteWord() + wasSwipeSecondary && spec?.secondary != null -> onAction(ImeKeyAction.Text(spec.secondary)) + !rejected && hadTarget && spec != null && !didRepeat -> { + if (wasLongPress && spec.secondary != null) onAction(ImeKeyAction.Text(spec.secondary)) + else if (!wasLongPress) onAction(spec.action) + } + } + } + + private fun showPreview(key: KeyCapView?, override: String? = null, accented: Boolean = false) { + val spec = specOf(key) + if (key == null || spec?.action !is ImeKeyAction.Text || holdingVoice) { + preview.visibility = GONE + return + } + val text = override ?: spec.label + preview.show(text, accented) + preview.x = (key.left + key.width / 2f - dp(27)).coerceIn(0f, (width - dp(54)).coerceAtLeast(0).toFloat()) + // Float above Row 1 into the candidate strip area instead of covering the key. + preview.y = (key.top - dp(58)).toFloat() + preview.visibility = VISIBLE + preview.bringToFront() + } + + private fun hit(x: Float, y: Float): KeyCapView? { + if (x < 0 || y < 0 || x >= width || y >= height) return null + // Include the visual gaps in the nearest key's target without overlapping rows. + val rowIndex = (y * rows.size / height.coerceAtLeast(1)).toInt().coerceIn(0, rows.lastIndex.coerceAtLeast(0)) + val row = rows.getOrNull(rowIndex) ?: return null + val offset = rows.take(rowIndex).sumOf { it.size } + return row.indices.mapNotNull { getChildAt(offset + it) as? KeyCapView } + .minByOrNull { abs(x - (it.left + it.right) / 2f) } + } + + private fun finishTouch() { + handler.removeCallbacks(hold) + handler.removeCallbacks(repeat) + pressed?.isPressed = false + pressed?.activeOverride = null + pressed?.cursorSlideActive = false + preview.visibility = GONE + pressed = null + pointerActive = false + activePointer = -1 + longPressed = false + swipeUpSecondary = false + cursorSliding = false + backspaceSwiping = false + repeating = false + holdingVoice = false + voiceCancelled = false + voiceRejected = false + } + + fun cancelTouch() { + val wasVoice = holdingVoice + finishTouch() + if (wasVoice) onVoiceEnd(true) + } + + override fun onDetachedFromWindow() { + cancelTouch() + super.onDetachedFromWindow() + } + } + + /** Real sample history, not a time-driven synthetic sine wave. */ + private inner class LevelView(context: Context) : View(context) { + private val samples = FloatArray(25) + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = palette.accent; strokeCap = Paint.Cap.ROUND } + fun push(value: Float) { + samples.copyInto(samples, 0, 1) + samples[samples.lastIndex] = if (value.isFinite()) value.coerceIn(0f, 1f) else 0f + invalidate() + } + fun clear() { samples.fill(0f); invalidate() } + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + paint.strokeWidth = dp(3).toFloat() + val spacing = width.toFloat() / samples.size + samples.forEachIndexed { index, value -> + val amplitude = if (value < 0.02f) 0f else value + val halfHeight = (height * 0.42f * amplitude).coerceAtLeast(dp(1).toFloat()) + val x = spacing * (index + 0.5f) + canvas.drawLine(x, height / 2f - halfHeight, x, height / 2f + halfHeight, paint) + } + } + } +} diff --git a/openless-all/android/kotlin/ImeVoiceFramePolicy.kt b/openless-all/android/kotlin/ImeVoiceFramePolicy.kt new file mode 100644 index 000000000..58297d2cd --- /dev/null +++ b/openless-all/android/kotlin/ImeVoiceFramePolicy.kt @@ -0,0 +1,32 @@ +package com.openless.app + +/** Capsule frames are global; only the IME result channel may complete an IME request. */ +internal enum class ImeVoiceFrameAction { + EXTERNAL, IGNORE, RECORDING, PROCESSING, WAIT_RESULT, EXTERNALLY_COMPLETED, CANCELLED, ERROR, +} + +internal object ImeVoiceFramePolicy { + /** No second stop/mode mutation once a buffered frame shows finalization. */ + fun canApplyQueuedStartActions(bufferedState: String?): Boolean = bufferedState !in setOf( + "transcribing", "polishing", "done", "cancelled", "error", + ) + + fun resolve( + ownsRequest: Boolean, + captureEnded: Boolean, + state: String, + stopSubmitted: Boolean = captureEnded, + ): ImeVoiceFrameAction { + if (!ownsRequest) return ImeVoiceFrameAction.EXTERNAL + return when (state) { + "recording" -> if (captureEnded) ImeVoiceFrameAction.IGNORE else ImeVoiceFrameAction.RECORDING + "transcribing", "polishing" -> ImeVoiceFrameAction.PROCESSING + // A global done cue may precede the request-scoped text delivery. + // Do not open another start window and then drop the prior result. + "done" -> if (stopSubmitted) ImeVoiceFrameAction.WAIT_RESULT else ImeVoiceFrameAction.EXTERNALLY_COMPLETED + "cancelled" -> ImeVoiceFrameAction.CANCELLED + "error" -> ImeVoiceFrameAction.ERROR + else -> ImeVoiceFrameAction.IGNORE + } + } +} diff --git a/openless-all/android/kotlin/ImeVoicePanel.kt b/openless-all/android/kotlin/ImeVoicePanel.kt new file mode 100644 index 000000000..bf4476235 --- /dev/null +++ b/openless-all/android/kotlin/ImeVoicePanel.kt @@ -0,0 +1,664 @@ +package com.openless.app + +import android.animation.ValueAnimator +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF +import android.graphics.drawable.GradientDrawable +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.TextView +import kotlin.math.abs +import kotlin.math.min + +/** + * 新版独立语音面板与其主按钮。 + * + * 只做展示与手势判定:不持有 Service、不读 InputConnection、不触达 JNI, + * 所有业务动作都通过构造参数里的回调交给宿主。 + * + * 手势(均在 UP 时提交一次,阈值取系统 touch slop 与 28dp 的较大值): + * - 轻点 → TAP + * - 上滑 → RAW + * - 左滑 → QUICK_NOTE + * - 右滑 → CLOUD_NOTE + * - 下滑 → CANCEL(仅录音中;非录音时忽略) + * ACTION_CANCEL / 多指只清除当前手势,不产生任何手势回调。 + */ +internal enum class ImeVoiceGesture { TAP, RAW, QUICK_NOTE, CLOUD_NOTE, REVIEW_CLOUD, CANCEL } + +internal class ImeVoiceButton( + context: Context, + private val palette: ImePalette, + private val onGesture: (ImeVoiceGesture) -> Unit, +) : View(context) { + var isRecording: Boolean = false + set(value) { + if (field == value) return + field = value + if (!value) { + samples.fill(0f) + sampleCount = 0 + } + pressedState = false + invalidate() + } + + var isProcessing: Boolean = false + set(value) { + if (field == value) return + field = value + invalidate() + } + + var rawModeActive: Boolean = false + set(value) { + if (field == value) return + field = value + invalidate() + } + + var quickNoteActive: Boolean = false + set(value) { + if (field == value) return + field = value + invalidate() + } + + var cloudNoteActive: Boolean = false + set(value) { + if (field == value) return + field = value + invalidate() + } + + /** 由宿主按真实采集电平写入(0..1);写入即进入环形历史,无写入则保持静止。 */ + var audioLevel: Float = 0f + set(value) { + val level = if (value.isFinite()) value.coerceIn(0f, 1f) else 0f + field = level + if (isRecording) pushSample(level) + invalidate() + } + + private val samples = FloatArray(SAMPLE_COUNT) + private var sampleCount = 0 + private var pressedState = false + private var processingPhase = 0 + + private var downX = 0f + private var downY = 0f + private var pointerId = -1 + private var tracking = false + private var gestureCommitted = false + + private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val glyphPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + private val glyphStroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeCap = Paint.Cap.ROUND + } + + init { + setWillNotDraw(false) + isClickable = true + isFocusable = true + contentDescription = "语音输入 / Voice input" + } + + private fun pushSample(value: Float) { + samples.copyInto(samples, 0, 1) + samples[samples.lastIndex] = value + if (sampleCount < SAMPLE_COUNT) sampleCount++ + } + + // --- 手势 --- + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (!isEnabled) { clearGesture(); return true } + if (event.pointerCount != 1) { + // 多指:只清除当前手势,绝不误提交。 + clearGesture() + return true + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + clearGesture() + downX = event.x + downY = event.y + pointerId = event.getPointerId(0) + tracking = true + pressedState = true + invalidate() + return true + } + + MotionEvent.ACTION_MOVE -> return tracking + + MotionEvent.ACTION_UP -> { + if (!tracking || event.getPointerId(0) != pointerId) { + clearGesture() + return true + } + val gesture = resolveGesture(event.x - downX, event.y - downY) + clearGesture() + if (gesture != null && !gestureCommitted) { + gestureCommitted = true + if (gesture == ImeVoiceGesture.TAP) performClick() else onGesture(gesture) + } + return true + } + + MotionEvent.ACTION_CANCEL -> { + clearGesture() + return true + } + } + return super.onTouchEvent(event) + } + + override fun performClick(): Boolean { + if (!isEnabled) return false + super.performClick() + onGesture(ImeVoiceGesture.TAP) + return true + } + + private fun resolveGesture(dx: Float, dy: Float): ImeVoiceGesture? { + val threshold = maxOf(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), dp(28).toFloat()) + val horizontal = abs(dx) + val vertical = abs(dy) + return when { + horizontal < threshold && vertical < threshold -> ImeVoiceGesture.TAP + vertical >= horizontal && dy < 0f -> if (isRecording && cloudNoteActive) ImeVoiceGesture.REVIEW_CLOUD else ImeVoiceGesture.RAW + vertical >= horizontal && dy > 0f -> if (isRecording) ImeVoiceGesture.CANCEL else null + dx < 0f -> ImeVoiceGesture.QUICK_NOTE + else -> ImeVoiceGesture.CLOUD_NOTE + } + } + + private fun clearGesture() { + tracking = false + gestureCommitted = false + pointerId = -1 + pressedState = false + invalidate() + } + + override fun onDetachedFromWindow() { + clearGesture() + super.onDetachedFromWindow() + } + + // --- 绘制 --- + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val cx = width / 2f + val cy = height / 2f + val radius = min(width, height) / 2f - dp(5) + if (radius <= 0f) return + + fillPaint.color = if (pressedState) palette.pressed else palette.key + canvas.drawCircle(cx, cy, radius, fillPaint) + + strokePaint.color = ringColor() + strokePaint.strokeWidth = dp(3).toFloat() + canvas.drawCircle(cx, cy, radius - dp(2), strokePaint) + + when { + isProcessing -> drawProcessing(canvas, cx, cy, radius) + isRecording || sampleCount > 0 -> drawWaveform(canvas, cx, cy, radius) + else -> drawMicrophone(canvas, cx, cy, radius) + } + } + + private fun ringColor(): Int = when { + cloudNoteActive -> palette.error + rawModeActive || quickNoteActive || isRecording -> palette.accent + else -> palette.separator + } + + private fun drawMicrophone(canvas: Canvas, cx: Float, cy: Float, radius: Float) { + val bodyWidth = radius * 0.34f + val bodyHeight = radius * 0.56f + glyphPaint.color = palette.text + val body = RectF( + cx - bodyWidth / 2f, + cy - radius * 0.30f, + cx + bodyWidth / 2f, + cy - radius * 0.30f + bodyHeight, + ) + canvas.drawRoundRect(body, bodyWidth / 2f, bodyWidth / 2f, glyphPaint) + + glyphStroke.color = palette.text + glyphStroke.strokeWidth = dp(2).toFloat() + val cradle = RectF( + cx - bodyWidth * 0.85f, + cy - radius * 0.18f, + cx + bodyWidth * 0.85f, + cy + radius * 0.22f, + ) + canvas.drawArc(cradle, 0f, 180f, false, glyphStroke) + canvas.drawLine(cx, cy + radius * 0.22f, cx, cy + radius * 0.34f, glyphStroke) + } + + private fun drawWaveform(canvas: Canvas, cx: Float, cy: Float, radius: Float) { + if (sampleCount == 0) return + val span = radius * 1.28f + val step = span / SAMPLE_COUNT + val startX = cx - span / 2f + step / 2f + val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = palette.accent + style = Paint.Style.STROKE + strokeCap = Paint.Cap.ROUND + strokeWidth = (step * 0.5f).coerceAtLeast(dp(2).toFloat()) + } + val maxHalf = radius * 0.52f + for (index in 0 until SAMPLE_COUNT) { + val value = samples[index] + val half = (value * maxHalf).coerceIn(dp(1).toFloat(), maxHalf) + val x = startX + step * index + canvas.drawLine(x, cy - half, x, cy + half, stroke) + } + } + + private fun drawProcessing(canvas: Canvas, cx: Float, cy: Float, radius: Float) { + val animatorsEnabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + ValueAnimator.areAnimatorsEnabled() + } else { + true + } + val dotRadius = dp(5).toFloat() + val gap = radius * 0.42f + glyphPaint.color = palette.accent + for (index in 0 until 3) { + val alpha = if (animatorsEnabled) { + val distance = (processingPhase - index + 3) % 3 + when (distance) { + 0 -> 255 + 1 -> 150 + else -> 80 + } + } else { + 170 + } + glyphPaint.alpha = alpha + val x = cx + (index - 1) * gap + canvas.drawCircle(x, cy, dotRadius, glyphPaint) + } + glyphPaint.alpha = 255 + if (animatorsEnabled && isAttachedToWindow) { + processingPhase = (processingPhase + 1) % 3 + postInvalidateDelayed(120L) + } + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + private companion object { + const val SAMPLE_COUNT = 21 + } +} + +internal class ImeVoicePanel( + context: Context, + private val palette: ImePalette, + header: View, + private val englishUi: Boolean, + private val onVoiceGesture: (ImeVoiceGesture) -> Unit, + private val onUndo: () -> Unit, + private val onEdit: () -> Unit, + private val onEnter: () -> Unit, + private val onBackspace: () -> Unit, + private val onAt: () -> Unit, + private val onRestart: () -> Unit, + private val onFeedback: () -> Unit = {}, + interactionPolicy: ImeInteractionPolicy = ImeInteractionPolicy.DEFAULT, +) : LinearLayout(context) { + + val status: TextView + val modeHint: TextView + val warning: TextView + val voiceButton: ImeVoiceButton + val undo: TextView + val edit: TextView + val resultRow: LinearLayout + val cancel: TextView + + private val body: FrameLayout + private val modeHintRow: LinearLayout + private val handler = Handler(Looper.getMainLooper()) + private var policy = interactionPolicy + private var backspaceRepeating = false + private var backspacePressed = false + private var suppressFooterClickFeedback = false + private val footerKeys = ArrayList() + private val modeKeys = ArrayList() + + init { + orientation = VERTICAL + setBackgroundColor(palette.surface) + + addView(header, LayoutParams(LayoutParams.MATCH_PARENT, dp(40))) + + status = textView("", 13f, palette.secondaryText).apply { + contentDescription = if (englishUi) "Voice status" else "语音状态" + } + addView(status, LayoutParams(LayoutParams.MATCH_PARENT, dp(30))) + + modeHint = textView(defaultModeHint(), 11f, palette.secondaryText) + modeHintRow = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER + addView(modeHint, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + } + addView(modeHintRow, LayoutParams(LayoutParams.MATCH_PARENT, dp(22))) + + val chips = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER + setPadding(dp(8), dp(2), dp(8), dp(2)) + } + fun chipParams() = LayoutParams(LayoutParams.WRAP_CONTENT, dp(28)).apply { + marginStart = dp(4) + marginEnd = dp(4) + } + chips.addView(modeChip(if (englishUi) "RAW" else "RAW") { onVoiceGesture(ImeVoiceGesture.RAW) }, chipParams()) + chips.addView(modeChip(if (englishUi) "Quick note" else "速记") { + onVoiceGesture(ImeVoiceGesture.QUICK_NOTE) + }, chipParams()) + chips.addView(modeChip(if (englishUi) "Cloud note" else "云笔记") { + onVoiceGesture(ImeVoiceGesture.CLOUD_NOTE) + }, chipParams()) + cancel = chip(if (englishUi) "Cancel" else "取消") { onVoiceGesture(ImeVoiceGesture.CANCEL) } + cancel.contentDescription = if (englishUi) "Cancel dictation" else "取消听写" + cancel.isEnabled = false + cancel.alpha = 0.4f + chips.addView(cancel, chipParams()) + addView(chips, LayoutParams(LayoutParams.MATCH_PARENT, dp(34))) + + body = FrameLayout(context) + voiceButton = ImeVoiceButton(context, palette, onVoiceGesture).apply { + contentDescription = if (englishUi) "Voice input" else "语音输入" + } + body.addView( + voiceButton, + FrameLayout.LayoutParams(dp(150), dp(150), Gravity.CENTER), + ) + + warning = textView(defaultWarning(), 12f, palette.error).apply { + gravity = Gravity.CENTER + visibility = GONE + isClickable = true + isFocusable = true + setPadding(dp(8), dp(2), dp(8), dp(2)) + contentDescription = defaultWarning() + setOnClickListener { onRestart() } + } + body.addView( + warning, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.WRAP_CONTENT, + FrameLayout.LayoutParams.WRAP_CONTENT, + Gravity.TOP or Gravity.CENTER_HORIZONTAL, + ), + ) + + undo = actionText(if (englishUi) "Undo" else "撤销", onUndo) + edit = actionText(if (englishUi) "Edit" else "编辑", onEdit) + resultRow = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER + visibility = GONE + setPadding(dp(8), dp(2), dp(8), dp(2)) + background = GradientDrawable().apply { + cornerRadius = dp(14).toFloat() + setColor(palette.auxiliary) + } + addView(undo, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) + addView(edit, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) + } + body.addView( + resultRow, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.WRAP_CONTENT, + FrameLayout.LayoutParams.WRAP_CONTENT, + Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, + ), + ) + addView(body, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + + val footer = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER + setPadding(dp(6), dp(3), dp(6), dp(3)) + } + footer.addView(footerKey("@", onAt, repeatOnHold = false), footerParams(1f)) + footer.addView( + footerKey(if (englishUi) "Enter" else "换行", onEnter, repeatOnHold = false), + footerParams(1.6f), + ) + footer.addView( + footerKey("⌫", onBackspace, repeatOnHold = true), + footerParams(1.6f), + ) + addView(footer, LayoutParams(LayoutParams.MATCH_PARENT, dp(46))) + + body.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> resizeVoiceButton() } + resultRow.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> resizeVoiceButton() } + warning.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> resizeVoiceButton() } + } + + override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { + super.onSizeChanged(width, height, oldWidth, oldHeight) + // 220dp 级别的小屏:收起提示行,把高度让给中心按钮,避免与 footer 重叠。 + val compact = height < dp(300) + val wanted = if (compact) View.GONE else View.VISIBLE + if (modeHintRow.visibility != wanted) { + modeHintRow.visibility = wanted + requestLayout() + } + resizeVoiceButton() + } + + private fun resizeVoiceButton() { + val bodyHeight = body.height + if (bodyHeight <= 0) return + val resultHeight = if (resultRow.visibility == View.VISIBLE) resultRow.height else 0 + val warningHeight = if (warning.visibility == View.VISIBLE) warning.height else 0 + val available = bodyHeight - dp(8) - resultHeight - warningHeight + val size = available.coerceIn(0, dp(190)) + if (size <= 0) return + val params = voiceButton.layoutParams as? FrameLayout.LayoutParams ?: return + if (params.width != size || params.height != size) { + params.width = size + params.height = size + voiceButton.layoutParams = params + } + } + + fun renderAvailability( + recording: Boolean, + processing: Boolean, + cancellable: Boolean = recording || processing, + canUseVoiceModes: Boolean = recording || !processing, + ) { + cancel.isEnabled = cancellable + modeKeys.forEach { key -> + if (!canUseVoiceModes) { key.isPressed = false; key.cancelPendingInputEvents() } + key.isEnabled = canUseVoiceModes + key.alpha = if (canUseVoiceModes) 1f else 0.4f + } + val editingAllowed = !recording && !processing + if (!editingAllowed) stopBackspaceRepeat() + footerKeys.forEach { key -> + key.isEnabled = editingAllowed + key.isPressed = false + key.alpha = if (editingAllowed) 1f else 0.4f + } + cancel.alpha = if (cancel.isEnabled) 1f else 0.4f + voiceButton.contentDescription = when { + recording -> if (englishUi) "Finish dictation" else "结束听写" + processing -> if (englishUi) "Processing dictation" else "正在处理听写" + else -> if (englishUi) "Start dictation" else "开始听写" + } + } + + /** 下发统一互动策略:值变化时先中止旧 repeat/按下态;相同值不影响进行中的交互。 */ + fun applyInteractionPolicy(policy: ImeInteractionPolicy) { + if (policy == this.policy) return + stopBackspaceRepeat() + footerKeys.forEach { key -> + key.isPressed = false + key.cancelPendingInputEvents() + } + suppressFooterClickFeedback = false + this.policy = policy + } + + private fun defaultModeHint(): String = if (englishUi) { + "Swipe ↑ RAW · ← Quick note · → Cloud · ↓ Cancel" + } else { + "上滑 RAW · 左滑速记 · 右滑云笔记 · 下滑取消" + } + + private fun defaultWarning(): String = if (englishUi) { + "Voice unavailable. Tap to retry" + } else { + "语音暂不可用,点击重试" + } + + private fun textView(value: String, size: Float, color: Int): TextView = TextView(context).apply { + text = value + textSize = size + gravity = Gravity.CENTER + setTextColor(color) + includeFontPadding = false + maxLines = 1 + } + + private fun modeChip(label: String, action: () -> Unit): TextView = chip(label, action).also { modeKeys += it } + + private fun chip(label: String, action: () -> Unit): TextView = textView(label, 12f, palette.text).apply { + setPadding(dp(14), 0, dp(14), 0) + background = GradientDrawable().apply { + cornerRadius = dp(15).toFloat() + setColor(palette.auxiliary) + } + isClickable = true + isFocusable = true + contentDescription = label + setOnClickListener { action() } + } + + private fun actionText(label: String, action: () -> Unit): TextView = + textView(label, 13f, palette.accent).apply { + setPadding(dp(14), dp(6), dp(14), dp(6)) + isClickable = true + isFocusable = true + contentDescription = label + setOnClickListener { action() } + } + + private fun footerKey(label: String, action: () -> Unit, repeatOnHold: Boolean): TextView = + textView(label, 17f, palette.text).apply { + footerKeys.add(this) + gravity = Gravity.CENTER + background = GradientDrawable().apply { + cornerRadius = dp(6).toFloat() + setColor(palette.key) + } + isClickable = true + isFocusable = true + contentDescription = label + setOnClickListener { + // 触摸路径的 DOWN 已反馈过(suppress 时不再重复);无障碍 click 没有 DOWN,这里补一次。 + if (!suppressFooterClickFeedback) onFeedback() + action() + } + setOnTouchListener { view, event -> + if (!view.isEnabled) return@setOnTouchListener false + if (event.pointerCount != 1 || event.actionMasked == MotionEvent.ACTION_CANCEL) { + stopBackspaceRepeat() + view.isPressed = false + suppressFooterClickFeedback = false + return@setOnTouchListener true + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + stopBackspaceRepeat() + view.isPressed = true + backspacePressed = true + backspaceRepeating = false + onFeedback() + if (repeatOnHold) { + handler.postDelayed(backspaceRepeat(action), ViewConfiguration.getLongPressTimeout().toLong()) + } + true + } + MotionEvent.ACTION_MOVE -> { + if (event.x < 0 || event.y < 0 || event.x >= view.width || event.y >= view.height) { + stopBackspaceRepeat() + view.isPressed = false + } + true + } + MotionEvent.ACTION_UP -> { + val inside = event.x >= 0 && event.y >= 0 && event.x < view.width && event.y < view.height + val commit = backspacePressed && !backspaceRepeating && inside + stopBackspaceRepeat() + view.isPressed = false + if (commit) { + suppressFooterClickFeedback = true + view.performClick() + suppressFooterClickFeedback = false + } + true + } + else -> true + } + } + } + + private fun backspaceRepeat(action: () -> Unit): Runnable = object : Runnable { + override fun run() { + if (!backspacePressed || !isAttachedToWindow) return + backspaceRepeating = true + action() + onFeedback() + // 动作可能同步触发宿主 applyInteractionPolicy(不同值)/禁用/隐藏:排期前重新校验。 + if (backspacePressed && isAttachedToWindow && isShown) { + handler.postDelayed(this, policy.repeatIntervalMs) + } + } + } + + private fun stopBackspaceRepeat() { + handler.removeCallbacksAndMessages(null) + backspacePressed = false + backspaceRepeating = false + } + + private fun footerParams(weight: Float) = LayoutParams(0, dp(38), weight).apply { + marginStart = dp(3) + marginEnd = dp(3) + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + + override fun onDetachedFromWindow() { + stopBackspaceRepeat() + super.onDetachedFromWindow() + } +} diff --git a/openless-all/android/kotlin/ImeVoiceUiState.kt b/openless-all/android/kotlin/ImeVoiceUiState.kt new file mode 100644 index 000000000..cf90f8656 --- /dev/null +++ b/openless-all/android/kotlin/ImeVoiceUiState.kt @@ -0,0 +1,112 @@ +package com.openless.app + +/** + * 语音 UI 的**纯投影**。 + * + * 设计约束(重要): + * - 单向下行:只把宿主(Service)已有的 legacy 状态/switches 映射成可渲染快照, + * **不发送任何命令**,也不回写/修正业务 flags; + * - 状态真实性:`recording`/`processing` 永远如实回显入参 flag,绝不根据字符串 + * (如 "speaking"/"thinking")虚构录音或处理中状态; + * - 可取消性:Webhook 提交(cloudSubmitting)**不承诺可取消**(`canCancel=false`), + * 但允许在其未完成时开始新的录音(`canStart=true`,与旧协议一致); + * - 无 Android SDK 依赖,可直接用 JVM JUnit 验证。 + * + * 说明:`state` 仅用于把终态文案映射为 [ImeVoicePhase],不参与任何业务动作。 + */ +internal enum class ImeVoicePhase { IDLE, STARTING, RECORDING, PROCESSING, SUBMITTING, DONE, CANCELLED, ERROR } + +internal enum class ImeVoiceMode { DICTATION, RAW, QUICK_NOTE, CLOUD_NOTE } + +internal data class ImeVoiceUiSnapshot( + val phase: ImeVoicePhase, + val mode: ImeVoiceMode, + val message: String, + val audioLevel: Float, + val recording: Boolean, + val processing: Boolean, + val editorLocked: Boolean, + val canCancel: Boolean, + val canStart: Boolean, +) + +/** Capabilities only narrow from observed state; they never grant another entry's controls. */ +internal fun ImeVoiceUiSnapshot.withEligibility( + ownsRequest: Boolean, + microphoneGranted: Boolean, + sensitiveField: Boolean, + foreignBusy: Boolean, +): ImeVoiceUiSnapshot = copy( + canCancel = canCancel && ownsRequest, + canStart = canStart && microphoneGranted && !sensitiveField && !foreignBusy, +) + +internal object ImeVoiceUiProjection { + + /** + * 从 legacy 字段投影出 UI 快照(纯函数)。 + * + * 状态优先级(高 → 低):recording(awaitingStart ? STARTING : RECORDING) + * → processing → cloudSubmitting → legacy `state` 终态(done/cancelled/error) + * → IDLE。`state` 中的 "speaking"/"thinking" 在没有真实 flag 时按 IDLE 处理。 + * + * 模式优先级(与现有颜色/强调优先级一致):RAW > QUICK_NOTE > CLOUD_NOTE > DICTATION。 + */ + fun fromLegacy( + state: String, + recording: Boolean, + processing: Boolean, + cloudSubmitting: Boolean, + raw: Boolean, + quickNote: Boolean, + cloud: Boolean, + message: String, + level: Float = 0f, + awaitingStart: Boolean = false, + ): ImeVoiceUiSnapshot { + val phase = when { + recording -> if (awaitingStart) ImeVoicePhase.STARTING else ImeVoicePhase.RECORDING + processing -> ImeVoicePhase.PROCESSING + cloudSubmitting -> ImeVoicePhase.SUBMITTING + else -> terminalPhase(state) + } + val mode = when { + raw -> ImeVoiceMode.RAW + quickNote -> ImeVoiceMode.QUICK_NOTE + cloud || cloudSubmitting -> ImeVoiceMode.CLOUD_NOTE + else -> ImeVoiceMode.DICTATION + } + // 只有真实录音时才展示电平;NaN/Inf/越界一律收敛到 [0,1],其余状态归 0。 + val audioLevel = if (recording && level.isFinite()) level.coerceIn(0f, 1f) else 0f + return ImeVoiceUiSnapshot( + phase = phase, + mode = mode, + message = message, + audioLevel = audioLevel, + recording = recording, + processing = processing, + editorLocked = recording || processing || cloudSubmitting, + canCancel = recording || processing, + canStart = !recording && !processing, + ) + } + + /** 只在没有 recording/processing/cloudSubmitting 真实 flag 时使用。 */ + private fun terminalPhase(state: String): ImeVoicePhase = when (state.trim().lowercase()) { + "done" -> ImeVoicePhase.DONE + "cancelled", "canceled" -> ImeVoicePhase.CANCELLED + "error" -> ImeVoicePhase.ERROR + else -> ImeVoicePhase.IDLE + } +} + +/** + * 一次语音请求的所有权凭证。 + * + * 所有权**不会**因停止采集而自动释放:UI 适配层应保存本对象,直到处理结束、 + * 取消或输入目标失效,再用 [matches] 拒绝迟到/串场的回调。 + */ +internal data class ImeRequestOwner(val epoch: Long, val requestId: Long) { + fun matches(epoch: Long, requestId: Long): Boolean = + this.epoch == epoch && this.requestId == requestId +} diff --git a/openless-all/android/kotlin/OpenLessImeService.kt b/openless-all/android/kotlin/OpenLessImeService.kt index 1f1cda5da..0cc8116d7 100644 --- a/openless-all/android/kotlin/OpenLessImeService.kt +++ b/openless-all/android/kotlin/OpenLessImeService.kt @@ -6,10 +6,8 @@ import android.content.res.Configuration import android.content.pm.PackageManager import android.graphics.Canvas import android.graphics.Color -import android.graphics.LinearGradient import android.graphics.Paint import android.graphics.Path -import android.graphics.Shader import android.graphics.Typeface import android.graphics.drawable.GradientDrawable import android.icu.text.Transliterator @@ -21,7 +19,6 @@ import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager import android.text.InputType -import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo @@ -56,6 +53,15 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private var lastCancelledImeRequest = 0L private var imeRequestId = 0L private var imeSessionId: String? = null + private var typingVoiceOwner: ImeRequestOwner? = null + private var activeImeOwner: ImeRequestOwner? = null + private val imeFrameGate = ImeScopedFrameGate() + private var externalVoiceSessionId: String? = null + private var imeStopRequested = false + private var imeCaptureEnded = false + private var externalRecording = false + private var externalProcessing = false + private var microphoneGranted = false private var pendingCloudArm = false private var pendingImeStop = false private var cloudNoteDestination: Pair? = null @@ -102,13 +108,23 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt if (imeRequestId != 0L) { lastCancelledImeRequest = imeRequestId; sendImeCommand("cancel") } imeRequestId = 0L imeSessionId = null + typingVoiceOwner = null + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + imeStopRequested = false + imeCaptureEnded = false + recording = false + processing = false pendingImeStop = false cloudNoteDestination = null pendingCloudArm = false cloudNoteSubmitting = false + renderVoiceUi() } private fun stopImeSession() { + imeStopRequested = true + imeCaptureEnded = true if (imeSessionId == null) pendingImeStop = true else if (!sendImeCommand("stop")) { recording = false; processing = false } } @@ -116,6 +132,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun onImeSessionEvent(json: String) { val event = runCatching { org.json.JSONObject(json) }.getOrNull() ?: return if (event.optLong("requestId") != imeRequestId || imeRequestId == 0L) { + event.optString("sessionId").takeIf { it.isNotBlank() }?.let(imeFrameGate::retire) if (event.optLong("requestId") == lastCancelledImeRequest && event.optString("error") == "Persistence") { OpenLessNativeNotice.makeText(this, ui("录音清理失败,重新打开应用后重试", "Recording cleanup failed; reopen the app to retry"), Toast.LENGTH_LONG).show() } @@ -123,15 +140,50 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } when (event.optString("kind")) { "started" -> { - imeSessionId = event.getString("sessionId") + val identity = event.optString("sessionId") + val owner = activeImeOwner + if (owner == null || !owner.matches(sessionEpoch, imeRequestId)) { + if (identity.isNotBlank()) imeFrameGate.retire(identity) + return + } + if (imeSessionId == identity && imeFrameGate.isBound(owner, identity)) { + // Replayed acknowledgements cannot reapply cloud mode or + // resubmit stop after finalization has already begun. + updateStatus(currentMessage) + return + } + val buffered = imeFrameGate.bind(owner, identity) + if (!imeFrameGate.isBound(owner, identity)) { + cancelImeSession() + setState("error", ui("无法确认听写会话,请重试", "Could not identify the dictation session; retry")) + return + } + imeSessionId = identity + if (!ImeVoiceFramePolicy.canApplyQueuedStartActions(buffered?.state)) { + // The backend already stopped/failed before this ack. Stop is + // not idempotent: never send another stop just to obtain text. + pendingImeStop = false + pendingCloudArm = false + imeStopRequested = false + buffered?.let { onCapsuleStateChangedWithSession(it.state, it.message, it.level, it.sessionId) } + updateStatus(currentMessage) + return + } if (pendingCloudArm) { pendingCloudArm = false; cloudNoteArmed = true } if (cloudNoteArmed && !sendImeCommand("cloud")) { cancelImeSession(); return } if (pendingImeStop) { pendingImeStop = false; stopImeSession() } + buffered?.let { onCapsuleStateChangedWithSession(it.state, it.message, it.level, it.sessionId) } + updateStatus(currentMessage) } "completed" -> { - if (event.optString("sessionId") != imeSessionId) return + if (!ownsImeRequest() || event.optString("sessionId") != imeSessionId) return val destination = cloudNoteDestination val reviewCloudNote = cloudNoteReviewArmed + typingVoiceOwner = null + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + imeStopRequested = false + imeCaptureEnded = false imeSessionId = null recording = false processing = false @@ -144,12 +196,18 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt else commitImeText(event.optString("text")) } "error" -> { + typingVoiceOwner = null + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + imeStopRequested = false + imeCaptureEnded = false recording = false processing = false imeSessionId = null pendingImeStop = false pendingCloudArm = false - setState("error", ui("听写失败,请重试", "Dictation failed; please retry")) + if (event.optString("error") == "Cancelled") setState("cancelled", ui("已取消", "Cancelled")) + else setState("error", ui("听写失败,请重试", "Dictation failed; please retry")) } } } @@ -239,7 +297,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } /** True from the start of a recording through the "thinking" step that follows it — the span an armed mode keeps its accent for. */ - private fun dictationInProgress(): Boolean = state == "speaking" || state == "thinking" + private fun dictationInProgress(): Boolean = voiceUiState().editorLocked /** Status text color while a recording or thinking prompt is showing — the armed mode's accent, normal otherwise. */ private fun recordingAccentColor(): Int = @@ -254,6 +312,11 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // is ENGLISH, and "英文" while it's PINYIN. private var latinInputMode = LatinInputMode.ENGLISH private val rimePinyinController by lazy { RimePinyinController(this) } + private var pinyinComposingActive = false + private var quickChipPayload: String? = null + private var quickChipLabel: String? = null + private var quickChipExpiresAtMs: Long = 0L + private var quickChipIsUndoDelete: Boolean = false // The word currently being typed on the English keyboard — appended to // per letter, trimmed per backspace, cleared at every word boundary // (space/return/punctuation/candidate tap/mode or panel switch). Never @@ -261,12 +324,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // committed immediately, same as before this feature: this buffer only // tracks what to re-query/replace for candidates. private val englishComposingWord = StringBuilder() - private var englishCandidateRow: LinearLayout? = null - // The row+divider bar as a whole (shown/hidden together when the - // suggestions setting is toggled) and its overflow "▼" button — see - // buildEnglishCandidateBar(). - private var englishCandidateBarContainer: View? = null - private var englishExpandCandidatesButton: View? = null private var englishCandidateQueryEpoch = 0L // Lazy, not eager: the base dictionary/trie only gets built the first // time the English keyboard is actually opened (see @@ -304,40 +361,19 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private var lastEnglishSpaceAt = 0L private var state = "idle" private var currentMessage = "点击开始说话" + private var latestVoiceLevel = 0f private var status: TextView? = null private var voiceRawHint: TextView? = null private var statusNormalColor = Color.GRAY - // Single shared top-level preview bubble for every key across the - // English and stroke keyboards (see wrapWithKeyPreviewOverlay()) — reset - // on every panel rebuild since it lives inside that panel's own root - // View tree, same lifecycle as voiceButton/status below. Null in panels - // that never show a key preview (voice, clipboard, edit); callers use - // the safe-call operator so that's a no-op rather than a crash. - private var keyPreviewOverlay: KeyPreviewOverlay? = null // Last height_dp:raise_dp baked into the cached input view — compared in // onStartInputView so leaving keyboard settings and refocusing rebuilds // when the footprint prefs changed. private var appliedKeyboardFootprintKey: String? = null - // LETTERS layer's swipe-up-bearing keys (buildEnglishCharKey()'s - // wrapper -> its symbol — row1's digits, row2's @#$%&-+(), row3's - // :;'.,!?), so a swipe-armed drag can retarget across a row the same - // way a plain tap-drag already retargets across letters. Cleared and - // repopulated once per LETTERS render (see addEnglishCharRow()'s own - // row1 call, which always runs first — row2/row3 add straight into - // that same fresh map), since a shift toggle etc. throws the whole - // view tree away via refreshInputView() and would otherwise leave - // stale View keys behind. - private val englishSwipeSymbols = HashMap() - // The letter keys and Shift key of the English panel on screen, so a - // Shift change can relabel them in place (applyShiftState()) instead of - // rebuilding the whole keyboard. Entries from an older panel are simply - // no longer attached to the window and get skipped. - private val englishLetterKeys = ArrayList>() - private var englishShiftKey: ShiftKeyView? = null - // Binding behind each reusable candidate view in englishCandidateRow — - // see populateLatinCandidateRow(). - private val latinCandidateSlots = java.util.WeakHashMap() - private var voiceButton: VoiceButton? = null + private var surfaceHost: ImeSurfaceHost? = null + private var keyboardSurface: View? = null + private var draftBar: ImeDraftBar? = null + private var voiceButton: ImeVoiceButton? = null + private var voicePanel: ImeVoicePanel? = null // Silence-detection for the main voice panel: if the mic capture never // reports a meaningful level for a while after recording starts, the // audio link is probably broken upstream (muted mic, dead capture @@ -351,7 +387,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // later. Reassigned on every panel rebuild, same pattern as // voiceButton/status below. private var backendLinkIndicator: View? = null - private var backendLinkPulseAnimator: android.animation.ObjectAnimator? = null + private var keyboardHeader: ImeKeyboardHeader? = null // Which recognizer the next dictation uses, as nativeAsrRoute() reports // it ("cloud", "local", "localRaw", "unavailable"). The idle dot shows // local in dark green and pure-local raw output (no usable polish @@ -433,14 +469,25 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt /** Picks `dark` or `light` for the current system theme — the one place every themed color in this file goes through. */ internal fun tone(dark: Int, light: Int): Int = if (isDarkTheme) dark else light - // Mirrors whatever's currently in strokeCandidates (word/stroke matches - // or phrase associations) as plain (label, action) pairs, so the "show - // more" overlay can replay the exact same set without duplicating the - // stroke-match vs. association branching logic. - internal var candidateOverlayEntries: List Unit>> = emptyList() - internal fun ui(zh: String, en: String) = if (englishUi) en else zh + internal fun keyboardPalette(): ImePalette = ImePalette.resolve(isDarkTheme) + internal fun interactionPolicy(): ImeInteractionPolicy = ImeInteractionPolicy.fromStoredRepeat(keyRepeatIntervalMs()) + internal fun emitKeyFeedback() { performKeyHaptic() } + + private fun refreshInteractionPolicy() { + val policy = interactionPolicy() + typingPanel?.applyInteractionPolicy(policy) + voicePanel?.applyInteractionPolicy(policy) + clipboardPanel?.applyInteractionPolicy(policy) + strokeController.applyInteractionPolicy(policy) + } + + internal fun isKeyboardEditingBlocked(): Boolean = dictationEditingLocked() + internal fun buildKeyboardHeader(): View = buildVoiceHeader() + internal fun isEnglishKeyboardUi(): Boolean = englishUi + + internal fun outputScript(text: String): String { if (!traditionalOutput) return text return runCatching { simplifiedToTraditional.transliterate(text) }.getOrDefault(text) @@ -461,8 +508,13 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt 'z' -> { val start = builder.length builder.append(' ') + val align = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + android.text.style.DynamicDrawableSpan.ALIGN_CENTER + } else { + android.text.style.ImageSpan.ALIGN_BOTTOM + } builder.setSpan( - android.text.style.ImageSpan(strokeFifthGlyphDrawable(), android.text.style.ImageSpan.ALIGN_BASELINE), + android.text.style.ImageSpan(strokeFifthGlyphDrawable(), align), start, builder.length, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, @@ -477,7 +529,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt /** Same diagonal-then-horizontal shape as the "5" key's own icon, sized and colored to sit inline in strokePreview's text. */ private fun strokeFifthGlyphDrawable(): android.graphics.drawable.Drawable { - val sizePx = (16.5f * resources.displayMetrics.scaledDensity).toInt().coerceAtLeast(dp(14)) + val sizePx = (14f * resources.displayMetrics.scaledDensity).toInt().coerceAtLeast(dp(12)) val glyphPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = strokeEncodeAccentColor style = Paint.Style.STROKE @@ -549,9 +601,11 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } private fun restoreLatinInputMode() { - latinInputMode = when (getSharedPreferences("openless_ime_ui", MODE_PRIVATE).getString("latin_input_mode", "english")) { + val stored = getSharedPreferences("openless_ime_ui", MODE_PRIVATE).getString("latin_input_mode", null) + latinInputMode = when (stored) { "pinyin" -> LatinInputMode.PINYIN - else -> LatinInputMode.ENGLISH + "english" -> LatinInputMode.ENGLISH + else -> if (englishUi) LatinInputMode.ENGLISH else LatinInputMode.PINYIN } } @@ -572,6 +626,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun toggleLatinInputMode() { englishComposingWord.clear() englishCandidateQueryEpoch++ + clearPinyinComposingInEditor() rimePinyinController.clear() latinInputMode = latinInputMode.toggled() saveLatinInputMode(latinInputMode) @@ -593,7 +648,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun refreshLatinCandidateBar() { if (latinInputMode == LatinInputMode.PINYIN) { rimePinyinController.refresh { renderPinyinCandidates(it) } - englishCandidateBarContainer?.visibility = View.VISIBLE } else { updateEnglishCandidates() } @@ -611,6 +665,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt ?.coerceToText(this)?.toString() if (!text.isNullOrBlank()) { OpenLessClipboardHistory.recordCopy(this, text) + offerClipboardQuickChip(text) } } @@ -622,7 +677,9 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt override fun onCreate() { super.onCreate() + microphoneGranted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED learningMigrationComplete = ImeLearningPolicy.migrate(this) + refreshLanguage() restoreInputMode() restoreScriptPreference() restoreLatinInputMode() @@ -630,17 +687,15 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt OpenLessOverlayBridge.imeListener = this OpenLessOverlayBridge.imeSessionListener = ::onImeSessionEvent startRuntimeService() - // Load the offline stroke dictionary and the (much larger, ~220k- - // phrase) association dictionary while the IME is idle — the latter - // used to load lazily on whichever word's commit was the first to - // ever need an association, which is exactly the moment a user is - // sitting there waiting for the candidate row to update. + // Pre-warm offline stroke, phrase association, and Rime pinyin engines off the UI thread. strokeController.preloadAsync() + rimePinyinController.preload() clipboardManager.addPrimaryClipChangedListener(clipboardHistoryListener) backendHeartbeatHandler.post(backendHeartbeatRunnable) } override fun onDestroy() { + draftBar?.cancelInteractions() cancelImeSession() if (activeInstance?.get() === this) { activeInstance = null @@ -650,7 +705,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt OpenLessOverlayBridge.imeSessionListener = null } backendHeartbeatHandler.removeCallbacks(backendHeartbeatRunnable) - backendLinkPulseAnimator?.cancel() + keyboardHeader?.cancelInteractions() clipboardManager.removePrimaryClipChangedListener(clipboardHistoryListener) stopRuntimeService() strokeController.shutdown() @@ -697,7 +752,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt ) addView( View(this@OpenLessImeService).apply { - setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) + setBackgroundColor(keyboardPalette().surface) visibility = if (raisePx > 0) View.VISIBLE else View.GONE }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, raisePx), @@ -706,432 +761,172 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } override fun onCreateInputView(): View { + val host = ImeSurfaceHost(this) + surfaceHost = host + rebuildSurfaceContent() + return host.also { excludeFromSystemGestures(it) } + } + + private fun rebuildSurfaceContent(): View { + draftBar?.cancelInteractions() + draftBar = null + typingPanel?.closeTransientUi() + clipboardPanel?.cancelInteractions() + strokeController.cancelInteractions() + keyboardHeader?.cancelInteractions() + keyboardHeader = null + clipboardPanel = null + typingPanel = null + voicePanel = null + voiceButton = null + status = null + voiceRawHint = null + voiceLinkWarning = null + dictationResultRow = null + undoRedoButton = null + editResultButton = null refreshLanguage() - startRuntimeService() val content = when { - inputMode == InputMode.ENGLISH -> wrapWithKeyPreviewOverlay(buildKeyboardView()) - inputMode == InputMode.STROKE -> wrapWithKeyPreviewOverlay( - if (strokeController.strokeNumberMode) strokeController.buildStrokeNumberView() - else strokeController.buildStrokeView(), - ) + inputMode == InputMode.ENGLISH -> buildKeyboardView() + inputMode == InputMode.STROKE -> strokeController.buildStrokeView() inputMode == InputMode.CLIPBOARD -> if (clipboardHistoryMode) buildClipboardHistoryView() else buildClipboardView() else -> buildVoiceInputView() } - val view = applyKeyboardRaise(content) + val keyboard = applyKeyboardRaise(content) + keyboardSurface = keyboard + val draft = buildDraftBar() + surfaceHost?.render(keyboard, draft, draftEdit) appliedKeyboardFootprintKey = keyboardFootprintKey() - return wrapWithDraftBar(view) + return keyboard } - /** Voice panel + floating dictation-result overlay (former onCreateInputView body). */ - private fun buildVoiceInputView(): View { - val panel = SwipeModeContainer(this) { direction -> swipeInputMode(direction) }.apply { - orientation = LinearLayout.VERTICAL - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyboardPanelHeightPx()) - minimumHeight = keyboardPanelHeightPx() - setPadding(dp(16), dp(8), dp(16), dp(4)) - setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - clipChildren = false - clipToPadding = false - } - panel.addView(buildVoiceHeader(), LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - dp(38), - )) - statusNormalColor = tone(Color.rgb(190, 190, 190), Color.rgb(110, 110, 115)) - status = TextView(this).apply { - text = displayStatus(currentMessage) - textSize = 16f - if (englishUi) typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - gravity = android.view.Gravity.CENTER - setTextColor(statusNormalColor) - setPadding(0, dp(6), 0, dp(4)) - } - panel.addView(status, LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - dp(38), - )) + private fun replaceSurfaceContent(): View { + if (surfaceHost == null) { + setInputView(onCreateInputView()) + return requireNotNull(keyboardSurface) + } + return rebuildSurfaceContent() + } - voiceButton = VoiceButton(this, isDarkTheme).apply { - isClickable = true - setOnClickListener { toggleDictation() } - contentDescription = ui("OpenLess 语音听写", "OpenLess dictation") - // All four swipe gestures follow the same pattern: a LIVE - // boolean re-evaluated every ACTION_MOVE (not a one-way latch), - // a matching live visual on VoiceButton (idle capsule orange for - // swipe-up-to-raw / green for swipe-left-to-quick-notes / red for - // swipe-right-to-cloud-notes, waveform light red for swipe-down-to- - // cancel — all four ease back the moment the finger drops back - // below their own threshold), a single haptic tick on every - // crossing in either direction, and the actual action (cancel / - // enter raw mode / enter quick-notes mode / enter cloud-notes mode) - // only committed on release, gated on whichever one is still - // active at that instant. Nothing commits mid-drag — swipe down - // used to cancel the moment the threshold was first crossed - // during the move, but that gave no chance to back out of an - // accidental trigger, same reasoning as the swipe-up threshold's - // own move-to-release change earlier. - // - // requestDisallowInterceptTouchEvent is still claimed - // unconditionally on DOWN (not only once a threshold is - // crossed), matching buildEnglishCharKey()'s same fix earlier - // this session: without it, a downward drag here is - // indistinguishable from the enclosing SwipeModeContainer's own - // "long downward drag dismisses the keyboard" gesture, and that - // ancestor can steal the sequence before our own dp(30) check - // ever sees the full distance. - var downX = 0f - var downY = 0f - var swipeUpActive = false - var swipeDownActive = false - // Same shape as swipeUpActive (no `recording` gate on the MOVE - // check — armable both from idle and mid-recording), just on the - // horizontal axis — see cloudNoteArmed's own doc comment for what - // release does in each case. - var swipeRightActive = false - // Same shape again, mirrored to the other horizontal direction — - // see quickNoteArmed's own doc comment for what release does. - var swipeLeftActive = false - setOnTouchListener { view, event -> - when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { - downX = event.x - downY = event.y - swipeUpActive = false - swipeDownActive = false - swipeRightActive = false - swipeLeftActive = false - view.parent?.requestDisallowInterceptTouchEvent(true) - } - MotionEvent.ACTION_MOVE -> { - if (recording) { - val active = event.y - downY >= dp(30) - if (active != swipeDownActive) { - swipeDownActive = active - voiceButton?.armedForCancel = active - performKeyHaptic() - } - } - val active = downY - event.y >= dp(30) - if (active != swipeUpActive) { - swipeUpActive = active - // Mid Cloud-notes recording a swipe up asks for the - // draft editor, not Raw — keep the orange preview off. - voiceButton?.armedForRawSwipe = active && !(recording && (cloudNoteArmed || pendingCloudArm)) - // One tick every time the threshold is - // crossed, either direction — entering AND - // leaving the armed zone both get felt, not - // just the eventual release. - performKeyHaptic() - } - val activeRight = event.x - downX >= dp(30) - if (activeRight != swipeRightActive) { - swipeRightActive = activeRight - voiceButton?.armedForCloudNote = activeRight - performKeyHaptic() - } - val activeLeft = downX - event.x >= dp(30) - if (activeLeft != swipeLeftActive) { - swipeLeftActive = activeLeft - voiceButton?.armedForQuickNote = activeLeft - performKeyHaptic() - } - } - MotionEvent.ACTION_UP -> { - if (swipeDownActive) { - performDoubleKeyHaptic() - cancelDictation() - } else if (swipeUpActive) { - if (recording && (cloudNoteArmed || pendingCloudArm)) { - // Ends the recording right here; the result opens - // in the draft bar instead of being sent. The - // click that may follow this release is a no-op: - // toggleDictation() ignores taps while processing. - cloudNoteReviewArmed = true - performDoubleKeyHaptic() - toggleDictation() - } else if (recording && !rawModeArmed) { - rawModeArmed = true - performDoubleKeyHaptic() - updateStatus(currentMessage) - } else if (!recording && !processing) { - toggleDictation() - if (recording) { - rawModeArmed = true - performDoubleKeyHaptic() - updateStatus(currentMessage) - } - } - } else if (swipeRightActive) { - if (recording && !cloudNoteArmed) { - cloudNoteArmed = true - performDoubleKeyHaptic() - updateStatus(currentMessage) - } else if (!recording && !processing) { - toggleDictation(initialCloud = true) - if (recording) { - cloudNoteArmed = true - performDoubleKeyHaptic() - updateStatus(currentMessage) - } - } - } else if (swipeLeftActive) { - if (recording && !quickNoteArmed) { - quickNoteArmed = true - performDoubleKeyHaptic() - updateStatus(currentMessage) - } else if (!recording && !processing) { - toggleDictation() - if (recording) { - quickNoteArmed = true - performDoubleKeyHaptic() - updateStatus(currentMessage) - } - } - } - swipeUpActive = false - swipeDownActive = false - swipeRightActive = false - swipeLeftActive = false - voiceButton?.armedForRawSwipe = false - voiceButton?.armedForCancel = false - voiceButton?.armedForQuickNote = false - voiceButton?.armedForCloudNote = false - } - MotionEvent.ACTION_CANCEL -> { - swipeUpActive = false - swipeDownActive = false - swipeRightActive = false - swipeLeftActive = false - voiceButton?.armedForRawSwipe = false - voiceButton?.armedForCancel = false - voiceButton?.armedForQuickNote = false - voiceButton?.armedForCloudNote = false - } + /** View components render state; this adapter alone owns native operations. */ + private fun buildVoiceInputView(): View { + val palette = ImePalette.resolve(isDarkTheme) + return ImeVoicePanel( + this, palette, buildVoiceHeader(), englishUi, + onVoiceGesture = ::handleVoiceGesture, + onUndo = ::toggleUndoRedoDictation, + onEdit = { openDictationEditDraft(requireSelection = false) }, + onEnter = { if (!dictationEditingLocked()) sendEnterKey() }, + onBackspace = { if (!dictationEditingLocked()) deleteBackward() }, + onAt = { if (!dictationEditingLocked()) currentInputConnection?.commitText("@", 1) }, + onRestart = ::restartApp, + onFeedback = ::performKeyHaptic, + interactionPolicy = interactionPolicy(), + ).also { panel -> + voicePanel = panel + statusNormalColor = palette.secondaryText + status = panel.status + voiceButton = panel.voiceButton + voiceRawHint = panel.modeHint + voiceLinkWarning = panel.warning + undoRedoButton = panel.undo + editResultButton = panel.edit + dictationResultRow = panel.resultRow + updateStatus(currentMessage) + } + } + + private fun dictationEditingLocked(): Boolean = voiceUiState().editorLocked + + private fun ownsImeRequest(): Boolean = activeImeOwner?.matches(sessionEpoch, imeRequestId) == true + private fun hasForeignVoiceActivity(): Boolean = (externalRecording || externalProcessing) && !ownsImeRequest() + + private fun voiceUiState(): ImeVoiceUiSnapshot { + val foreign = hasForeignVoiceActivity() + return ImeVoiceUiProjection.fromLegacy( + state, recording || externalRecording, processing || externalProcessing, cloudNoteSubmitting, + rawModeArmed && !foreign, quickNoteArmed && !foreign, (cloudNoteArmed || pendingCloudArm) && !foreign, + displayStatus(currentMessage), if (foreign) 0f else latestVoiceLevel, + awaitingStart = ownsImeRequest() && recording && imeSessionId == null, + ).withEligibility(ownsImeRequest(), microphoneGranted, isSensitiveField(currentInputEditorInfo), foreign) + } + + private fun handleVoiceGesture(action: ImeVoiceGesture) { + if (hasForeignVoiceActivity()) { renderVoiceUi(); return } + if (processing && action != ImeVoiceGesture.CANCEL) return + when (action) { + ImeVoiceGesture.TAP -> toggleDictation() + ImeVoiceGesture.CANCEL -> if (recording || processing) cancelDictation() + ImeVoiceGesture.REVIEW_CLOUD -> { + if (recording && (cloudNoteArmed || pendingCloudArm)) { + cloudNoteReviewArmed = true + toggleDictation() + } + } + ImeVoiceGesture.RAW -> { + if (!recording) toggleDictation() + if (recording) { + quickNoteArmed = false + rawModeArmed = true + performDoubleKeyHaptic() + updateStatus(currentMessage) + } + } + ImeVoiceGesture.QUICK_NOTE -> { + if (!recording) toggleDictation() + if (recording) { + rawModeArmed = false + quickNoteArmed = true + performDoubleKeyHaptic() + updateStatus(currentMessage) + } + } + ImeVoiceGesture.CLOUD_NOTE -> { + val prefs = getSharedPreferences("openless_ime_ui", MODE_PRIVATE) + val hasDestination = !prefs.getString("key_cloud_note_webhook_url", "").isNullOrBlank() && + !prefs.getString("key_cloud_note_webhook_token", "").isNullOrBlank() + if (!hasDestination) { + updateStatus(ui("请先配置云笔记地址和 Token,未开始云笔记听写", "Configure the Cloud note URL and token first; recording was not changed")) + return + } + if (!recording) toggleDictation(initialCloud = true) + if (recording) { + cloudNoteArmed = true + performDoubleKeyHaptic() + updateStatus(currentMessage) } - false - } - } - // FrameLayout, not LinearLayout: voiceButton is centered purely by - // its own Gravity.CENTER, independent of whatever else shares this - // holder — a LinearLayout would instead center the *whole stack* of - // children as one block, which pushed the mic icon itself upward - // (away from the status line above) once voiceRawHint became a - // permanently-participating sibling instead of an occasional one. - // voiceRawHint/voiceLinkWarning use that same CENTER anchor plus a - // fixed topMargin, so they sit a fixed distance below the mic - // without perturbing its own position at all. - val buttonHolder = FrameLayout(this).apply { - setBackgroundColor(Color.TRANSPARENT) - clipChildren = false - clipToPadding = false - } - buttonHolder.addView(voiceButton!!, FrameLayout.LayoutParams(dp(176), dp(72), android.view.Gravity.CENTER)) - - // Small companion hint — deliberately muted (low size + alpha) so it - // doesn't compete with "Tap to speak" for attention, but - // discoverable enough that a user notices the three swipe gestures - // exist at all. Sits just above the footer row (right above the - // Return key, which is horizontally centered there the same way - // this hint is) rather than directly under the mic — out of the way - // of the mic capsule and its own waveform/pill animations, but still - // close enough to read while a hand hovers over the mic. Tap or - // long-press explains what Raw mode actually does via a Toast, - // rather than building a dedicated tooltip bubble for a single - // one-off explanation. Hidden entirely while recording/thinking in - // an ordinary (non-Raw) dictation — see rawModeHintVisible() — - // since at that point it's neither teaching a still-relevant - // gesture nor confirming anything, just noise. - val rawModeTooltip = ui("Raw模式,语音原样转写,不做AI润色整理", "Raw mode, verbatim transcription without AI polishing") - voiceRawHint = TextView(this).apply { - text = rawModeHintText() - textSize = 11f - if (englishUi) typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - gravity = android.view.Gravity.CENTER - setTextColor(rawModeHintColor()) - visibility = if (rawModeHintVisible()) View.VISIBLE else View.GONE - isClickable = true - setOnClickListener { OpenLessNativeNotice.makeText(this@OpenLessImeService, rawModeTooltip, Toast.LENGTH_SHORT).show() } - setOnLongClickListener { - OpenLessNativeNotice.makeText(this@OpenLessImeService, rawModeTooltip, Toast.LENGTH_SHORT).show() - true } } - buttonHolder.addView( - voiceRawHint, - FrameLayout.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT, - android.view.Gravity.BOTTOM or android.view.Gravity.CENTER_HORIZONTAL, - ).apply { - bottomMargin = dp(6) - }, - ) - voiceLinkWarning = TextView(this).apply { - text = ui("检测到麦克风无声音,点击重启应用", "No mic audio detected — tap to restart the app") - textSize = 16f - if (englishUi) { - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - } else { - setTypeface(typeface, android.graphics.Typeface.BOLD) - } - gravity = android.view.Gravity.CENTER - setTextColor(Color.rgb(255, 90, 90)) - setPadding(dp(12), 0, dp(12), 0) - visibility = View.GONE - isClickable = true - setOnClickListener { restartApp() } - } - buttonHolder.addView( - voiceLinkWarning, - FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, android.view.Gravity.CENTER).apply { - // Below where the Raw hint sits, so the two never overlap on - // the rare occasion both are visible at once (Raw-armed - // recording with a simultaneous mic-silence warning). - topMargin = dp(70) - }, - ) - panel.addView(buttonHolder, LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - 0, - 1f, - )) - - panel.addView(buildVoiceFooter(), LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - dp(84), - )) - - // The undo/redo/edit controls float over the panel instead of taking - // a reserved slot in its own layout — that way showing or hiding - // them can never nudge the mic (or anything else) out of its - // original centered position, regardless of visibility state. - val overlayHost = FrameLayout(this).apply { - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyboardPanelHeightPx()) - } - overlayHost.addView(panel, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) - overlayHost.addView(buildDictationResultOverlay(), FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT, - android.view.Gravity.BOTTOM, - ).apply { - marginStart = dp(16) - marginEnd = dp(16) - // Panel's own bottom padding (4dp) + footer height (84dp) + a - // small gap (6dp), so this lands just above @ and backspace. - bottomMargin = dp(4) + dp(84) + dp(6) - }) - return overlayHost - } - - private fun buildVoiceHeader(): LinearLayout { - val header = LinearLayout(this).apply { - gravity = android.view.Gravity.CENTER_VERTICAL - } - header.addView(buildBrandView(), LinearLayout.LayoutParams(0, dp(38), 1f)) - header.addView(buildModeToggle(), LinearLayout.LayoutParams(dp(240), dp(38))) - return header - } - - /** Flat pill fill (no elevation) shared by every footer-row button — @, return, backspace, undo/redo, edit. */ - private fun flattenFooterButton(view: TextView, height: Int) { - view.elevation = 0f - view.translationZ = 0f - // A single flat fill, not roundedButton()'s layered "keycap" look - // (gradient face + exposed darker step) — genuinely flat, matching - // the mic capsule's own plain drawRoundRect fill exactly. - view.background = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - cornerRadius = (height / 2).toFloat() - setColor(tone(Color.rgb(60, 60, 60), Color.rgb(225, 225, 228))) - } - } - - /** @ / return / backspace — the plain footer row, unaffected by the undo/redo/edit overlay above it. */ - private fun buildVoiceFooter(): LinearLayout { - val footerButtonHeight = dp(48) - val footer = LinearLayout(this).apply { - gravity = android.view.Gravity.CENTER_VERTICAL - clipChildren = false - clipToPadding = false - } - val atButton = keyboardKey("@", 1f, action = { currentInputConnection?.commitText("@", 1) }).apply { - textSize = 20f - contentDescription = ui("输入 @", "Insert at sign") - layoutParams = LinearLayout.LayoutParams(dp(84), footerButtonHeight) - flattenFooterButton(this, footerButtonHeight) - } - // Chinese UI shows "换行" (line break) instead of the English word - // "Return" — a real Chinese label reads better here than the - // borrowed English term, so it gets its own larger, bold treatment - // rather than reusing "Return"'s smaller size. - val returnLabel = if (englishUi) "Return" else "换行" - val returnButton = keyboardKey(returnLabel, 1f, action = { sendEnterKey() }).apply { - textSize = if (englishUi) 18f else 20f - if (englishUi) { - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - } else { - setTypeface(typeface, android.graphics.Typeface.BOLD) - } - contentDescription = ui("回车", "Return") - layoutParams = LinearLayout.LayoutParams(dp(120), footerButtonHeight) - flattenFooterButton(this, footerButtonHeight) - } - val backspaceButton = keyboardKey( - "⌫", - 1f, - action = { deleteBackward() }, - repeatOnLongPress = true, - repeatAction = { deleteBackward() }, - ).apply { - textSize = 22f - contentDescription = ui("退格", "Backspace") - layoutParams = LinearLayout.LayoutParams(dp(84), footerButtonHeight) - flattenFooterButton(this, footerButtonHeight) - } - val returnHolder = LinearLayout(this).apply { - gravity = android.view.Gravity.CENTER - addView(returnButton) - } - footer.addView(atButton) - footer.addView(returnHolder, LinearLayout.LayoutParams(0, dp(84), 1f)) - footer.addView(backspaceButton) - return footer } - /** - * Undo/redo + edit controls for the last dictation result, same size and - * style as the footer's @/backspace keys. Built standalone (not part of - * buildVoiceFooter()'s layout flow) so it can be positioned as a - * FrameLayout overlay above the footer — showing or hiding it can never - * shift the mic or footer since it never occupies space in their own - * LinearLayout. - */ - private fun buildDictationResultOverlay(): View { - val footerButtonHeight = dp(48) - undoRedoButton = keyboardKey("✕", 1f, action = { toggleUndoRedoDictation() }).apply { - textSize = 20f - contentDescription = ui("撤销本次听写结果", "Undo this dictation") - layoutParams = LinearLayout.LayoutParams(dp(84), footerButtonHeight) - flattenFooterButton(this, footerButtonHeight) - } - editResultButton = keyboardKey("✎", 1f, action = { openDictationEditDraft(requireSelection = false) }).apply { - textSize = 20f - contentDescription = ui("编辑听写结果", "Edit dictation result") - layoutParams = LinearLayout.LayoutParams(dp(84), footerButtonHeight) - flattenFooterButton(this, footerButtonHeight) - } - val row = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER_VERTICAL } - row.addView(undoRedoButton!!, LinearLayout.LayoutParams(dp(84), footerButtonHeight)) - row.addView(View(this), LinearLayout.LayoutParams(0, footerButtonHeight, 1f)) - row.addView(editResultButton!!, LinearLayout.LayoutParams(dp(84), footerButtonHeight)) - dictationResultRow = row - updateDictationResultControls() - return row + private fun buildVoiceHeader(): ImeKeyboardHeader = ImeKeyboardHeader( + this, keyboardPalette(), buildModeToggle(), brandLogoBitmap, + onSettings = ::openSettings, + onKeyboardSettings = ::openKeyboardSettings, + onModeStep = ::swipeInputMode, + onHide = ::hideKeyboardPanel, + ).also { + keyboardHeader = it + backendLinkIndicator = it.indicator + updateBackendLinkIndicator() } internal fun refreshInputView() { - setInputView(onCreateInputView()) + if (inputMode == InputMode.STROKE && appliedKeyboardFootprintKey == keyboardFootprintKey() && + strokeController.refreshPanel()) return + if (inputMode == InputMode.CLIPBOARD && clipboardPanel != null && + appliedKeyboardFootprintKey == keyboardFootprintKey()) { + renderClipboardPanel() + return + } + if (inputMode == InputMode.ENGLISH && typingPanel != null && + appliedKeyboardFootprintKey == keyboardFootprintKey()) { + renderTypingKeyboard() + refreshLatinCandidateBar() + return + } + replaceSurfaceContent() } /** @@ -1149,13 +944,11 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt * width. */ private fun refreshInputView(slideDirection: Int) { - val newView = onCreateInputView() - setInputView(newView) + val keyboard = replaceSurfaceContent() val offset = resources.displayMetrics.widthPixels.toFloat() * slideDirection // RaisedKeyboardHost wraps [panel, raiseSpacer] — slide the panel's // own children (skip header at 0), not the raise spacer. The draft // bar sits above that host and stays put as well. - val keyboard = (newView as? DraftHost)?.keyboard ?: newView val container = when (keyboard) { is RaisedKeyboardHost -> keyboard.getChildAt(0) as? ViewGroup is ViewGroup -> keyboard @@ -1181,7 +974,12 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // segment to the right slides in from the right, matching what a // swipe in that direction would already do. Tapping the // already-selected segment has no direction to slide from. - internal fun buildModeToggle(): View = ModeToggle(this, inputMode, isDarkTheme) { selected -> + internal fun buildModeToggle(): View = ImeModeBar( + this, ImePalette.resolve(isDarkTheme), + listOf(ui("语音", "Voice"), ui("笔画", "Stroke"), ui("编辑", "Edit"), ui("键盘", "Keys")), + inputMode.ordinal, + ) { index -> + val selected = InputMode.entries[index] val direction = when { selected.ordinal > inputMode.ordinal -> 1 selected.ordinal < inputMode.ordinal -> -1 @@ -1190,87 +988,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt selectInputMode(selected, slideDirection = direction) } - /** - * White-on-transparent wordmark used in every panel header, replacing - * the old text label, plus the backend-link status dot right after it. - * A plain horizontal LinearLayout (not a FrameLayout) so the dot just - * lands after the logo/text in sequence with a fixed gap, regardless of - * which of the two logo/text branches below actually renders — the - * existing call sites all pass their own LinearLayout.LayoutParams for - * this whole row. - */ - internal fun buildBrandView(): View { - val bitmap = brandLogoBitmap - val wrapper = LinearLayout(this).apply { - orientation = LinearLayout.HORIZONTAL - gravity = android.view.Gravity.START or android.view.Gravity.CENTER_VERTICAL - isClickable = true - contentDescription = ui("打开 OpenLess 设置", "Open OpenLess settings") - setOnClickListener { openSettings() } - // Long-press opens a full-screen native settings window for - // keyboard-only preferences (starting with vibration) that don't - // need the full OpenLess app — separate from the short-tap, - // which still opens the main app's own settings. - setOnLongClickListener { - openKeyboardSettings() - true - } - } - if (bitmap != null) { - // Half the wordmark's previous rendered size — at full size it - // crowded the header row next to the mode toggle/close button. - val heightPx = dp(19) - val widthPx = (heightPx.toFloat() * bitmap.width / bitmap.height).toInt() - wrapper.addView(android.widget.ImageView(this).apply { - setImageBitmap(bitmap) - scaleType = android.widget.ImageView.ScaleType.FIT_XY - // The wordmark asset is white-on-transparent; on the light - // theme's light panel that would be invisible, so it's - // recolored dark via a tint rather than shipping a second - // asset. - if (!isDarkTheme) { - colorFilter = android.graphics.PorterDuffColorFilter(Color.rgb(30, 30, 34), android.graphics.PorterDuff.Mode.SRC_IN) - } - }, LinearLayout.LayoutParams(widthPx, heightPx)) - } else { - wrapper.addView(TextView(this).apply { - text = "OpenLess" - textSize = 18f - setTypeface(typeface, android.graphics.Typeface.BOLD) - setTextColor(tone(Color.WHITE, Color.rgb(30, 30, 34))) - }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - } - // Status dot: see backendLinkIndicator's field comment. Reassigned - // here on every panel rebuild (buildBrandView() is shared by every - // panel's own header), then immediately colored so it never shows a - // stale state (e.g. still green right after a rebuild that happened - // while actually recording) — visible everywhere per product - // request, not just the Voice panel. - backendLinkIndicator = View(this).apply { - background = GradientDrawable().apply { - shape = GradientDrawable.OVAL - setColor(LINK_COLOR_READY) - } - } - // Continuous breathing pulse so the dot reads as "alive" rather - // than a static badge — cancels whatever animator was running on - // the previous panel's now-discarded indicator first, since each - // rebuild creates a brand new View instance. - backendLinkPulseAnimator?.cancel() - backendLinkPulseAnimator = android.animation.ObjectAnimator.ofFloat(backendLinkIndicator, View.ALPHA, 1f, 0.35f).apply { - duration = BACKEND_LINK_READY_PULSE_DURATION_MS - repeatMode = android.animation.ValueAnimator.REVERSE - repeatCount = android.animation.ValueAnimator.INFINITE - start() - } - wrapper.addView( - backendLinkIndicator, - LinearLayout.LayoutParams(dp(12), dp(12)).apply { marginStart = dp(5) }, - ) - updateBackendLinkIndicator() - return wrapper - } - private fun selectInputMode(selected: InputMode, slideDirection: Int? = null) { if (recording || processing) cancelDictation() inputMode = selected @@ -1278,6 +995,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt englishLayer = EnglishLayer.LETTERS englishComposingWord.clear() englishCandidateQueryEpoch++ + clearPinyinComposingInEditor() rimePinyinController.clear() rimePinyinController.resetAssociationContext() strokeController.resetForModeSwitch() @@ -1294,7 +1012,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } /** - * Left/right swipe on any panel steps through the same Voice-Stroke-English + * A deliberate header swipe steps through the same mode order * order as the toggle switch, clamped at both ends (no wraparound) — * swiping left keeps landing on Voice, right keeps landing on English. * The new panel slides in from the side matching the ordinal direction @@ -1306,325 +1024,113 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt if (next != inputMode) selectInputMode(next, slideDirection = direction) } - /** - * English ABC/123/#+= keyboard — key relationships (rows, per-row key - * count, relative widths, and the 123/ABC/#+= switching logic) follow - * iOS 17's own English keyboard; colors, key surface, and every other - * visual detail are OpenLess's existing key styling (roundedButton()/ - * tone()), matching the stroke panel. See EnglishLayer for the ABC/123/ - * #+= state and README's "英文键盘 iOS 17 布局" entry for the full - * rationale. - */ - /** - * Wraps a panel root in a plain FrameLayout with a KeyPreviewOverlay as - * its second (top-drawn) child, so every key preview bubble in that - * panel renders above the whole keyboard — unclipped by the panel's own - * clipChildren/candidate-row/mode-toggle bounds — without taking part in - * its layout at all. The wrapper takes on the panel's own layoutParams - * (every panel already sets its own fixed MATCH_PARENT x keyboardPanelHeightPx()) so - * this changes nothing about the panel's measured size; the panel then - * fills the wrapper exactly as it used to fill the IME window directly. - */ - private fun wrapWithKeyPreviewOverlay(content: View): View { - val host = FrameLayout(this).apply { - layoutParams = content.layoutParams ?: ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyboardPanelHeightPx()) - clipChildren = false - clipToPadding = false - } - host.addView(content, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) - val overlay = KeyPreviewOverlay(this, isDarkTheme) - keyPreviewOverlay = overlay - host.addView(overlay, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) - return host - } + private var typingPanel: ImeTypingPanel? = null + /** Native presentation is independent of the IME's input/learning backends. */ private fun buildKeyboardView(): View { - val root = SwipeModeContainer(this) { direction -> swipeInputMode(direction) }.apply { - orientation = LinearLayout.VERTICAL - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyboardPanelHeightPx()) - minimumHeight = keyboardPanelHeightPx() - setPadding(dp(8), dp(8), dp(8), dp(8)) - setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - } - val header = LinearLayout(this).apply { - gravity = android.view.Gravity.CENTER_VERTICAL - } - header.addView(buildBrandView(), LinearLayout.LayoutParams(0, dp(38), 1f)) - header.addView(buildModeToggle(), LinearLayout.LayoutParams(dp(240), dp(38))) - // This panel's own root padding (8dp) is narrower than the voice panel's - // (16dp), which it needs for its body rows. Compensate with margins so - // the header/toggle still land at the same canonical 16dp/8dp inset as - // every other panel — otherwise the logo and toggle visibly jump left - // and up when switching modes. - root.addView(header, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(38)).apply { - marginStart = dp(8) - marginEnd = dp(8) - }) - - root.addView(buildEnglishCandidateBar(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - refreshLatinCandidateBar() - - when (englishLayer) { - EnglishLayer.LETTERS -> { - addEnglishCharRow( - root, - listOf("q", "w", "e", "r", "t", "y", "u", "i", "o", "p"), - swipeSymbols = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"), - ) - // iOS insets this row by half a key on each side (9 keys - // spanning the same width as the 10-key rows above/below); - // 0.5f spacers on either side of 1f-weight letter keys - // reproduce that without a second, differently-measured row. - val row2 = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER } - row2.addView(View(this), LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f)) - listOf("a", "s", "d", "f", "g", "h", "j", "k", "l") - .zip(listOf("~", "@", "#", "!", "%", "&", "*", "(", ")")) - .forEach { (key, symbol) -> row2.addView(buildEnglishCharKey(key, 1f, swipeSymbol = symbol)) } - row2.addView(View(this), LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f)) - root.addView(row2, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - - val row3 = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER } - row3.addView(keyboardKey("⇧", 1.5f, action = { cycleEnglishShift() })) - listOf("z", "x", "c", "v", "b", "n", "m") - .zip(listOf("'", "/", "-", "_", ":", ";", "?")) - .forEach { (key, symbol) -> row3.addView(buildEnglishCharKey(key, 1f, swipeSymbol = symbol)) } - row3.addView( - keyboardKey("⌫", 1.5f, action = { englishDeleteBackward() }, repeatOnLongPress = true, repeatAction = { englishDeleteBackward() }).apply { - // Same cherry red as the stroke panel's own - // right-side action rail, matching the Return key - // right next to it. - background = roundedButton(Color.rgb(153, 26, 40), dp(5)) - setTextColor(Color.WHITE) - }, - ) - root.addView(row3, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - } - EnglishLayer.NUMBERS -> { - addEnglishCharRow(root, listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")) - addEnglishCharRow(root, listOf("-", "/", ":", ";", "(", ")", "$", "&", "@", "\"")) - addEnglishSymbolActionRow(root, listOf(".", ",", "?", "!", "'")) - } - EnglishLayer.SYMBOLS -> { - addEnglishCharRow(root, listOf("[", "]", "{", "}", "#", "%", "^", "*", "+", "=")) - addEnglishCharRow(root, listOf("_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•")) - addEnglishSymbolActionRow(root, listOf(".", ",", "?", "!", "'")) - } - } - - val bottom = LinearLayout(this).apply { - gravity = android.view.Gravity.CENTER_VERTICAL - } - // Same sans-serif-medium as the letter grid (buildEnglishCharKey()'s - // letterView), applied after the fact rather than as a keyboardKey() - // parameter — keyboardKey() is shared by every panel's keys, and - // only these two English bottom-row labels are meant to match the - // letters' new weight for now. Size/color/position left exactly as - // keyboardKey() already set them. - // Swipe up on "123" for a comma and on Space for a full stop — the - // two marks the letter grid's own swipe-up symbols leave out. Neither - // key shows a hint for it; the preview bubble names the mark mid-swipe. - val onLetters = englishLayer == EnglishLayer.LETTERS - val modeButton = keyboardKey( - if (onLetters) "123" else "ABC", - 1.3f, - action = { handleEnglishBottomModeToggle() }, - swipeUpAction = if (onLetters) ({ commitEnglishChar(",") }) else null, - swipePreview = if (onLetters) "," else null, - ).apply { typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) } - // "Space" stays keyboardKey()'s own plain centered label (own - // View, own vertical centering, untouched by the hint) — per - // real-device feedback, side-by-side (hint right-aligned next to - // "Space", both 12sp) reads much better than the two stacked-line - // approaches tried first (a single two-line SpannableString label, - // and before that a padding-pushed overlay), both of which fought - // this row's actual (tighter than assumed) real height. - val spaceButton = keyboardKey("Space", 5f, action = { - if (latinInputMode == LatinInputMode.PINYIN) { - rimePinyinController.space { renderPinyinCandidates(it) } - return@keyboardKey - } - finalizeEnglishComposingWord() - rimePinyinController.clear() - commitEnglishSpace() - }, swipeUpAction = { commitEnglishChar(".") }, swipePreview = ".", longPressAction = { toggleLatinInputMode() }).apply { - // Same size as Return (17sp — keyboardKey()'s own special case - // for that label), per real-device feedback. - textSize = 17f - } - // Own View, overlaid on top of spaceButton (not inside its own - // text) — left-aligned and vertically centered. The hint keeps its - // own tap/long-press target, while upward swipes are delegated to - // spaceButton so the key's existing preview and commit handling is - // shared. Shows BOTH labels (拼音 always on top, 英文 always on the - // bottom — fixed position, per user request) rather than just naming - // the target mode — whichever is currently active is cherry red, the - // other gray, so long-press's effect is legible at a glance either - // way. - val spaceHint = TextView(this).apply { - val pinyinLabel = ui("拼音", "PINYIN") - val englishLabel = ui("英文", "ENGLISH") - val hintText = "$pinyinLabel\n$englishLabel" - val englishStart = hintText.length - englishLabel.length - val activeColor = if (isDarkTheme) Color.rgb(190, 45, 60) else Color.rgb(153, 26, 40) - val inactiveColor = tone(Color.rgb(150, 150, 150), Color.rgb(140, 140, 145)) - text = android.text.SpannableString(hintText).apply { - setSpan( - android.text.style.ForegroundColorSpan(if (latinInputMode == LatinInputMode.PINYIN) activeColor else inactiveColor), - 0, pinyinLabel.length, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, - ) - setSpan( - android.text.style.ForegroundColorSpan(if (latinInputMode == LatinInputMode.ENGLISH) activeColor else inactiveColor), - englishStart, hintText.length, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, - ) - } - textSize = 12f - gravity = android.view.Gravity.CENTER - setTypeface(typeface, android.graphics.Typeface.BOLD) - isClickable = true - isFocusable = true - contentDescription = ui("切换拼音和英文", "Switch between Pinyin and English") - setOnClickListener { toggleLatinInputMode() } - // Keep the hint above the raised space key so its tap target is - // the visible mode label rather than the key underneath it. - translationZ = dp(10).toFloat() - } - var forwardingSpaceSwipe = false - var spaceHintLongPressed = false - var spaceHintDown: MotionEvent? = null - fun dispatchSpaceTouch(event: MotionEvent) { - val forwarded = MotionEvent.obtain(event) - val hintLocation = IntArray(2) - val spaceLocation = IntArray(2) - spaceHint.getLocationOnScreen(hintLocation) - spaceButton.getLocationOnScreen(spaceLocation) - forwarded.offsetLocation( - (hintLocation[0] - spaceLocation[0]).toFloat(), - (hintLocation[1] - spaceLocation[1]).toFloat(), - ) - spaceButton.dispatchTouchEvent(forwarded) - forwarded.recycle() - } - spaceHint.setOnLongClickListener { - spaceHintLongPressed = true - toggleLatinInputMode() - true - } - spaceHint.setOnTouchListener { view, event -> - when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { - spaceHintDown?.recycle() - spaceHintDown = MotionEvent.obtain(event) - forwardingSpaceSwipe = false - spaceHintLongPressed = false + // Survives a presentation-only rebuild while processing, but this view + // still cannot cancel a different request started by a newer view. + var viewVoiceOwner = typingVoiceOwner + return ImeTypingPanel( + this, + ImePalette.resolve(isDarkTheme), + buildVoiceHeader(), + onAction = ::handleTypingAction, + onFeedback = ::performKeyHaptic, + onVoiceStart = { + if (recording || processing) { false - } - MotionEvent.ACTION_MOVE -> { - if (!forwardingSpaceSwipe && !spaceHintLongPressed && spaceHintDown != null && - spaceHintDown!!.y - event.y >= dp(10) - ) { - forwardingSpaceSwipe = true - view.cancelLongPress() - view.isPressed = false - view.parent?.requestDisallowInterceptTouchEvent(true) - spaceHintDown?.let { dispatchSpaceTouch(it) } - dispatchSpaceTouch(event) - true - } else if (forwardingSpaceSwipe) { - dispatchSpaceTouch(event) - true - } else { - false + } else if (!rimePinyinController.isEmpty()) { + updateStatus(ui("请先确认拼音候选,再开始说话", "Confirm the Pinyin candidate before speaking")) + false + } else { + finalizeEnglishComposingWord() + if (!recording && !processing) toggleDictation() + if (recording) { + viewVoiceOwner = ImeRequestOwner(sessionEpoch, imeRequestId) + typingVoiceOwner = viewVoiceOwner } + recording } - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - if (forwardingSpaceSwipe) { - dispatchSpaceTouch(event) - view.isPressed = false - forwardingSpaceSwipe = false - spaceHintDown?.recycle() - spaceHintDown = null - true - } else { - spaceHintDown?.recycle() - spaceHintDown = null - false + }, + onVoiceEnd = { cancelled -> + val owner = viewVoiceOwner + if (owner != null && owner == typingVoiceOwner && owner.matches(sessionEpoch, imeRequestId)) { + if (cancelled) { + viewVoiceOwner = null + typingVoiceOwner = null + if (recording || processing) cancelDictation() + } else if (recording) { + // Release stops capture, but ownership remains while the + // result is processing so the visible Cancel still works. + toggleDictation() } } - else -> forwardingSpaceSwipe - } - } - val spaceWrapper = FrameLayout(this).apply { - addView(spaceButton, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) - addView( - spaceHint, - FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, android.view.Gravity.CENTER_VERTICAL or android.view.Gravity.START).apply { - marginStart = dp(14) - }, - ) - layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 5f) - } - val returnButton = keyboardKey("Return", 1.7f, action = { - if (latinInputMode != LatinInputMode.PINYIN) finalizeEnglishComposingWord() - sendEnterKey() - }).apply { - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - // Same cherry red as the stroke panel's own right-side action - // rail (Color.rgb(153, 26, 40)), per product request; fixed - // white text regardless of theme since keyboardKey()'s own - // default text color reads poorly against red in light theme. - background = roundedButton(Color.rgb(153, 26, 40), dp(5)) - setTextColor(Color.WHITE) - } - bottom.addView(modeButton) - bottom.addView(spaceWrapper) - bottom.addView(returnButton) - root.addView(bottom, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - return root + }, + interfaceEnglish = englishUi, + interactionPolicy = interactionPolicy(), + onClearPreedit = ::clearPinyinEncoding, + onCommitRawPreedit = ::commitRawPinyinInput, + onCursorMove = ::handleTypingCursorMove, + onDeleteWord = ::handleTypingDeleteWord, + ).also { + typingPanel = it + renderTypingKeyboard() + refreshLatinCandidateBar() + renderClipboardQuickChip() + renderVoiceUi() + } + } + + private fun renderTypingKeyboard() { + typingPanel?.renderKeyboard( + ImeKeyboardLayer.valueOf(englishLayer.name), + if (latinInputMode == LatinInputMode.PINYIN) ImeTypingLanguage.PINYIN else ImeTypingLanguage.ENGLISH, + when (shiftState) { + ShiftState.OFF -> ImeLetterCase.LOWER + ShiftState.SHIFT_ONCE -> ImeLetterCase.SHIFT + ShiftState.CAPS_LOCK -> ImeLetterCase.CAPS_LOCK + }, + editorActionLabel(), + englishUi, + ) } - /** - * A plain character row (digits/symbols, no shift-sensitivity) built - * from buildEnglishCharKey() — key preview, no drag-to-adjacent-key - * distinction from a letter row since neither cares about shift. - * - * @param swipeSymbols Same size as [keys] when given (the QWERTY top - * row's own q..p -> 1..0 mapping) — forwarded 1:1 as each key's own - * swipe-up symbol. Left null for every other row (NUMBERS/SYMBOLS - * layers are already digits/symbols themselves; nothing to swipe up - * to). Clears englishSwipeSymbols first — this is always the first - * row built for a fresh LETTERS render (see buildKeyboardView()), so - * row2/row3's own direct buildEnglishCharKey() calls right after can - * add straight into the same now-fresh map without re-clearing it. - */ - private fun addEnglishCharRow(parent: LinearLayout, keys: List, swipeSymbols: List? = null) { - if (swipeSymbols != null) { - englishSwipeSymbols.clear() - englishLetterKeys.clear() - } - val row = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER } - keys.forEachIndexed { index, key -> - row.addView(buildEnglishCharKey(key, 1f, swipeSymbol = swipeSymbols?.getOrNull(index))) + private fun editorActionLabel(): String { + val options = currentInputEditorInfo?.imeOptions ?: 0 + if (draftEdit != null || options and EditorInfo.IME_FLAG_NO_ENTER_ACTION != 0) return ui("换行", "Return") + return when (options and EditorInfo.IME_MASK_ACTION) { + EditorInfo.IME_ACTION_SEARCH -> ui("搜索", "Search") + EditorInfo.IME_ACTION_SEND -> ui("发送", "Send") + EditorInfo.IME_ACTION_GO -> ui("前往", "Go") + EditorInfo.IME_ACTION_NEXT -> ui("下一项", "Next") + EditorInfo.IME_ACTION_DONE -> ui("完成", "Done") + else -> ui("换行", "Return") + } + } + + private fun handleTypingAction(action: ImeKeyAction) { + if (recording || processing) return + when (action) { + is ImeKeyAction.Text -> commitEnglishChar(action.value) + ImeKeyAction.Backspace -> englishDeleteBackward() + ImeKeyAction.Shift -> cycleEnglishShift() + ImeKeyAction.Language -> toggleLatinInputMode() + ImeKeyAction.ToggleNumbers -> handleEnglishBottomModeToggle() + ImeKeyAction.ToggleSymbols -> handleEnglishRow3ModeToggle() + ImeKeyAction.Space -> { + if (latinInputMode == LatinInputMode.PINYIN) { + rimePinyinController.space { renderPinyinCandidates(it) } + } else { + finalizeEnglishComposingWord() + commitEnglishSpace() + } + } + ImeKeyAction.Enter -> { + if (latinInputMode != LatinInputMode.PINYIN) finalizeEnglishComposingWord() + sendEnterKey() + } } - parent.addView(row, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - } - - /** - * 123 page's row 3 (`#+= . , ? ! ' ⌫`) and #+= page's row 3 - * (`123 . , ? ! ' ⌫`) — same shape, only the leading toggle - * key's label/action differs, so both layers share this one builder. - */ - private fun addEnglishSymbolActionRow(parent: LinearLayout, middleKeys: List) { - val row = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER } - val toggleLabel = if (englishLayer == EnglishLayer.NUMBERS) "#+=" else "123" - row.addView(keyboardKey(toggleLabel, 1.5f, action = { handleEnglishRow3ModeToggle() })) - middleKeys.forEach { row.addView(buildEnglishCharKey(it, 1f)) } - row.addView( - keyboardKey("⌫", 1.5f, action = { englishDeleteBackward() }, repeatOnLongPress = true, repeatAction = { englishDeleteBackward() }).apply { - background = roundedButton(Color.rgb(153, 26, 40), dp(5)) - setTextColor(Color.WHITE) - }, - ) - parent.addView(row, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) } /** Bottom-row toggle: always jumps straight to/from Letters, regardless of which of Numbers/Symbols was showing (matches iOS's own "ABC" key). */ @@ -1747,198 +1253,176 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt updateEnglishCandidates() } - /** - * The selected/first candidate is marked by color+weight only (the same - * red as the right-hand action rail's ←/↵/清除/123 keys, bold) — no - * size, background, border or shadow change, so it can't shift - * candidate width/spacing or row height. A real else branch (not just - * skipping the isFirst==false case) matters once populateCandidateRow() - * can reuse a view that used to be first-candidate for one that isn't. - */ - internal fun styleCandidateFirstState(view: TextView, isFirst: Boolean) { - if (isFirst) { - // Same red as the action rail's own background - // (Color.rgb(153, 26, 40)), brightened a touch for dark - // theme only — same hue, just a bit lighter so it reads - // more clearly against a dark panel; light theme keeps the - // exact action-rail red. - view.setTextColor(if (isDarkTheme) Color.rgb(190, 45, 60) else Color.rgb(153, 26, 40)) - view.setTypeface(view.typeface, android.graphics.Typeface.BOLD) + private class LatinCandidate(val label: String, val longPress: (() -> Unit)?, val action: () -> Unit) + + /** Provider callbacks become target-bound actions; presentation owns view reuse. */ + private fun populateLatinCandidateRow( + candidates: List, + leadingLabel: String? = null, + statusHint: String? = null, + ) { + val epoch = sessionEpoch + typingPanel?.submitCandidates(candidates.map { candidate -> + ImeTypingPanel.Candidate( + candidate.label, + select = { if (epoch == sessionEpoch && inputMode == InputMode.ENGLISH) candidate.action() }, + forget = candidate.longPress?.let { action -> + { if (epoch == sessionEpoch && inputMode == InputMode.ENGLISH) action() } + }, + ) + }, leadingLabel, statusHint) + } + + private fun syncPinyinComposingText(preedit: String?) { + val connection = currentInputConnection + val allowed = connection != null && + inputMode == InputMode.ENGLISH && + latinInputMode == LatinInputMode.PINYIN && + !ImeLearningPolicy.isPassword(currentInputEditorInfo?.inputType ?: 0) + if (allowed && !preedit.isNullOrEmpty()) { + connection.setComposingText(preedit, 1) + pinyinComposingActive = true } else { - view.setTextColor(tone(Color.rgb(245, 245, 245), Color.rgb(30, 30, 34))) - view.setTypeface(android.graphics.Typeface.DEFAULT, android.graphics.Typeface.NORMAL) + clearPinyinComposingInEditor() } } - /** - * Plain-text candidate item — no independent keycap background, just the - * label, matching a stroke candidate bar rather than a row of separate - * buttons. Height always comes from the parent row (MATCH_PARENT) so it - * can never itself grow the fixed 36dp candidate row. - */ - internal fun candidateItemView( - label: String, - isFirst: Boolean, - onLongPress: (() -> Unit)? = null, - action: () -> Unit, - ): TextView { - return keyboardKey(label, 1f, action = action, longPressAction = onLongPress).apply { - // Was 20f/dp(9); briefly tried 17f/dp(12) to fix a clipped-glyph - // report on a Xiaomi MIUI device (that OEM's default system - // font renders visibly wider per character than stock Android - // at the same sp), but 20sp reads noticeably better across - // devices — settled on keeping the original text size and - // widening padding a bit instead (dp(9) -> dp(11)), which still - // gives MIUI's wider glyphs a bit more breathing room without - // shrinking the text everyone else sees. - textSize = 20f - setSingleLine(true) - maxLines = 1 - background = null - elevation = 0f - translationZ = 0f - setPadding(dp(11), 0, dp(11), 0) - styleCandidateFirstState(this, isFirst) - } - } - - /** What a reusable candidate view in englishCandidateRow does when tapped, swapped on every reuse. */ - private class LatinCandidateSlot(val hasLongPress: Boolean) { - var action: () -> Unit = {} - var longPress: () -> Unit = {} + private fun clearPinyinComposingInEditor() { + if (!pinyinComposingActive) return + pinyinComposingActive = false + currentInputConnection?.let { connection -> + connection.setComposingText("", 1) + connection.finishComposingText() + } } - private class LatinCandidate(val label: String, val longPress: (() -> Unit)?, val action: () -> Unit) + private fun clearPinyinEncoding() { + clearPinyinComposingInEditor() + rimePinyinController.clear() + renderPinyinCandidates(emptyList()) + } - private var pinyinEncodingLabel: TextView? = null + private fun commitRawPinyinInput() { + if (latinInputMode != LatinInputMode.PINYIN || ImeLearningPolicy.isPassword(currentInputEditorInfo?.inputType ?: 0)) return + rimePinyinController.commitRawInput({ renderPinyinCandidates(it) }, {}) + } - /** - * Fills englishCandidateRow with [candidates] (after an optional - * non-clickable [leadingLabel], pinyin's in-progress encoding), reusing - * the candidate views already there — same idea as the stroke row's - * populateCandidateRow(): this runs on every keystroke, and creating a - * dozen keyboardKey() views each time was the costly part. A view's tap - * and long-press go through its LatinCandidateSlot, so reusing it only - * swaps the slot's actions; keyboardKey()'s own long-press handling - * (including swallowing the tap that ends a long press) stays intact. - * Only a view of the same kind is reused — whether it has a long press - * is fixed when keyboardKey() builds it. - */ - private fun populateLatinCandidateRow(candidates: List, leadingLabel: String? = null) { - val row = englishCandidateRow ?: return - val firstIsLabel = row.childCount > 0 && row.getChildAt(0) === pinyinEncodingLabel - var offset = 0 - if (leadingLabel != null) { - val label = if (firstIsLabel) pinyinEncodingLabel!! else TextView(this).apply { - textSize = 16f - setSingleLine(true) - gravity = android.view.Gravity.CENTER - setTextColor(tone(Color.rgb(180, 180, 180), Color.rgb(120, 120, 125))) - setPadding(dp(9), 0, dp(9), 0) - isClickable = false - }.also { - pinyinEncodingLabel = it - row.addView(it, 0, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)) - } - label.text = leadingLabel - offset = 1 - } else if (firstIsLabel) { - row.removeViewAt(0) - } - candidates.forEachIndexed { index, candidate -> - val position = offset + index - val existing = row.getChildAt(position) as? TextView - val existingSlot = existing?.let { latinCandidateSlots[it] } - val view: TextView - val slot: LatinCandidateSlot - if (existing != null && existingSlot != null && existingSlot.hasLongPress == (candidate.longPress != null)) { - view = existing - slot = existingSlot - } else { - val fresh = LatinCandidateSlot(candidate.longPress != null) - slot = fresh - view = candidateItemView( - candidate.label, - isFirst = index == 0, - onLongPress = if (fresh.hasLongPress) ({ fresh.longPress() }) else null, - action = { fresh.action() }, - ) - latinCandidateSlots[view] = fresh - if (existing != null || position < row.childCount) row.removeViewAt(position) - row.addView(view, position, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)) - } - slot.action = candidate.action - candidate.longPress?.let { slot.longPress = it } - if (view.text.toString() != candidate.label) view.text = candidate.label - view.contentDescription = candidate.label - styleCandidateFirstState(view, index == 0) - } - while (row.childCount > offset + candidates.size) row.removeViewAt(row.childCount - 1) - // Shared with the stroke panel's own candidate row (only one of the - // two is ever visible at a time) — see showCandidateOverlay(). - candidateOverlayEntries = candidates.map { it.label to it.action } - if (candidates.isEmpty()) englishExpandCandidatesButton?.visibility = View.GONE + private fun handleTypingCursorMove(delta: Int) { + if (delta == 0) return + if (latinInputMode == LatinInputMode.PINYIN && !rimePinyinController.isEmpty()) return + finalizeEnglishComposingWord() + val key = if (delta > 0) android.view.KeyEvent.KEYCODE_DPAD_RIGHT else android.view.KeyEvent.KEYCODE_DPAD_LEFT + sendClipboardCursorKey(key) } - /** - * "Show more candidates" overlay — a PopupWindow anchored below the - * candidate row, wrapping the current full candidate/association list - * (whichever is showing) into a flow of rows. A PopupWindow floats over - * the existing panel without resizing or displacing it, matching the - * "must not push the keys below or change the keyboard height" rule. - */ - internal fun showCandidateOverlay(anchor: View) { - if (candidateOverlayEntries.isEmpty()) return - var activePopup: android.widget.PopupWindow? = null - val content = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(dp(8), dp(8), dp(8), dp(8)) - } - var currentRow: LinearLayout? = null - var usedWidth = 0 - val maxRowWidth = resources.displayMetrics.widthPixels - dp(32) - candidateOverlayEntries.forEach { (label, action) -> - val itemWidth = dp((label.codePointCount(0, label.length) * 24 + 20).coerceAtLeast(52)) - if (currentRow == null || usedWidth + itemWidth > maxRowWidth) { - currentRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL } - content.addView(currentRow) - usedWidth = 0 - } - currentRow?.addView( - TextView(this).apply { - text = label - textSize = 21f - setSingleLine(true) - gravity = android.view.Gravity.CENTER - setTextColor(tone(Color.rgb(245, 245, 245), Color.rgb(30, 30, 34))) - setPadding(dp(10), dp(10), dp(10), dp(10)) - setOnClickListener { - action() - activePopup?.dismiss() - } - }, - LinearLayout.LayoutParams(itemWidth, dp(46)), - ) - usedWidth += itemWidth + private fun handleTypingDeleteWord() { + if (latinInputMode == LatinInputMode.PINYIN && !rimePinyinController.isEmpty()) { + clearPinyinEncoding() + return + } + clearEnglishAutoText() + finalizeEnglishComposingWord() + val connection = currentInputConnection ?: return + val selected = connection.getSelectedText(0)?.toString() + if (!selected.isNullOrEmpty()) { + if (connection.commitText("", 1)) offerUndoDeleteChip(selected) + return } - val scroll = android.widget.ScrollView(this).apply { - isVerticalScrollBarEnabled = false - addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + val before = connection.getTextBeforeCursor(24, 0)?.toString().orEmpty() + if (before.isEmpty()) return + val deleteLen = computeWordDeleteLength(before) + if (deleteLen <= 0) return + val removed = before.takeLast(deleteLen) + if (connection.deleteSurroundingText(deleteLen, 0)) { + rimePinyinController.resetAssociationContext() + offerUndoDeleteChip(removed) + } + } + + private fun computeWordDeleteLength(before: String): Int { + var idx = before.length + while (idx > 0 && before[idx - 1].isWhitespace()) idx-- + if (idx == 0) return before.length + val last = before[idx - 1] + if (last.isLetterOrDigit() && last.code < 128) { + while (idx > 0 && (before[idx - 1].isLetterOrDigit() && before[idx - 1].code < 128 || before[idx - 1] == '\'')) idx-- + } else if (last in '\u4e00'..'\u9fff') { + var chars = 0 + while (idx > 0 && chars < 4 && before[idx - 1] in '\u4e00'..'\u9fff') { + idx-- + chars++ + } + } else { + idx-- } - val card = LinearLayout(this).apply { - addView(scroll, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - background = roundedButton(tone(Color.rgb(45, 45, 45), Color.rgb(238, 238, 241)), dp(8)) + return (before.length - idx).coerceAtLeast(1) + } + + private fun offerUndoDeleteChip(deleted: String) { + if (deleted.isEmpty() || isSensitiveField(currentInputEditorInfo)) return + quickChipPayload = deleted + val preview = deleted.replace('\n', ' ').take(10) + quickChipLabel = ui("撤销删除「$preview」", "Undo \"$preview\"") + quickChipExpiresAtMs = android.os.SystemClock.elapsedRealtime() + 15_000L + quickChipIsUndoDelete = true + renderClipboardQuickChip() + } + + private fun offerClipboardQuickChip(rawText: String) { + val trimmed = rawText.trim() + if (trimmed.isEmpty() || trimmed.length > 200) return + val otp = extractVerificationCode(trimmed) + if (otp != null) { + quickChipPayload = otp + quickChipLabel = ui("验证码: $otp", "Code: $otp") + } else { + quickChipPayload = trimmed + val preview = trimmed.replace('\n', ' ').take(18) + quickChipLabel = ui("粘贴: $preview", "Paste: $preview") + } + quickChipExpiresAtMs = android.os.SystemClock.elapsedRealtime() + 120_000L + quickChipIsUndoDelete = false + renderClipboardQuickChip() + } + + private fun extractVerificationCode(text: String): String? { + if (text.matches(Regex("\\d{4,8}"))) return text + val hasCue = text.contains("验证码") || text.contains("校验码") || text.contains("动态码") || + text.contains("code", ignoreCase = true) || text.contains("otp", ignoreCase = true) + if (!hasCue) return null + return Regex("(? quickChipExpiresAtMs || + (!quickChipIsUndoDelete && isSensitiveField(currentInputEditorInfo)) + ) { + panel.setClipboardSuggestion(null, {}, {}) + return } - val popup = android.widget.PopupWindow( - card, - resources.displayMetrics.widthPixels, - dp(150), - true, + panel.setClipboardSuggestion( + label, + onPaste = { + val connection = currentInputConnection + if (connection != null && connection.commitText(payload, 1)) { + performKeyHaptic() + dismissQuickChip() + } + }, + onDismiss = ::dismissQuickChip, ) - activePopup = popup - popup.isOutsideTouchable = true - popup.elevation = dp(8).toFloat() - popup.showAsDropDown(anchor, -anchor.left, dp(2)) } /** @@ -1957,17 +1441,23 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt val isLeft = code == android.view.KeyEvent.KEYCODE_DPAD_LEFT val isRight = code == android.view.KeyEvent.KEYCODE_DPAD_RIGHT if (clipboardSelectionMode && (isLeft || isRight)) { - if (clipboardSelectionAnchor < 0) { - val extracted = connection.getExtractedText(android.view.inputmethod.ExtractedTextRequest(), 0) - val start = extracted?.selectionStart?.coerceAtLeast(0) ?: 0 - clipboardSelectionAnchor = start - clipboardSelectionActive = start - } - clipboardSelectionActive = (clipboardSelectionActive + if (isRight) 1 else -1).coerceAtLeast(0) - connection.setSelection( - minOf(clipboardSelectionAnchor, clipboardSelectionActive), - maxOf(clipboardSelectionAnchor, clipboardSelectionActive), + val extracted = connection.getExtractedText(android.view.inputmethod.ExtractedTextRequest(), 0) + val previous = if (clipboardSelectionAnchor >= 0 && clipboardSelectionActive >= 0) { + ImeSelectionRange(clipboardSelectionAnchor, clipboardSelectionActive) + } else null + val range = ImeSelectionPolicy.extend( + extracted?.text, extracted?.startOffset ?: -1, + extracted?.selectionStart ?: -1, extracted?.selectionEnd ?: -1, + previous, if (isRight) 1 else -1, ) + if (range != null && connection.setSelection(minOf(range.anchor, range.active), maxOf(range.anchor, range.active))) { + clipboardSelectionAnchor = range.anchor + clipboardSelectionActive = range.active + } else { + // Unknown/partial/changed editor data must not select from a guessed zero. + clipboardSelectionAnchor = -1 + clipboardSelectionActive = -1 + } return } val now = android.os.SystemClock.uptimeMillis() @@ -1975,883 +1465,121 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt connection.sendKeyEvent(android.view.KeyEvent(now, now, android.view.KeyEvent.ACTION_UP, code, 0)) } - /** - * Clipboard panel: a direction pad (arrow keys double as selection - * extension when "选择" is toggled on) plus select-all/copy/paste and a - * button into the clipboard history browser. Styled like the stroke - * panel's own key grid. - */ - private fun buildClipboardView(): View { - val root = SwipeModeContainer(this) { direction -> swipeInputMode(direction) }.apply { - orientation = LinearLayout.VERTICAL - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyboardPanelHeightPx()) - minimumHeight = keyboardPanelHeightPx() - setPadding(dp(8), dp(8), dp(8), dp(8)) - setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - } - root.addView(buildVoiceHeader(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(38)).apply { - marginStart = dp(8) - marginEnd = dp(8) - }) - - // Most-recent-three-clips quick-tap strip (was four rows — reduced - // per user request, the freed space redistributed evenly across the - // remaining three so RECENT_CLIPS_COLUMN_HEIGHT_DP's own total is - // unchanged; see that constant's doc comment for the exact math). - // The rows use circled Unicode digits (①②③) for their prefixes; the - // glyphs come from Android's normal font fallback rather than a - // hand-drawn canvas shape. Flat gray now (was white prefix + cherry - // red content, before that a blue accent) — per user request, no - // color distinction between the prefix and the clip text anymore. - // The action grid below shrinks by the strip's fixed height - // automatically (LinearLayout's own weight=1f on `grid` further - // down already absorbs however much space this strip doesn't use — - // no separate shrink logic needed). Thin divider lines separate the - // rows rather than a colored background, matching the plain-divider - // treatment already used for the English candidate bar. - val circledIndices = listOf('①', '②', '③') - val recentClipTextColor = tone(Color.rgb(190, 190, 190), Color.rgb(140, 140, 145)) - fun recentClipRow(index: Int, entry: ClipboardEntry?): TextView = TextView(this).apply { - text = entry?.let { "${circledIndices[index]} ${it.text}" } ?: "" - textSize = 16f - maxLines = 1 - ellipsize = android.text.TextUtils.TruncateAt.END - gravity = android.view.Gravity.CENTER_VERTICAL - setTextColor(recentClipTextColor) - setPadding(dp(10), 0, dp(10), 0) - if (entry != null) { - isClickable = true - setOnClickListener { - currentInputConnection?.commitText(entry.text, 1) - OpenLessClipboardHistory.recordCopy(this@OpenLessImeService, entry.text) - refreshInputView() - } - } - } - // distinctBy(text): recordCopy() already dedupes going forward (an - // existing entry is moved to the front instead of a second row being - // added), but this guards the display itself against any duplicate - // already sitting in an existing history file (e.g. one written - // before that dedup existed) rather than trusting the stored data. - val recentClips = OpenLessClipboardHistory.load(this).distinctBy { it.text } - val recentClipsColumn = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } - recentClipsColumn.addView(buildDivider(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1))) - for (index in 0 until 3) { - recentClipsColumn.addView( - recentClipRow(index, recentClips.getOrNull(index)), - LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f), - ) - recentClipsColumn.addView(buildDivider(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1))) - } - // Added to root below the action grid, not here — per user request, - // the keyboard/action grid sits above the recent-clips strip now - // (was the other way around). - - // Arrow keys and the Select toggle work as one unit: while selection - // mode is on, the arrows extend the selection instead of just moving - // the cursor, so they share the same active-highlight background as - // the Select button itself — and lose it the moment it's toggled off. - val gap = dp(6) - val mediumTypeface = android.graphics.Typeface.create("sans-serif-medium", android.graphics.Typeface.NORMAL) - val softWhite = tone(Color.rgb(224, 224, 224), Color.rgb(40, 40, 44)) - - // Same keycap background as the stroke panel's own keys (plain - // keyboardKey() default background/elevation for the normal state, - // roundedButton() with the same rose highlight the stroke panel's - // own "繁" toggle uses when active) — only the label/icon size and - // grid spacing are new, not the button's edge style or palette. - fun quickActionLabel(label: String, action: () -> Unit, textSizeSp: Float, highlighted: Boolean = false, midDivider: Boolean = false) = - keyboardKey(label, 1f, action = action, midDivider = midDivider).apply { - textSize = textSizeSp - typeface = mediumTypeface - setTextColor(softWhite) - if (highlighted) background = roundedButton(tone(Color.rgb(112, 78, 92), Color.rgb(232, 205, 213)), dp(5)) - attachPressScale(this) - } + private var clipboardPanel: ImeClipboardPanel? = null - fun quickActionIcon( - graphicActionCode: String, - action: () -> Unit, - highlighted: Boolean = false, - rotationDegrees: Float = 0f, - repeatOnLongPress: Boolean = false, - // Unlike the stroke panel's always-dark-red action keys (white - // in both themes, StrokeActionView's own default), these icons - // normally sit on a normal or rose key that flips with the - // theme — pass an explicit color for a caller whose key is red - // regardless of theme (e.g. backspaceKey below), same reasoning - // as keyboardKey()'s own graphicIconColor doc comment. - iconColor: Int = tone(Color.WHITE, Color.rgb(30, 30, 34)), - ) = keyboardKey( - "", - 1f, - action = action, - repeatOnLongPress = repeatOnLongPress, - repeatAction = if (repeatOnLongPress) action else null, - graphicActionCode = graphicActionCode, - // Rotates only the icon drawn on the canvas, not the button - // View itself — rotating the whole View would also distort its - // rectangular background in a non-square cell. - graphicRotation = rotationDegrees, - graphicIconColor = iconColor, - ).apply { - if (highlighted) background = roundedButton(tone(Color.rgb(112, 78, 92), Color.rgb(232, 205, 213)), dp(5)) - attachPressScale(this) - } - - fun cell(): LinearLayout.LayoutParams { - val params = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f) - params.marginStart = gap / 2 - params.marginEnd = gap / 2 - return params - } - - val grid = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } - val row1 = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER } - val selectKey = quickActionLabel(ui("选择", "Range"), { - clipboardSelectionMode = !clipboardSelectionMode - clipboardSelectionAnchor = -1 - clipboardSelectionActive = -1 - refreshInputView() - }, 20f, highlighted = clipboardSelectionMode) - val leftKey = quickActionIcon("dir-up", { sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_LEFT) }, clipboardSelectionMode, rotationDegrees = 270f) - val rightKey = quickActionIcon("dir-up", { sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_RIGHT) }, clipboardSelectionMode, rotationDegrees = 90f) - val upKey = quickActionIcon("dir-up", { sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_UP) }, clipboardSelectionMode, rotationDegrees = 0f) - val downKey = quickActionIcon("dir-up", { sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_DOWN) }, clipboardSelectionMode, rotationDegrees = 180f) - for (key in listOf(selectKey, leftKey, rightKey, upKey, downKey)) { - row1.addView(key, cell()) - } - grid.addView(row1, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f).apply { - bottomMargin = gap / 2 - topMargin = gap / 2 - }) - - val row2 = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER } - val selectAllKey = quickActionLabel(ui("全选", "Select"), { - currentInputConnection?.performContextMenuAction(android.R.id.selectAll) - }, 20f) - val copyKey = quickActionLabel(ui("复制", "Copy"), { - currentInputConnection?.performContextMenuAction(android.R.id.copy) - }, 20f) - val pasteKey = quickActionLabel(ui("粘贴", "Paste"), { - currentInputConnection?.performContextMenuAction(android.R.id.paste) - }, 20f) - // Two lines ("History" / "Edit") since this button opens both the - // clipboard history browser (tap) and the draft bar for whatever's - // selected in the real input field (long-press). - // quickActionLabel()->keyboardKey()'s own '\n' handling shrinks only - // the label's first character (built for single-char rows like - // "1\n!"), which would leave just one letter undersized here, so the - // spanned text it sets is overwritten with a plain two-line string - // right after construction. - // Same cherry red as the stroke panel's own right-side action rail - // (Color.rgb(153, 26, 40)) — per product request, so these two keys - // read as the equivalent "action" keys on this panel. - val clipboardKey = quickActionLabel(ui("历史\n编辑", "History\nEdit"), { - clipboardHistoryMode = true - refreshInputView() - }, 17f, midDivider = true).apply { - text = ui("历史\n编辑", "History\nEdit") - background = roundedButton(Color.rgb(153, 26, 40), dp(5)) - // quickActionLabel()'s own softWhite text color reads fine on a - // normal/rose key but not on this now-red one (dark gray in - // light theme, on dark red) — fixed white regardless of theme, - // same reasoning as backspaceKey's iconColor override below. - setTextColor(Color.WHITE) - setOnLongClickListener { - openDictationEditDraft(requireSelection = true) - true - } - } - val backspaceKey = quickActionIcon( - "backspace-icon", - { deleteBackward() }, - repeatOnLongPress = true, - iconColor = Color.WHITE, - ).apply { - background = roundedButton(Color.rgb(153, 26, 40), dp(5)) - } - for (key in listOf(selectAllKey, copyKey, pasteKey, clipboardKey, backspaceKey)) { - row2.addView(key, cell()) - } - grid.addView(row2, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f).apply { - topMargin = gap / 2 - }) + private fun buildClipboardView(): View = buildClipboardSurface() + private fun buildClipboardHistoryView(): View = buildClipboardSurface() - root.addView(grid, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f).apply { - topMargin = dp(8) - }) - root.addView(recentClipsColumn, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(RECENT_CLIPS_COLUMN_HEIGHT_DP)).apply { - topMargin = dp(8) - }) - return root + private fun buildClipboardSurface(): View = ImeClipboardPanel( + this, keyboardPalette(), buildVoiceHeader(), englishUi, + onCommand = ::handleClipboardCommand, + onCategory = { category -> + if (clipboardActionCurrent(sessionEpoch)) { + OpenLessClipboardHistory.Category.entries.firstOrNull { it.name == category }?.let { + clipboardHistoryCategory = it + renderClipboardPanel() + } + } + }, + onFeedback = ::performKeyHaptic, + interactionPolicy = interactionPolicy(), + ).also { + clipboardPanel = it + renderClipboardPanel() } - /** - * Clipboard history browser: category tabs (全部/最近/文本/数字/链接) over a - * scrollable list of past clips. Tapping an entry commits it to the field - * and bumps it back to the front of the history, then returns to the - * direction-pad panel. - */ - private fun buildClipboardHistoryView(): View { - // Assigned once `scroll` itself is built, further down — captured - // by reference here so SwipeModeContainer's verticalDismissAllowed - // lambda reads whatever scroll position exists at actual touch - // time (the lambda only ever runs from a real user gesture, well - // after this whole view is fully constructed). - var historyScroll: android.widget.ScrollView? = null - // Rows handle their own left/right swipe (favorite / correction - // rule); the panel-switch swipe would otherwise compete for the - // exact same gesture. A downward drag only dismisses the keyboard - // once the list below is already scrolled to its own top — per - // user request, so scrolling up through history doesn't get - // mistaken for "swipe down to hide" partway through. - val root = SwipeModeContainer( - this, - horizontalSwipeEnabled = false, - verticalDismissAllowed = { (historyScroll?.scrollY ?: 0) == 0 }, - ) { direction -> swipeInputMode(direction) }.apply { - orientation = LinearLayout.VERTICAL - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, keyboardPanelHeightPx()) - minimumHeight = keyboardPanelHeightPx() - setPadding(dp(16), dp(8), dp(16), dp(8)) - setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - clipChildren = false - clipToPadding = false - } - root.addView(buildVoiceHeader(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(38))) - root.addView(buildDivider(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1)).apply { - topMargin = dp(6) - }) - - val tabsRow = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER_VERTICAL } - val tabs = listOf( - OpenLessClipboardHistory.Category.ALL to ui("全部", "All"), - OpenLessClipboardHistory.Category.RECENT to ui("最近", "Recent"), - OpenLessClipboardHistory.Category.TEXT to ui("文本", "Text"), - OpenLessClipboardHistory.Category.NUMBER to ui("数字", "Number"), - OpenLessClipboardHistory.Category.LINK to ui("链接", "Link"), - ) - tabs.forEach { (category, label) -> - val selected = category == clipboardHistoryCategory - tabsRow.addView(TextView(this).apply { - text = label - textSize = 14f - gravity = android.view.Gravity.CENTER - setTextColor(if (selected) Color.rgb(153, 26, 40) else tone(Color.rgb(190, 190, 190), Color.rgb(140, 140, 145))) - if (englishUi) { - typeface = Typeface.create("sans-serif-medium", if (selected) Typeface.BOLD else Typeface.NORMAL) - } else { - setTypeface(typeface, if (selected) android.graphics.Typeface.BOLD else android.graphics.Typeface.NORMAL) + private fun clipboardActionCurrent(epoch: Long): Boolean = + epoch == sessionEpoch && inputMode == InputMode.CLIPBOARD && isInputViewShown && !dictationEditingLocked() + + private fun renderClipboardPanel() { + val panel = clipboardPanel ?: return + val epoch = sessionEpoch + val all = OpenLessClipboardHistory.load(this).distinctBy { it.text } + val vocabulary = if (clipboardHistoryMode && isBackendReady()) { + runCatching { + val array = org.json.JSONArray(OpenLessNative.nativeVocabularyPhrases()) + (0 until array.length()).mapTo(mutableSetOf()) { array.getString(it) } + }.getOrDefault(emptySet()) + } else emptySet() + fun item(entry: ClipboardEntry) = ImeClipboardPanel.Item( + text = entry.text, + favorite = entry.favorite, + inDictionary = entry.text in vocabulary, + select = { + if (clipboardActionCurrent(epoch)) pasteClipboardHistory(entry.text) + }, + toggleFavorite = { + if (clipboardActionCurrent(epoch)) { + OpenLessClipboardHistory.toggleFavorite(this, entry.text) + renderClipboardPanel() } - setOnClickListener { - clipboardHistoryCategory = category - refreshInputView() + }, + remove = { + if (clipboardActionCurrent(epoch)) { + OpenLessClipboardHistory.delete(this, entry.text) + renderClipboardPanel() } - }, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f)) - } - // Not a category filter like the five tabs above — an action: - // deletes every non-favorited history entry outright (favorites are - // kept). Never shows "selected" styling since it isn't one of - // clipboardHistoryCategory's own values. No confirmation step per - // the request as given; only this app's own local history is - // affected, not anything external. - tabsRow.addView(TextView(this).apply { - text = ui("清空", "Clear") - textSize = 14f - gravity = android.view.Gravity.CENTER - setTextColor(tone(Color.rgb(190, 190, 190), Color.rgb(140, 140, 145))) - if (englishUi) { - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - } - setOnClickListener { - OpenLessClipboardHistory.clearNonFavorites(this@OpenLessImeService) - refreshInputView() - } - }, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f)) - tabsRow.addView(flatCircleButton("✕", 26, ui("关闭粘贴板", "Close clipboard")) { + }, + toggleDictionary = { + if (clipboardActionCurrent(epoch)) toggleClipboardDictionary(entry.text, entry.text in vocabulary) + }, + ) + panel.render( + epoch, clipboardHistoryMode, clipboardSelectionMode, clipboardHistoryCategory.name, + OpenLessClipboardHistory.filter(all, clipboardHistoryCategory).map(::item), + all.take(3).map(::item), + ) + panel.setBlocked(dictationEditingLocked()) + } + + private fun pasteClipboardHistory(text: String) { + if (currentInputConnection?.commitText(text, 1) == true) { + OpenLessClipboardHistory.recordCopy(this, text) clipboardHistoryMode = false - refreshInputView() - }, LinearLayout.LayoutParams(dp(30), dp(30))) - root.addView(tabsRow, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(34)).apply { - topMargin = dp(8) - }) - - root.addView(buildDivider(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1)).apply { - topMargin = dp(6) - bottomMargin = dp(6) - }) - - val listContainer = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } - val entries = OpenLessClipboardHistory.filter(OpenLessClipboardHistory.load(this), clipboardHistoryCategory) - // The Dictionary lives in the Rust backend (CORE_BACKEND), which is - // only registered once mobile_runtime::run()'s setup() has actually - // executed — not guaranteed just because the IME is showing. Without - // this, nativeVocabularyPhrases()/nativeAddVocabularyWord() below - // silently no-op against an unregistered backend: the star-like icon - // never appears and the swipe zone's "add" never takes, with no - // visible error either place. - ensureBackendReady() - // Fetched once per panel build, not per row: a native round trip - // per row would be wasted work when a single JSON snapshot already - // answers "is this text already in the dictionary" for all of them. - val vocabularyPhrases: Set = try { - val array = org.json.JSONArray(OpenLessNative.nativeVocabularyPhrases()) - (0 until array.length()).mapTo(mutableSetOf()) { array.getString(it) } - } catch (error: Exception) { - emptySet() - } - if (entries.isEmpty()) { - listContainer.addView(TextView(this).apply { - text = ui("暂无粘贴板记录", "No clipboard history yet") - textSize = 14f - if (englishUi) typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - gravity = android.view.Gravity.CENTER - setTextColor(tone(Color.rgb(140, 140, 140), Color.rgb(140, 140, 145))) - setPadding(0, dp(20), 0, 0) - }) + renderClipboardPanel() } else { - entries.forEachIndexed { index, entry -> - // Two fixed-width zones behind the row, revealed left-to-right - // as it's dragged right: favorite first, delete beyond it. A - // third zone behind the row's end, revealed right-to-left as - // it's dragged left, toggles a correction rule for this text. - val entryWrapper = FrameLayout(this) - val zoneWidth = dp(88) - val revealRow = LinearLayout(this) - val favoriteZone = TextView(this).apply { - textSize = 13f - setTypeface(typeface, android.graphics.Typeface.BOLD) - gravity = android.view.Gravity.CENTER - setTextColor(Color.WHITE) - setBackgroundColor(Color.rgb(181, 136, 32)) - setPadding(dp(6), 0, dp(6), 0) - } - val deleteZone = TextView(this).apply { - text = ui("删除", "Delete") - textSize = 13f - setTypeface(typeface, android.graphics.Typeface.BOLD) - gravity = android.view.Gravity.CENTER - setTextColor(Color.WHITE) - setBackgroundColor(Color.rgb(153, 26, 40)) - setPadding(dp(6), 0, dp(6), 0) - } - revealRow.addView(favoriteZone, LinearLayout.LayoutParams(zoneWidth, ViewGroup.LayoutParams.MATCH_PARENT)) - revealRow.addView(deleteZone, LinearLayout.LayoutParams(zoneWidth, ViewGroup.LayoutParams.MATCH_PARENT)) - entryWrapper.addView(revealRow, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)) - val correctionZone = TextView(this).apply { - textSize = 13f - setTypeface(typeface, android.graphics.Typeface.BOLD) - gravity = android.view.Gravity.CENTER - setTextColor(Color.WHITE) - setBackgroundColor(Color.rgb(46, 108, 168)) - setPadding(dp(6), 0, dp(6), 0) - } - entryWrapper.addView( - correctionZone, - FrameLayout.LayoutParams(zoneWidth, ViewGroup.LayoutParams.MATCH_PARENT, android.view.Gravity.END), - ) + OpenLessNativeNotice.makeText(this, ui("输入连接已失效,未粘贴", "Editor unavailable; nothing pasted"), Toast.LENGTH_SHORT).show() + } + } - val row = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER_VERTICAL } - val star = TextView(this).apply { - text = if (entry.favorite) "★" else "☆" - textSize = 14f - setTextColor( - if (entry.favorite) Color.rgb(153, 26, 40) else tone(Color.rgb(120, 120, 120), Color.rgb(180, 180, 184)), - ) - } - row.addView(star, LinearLayout.LayoutParams(dp(22), ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginEnd = dp(4) }) - row.addView( - TextView(this).apply { - text = entry.text - textSize = 14f - setTextColor(tone(Color.rgb(230, 230, 230), Color.rgb(30, 30, 34))) - maxLines = 2 - ellipsize = android.text.TextUtils.TruncateAt.END - }, - LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f), - ) - // After the weighted text view, not before it, so this lands - // at the row's far right edge instead of crowding the star. - if (vocabularyPhrases.contains(entry.text)) { - row.addView( - TextView(this).apply { - text = "✎" - textSize = 13f - setTextColor(Color.rgb(90, 156, 224)) - }, - LinearLayout.LayoutParams(dp(16), ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginStart = dp(4) }, - ) - } - // Plain flat row — no keycap-style background/press effect — - // but still opaque, so it fully hides the reveal zones until dragged. - row.setPadding(dp(12), dp(10), dp(12), dp(10)) - row.setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - entryWrapper.addView(row, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - - var suppressRowClick = false - row.setOnClickListener { - if (suppressRowClick) { - suppressRowClick = false - return@setOnClickListener - } - currentInputConnection?.commitText(entry.text, 1) - OpenLessClipboardHistory.recordCopy(this@OpenLessImeService, entry.text) - clipboardHistoryMode = false - refreshInputView() - } - attachClipboardRowSwipe( - row = row, - zoneWidth = zoneWidth, - favoriteZone = favoriteZone, - correctionZone = correctionZone, - isFavorite = { entry.favorite }, - hasCorrectionRule = { vocabularyPhrases.contains(entry.text) }, - addLabel = ui("加入收藏", "Add"), - removeLabel = ui("取消收藏", "Remove"), - addCorrectionLabel = ui("加入词典", "Add to dictionary"), - removeCorrectionLabel = ui("移出词典", "Remove from dictionary"), - onSuppressClick = { suppressRowClick = true }, - onToggleFavorite = { - OpenLessClipboardHistory.toggleFavorite(this, entry.text) - refreshInputView() - }, - onDelete = { - OpenLessClipboardHistory.delete(this, entry.text) - refreshInputView() - }, - onAddCorrection = { - runNativeAction("加入词典") { OpenLessNative.nativeAddVocabularyWord(entry.text) } - refreshInputView() - }, - onRemoveCorrection = { - OpenLessNative.nativeRemoveVocabularyWord(entry.text) - refreshInputView() - }, - ) - listContainer.addView(entryWrapper, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - if (index < entries.lastIndex) { - listContainer.addView(buildDivider(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1))) - } - } + private fun toggleClipboardDictionary(text: String, present: Boolean) { + if (!isBackendReady()) { + ensureBackendReady() + OpenLessNativeNotice.makeText(this, ui("词典服务正在准备,请稍后重试", "Dictionary is preparing; please retry"), Toast.LENGTH_SHORT).show() + return } - val scroll = android.widget.ScrollView(this).apply { - isVerticalScrollBarEnabled = false - overScrollMode = View.OVER_SCROLL_NEVER - addView(listContainer, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + runCatching { + if (present) OpenLessNative.nativeRemoveVocabularyWord(text) else OpenLessNative.nativeAddVocabularyWord(text) + }.onSuccess { renderClipboardPanel() }.onFailure { + OpenLessNativeNotice.makeText(this, ui("词典操作失败,请重试", "Dictionary operation failed; please retry"), Toast.LENGTH_SHORT).show() } - historyScroll = scroll - root.addView(scroll, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - return root } - /** - * Left/right swipe on one clipboard history row: the row itself tracks - * the finger 1:1 via translationX, revealing fixed-width zones behind it - * — favorite then delete to the right as it's dragged right, a single - * correction-rule zone to the left as it's dragged left — each clamped - * so the drag can't pull the row past its own side's zone width(s). - * Releasing inside a zone commits that zone's action; releasing short - * of it just springs the row back with no effect, on either side. - * - * Uses rawX/rawY, not the view-local x/y: once translationX starts - * moving the row mid-gesture, view-local coordinates from the same - * ongoing touch stream are reported relative to the view's shifting - * transform and drift, while raw screen coordinates stay stable for the - * whole gesture. - * - * onSuppressClick runs synchronously inside this same ACTION_UP handling - * — not deferred — because the row's own click (paste + close panel) - * gets evaluated by the View's default onTouchEvent immediately after - * this listener returns, within the very same event. Deferring the - * suppress flag (as a first cut of this did, bundled inside the action - * callback) let that stale click fire first: it pasted the row's text, - * reordered it to the front via recordCopy(), and closed back to the - * main clipboard view — exactly the "jumps back / reorders" symptom. - * onToggleFavorite/onDelete/onAddCorrection/onRemoveCorrection can still - * be posted, since only *those* (which rebuild the whole panel) need to - * avoid the panel flickering mid-gesture. - * - * The panel's own SwipeModeContainer has `horizontalSwipeEnabled = false` - * for this sub-panel specifically, so there is no competing ancestor - * gesture to race against here — recognizing the drag on ACTION_MOVE and - * calling requestDisallowInterceptTouchEvent is enough to keep the - * ScrollView from also treating it as a scroll attempt. - */ - private fun attachClipboardRowSwipe( - row: View, - zoneWidth: Int, - favoriteZone: TextView, - correctionZone: TextView, - isFavorite: () -> Boolean, - hasCorrectionRule: () -> Boolean, - addLabel: String, - removeLabel: String, - addCorrectionLabel: String, - removeCorrectionLabel: String, - onSuppressClick: () -> Unit, - onToggleFavorite: () -> Unit, - onDelete: () -> Unit, - onAddCorrection: () -> Unit, - onRemoveCorrection: () -> Unit, - ) { - val touchSlop = android.view.ViewConfiguration.get(this).scaledTouchSlop - val maxDragRight = zoneWidth * 2f - val maxDragLeft = zoneWidth.toFloat() - var startRawX = 0f - var startRawY = 0f - var horizontalDrag = false - row.setOnTouchListener { view, event -> - when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { - startRawX = event.rawX - startRawY = event.rawY - horizontalDrag = false - favoriteZone.text = if (isFavorite()) removeLabel else addLabel - correctionZone.text = if (hasCorrectionRule()) removeCorrectionLabel else addCorrectionLabel - } - MotionEvent.ACTION_MOVE -> { - val dx = event.rawX - startRawX - val dy = event.rawY - startRawY - if (!horizontalDrag && kotlin.math.abs(dx) > touchSlop && kotlin.math.abs(dx) > kotlin.math.abs(dy) * 1.5f) { - horizontalDrag = true - view.parent?.requestDisallowInterceptTouchEvent(true) - } - if (horizontalDrag) view.translationX = dx.coerceIn(-maxDragLeft, maxDragRight) - } - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - if (horizontalDrag) { - val dx = event.rawX - startRawX - if (dx > 0f) { - val clamped = dx.coerceIn(0f, maxDragRight) - when { - clamped >= maxDragRight -> { - onSuppressClick() - view.post { onDelete() } - } - clamped >= zoneWidth -> { - onSuppressClick() - view.post { onToggleFavorite() } - } - } - } else if (dx < 0f) { - val clamped = dx.coerceIn(-maxDragLeft, 0f) - // Only past the full zone width — the label is - // fully revealed by then — does releasing commit - // anything; short of that just springs back. - if (clamped <= -zoneWidth) { - onSuppressClick() - if (hasCorrectionRule()) { - view.post { onRemoveCorrection() } - } else { - view.post { onAddCorrection() } - } - } - } - view.animate().translationX(0f).setDuration(150L).start() - } - horizontalDrag = false - } - } - // Never consumed: a plain tap (no horizontal drag recognized) - // still needs to fall through to the row's own click listener. - false - } - } - - internal fun keyboardKey( - label: String, - weight: Float, - action: () -> Unit = {}, - repeatOnLongPress: Boolean = false, - repeatAction: (() -> Unit)? = null, - swipeUpAction: (() -> Unit)? = null, - swipePreview: String? = null, - // A single-shot delayed action, separate from - // repeatOnLongPress/repeatAction — used by the voice/mic key, whose - // long-press (switch to Voice mode) needs a longer fuse than the - // system's fixed ~500ms long-click timeout so a swipe-up gesture - // that pauses briefly before moving isn't preempted by it (see - // ACTION_MOVE below, which cancels this the moment the swipe-up - // threshold is crossed). setOnLongClickListener's timeout isn't - // adjustable per-view, so this schedules/cancels its own Handler - // callback instead of relying on it. - longPressAction: (() -> Unit)? = null, - longPressDelayMs: Long = 500L, - microphoneIcon: Boolean = false, - strokeIconCode: String? = null, - graphicCode: String? = null, - graphicActionCode: String? = null, - // Rotates only the icon drawn inside StrokeActionView's canvas, not - // the whole button (which would also rotate — and for a non-square - // cell, distort — its background). - graphicRotation: Float = 0f, - // Only meaningful with graphicActionCode: StrokeActionView's icon - // color. Left null for the always-dark-red action keys (white in - // both themes, StrokeActionView's own default); the clipboard - // panel's direction/undo icons — which sit on a normal or rose key, - // not red — pass the theme-appropriate color explicitly. - graphicIconColor: Int? = null, - // Draws a thin horizontal divider between the two lines of a - // two-line label (e.g. the clipboard panel's "History"/"Dict" - // key, which does two unrelated things depending on tap vs. - // long-press) — a plain '\n' alone read as one cramped label. - midDivider: Boolean = false, - ): TextView { - val keyView = when { - microphoneIcon -> MicrophoneKeyView(this, isDarkTheme) - strokeIconCode != null -> StrokeKeyView(this, strokeIconCode, isDarkTheme) - graphicCode != null -> StrokeGlyphView(this, graphicCode, isDarkTheme) - graphicActionCode != null -> if (graphicIconColor != null) { - StrokeActionView(this, graphicActionCode, graphicRotation, graphicIconColor) - } else { - StrokeActionView(this, graphicActionCode, graphicRotation) - } - label == "←" || label == "↵" -> ActionSymbolView(this, label, isDarkTheme) - label == "⇧" -> ShiftKeyView(this, shiftState, isDarkTheme).also { englishShiftKey = it } - midDivider -> MidDividerTextView(this, tone(Color.rgb(100, 100, 100), Color.rgb(205, 205, 209))) - else -> TextView(this) - } - return keyView.apply { - text = if (strokeIconCode != null || graphicCode != null || graphicActionCode != null || label == "⇧") { - "" - } else if ('\n' in label) { - android.text.SpannableString(label).apply { - setSpan(android.text.style.RelativeSizeSpan(0.55f), 0, 1, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - } - } else label - textSize = if (microphoneIcon) 10f else if (strokeIconCode != null) 1f else if (label == "Return") 17f else 22f - gravity = if (microphoneIcon) android.view.Gravity.TOP or android.view.Gravity.CENTER_HORIZONTAL else android.view.Gravity.CENTER - if (microphoneIcon) setPadding(0, dp(2), 0, 0) - setTextColor(tone(Color.rgb(245, 245, 245), Color.rgb(30, 30, 34))) - background = roundedButton(tone(Color.rgb(52, 52, 54), Color.rgb(255, 255, 255)), dp(5)) - // Keep the existing palette and geometry, but give each key a subtle raised surface. - elevation = dp(5).toFloat() - translationZ = dp(1).toFloat() - contentDescription = label.ifBlank { ui("空格", "Space") } - // Retargetable like buildEnglishCharKey()'s tap preview: any - // sibling key built with its own swipeUpAction/swipePreview - // carries that pair here as its tag, so a swipe-up gesture that - // drags sideways onto a different key (e.g. across the stroke - // grid's digit shortcuts) can look up and commit THAT key's own - // digit instead of the one originally pressed. - tag = if (swipeUpAction != null && swipePreview != null) Pair(swipeUpAction, swipePreview) else null - var suppressNextClick = false - var downX = 0f - var downY = 0f - var swipePreviewShown = false - // A one-way latch, same as swipePreviewShown: once the finger - // has dragged sideways far enough from where it started, the - // gesture is treated as a deliberate retarget-drag for the - // rest of this touch sequence, not re-checked drag-by-drag. - // Before that latch trips, trackedView never changes even if - // the finger's raw position happens to land inside another - // key's real hit bounds — a plain swipe straight up (whose own - // vertical travel easily reaches a neighboring row) must not - // silently relabel itself just because it crossed into that - // row's territory with no real sideways intent. - var horizontalDragArmed = false - var trackedView: View = this - @Suppress("UNCHECKED_CAST") - fun swipeSpecOf(view: View): Pair<() -> Unit, String>? = view.tag as? Pair<() -> Unit, String> - setOnClickListener { - if (suppressNextClick) { - suppressNextClick = false - } else { - action() - } + private fun handleClipboardCommand(command: String) { + if (!clipboardActionCurrent(sessionEpoch)) return + when (command) { + "range" -> { + clipboardSelectionMode = !clipboardSelectionMode + clipboardSelectionAnchor = -1 + clipboardSelectionActive = -1 + renderClipboardPanel() } - val repeatHandler = if (repeatOnLongPress && repeatAction != null) { - Handler(Looper.getMainLooper()) - } else null - val repeatRunnable = if (repeatHandler != null && repeatAction != null) { - object : Runnable { - override fun run() { - repeatAction.invoke() - repeatHandler.postDelayed(this, keyRepeatIntervalMs()) - } - } - } else null - if (repeatHandler != null && repeatRunnable != null && repeatAction != null) { - setOnLongClickListener { - repeatAction.invoke() - repeatHandler.postDelayed(repeatRunnable, keyRepeatIntervalMs()) - true - } - } - val longPressHandler = if (longPressAction != null) Handler(Looper.getMainLooper()) else null - var longPressRunnable: Runnable? = null - - // Hit-tests every swipe-capable sibling in this key's own row - // group, climbing to the row's own parent so a drag can - // retarget across rows too — same approach as - // buildEnglishCharKey()'s findTrackTargetAt, just keyed off a - // Pair(swipeUpAction, swipePreview) tag instead of a char tag. - // - // Vertical slop is deliberately tiny here (unlike the English - // version's generous dp(24)): the grid's rows sit almost flush - // against each other (~1dp margin, each row only ~1/4 of the - // grid's own height), so a large slop makes adjacent rows' - // hit zones overlap deeply — a plain straight swipe UP (whose - // whole point is to travel well past the pressed key, still - // within the same key's column) would then immediately - // "retarget" to the row above just from that expected vertical - // travel, with no real leftward/rightward drag at all. A - // near-zero vertical slop means only a finger that has - // genuinely reached a different row's real bounds retargets; - // once the finger is past every row (still swiping straight - // up), no row matches and findSwipeTargetAt falls back to - // returning trackedView — i.e. the original key stays selected - // for a simple swipe, exactly matching a single-key swipe-up's - // intent. - fun findSwipeTargetAt(rawX: Float, rawY: Float): View { - val row = parent as? ViewGroup ?: return this - val group = row.parent as? ViewGroup - val candidateRows = if (group != null) { - (0 until group.childCount).mapNotNull { index -> - (group.getChildAt(index) as? ViewGroup)?.takeIf { candidate -> - (0 until candidate.childCount).any { candidate.getChildAt(it).tag is Pair<*, *> } - } - } - } else { - listOf(row) - } - for (candidateRow in candidateRows) { - for (index in 0 until candidateRow.childCount) { - val sibling = candidateRow.getChildAt(index) - if (sibling.tag !is Pair<*, *>) continue - val loc = IntArray(2) - sibling.getLocationOnScreen(loc) - if (rawX >= loc[0] - dp(6) && rawX < loc[0] + sibling.width + dp(6) && - rawY >= loc[1] - dp(2) && rawY < loc[1] + sibling.height + dp(2) - ) { - return sibling - } - } - } - return trackedView - } - - setOnTouchListener { view, event -> - when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { - // An out-of-bounds swipe may not dispatch a click to clear this flag. - suppressNextClick = false - downX = event.x - downY = event.y - horizontalDragArmed = false - trackedView = view - view.animate() - .scaleX(0.97f) - .scaleY(0.97f) - .translationZ(dp(3).toFloat()) - .alpha(0.90f) - .setDuration(65L) - .start() - performKeyHaptic() - if (longPressHandler != null && longPressAction != null) { - val runnable = Runnable { - longPressAction.invoke() - suppressNextClick = true - } - longPressRunnable = runnable - longPressHandler.postDelayed(runnable, longPressDelayMs) - } - } - MotionEvent.ACTION_MOVE -> { - if (swipeUpAction != null && swipePreview != null) { - if (!swipePreviewShown && downY - event.y >= dp(10)) { - // Armed only once the initial swipe-up - // actually clears the threshold, not on - // every key's plain DOWN (that would also - // swallow the panel-switch swipe that - // legitimately starts on top of a - // non-swiping key) — so dragging across the - // grid to retarget isn't stolen by - // SwipeModeContainer's own swipe intercept - // mid-gesture. - view.parent?.requestDisallowInterceptTouchEvent(true) - // Cancels the voice/mic key's own delayed - // longPressAction (switch to Voice mode) the - // moment a swipe-up is recognized — a no-op - // for every other key (longPressRunnable is - // only ever set when longPressAction != null). - longPressRunnable?.let { longPressHandler?.removeCallbacks(it) } - swipePreviewShown = true - } - if (swipePreviewShown) { - // Retargeting itself is gated behind a - // second, separate threshold: the finger - // must have moved at least dp(10) - // horizontally from where it first went - // down, not merely landed inside another - // key's hit bounds. A plain swipe straight - // up travels well past the pressed key's - // own row by design (that vertical distance - // is the whole gesture), which — with no - // sideways intent at all — would otherwise - // still land inside a neighboring row's real - // bounds and silently relabel the bubble - // (e.g. "0" swiped straight up briefly - // reading as "8", the key directly above - // it). Once this latches on, though, any - // further drag — down, sideways, or across - // rows — keeps retargeting and following - // the finger for the rest of the gesture; - // release always commits whichever key is - // currently tracked (see ACTION_UP). - if (!horizontalDragArmed && kotlin.math.abs(event.x - downX) >= dp(10)) { - horizontalDragArmed = true - } - if (horizontalDragArmed) { - val target = findSwipeTargetAt(event.rawX, event.rawY) - if (target !== trackedView) { - trackedView = target - // Same haptic as a normal key press, - // so retargeting onto a new key - // reads as landing on that key, not - // just a silent label swap. - performKeyHaptic() - } - } - val spec = swipeSpecOf(trackedView) - if (spec != null) { - // Pinned to the tracked key's own actual - // on-screen position, a fixed gap above - // it (see KeyPreviewOverlay.showSwipePreview()) — - // not to the finger's current height. - keyPreviewOverlay?.showSwipePreview(spec.second, trackedView) - } - } - } - } - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - if (event.actionMasked == MotionEvent.ACTION_UP && swipePreviewShown) { - swipeSpecOf(trackedView)?.first?.invoke() - suppressNextClick = true - } - longPressRunnable?.let { longPressHandler?.removeCallbacks(it) } - repeatHandler?.let { handler -> - repeatRunnable?.let { handler.removeCallbacks(it) } - } - if (swipePreviewShown) { - keyPreviewOverlay?.hide() - swipePreviewShown = false - } - view.animate() - .scaleX(1f) - .scaleY(1f) - .translationZ(0f) - .alpha(1f) - .setDuration(90L) - .start() - } - } - false - } - layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, weight).apply { - setMargins(dp(3), dp(3), dp(3), dp(3)) + "left" -> sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_LEFT) + "right" -> sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_RIGHT) + "up" -> sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_UP) + "down" -> sendClipboardCursorKey(android.view.KeyEvent.KEYCODE_DPAD_DOWN) + "all" -> currentInputConnection?.performContextMenuAction(android.R.id.selectAll) + "copy" -> currentInputConnection?.performContextMenuAction(android.R.id.copy) + "paste" -> currentInputConnection?.performContextMenuAction(android.R.id.paste) + "backspace" -> deleteBackward() + "history" -> { + if (!isBackendReady()) ensureBackendReady() + clipboardHistoryMode = true + renderClipboardPanel() } + "close_history" -> { clipboardHistoryMode = false; renderClipboardPanel() } + "clear_history" -> { OpenLessClipboardHistory.clearNonFavorites(this); renderClipboardPanel() } + "edit" -> openDictationEditDraft(requireSelection = true) } } @@ -2895,273 +1623,23 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt android.os.Handler(Looper.getMainLooper()).postDelayed({ performKeyHaptic() }, keyRepeatIntervalMs()) } - /** - * A single ABC/123/#+= character-emitting key with an iOS-style press - * preview: a bubble above the key showing the character that will - * actually be committed (respecting shift for letters), with an arrow - * pointing at the key (KeyPreviewBubbleView, plain Canvas drawing — no - * new dependency). Dragging onto a horizontally adjacent sibling in the - * same row re-targets the preview and the eventual commit to that key - * instead (a "sloppy key", same idea as most predictive keyboards). - * - * @param swipeSymbol Any key that has one — top-row digits (q..p -> - * 1..0), row2's ~@#!%&*() and row3's '/-_:;? — swiping up commits - * this symbol instead of the letter, same interaction as the stroke - * panel's own swipe-up keys (see keyboardKey()'s swipeUpAction/ - * swipePreview). Shown as a small standalone hint pinned to the very - * top of the key, NOT a second line of the letter's own text (that - * was the first version of this — a single TextView with "symbol\n - * letter" and block-centered gravity, which visibly shoved the - * letter down off-center by about half the hint line's height). - * Two independent views layered in a FrameLayout instead: the letter - * stays exactly where it always was, completely unaffected by - * whether a swipe-up hint exists at all. - * - * This is a dedicated builder, not a keyboardKey() variant, precisely - * so none of this touch handling can affect any other panel's keys. - */ - /** What a char key types right now: its base character, uppercased for a letter while Shift is on. */ - private fun englishCharFor(view: View): String { - val base = view.tag as? String ?: return "" - return if (shiftState != ShiftState.OFF && base.length == 1 && base[0].isLetter()) base.uppercase() else base - } - - /** - * Shows the current shiftState on the English panel: relabels the letter - * keys and redraws Shift in place. Typing already reads shiftState at the - * moment of the tap (englishCharFor), so only the labels were stale — - * rebuilding the whole keyboard for that ran on every sentence start and - * every capital. Falls back to a rebuild when that panel isn't on screen. - */ + /** Shift updates presentation in place; it never replaces the IME window. */ private fun applyShiftState() { - val keys = englishLetterKeys.filter { it.first.isAttachedToWindow } - val shiftKey = englishShiftKey?.takeIf { it.isAttachedToWindow } - if (keys.isEmpty() || shiftKey == null) { - refreshInputView() - return - } - keys.forEach { (key, letter) -> - val char = englishCharFor(key) - letter.text = char - key.contentDescription = char - } - shiftKey.state = shiftState - } - - private fun buildEnglishCharKey(baseChar: String, weight: Float, swipeSymbol: String? = null): View { - fun charFor(view: View): String = englishCharFor(view) - val letterView = TextView(this).apply { - textSize = 22f - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - gravity = android.view.Gravity.CENTER - setTextColor(tone(Color.rgb(245, 245, 245), Color.rgb(30, 30, 34))) - isClickable = false - // A small nudge off dead-center, down toward the digit/symbol - // hint's baseline — a plain translationY (not padding) so it's - // a pure render-time shift that doesn't touch this view's - // measured layout at all. - translationY = dp(LETTER_VERTICAL_NUDGE_DP).toFloat() - } - return FrameLayout(this).apply { - tag = baseChar - if (swipeSymbol != null) englishSwipeSymbols[this] = swipeSymbol - letterView.text = charFor(this) - if (baseChar.length == 1 && baseChar[0].isLetter()) englishLetterKeys += this to letterView - addView(letterView, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)) - if (swipeSymbol != null) { - addView( - TextView(this@OpenLessImeService).apply { - text = swipeSymbol - textSize = SWIPE_SYMBOL_HINT_TEXT_SIZE_SP - gravity = android.view.Gravity.TOP or android.view.Gravity.CENTER_HORIZONTAL - // Muted/secondary, not the same bright/near-black - // tone as the letter — a small top-corner hint - // should read as secondary at a glance, not - // compete with the actual letter for attention. - // (Tried matching the swipe-preview bubble's red - // here — read as less legible at this size than - // the plain gray, so reverted.) - setTextColor(tone(Color.rgb(150, 150, 150), Color.rgb(140, 140, 145))) - setPadding(0, dp(SWIPE_SYMBOL_HINT_TOP_PADDING_DP), 0, 0) - isClickable = false - }, - FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, android.view.Gravity.TOP), - ) - } - background = roundedButton(tone(Color.rgb(52, 52, 54), Color.rgb(255, 255, 255)), dp(5)) - elevation = dp(5).toFloat() - translationZ = dp(1).toFloat() - contentDescription = charFor(this) - var trackedView: View = this - var downY = 0f - var swipePreviewShown = false - - // Shown via the shared top-level KeyPreviewOverlay (see - // wrapWithKeyPreviewOverlay()) instead of a per-key PopupWindow — - // a single overlay reused by every key means dragging onto a - // different key just repositions the same bubble instead of - // tearing one popup down and standing up another. - fun showBubbleFor(target: View) { - keyPreviewOverlay?.showTapPreview(charFor(target), target) - } - - // Hit-tests every char-key row in this key's own row group (not - // just its immediate row siblings) by their actual on-screen - // bounds — a little slop added on both axes, since a real - // finger drifts while sliding. Climbing to the row's own parent - // and collecting every child row that has at least one - // String-tagged (char) key lets a vertical drag retarget across - // rows (e.g. row2's "a" up to row1's "q") the same way a - // horizontal drag already retargets within one row — the - // candidate bar, header, and bottom row (space/return/mode - // toggle) never have any String-tagged children, so they're - // simply never included. Functional keys within an included row - // (shift/backspace, tag == null) are still never matched. - fun findTrackTargetAt(rawX: Float, rawY: Float): View { - val row = parent as? ViewGroup ?: return this - val group = row.parent as? ViewGroup - val candidateRows = if (group != null) { - (0 until group.childCount).mapNotNull { index -> - (group.getChildAt(index) as? ViewGroup)?.takeIf { candidate -> - (0 until candidate.childCount).any { candidate.getChildAt(it).tag is String } - } - } - } else { - listOf(row) - } - for (candidateRow in candidateRows) { - for (index in 0 until candidateRow.childCount) { - val sibling = candidateRow.getChildAt(index) - if (sibling.tag !is String) continue - val loc = IntArray(2) - sibling.getLocationOnScreen(loc) - if (rawX >= loc[0] - dp(6) && rawX < loc[0] + sibling.width + dp(6) && - rawY >= loc[1] - dp(24) && rawY < loc[1] + sibling.height + dp(24) - ) { - return sibling - } - } - } - return trackedView - } - - // Same idea as findTrackTargetAt above, but only among this - // row's own swipe-symbol-bearing keys (englishSwipeSymbols) — - // once a swipe is armed, sliding sideways still retargets which - // symbol release will commit, and showSwipePreview() re-anchors - // to that key so the bubble visibly follows the finger instead - // of freezing above the key the gesture started on. A generous - // vertical band since an armed drag has already moved well - // above the row. - fun findSwipeTargetAt(rawX: Float, rawY: Float): View { - val row = parent as? ViewGroup ?: return trackedView - for (index in 0 until row.childCount) { - val sibling = row.getChildAt(index) - if (sibling !in englishSwipeSymbols) continue - val loc = IntArray(2) - sibling.getLocationOnScreen(loc) - if (rawX >= loc[0] - dp(6) && rawX < loc[0] + sibling.width + dp(6) && - rawY >= loc[1] - dp(60) && rawY < loc[1] + sibling.height + dp(24) - ) { - return sibling - } - } - return trackedView - } - - setOnTouchListener { view, event -> - when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { - // Without this, a same-row drag to an adjacent key - // (a clearly horizontal drag, same shape as a - // panel-switch swipe) gets stolen mid-gesture by the - // enclosing SwipeModeContainer's own horizontal-swipe - // intercept once it crosses touchSlop — the key would - // stop receiving MOVE/UP entirely, so the bubble - // never follows the finger and nothing ever commits - // on release. Claimed unconditionally on DOWN, not - // only once a drag is detected: any movement that - // starts on a key belongs to that key's own - // press/retarget/commit handling, never to a - // panel-switch gesture. - view.parent?.requestDisallowInterceptTouchEvent(true) - trackedView = view - downY = event.y - swipePreviewShown = false - view.animate().scaleX(0.97f).scaleY(0.97f).translationZ(dp(3).toFloat()).alpha(0.90f).setDuration(65L).start() - performKeyHaptic() - showBubbleFor(view) - } - MotionEvent.ACTION_MOVE -> { - // Swipe-up-for-symbol (swipeSymbol != null; the - // digit row, and now row2/row3's punctuation) — - // same dp(10) arm threshold as keyboardKey()'s own - // swipe handling. Once armed, sliding sideways - // still retargets across the row's other - // symbol-bearing keys via findSwipeTargetAt (the - // bubble follows the finger to whichever symbol is - // now under it), separate from findTrackTargetAt's - // own retargeting used for the un-armed tap case. - // - // Live, not a one-way latch: armed is re-evaluated - // against the finger's *current* height every move, - // not just the first time it crosses the threshold - // — dragging back down below it un-arms and falls - // through to the normal tap-preview/retarget path - // below, giving a way to back out of the symbol - // mid-gesture without lifting the finger. - if (swipeSymbol != null) { - val armed = downY - event.y >= dp(10) - if (armed != swipePreviewShown) { - view.parent?.requestDisallowInterceptTouchEvent(true) - swipePreviewShown = armed - } - if (swipePreviewShown) { - val target = findSwipeTargetAt(event.rawX, event.rawY) - if (target !== trackedView) trackedView = target - val symbol = englishSwipeSymbols[trackedView] ?: swipeSymbol - keyPreviewOverlay?.showSwipePreview(symbol, trackedView) - return@setOnTouchListener true - } - } - val target = findTrackTargetAt(event.rawX, event.rawY) - if (target !== trackedView) trackedView = target - showBubbleFor(trackedView) - } - MotionEvent.ACTION_UP -> { - keyPreviewOverlay?.hide() - view.animate().scaleX(1f).scaleY(1f).translationZ(0f).alpha(1f).setDuration(90L).start() - if (swipeSymbol != null && swipePreviewShown) { - commitEnglishChar(englishSwipeSymbols[trackedView] ?: swipeSymbol) - } else { - commitEnglishChar(charFor(trackedView)) - } - } - MotionEvent.ACTION_CANCEL -> { - keyPreviewOverlay?.hide() - view.animate().scaleX(1f).scaleY(1f).translationZ(0f).alpha(1f).setDuration(90L).start() - } - } - true - } - layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, weight).apply { - setMargins(dp(3), dp(3), dp(3), dp(3)) - } - } + if (inputMode == InputMode.ENGLISH) renderTypingKeyboard() } private fun commitEnglishChar(char: String) { if (char.isEmpty()) return if (latinInputMode == LatinInputMode.PINYIN && !ImeLearningPolicy.isPassword(currentInputEditorInfo?.inputType ?: 0)) { if (char.length == 1 && char[0].isLetter()) { - // Never calls commitText() — a letter only feeds the - // encoding buffer in Pinyin mode; see - // RimePinyinController's own doc comment. + // Feed letter to Rime composition; preserve uppercase when Shift/CapsLock is on + // so mixed English tokens (e.g. AI, DNA) work natively in rime_ice. rimePinyinController.appendLetter(char[0]) { renderPinyinCandidates(it) } consumeShiftOnce() return } - rimePinyinController.insertLiteral(char) { renderPinyinCandidates(it) } + val mapped = smartPinyinPunctuation(char) + rimePinyinController.insertLiteral(mapped) { renderPinyinCandidates(it) } return } val connection = currentInputConnection ?: return @@ -3212,74 +1690,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun englishSuggestionsEnabled(): Boolean = getSharedPreferences("openless_ime_ui", MODE_PRIVATE).getBoolean("english_suggestions_enabled", true) - /** - * Same presentation as the stroke panel's own candidate row: a - * HorizontalScrollView (so as many words as actually exist can be - * scrolled through, not a fixed 3-slot row) with the same - * touch-intercept override and the same overflow-triggered "▼ show - * more" button opening showCandidateOverlay() — the exact mechanism - * and candidateItemView() styling the stroke panel itself uses, reused - * as-is rather than a parallel implementation. - */ - private fun buildEnglishCandidateBar(): View { - // Outer vertical wrapper — divider, the actual bar, divider — so - // hiding it (see updateEnglishCandidates()) when suggestions are - // off takes both border lines with it instead of leaving two empty - // lines with nothing between them. - val wrapper = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } - englishCandidateBarContainer = wrapper - wrapper.addView( - buildDivider(), - LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1)).apply { - marginStart = dp(1) - marginEnd = dp(1) - }, - ) - val container = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER_VERTICAL } - wrapper.addView(container, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(36))) - wrapper.addView( - buildDivider(), - LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1)).apply { - marginStart = dp(1) - marginEnd = dp(1) - bottomMargin = dp(2) - }, - ) - val scroll = object : android.widget.HorizontalScrollView(this) { - override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { - if (ev.actionMasked == MotionEvent.ACTION_DOWN) { - parent?.requestDisallowInterceptTouchEvent(true) - } - return super.onInterceptTouchEvent(ev) - } - }.apply { - isHorizontalScrollBarEnabled = false - isFillViewport = false - overScrollMode = View.OVER_SCROLL_NEVER - } - val row = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER_VERTICAL } - englishCandidateRow = row - scroll.addView(row, ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)) - container.addView(scroll, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f)) - val expandButton = StrokeActionView( - this, - "triangle-down", - iconColor = tone(Color.rgb(180, 180, 180), Color.rgb(130, 130, 135)), - ).apply { - contentDescription = ui("展开更多候选", "Show more candidates") - visibility = View.GONE - setOnClickListener { showCandidateOverlay(this) } - } - englishExpandCandidatesButton = expandButton - container.addView(expandButton, LinearLayout.LayoutParams(dp(28), ViewGroup.LayoutParams.MATCH_PARENT)) - // Same idea as the stroke candidate row's own listener: only shown - // once the candidates actually overflow the visible scroll width. - scroll.viewTreeObserver.addOnGlobalLayoutListener { - expandButton.visibility = if (row.width > scroll.width) View.VISIBLE else View.GONE - } - return wrapper - } - /** * Re-queries EnglishCandidateProvider for the current englishComposingWord * prefix (or clears the bar if suggestions are off / nothing is being @@ -3289,13 +1699,11 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt */ private fun updateEnglishCandidates() { val epoch = ++englishCandidateQueryEpoch - if (englishCandidateRow == null) return + if (typingPanel == null) return if (!personalizedLearningAllowed() || !englishSuggestionsEnabled()) { renderEnglishCandidates(emptyList()) - englishCandidateBarContainer?.visibility = View.GONE return } - englishCandidateBarContainer?.visibility = View.VISIBLE val prefix = englishComposingWord.toString() if (prefix.isEmpty()) { renderEnglishCandidates(emptyList()) @@ -3368,13 +1776,51 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt * a non-empty encoding, per phase-0 audit section 5, adding no new row * or container so the fixed 300dp panel height is never touched. */ + private fun smartPinyinPunctuation(char: String): String { + if (char.length != 1) return char + val ch = char[0] + val afterDigit = rimePinyinController.isEmpty() && + currentInputConnection?.getTextBeforeCursor(1, 0)?.lastOrNull()?.isDigit() == true + return when (ch) { + ',' -> "," + '.' -> if (afterDigit) "." else "。" + '。' -> if (afterDigit) "." else "。" + ':' -> if (afterDigit) ":" else ":" + '?' -> "?" + '!' -> "!" + ';' -> ";" + '(' -> "(" + ')' -> ")" + else -> char + } + } + private fun renderPinyinCandidates(candidates: List) { + val preedit = rimePinyinController.currentPreedit().takeIf { it.isNotEmpty() } + syncPinyinComposingText(preedit) + val allowForget = personalizedLearningAllowed() && preedit != null populateLatinCandidateRow( - candidates.map { char -> LatinCandidate(char, longPress = null) { selectPinyinCandidate(char) } }, - leadingLabel = rimePinyinController.currentEncoding().takeIf { it.isNotEmpty() }, + candidates.map { char -> + LatinCandidate( + char, + longPress = if (allowForget) ({ forgetPinyinCandidate(char) }) else null, + ) { selectPinyinCandidate(char) } + }, + leadingLabel = preedit, + statusHint = rimePinyinController.statusHint(), ) } + private fun forgetPinyinCandidate(word: String) { + if (!personalizedLearningAllowed()) return + rimePinyinController.deleteCandidate(word, { renderPinyinCandidates(it) }) { deleted -> + if (deleted) { + performKeyHaptic() + OpenLessNativeNotice.makeText(this, ui("已删除「$word」", "Removed \"$word\""), Toast.LENGTH_SHORT).show() + } + } + } + /** Candidate tap is the ONLY way a pinyin candidate reaches the field — see toggleLatinInputMode()'s doc comment on why Space deliberately never does this. */ private fun selectPinyinCandidate(char: String) { if (ImeLearningPolicy.isPassword(currentInputEditorInfo?.inputType ?: 0)) return @@ -3445,8 +1891,11 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt val selected = connection.getSelectedText(0) if (!selected.isNullOrEmpty()) { connection.commitText("", 1) - } else { - connection.deleteSurroundingText(1, 0) + } else if (!connection.deleteSurroundingTextInCodePoints(1, 0)) { + // Editors without the codepoint API can interpret DEL themselves; + // deleting one UTF-16 unit could leave half of an emoji behind. + connection.sendKeyEvent(android.view.KeyEvent(android.view.KeyEvent.ACTION_DOWN, android.view.KeyEvent.KEYCODE_DEL)) + connection.sendKeyEvent(android.view.KeyEvent(android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_DEL)) } } @@ -3461,11 +1910,17 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } private fun sendEditorEnterKey() { - currentInputConnection?.sendKeyEvent(android.view.KeyEvent( + val connection = currentInputConnection ?: return + val options = currentInputEditorInfo?.imeOptions ?: 0 + val action = options and EditorInfo.IME_MASK_ACTION + if (draftEdit == null && options and EditorInfo.IME_FLAG_NO_ENTER_ACTION == 0 && + action != EditorInfo.IME_ACTION_NONE && action != EditorInfo.IME_ACTION_UNSPECIFIED && + connection.performEditorAction(action)) return + connection.sendKeyEvent(android.view.KeyEvent( android.view.KeyEvent.ACTION_DOWN, android.view.KeyEvent.KEYCODE_ENTER, )) - currentInputConnection?.sendKeyEvent(android.view.KeyEvent( + connection.sendKeyEvent(android.view.KeyEvent( android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_ENTER, )) @@ -3475,10 +1930,13 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt cancelImeSession() closeDraft() super.onStartInput(attribute, restarting) + keyboardHeader?.cancelInteractions() + typingPanel?.closeTransientUi() + clipboardPanel?.cancelInteractions() + refreshLanguage() restoreInputMode() restoreScriptPreference() restoreLatinInputMode() - refreshLanguage() strokeController.resetForNewInputSession() englishLayer = EnglishLayer.LETTERS // An automatic capital belonged to the old field's sentence start; @@ -3488,12 +1946,19 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt clearEnglishAutoText() englishComposingWord.clear() englishCandidateQueryEpoch++ + clearPinyinComposingInEditor() rimePinyinController.clear() rimePinyinController.resetAssociationContext() rimePinyinController.setLearningAllowed(personalizedLearningAllowed()) + rimePinyinController.bindAfterCommit { + if (inputMode == InputMode.ENGLISH && latinInputMode == LatinInputMode.PINYIN && rimePinyinController.isEmpty()) { + refreshPinyinAssociations() + } + } rimePinyinController.bindCommit { text -> if (ImeLearningPolicy.isPassword(currentInputEditorInfo?.inputType ?: 0)) false else if (currentInputConnection?.commitText(text, 1) == true) { + pinyinComposingActive = false // Typing an offered association out by hand counts as picking it. if (personalizedLearningAllowed() && OpenLessAndroidPreferences.strokeUsageEnabled(this)) { strokeController.phraseRepository.recordTypedContinuation( @@ -3507,9 +1972,12 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt true } else false } - if (ImeLearningPolicy.isPassword(attribute?.inputType ?: 0)) { + if (ImeLearningPolicy.isPassword(attribute?.inputType ?: 0) || + ImeEditorFieldPolicy.prefersNumeric(attribute?.inputType ?: 0)) { + // Field adaptation is temporary; do not overwrite the user's last page. inputMode = InputMode.ENGLISH latinInputMode = LatinInputMode.ENGLISH + if (ImeEditorFieldPolicy.prefersNumeric(attribute?.inputType ?: 0)) englishLayer = EnglishLayer.NUMBERS } renderEnglishCandidates(emptyList()) startRuntimeService() @@ -3530,6 +1998,9 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt override fun onStartInputView(info: EditorInfo?, restarting: Boolean) { super.onStartInputView(info, restarting) + refreshInteractionPolicy() + microphoneGranted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + renderVoiceUi() // InputMethodService caches onCreateInputView()'s result across hide/ // show. Keyboard settings write height/raise prefs while that cached // view is still the old footprint — rebuild when they diverge so the @@ -3540,20 +2011,38 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt val rebuild = appliedKeyboardFootprintKey != key updateAutoShift(refresh = false) if (rebuild) { - appliedKeyboardFootprintKey = key + // Only onCreateInputView may acknowledge a newly built footprint. + // Updating this before refresh would incorrectly select the fast path. refreshInputView() } else if (inputMode == InputMode.ENGLISH && englishLayer == EnglishLayer.LETTERS) { applyShiftState() + refreshLatinCandidateBar() + renderClipboardQuickChip() + } else if (inputMode == InputMode.ENGLISH) { + // A cached alphabet page may now serve a numeric field with the + // same privacy footprint (for example password -> phone number). + renderTypingKeyboard() + refreshLatinCandidateBar() + renderClipboardQuickChip() + } else if (inputMode == InputMode.CLIPBOARD) { + renderClipboardPanel() + } else if (inputMode == InputMode.STROKE) { + strokeController.refreshPanel() } } private fun keyboardFootprintKey(): String = - "${keyboardPanelHeightDp()}:${raiseHeightDp(this)}:$inputMode:$latinInputMode:${personalizedLearningAllowed()}" + "${keyboardPanelHeightDp()}:${raiseHeightDp(this)}:$inputMode:$latinInputMode:${personalizedLearningAllowed()}:$isDarkTheme:$englishUi:draft=$draftToken:${draftEdit != null}" override fun onFinishInputView(finishingInput: Boolean) { + draftBar?.cancelInteractions() + keyboardHeader?.cancelInteractions() + typingPanel?.closeTransientUi() clearEnglishAutoText() if (draftEdit != null && (recording || processing)) cancelDictation() closeDraft() + clipboardPanel?.cancelInteractions() + strokeController.cancelInteractions() super.onFinishInputView(finishingInput) } @@ -3574,12 +2063,16 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } override fun onFinishInput() { + keyboardHeader?.cancelInteractions() + typingPanel?.closeTransientUi() + clipboardPanel?.cancelInteractions() clearEnglishAutoText() if (draftEdit != null && (recording || processing)) cancelDictation() closeDraft() cancelImeSession() englishCandidateQueryEpoch++ englishComposingWord.clear() + clearPinyinComposingInEditor() rimePinyinController.clear() rimePinyinController.resetAssociationContext() strokeController.resetForNewInputSession() @@ -3656,14 +2149,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt internal fun toggleDictation(initialCloud: Boolean = false) { if (processing) return - if (isSensitiveField(currentInputEditorInfo)) { - updateStatus("敏感字段,禁止听写") - return - } - if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { - updateStatus("请先授予麦克风权限") - return - } if (recording && quickNoteArmed) { quickNoteDictation() return @@ -3674,6 +2159,16 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt setState("thinking", "正在思考") stopImeSession() } else { + if (hasForeignVoiceActivity()) { renderVoiceUi(); return } + if (isSensitiveField(currentInputEditorInfo)) { + updateStatus("敏感字段,禁止听写") + return + } + microphoneGranted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + if (!microphoneGranted) { + updateStatus("请先授予麦克风权限") + return + } if (!isBackendReady()) { if (!awaitingBackendReadyRecheck) { backendRecheckStartedAtMs = android.os.SystemClock.elapsedRealtime() @@ -3707,6 +2202,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // callback ever arrives, so both were structurally unreachable // on every normal tap-to-start (silently never firing). recordingStartedAtMs = android.os.SystemClock.elapsedRealtime() + latestVoiceLevel = 0f maxObservedLevelThisSession = 0f voiceLinkWarning?.visibility = View.GONE performKeyHaptic() @@ -3720,8 +2216,22 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt imeSessionId = null cloudNoteArmed = initialCloud imeRequestId = nextImeRequest.incrementAndGet() + activeImeOwner = ImeRequestOwner(sessionEpoch, imeRequestId) + activeImeOwner?.let(imeFrameGate::begin) + typingVoiceOwner = null + imeStopRequested = false + imeCaptureEnded = false + externalRecording = false + externalProcessing = false + externalVoiceSessionId = null pendingImeStop = false - if (!sendImeCommand("start", captureCursorContext())) { recording = false; processing = false } + if (!sendImeCommand("start", captureCursorContext())) { + recording = false + processing = false + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + updateStatus(currentMessage) + } else updateStatus(currentMessage) } } @@ -3733,6 +2243,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt cloudNoteArmed = false cloudNoteSubmitting = false invalidateSession("已取消") + setState("cancelled", ui("已取消", "Cancelled")) cancelImeSession() } @@ -3796,29 +2307,26 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt * what the user described as the link being "disconnected". */ private fun updateBackendLinkIndicator() { - val armedAccent = armedAccentColor() + val uiState = voiceUiState() + val displayCapture = uiState.phase == ImeVoicePhase.RECORDING || uiState.phase == ImeVoicePhase.STARTING + val displayProcessing = uiState.phase == ImeVoicePhase.PROCESSING || uiState.phase == ImeVoicePhase.SUBMITTING + val armedAccent = if (hasForeignVoiceActivity()) null else armedAccentColor() val color = when { // Matches VoiceButton's own waveform/dots color for each armed // gesture exactly (armedModeColor()) — the breathing dot and // the mic animation should never disagree about which mode a // dictation is currently armed for, recording or thinking. - (recording || processing || cloudNoteSubmitting) && armedAccent != null -> armedAccent - recording -> LINK_COLOR_RECORDING - processing -> LINK_COLOR_PROCESSING + (displayCapture || displayProcessing) && armedAccent != null -> armedAccent + displayCapture -> LINK_COLOR_RECORDING + displayProcessing -> LINK_COLOR_PROCESSING !backendLinkHealthy -> LINK_COLOR_ISSUE asrRoute == "localRaw" || (asrRoute == "local" && !networkAvailable) -> LINK_COLOR_READY_LOCAL_RAW asrRoute == "local" -> LINK_COLOR_READY_LOCAL asrRoute == "unavailable" -> LINK_COLOR_ISSUE else -> LINK_COLOR_READY } - (backendLinkIndicator?.background as? GradientDrawable)?.apply { - setColor(color) - // The light-white dot would vanish on the light keyboard without an edge. - if (color == LINK_COLOR_READY_LOCAL_RAW) setStroke(dp(1), Color.rgb(148, 163, 184)) else setStroke(0, Color.TRANSPARENT) - } val ready = color == LINK_COLOR_READY || color == LINK_COLOR_READY_LOCAL || color == LINK_COLOR_READY_LOCAL_RAW - backendLinkPulseAnimator?.duration = - if (ready) BACKEND_LINK_READY_PULSE_DURATION_MS else BACKEND_LINK_PULSE_DURATION_MS + keyboardHeader?.renderLink(color, ready) } /** @@ -3896,17 +2404,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt }, 1000L) } - private fun runNativeAction(action: String, call: () -> Unit) { - try { - call() - } catch (error: Throwable) { - recording = false - processing = false - updateStatus("${action}失败,请打开 OpenLess 后重试") - android.util.Log.w("OpenLessImeService", "$action native bridge unavailable", error) - } - } - /** * `message ?: fallback` only substitutes for a literal null — a native * capsule-state event carrying a blank-but-non-null message (empty @@ -3921,70 +2418,111 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun String?.orDefault(fallback: String): String = this?.takeIf { it.isNotBlank() } ?: fallback override fun onCapsuleStateChanged(state: String, message: String?, level: Float) { - voiceButton?.audioLevel = level.coerceIn(0f, 1f) - when (state) { - "recording" -> { - if (!recording) { - // Fresh recording attempt — give it a clean silence watch. - recordingStartedAtMs = android.os.SystemClock.elapsedRealtime() - maxObservedLevelThisSession = 0f - voiceLinkWarning?.visibility = View.GONE - performKeyHaptic() + onCapsuleStateChangedWithSession(state, message, level, null) + } + + override fun onCapsuleStateChangedWithSession(state: String, message: String?, level: Float, sessionId: String?) { + val frame = ImeCapsuleFrame(sessionId?.takeUnless { it.isBlank() }, state, message, level) + when (imeFrameGate.accept(frame)) { + ImeFrameDisposition.OWNED -> { + if (!ownsImeRequest()) return + externalRecording = false + externalProcessing = false + externalVoiceSessionId = null + applyOwnedCapsuleFrame(frame) + } + ImeFrameDisposition.EXTERNAL -> { + when (state) { + "recording" -> { externalRecording = true; externalProcessing = false; externalVoiceSessionId = frame.sessionId } + "transcribing", "polishing" -> { externalRecording = false; externalProcessing = true; externalVoiceSessionId = frame.sessionId } + "idle", "done", "cancelled", "error" -> { + if (frame.sessionId == null || externalVoiceSessionId == null || frame.sessionId == externalVoiceSessionId) { + externalRecording = false + externalProcessing = false + externalVoiceSessionId = null + } + // Only real terminal frames retire a known foreign id. + // Idle is a presentation cue and may be temporary. + if (state != "idle") frame.sessionId?.let(imeFrameGate::retire) + } } + renderVoiceUi() + } + ImeFrameDisposition.BUFFERED, ImeFrameDisposition.FOREIGN, + ImeFrameDisposition.UNIDENTIFIED, ImeFrameDisposition.STALE -> Unit + } + } + + private fun applyOwnedCapsuleFrame(frame: ImeCapsuleFrame) { + val state = frame.state + val message = frame.message + val level = frame.level + when (ImeVoiceFramePolicy.resolve(true, imeCaptureEnded, state, imeStopRequested)) { + ImeVoiceFrameAction.EXTERNAL -> return + ImeVoiceFrameAction.IGNORE -> return + ImeVoiceFrameAction.RECORDING -> { + latestVoiceLevel = level recording = true processing = false - maxObservedLevelThisSession = maxOf(maxObservedLevelThisSession, level) + maxObservedLevelThisSession = maxOf(maxObservedLevelThisSession, if (level.isFinite()) level else 0f) val elapsedMs = android.os.SystemClock.elapsedRealtime() - recordingStartedAtMs - if (maxObservedLevelThisSession >= SILENCE_LEVEL_THRESHOLD) { - voiceLinkWarning?.visibility = View.GONE - } else if (elapsedMs > SILENCE_CHECK_DELAY_MS) { - // This only runs once an actual recording session is - // underway, so it can't overlap with the "backend not - // ready" case in toggleDictation() (that one returns - // before a session ever starts) — but set this widget's - // own text explicitly anyway rather than trusting - // whatever the other case last left it as. + if (maxObservedLevelThisSession >= SILENCE_LEVEL_THRESHOLD) voiceLinkWarning?.visibility = View.GONE + else if (elapsedMs > SILENCE_CHECK_DELAY_MS) { voiceLinkWarning?.text = ui("检测到麦克风无声音,点击重启应用", "No mic audio detected — tap to restart the app") voiceLinkWarning?.visibility = View.VISIBLE } setState("speaking", "再次点击结束 · 下划取消") } - "transcribing" -> { - // Guarded by the same "was still recording" check as - // "polishing" below, since either one can be the first to - // fire after recording actually stops — only whichever - // gets there first should vibrate. + ImeVoiceFrameAction.PROCESSING -> { if (recording) performKeyHaptic() + imeCaptureEnded = true recording = false processing = true setState("thinking", "正在思考") } - "polishing" -> { - if (recording) performKeyHaptic() + ImeVoiceFrameAction.WAIT_RESULT -> { + imeCaptureEnded = true recording = false processing = true - setState("thinking", "正在思考") + setState("thinking", ui("正在完成听写", "Finishing dictation")) } - "done" -> { + ImeVoiceFrameAction.EXTERNALLY_COMPLETED -> { + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + typingVoiceOwner = null recording = false processing = false - setState("done", message.orDefault("已完成")) - performKeyHaptic() - } - "cancelled" -> { + imeCaptureEnded = true + // A global stop does not emit this client's completed/text + // callback. Never fabricate receipt or write an unknown result. + setState("error", ui("听写已由其他入口结束,本输入法未收到文字;请检查历史或重试", "Dictation ended elsewhere; this keyboard received no text. Check history or retry")) + } + ImeVoiceFrameAction.CANCELLED -> { + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + typingVoiceOwner = null recording = false processing = false - setState("idle", message.orDefault("已取消")) + setState("cancelled", message.orDefault("已取消")) } - "error" -> { + ImeVoiceFrameAction.ERROR -> { recording = false - processing = false - setState("error", message.orDefault("识别失败")) - } - "idle" -> if (!recording) { - setState("idle", message.orDefault("点击开始说话")) + imeCaptureEnded = true + if (imeStopRequested) { + // A terminal cue is not the scoped result. Keep the owner + // until its completed/error callback prevents early restart. + processing = true + setState("thinking", message.orDefault("正在确认听写结果")) + } else { + imeFrameGate.finish(activeImeOwner) + activeImeOwner = null + typingVoiceOwner = null + processing = false + setState("error", message.orDefault("识别失败")) + } } } + renderVoiceUi(pushAudio = true) } private fun invalidateSession(message: String) { @@ -4003,21 +2541,47 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun updateStatus(message: String) { currentMessage = message - status?.text = displayStatus(message) + renderVoiceUi() + } + + private fun renderVoiceUi(pushAudio: Boolean = false) { + val snapshot = voiceUiState() + val foreign = hasForeignVoiceActivity() + val capture = !foreign && snapshot.phase == ImeVoicePhase.RECORDING + val busy = foreign || snapshot.phase in listOf(ImeVoicePhase.STARTING, ImeVoicePhase.PROCESSING, ImeVoicePhase.SUBMITTING) + val caption = when { + foreign -> ui("听写服务正忙,请在发起听写的入口结束", "Dictation is busy; finish it in the entry that started it") + snapshot.phase == ImeVoicePhase.STARTING -> ui("正在准备录音", "Preparing recording") + !snapshot.canStart && !snapshot.editorLocked && isSensitiveField(currentInputEditorInfo) -> ui("敏感字段,已禁用听写", "Dictation disabled in this field") + !snapshot.canStart && !snapshot.editorLocked && !microphoneGranted -> ui("需要麦克风权限,请打开设置", "Microphone permission required; open settings") + else -> snapshot.message + } + status?.text = caption status?.setTextColor(recordingAccentColor()) voiceRawHint?.text = rawModeHintText() voiceRawHint?.setTextColor(rawModeHintColor()) - voiceRawHint?.visibility = if (rawModeHintVisible()) View.VISIBLE else View.GONE - voiceButton?.isRecording = recording - // The Cloud notes submit shows the same thinking dots as the step - // before it, even though `processing` itself is already false. - voiceButton?.isProcessing = processing || cloudNoteSubmitting - // Re-pushed here, not only from each field's own setter: a panel - // rebuild mid-dictation (a draft opening or closing, a mode switch) - // hands us a fresh VoiceButton that never saw those setters fire. - voiceButton?.rawModeActive = rawModeArmed - voiceButton?.quickNoteActive = quickNoteArmed - voiceButton?.cloudNoteActive = cloudNoteArmed || cloudNoteSubmitting + voiceRawHint?.visibility = if (!foreign && rawModeHintVisible()) View.VISIBLE else View.GONE + voiceButton?.isEnabled = snapshot.canStart || (ownsImeRequest() && recording) + voiceButton?.isRecording = capture + voiceButton?.isProcessing = busy + voiceButton?.rawModeActive = snapshot.mode == ImeVoiceMode.RAW + voiceButton?.quickNoteActive = snapshot.mode == ImeVoiceMode.QUICK_NOTE + voiceButton?.cloudNoteActive = snapshot.mode == ImeVoiceMode.CLOUD_NOTE + if (pushAudio) voiceButton?.audioLevel = snapshot.audioLevel + voicePanel?.renderAvailability(capture, busy, snapshot.canCancel, snapshot.canStart || (ownsImeRequest() && recording)) + clipboardPanel?.setBlocked(snapshot.editorLocked) + strokeController.setInteractionBlocked(snapshot.editorLocked) + voiceButton?.contentDescription = when { + foreign -> ui("其他入口正在听写", "Another entry is dictating") + snapshot.phase == ImeVoicePhase.STARTING -> ui("正在准备录音,点击结束", "Preparing recording; tap to finish") + ownsImeRequest() && recording -> ui("结束听写", "Finish dictation") + snapshot.canStart -> ui("开始听写", "Start dictation") + else -> caption + } + typingPanel?.renderVoice( + caption, capture, busy, if (pushAudio) snapshot.audioLevel else null, + snapshot.canCancel && typingVoiceOwner?.matches(sessionEpoch, imeRequestId) == true, + ) updateDictationResultControls() updateBackendLinkIndicator() } @@ -4186,9 +2750,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private var draftMessageIsError = false // Bumped whenever a draft opens or closes; a submit result only applies to the draft that sent it. private var draftToken = 0L - private var draftStatusView: TextView? = null - private var draftCancelButton: TextView? = null - private var draftConfirmButton: TextView? = null /** * Every key, candidate, backspace and dictation commit in this service @@ -4211,6 +2772,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt clearEnglishAutoText() englishComposingWord.clear() englishCandidateQueryEpoch++ + clearPinyinComposingInEditor() rimePinyinController.clear() rimePinyinController.resetAssociationContext() strokeController.resetForModeSwitch() @@ -4439,9 +3001,8 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt draftSubmitting = false draftMessage = null draftMessageIsError = false - draftStatusView = null - draftCancelButton = null - draftConfirmButton = null + draftBar?.cancelInteractions() + draftBar = null resetEditingStateForTargetChange() refreshInputView() } @@ -4453,105 +3014,31 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } private fun updateDraftControls() { - draftStatusView?.apply { - text = draftMessage ?: when (draftPurpose) { - DraftPurpose.CLOUD_NOTE -> ui("云笔记草稿", "Cloud note draft") - DraftPurpose.DICTATION_EDIT -> ui("编辑后替换原文", "Edit, then replace") - } - setTextColor( - if (draftMessage != null && draftMessageIsError) LINK_COLOR_CLOUD_NOTE - else tone(Color.rgb(190, 190, 190), Color.rgb(110, 110, 115)), - ) - } - val enabled = !draftSubmitting - listOf(draftCancelButton, draftConfirmButton).forEach { button -> - button?.isEnabled = enabled - button?.alpha = if (enabled) 1f else 0.45f + val message = draftMessage ?: when (draftPurpose) { + DraftPurpose.CLOUD_NOTE -> ui("云笔记草稿", "Cloud note draft") + DraftPurpose.DICTATION_EDIT -> ui("编辑后替换原文", "Edit, then replace") } + draftBar?.render( + message, draftMessage != null && draftMessageIsError, draftSubmitting, + if (draftPurpose == DraftPurpose.CLOUD_NOTE) keyboardPalette().error else keyboardPalette().accent, + ) } - /** - * Stacks the draft bar (draft box, then Cancel / status / Confirm) on top - * of the regular input view while a draft is open. The keyboard panel - * below keeps its own height, header and mode toggle, so every input - * mode stays fully usable for editing the draft; the IME just grows - * taller by the height of the bar. - */ - private fun wrapWithDraftBar(keyboard: View): View { - val edit = draftEdit ?: return keyboard - (edit.parent as? ViewGroup)?.removeView(edit) - val panelColor = tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246)) - edit.setTextColor(tone(Color.WHITE, Color.rgb(28, 28, 30))) - edit.background = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - cornerRadius = dp(10).toFloat() - setColor(tone(Color.rgb(34, 34, 34), Color.WHITE)) - setStroke(dp(1), tone(Color.rgb(68, 68, 68), Color.rgb(215, 215, 218))) - } - edit.setPadding(dp(12), dp(8), dp(12), dp(8)) - - fun barButton(label: String, fill: Int, textColor: Int, action: () -> Unit) = TextView(this).apply { - text = label - textSize = 15f - gravity = android.view.Gravity.CENTER - setTextColor(textColor) - setTypeface(typeface, Typeface.BOLD) - background = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - cornerRadius = dp(18).toFloat() - setColor(fill) - } - isClickable = true - setOnClickListener { - performKeyHaptic() - action() - } - } - val cancel = barButton( - ui("取消", "Cancel"), - tone(Color.rgb(60, 60, 60), Color.rgb(225, 225, 228)), - tone(Color.WHITE, Color.rgb(40, 40, 44)), - ) { discardDraft() } - val confirmFill = if (draftPurpose == DraftPurpose.CLOUD_NOTE) LINK_COLOR_CLOUD_NOTE else strokeEncodeAccentColor - val confirm = barButton(ui("确认", "Confirm"), confirmFill, Color.WHITE) { confirmDraft() } - val statusView = TextView(this).apply { - textSize = 13f - gravity = android.view.Gravity.CENTER - maxLines = 1 - ellipsize = android.text.TextUtils.TruncateAt.END - } - draftCancelButton = cancel - draftConfirmButton = confirm - draftStatusView = statusView - updateDraftControls() - - val buttons = LinearLayout(this).apply { gravity = android.view.Gravity.CENTER_VERTICAL } - buttons.addView(cancel, LinearLayout.LayoutParams(dp(84), dp(36))) - buttons.addView(statusView, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f).apply { - marginStart = dp(8) - marginEnd = dp(8) - }) - buttons.addView(confirm, LinearLayout.LayoutParams(dp(84), dp(36))) - - val bar = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(dp(16), dp(10), dp(16), dp(8)) - setBackgroundColor(panelColor) - // Swallow stray touches in the bar's padding so they can't reach the app underneath. - isClickable = true + private fun buildDraftBar(): ImeDraftBar? { + val edit = draftEdit ?: return null + return ImeDraftBar( + this, keyboardPalette(), edit, + onCancel = ::discardDraft, + onConfirm = ::confirmDraft, + onFeedback = ::performKeyHaptic, + ).also { bar -> + draftBar = bar + bar.cancel.text = ui("取消", "Cancel") + bar.cancel.contentDescription = ui("取消草稿", "Cancel draft") + bar.confirm.text = ui("确认", "Confirm") + bar.confirm.contentDescription = ui("确认草稿", "Confirm draft") + updateDraftControls() } - bar.addView(edit, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - bar.addView(buttons, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { - topMargin = dp(8) - }) - - val host = DraftHost(this, keyboard).apply { orientation = LinearLayout.VERTICAL } - host.addView(bar, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - host.addView(buildDivider(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1))) - host.addView(keyboard) - // View focus (not window focus) is what makes the caret draw and follow the text. - edit.post { edit.requestFocus() } - return host } private fun commitImeText(text: String) { @@ -4576,21 +3063,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt setState("done", "已上屏") } - private fun flatCircleButton(icon: String, sizeDp: Int, description: String, action: () -> Unit): TextView { - return TextView(this).apply { - text = icon - textSize = sizeDp * 0.45f - gravity = android.view.Gravity.CENTER - setTextColor(tone(Color.WHITE, Color.rgb(40, 40, 44))) - background = GradientDrawable().apply { - shape = GradientDrawable.OVAL - setColor(tone(Color.rgb(60, 60, 60), Color.rgb(225, 225, 228))) - } - contentDescription = description - setOnClickListener { action() } - } - } - /** Shows/hides and relabels the undo↔redo toggle and edit button for the last dictation result. */ private fun updateDictationResultControls() { // No longer gated on state == "done": that flips to "recording"/ @@ -4711,6 +3183,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt private fun setState(nextState: String, message: String, revertDelayMs: Long = DONE_TO_IDLE_DELAY_MS) { state = nextState + if (nextState != "done") ++statusRevertToken // The submit only ever shows as "thinking"; any other state means // it finished, failed, or a new dictation took over. if (nextState != "thinking") cloudNoteSubmitting = false @@ -4723,7 +3196,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // away — see scheduleRevertToIdle(). revertDelayMs only ever // differs from the default for quickNoteDictation()'s own shorter // "笔记已记录" confirmation (QUICK_NOTE_CONFIRMATION_DELAY_MS). - if (nextState == "done") scheduleRevertToIdle(revertDelayMs) + if (nextState == "done" || nextState == "cancelled") scheduleRevertToIdle(revertDelayMs) } /** @@ -4744,7 +3217,7 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt val epoch = sessionEpoch val token = ++statusRevertToken android.os.Handler(Looper.getMainLooper()).postDelayed({ - if (sessionEpoch == epoch && statusRevertToken == token) { + if (sessionEpoch == epoch && statusRevertToken == token && !dictationEditingLocked()) { setState("idle", ui("点击开始说话", "Tap to speak")) } }, delayMs) @@ -4782,82 +3255,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt internal fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() - /** - * Purely visual 0.98x press-scale via StateListAnimator, which reacts to - * the view's own pressed drawable-state — it doesn't add or replace any - * click/touch listener, so a key's existing action/repeat wiring is - * untouched. - */ - private fun attachPressScale(view: View) { - val down = android.animation.ObjectAnimator.ofPropertyValuesHolder( - view, - android.animation.PropertyValuesHolder.ofFloat(View.SCALE_X, 0.98f), - android.animation.PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.98f), - ).setDuration(100) - val up = android.animation.ObjectAnimator.ofPropertyValuesHolder( - view, - android.animation.PropertyValuesHolder.ofFloat(View.SCALE_X, 1f), - android.animation.PropertyValuesHolder.ofFloat(View.SCALE_Y, 1f), - ).setDuration(100) - view.stateListAnimator = android.animation.StateListAnimator().apply { - addState(intArrayOf(android.R.attr.state_pressed), down) - addState(intArrayOf(), up) - } - } - - internal fun roundedButton(color: Int, radius: Int): android.graphics.drawable.Drawable { - val lowerEdge = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - cornerRadius = radius.toFloat() - setColor(mixColor(color, Color.BLACK, 0.72f)) - } - val face = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - cornerRadius = radius.toFloat() - orientation = GradientDrawable.Orientation.TOP_BOTTOM - colors = intArrayOf( - mixColor(color, Color.WHITE, 0.09f), - color, - mixColor(color, Color.BLACK, 0.18f), - ) - setStroke(dp(1), mixColor(color, Color.BLACK, 0.55f)) - } - return android.graphics.drawable.LayerDrawable(arrayOf(lowerEdge, face)).apply { - // The exposed lower layer forms the reference keyboard's dark keycap step. - setLayerInset(0, 0, dp(2), 0, 0) - setLayerInset(1, 0, 0, 0, dp(3)) - } - } - - // Flat (no keycap relief) background for the encode+candidate strip: a - // rounded rect a touch lighter than the panel, plus a hairline divider - // baked in at the fixed 24dp encode/candidate boundary. Since `top`'s - // height is always exactly dp(60), this offset never drifts. - internal fun buildEncodeAreaBackground(): android.graphics.drawable.Drawable { - val panel = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - cornerRadius = dp(6).toFloat() - setColor(tone(Color.rgb(58, 58, 58), Color.rgb(228, 228, 232))) - } - val divider = GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - setColor(tone(Color.rgb(82, 82, 82), Color.rgb(205, 205, 210))) - } - val dividerBottomInset = (dp(60) - dp(24) - dp(1)).coerceAtLeast(0) - return android.graphics.drawable.LayerDrawable(arrayOf(panel, divider)).apply { - setLayerInset(1, dp(8), dp(24), dp(8), dividerBottomInset) - } - } - - private fun mixColor(first: Int, second: Int, amount: Float): Int { - val ratio = amount.coerceIn(0f, 1f) - return Color.rgb( - (Color.red(first) + (Color.red(second) - Color.red(first)) * ratio).toInt(), - (Color.green(first) + (Color.green(second) - Color.green(first)) * ratio).toInt(), - (Color.blue(first) + (Color.blue(second) - Color.blue(first)) * ratio).toInt(), - ) - } - private fun startRuntimeService() { try { OpenLessRuntimeService.setImeRequested(this, true) @@ -4923,69 +3320,9 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt OpenLessRuntimeService.setImeRequested(this, false) } - /** - * A vertical stack of keys that also recognizes a whole-column swipe: - * once a drag exceeds touch slop, this claims the gesture from whichever - * child key the drag started on (via onInterceptTouchEvent) so a single - * swipe anywhere in the column advances exactly one group, rather than - * being absorbed as a press/drag on one key. - */ - internal class SwipeRail( - context: android.content.Context, - private val onSwipe: (Int) -> Unit, - ) : LinearLayout(context) { - private var startY = 0f - private var intercepting = false - private val touchSlop = android.view.ViewConfiguration.get(context).scaledTouchSlop - - init { - excludeFromSystemGestures(this) - } - - override fun onInterceptTouchEvent(ev: android.view.MotionEvent): Boolean { - when (ev.actionMasked) { - android.view.MotionEvent.ACTION_DOWN -> { - startY = ev.y - intercepting = false - } - android.view.MotionEvent.ACTION_MOVE -> { - if (!intercepting && kotlin.math.abs(ev.y - startY) > touchSlop) { - intercepting = true - // Stop the outer SwipeModeContainer (or any other - // ancestor) from also trying to claim this gesture - // once we've committed to handling it as a vertical - // drag — otherwise a still-moving finger can flip - // back and forth between the two interceptors. - parent?.requestDisallowInterceptTouchEvent(true) - } - } - } - return intercepting - } - - override fun onTouchEvent(event: android.view.MotionEvent): Boolean { - if (event.actionMasked == android.view.MotionEvent.ACTION_UP || - event.actionMasked == android.view.MotionEvent.ACTION_CANCEL - ) { - val dy = startY - event.y - // Swiping up (finger moves toward the top, dy > 0) advances to - // the next group; swiping down goes back to the previous one. - // Posted rather than called inline: onSwipe rebuilds the whole - // input view, and doing that synchronously while this touch - // gesture is still unwinding through the view we're about to - // replace is what caused the panel to visibly flicker - // closed/open under the finger. - if (kotlin.math.abs(dy) > touchSlop) post { onSwipe(if (dy > 0) 1 else -1) } - intercepting = false - } - return true - } - } - /** * Outer IME host for stretch+raise: key panel on top + empty lift strip - * below. Forces EXACT total height the same way [SwipeModeContainer] - * forces the key-panel height (setInputView discards LayoutParams). + * below. Owns exact total height because setInputView replaces LayoutParams. * Re-reads prefs on every measure so a settings change applies on the * next layout even before a full view rebuild. */ @@ -4993,14 +3330,20 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt context: android.content.Context, ) : LinearLayout(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { - val panel = panelHeightPx(context) - val raise = raiseHeightPx(context) + val preferredPanel = panelHeightPx(context) + val preferredRaise = raiseHeightPx(context) + val bound = if (View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.UNSPECIFIED) { + preferredPanel + preferredRaise + } else View.MeasureSpec.getSize(heightMeasureSpec).coerceAtLeast(0) + val panel = minOf(preferredPanel, bound) + val raise = minOf(preferredRaise, (bound - panel).coerceAtLeast(0)) if (childCount >= 1) { - getChildAt(0).layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, panel) + val keys = getChildAt(0) + if (keys.layoutParams.height != panel) keys.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, panel) } if (childCount >= 2) { val spacer = getChildAt(1) - spacer.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, raise) + if (spacer.layoutParams.height != raise) spacer.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, raise) spacer.visibility = if (raise > 0) View.VISIBLE else View.GONE } val exactHeightSpec = android.view.View.MeasureSpec.makeMeasureSpec( @@ -5011,12 +3354,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt } } - /** Input view while a draft is open: the draft bar stacked above the regular [keyboard] view. */ - private class DraftHost( - context: android.content.Context, - val keyboard: View, - ) : LinearLayout(context) - /** * The draft box's own InputConnection, with key events turned into text * edits. The IME window never has window focus, and the framework drops @@ -5059,1352 +3396,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt override fun performEditorAction(actionCode: Int): Boolean = commitText("\n", 1) } - /** - * Horizontal swipe-to-switch-mode, applied to every panel's root - * container: a left/right drag anywhere that isn't already claimed by a - * vertical gesture (like SwipeRail) steps the input mode toward - * Voice/English, matching the toggle switch's order. A downward drag - * anywhere on the panel dismisses the keyboard entirely, same as any - * other IME's own hide gesture. - */ - internal class SwipeModeContainer( - context: android.content.Context, - // Fraction of the container's width, measured from the left edge, - // where a downward drag never triggers dismiss — the stroke panel's - // punctuation rail lives there and owns vertical drags itself - // (cycling punctuation groups). Without this, a clean vertical drag - // starting on the rail was won by this container's own intercept - // check on the very same touch-move event, before the rail (a - // descendant, checked only after this ancestor) ever got a chance - // to call requestDisallowInterceptTouchEvent — so its own "stop the - // outer container" call never ran in time. Excluding the zone by - // touch-down position sidesteps that dispatch-order race entirely. - private val verticalDismissExclusionRatio: Float = 0f, - // Off for the clipboard history sub-panel: its rows use left/right - // swipes themselves (favorite / add correction rule), and trying to - // exclude just their region would hit the exact same dispatch-order - // race noted above for the punctuation rail — simplest to just not - // compete for horizontal drags at all inside that sub-panel. - private val horizontalSwipeEnabled: Boolean = true, - // Checked once, at the moment a drag first looks vertical enough to - // possibly claim (see onInterceptTouchEvent's ACTION_MOVE branch) — - // returning false there lets the gesture fall through to a nested - // scrollable child instead (e.g. the clipboard history list), so a - // downward drag only dismisses the keyboard once that child is - // already scrolled to its own top, the same "pull past the top to - // dismiss" convention most scrollable sheets use. Defaults to - // "always allowed" for every panel that has no such nested scroll. - private val verticalDismissAllowed: () -> Boolean = { true }, - private val onSwipe: (Int) -> Unit, - ) : LinearLayout(context) { - private var startX = 0f - private var startY = 0f - private var interceptingHorizontal = false - private var interceptingVertical = false - private var verticalDismissBlockedForGesture = false - private val touchSlop = android.view.ViewConfiguration.get(context).scaledTouchSlop - private val dismissThreshold = (120 * resources.displayMetrics.density).toInt() - // Committing an actual mode switch needs a much bigger, deliberate - // drag than the touchSlop-based early claim above (which only - // exists so a vertical scroll elsewhere doesn't get mistaken for a - // mode swipe partway through) — a fraction of the panel's own width - // rather than a fixed dp figure, so the required drag scales with - // the device instead of feeling different on a small vs. large - // screen. Computed against `width` at commit time (onTouchEvent), - // not here at construction, since the view isn't laid out yet. - private val commitThresholdFraction = 1f / 3f - - init { - excludeFromSystemGestures(this) - } - - // InputMethodService.setInputView() re-wraps whatever view we return - // in its OWN FrameLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT), - // discarding the fixed-height LayoutParams every panel builder sets - // on its root — confirmed via a live device: the attached root's - // own layoutParams.height read back as WRAP_CONTENT (-2), not the - // configured height we set. Under a generous (near-fullscreen) - // WRAP_CONTENT/AT_MOST measure spec from the system, any 0dp/weight=1 - // flexible child (the spacer used by several panels) happily expands - // to fill that huge bound instead of the real configured height. - // Forcing an EXACTLY height spec here — regardless of what the parent - // asks for — makes every panel's height genuinely fixed instead of - // accidental. - override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { - val fixedHeight = panelHeightPx(context) - val exactHeightSpec = android.view.View.MeasureSpec.makeMeasureSpec(fixedHeight, android.view.View.MeasureSpec.EXACTLY) - super.onMeasure(widthMeasureSpec, exactHeightSpec) - } - - override fun onInterceptTouchEvent(ev: android.view.MotionEvent): Boolean { - when (ev.actionMasked) { - android.view.MotionEvent.ACTION_DOWN -> { - startX = ev.x - startY = ev.y - interceptingHorizontal = false - interceptingVertical = false - verticalDismissBlockedForGesture = verticalDismissExclusionRatio > 0f && - ev.x < width * verticalDismissExclusionRatio - } - android.view.MotionEvent.ACTION_MOVE -> { - val dx = ev.x - startX - val dy = ev.y - startY - // Require a clearly horizontal drag so this never steals a - // vertical gesture meant for a nested SwipeRail. - if (horizontalSwipeEnabled && !interceptingHorizontal && !interceptingVertical && - kotlin.math.abs(dx) > touchSlop && kotlin.math.abs(dx) > kotlin.math.abs(dy) * 1.5f - ) { - interceptingHorizontal = true - parent?.requestDisallowInterceptTouchEvent(true) - } - // A downward drag anywhere not already claimed by a - // nested vertical gesture (the candidate scroll) or - // excluded by touch-down position (the punctuation rail) - // dismisses the keyboard — unless verticalDismissAllowed() - // says a nested scrollable child still has room to - // scroll up first (the clipboard history list). - if (!interceptingHorizontal && !interceptingVertical && !verticalDismissBlockedForGesture && - dy > touchSlop && dy > kotlin.math.abs(dx) * 1.5f && verticalDismissAllowed() - ) { - interceptingVertical = true - parent?.requestDisallowInterceptTouchEvent(true) - } - } - } - return interceptingHorizontal || interceptingVertical - } - - override fun onTouchEvent(event: android.view.MotionEvent): Boolean { - if (event.actionMasked == android.view.MotionEvent.ACTION_UP || - event.actionMasked == android.view.MotionEvent.ACTION_CANCEL - ) { - val dx = event.x - startX - val dy = event.y - startY - if (interceptingVertical && dy > dismissThreshold) { - post { (context as? OpenLessImeService)?.hideKeyboardPanel() } - } else if (kotlin.math.abs(dx) > width * commitThresholdFraction) { - // Swiping left (finger moves toward the start, dx < 0) - // steps toward Voice; swiping right steps toward - // English. (This is inverted from the raw dx sign — on- - // device testing showed dx < 0 landing on English, so - // the mapping below matches what actually happens rather - // than the "obvious" sign.) - // Posted for the same reason as SwipeRail: avoid - // rebuilding the input view synchronously mid-gesture. - post { onSwipe(if (dx < 0) 1 else -1) } - } - interceptingHorizontal = false - interceptingVertical = false - } - return true - } - } - - private class ModeToggle( - context: android.content.Context, - private val selectedMode: InputMode, - private val darkTheme: Boolean, - private val onModeSelected: (InputMode) -> Unit, - ) : View(context) { - // Instance properties, not companion constants — this view is - // rebuilt on every panel refresh, so a live theme switch just means - // a fresh instance with the other branch's colors. - private val trackColor = if (darkTheme) Color.rgb(28, 28, 28) else Color.rgb(222, 222, 226) - // Weakened from a fully-opaque line to a near-invisible one — the - // floating selected pill below is meant to be the only thing the - // user reads as "current mode", not these dividers, but the layout - // math that positions the four icons/labels still uses the same - // segmentWidth split, so the dividers stay (very faintly) for - // continuity rather than being deleted outright. - private val dividerColor = run { - val base = if (darkTheme) Color.rgb(58, 58, 58) else Color.rgb(200, 200, 204) - Color.argb(28, Color.red(base), Color.green(base), Color.blue(base)) - } - // Same surface color as every ordinary key's own background - // (roundedButton(tone(Color.rgb(52, 52, 54), Color.WHITE), ...) — - // see buildEnglishCharKey()/keyboardKey()) — reusing it here ties - // the selected pill into the keyboard's existing "raised key" - // visual language instead of introducing a new floating-pill color. - private val selectedPillColor = if (darkTheme) Color.rgb(52, 52, 54) else Color.WHITE - private val iconColor = if (darkTheme) Color.rgb(240, 240, 240) else Color.rgb(50, 50, 54) - // Unselected icons/labels dim slightly (not a color or hue change) - // so the fully-opaque selected one reads as the one thing actively - // "on" — a light touch, not the kind of visible recolor the spec - // asks not to introduce. - private val dimmedIconColor = Color.argb(178, Color.red(iconColor), Color.green(iconColor), Color.blue(iconColor)) - private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - strokeCap = Paint.Cap.ROUND - strokeJoin = Paint.Join.ROUND - } - // Labels are drawn at a size derived from the view height, not the - // system text size, so they never shift with font scale or UI language. - private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = iconColor - typeface = android.graphics.Typeface.create(android.graphics.Typeface.DEFAULT, android.graphics.Typeface.BOLD) - } - private val textBounds = android.graphics.Rect() - private val chevronPath = Path() - - // Continuous [0, modes.size - 1] position of the selected pill, in - // segment units — settles on the selected index, but slides through - // fractional values mid-animation. This view is a fresh instance on - // every panel rebuild (see the class doc above), so a real mode - // switch is detected by comparing against lastRenderedMode (a - // companion field, surviving across those rebuilds) rather than any - // state this instance could hold itself; an unrelated rebuild that - // leaves the mode unchanged just settles here with no animation. - private var indicatorPosition: Float - private var indicatorAnimator: android.animation.ValueAnimator? = null - - init { - val modes = InputMode.entries - val targetIndex = modes.indexOf(selectedMode).coerceAtLeast(0).toFloat() - val previousMode = lastRenderedMode - if (previousMode != null && previousMode != selectedMode) { - val startIndex = modes.indexOf(previousMode).coerceAtLeast(0).toFloat() - indicatorPosition = startIndex - indicatorAnimator = android.animation.ValueAnimator.ofFloat(startIndex, targetIndex).apply { - duration = 180L - interpolator = android.view.animation.DecelerateInterpolator() - addUpdateListener { - indicatorPosition = it.animatedValue as Float - invalidate() - } - start() - } - } else { - indicatorPosition = targetIndex - } - lastRenderedMode = selectedMode - } - - override fun onDetachedFromWindow() { - indicatorAnimator?.cancel() - super.onDetachedFromWindow() - } - - // Every proportion below is measured off the reference toggle design - // and expressed in units of the pill height `h`. - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - val modes = InputMode.entries - val h = height.toFloat() - val w = width.toFloat() - val segmentWidth = w / modes.size - val centerY = h / 2f - - paint.style = Paint.Style.FILL - paint.color = trackColor - canvas.drawRoundRect(0f, 0f, w, h, h / 2f, h / 2f, paint) - - paint.color = dividerColor - paint.strokeWidth = h * 0.012f - for (i in 1 until modes.size) { - val x = segmentWidth * i - canvas.drawLine(x, h * 0.2f, x, h * 0.8f, paint) - } - - // Floating rounded pill instead of the old sharp, edge-to-edge - // highlight: inset on every side so it reads as its own raised - // surface hovering over the track rather than a panel-colored - // cutout flush with the track's shape. Insets alone keep it - // well inside the track's rounded corners even at the first/ - // last segment, so no extra clip path is needed the way the - // sharp-cornered version required one. - // Proportional again, not fixed dp — carries forward the exact - // ratio the last explicit dp spec settled on (5dp inset / 38dp - // track height, 53dp pill / 60dp segment width at the 240dp - // outer track width in use then), so the pill keeps this same - // look if the outer track's own width/height are ever tuned - // again, instead of needing a matching manual dp recompute. - val pillInsetV = h * (5f / 38f) - val pillWidth = segmentWidth * (53f / 60f) - val pillCenterX = segmentWidth * (indicatorPosition + 0.5f) - val pillLeft = pillCenterX - pillWidth / 2f - val pillRight = pillCenterX + pillWidth / 2f - val pillTop = pillInsetV - val pillBottom = h - pillInsetV - paint.color = selectedPillColor - canvas.drawRoundRect(pillLeft, pillTop, pillRight, pillBottom, (pillBottom - pillTop) / 2f, (pillBottom - pillTop) / 2f, paint) - - val selectedIndex = modes.indexOf(selectedMode).coerceAtLeast(0) - fun colorFor(index: Int) = if (index == selectedIndex) iconColor else dimmedIconColor - - paint.color = colorFor(0) - drawWaveform(canvas, segmentWidth * 0.5f, centerY, h) - textPaint.color = colorFor(1) - drawLabel(canvas, "笔画", segmentWidth * 1.5f, centerY, h * 0.38f, extraBold = true) - paint.color = colorFor(2) - drawCursorBrackets(canvas, segmentWidth * 2.5f, centerY, h) - textPaint.color = colorFor(3) - drawLabel(canvas, "EN", segmentWidth * 3.5f, centerY, h * 0.28f) - } - - /** Five bars — short, mid, tall, mid, short. */ - private fun drawWaveform(canvas: Canvas, centerX: Float, centerY: Float, h: Float) { - paint.strokeWidth = h * 0.033f - val spacing = h * 0.11f - floatArrayOf(0.078f, 0.153f, 0.225f, 0.153f, 0.078f).forEachIndexed { index, half -> - val x = centerX + (index - 2) * spacing - canvas.drawLine(x, centerY - h * half, x, centerY + h * half, paint) - } - } - - /** "": a bold capital-I beam (with top/bottom serifs) flanked by chevrons nearly as tall as it. */ - private fun drawCursorBrackets(canvas: Canvas, centerX: Float, centerY: Float, h: Float) { - // Overall extent (openX/tipX/halfH below) is unchanged from the - // plain-bar version, so the icon's total width/height stays put - // even though the center beam is now a thicker "I" with serifs. - val barHalfH = h * 0.16f - val serifHalfW = h * 0.05f - paint.strokeWidth = h * 0.045f - canvas.drawLine(centerX, centerY - barHalfH, centerX, centerY + barHalfH, paint) - canvas.drawLine(centerX - serifHalfW, centerY - barHalfH, centerX + serifHalfW, centerY - barHalfH, paint) - canvas.drawLine(centerX - serifHalfW, centerY + barHalfH, centerX + serifHalfW, centerY + barHalfH, paint) - - paint.strokeWidth = h * 0.03f - val openX = h * 0.14f - val tipX = h * 0.289f - val halfH = h * 0.143f - paint.style = Paint.Style.STROKE - chevronPath.reset() - chevronPath.moveTo(centerX - openX, centerY - halfH) - chevronPath.lineTo(centerX - tipX, centerY) - chevronPath.lineTo(centerX - openX, centerY + halfH) - chevronPath.moveTo(centerX + openX, centerY - halfH) - chevronPath.lineTo(centerX + tipX, centerY) - chevronPath.lineTo(centerX + openX, centerY + halfH) - canvas.drawPath(chevronPath, paint) - paint.style = Paint.Style.FILL - } - - /** Bold label scaled so its actual ink height (not the font's line height) equals [inkHeight]. */ - private fun drawLabel(canvas: Canvas, label: String, centerX: Float, centerY: Float, inkHeight: Float, extraBold: Boolean = false) { - textPaint.isFakeBoldText = extraBold - textPaint.textSize = 100f - textPaint.getTextBounds(label, 0, label.length, textBounds) - textPaint.textSize = 100f * inkHeight / textBounds.height().coerceAtLeast(1) - textPaint.getTextBounds(label, 0, label.length, textBounds) - canvas.drawText(label, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint) - } - - override fun onTouchEvent(event: android.view.MotionEvent): Boolean { - if (event.action == android.view.MotionEvent.ACTION_UP) { - val modes = InputMode.entries - val index = (event.x / (width / modes.size.toFloat())).toInt().coerceIn(0, modes.lastIndex) - onModeSelected(modes[index]) - } - return true - } - - private companion object { - // Survives across this view's per-rebuild instances (see the - // class doc above) so a fresh instance can tell "the mode - // actually changed since last drawn" from "this rebuild is for - // some unrelated reason" and only animate the former. - @Volatile - private var lastRenderedMode: InputMode? = null - } - } - - /** Central stroke keys use a canvas glyph so their proportions do not depend on a font. */ - private class StrokeGlyphView( - context: android.content.Context, - private val glyphCode: String, - darkTheme: Boolean, - ) : TextView(context) { - private val iconColor = if (darkTheme) Color.rgb(232, 232, 232) else Color.rgb(40, 40, 44) - private val mutedColor = if (darkTheme) Color.rgb(155, 155, 155) else Color.rgb(130, 130, 135) - private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = iconColor - textAlign = Paint.Align.CENTER - typeface = android.graphics.Typeface.create("sans-serif", android.graphics.Typeface.NORMAL) - } - - override fun onDraw(canvas: Canvas) { - val unit = minOf(width, height).coerceAtLeast(1) / 100f - val x = width / 2f - paint.style = Paint.Style.FILL - paint.textSize = 19f * unit - val text = when (glyphCode) { - "*" -> "通配" - " " -> "分词" - ":" -> ":" - ";" -> ";" - "symbols" -> "符号" - "script" -> "繁" - else -> glyphCode - } - val top = when (glyphCode) { - "*" -> "6" - " " -> "7" - ":" -> "8" - ";" -> "9" - else -> "" - } - if (top.isNotEmpty()) { - paint.color = mutedColor - paint.textSize = 20f * unit - // Matches the "0" key's TextView-rendered top-gravity number, which - // sits lower than this baseline-based canvas position implied. - canvas.drawText(top, x, 32f * unit, paint) - paint.color = iconColor - } - paint.textSize = if (text in listOf("符号", "通配", "分词", "繁")) 33f * unit else 27f * unit - canvas.drawText(text, x, if (top.isEmpty()) 61f * unit else 76f * unit, paint) - } - } - - /** - * Red actions are also custom-drawn to keep the reference glyph geometry - * stable. Takes an explicit icon color rather than a theme flag: this - * view is reused both on the always-dark-red action keys (icon always - * white, in both themes) and, undecorated, on the clipboard panel's - * normal/highlighted keys (icon needs to flip with the theme there). - */ - internal class StrokeActionView( - context: android.content.Context, - private val actionCode: String, - private val iconRotation: Float = 0f, - private val iconColor: Int = Color.WHITE, - ) : TextView(context) { - private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = iconColor - style = Paint.Style.STROKE - strokeWidth = 5.2f - strokeCap = Paint.Cap.SQUARE - strokeJoin = Paint.Join.MITER - } - private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = iconColor - textAlign = Paint.Align.CENTER - typeface = android.graphics.Typeface.create("sans-serif", android.graphics.Typeface.NORMAL) - } - private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = iconColor - style = Paint.Style.FILL - } - - override fun onDraw(canvas: Canvas) { - val u = minOf(width, height).coerceAtLeast(1) / 100f - val cx = width / 2f - val cy = height / 2f - paint.strokeWidth = 5.2f * u - when (actionCode) { - "triangle-down" -> { - // Fixed absolute size, independent of this button's own - // (roughly 28x36dp, non-square) cell — about the same - // visual footprint as a single candidate glyph - // (candidateItemView's 20sp text), not scaled to the - // fixed-100-unit icon canvas the other cases share. - val triangleSize = 16f * resources.displayMetrics.density - val topY = cy - triangleSize / 2f - val path = Path().apply { - moveTo(cx - triangleSize / 2f, topY) - lineTo(cx + triangleSize / 2f, topY) - lineTo(cx, topY + triangleSize) - close() - } - canvas.drawPath(path, fillPaint) - } - "←" -> { - canvas.drawLine(cx - 23f * u, cy, cx + 23f * u, cy, paint) - canvas.drawLine(cx - 23f * u, cy, cx - 8f * u, cy - 12f * u, paint) - canvas.drawLine(cx - 23f * u, cy, cx - 8f * u, cy + 12f * u, paint) - } - "↵" -> { - val path = Path().apply { - moveTo(cx + 23f * u, cy - 14f * u) - lineTo(cx + 23f * u, cy + 5f * u) - quadTo(cx + 23f * u, cy + 15f * u, cx + 13f * u, cy + 15f * u) - lineTo(cx - 22f * u, cy + 15f * u) - } - canvas.drawPath(path, paint) - canvas.drawLine(cx - 22f * u, cy + 15f * u, cx - 10f * u, cy + 5f * u, paint) - canvas.drawLine(cx - 22f * u, cy + 15f * u, cx - 10f * u, cy + 25f * u, paint) - } - "dir-up", "backspace-icon" -> { - // Fixed 32dp icon canvas (not scaled to the button's own, - // possibly larger, size) so all four rotated direction - // keys and the backspace key render at one identical - // visual size no matter how the grid divides the row. - // Rotating the canvas (not the whole View) keeps the - // button's own rectangular background undistorted even - // when the cell itself isn't perfectly square. - val iconUnit = (32 * resources.displayMetrics.density) / 100f - paint.strokeWidth = 9f * iconUnit - paint.strokeCap = Paint.Cap.ROUND - paint.strokeJoin = Paint.Join.ROUND - canvas.save() - if (iconRotation != 0f) canvas.rotate(iconRotation, cx, cy) - if (actionCode == "dir-up") { - val chevron = Path().apply { - moveTo(cx - 22f * iconUnit, cy + 12f * iconUnit) - lineTo(cx, cy - 12f * iconUnit) - lineTo(cx + 22f * iconUnit, cy + 12f * iconUnit) - } - canvas.drawPath(chevron, paint) - } else { - // Classic backspace silhouette: a left-pointing tag - // outline with an "X" inside, same line weight as the - // direction arrows. - val outline = Path().apply { - moveTo(cx - 26f * iconUnit, cy) - lineTo(cx - 8f * iconUnit, cy - 22f * iconUnit) - lineTo(cx + 26f * iconUnit, cy - 22f * iconUnit) - lineTo(cx + 26f * iconUnit, cy + 22f * iconUnit) - lineTo(cx - 8f * iconUnit, cy + 22f * iconUnit) - close() - } - canvas.drawPath(outline, paint) - canvas.drawLine(cx - 2f * iconUnit, cy - 10f * iconUnit, cx + 16f * iconUnit, cy + 10f * iconUnit, paint) - canvas.drawLine(cx + 16f * iconUnit, cy - 10f * iconUnit, cx - 2f * iconUnit, cy + 10f * iconUnit, paint) - } - canvas.restore() - } - else -> { - textPaint.textSize = if (actionCode == "清除") 32f * u else 30f * u - canvas.drawText(actionCode, cx, cy - (textPaint.ascent() + textPaint.descent()) / 2f, textPaint) - } - } - } - } - - private class StrokeKeyView( - context: android.content.Context, - private val strokeCode: String, - darkTheme: Boolean, - ) : TextView(context) { - private val numberPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = if (darkTheme) Color.rgb(155, 155, 155) else Color.rgb(130, 130, 135) - textAlign = Paint.Align.CENTER - typeface = android.graphics.Typeface.create("sans-serif", android.graphics.Typeface.NORMAL) - } - private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = if (darkTheme) Color.rgb(232, 232, 232) else Color.rgb(40, 40, 44) - style = Paint.Style.STROKE - strokeCap = Paint.Cap.ROUND - strokeJoin = Paint.Join.ROUND - } - - override fun onDraw(canvas: Canvas) { - val unit = minOf(width, height).coerceAtLeast(1) / 100f - val centerX = width / 2f - val topNumber = when (strokeCode) { - "h" -> "1" - "s" -> "2" - "p" -> "3" - "n" -> "4" - else -> "5" - } - numberPaint.textSize = 20f * unit - // Matches the "0" key's TextView-rendered top-gravity number, which - // sits lower than this baseline-based canvas position implied. - canvas.drawText(topNumber, centerX, 32f * unit, numberPaint) - - strokePaint.strokeWidth = 3.2f * unit - val stroke = Path() - when (strokeCode) { - "h" -> { - stroke.moveTo(centerX - 20f * unit, 62f * unit) - stroke.lineTo(centerX + 20f * unit, 62f * unit) - } - "s" -> { - // Top trimmed by 1/6 of the original 42–79 length (bottom - // unchanged) at the user's request: 42 + (79-42)/6 ≈ 48.17. - stroke.moveTo(centerX, 48.17f * unit) - stroke.lineTo(centerX, 79f * unit) - } - "p" -> { - // Traced from the reference glyph: straight down for most - // of the stroke, hooking left only at the very end — a "J" - // shape, not a curve along its whole length. Top trimmed - // by 1/6 of the original 38–77 length (bottom/control - // points unchanged): 38 + (77-38)/6 = 44.5. - stroke.moveTo(centerX - 2f * unit, 44.5f * unit) - stroke.cubicTo( - centerX - 2f * unit, 55f * unit, - centerX - 5f * unit, 68f * unit, - centerX - 16f * unit, 77f * unit, - ) - } - "n" -> { - // Traced from the reference glyph: a short, straight tick, - // not a long curve — 丶 is a dot/dian, not a swooping line. - stroke.moveTo(centerX - 7f * unit, 50f * unit) - stroke.lineTo(centerX + 6f * unit, 67f * unit) - } - else -> { - // Traced from the reference glyph: a diagonal down-left to - // a corner, then a horizontal finish to the right (乙/横折). - // Top trimmed by 1/6 of the original 42–71 diagonal length - // (bottom unchanged): 42 + (71-42)/6 ≈ 46.83. - stroke.moveTo(centerX + 1f * unit, 46.83f * unit) - stroke.lineTo(centerX - 13f * unit, 71f * unit) - stroke.lineTo(centerX + 15f * unit, 71f * unit) - } - } - canvas.drawPath(stroke, strokePaint) - } - } - - /** - * Two-line label (via a plain "\n") with a thin horizontal divider - * drawn between the lines — the divider just needs the vertical - * midpoint of the view, which lands between the two centered lines of - * text closely enough without measuring actual text layout bounds. - */ - /** - * The one key-press preview bubble shared by every keyboard (English - * and stroke) — a short, wide "floating keycap": a rounded rect with a - * short stubby arrow, soft light-gray body and near-black text, no - * accent color. Always sized/positioned by its owner (KeyPreviewOverlay) - * rather than by itself; this class only draws. Plain Canvas drawing, - * matching every other custom key glyph in this file (ShiftKeyView, - * ActionSymbolView, etc.) — no new dependency. - */ - private class KeyPreviewBubbleView( - context: android.content.Context, - darkTheme: Boolean, - ) : View(context) { - var label: String = "" - set(value) { - field = value - invalidate() - } - // Non-null (the stroke keyboard's swipe-up digit preview) matches - // the actual pressed key's own font size (TextView.getTextSize(), - // already resolved to raw pixels, so no sp->px conversion is - // needed here) instead of the default size derived from the - // bubble's own height, which the English tap preview still relies on. - var fixedTextSizePx: Float? = null - set(value) { - field = value - invalidate() - } - private val bodyPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - // Lighter than the stroke encode/candidate row's own card - // background in both themes (buildEncodeAreaBackground(): - // 58,58,58 dark / 228,228,232 light) rather than darker — a - // darker-than-the-card bubble read as low-contrast/blended-in; - // sitting a step lighter than that card makes the bubble read - // as its own raised surface instead. - color = if (darkTheme) Color.rgb(96, 96, 100) else Color.rgb(246, 246, 249) - } - private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - style = Paint.Style.STROKE - strokeWidth = 2f - // Dark theme: a lighter outline than the body for definition - // against a similarly-dark panel. Light theme: a slightly - // darker outline than the now near-white body, since a lighter - // outline there would have no contrast against anything. - color = if (darkTheme) Color.rgb(128, 128, 133) else Color.rgb(210, 210, 215) - } - // Same red as the right-hand action rail's ←/↵/清除/123 keys and - // the stroke candidate row's own selected/first candidate - // (candidateItemView()), brightened for dark theme by the same - // amount as candidateItemView()'s own dark-theme branch — the two - // stay in sync since they're tuned together. - private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = if (darkTheme) Color.rgb(190, 45, 60) else Color.rgb(153, 26, 40) - textAlign = Paint.Align.CENTER - typeface = android.graphics.Typeface.DEFAULT_BOLD - // FILL_AND_STROKE over DEFAULT_BOLD's own fill adds a touch more - // weight than the typeface alone — there's no heavier built-in - // weight to switch to without bundling a custom font. - style = Paint.Style.FILL_AND_STROKE - strokeWidth = 1.4f - } - private val outline = Path() - - private fun dp(value: Int): Float = value * resources.displayMetrics.density - - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - val w = width.toFloat() - val h = height.toFloat() - if (w <= 0f || h <= 0f) return - val arrowHeight = dp(ARROW_HEIGHT_DP) - val arrowHalfWidth = dp(ARROW_WIDTH_DP) / 2f - val bodyBottom = h - arrowHeight - // Also capped by the flat run left on either side of the arrow - // notch (w/2 - arrowHalfWidth) — at the narrowest bubble widths - // this is tighter than bodyBottom/2, and skipping it would let - // the bottom-corner arcs overrun the notch and self-intersect. - val radius = dp(CORNER_RADIUS_DP) - .coerceAtMost(bodyBottom / 2f) - .coerceAtMost((w / 2f - arrowHalfWidth).coerceAtLeast(0f)) - val cx = w / 2f - // One continuous outline (all four corners rounded to the same - // radius, short triangular notch at the bottom center) so a - // stroked border never shows a seam where the arrow meets the - // body. - outline.reset() - outline.moveTo(radius, 0f) - outline.lineTo(w - radius, 0f) - outline.arcTo(android.graphics.RectF(w - 2f * radius, 0f, w, 2f * radius), -90f, 90f) - outline.lineTo(w, bodyBottom - radius) - outline.arcTo(android.graphics.RectF(w - 2f * radius, bodyBottom - 2f * radius, w, bodyBottom), 0f, 90f) - outline.lineTo(cx + arrowHalfWidth, bodyBottom) - outline.lineTo(cx, h) - outline.lineTo(cx - arrowHalfWidth, bodyBottom) - outline.lineTo(radius, bodyBottom) - outline.arcTo(android.graphics.RectF(0f, bodyBottom - 2f * radius, 2f * radius, bodyBottom), 90f, 90f) - outline.lineTo(0f, radius) - outline.arcTo(android.graphics.RectF(0f, 0f, 2f * radius, 2f * radius), 180f, 90f) - outline.close() - canvas.drawPath(outline, bodyPaint) - canvas.drawPath(outline, borderPaint) - textPaint.textSize = fixedTextSizePx ?: (bodyBottom * 0.5f) - val metrics = textPaint.fontMetrics - val textY = bodyBottom / 2f - (metrics.ascent + metrics.descent) / 2f - canvas.drawText(label, cx, textY, textPaint) - } - - companion object { - const val ARROW_HEIGHT_DP = 12 - const val ARROW_WIDTH_DP = 22 - const val CORNER_RADIUS_DP = 4 - const val BODY_HEIGHT_DP = 48 - const val TOTAL_HEIGHT_DP = BODY_HEIGHT_DP + ARROW_HEIGHT_DP - } - } - - /** - * Single top-level overlay hosting the one KeyPreviewBubbleView shared - * by every key in a panel (see wrapWithKeyPreviewOverlay()). Added as - * the last (topmost-drawn) child of the FrameLayout that wraps a - * panel's own root, so the bubble renders above the whole keyboard — - * unaffected by the panel's own clipChildren/candidate-row/mode-toggle - * bounds — without taking part in that panel's layout: it never - * changes size, position, or measurement of anything else, and it - * never intercepts touch (dispatchTouchEvent always returns false, so - * every gesture falls straight through to whatever key is underneath). - */ - private class KeyPreviewOverlay( - context: android.content.Context, - darkTheme: Boolean, - ) : FrameLayout(context) { - private val bubble = KeyPreviewBubbleView(context, darkTheme).apply { - alpha = 0f - visibility = View.GONE - } - - init { - isClickable = false - isFocusable = false - clipChildren = false - clipToPadding = false - addView(bubble, LayoutParams(0, 0)) - } - - // A pure visual layer: never claims a touch sequence, regardless of - // where the bubble is currently drawn, so a stroke swipe or an - // English drag-retarget already in progress is never disturbed by - // the preview appearing on top of it. - override fun onInterceptTouchEvent(ev: MotionEvent): Boolean = false - override fun dispatchTouchEvent(ev: MotionEvent): Boolean = false - - private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() - - private fun relativeLocation(target: View): IntArray { - val targetLoc = IntArray(2) - target.getLocationOnScreen(targetLoc) - val selfLoc = IntArray(2) - getLocationOnScreen(selfLoc) - return intArrayOf(targetLoc[0] - selfLoc[0], targetLoc[1] - selfLoc[1]) - } - - private fun placeBubble(centerX: Int, top: Int, bubbleWidth: Int, bubbleHeight: Int) { - val maxLeft = (width - bubbleWidth - dp(4)).coerceAtLeast(dp(4)) - val left = (centerX - bubbleWidth / 2).coerceIn(dp(4), maxLeft) - val clampedTop = top.coerceAtLeast(dp(2)) - val params = bubble.layoutParams as LayoutParams - params.width = bubbleWidth - params.height = bubbleHeight - params.leftMargin = left - params.topMargin = clampedTop - bubble.layoutParams = params - } - - /** - * TAP preview (English/number/symbol keys): centered directly above - * the anchor key, sized relative to it, with the default - * proportional-to-body text size (fixedTextSizePx left null). - */ - fun showTapPreview(text: String, anchor: View) { - val loc = relativeLocation(anchor) - val bubbleWidth = (anchor.width * BUBBLE_WIDTH_RATIO).toInt().coerceAtLeast(dp(40)) - val bubbleHeight = dp(KeyPreviewBubbleView.TOTAL_HEIGHT_DP) - bubble.fixedTextSizePx = null - bubble.label = text - val centerX = loc[0] + anchor.width / 2 - val top = loc[1] - bubbleHeight - dp(TAP_GAP_DP) - placeBubble(centerX, top, bubbleWidth, bubbleHeight) - show() - } - - /** - * SWIPE preview (stroke digit swipe-up): pinned to the actual - * anchor key's own on-screen position, same as showTapPreview — - * not to the finger's current height. It used to float a fixed - * distance above the raw touch point instead, which looked right - * for a straight vertical swipe on one key but drifted away from - * the real key as soon as a drag retargeted sideways or across - * rows (the bubble's X snapped to the new key while its Y stayed - * tied to wherever the finger happened to be). - * - * Text size is a fixed constant here, not the tracked key's own - * face text size — the "0" digit's key is the microphone icon key, - * whose own face text is much smaller than every other digit key's - * (10sp vs 17sp, since it's mostly an icon), so sizing off the key - * made "0"'s bubble read noticeably smaller than the other nine. - */ - fun showSwipePreview(text: String, anchor: View) { - val loc = relativeLocation(anchor) - val bubbleWidth = (anchor.width * BUBBLE_WIDTH_RATIO).toInt().coerceAtLeast(dp(40)) - val bubbleHeight = dp(KeyPreviewBubbleView.TOTAL_HEIGHT_DP) - bubble.fixedTextSizePx = dp(SWIPE_TEXT_SIZE_DP).toFloat() - bubble.label = text - val centerX = loc[0] + anchor.width / 2 - // 20dp further above the key than the tap preview's own gap — - // a separate constant so this doesn't also shift - // showTapPreview's gap for the English/number keys. - val top = loc[1] - bubbleHeight - dp(SWIPE_GAP_DP) - placeBubble(centerX, top, bubbleWidth, bubbleHeight) - show() - } - - // No fade animation: a fast tap's down-to-up gap is often shorter - // than any fade would take, so an animated show/hide left the - // bubble stuck mid-fade — either never reaching full opacity - // (looked "too transparent to read") or reversing before it ever - // became visible at all. Popping straight to alpha=1 (matching the - // pre-refactor PopupWindow, which never animated either) - // guarantees the bubble is fully opaque the instant it shows, - // regardless of tap speed. - private fun show() { - bubble.animate().cancel() - bubble.alpha = 1f - bubble.scaleX = 1f - bubble.scaleY = 1f - bubble.visibility = View.VISIBLE - } - - fun hide() { - bubble.animate().cancel() - bubble.visibility = View.GONE - } - - private companion object { - const val BUBBLE_WIDTH_RATIO = 1.2f - const val TAP_GAP_DP = 3 - const val SWIPE_GAP_DP = TAP_GAP_DP + 20 - // Bigger than the default proportional size the tap preview - // falls back to (bodyBottom * 0.5, ~24dp-equivalent here) and, - // being a flat constant rather than derived from any one key's - // own face size, the same for every digit including "0". - const val SWIPE_TEXT_SIZE_DP = 22 - } - } - - private class MidDividerTextView( - context: android.content.Context, - private val dividerColor: Int, - ) : TextView(context) { - private val dividerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { strokeWidth = 1.5f } - - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - dividerPaint.color = dividerColor - val marginX = width * 0.22f - canvas.drawLine(marginX, height / 2f, width - marginX, height / 2f, dividerPaint) - } - } - - private class ActionSymbolView( - context: android.content.Context, - private val symbol: String, - darkTheme: Boolean, - ) : TextView(context) { - private val symbolPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = if (darkTheme) Color.WHITE else Color.rgb(30, 30, 34) - style = Paint.Style.STROKE - strokeCap = Paint.Cap.SQUARE - strokeJoin = Paint.Join.ROUND - } - - override fun onDraw(canvas: Canvas) { - val unit = minOf(width, height).coerceAtLeast(1) / 100f - val centerX = width / 2f - val centerY = height / 2f - symbolPaint.strokeWidth = 5.5f * unit - if (symbol == "←") { - val left = centerX - 27f * unit - val right = centerX + 27f * unit - canvas.drawLine(left + 13f * unit, centerY, right, centerY, symbolPaint) - val arrow = Path().apply { - moveTo(left + 13f * unit, centerY) - lineTo(left + 27f * unit, centerY - 12f * unit) - moveTo(left + 13f * unit, centerY) - lineTo(left + 27f * unit, centerY + 12f * unit) - } - canvas.drawPath(arrow, symbolPaint) - } else { - val path = Path().apply { - moveTo(centerX + 29f * unit, centerY - 14f * unit) - lineTo(centerX + 29f * unit, centerY + 8f * unit) - lineTo(centerX + 21f * unit, centerY + 18f * unit) - lineTo(centerX + 7f * unit, centerY + 18f * unit) - lineTo(centerX - 25f * unit, centerY + 18f * unit) - } - canvas.drawPath(path, symbolPaint) - val arrow = Path().apply { - moveTo(centerX - 25f * unit, centerY + 18f * unit) - lineTo(centerX - 12f * unit, centerY + 8f * unit) - moveTo(centerX - 25f * unit, centerY + 18f * unit) - lineTo(centerX - 12f * unit, centerY + 28f * unit) - } - canvas.drawPath(arrow, symbolPaint) - } - } - } - - /** - * The English keyboard's shift key draws one of three distinct icons so - * its state is visible at a glance: a hollow arrow (lowercase), a solid - * arrow (capitalize the next letter only), or a solid arrow with an - * underline bar (caps lock — every letter is capitalized until toggled - * off again). - */ - private class ShiftKeyView( - context: android.content.Context, - initialState: ShiftState, - private val darkTheme: Boolean, - ) : TextView(context) { - var state: ShiftState = initialState - set(value) { - if (field == value) return - field = value - invalidate() - } - private val mutedColor = if (darkTheme) Color.rgb(190, 190, 190) else Color.rgb(120, 120, 125) - private val activeColor = if (darkTheme) Color.rgb(245, 245, 245) else Color.rgb(30, 30, 34) - private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - strokeJoin = Paint.Join.ROUND - strokeCap = Paint.Cap.ROUND - } - - override fun onDraw(canvas: Canvas) { - val unit = minOf(width, height).coerceAtLeast(1) / 100f - val cx = width / 2f - val cy = height / 2f - 6f * unit - val arrow = Path().apply { - moveTo(cx, cy - 20f * unit) - lineTo(cx + 17f * unit, cy - 2f * unit) - lineTo(cx + 8f * unit, cy - 2f * unit) - lineTo(cx + 8f * unit, cy + 15f * unit) - lineTo(cx - 8f * unit, cy + 15f * unit) - lineTo(cx - 8f * unit, cy - 2f * unit) - lineTo(cx - 17f * unit, cy - 2f * unit) - close() - } - when (state) { - ShiftState.OFF -> { - paint.style = Paint.Style.STROKE - paint.strokeWidth = 3f * unit - paint.color = mutedColor - } - ShiftState.SHIFT_ONCE, ShiftState.CAPS_LOCK -> { - paint.style = Paint.Style.FILL - paint.color = activeColor - } - } - canvas.drawPath(arrow, paint) - if (state == ShiftState.CAPS_LOCK) { - paint.style = Paint.Style.FILL - paint.color = activeColor - canvas.drawRoundRect( - cx - 17f * unit, cy + 22f * unit, cx + 17f * unit, cy + 28f * unit, - 3f * unit, 3f * unit, paint, - ) - } - } - } - - private class MicrophoneKeyView(context: android.content.Context, darkTheme: Boolean) : TextView(context) { - private val microphonePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = if (darkTheme) Color.rgb(190, 190, 190) else Color.rgb(110, 110, 115) - strokeCap = Paint.Cap.ROUND - strokeJoin = Paint.Join.ROUND - style = Paint.Style.FILL - } - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - // Keep the same proportions as VoiceButton, but leave room for the small 0 label. - val unit = minOf(width, height).coerceAtLeast(1) / 160f - val centerX = width / 2f - val centerY = height * 0.56f - val bodyWidth = 11.5f * unit - val bodyTop = centerY - 24f * unit - val bodyBottom = centerY + 20f * unit - canvas.drawRoundRect( - centerX - bodyWidth, - bodyTop, - centerX + bodyWidth, - bodyBottom, - bodyWidth, - bodyWidth, - microphonePaint, - ) - microphonePaint.style = Paint.Style.STROKE - microphonePaint.strokeWidth = 4.5f * unit - val arc = Path().apply { - moveTo(centerX - 19f * unit, centerY + 8f * unit) - cubicTo( - centerX - 18f * unit, centerY + 25f * unit, - centerX - 9f * unit, centerY + 30f * unit, - centerX, centerY + 30f * unit, - ) - cubicTo( - centerX + 9f * unit, centerY + 30f * unit, - centerX + 18f * unit, centerY + 25f * unit, - centerX + 19f * unit, centerY + 8f * unit, - ) - } - canvas.drawPath(arc, microphonePaint) - canvas.drawLine( - centerX, - centerY + 30f * unit, - centerX, - centerY + 39f * unit, - microphonePaint, - ) - microphonePaint.style = Paint.Style.FILL - } - } - - private class VoiceButton(context: android.content.Context, private val darkTheme: Boolean) : View(context) { - private val paint = Paint(Paint.ANTI_ALIAS_FLAG) - // Panel's own dark-theme background is rgb(48,48,48); this reads - // 12/255 lighter (tried 6 — too subtle to tell apart from the panel - // — then 24, which read as too strong; 12 is the settled value). - private val idlePillColor = if (darkTheme) Color.rgb(60, 60, 60) else Color.rgb(225, 225, 228) - private val idleIconColor = if (darkTheme) Color.WHITE else Color.rgb(60, 60, 64) - // Match the raw-mode recording indicator exactly, so the swipe-up - // preview and the resulting raw recording state use one consistent - // orange-yellow accent. - private val swipeArmedPillColor = LINK_COLOR_RECORDING_RAW - // Same idea, for the swipe-left-to-Note gesture's own idle-pill - // preview — see armedForQuickNote/pillArmedAmountGreen below. - private val quickNoteArmedPillColor = LINK_COLOR_QUICK_NOTE - // Same idea again, for the swipe-right-to-Cloud-notes gesture's own - // idle-pill preview — see armedForCloudNote/pillArmedAmountRed below. - private val cloudNoteArmedPillColor = LINK_COLOR_CLOUD_NOTE - // Light red, blended into the waveform bars while a swipe-down-to- - // cancel gesture is past its commit threshold — same value in both - // themes, mirroring swipeArmedPillColor's own choice. - private val cancelArmedWaveformColor = Color.rgb(255, 150, 150) - private val waveformColor = if (darkTheme) Color.rgb(222, 222, 222) else Color.rgb(70, 70, 74) - private val processingDotColors = if (darkTheme) { - intArrayOf( - Color.rgb(245, 245, 245), Color.rgb(205, 205, 205), - Color.rgb(170, 170, 170), Color.rgb(235, 235, 235), - Color.rgb(190, 190, 190), Color.rgb(220, 220, 220), - ) - } else { - intArrayOf( - Color.rgb(40, 40, 40), Color.rgb(90, 90, 90), - Color.rgb(130, 130, 130), Color.rgb(55, 55, 55), - Color.rgb(100, 100, 100), Color.rgb(70, 70, 70), - ) - } - // Per-dot alpha for the thinking ring when an armed mode tints it - // (see armedModeColor()) — the same strong/soft rhythm around the - // ring as processingDotColors' own grays, in one hue. - private val processingDotAlphas = intArrayOf(255, 205, 160, 240, 185, 220) - var isRecording: Boolean = false - set(value) { - field = value - invalidate() - } - var isProcessing: Boolean = false - set(value) { - field = value - invalidate() - } - - var rawModeActive: Boolean = false - set(value) { - field = value - invalidate() - } - - var quickNoteActive: Boolean = false - set(value) { - field = value - invalidate() - } - - var cloudNoteActive: Boolean = false - set(value) { - field = value - invalidate() - } - - var audioLevel: Float = 0f - set(value) { - field = value - invalidate() - } - - // Live "would releasing now enter raw mode?" indicator — the - // setter only starts an ease toward the target (see - // pillArmedAmount below); it doesn't jump straight there, so - // rapid on/off toggling right at the dp(30) threshold doesn't - // flicker instantly between the two colors. - var armedForRawSwipe: Boolean = false - set(value) { - if (field == value) return - field = value - pillArmedAnimator?.cancel() - pillArmedAnimator = android.animation.ValueAnimator.ofFloat(pillArmedAmount, if (value) 1f else 0f).apply { - duration = 120L - addUpdateListener { pillArmedAmount = it.animatedValue as Float } - start() - } - } - private var pillArmedAmount: Float = 0f - set(value) { - field = value - invalidate() - } - private var pillArmedAnimator: android.animation.ValueAnimator? = null - - // Same pattern as armedForRawSwipe/pillArmedAmount above, for the - // swipe-left-to-Note idle-pill preview. - var armedForQuickNote: Boolean = false - set(value) { - if (field == value) return - field = value - pillArmedAnimatorGreen?.cancel() - pillArmedAnimatorGreen = android.animation.ValueAnimator.ofFloat(pillArmedAmountGreen, if (value) 1f else 0f).apply { - duration = 120L - addUpdateListener { pillArmedAmountGreen = it.animatedValue as Float } - start() - } - } - private var pillArmedAmountGreen: Float = 0f - set(value) { - field = value - invalidate() - } - private var pillArmedAnimatorGreen: android.animation.ValueAnimator? = null - - // Same pattern again, for the swipe-right-to-Cloud-notes idle-pill - // preview. - var armedForCloudNote: Boolean = false - set(value) { - if (field == value) return - field = value - pillArmedAnimatorRed?.cancel() - pillArmedAnimatorRed = android.animation.ValueAnimator.ofFloat(pillArmedAmountRed, if (value) 1f else 0f).apply { - duration = 120L - addUpdateListener { pillArmedAmountRed = it.animatedValue as Float } - start() - } - } - private var pillArmedAmountRed: Float = 0f - set(value) { - field = value - invalidate() - } - private var pillArmedAnimatorRed: android.animation.ValueAnimator? = null - - // Same pattern as armedForRawSwipe/pillArmedAmount above, applied - // to the recording waveform instead of the idle capsule — swipe - // DOWN past the threshold while recording tints the waveform bars - // light red instead of the capsule turning green. - var armedForCancel: Boolean = false - set(value) { - if (field == value) return - field = value - waveformCancelAnimator?.cancel() - waveformCancelAnimator = android.animation.ValueAnimator.ofFloat(waveformCancelAmount, if (value) 1f else 0f).apply { - duration = 120L - addUpdateListener { waveformCancelAmount = it.animatedValue as Float } - start() - } - } - private var waveformCancelAmount: Float = 0f - set(value) { - field = value - invalidate() - } - private var waveformCancelAnimator: android.animation.ValueAnimator? = null - - private fun lerpColor(from: Int, to: Int, amount: Float): Int { - val t = amount.coerceIn(0f, 1f) - return Color.rgb( - (Color.red(from) + (Color.red(to) - Color.red(from)) * t).toInt(), - (Color.green(from) + (Color.green(to) - Color.green(from)) * t).toInt(), - (Color.blue(from) + (Color.blue(to) - Color.blue(from)) * t).toInt(), - ) - } - - /** Accent of the armed gesture mode, shared by the recording waveform and the thinking dots so the two never disagree — null for an ordinary dictation. */ - private fun armedModeColor(): Int? = when { - rawModeActive -> LINK_COLOR_RECORDING_RAW - quickNoteActive -> LINK_COLOR_QUICK_NOTE - cloudNoteActive -> LINK_COLOR_CLOUD_NOTE - else -> null - } - - private var phase = 0f - private val animator = object : Runnable { - override fun run() { - phase += 0.18f - invalidate() - postDelayed(this, 50L) - } - } - - override fun onAttachedToWindow() { - super.onAttachedToWindow() - post(animator) - } - - override fun onDetachedFromWindow() { - removeCallbacks(animator) - pillArmedAnimator?.cancel() - pillArmedAnimatorGreen?.cancel() - pillArmedAnimatorRed?.cancel() - waveformCancelAnimator?.cancel() - super.onDetachedFromWindow() - } - - private fun dp(value: Int): Int = - (value * resources.displayMetrics.density).toInt() - - override fun onDraw(canvas: Canvas) { - super.onDraw(canvas) - val centerX = width / 2f - val centerY = height / 2f - val scale = if (isRecording) { - 1f + 0.04f + audioLevel * 0.20f - } else { - 1f - } - val pillWidth = width * 0.86f - val pillHeight = minOf(pillWidth * 192f / 470f, height * 0.90f) - val left = centerX - pillWidth / 2f - val top = centerY - pillHeight * scale / 2f - val right = centerX + pillWidth / 2f - val bottom = centerY + pillHeight * scale / 2f - val radius = pillHeight * 0.5f - // Recording/thinking states show only the animation with the capsule background - // fully removed; the idle state keeps the mic button. - if (!isRecording && !isProcessing) { - val pillColor = lerpColor( - lerpColor( - lerpColor(idlePillColor, swipeArmedPillColor, pillArmedAmount), - quickNoteArmedPillColor, - pillArmedAmountGreen, - ), - cloudNoteArmedPillColor, - pillArmedAmountRed, - ) - paint.color = pillColor - canvas.drawRoundRect(left, top, right, bottom, radius, radius, paint) - } - - paint.color = idleIconColor - paint.strokeWidth = width * 0.025f - paint.strokeCap = Paint.Cap.ROUND - if (!isRecording && !isProcessing) { - // Reference crop: capsule (393,380)-(863,572), 470 x 192. - // All geometry uses that ONE coordinate system and uniform scaling. - canvas.save() - val unit = pillHeight / 192f - canvas.translate(centerX - 235f * unit, centerY - 96f * unit) - canvas.scale(unit, unit) - paint.style = Paint.Style.FILL - canvas.drawRoundRect(213f, 40f, 259f, 113f, 23f, 23f, paint) - paint.style = Paint.Style.STROKE - paint.strokeWidth = 11f - val arc = Path().apply { - moveTo(196f, 96f) - cubicTo(198f, 118f, 215f, 130f, 236f, 130f) - cubicTo(257f, 130f, 274f, 118f, 275f, 96f) - } - canvas.drawPath(arc, paint) - canvas.drawLine(236f, 130f, 236f, 146f, paint) - paint.style = Paint.Style.FILL - canvas.restore() - return - } - if (isRecording) { - // The normal waveform is monochrome; RAW recording uses the - // same orange-yellow accent as the RAW indicator and the - // swipe-up preview. Quiet input stays compact while speech - // expands the bars clearly with the live microphone level. - // Longer bar group (17 vs the original 9) with a genuine - // left-flowing traveling wave — as `phase` advances, the sine - // term's peak visibly drifts from higher to lower bar - // indices, i.e. right to left — layered on top of the same - // bell-shaped envelope (tallest in the middle) as before. - // Gap is derived from bar count so the group always spans the - // same ~86% of the view width regardless of how many bars. - val live = (audioLevel * 1.15f).coerceIn(0f, 1f) - val barCount = 17 - val envelopeCenter = (barCount - 1) / 2f - val gap = width * 0.86f / (barCount - 1) - val startX = centerX - gap * (barCount - 1) / 2f - val rawWaveformColor = armedModeColor() ?: waveformColor - val currentWaveformColor = lerpColor(rawWaveformColor, cancelArmedWaveformColor, waveformCancelAmount) - for (index in 0 until barCount) { - val x = startX + index * gap - val distanceFromCenter = kotlin.math.abs(index - envelopeCenter) / envelopeCenter - val envelope = 1f - distanceFromCenter * distanceFromCenter * 0.75f - val flow = 0.55f + 0.45f * kotlin.math.sin( - (phase * 2.2f + index * 0.9f).toDouble(), - ).toFloat() - val halfHeight = minOf(height * 0.95f, dp(66).toFloat()) * - (0.035f + live * 0.965f) * envelope * flow - paint.color = currentWaveformColor - paint.strokeWidth = dp(3).toFloat() - canvas.drawLine(x, centerY - halfHeight, x, centerY + halfHeight, paint) - } - } else if (isProcessing) { - // Analysis state uses the same restrained monochrome palette - // for an ordinary dictation, and the armed mode's own accent - // (the color its recording waveform just had) otherwise; - // the ring of dots keeps rotating exactly as before, and on - // top of that the whole ring's radius now breathes — growing - // then shrinking together as one — rather than each dot - // sizing itself independently off its own angle. - val accent = armedModeColor() - val colors = processingDotColors - val baseOrbit = minOf(width * 0.28f, height * 0.52f) - val baseDotRadius = minOf(width * 0.055f, height * 0.15f) - val breathe = 0.6f + 0.4f * ((1f + kotlin.math.sin((phase * 0.5f).toDouble()).toFloat()) / 2f) - val orbit = baseOrbit * breathe - val dotRadius = baseDotRadius * breathe - colors.forEachIndexed { index, color -> - val angle = phase * 0.65f + index * (Math.PI.toFloat() / 3f) - val x = centerX + kotlin.math.cos(angle.toDouble()).toFloat() * orbit - val y = centerY + kotlin.math.sin(angle.toDouble()).toFloat() * orbit - paint.color = if (accent == null) { - color - } else { - Color.argb(processingDotAlphas[index], Color.red(accent), Color.green(accent), Color.blue(accent)) - } - canvas.drawCircle(x, y, dotRadius, paint) - } - } - } - } - companion object { private val nextImeRequest = java.util.concurrent.atomic.AtomicLong() const val PREF_KEYBOARD_HEIGHT_DP = "keyboard_height_dp" @@ -6454,30 +3445,6 @@ class OpenLessImeService : InputMethodService(), OpenLessOverlayBridge.OverlaySt // scrolling actually reveals more real options. private const val ENGLISH_CANDIDATE_QUERY_LIMIT = 10 private const val DOUBLE_SPACE_WINDOW_MS = 500L - // buildClipboardView()'s "recent clips" strip. Originally 92dp for - // 4 equal-weight rows + 5 divider lines (dp(1) each), raised ~1.2x - // to 109dp per user request: (92-5)/4=21.75dp/row * 1.2 = 26.1, - // 26.1*4+5=109.4 -> 109. Then reduced from 4 rows to 3 (also per - // user request) WITHOUT changing this total — 3 rows only need 4 - // dividers, not 5, so the freed divider's dp plus the freed row's - // own share both land back on the remaining 3: (109-4)/3=35dp/row, - // up from 26dp. The button grid below needs no matching change — - // it's already LinearLayout.LayoutParams(.., 0, 1f), i.e. "whatever - // space is left after this strip's fixed height," so it grows or - // shrinks on its own the moment this constant or the row count - // changes. - private const val RECENT_CLIPS_COLUMN_HEIGHT_DP = 109 - // Swipe-up symbol hint, any LETTERS-layer row (buildEnglishCharKey()) - // — its own independent TextView pinned to the key's top edge, so - // these are absolute sizes, not a ratio of the 22sp letter below - // it. Small and close to the top by design; tune these two numbers - // directly. Shared by row1's digits and row2/row3's punctuation so - // all three rows read as one consistent hint style. - private const val SWIPE_SYMBOL_HINT_TEXT_SIZE_SP = 11f - private const val SWIPE_SYMBOL_HINT_TOP_PADDING_DP = 2 - // Pure render-time offset (View.translationY), not part of the - // letter TextView's own measured layout — see buildEnglishCharKey(). - private const val LETTER_VERTICAL_NUDGE_DP = 2 // Same hue family as OpenLessOverlayService's OverlayVisualState // (recording/processing), plus a light-green "ready" and an amber // "link issue" that overlay doesn't have. diff --git a/openless-all/android/kotlin/OpenLessKeyboardSettingsActivity.kt b/openless-all/android/kotlin/OpenLessKeyboardSettingsActivity.kt index 821cadd11..54a076b21 100644 --- a/openless-all/android/kotlin/OpenLessKeyboardSettingsActivity.kt +++ b/openless-all/android/kotlin/OpenLessKeyboardSettingsActivity.kt @@ -1054,36 +1054,7 @@ class OpenLessKeyboardSettingsActivity : Activity() { setTextColor(tone(Color.rgb(160, 160, 160), Color.rgb(100, 100, 105))) setPadding(0, dp(6), 0, dp(4)) } - val keysBlock = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - gravity = Gravity.CENTER - setBackgroundColor(tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - setPadding(dp(12), dp(10), dp(12), dp(10)) - // Three fake key rows so stretch is visually obvious. - repeat(3) { rowIndex -> - val row = LinearLayout(this@OpenLessKeyboardSettingsActivity).apply { - orientation = LinearLayout.HORIZONTAL - gravity = Gravity.CENTER - } - repeat(10) { - row.addView( - View(this@OpenLessKeyboardSettingsActivity).apply { - setBackgroundColor(tone(Color.rgb(70, 70, 70), Color.rgb(255, 255, 255))) - }, - LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f).apply { - marginStart = dp(2) - marginEnd = dp(2) - }, - ) - } - addView( - row, - LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f).apply { - if (rowIndex > 0) topMargin = dp(6) - }, - ) - } - } + val keysBlock = ImeKeyboardPreview(this, ImePalette.resolve(isDarkTheme), englishUi) val raiseBlock = FrameLayout(this).apply { setBackgroundColor(tone(Color.rgb(36, 36, 36), Color.rgb(220, 220, 224))) addView( diff --git a/openless-all/android/kotlin/OpenLessOverlayBridge.kt b/openless-all/android/kotlin/OpenLessOverlayBridge.kt index 2b659cdd5..2d568bf2f 100644 --- a/openless-all/android/kotlin/OpenLessOverlayBridge.kt +++ b/openless-all/android/kotlin/OpenLessOverlayBridge.kt @@ -15,14 +15,26 @@ object OpenLessOverlayBridge { interface OverlayStateListener { fun onCapsuleStateChanged(state: String, message: String?, level: Float) + + /** Legacy observers can keep implementing only the original callback. */ + fun onCapsuleStateChangedWithSession(state: String, message: String?, level: Float, sessionId: String?) { + onCapsuleStateChanged(state, message, level) + } } @Keep @JvmStatic fun onCapsuleStateChanged(state: String, message: String?, level: Float) { + onCapsuleStateChangedWithSession(state, message, level, null) + } + + @Keep + @JvmStatic + fun onCapsuleStateChangedWithSession(state: String, message: String?, level: Float, sessionId: String?) { + val identity = sessionId?.takeUnless { it.isBlank() } mainHandler.post { - listener?.onCapsuleStateChanged(state, message, level) - imeListener?.onCapsuleStateChanged(state, message, level) + listener?.onCapsuleStateChangedWithSession(state, message, level, identity) + imeListener?.onCapsuleStateChangedWithSession(state, message, level, identity) } } diff --git a/openless-all/android/kotlin/OpenLessOverlayService.kt b/openless-all/android/kotlin/OpenLessOverlayService.kt index 2b9c184d0..ff62003db 100644 --- a/openless-all/android/kotlin/OpenLessOverlayService.kt +++ b/openless-all/android/kotlin/OpenLessOverlayService.kt @@ -26,6 +26,51 @@ import kotlin.math.abs internal fun shouldIgnoreOverlayRecordingFrame(processing: Boolean, message: String?): Boolean = processing && message.isNullOrBlank() +/** 悬浮球收到全局录音帧时允许执行的自动动作。 */ +internal enum class OverlayRecordingFrameAction { + /** 排队中的电平帧,忽略。 */ + IGNORE, + + /** 非本入口发起的录音:只镜像显示,绝不做麦克风 FGS 提升/失败自动取消/生命周期清理。 */ + MIRROR_ONLY, + + /** 本入口发起的录音:保留原有 FGS 提升与失败取消行为。 */ + PROMOTE_AND_SHOW, +} + +internal fun overlayRecordingFrameAction( + ownsSession: Boolean, + processing: Boolean, + message: String?, +): OverlayRecordingFrameAction = when { + shouldIgnoreOverlayRecordingFrame(processing, message) -> OverlayRecordingFrameAction.IGNORE + !ownsSession -> OverlayRecordingFrameAction.MIRROR_ONLY + else -> OverlayRecordingFrameAction.PROMOTE_AND_SHOW +} + +/** + * 只有本入口发起的录音,自动失败清理才可以取消会话;外部(IME/热键)发起的会话 + * 必须交由对应入口处理,避免悬浮球自动清理误取消别人的听写。 + * + * 注意:这是"启动意图"级别的守卫,不是强 session 归属绑定——NativeStart 是异步的, + * 且桥接回调不带 sessionId,无法在本层验证被抓的到底是不是本次 start 的会话。 + */ +internal fun shouldAutoCancelOwnedSession(ownsSession: Boolean): Boolean = ownsSession + +/** 悬浮球自身"已发起录音"的启动意图状态;终态/取消/失败/手动手势都释放。 */ +internal class OverlaySessionOwnership { + var owned: Boolean = false + private set + + fun markStarted() { + owned = true + } + + fun release() { + owned = false + } +} + /** Foreground service + TYPE_APPLICATION_OVERLAY floating dictation control. */ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateListener { @@ -62,6 +107,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList private var longPressRecording = false private var pendingSwipe: SwipeDirection? = null private var swipeConsumed = false + private val sessionOwnership = OverlaySessionOwnership() private lateinit var iconContainer: FrameLayout private lateinit var iconButton: ImageView @@ -117,6 +163,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList beginDictationFromOverlay() } ACTION_HIDE -> { + sessionOwnership.release() hideOverlay() demoteFromRecordingForeground() stopSelf(startId) @@ -136,6 +183,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList } override fun onDestroy() { + sessionOwnership.release() if (OpenLessOverlayBridge.listener === this) { OpenLessOverlayBridge.listener = null } @@ -159,32 +207,49 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList override fun onCapsuleStateChanged(state: String, message: String?, level: Float) { when (state) { "recording" -> { - // Queued meter frames must not undo a stop/handoff gesture. - if (shouldIgnoreOverlayRecordingFrame(processing, message)) return - recording = true - processing = false - if (!tryPromoteRecordingForeground()) { - try { - OpenLessNative.nativeCancelDictation() - } catch (error: Throwable) { - Log.w(TAG, "cancel dictation bridge unavailable", error) + when (overlayRecordingFrameAction(sessionOwnership.owned, processing, message)) { + OverlayRecordingFrameAction.IGNORE -> return + OverlayRecordingFrameAction.MIRROR_ONLY -> { + // 外部入口(IME/热键)发起的录音:只镜像显示。 + // 不做麦克风 FGS 提升,也不在失败时取消别人的会话。 + recording = true + processing = false + applyVisualState(OverlayVisualState.Recording) + return + } + OverlayRecordingFrameAction.PROMOTE_AND_SHOW -> { + recording = true + processing = false + if (!tryPromoteRecordingForeground()) { + if (shouldAutoCancelOwnedSession(sessionOwnership.owned)) { + try { + OpenLessNative.nativeCancelDictation() + } catch (error: Throwable) { + Log.w(TAG, "cancel dictation bridge unavailable", error) + } + } + sessionOwnership.release() + return + } + applyVisualState(OverlayVisualState.Recording) } - return } - applyVisualState(OverlayVisualState.Recording) } "transcribing", "polishing" -> { + sessionOwnership.release() recording = false processing = true applyVisualState(OverlayVisualState.Processing) } "done" -> { + sessionOwnership.release() recording = false processing = false setArmed(false) } "error" -> { + sessionOwnership.release() recording = false processing = false setArmed(false) @@ -193,6 +258,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList } "cancelled", "idle" -> { + sessionOwnership.release() recording = false processing = false setArmed(false) @@ -683,6 +749,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList if (!recording || gestureAction(direction) != "cancel") { return } + sessionOwnership.release() try { OpenLessNative.nativeCancelDictation() recording = false @@ -711,6 +778,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList private fun finalizeVoiceEditFromOverlay() { if (!recording) return + sessionOwnership.release() try { OpenLessNative.nativeFinalizeVoiceEditFromOverlay() recording = false @@ -726,12 +794,16 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList } private fun abortRecordingStart(startId: Int) { + val owned = sessionOwnership.owned + sessionOwnership.release() recording = false processing = false - try { - OpenLessNative.nativeCancelDictation() - } catch (error: Throwable) { - Log.w(TAG, "cancel dictation after foreground failure", error) + if (shouldAutoCancelOwnedSession(owned)) { + try { + OpenLessNative.nativeCancelDictation() + } catch (error: Throwable) { + Log.w(TAG, "cancel dictation after foreground failure", error) + } } stopSelf(startId) } @@ -743,11 +815,13 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList } else { OpenLessNative.nativeStartDictation() } + sessionOwnership.markStarted() recording = true processing = false setArmed(false) applyVisualState(OverlayVisualState.Recording) } catch (error: Throwable) { + sessionOwnership.release() Log.w(TAG, "start dictation bridge unavailable", error) // recording was never set true on this path (the native start // call itself threw), so the `recording` setter's own @@ -775,6 +849,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList } private fun stopRecordingFromOverlay(translation: Boolean = false) { + sessionOwnership.release() try { recording = false processing = true @@ -803,6 +878,7 @@ class OpenLessOverlayService : Service(), OpenLessOverlayBridge.OverlayStateList } private fun stopQuickNoteFromOverlay() { + sessionOwnership.release() try { recording = false processing = true diff --git a/openless-all/android/kotlin/OpenLessRime.kt b/openless-all/android/kotlin/OpenLessRime.kt index 89d05b350..6306e2c36 100644 --- a/openless-all/android/kotlin/OpenLessRime.kt +++ b/openless-all/android/kotlin/OpenLessRime.kt @@ -6,6 +6,10 @@ import java.io.File internal object OpenLessRime { init { System.loadLibrary("openless_rime") } + @Volatile var isReady = false + private set + @Volatile var lastInitError: String? = null + private set private var initialized = false private val dictionaryWorker = java.util.concurrent.Executors.newSingleThreadExecutor() private var nextDictionaryCheck = 0L @@ -13,6 +17,20 @@ internal object OpenLessRime { @Volatile var sessionGeneration = 0L private set external fun nativeRequest(operation: String, session: String, argument: String): String + + /** Pre-warms Rime off the main thread so the first Chinese keystroke does not stall. */ + fun preloadAsync(context: Context) { + if (isReady) return + val appContext = context.applicationContext + RimeTaskQueue.executor.execute { + runCatching { initialize(appContext) } + .onFailure { error -> + lastInitError = error.message ?: error.javaClass.simpleName + android.util.Log.e("OpenLessRime", "preload failed: ${error.message}", error) + } + } + } + @Synchronized fun initialize(context: Context) { if (initialized) { refreshPublicDictionary(context); return } // Rime replaced LitePinyin; its stores are no longer read or backed up. @@ -20,6 +38,7 @@ internal object OpenLessRime { val shared = File(context.filesDir, "rime-shared-1.17.0-ice-da1fbe60-v1").apply { mkdirs() } val files = context.assets.list("rime") ?: error("Rime assets unavailable") require(files.isNotEmpty()) + var maxSourceMtime = 0L for (name in files) { require(!name.contains('/') && !name.contains("..")) val target = File(shared, name) @@ -28,27 +47,75 @@ internal object OpenLessRime { context.assets.open("rime/$name").use { input -> temporary.outputStream().use { input.copyTo(it) } } check(temporary.renameTo(target)) } + if (target.lastModified() > maxSourceMtime) maxSourceMtime = target.lastModified() } var selected = runCatching { JSONObject(OpenLessNative.nativePublicDictionary(shared.absolutePath, "select")).optString("data_path", shared.absolutePath) } .getOrDefault(shared.absolutePath) - val profile = File(context.filesDir, "rime-user").absolutePath + val profileDir = File(context.filesDir, "rime-user").apply { mkdirs() } + val profile = profileDir.absolutePath + seedPrebuiltArtifacts(context, profileDir, selected == shared.absolutePath, maxSourceMtime) var ready = false - repeat(3) { - if (!ready) { - if (selected != shared.absolutePath && !selected.startsWith(shared.absolutePath + "/public-updates-v1/")) selected = shared.absolutePath - try { request("initialize", selected, profile); ready = true } - catch (error: Exception) { - if (selected == shared.absolutePath) throw error - selected = if (it == 1) shared.absolutePath else runCatching { - JSONObject(OpenLessNative.nativePublicDictionary(shared.absolutePath, "reject")).optString("data_path", shared.absolutePath) - }.getOrDefault(shared.absolutePath) + try { + repeat(3) { + if (!ready) { + if (selected != shared.absolutePath && !selected.startsWith(shared.absolutePath + "/public-updates-v1/")) selected = shared.absolutePath + try { request("initialize", selected, profile); ready = true } + catch (error: Exception) { + if (selected == shared.absolutePath) throw error + selected = if (it == 1) shared.absolutePath else runCatching { + JSONObject(OpenLessNative.nativePublicDictionary(shared.absolutePath, "reject")).optString("data_path", shared.absolutePath) + }.getOrDefault(shared.absolutePath) + } } } + check(ready) + initialized = true + isReady = true + lastInitError = null + } catch (error: Throwable) { + lastInitError = error.message ?: error.javaClass.simpleName + throw error } - check(ready) - initialized = true refreshPublicDictionary(context) } + + /** + * Copies host-precompiled Rime binary tables into rime-user/build on first install + * (or data-version change) so librime skips 30–90s of on-device YAML compilation. + */ + private fun seedPrebuiltArtifacts( + context: Context, + profileDir: File, + usingBundledData: Boolean, + maxSourceMtime: Long, + ) { + if (!usingBundledData) return + val prebuilt = runCatching { context.assets.list("rime-prebuilt") }.getOrNull() + if (prebuilt.isNullOrEmpty()) return + val buildDir = File(profileDir, "build").apply { mkdirs() } + val stamp = File(buildDir, ".openless-prebuilt-stamp") + val version = "rime-1.17.0-ice-da1fbe60-v1" + if (stamp.exists() && runCatching { stamp.readText().trim() }.getOrNull() == version) return + val hasCustomPatch = File(profileDir, "openless_pinyin_learning.custom.yaml").exists() || + File(profileDir, "openless_pinyin_private.custom.yaml").exists() + val freshMtime = maxOf(System.currentTimeMillis(), maxSourceMtime + 2000L) + runCatching { + for (name in prebuilt) { + if (name.contains('/') || name.contains("..")) continue + if (hasCustomPatch && name.endsWith(".schema.yaml")) continue + val target = File(buildDir, name) + val temporary = File(buildDir, "$name.tmp") + context.assets.open("rime-prebuilt/$name").use { input -> + temporary.outputStream().use { input.copyTo(it) } + } + check(temporary.renameTo(target)) + target.setLastModified(freshMtime) + } + stamp.writeText(version) + }.onFailure { error -> + android.util.Log.w("OpenLessRime", "prebuilt seed skipped: ${error.message}") + } + } private fun refreshPublicDictionary(context: Context) { if (!context.getSharedPreferences("openless_ime_ui", Context.MODE_PRIVATE).getBoolean("public_dictionary_updates", true)) return val now = System.currentTimeMillis() diff --git a/openless-all/android/kotlin/RimePinyinController.kt b/openless-all/android/kotlin/RimePinyinController.kt index 5361518cb..6e3f686a8 100644 --- a/openless-all/android/kotlin/RimePinyinController.kt +++ b/openless-all/android/kotlin/RimePinyinController.kt @@ -19,6 +19,8 @@ internal class RimePinyinController(context: Context) { @Volatile private var requestId = 0L @Volatile private var learning = false @Volatile private var encoding = "" + @Volatile private var preeditText = "" + @Volatile private var statusHint: String? = null @Volatile private var candidates: List = emptyList() @Volatile private var cloudChoices: Set = emptySet() @Volatile private var candidateRevision = 0L @@ -27,12 +29,17 @@ internal class RimePinyinController(context: Context) { private var pending = "" private var pendingLiteral = "" private var commit: (String) -> Boolean = { false } + private var onCommitted: ((String) -> Unit)? = null private val confirmedText = StringBuilder() val associationLearning = TypedContinuationHistory() private var associationEpoch = 0L fun bindCommit(handler: (String) -> Boolean) { commit = handler } + fun bindAfterCommit(handler: (String) -> Unit) { onCommitted = handler } fun currentEncoding(): String = encoding + fun currentPreedit(): String = preeditText.ifEmpty { encoding } + fun statusHint(): String? = statusHint fun isEmpty(): Boolean = encoding.isEmpty() + fun preload() { OpenLessRime.preloadAsync(context) } fun setLearningAllowed(allowed: Boolean) { learning = allowed; clear(); resetAssociationContext() } fun refresh(update: (List) -> Unit) { submit("state", "", update) } private fun deliver(text: String, epoch: Long): Boolean = onEditor(epoch) { commit(text) } @@ -55,6 +62,12 @@ internal class RimePinyinController(context: Context) { private fun submit(operation: String, argument: String, update: (List) -> Unit, emptyAction: (() -> Unit)? = null) { val epoch = generation val revision = ++requestId + if (!OpenLessRime.isReady && operation != "state") { + statusHint = "词库初始化中…" + main.post { + if (epoch == generation && revision == requestId && !OpenLessRime.isReady) update(candidates) + } + } worker.execute { try { if (epoch != generation) return@execute @@ -69,8 +82,10 @@ internal class RimePinyinController(context: Context) { sessionGeneration = OpenLessRime.sessionGeneration session = OpenLessRime.request("create", "", if (learning) "learning" else "private").getString("session") } + var committedNow: String? = null if (pending.isNotEmpty()) { check(deliver(pending, epoch)) { "Editor write failed" } + committedNow = pending OpenLessRime.request("ack", session); pending = "" } if (pendingLiteral.isNotEmpty()) { @@ -84,24 +99,29 @@ internal class RimePinyinController(context: Context) { val nativeOperation = when (operation) { "backspace", "space", "confirmFirst" -> if (composing) "key" else "state" "literal" -> if (argument == "'" && composing) "key" else "confirm" + "commitRaw" -> if (composing) "clear" else "state" else -> operation } + val rawBeforeClear = if (operation == "commitRaw" && composing) state.optString("input") else "" val nativeArgument = when (operation) { "backspace" -> "65288" "space", "confirmFirst" -> "32" "literal" -> if (argument == "'" && composing) "39" else argument + "commitRaw" -> "" else -> argument } - if (!composing && operation in listOf("backspace", "space", "confirmFirst")) { + if (!composing && operation in listOf("backspace", "space", "confirmFirst", "commitRaw")) { if (operation == "space") check(deliver(" ", epoch)) { "Editor write failed" } else check(onEditor(epoch) { emptyAction?.invoke(); true }) { "Editor unavailable" } } else { state = OpenLessRime.request(nativeOperation, session, nativeArgument) } if (operation == "literal" && nativeOperation == "confirm") pendingLiteral = argument + if (rawBeforeClear.isNotEmpty()) pendingLiteral = rawBeforeClear pending = state.optString("commit") if (pending.isNotEmpty()) { check(deliver(pending, epoch)) { "Editor write failed" } + committedNow = pending state = OpenLessRime.request("ack", session); pending = "" } if (pendingLiteral.isNotEmpty()) { @@ -111,34 +131,50 @@ internal class RimePinyinController(context: Context) { if (epoch != generation || revision != requestId) return@execute state = OpenLessRime.request("candidates", session) val input = state.optString("input") + val preedit = state.optString("preedit").ifEmpty { input } val rows = state.optJSONArray("candidates") val result = if (rows == null) emptyList() else (0 until rows.length()).map { rows.getString(it) } + val committedForHook = committedNow main.post { if (epoch != generation || revision != requestId) return@post - encoding = input; candidates = result; cloudChoices = emptySet() + statusHint = null + encoding = input; preeditText = preedit; candidates = result; cloudChoices = emptySet() candidateRevision = state.optLong("revision"); update(result) + if (committedForHook != null && input.isEmpty()) onCommitted?.invoke(committedForHook) scheduleCloud(input, result, epoch, revision, update) } } catch (error: Throwable) { - Log.e("OpenLessRime", "engine request failed: ${error.javaClass.simpleName}") + Log.e("OpenLessRime", "engine request failed: ${error.javaClass.simpleName}: ${error.message}", error) // Retain the native composition on a rejected stale selection or // failed editor write, rather than presenting an empty candidate bar. - runCatching { + val recovered = runCatching { val state = OpenLessRime.request("candidates", session) val rows = state.getJSONArray("candidates") val result = (0 until rows.length()).map { rows.getString(it) } + val input = state.optString("input") + val preedit = state.optString("preedit").ifEmpty { input } main.post { if (epoch == generation && revision == requestId) { - encoding = state.optString("input"); candidates = result + statusHint = null + encoding = input; preeditText = preedit; candidates = result candidateRevision = state.optLong("revision"); update(result) } } } + if (recovered.isFailure) { + val reason = error.message ?: error.javaClass.simpleName + main.post { + if (epoch == generation && revision == requestId) { + statusHint = "拼音引擎异常:$reason" + update(emptyList()) + } + } + } } } } fun appendLetter(letter: Char, update: (List) -> Unit) { - submit("key", letter.lowercaseChar().code.toString(), update) + submit("key", letter.code.toString(), update) } fun backspace(update: (List) -> Unit, deleteFromEditor: () -> Unit) { submit("backspace", "", update, deleteFromEditor) @@ -151,13 +187,45 @@ internal class RimePinyinController(context: Context) { val index = candidates.indexOf(text) if (index >= 0) submit("select_absolute", "$index@$candidateRevision", update) } + fun deleteCandidate(text: String, update: (List) -> Unit, onResult: (Boolean) -> Unit = {}) { + if (cloudChoices.contains(text)) { onResult(false); return } + val index = candidates.indexOf(text) + if (index < 0) { onResult(false); return } + val epoch = generation + val revision = ++requestId + val targetRev = candidateRevision + worker.execute { + val deleted = runCatching { + if (epoch != generation || session.isEmpty()) return@runCatching false + OpenLessRime.request("delete_candidate", session, "$index@$targetRev") + true + }.getOrDefault(false) + if (epoch != generation || revision != requestId) return@execute + val refreshed = runCatching { OpenLessRime.request("candidates", session) }.getOrNull() + main.post { + if (epoch != generation || revision != requestId) return@post + if (refreshed != null) { + val input = refreshed.optString("input") + val preedit = refreshed.optString("preedit").ifEmpty { input } + val rows = refreshed.optJSONArray("candidates") + val result = if (rows == null) emptyList() else (0 until rows.length()).map { rows.getString(it) } + encoding = input; preeditText = preedit; candidates = result + candidateRevision = refreshed.optLong("revision"); update(result) + } + onResult(deleted) + } + } + } fun space(update: (List) -> Unit) { submit("space", "", update) } fun confirmFirst(update: (List) -> Unit, emptyAction: () -> Unit) { submit("confirmFirst", "", update, emptyAction) } + fun commitRawInput(update: (List) -> Unit, emptyAction: () -> Unit) { + submit("commitRaw", "", update, emptyAction) + } fun insertLiteral(text: String, update: (List) -> Unit) { submit("literal", text, update) } fun clear() { - generation++; requestId++; encoding = ""; candidates = emptyList(); cloudChoices = emptySet() + generation++; requestId++; encoding = ""; preeditText = ""; candidates = emptyList(); cloudChoices = emptySet() worker.execute { try { if (session.isNotEmpty()) OpenLessRime.request("destroy", session) } catch (_: Throwable) {} finally { session = ""; pending = ""; pendingLiteral = "" } diff --git a/openless-all/android/kotlin/StrokeInputController.kt b/openless-all/android/kotlin/StrokeInputController.kt index c64955068..a799ab0cc 100644 --- a/openless-all/android/kotlin/StrokeInputController.kt +++ b/openless-all/android/kotlin/StrokeInputController.kt @@ -1,32 +1,8 @@ package com.openless.app -import android.graphics.Color -import android.graphics.drawable.GradientDrawable -import android.view.Gravity import android.view.View -import android.view.ViewGroup -import android.widget.LinearLayout -import android.widget.TextView -/** - * Everything specific to the 笔画 (stroke) input panel — encode entry, the - * 字候选/联想候选 query+render+commit pipeline, and the number/symbol sub-panel - * — split out of OpenLessImeService.kt, which otherwise hosted every panel's - * build/query/render/commit logic in one class; this alone was a large, - * mostly self-contained chunk of it (see the "OpenLessImeService.kt 拆分" - * item this was pulled out of). - * - * Shared machinery — candidateItemView()/styleCandidateFirstState() - * (English's own candidate row uses these too), showCandidateOverlay()/ - * candidateOverlayEntries, keyboardKey(), theme/layout helpers, and - * InputConnection access — stays on [service] and is called back into - * explicitly rather than duplicated here. This class owns exactly the - * stroke-specific state the two old inline reset blocks - * (selectInputMode()/onStartInput()) used to touch — see - * resetForModeSwitch()/resetForNewInputSession(), which preserve each call - * site's own exact field list rather than merging them into one generic - * reset. - */ +/** Stroke engine/session adapter. UI components do not own input or learning. */ internal class StrokeInputController(private val service: OpenLessImeService) { private val strokeRepository by lazy { StrokeInputRepository(service) } // internal, not private: Pinyin mode's own post-commit association @@ -43,9 +19,9 @@ internal class StrokeInputController(private val service: OpenLessImeService) { private var confirmedText = "" private val associationLearning = TypedContinuationHistory() private var phraseQueryEpoch = 0L - private var strokePreview: TextView? = null - private var clearStrokeButton: TextView? = null - private var strokeCandidates: LinearLayout? = null + private var panel: ImeStrokePanel? = null + private var candidateEntries = emptyList() + private var inputGeneration = 0L // Read by OpenLessImeService's own panel dispatcher (onCreateInputView()) // to choose between buildStrokeView()/buildStrokeNumberView() — the only @@ -78,8 +54,13 @@ internal class StrokeInputController(private val service: OpenLessImeService) { phraseRepository.shutdown() } - /** Matches selectInputMode()'s own old inline reset exactly — mode-switch also resets the number/symbol sub-panel and the punctuation rail's page, which resetForNewInputSession() below does not. */ + /** Explicit mode switches discard pending composition, never carrying segments into a later mode. */ fun resetForModeSwitch() { + ++inputGeneration + panel?.cancelInteractions() + candidateEntries = emptyList() + wordSegments.clear() + lastStrokeCandidates = emptyList() associationLearning.reset() strokeNumberMode = false numberSymbolMode = false @@ -93,6 +74,8 @@ internal class StrokeInputController(private val service: OpenLessImeService) { /** Matches onStartInput()'s own old inline reset exactly — a fresh input session also drops any in-progress word segments/candidates, but leaves the punctuation rail's page alone. */ fun resetForNewInputSession() { + ++inputGeneration + panel?.cancelInteractions() associationLearning.reset() strokeNumberMode = false numberSymbolMode = false @@ -103,10 +86,8 @@ internal class StrokeInputController(private val service: OpenLessImeService) { strokeQueryEpoch++ wordSegments.clear() lastStrokeCandidates = emptyList() - // The panel isn't rebuilt for a new session, so the views still show the old field's code and candidates. - strokePreview?.text = "" - strokeCandidates?.removeAllViews() - updateClearStrokeButtonVisibility() + candidateEntries = emptyList() + refreshPanel() } /** @@ -126,337 +107,88 @@ internal class StrokeInputController(private val service: OpenLessImeService) { } } - fun buildStrokeView(): View { - // Matches the punctuation rail's own 0.16f width share below (body's - // "0.16f/0.65f/0.19f" split) so a downward drag anywhere on the rail - // is excluded from swipe-to-dismiss and left entirely to SwipeRail. - val root = OpenLessImeService.SwipeModeContainer(service, verticalDismissExclusionRatio = 0.16f) { direction -> service.swipeInputMode(direction) }.apply { - orientation = LinearLayout.VERTICAL - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.keyboardPanelHeightPx()) - minimumHeight = service.keyboardPanelHeightPx() - setPadding(service.dp(4), service.dp(3), service.dp(4), service.dp(3)) - setBackgroundColor(service.tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - } - val header = LinearLayout(service).apply { gravity = Gravity.CENTER_VERTICAL } - header.addView(service.buildBrandView(), LinearLayout.LayoutParams(0, service.dp(38), 1f)) - header.addView(service.buildModeToggle(), LinearLayout.LayoutParams(service.dp(240), service.dp(38))) - // Stroke mode's root padding is much tighter (4dp/3dp) to fit its dense - // grid. Compensate with margins so the header/toggle still land at the - // same canonical 16dp/8dp inset as every other panel. - root.addView(header, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.dp(38)).apply { - marginStart = service.dp(12) - marginEnd = service.dp(12) - topMargin = service.dp(5) - }) - - // Stroke mode follows the reference layout: a compact stroke row, - // candidate row, punctuation column, stroke grid, and action rail. - // Encode + candidate rows are fixed-height (24dp + 36dp = 60dp, same - // total as before this pass) and never resize with content — only - // the candidate list scrolls horizontally — so the stroke keys below - // never move. Both rows share one rounded background (an existing - // panel color, not a new one) so they read as a single continuous - // strip rather than two separate cards. - val top = LinearLayout(service).apply { - orientation = LinearLayout.VERTICAL - background = service.buildEncodeAreaBackground() - } - val strokeRow = LinearLayout(service).apply { gravity = Gravity.CENTER_VERTICAL } - strokePreview = TextView(service).apply { - text = "" - textSize = 16.5f - setTextColor(service.strokeEncodeAccentColor) - gravity = Gravity.CENTER_VERTICAL - setSingleLine(true) - setPadding(service.dp(10), 0, 0, 0) - } - strokeRow.addView(strokePreview, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f)) - // Clear-code button: a 40x30dp hit target with a small glyph, not a - // heavy independent button — tapping it is the same clearStrokes() - // already wired to the action rail's "清除" key. - clearStrokeButton = TextView(service).apply { - text = "✕" - textSize = 13f - gravity = Gravity.CENTER - setTextColor(service.tone(Color.rgb(150, 150, 150), Color.rgb(130, 130, 135))) - contentDescription = service.ui("清除笔画编码", "Clear stroke code") - setOnClickListener { clearStrokes() } - } - strokeRow.addView(clearStrokeButton, LinearLayout.LayoutParams(service.dp(40), ViewGroup.LayoutParams.MATCH_PARENT)) - updateClearStrokeButtonVisibility() - top.addView(strokeRow, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.dp(24))) - - val candidateRow = LinearLayout(service).apply { gravity = Gravity.CENTER_VERTICAL } - // A plain setOnTouchListener on the ScrollView never actually fires - // here: each candidate is its own clickable keyboardKey() view, so - // it claims ACTION_DOWN before the ScrollView's own onTouchEvent - // ever runs. Overriding onInterceptTouchEvent instead runs at the - // right point in the dispatch chain — before any child gets a - // chance to claim the touch — so it reliably blocks - // SwipeModeContainer's mode-switch gesture from stealing a drag - // that starts on top of a candidate button. - val candidatesScroll = object : android.widget.HorizontalScrollView(service) { - override fun onInterceptTouchEvent(ev: android.view.MotionEvent): Boolean { - if (ev.actionMasked == android.view.MotionEvent.ACTION_DOWN) { - parent?.requestDisallowInterceptTouchEvent(true) + fun buildStrokeView(): View = buildPanel() + fun buildStrokeNumberView(): View = buildPanel() + + private fun buildPanel(): View { + panel?.cancelInteractions() + return ImeStrokePanel( + service, service.keyboardPalette(), service.buildKeyboardHeader(), service.isEnglishKeyboardUi(), + onCommand = ::handleCommand, + onText = { text -> if (isCurrentPanel()) commitDirect(text) }, + onPunctuationPage = { step -> + if (isCurrentPanel()) { + punctuationGroupIndex = (punctuationGroupIndex + step).mod(punctuationGroups.size) + refreshPanel() } - return super.onInterceptTouchEvent(ev) - } - }.apply { - isHorizontalScrollBarEnabled = false - isFillViewport = false - overScrollMode = View.OVER_SCROLL_NEVER - strokeCandidates = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL } - strokeCandidates?.orientation = LinearLayout.HORIZONTAL - addView(strokeCandidates, ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)) - } - candidateRow.addView(candidatesScroll, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f)) - // "Show more" — opens the full candidate/association list in a - // floating overlay instead of growing this row or the panel height. - val expandCandidatesButton = OpenLessImeService.StrokeActionView( - service, - "triangle-down", - iconColor = service.tone(Color.rgb(180, 180, 180), Color.rgb(130, 130, 135)), - ).apply { - contentDescription = service.ui("展开更多候选", "Show more candidates") + }, + onFeedback = service::emitKeyFeedback, + interactionPolicy = service.interactionPolicy(), + ).also { + panel = it + refreshPanel() + if (strokeCode.isNotEmpty()) refreshStrokeCandidates(strokeCode) } - expandCandidatesButton.visibility = View.GONE - expandCandidatesButton.setOnClickListener { service.showCandidateOverlay(expandCandidatesButton) } - candidateRow.addView(expandCandidatesButton, LinearLayout.LayoutParams(service.dp(28), ViewGroup.LayoutParams.MATCH_PARENT)) - // Only shown once the candidates actually overflow the visible - // scroll width — otherwise it sat there whether or not there was - // anything more to show, which read as an odd stray control. - // renderCandidateRow()/refreshAssociations() both just repopulate - // strokeCandidates and let layout happen, so a global layout - // listener (fires after every layout pass, including the one - // triggered by add/removeAllViews) is what re-checks this instead - // of hooking every candidate-population call site individually. - candidatesScroll.viewTreeObserver.addOnGlobalLayoutListener { - val candidates = strokeCandidates - expandCandidatesButton.visibility = - if (candidates != null && candidates.width > candidatesScroll.width) View.VISIBLE else View.GONE - } - top.addView(candidateRow, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.dp(36))) - root.addView(top, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.dp(60))) - - val body = LinearLayout(service).apply { gravity = Gravity.CENTER } - // Swiping the rail up/down cycles through punctuationGroups instead of - // scrolling — one swipe always advances exactly one group. - val punctuation = OpenLessImeService.SwipeRail(service) { direction -> - val count = punctuationGroups.size - punctuationGroupIndex = ((punctuationGroupIndex + direction) % count + count) % count - service.refreshInputView() - }.apply { - orientation = LinearLayout.VERTICAL - gravity = Gravity.CENTER - // Zero vertical padding so the rail's own top/bottom edges land - // exactly on the grid/actions columns' top/bottom edges (all - // three share the same MATCH_PARENT body height) — horizontal - // padding is kept since it only insets key width, not row - // position. - setPadding(service.dp(2), 0, service.dp(2), 0) - background = service.roundedButton(service.tone(Color.rgb(45, 45, 45), Color.rgb(230, 230, 234)), service.dp(4)) - } - punctuationGroups[punctuationGroupIndex].forEachIndexed { index, mark -> - punctuation.addView(service.keyboardKey(mark, 1f, action = { commitDirect(mark) }).apply { - textSize = 18f - // The rail is one connected key surface; separators provide the only visual split. - background = GradientDrawable().apply { setColor(Color.TRANSPARENT) } - layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f) - }) - if (index < 4) { - punctuation.addView(View(service).apply { - setBackgroundColor(service.tone(Color.rgb(28, 28, 28), Color.rgb(205, 205, 210))) - }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.dp(1))) - } - } - // Match the reference proportions: both side rails occupy the same share of the panel. - body.addView(punctuation, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.16f)) + } - val grid = LinearLayout(service).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER } - val strokeRows = listOf( - listOf("1\n一" to "h", "2\n丨" to "s", "3\n丿" to "p"), - listOf("4\n丶" to "n", "5\n乙" to "z", "6\n通配" to "*"), - listOf("7\n分词" to " ", "8\n:" to ":", "9\n;" to ";"), - listOf("繁" to "script", "🎙" to "voice", "符号" to "symbols"), + private fun isCurrentPanel(): Boolean = + service.inputMode == OpenLessImeService.InputMode.STROKE && service.isInputViewShown && !service.isKeyboardEditingBlocked() + + fun cancelInteractions() { panel?.cancelInteractions() } + fun applyInteractionPolicy(policy: ImeInteractionPolicy) { panel?.applyInteractionPolicy(policy) } + fun setInteractionBlocked(blocked: Boolean) { panel?.setBlocked(blocked) } + + fun refreshPanel(): Boolean { + val current = panel ?: return false + val preview = android.text.TextUtils.concat(wordSegments.joinToString(""), service.displayStrokeCode(strokeCode)) + current.render( + preview, service.traditionalOutput, strokeNumberMode, numberSymbolMode, + symbolPageIndex, numberPanelSymbolPages.size, + numberPanelSymbolPages[symbolPageIndex.coerceIn(numberPanelSymbolPages.indices)], + punctuationGroups[punctuationGroupIndex], ) - strokeRows.forEach { rowItems -> - val row = LinearLayout(service).apply { gravity = Gravity.CENTER } - rowItems.forEach { (label, code) -> - val key = if (code == "script") service.keyboardKey(label, 1f, action = { - service.toggleScriptPreference() - }, graphicCode = "script").apply { - if (service.traditionalOutput) { - background = service.roundedButton(service.tone(Color.rgb(112, 78, 92), Color.rgb(232, 205, 213)), service.dp(5)) - } - } else if (code == "voice") service.keyboardKey("0", 1f, action = { - commitDirect(" ") - }, swipeUpAction = { - commitDirect("0") - }, swipePreview = "0", microphoneIcon = true, longPressDelayMs = 900L, longPressAction = { - service.inputMode = OpenLessImeService.InputMode.VOICE - service.saveInputMode(service.inputMode) - clearStrokes() - service.refreshInputView() - if (!service.recording) service.toggleDictation() - }) else { - val swipeDigit = label.substringBefore("\n").takeIf { it.length == 1 && it[0].isDigit() } - service.keyboardKey(label, 1f, action = { - when (code) { - "symbols" -> { - strokeNumberMode = true - numberSymbolMode = true - symbolPageIndex = 0 - service.refreshInputView() - } - " " -> segmentStroke() - else -> if (code in listOf("h", "s", "p", "n", "z", "*")) appendStroke(code) else commitDirect(code) - } - }, swipeUpAction = swipeDigit?.let { digit -> - { commitDirect(digit) } - }, swipePreview = swipeDigit, strokeIconCode = code.takeIf { - it in listOf("h", "s", "p", "n", "z") - }, graphicCode = code.takeIf { - it in listOf("*", ":", ";", " ", "symbols") - }) - } - key.textSize = if (code == "voice") 10f else 17f - // dp(1) on every side gives a uniform ~2dp gap both ways - // (keys stay clearly separated) and puts as much of the - // reclaimed margin as possible into visible key size, not - // new padding. The action rail's vertical margin is kept at - // the same dp(1)/dp(1) below so row top/bottom edges still - // land exactly together across both columns. - key.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f).apply { - setMargins(service.dp(1), service.dp(1), service.dp(1), service.dp(1)) - } - row.addView(key) + val generation = inputGeneration + current.submitCandidates(candidateEntries.map { entry -> + ImeStrokePanel.Candidate(entry.label) { + if (generation == inputGeneration && isCurrentPanel()) entry.action() } - grid.addView(row, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - } - body.addView(grid, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.65f)) - - val actions = LinearLayout(service).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER } - listOf("←" to { deleteStroke() }, "↵" to { abandonComposition(); service.sendEnterKey() }, "清除" to { clearStrokes() }, "123" to { - strokeNumberMode = true - numberSymbolMode = false - symbolPageIndex = 0 - service.refreshInputView() - }).forEach { (label, action) -> - actions.addView(service.keyboardKey(label, 1f, action, repeatOnLongPress = label == "←", repeatAction = action, - graphicActionCode = label).apply { - textSize = if (label == "←" || label == "↵") 30f else 17f - // Vertical margin matches the grid keys' dp(1)/dp(1) exactly - // so every row's top/bottom edge lines up across both - // columns; horizontal margin is independent (single column). - layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f).apply { - setMargins(service.dp(1), service.dp(1), service.dp(1), service.dp(1)) - } - background = service.roundedButton(Color.rgb(153, 26, 40), service.dp(5)) - }) - } - body.addView(actions, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.19f)) - root.addView(body, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - // Rebuilds caused by switching back from the numeric panel must restore - // both the visible code and its candidates from the retained buffer. - if (strokeCode.isNotEmpty()) { - strokePreview?.text = service.displayStrokeCode(strokeCode) - refreshStrokeCandidates(strokeCode) - } - return root - } - - fun buildStrokeNumberView(): View { - service.refreshLanguage() - val root = OpenLessImeService.SwipeModeContainer(service) { direction -> service.swipeInputMode(direction) }.apply { - orientation = LinearLayout.VERTICAL - layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.keyboardPanelHeightPx()) - minimumHeight = service.keyboardPanelHeightPx() - setPadding(service.dp(8), service.dp(8), service.dp(8), service.dp(8)) - setBackgroundColor(service.tone(Color.rgb(48, 48, 48), Color.rgb(242, 242, 246))) - } - val header = LinearLayout(service).apply { gravity = Gravity.CENTER_VERTICAL } - header.addView(service.buildBrandView().apply { setPadding(service.dp(8), 0, 0, 0) }, LinearLayout.LayoutParams(0, service.dp(38), 1f)) - header.addView(service.buildModeToggle(), LinearLayout.LayoutParams(service.dp(240), service.dp(38))) - // This panel's own root padding (8dp) is narrower than the voice panel's - // (16dp). Compensate with margins so the header/toggle still land at the - // same canonical 16dp/8dp inset as every other panel. - root.addView(header, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, service.dp(38)).apply { - marginStart = service.dp(8) - marginEnd = service.dp(8) }) + current.setBlocked(service.isKeyboardEditingBlocked()) + return true + } - // Backspace/Enter/Voice/Return/Symbols stay in Chinese regardless of UI - // language: they're functional keys on the number/symbol panel, not - // content the user is composing. - val rows = if (numberSymbolMode) { - val page = numberPanelSymbolPages[symbolPageIndex.coerceIn(numberPanelSymbolPages.indices)] - listOf( - page.subList(0, 4) + "退格", - page.subList(4, 8) + "回车", - page.subList(8, 12) + "语音", - listOf("▲", "${symbolPageIndex + 1}/${numberPanelSymbolPages.size}", "▼", "数字", "返回"), - ) - } else { - listOf( - listOf("@", "1", "2", "3", "退格"), - listOf(":", "4", "5", "6", "回车"), - listOf(",", "7", "8", "9", "语音"), - // "0" sits directly under "8", flanked by +/. — the same - // layout convention as a phone dial pad's "* 0 #" row. - listOf("+", "0", ".", "符号", "返回"), - ) - } - val body = LinearLayout(service).apply { orientation = LinearLayout.VERTICAL } - rows.forEachIndexed { rowIndex, rowItems -> - val row = LinearLayout(service).apply { gravity = Gravity.CENTER } - rowItems.forEachIndexed { index, label -> - val isAction = index == rowItems.lastIndex - val action: () -> Unit = when { - rowIndex == 0 && isAction -> ({ service.deleteBackward() }) - rowIndex == 1 && isAction -> ({ service.sendEnterKey() }) - rowIndex == 2 && isAction -> ({ - service.inputMode = OpenLessImeService.InputMode.VOICE - service.saveInputMode(service.inputMode) - strokeNumberMode = false - numberSymbolMode = false - symbolPageIndex = 0 - service.refreshInputView() - }) - // Symbol-page navigation only replaces row 3's first three - // cells (previously "+ - .") while in symbol mode; the - // middle cell is just a page indicator, not clickable. - rowIndex == 3 && index == 0 && numberSymbolMode -> ({ - symbolPageIndex = (symbolPageIndex - 1 + numberPanelSymbolPages.size) % numberPanelSymbolPages.size - service.refreshInputView() - }) - rowIndex == 3 && index == 1 && numberSymbolMode -> ({}) - rowIndex == 3 && index == 2 && numberSymbolMode -> ({ - symbolPageIndex = (symbolPageIndex + 1) % numberPanelSymbolPages.size - service.refreshInputView() - }) - rowIndex == 3 && index == 3 -> ({ - numberSymbolMode = !numberSymbolMode - symbolPageIndex = 0 - service.refreshInputView() - }) - rowIndex == 3 && isAction -> ({ - strokeNumberMode = false - numberSymbolMode = false - symbolPageIndex = 0 - service.refreshInputView() - }) - else -> ({ commitDirect(label) }) - } - row.addView(service.keyboardKey(label, 1f, action, repeatOnLongPress = rowIndex == 0 && isAction, repeatAction = action).apply { - textSize = if (isAction) 15f else 20f - if (isAction) background = service.roundedButton(Color.rgb(153, 26, 40), service.dp(7)) - }) + private fun handleCommand(command: String) { + if (!isCurrentPanel()) return + when (command) { + "h", "s", "p", "n", "z", "*" -> appendStroke(command) + "segment" -> segmentStroke() + "script" -> { + service.toggleScriptPreference() + if (strokeCode.isNotEmpty() || wordSegments.isNotEmpty()) renderCandidateRow(lastStrokeCandidates) + else refreshAssociations() + } + "space" -> commitDirect(" ") + "backspace" -> if (strokeNumberMode) service.deleteBackward() else deleteStroke() + "enter" -> { abandonComposition(); service.sendEnterKey() } + "clear" -> clearStrokes() + "symbols" -> { strokeNumberMode = true; numberSymbolMode = true; symbolPageIndex = 0; refreshPanel() } + "numbers" -> { strokeNumberMode = true; numberSymbolMode = false; symbolPageIndex = 0; refreshPanel() } + "toggle_symbols" -> { numberSymbolMode = !numberSymbolMode; symbolPageIndex = 0; refreshPanel() } + "prev" -> { symbolPageIndex = (symbolPageIndex - 1).mod(numberPanelSymbolPages.size); refreshPanel() } + "next" -> { symbolPageIndex = (symbolPageIndex + 1).mod(numberPanelSymbolPages.size); refreshPanel() } + "back" -> { strokeNumberMode = false; numberSymbolMode = false; symbolPageIndex = 0; refreshPanel() } + "voice" -> { + val startRecording = !strokeNumberMode + strokeNumberMode = false + numberSymbolMode = false + symbolPageIndex = 0 + clearStrokes() + service.inputMode = OpenLessImeService.InputMode.VOICE + service.saveInputMode(service.inputMode) + service.refreshInputView() + if (startRecording && !service.recording) service.toggleDictation() } - body.addView(row, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) } - root.addView(body, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) - return root } private fun appendStroke(stroke: String) { @@ -483,18 +215,7 @@ internal class StrokeInputController(private val service: OpenLessImeService) { renderCandidateRow(emptyList()) } - private fun updateStrokePreview() { - // Plain "+" concatenation on a CharSequence would call toString() and - // drop the ImageSpan the 5th stroke relies on — TextUtils.concat() - // preserves spans across both pieces. - strokePreview?.text = android.text.TextUtils.concat(wordSegments.joinToString(""), service.displayStrokeCode(strokeCode)) - updateClearStrokeButtonVisibility() - } - - /** Only shows the encode row's "✕" once there's actually something to clear — otherwise it just sat there doing nothing. */ - private fun updateClearStrokeButtonVisibility() { - clearStrokeButton?.visibility = if (strokeCode.isEmpty() && wordSegments.isEmpty()) View.GONE else View.VISIBLE - } + private fun updateStrokePreview() { refreshPanel() } private fun refreshStrokeCandidates(code: String) { val query = ++strokeQueryEpoch @@ -515,73 +236,22 @@ internal class StrokeInputController(private val service: OpenLessImeService) { * single-character candidates for the character currently being typed. */ private fun renderCandidateRow(strokeMatches: List) { - val specs = mutableListOf() - // The very first candidate shown — whichever one that is — is - // highlighted in the same red as the right-hand action rail, since - // it's what a bare space/enter would commit. - var firstCandidate = true + val entries = mutableListOf() if (wordSegments.isNotEmpty()) { val word = wordSegments.joinToString("") - val displayWord = service.outputScript(word) - // Matches candidateItemView()'s own dp(11)-per-side padding - // (2*11=22) plus ~22dp per glyph at its 20sp text size. - val wordWidth = service.dp((displayWord.codePointCount(0, displayWord.length) * 22 + 22).coerceAtLeast(50)) - specs.add(CandidateSpec(displayWord, firstCandidate, wordWidth) { commitWord(word) }) - firstCandidate = false + entries += CandidateSpec(service.outputScript(word)) { commitWord(word) } } - strokeMatches.forEach { candidate -> - val displayCandidate = service.outputScript(candidate) - // Was dp(38); briefly widened to dp(46) alongside - // candidateItemView()'s own now-reverted padding/text-size - // experiment (see that function's comment) — settled on dp(45). - specs.add(CandidateSpec(displayCandidate, firstCandidate, service.dp(45)) { commitStrokeCandidate(candidate) }) - firstCandidate = false + strokeMatches.forEach { word -> + entries += CandidateSpec(service.outputScript(word)) { commitStrokeCandidate(word) } } - populateCandidateRow(specs) - service.candidateOverlayEntries = specs.map { it.label to it.action } + populateCandidateRow(entries) } - /** One candidate slot's content, independent of whatever View (if any) ends up showing it — see populateCandidateRow(). */ - private data class CandidateSpec(val label: String, val isFirst: Boolean, val widthPx: Int, val action: () -> Unit) + private data class CandidateSpec(val label: String, val action: () -> Unit) - /** - * Repopulates strokeCandidates with [specs] by reusing existing child - * views in place — retexting/rewidthing/rebinding the click target of - * whatever's already sitting at each index — instead of this row's old - * removeAllViews()-then-addView()-every-candidate approach. Rebuilding - * up to MAX_CANDIDATES real keyboardKey()-backed Views (a background - * drawable allocated then immediately discarded, plus a full touch- - * listener closure with long-press/swipe-retarget plumbing this row - * never uses) on literally every keystroke is the actual source of - * candidate-row lag on a slow device, not the async dictionary lookup - * feeding it — this call site is on the hot path (every stroke and - * every phrase-association refresh), so only the surplus or shortfall - * between the previous and new candidate count now creates or removes - * a View at all. - */ private fun populateCandidateRow(specs: List) { - val row = strokeCandidates ?: return - specs.forEachIndexed { index, spec -> - when (val existing = row.getChildAt(index)) { - is TextView -> { - existing.text = spec.label - existing.setOnClickListener { spec.action() } - service.styleCandidateFirstState(existing, spec.isFirst) - val params = existing.layoutParams as LinearLayout.LayoutParams - if (params.width != spec.widthPx) { - params.width = spec.widthPx - existing.layoutParams = params - } - } - else -> row.addView( - service.candidateItemView(spec.label, spec.isFirst, action = spec.action), - LinearLayout.LayoutParams(spec.widthPx, ViewGroup.LayoutParams.MATCH_PARENT), - ) - } - } - while (row.childCount > specs.size) { - row.removeViewAt(row.childCount - 1) - } + candidateEntries = specs + refreshPanel() } /** Commits the current character together with any segments already marked via 分词. */ @@ -613,7 +283,6 @@ internal class StrokeInputController(private val service: OpenLessImeService) { private fun refreshAssociations() { if (!service.personalizedLearningAllowed() || !OpenLessAndroidPreferences.strokeAssociationEnabled(service)) { populateCandidateRow(emptyList()) - service.candidateOverlayEntries = emptyList() return } val context = confirmedText.takeLast(MAX_ASSOCIATION_CONTEXT) @@ -621,14 +290,12 @@ internal class StrokeInputController(private val service: OpenLessImeService) { if (context.isEmpty()) return phraseRepository.searchAsync(context) { result -> if (query != phraseQueryEpoch || service.inputMode != OpenLessImeService.InputMode.STROKE || confirmedText.takeLast(MAX_ASSOCIATION_CONTEXT) != context) return@searchAsync - val specs = result.mapIndexed { index, candidate -> + val specs = result.map { candidate -> val matchedPrefix = candidate.matchedPrefix.ifEmpty { context } val displayText = service.outputScript(candidate.text) - val candidateWidth = service.dp((displayText.codePointCount(0, displayText.length) * 22 + 16).coerceAtLeast(46)) - CandidateSpec(displayText, index == 0, candidateWidth) { commitAssociation(candidate.text, matchedPrefix) } + CandidateSpec(displayText) { commitAssociation(candidate.text, matchedPrefix) } } populateCandidateRow(specs) - service.candidateOverlayEntries = specs.map { it.label to it.action } } } @@ -669,7 +336,7 @@ internal class StrokeInputController(private val service: OpenLessImeService) { phraseQueryEpoch++ refreshAssociations() } else { - strokeCandidates?.removeAllViews() + populateCandidateRow(emptyList()) } } } @@ -679,9 +346,8 @@ internal class StrokeInputController(private val service: OpenLessImeService) { strokeQueryEpoch++ wordSegments.clear() lastStrokeCandidates = emptyList() - strokePreview?.text = "" - strokeCandidates?.removeAllViews() - updateClearStrokeButtonVisibility() + candidateEntries = emptyList() + refreshPanel() } /** @@ -696,7 +362,6 @@ internal class StrokeInputController(private val service: OpenLessImeService) { clearStrokes() confirmedText = "" phraseQueryEpoch++ - service.candidateOverlayEntries = emptyList() } private fun commitDirect(text: String) { diff --git a/openless-all/android/kotlin/androidTest/ImeAutoTextIntegrationTest.kt b/openless-all/android/kotlin/androidTest/ImeAutoTextIntegrationTest.kt index e4d57a2d7..925de286a 100644 --- a/openless-all/android/kotlin/androidTest/ImeAutoTextIntegrationTest.kt +++ b/openless-all/android/kotlin/androidTest/ImeAutoTextIntegrationTest.kt @@ -135,6 +135,11 @@ class ImeAutoTextIntegrationTest { deleted.countDown() return result } + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean { + val result = super.deleteSurroundingTextInCodePoints(beforeLength, afterLength) + deleted.countDown() + return result + } }) call(service, "englishDeleteBackward") } diff --git a/openless-all/android/kotlin/androidTest/ImeBridgeCompatibilityInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeBridgeCompatibilityInstrumentedTest.kt new file mode 100644 index 000000000..bc80d52f0 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeBridgeCompatibilityInstrumentedTest.kt @@ -0,0 +1,51 @@ +package com.openless.app + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith + +/** Listener compatibility independent of microphone, backend and app-private data. */ +@RunWith(AndroidJUnit4::class) +class ImeBridgeCompatibilityInstrumentedTest { + @Test fun legacyListenerReceivesOneNotificationFromMetadataCallback() { + val states = mutableListOf() + val listener = object : OpenLessOverlayBridge.OverlayStateListener { + override fun onCapsuleStateChanged(state: String, message: String?, level: Float) { + states += "$state:$message:$level" + } + } + listener.onCapsuleStateChangedWithSession("recording", "ready", 0.5f, "session-a") + assertEquals(listOf("recording:ready:0.5"), states) + } + + @Test fun scopedListenerReceivesOpaqueIdentityWithoutLegacyDoubleDispatch() { + var legacyCalls = 0 + var scopedCalls = 0 + var identity: String? = null + val listener = object : OpenLessOverlayBridge.OverlayStateListener { + override fun onCapsuleStateChanged(state: String, message: String?, level: Float) { legacyCalls++ } + override fun onCapsuleStateChangedWithSession(state: String, message: String?, level: Float, sessionId: String?) { + scopedCalls++ + identity = sessionId + } + } + listener.onCapsuleStateChangedWithSession("done", null, 0f, "Opaque-ID 7") + assertEquals(0, legacyCalls) + assertEquals(1, scopedCalls) + assertEquals("Opaque-ID 7", identity) + } + + @Test fun unscopedLegacyNotificationsRemainExplicitlyUnknown() { + var identity: String? = "unexpected" + val listener = object : OpenLessOverlayBridge.OverlayStateListener { + override fun onCapsuleStateChanged(state: String, message: String?, level: Float) = Unit + override fun onCapsuleStateChangedWithSession(state: String, message: String?, level: Float, sessionId: String?) { + identity = sessionId + } + } + listener.onCapsuleStateChangedWithSession("error", "unscoped", 0f, null) + assertNull(identity) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeDraftBarInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeDraftBarInstrumentedTest.kt new file mode 100644 index 000000000..92e7a45d1 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeDraftBarInstrumentedTest.kt @@ -0,0 +1,257 @@ +package com.openless.app + +import android.graphics.drawable.GradientDrawable +import android.os.Build +import android.view.View +import android.view.ViewGroup +import android.widget.EditText +import android.widget.FrameLayout +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * 独立草稿栏的 View 级仪器测试:不启动 Activity、不触达 Service/JNI/InputConnection/网络。 + * + * - 真实 [EditText] + fake 回调,`instrumentation.runOnMainSync` 内构建/布局/点击; + * - 覆盖:重挂保留 editor 内容与选区、render 不写 editor、confirm/cancel 单次且各一次反馈、 + * submitting 真正禁用、错误态色/可读 a11y、confirm accent、detach 后旧挂起聚焦不夺权、 + * 不同 AT_MOST 尺寸下控件不重叠可点击、cancelInteractions 清 pressed。 + * + * 限制:测试不附着真实窗口(`isAttachedToWindow` 恒为 false),因此只断言"父节点归属/无夺权" + * 这类结构性约束;真实光标聚焦需要真机/Activity 场景,本文件不声称已实测。 + */ +@RunWith(AndroidJUnit4::class) +class ImeDraftBarInstrumentedTest { + + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private val palette = ImePalette.resolve(false) + + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + + private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt() + + private var cancelCount = 0 + private var confirmCount = 0 + private var feedbackCount = 0 + + private fun newEditor(text: String = "草稿内容 draft"): EditText = EditText(context).apply { + setText(text) + setSelection(minOf(2, text.length), minOf(5, text.length)) + } + + private fun buildBar(editor: EditText): ImeDraftBar = ImeDraftBar( + context, + palette, + editor, + onCancel = { cancelCount++ }, + onConfirm = { confirmCount++ }, + onFeedback = { feedbackCount++ }, + ) + + private fun host(view: View, width: Int = dp(360), height: Int = dp(240)): FrameLayout { + val host = FrameLayout(context) + host.addView( + view, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.WRAP_CONTENT, + ), + ) + layout(host, width, height) + return host + } + + private fun layout(view: View, width: Int, height: Int) { + view.measure( + View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST), + View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST), + ) + view.layout(0, 0, view.measuredWidth, view.measuredHeight) + } + + private fun resetCounters() { + cancelCount = 0 + confirmCount = 0 + feedbackCount = 0 + } + + @Test + fun reattachKeepsEditorContentAndSelectionWithoutWritingIt() { + lateinit var editor: EditText + lateinit var oldParent: FrameLayout + lateinit var bar: ImeDraftBar + onMain { + editor = newEditor() + oldParent = FrameLayout(context) + oldParent.addView(editor) + bar = buildBar(editor) + } + assertSame("editor 必须被搬到新栏", bar, editor.parent) + assertEquals(0, oldParent.childCount) + assertEquals("草稿内容 draft", editor.text.toString()) + assertEquals(2, editor.selectionStart) + assertEquals(5, editor.selectionEnd) + + onMain { bar.render("编辑中", isError = false, submitting = false) } + + assertEquals("render 不得改写 editor 文本", "草稿内容 draft", editor.text.toString()) + assertEquals(2, editor.selectionStart) + assertEquals(5, editor.selectionEnd) + } + + @Test + fun confirmAndCancelFireOnceEachWithOneFeedbackPerClick() { + lateinit var bar: ImeDraftBar + onMain { + resetCounters() + bar = buildBar(newEditor()) + host(bar) + } + onMain { bar.confirm.performClick() } + assertEquals(1, confirmCount) + assertEquals(0, cancelCount) + assertEquals(1, feedbackCount) + + onMain { bar.cancel.performClick() } + assertEquals(1, confirmCount) + assertEquals(1, cancelCount) + assertEquals(2, feedbackCount) + } + + @Test + fun submittingDisablesBothButtonsAndBlocksCallbacks() { + lateinit var bar: ImeDraftBar + onMain { + resetCounters() + bar = buildBar(newEditor()) + host(bar) + bar.render("提交中", isError = false, submitting = true) + } + assertFalse(bar.confirm.isEnabled) + assertFalse(bar.cancel.isEnabled) + + onMain { + bar.confirm.performClick() + bar.cancel.performClick() + } + assertEquals(0, confirmCount) + assertEquals(0, cancelCount) + assertEquals(0, feedbackCount) + + onMain { + bar.render("编辑中", isError = false, submitting = false) + bar.confirm.performClick() + } + assertTrue(bar.confirm.isEnabled) + assertTrue(bar.cancel.isEnabled) + assertEquals(1, confirmCount) + assertEquals(1, feedbackCount) + } + + @Test + fun errorStateUsesPaletteErrorAndReadableDescription() { + lateinit var bar: ImeDraftBar + onMain { + bar = buildBar(newEditor()) + host(bar) + bar.render("保存失败", isError = true, submitting = false) + } + assertEquals("保存失败", bar.status.text.toString()) + assertEquals(palette.error, bar.status.currentTextColor) + assertEquals("保存失败", bar.status.contentDescription?.toString()) + + onMain { bar.render("已就绪", isError = false, submitting = false) } + assertEquals(palette.secondaryText, bar.status.currentTextColor) + assertNull(bar.status.contentDescription) + } + + @Test + fun confirmAccentIsAppliedToConfirmBackground() { + // GradientDrawable.getColor() 仅 API 24+ 暴露;低版本设备跳过该色值读取。 + org.junit.Assume.assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + lateinit var bar: ImeDraftBar + val accent = 0xFF00C853.toInt() + onMain { + bar = buildBar(newEditor()) + host(bar) + bar.render("编辑中", isError = false, submitting = false, confirmAccent = accent) + } + val background = bar.confirm.background as GradientDrawable + assertEquals(accent, background.color?.defaultColor) + } + + @Test + fun detachedBarCannotRepostFocusAfterEditorMovesToAnotherBar() { + lateinit var editor: EditText + lateinit var firstBar: ImeDraftBar + lateinit var secondBar: ImeDraftBar + val firstHost = FrameLayout(context) + val secondHost = FrameLayout(context) + onMain { + editor = newEditor() + firstBar = buildBar(editor) + firstHost.addView(firstBar) + } + onMain { + firstHost.removeView(firstBar) + secondBar = buildBar(editor) + secondHost.addView(secondBar) + } + instrumentation.waitForIdleSync() + + assertSame("重挂后 editor 必须归第二栏", secondBar, editor.parent) + assertNotSame(firstBar, editor.parent) + onMain { firstBar.cancelInteractions() } + assertSame("旧栏取消交互不得夺回 editor", secondBar, editor.parent) + } + + @Test + fun atMostConstraintsKeepControlsNonOverlappingAndClickable() { + lateinit var bar: ImeDraftBar + onMain { + bar = buildBar(newEditor("短草稿")) + layout(bar, dp(320), dp(240)) + } + assertTrue("应尊重 AT_MOST 高度", bar.measuredHeight <= dp(240)) + assertTrue(bar.cancel.height > 0) + assertTrue(bar.confirm.height > 0) + assertTrue("cancel 不得与 status 重叠", bar.cancel.right <= bar.status.left) + assertTrue("status 不得与 confirm 重叠", bar.status.right <= bar.confirm.left) + assertTrue("confirm 必须在栏内", bar.confirm.right <= bar.width) + + onMain { + layout(bar, dp(1080), dp(900)) + } + assertTrue(bar.confirm.width > 0) + assertTrue(bar.confirm.right <= bar.width) + } + + @Test + fun cancelInteractionsClearsPressedStateAndDoesNotCallBack() { + lateinit var bar: ImeDraftBar + onMain { + resetCounters() + bar = buildBar(newEditor()) + host(bar) + } + onMain { + bar.cancel.isPressed = true + bar.confirm.isPressed = true + bar.cancelInteractions() + } + assertFalse(bar.cancel.isPressed) + assertFalse(bar.confirm.isPressed) + assertEquals(0, cancelCount) + assertEquals(0, confirmCount) + assertEquals(0, feedbackCount) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeEditingSafetyInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeEditingSafetyInstrumentedTest.kt new file mode 100644 index 000000000..06cb83a76 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeEditingSafetyInstrumentedTest.kt @@ -0,0 +1,115 @@ +package com.openless.app + +import android.content.Context +import android.content.ContextWrapper +import android.view.KeyEvent +import android.view.inputmethod.BaseInputConnection +import android.view.inputmethod.ExtractedText +import android.view.inputmethod.ExtractedTextRequest +import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputConnectionWrapper +import android.widget.EditText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** Only fake editor connections; no service onCreate, Native, microphone or user text. */ +@RunWith(AndroidJUnit4::class) +class ImeEditingSafetyInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + private fun set(service: OpenLessImeService, name: String, value: Any?) { + OpenLessImeService::class.java.getDeclaredField(name).apply { isAccessible = true }.set(service, value) + } + private fun service(edit: EditText, connection: InputConnection): OpenLessImeService { + val service = OpenLessImeService() + ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java) + .apply { isAccessible = true }.invoke(service, context) + set(service, "draftEdit", edit) + set(service, "draftConnection", connection) + return service + } + private fun base(edit: EditText) = object : BaseInputConnection(edit, true) { + override fun getEditable() = edit.text + } + + @Test fun backspaceDeletesAnEntireSupplementaryCodepoint() { + var text = "" + onMain { + val edit = EditText(context).apply { setText("a😀"); setSelection(length()) } + service(edit, base(edit)).deleteBackward() + text = edit.text.toString() + } + assertEquals("a", text) + } + + @Test fun backspacePreservesSelectionReplacementSemantics() { + var text = "" + onMain { + val edit = EditText(context).apply { setText("abc"); setSelection(1, 2) } + service(edit, base(edit)).deleteBackward() + text = edit.text.toString() + } + assertEquals("ac", text) + } + + @Test fun unsupportedCodepointDeletionFallsBackToCapturedConnectionKeyEvents() { + val events = mutableListOf>() + onMain { + val edit = EditText(context).apply { setText("a"); setSelection(1) } + val connection = object : InputConnectionWrapper(base(edit), false) { + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int) = false + override fun sendKeyEvent(event: KeyEvent): Boolean { + events += event.action to event.keyCode + return true + } + } + service(edit, connection).deleteBackward() + } + assertEquals(listOf(KeyEvent.ACTION_DOWN to KeyEvent.KEYCODE_DEL, KeyEvent.ACTION_UP to KeyEvent.KEYCODE_DEL), events) + } + + @Test fun rangeSelectionAddsPartialOffsetAndDoesNotSplitEmoji() { + val selections = mutableListOf>() + onMain { + val edit = EditText(context) + val connection = object : InputConnectionWrapper(base(edit), false) { + override fun getExtractedText(request: ExtractedTextRequest?, flags: Int) = ExtractedText().apply { + text = "a😀b" + startOffset = 10 + selectionStart = 1 + selectionEnd = 1 + } + override fun setSelection(start: Int, end: Int): Boolean { + selections += start to end + return true + } + } + val service = service(edit, connection) + set(service, "clipboardSelectionMode", true) + OpenLessImeService::class.java.getDeclaredMethod("sendClipboardCursorKey", Int::class.javaPrimitiveType) + .apply { isAccessible = true }.invoke(service, KeyEvent.KEYCODE_DPAD_RIGHT) + } + assertEquals(listOf(11 to 13), selections) + } + + @Test fun unknownExtractedTextDoesNotSelectFromGuessedZero() { + val selections = mutableListOf>() + onMain { + val edit = EditText(context) + val connection = object : InputConnectionWrapper(base(edit), false) { + override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText? = null + override fun setSelection(start: Int, end: Int): Boolean { selections += start to end; return true } + } + val service = service(edit, connection) + set(service, "clipboardSelectionMode", true) + OpenLessImeService::class.java.getDeclaredMethod("sendClipboardCursorKey", Int::class.javaPrimitiveType) + .apply { isAccessible = true }.invoke(service, KeyEvent.KEYCODE_DPAD_RIGHT) + } + assertTrue(selections.isEmpty()) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeInteractionFeedbackInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeInteractionFeedbackInstrumentedTest.kt new file mode 100644 index 000000000..902d952eb --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeInteractionFeedbackInstrumentedTest.kt @@ -0,0 +1,271 @@ +package com.openless.app + +import android.os.SystemClock +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * 反馈 / 互动策略的本地 View 级测试(不附着窗口、不 sleep、不跑定时器 tick)。 + * + * 约定与假设: + * - 只在主线程构造/measure/layout(尺寸由测试显式给定),事件用真实 + * `dispatchTouchEvent(DOWN/MOVE/UP/CANCEL)`; + * - `holdDelayMs` 故意设为 30s,测试期间不推进 looper,因此不会触发 hold/repeat 计时器; + * - 不触达 Service/Native/真实 vibrator,也不读写用户偏好; + * - 断言全部在主线程外执行(主线程内只做调用与计数采集)。 + */ +@RunWith(AndroidJUnit4::class) +class ImeInteractionFeedbackInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private val palette = ImePalette.resolve(false) + + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + + private fun newButton( + onAction: () -> Unit, + onFeedback: () -> Unit, + onHold: (() -> Unit)? = null, + repeatOnHold: Boolean = false, + interactionPolicy: ImeInteractionPolicy = ImeInteractionPolicy.DEFAULT, + enabled: Boolean = true, + ): ImeActionButton = ImeActionButton( + context, + palette, + "键", + description = "test key", + onAction = onAction, + onHold = onHold, + repeatOnHold = repeatOnHold, + holdDelayMs = 30_000L, + onFeedback = onFeedback, + interactionPolicy = interactionPolicy, + ).apply { isEnabled = enabled } + + private fun layout(view: View, width: Int = 240, height: Int = 96) { + view.measure( + View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY), + ) + view.layout(0, 0, width, height) + } + + private fun dispatch(view: View, action: Int, x: Float, y: Float) { + val now = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(now, now, action, x, y, 0) + view.dispatchTouchEvent(event) + event.recycle() + } + + private fun centerX(view: View): Float = view.width / 2f + private fun centerY(view: View): Float = view.height / 2f + + private fun tap(view: View) { + val x = centerX(view) + val y = centerY(view) + dispatch(view, MotionEvent.ACTION_DOWN, x, y) + dispatch(view, MotionEvent.ACTION_MOVE, x + 2f, y + 1f) + dispatch(view, MotionEvent.ACTION_UP, x, y) + } + + private fun findButton(root: View, predicate: (ImeActionButton) -> Boolean = { true }): ImeActionButton? { + if (root is ImeActionButton && predicate(root)) return root + if (root is ViewGroup) { + for (index in 0 until root.childCount) { + findButton(root.getChildAt(index), predicate)?.let { return it } + } + } + return null + } + + // --- ImeActionButton:反馈不重复 --- + + @Test + fun tapFeedsDownOnceAndUpDoesNotDoubleFeedback() { + var actions = 0 + var feedback = 0 + onMain { + val button = newButton(onAction = { actions++ }, onFeedback = { feedback++ }) + layout(button) + tap(button) + } + assertEquals("onAction 只应触发一次", 1, actions) + assertEquals("DOWN 反馈一次,UP 不重复", 1, feedback) + } + + @Test + fun accessibilityPerformClickFeedsOnce() { + var actions = 0 + var feedback = 0 + var handled = false + onMain { + val button = newButton(onAction = { actions++ }, onFeedback = { feedback++ }) + layout(button) + handled = button.performClick() + } + assertTrue(handled) + assertEquals(1, actions) + assertEquals("无障碍 click 没有 DOWN,应补一次反馈", 1, feedback) + } + + @Test + fun accessibilityPerformLongClickCallsHoldNotPlainAction() { + var actions = 0 + var holds = 0 + var feedback = 0 + var handled = false + onMain { + val button = newButton( + onAction = { actions++ }, + onFeedback = { feedback++ }, + onHold = { holds++ }, + ) + layout(button) + handled = button.performLongClick() + } + assertTrue(handled) + assertEquals("长按必须走 onHold", 1, holds) + assertEquals("长按不得触发普通 onAction", 0, actions) + assertEquals(1, feedback) + } + + // --- 互动策略 apply 语义 --- + + @Test + fun samePolicyApplyDoesNotCancelInProgressTap() { + var actions = 0 + var feedback = 0 + onMain { + val button = newButton(onAction = { actions++ }, onFeedback = { feedback++ }) + layout(button) + val x = centerX(button) + val y = centerY(button) + dispatch(button, MotionEvent.ACTION_DOWN, x, y) + // 与 DEFAULT 等值(都 60ms):不得取消进行中的触摸。 + button.applyInteractionPolicy(ImeInteractionPolicy.fromStoredRepeat(60L)) + dispatch(button, MotionEvent.ACTION_MOVE, x + 2f, y + 1f) + dispatch(button, MotionEvent.ACTION_UP, x, y) + } + assertEquals("相同策略不应打断点击", 1, actions) + assertEquals(1, feedback) + } + + @Test + fun differentPolicyApplyCancelsInProgressTap() { + var actions = 0 + var feedback = 0 + onMain { + val button = newButton(onAction = { actions++ }, onFeedback = { feedback++ }) + layout(button) + val x = centerX(button) + val y = centerY(button) + dispatch(button, MotionEvent.ACTION_DOWN, x, y) + button.applyInteractionPolicy(ImeInteractionPolicy.fromStoredRepeat(130L)) + dispatch(button, MotionEvent.ACTION_MOVE, x + 2f, y + 1f) + dispatch(button, MotionEvent.ACTION_UP, x, y) + } + assertEquals("不同策略应中止进行中的点击", 0, actions) + assertEquals("只有 DOWN 那一次反馈", 1, feedback) + } + + @Test + fun cancelAfterDownKeepsSingleFeedbackWithoutAction() { + var actions = 0 + var feedback = 0 + onMain { + val button = newButton(onAction = { actions++ }, onFeedback = { feedback++ }) + layout(button) + val x = centerX(button) + val y = centerY(button) + dispatch(button, MotionEvent.ACTION_DOWN, x, y) + dispatch(button, MotionEvent.ACTION_CANCEL, x, y) + } + assertEquals("ACTION_CANCEL 不得执行动作", 0, actions) + assertEquals("CANCEL 只保留按下时的反馈", 1, feedback) + } + + @Test + fun disabledKeyDoesNotFeedOrAct() { + var actions = 0 + var feedback = 0 + var clickHandled = true + onMain { + val button = newButton( + onAction = { actions++ }, + onFeedback = { feedback++ }, + enabled = false, + ) + layout(button) + tap(button) + clickHandled = button.performClick() + } + assertEquals(0, actions) + // 实现约定:disabled 的 DOWN 在反馈前即被拒绝,因此不应有任何震动。 + assertEquals(0, feedback) + assertFalse("disabled 的 performClick 应返回 false", clickHandled) + } + + // --- Stroke / Clipboard 入口确实接上了 feedback/policy(非模型空参数) --- + + @Test + fun strokePanelRoutesFeedbackAndCommandsToHostHooks() { + var feedback = 0 + var business = 0 + var found = false + onMain { + val panel = ImeStrokePanel( + context, + palette, + View(context), + englishUi = false, + onCommand = { business++ }, + onText = { business++ }, + onPunctuationPage = { business++ }, + onFeedback = { feedback++ }, + ) + layout(panel, width = 1080, height = 900) + // 不同策略下也应更新子按键,再验证点击仍把 feedback 送到宿主 hook。 + panel.applyInteractionPolicy(ImeInteractionPolicy.fromStoredRepeat(120L)) + val key = findButton(panel) { it.isEnabled && it.visibility == View.VISIBLE } + found = key != null + key?.performClick() + } + assertTrue(found) + assertEquals("Stroke 子按键的反馈应到达 onFeedback", 1, feedback) + assertEquals("Stroke 子按键应触发真实业务回调", 1, business) + } + + @Test + fun clipboardPanelRoutesFeedbackAndCommandsToHostHooks() { + var feedback = 0 + var clipboardKeyFound = false + val commands = mutableListOf() + onMain { + val panel = ImeClipboardPanel( + context, + palette, + View(context), + englishUi = false, + onCommand = { commands += it }, + onCategory = { commands += "category:$it" }, + onFeedback = { feedback++ }, + ) + layout(panel, width = 1080, height = 900) + panel.applyInteractionPolicy(ImeInteractionPolicy.fromStoredRepeat(140L)) + val copyKey = findButton(panel) { it.tag == "ime-edit-copy" } + clipboardKeyFound = copyKey != null + copyKey?.performClick() + } + assertTrue("剪贴板编辑网格应有 copy 键", clipboardKeyFound) + assertEquals("Clipboard 子按键的反馈应到达 onFeedback", 1, feedback) + assertEquals("Clipboard 子按键应触发真实命令回调", listOf("copy"), commands) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImePanelInteractionEdgeCasesInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImePanelInteractionEdgeCasesInstrumentedTest.kt new file mode 100644 index 000000000..42b386e9b --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImePanelInteractionEdgeCasesInstrumentedTest.kt @@ -0,0 +1,157 @@ +package com.openless.app + +import android.os.SystemClock +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * 两个收敛点的真实 View callback 测试(不只看文字): + * 1) 父级 `isEnabled=false` 时,clear / 候选 select 都不能触发业务回调;重新启用后恢复; + * 2) 稀疏 symbols → 同 geometry 更新为更满 symbols 时,新出现的非空槽恢复可点且回调一次。 + * + * 不附着窗口、不 sleep、不跑定时器 tick;断言在主线程外。 + */ +@RunWith(AndroidJUnit4::class) +class ImePanelInteractionEdgeCasesInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private val palette = ImePalette.resolve(false) + + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + + private fun layout(view: View, width: Int = 1080, height: Int = 900) { + view.measure( + View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY), + ) + view.layout(0, 0, width, height) + } + + private fun findView(root: View, predicate: (View) -> Boolean): View? { + if (predicate(root)) return root + if (root is ViewGroup) { + for (index in 0 until root.childCount) { + findView(root.getChildAt(index), predicate)?.let { return it } + } + } + return null + } + + private fun dispatch(view: View, action: Int, x: Float, y: Float) { + val now = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(now, now, action, x, y, 0) + view.dispatchTouchEvent(event) + event.recycle() + } + + @Test + fun parentDisabledBlocksClearAndCandidateSelectWithRealCallbacks() { + val commands = mutableListOf() + val texts = mutableListOf() + val selections = mutableListOf() + val pages = mutableListOf() + var feedback = 0 + var clearClickedWhenDisabled = true + var businessClicksWhenDisabled = 0 + var businessClicksAfterEnable = 0 + var selectWhenDisabled = 0 + var selectAfterEnable = 0 + + onMain { + val panel = ImeStrokePanel( + context, + palette, + View(context), + englishUi = false, + onCommand = { commands += it }, + onText = { texts += it }, + onPunctuationPage = { pages += it }, + onFeedback = { feedback++ }, + ) + layout(panel) + panel.submitCandidates(listOf(ImeStrokePanel.Candidate("候") { selections += "候" })) + + val clearKey = findView(panel) { it is ImeActionButton && it.text == "✕" } as ImeActionButton? + val businessKey = findView(panel) { + it is ImeActionButton && it.text.isNotEmpty() && it.text != "✕" + } as ImeActionButton? + val candidate = findView(panel) { it.contentDescription == "候" } + + panel.isEnabled = false + clearClickedWhenDisabled = clearKey?.performClick() ?: false + businessKey?.performClick() + businessClicksWhenDisabled = commands.size + texts.size + pages.size + candidate?.performClick() + selectWhenDisabled = selections.size + + // 恢复父级后,同一批 View 应重新可用(证明禁用不是永久破坏)。 + panel.isEnabled = true + businessKey?.performClick() + businessClicksAfterEnable = commands.size + texts.size + pages.size + candidate?.performClick() + selectAfterEnable = selections.size + } + + assertTrue("禁用时 clear 的 performClick 应返回 false", !clearClickedWhenDisabled) + assertEquals("禁用时 clear 不得触发 onCommand(\"clear\")", 0, commands.count { it == "clear" }) + assertEquals("禁用时任何业务键都不得回调", 0, businessClicksWhenDisabled) + assertEquals("禁用时候选 select 不得触发", 0, selectWhenDisabled) + assertEquals("恢复后业务键应回调一次", 1, businessClicksAfterEnable) + assertEquals("恢复后候选 select 应回调一次", 1, selectAfterEnable) + assertEquals(listOf("候"), selections) + } + + @Test + fun sparseSymbolPageThenFullPageRestoresClickableSlots() { + val texts = mutableListOf() + var feedback = 0 + var slotWasDisabledInitially = false + var sameViewReused = false + var slotEnabledAfterUpdate = false + var textsAfterClick = 0 + + onMain { + val panel = ImeStrokePanel( + context, + palette, + View(context), + englishUi = false, + onCommand = {}, + onText = { texts += it }, + onPunctuationPage = {}, + onFeedback = { feedback++ }, + ) + layout(panel) + // 稀疏符号页:只有 3 项,其余槽为空 -> 构建时 INVISIBLE + disabled。 + panel.render("", false, numberMode = true, symbolMode = true, symbolPage = 0, symbolPageCount = 2, + symbols = listOf("A", "B", "C"), punctuation = emptyList()) + val sparseSlot = findView(panel) { it is ImeActionButton && it.text.isEmpty() } as ImeActionButton? + slotWasDisabledInitially = sparseSlot != null && !sparseSlot.isEnabled + + // 同 geometry(不重建)更新为满 12 项:原空槽变 "D" 且必须恢复可点。 + panel.render("", false, numberMode = true, symbolMode = true, symbolPage = 1, symbolPageCount = 2, + symbols = listOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"), + punctuation = emptyList()) + val slotAfter = findView(panel) { it is ImeActionButton && it.text == "D" } as ImeActionButton? + sameViewReused = sparseSlot != null && sparseSlot === slotAfter + slotEnabledAfterUpdate = slotAfter?.isEnabled == true + slotAfter?.performClick() + textsAfterClick = texts.size + } + + assertTrue("稀疏页的空槽初始应为 disabled", slotWasDisabledInitially) + assertTrue("同 geometry 更新应复用同一个 View(不重建)", sameViewReused) + assertTrue("新非空槽必须恢复 enabled", slotEnabledAfterUpdate) + assertEquals("点击新非空槽应触发 onText 一次", 1, textsAfterClick) + assertEquals(listOf("D"), texts) + assertEquals("无障碍 click 应反馈一次", 1, feedback) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeRemainingPanelsInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeRemainingPanelsInstrumentedTest.kt new file mode 100644 index 000000000..98e806a99 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeRemainingPanelsInstrumentedTest.kt @@ -0,0 +1,646 @@ +package com.openless.app + +import android.os.SystemClock +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.TextView +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * 剩余面板的 View 级仪器测试:ImeActionButton / ImeCandidateStrip / ImeStrokePanel / ImeClipboardPanel。 + * + * - 不启动 Activity,不触达 Service/JNI/InputConnection/native;全部用 fake 回调。 + * - 固定 measure/layout(默认 1080×900)后用真实 MotionEvent 序列驱动手势路径。 + * - 触摸钮上的手势直接向该按钮 [View.dispatchTouchEvent] 发送(坐标是按钮本地坐标), + * 面板级定位用 `offsetDescendantRectToMyCoords`。 + * - 不 sleep、不等待长按定时器:`ImeActionButton` 的 hold/repeat 依赖 `isAttachedToWindow`, + * 本测试不附着窗口,因此只覆盖点击/上滑/取消/移出等触摸路径(限制见文件末注释)。 + * + * 断言对象是**目标语义**(与 root 已确认的 production 修订一致,例如标点/符号翻页后点击命中最新值、 + * 符号页保留退格/回车/语音动作键、笔画键标签同时含数字与笔画字形且至少两行)。因此本文件在 + * production 修订合入前可能失败,属于预期。 + */ +@RunWith(AndroidJUnit4::class) +class ImeRemainingPanelsInstrumentedTest { + + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private val palette = ImePalette.resolve(false) + + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + + private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt() + + // ---- 通用布局/事件辅助 ---- + + private fun layout(view: View, width: Int = 1080, height: Int = 900) { + val widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY) + val heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY) + view.measure(widthSpec, heightSpec) + view.layout(0, 0, width, height) + } + + private fun host(view: View, width: Int = 720, height: Int = 200): FrameLayout { + val host = FrameLayout(context) + host.addView( + view, + FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT), + ) + layout(host, width, height) + return host + } + + private fun dispatch(view: View, action: Int, x: Float, y: Float) { + val now = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(now, now, action, x, y, 0) + view.dispatchTouchEvent(event) + event.recycle() + } + + private fun tap(view: View) { + val x = view.width / 2f + val y = view.height / 2f + dispatch(view, MotionEvent.ACTION_DOWN, x, y) + dispatch(view, MotionEvent.ACTION_UP, x, y) + } + + private fun pressThenUp(view: View, upX: Float, upY: Float, moves: List> = emptyList()) { + val startX = view.width / 2f + val startY = view.height / 2f + dispatch(view, MotionEvent.ACTION_DOWN, startX, startY) + moves.forEach { (x, y) -> dispatch(view, MotionEvent.ACTION_MOVE, x, y) } + dispatch(view, MotionEvent.ACTION_UP, upX, upY) + } + + private fun walk(root: View, action: (View) -> Unit) { + action(root) + if (root is ViewGroup) { + for (index in 0 until root.childCount) walk(root.getChildAt(index), action) + } + } + + private fun allButtons(root: View): List { + val result = mutableListOf() + walk(root) { if (it is ImeActionButton) result.add(it) } + return result + } + + /** 按文本包含关系定位(production 不用 tag 时唯一稳定的定位方式)。 */ + private fun findKey(root: View, contains: String): ImeActionButton { + var found: ImeActionButton? = null + walk(root) { view -> + if (found == null && view is ImeActionButton && view.text.toString().contains(contains)) { + found = view + } + } + assertNotNull("找不到包含「$contains」的按键", found) + return found!! + } + + private fun findTagged(root: View, tag: String): View { + var found: View? = null + walk(root) { if (found == null && it.tag == tag) found = it } + assertNotNull("找不到 tag=$tag", found) + return found!! + } + + private fun findTextMatching(root: View, regex: Regex): TextView { + var found: TextView? = null + walk(root) { view -> + if (found == null && view is TextView && regex.matches(view.text.toString().trim())) { + found = view + } + } + assertNotNull("找不到匹配 $regex 的文本", found) + return found!! + } + + // ================= ImeActionButton ================= + + private fun buildButton( + label: String = "k", + onSwipeUp: (() -> Unit)? = null, + ): Pair> { + val events = mutableListOf() + val button = ImeActionButton( + context, + palette, + label, + description = label, + onAction = { events.add("click") }, + onSwipeUp = onSwipeUp?.let { { events.add("swipe") } }, + ) + host(button, width = dp(120), height = dp(80)) + return button to events + } + + @Test + fun plainKeySwipedPastTopEdgeDoesNotClick() { + val (button, events) = buildButton() + onMain { + pressThenUp(button, upX = button.width / 2f, upY = -dp(40).toFloat(), moves = listOf( + button.width / 2f to -dp(40).toFloat(), + )) + } + assertEquals(emptyList(), events) + } + + @Test + fun swipeKeyPastTopEdgeFiresSwipeOnceAndNeverClicks() { + val (button, events) = buildButton(onSwipeUp = {}) + onMain { + pressThenUp(button, upX = button.width / 2f, upY = -dp(40).toFloat(), moves = listOf( + button.width / 2f to -dp(40).toFloat(), + )) + } + assertEquals(listOf("swipe"), events) + } + + @Test + fun cancelEventNeverClicks() { + val (button, events) = buildButton() + onMain { + dispatch(button, MotionEvent.ACTION_DOWN, button.width / 2f, button.height / 2f) + dispatch(button, MotionEvent.ACTION_CANCEL, button.width / 2f, button.height / 2f) + } + assertEquals(emptyList(), events) + } + + @Test + fun movingOutsideThenBackInsideDoesNotClick() { + val (button, events) = buildButton() + val centerX = button.width / 2f + val centerY = button.height / 2f + onMain { + dispatch(button, MotionEvent.ACTION_DOWN, centerX, centerY) + dispatch(button, MotionEvent.ACTION_MOVE, button.width + dp(60).toFloat(), centerY) + dispatch(button, MotionEvent.ACTION_MOVE, centerX, centerY) + dispatch(button, MotionEvent.ACTION_UP, centerX, centerY) + } + assertEquals(emptyList(), events) + } + + // ================= ImeCandidateStrip ================= + + private fun buildStrip(onExpansion: (Boolean) -> Unit = {}): Pair { + val strip = ImeCandidateStrip(context, palette, englishUi = false, onExpansionChanged = onExpansion) + val host = host(strip, width = 1080, height = dp(42)) + return strip to host + } + + @Test + fun sameLabelReusesViewAndBindsLatestCallback() { + val stripAndHost = buildStrip() + val strip = stripAndHost.first + val selected = mutableListOf() + onMain { + strip.submit(listOf(0, 1, 2).map { index -> + ImeCandidateStrip.Item("same-$index", select = { selected.add("old-$index") }) + }) + val reused = findTagged(strip, "ime-cand-0") + strip.submit(listOf(0, 1, 2).map { index -> + ImeCandidateStrip.Item("same-$index", select = { selected.add("new-$index") }) + }) + val after = findTagged(strip, "ime-cand-0") + assertSame(reused, after) + reused.performClick() + } + assertEquals(listOf("new-0"), selected) + } + + @Test + fun replacedCandidateViewCannotFireNewSlotAction() { + val strip = buildStrip().first + val selected = mutableListOf() + lateinit var stale: View + onMain { + strip.submit(listOf(ImeCandidateStrip.Item("alpha", select = { selected.add("alpha") }))) + stale = findTagged(strip, "ime-cand-0") + strip.submit(listOf(ImeCandidateStrip.Item("beta", select = { selected.add("beta") }))) + // 槽位换了 View:旧引用点击必须无效。 + stale.performClick() + } + assertEquals(emptyList(), selected) + onMain { + findTagged(strip, "ime-cand-0").performClick() + } + assertEquals(listOf("beta"), selected) + } + + @Test + fun closingExpandedStopsExpandedCandidateClicks() { + val strip = buildStrip().first + val selected = mutableListOf() + lateinit var expandedItem: View + onMain { + strip.submit(listOf(ImeCandidateStrip.Item("one", select = { selected.add("one") }))) + findTagged(strip, "ime-cand-expand").performClick() + } + onMain { + expandedItem = findTagged(strip.expandedView, "ime-cand-expanded-0") + expandedItem.performClick() + assertEquals(listOf("one"), selected) + strip.closeExpanded() + expandedItem.performClick() + } + assertEquals(listOf("one"), selected) + } + + @Test + fun blockedStripIgnoresCandidateAndExpansion() { + val strip = buildStrip().first + val selected = mutableListOf() + onMain { + strip.submit(listOf(ImeCandidateStrip.Item("one", select = { selected.add("one") }))) + strip.setBlocked(true) + findTagged(strip, "ime-cand-0").performClick() + findTagged(strip, "ime-cand-expand").performClick() + assertFalse(findTagged(strip, "ime-cand-expand").isEnabled) + } + assertEquals(emptyList(), selected) + onMain { + strip.setBlocked(false) + findTagged(strip, "ime-cand-0").performClick() + } + assertEquals(listOf("one"), selected) + } + + // ================= ImeStrokePanel ================= + + private val commands = mutableListOf() + private val texts = mutableListOf() + private val punctuationPages = mutableListOf() + private lateinit var strokePanel: ImeStrokePanel + + private fun buildStrokePanel() { + commands.clear() + texts.clear() + punctuationPages.clear() + strokePanel = ImeStrokePanel( + context, + palette, + View(context), + englishUi = false, + onCommand = { commands.add(it) }, + onText = { texts.add(it) }, + onPunctuationPage = { punctuationPages.add(it) }, + ) + layout(strokePanel, 1080, 900) + } + + private fun strokeRender( + preedit: CharSequence = "", + traditional: Boolean = false, + numberMode: Boolean = false, + symbolMode: Boolean = false, + symbolPage: Int = 0, + symbolPageCount: Int = 1, + symbols: List = emptyList(), + punctuation: List = listOf(",", "°", "?", "!", "~"), + ) { + strokePanel.render( + preedit, + traditional, + numberMode, + symbolMode, + symbolPage, + symbolPageCount, + symbols, + punctuation, + ) + layout(strokePanel, 1080, 900) + } + + @Test + fun strokeGridEmitsExpectedCommandsAndTexts() { + onMain { + buildStrokePanel() + strokeRender() + findKey(strokePanel, "一").performClick() + findKey(strokePanel, "丨").performClick() + findKey(strokePanel, "丿").performClick() + findKey(strokePanel, "丶").performClick() + findKey(strokePanel, "乙").performClick() + findKey(strokePanel, "通配").performClick() + findKey(strokePanel, "分词").performClick() + findKey(strokePanel, "繁").performClick() + findKey(strokePanel, "空格").performClick() + findKey(strokePanel, "←").performClick() + findKey(strokePanel, "↵").performClick() + findKey(strokePanel, "清除").performClick() + findKey(strokePanel, "123").performClick() + findKey(strokePanel, ":").performClick() + findKey(strokePanel, ";").performClick() + } + assertEquals( + listOf("h", "s", "p", "n", "z", "*", "segment", "script", "space", "backspace", "enter", "clear", "numbers"), + commands, + ) + assertEquals(listOf(":", ";"), texts) + } + + @Test + fun digitKeysSwipeUpEmitDigits() { + onMain { + buildStrokePanel() + strokeRender() + val digitOne = findKey(strokePanel, "一") + val digitNine = findKey(strokePanel, ";") + listOf(digitOne to "1", digitNine to "9").forEach { (key, digit) -> + val x = key.width / 2f + dispatch(key, MotionEvent.ACTION_DOWN, x, key.height / 2f) + dispatch(key, MotionEvent.ACTION_MOVE, x, -dp(40).toFloat()) + dispatch(key, MotionEvent.ACTION_UP, x, -dp(40).toFloat()) + assertTrue("swipe up 应产生 $digit", texts.contains(digit)) + } + } + assertTrue(texts.contains("1")) + assertTrue(texts.contains("9")) + assertFalse(commands.contains("h")) + } + + @Test + fun punctuationPageFlipUsesLatestValues() { + val firstPage = listOf("、", "。", ",") + val secondPage = listOf("〈", "〉", "「") + onMain { + buildStrokePanel() + strokeRender(punctuation = firstPage) + val railKey = findKey(strokePanel, "、") + strokeRender(punctuation = secondPage) + // 同一几何只更新标签:旧引用点击必须命中最新一组的第一个值。 + railKey.performClick() + } + assertEquals(listOf("〈"), texts) + } + + @Test + fun numberModeEmitsCommands() { + onMain { + buildStrokePanel() + strokeRender(numberMode = true) + findKey(strokePanel, "退格").performClick() + findKey(strokePanel, "回车").performClick() + findKey(strokePanel, "语音").performClick() + findKey(strokePanel, "符号").performClick() + findKey(strokePanel, "返回").performClick() + findKey(strokePanel, "7").performClick() + } + assertEquals(listOf("backspace", "enter", "voice", "toggle_symbols", "back"), commands) + assertEquals(listOf("7"), texts) + } + + @Test + fun symbolModeKeepsActionKeysAndUsesLatestPage() { + val firstPage = listOf("α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ") + val secondPage = listOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L") + onMain { + buildStrokePanel() + strokeRender(symbolMode = true, symbolPage = 0, symbolPageCount = 2, symbols = firstPage) + val firstSymbol = findKey(strokePanel, "α") + strokeRender(symbolMode = true, symbolPage = 1, symbolPageCount = 2, symbols = secondPage) + firstSymbol.performClick() + // root 修订后符号页每行保留一个动作键:3 行 × 5(4 符号 + 1 动作)+ footer 5。 + findKey(strokePanel, "退格").performClick() + findKey(strokePanel, "回车").performClick() + findKey(strokePanel, "语音").performClick() + findKey(strokePanel, "▲").performClick() + findKey(strokePanel, "▼").performClick() + findKey(strokePanel, "返回").performClick() + } + assertEquals(listOf("A"), texts) + assertEquals(listOf("backspace", "enter", "voice", "prev", "next", "back"), commands) + val indicator = findTextMatching(strokePanel, Regex("\\d+/\\d+")) + assertFalse("页码指示器不可点击", indicator.isClickable) + } + + @Test + fun strokeDigitLabelsExposeDigitAndStrokeGlyphOnTwoLines() { + onMain { + buildStrokePanel() + strokeRender() + val one = findKey(strokePanel, "一") + assertTrue("标签应同时含数字 1 与笔画字形 一", one.text.toString().contains("1")) + assertTrue("笔画键至少两行以容纳数字提示", one.maxLines >= 2 || one.lineCount >= 2) + } + } + + @Test + fun clearPreeditTouchIsCanceledByCancelInteractions() { + onMain { + buildStrokePanel() + strokeRender(preedit = "横竖") + val clearKey = findKey(strokePanel, "✕") + assertEquals(View.VISIBLE, clearKey.visibility) + dispatch(clearKey, MotionEvent.ACTION_DOWN, clearKey.width / 2f, clearKey.height / 2f) + strokePanel.cancelInteractions() + dispatch(clearKey, MotionEvent.ACTION_UP, clearKey.width / 2f, clearKey.height / 2f) + } + assertFalse("cancelInteractions 应取消 preedit 清除键的进行中触摸", commands.contains("clear")) + } + + @Test + fun blockedStrokePanelIgnoresClicks() { + onMain { + buildStrokePanel() + strokeRender() + strokePanel.setBlocked(true) + findKey(strokePanel, "一").performClick() + findKey(strokePanel, "←").performClick() + strokePanel.setBlocked(false) + findKey(strokePanel, "一").performClick() + } + assertEquals(listOf("h"), commands) + } + + @Test + fun setBlockedCancelsInFlightKeyTouch() { + onMain { + buildStrokePanel() + strokeRender() + val key = findKey(strokePanel, "一") + dispatch(key, MotionEvent.ACTION_DOWN, key.width / 2f, key.height / 2f) + strokePanel.setBlocked(true) + dispatch(key, MotionEvent.ACTION_UP, key.width / 2f, key.height / 2f) + strokePanel.setBlocked(false) + } + assertEquals(emptyList(), commands) + } + + @Test + fun candidateExpansionKeepsPanelHeight() { + onMain { + buildStrokePanel() + strokeRender() + strokePanel.submitCandidates( + (0 until 20).map { ImeStrokePanel.Candidate("候选$it") {} }, + ) + layout(strokePanel, 1080, 900) + val before = strokePanel.height + findTagged(strokePanel, "ime-cand-expand").performClick() + layout(strokePanel, 1080, 900) + assertEquals("展开候选不得改变面板总高度", before, strokePanel.height) + } + } + + // ================= ImeClipboardPanel ================= + + private val clipboardCommands = mutableListOf() + private val categories = mutableListOf() + private val selections = mutableListOf() + private lateinit var clipboardPanel: ImeClipboardPanel + + private fun clipItem(text: String): ImeClipboardPanel.Item = ImeClipboardPanel.Item( + text = text, + favorite = false, + inDictionary = false, + select = { selections.add(text) }, + toggleFavorite = { selections.add("favorite:$text") }, + remove = { selections.add("remove:$text") }, + toggleDictionary = { selections.add("dictionary:$text") }, + ) + + private fun buildClipboardPanel() { + clipboardCommands.clear() + categories.clear() + selections.clear() + clipboardPanel = ImeClipboardPanel( + context, + palette, + View(context), + englishUi = false, + onCommand = { clipboardCommands.add(it) }, + onCategory = { categories.add(it) }, + ) + layout(clipboardPanel, 1080, 900) + } + + private fun clipRender( + editorToken: Long = 1L, + historyVisible: Boolean = false, + selection: Boolean = false, + category: String = "ALL", + entries: List = emptyList(), + recent: List = emptyList(), + ) { + clipboardPanel.render(editorToken, historyVisible, selection, category, entries, recent) + layout(clipboardPanel, 1080, 900) + } + + @Test + fun clipboardEditingCommandsOnlyDispatchCommands() { + onMain { + buildClipboardPanel() + clipRender(recent = listOf(clipItem("recent-a"))) + findTagged(clipboardPanel, "ime-edit-range").performClick() + findTagged(clipboardPanel, "ime-edit-copy").performClick() + findTagged(clipboardPanel, "ime-edit-paste").performClick() + findTagged(clipboardPanel, "ime-edit-backspace").performClick() + findTagged(clipboardPanel, "ime-clip-recent-0").performClick() + } + assertEquals(listOf("range", "copy", "paste", "backspace"), clipboardCommands) + assertEquals(listOf("recent-a"), selections) + } + + @Test + fun clipboardSelectionStateMarksMoveKeysAndHistoryHoldEdits() { + onMain { + buildClipboardPanel() + clipRender(selection = true) + val left = findTagged(clipboardPanel, "ime-edit-left") as TextView + assertTrue("选择态应高亮方向键", left.isSelected) + findTagged(clipboardPanel, "ime-edit-history").performLongClick() + } + assertEquals(listOf("edit"), clipboardCommands) + } + + @Test + fun clipboardHistoryFiltersSelectsAndClears() { + onMain { + buildClipboardPanel() + clipRender(historyVisible = true, category = "ALL", entries = listOf(clipItem("history-a"), clipItem("history-b"))) + findTagged(clipboardPanel, "ime-clip-filter-TEXT").performClick() + findTagged(clipboardPanel, "ime-clip-item-1").performClick() + findTagged(clipboardPanel, "ime-clip-favorite-0").performClick() + findTagged(clipboardPanel, "ime-history-clear").performClick() + findTagged(clipboardPanel, "ime-history-close").performClick() + } + assertEquals(listOf("TEXT"), categories) + assertEquals(listOf("history-b", "favorite:history-a"), selections) + assertEquals(listOf("clear_history", "close_history"), clipboardCommands) + } + + @Test + fun clipboardBlockedIgnoresEverything() { + onMain { + buildClipboardPanel() + clipRender(historyVisible = true, entries = listOf(clipItem("blocked-a"))) + clipboardPanel.setBlocked(true) + findTagged(clipboardPanel, "ime-clip-item-0").performClick() + findTagged(clipboardPanel, "ime-edit-copy").performClick() + findTagged(clipboardPanel, "ime-history-clear").performClick() + clipboardPanel.setBlocked(false) + findTagged(clipboardPanel, "ime-edit-copy").performClick() + } + assertEquals(emptyList(), selections) + assertEquals(listOf("copy"), clipboardCommands) + } + + @Test + fun clipboardStaleGenerationItemDoesNothing() { + onMain { + buildClipboardPanel() + clipRender(historyVisible = true, entries = listOf(clipItem("first-a"))) + val staleItem = findTagged(clipboardPanel, "ime-clip-item-0") + // 同一 editorToken 但新一轮 render:generation 递增,旧 View 引用必须失效。 + clipRender(historyVisible = true, entries = listOf(clipItem("second-a"))) + staleItem.performClick() + } + assertEquals(emptyList(), selections) + } + + @Test + fun clipboardCancelInteractionsThenRenderRecovers() { + onMain { + buildClipboardPanel() + clipRender(historyVisible = true, entries = listOf(clipItem("before-cancel"))) + clipboardPanel.cancelInteractions() + clipRender(historyVisible = true, entries = listOf(clipItem("after-cancel"))) + findTagged(clipboardPanel, "ime-clip-item-0").performClick() + } + assertEquals(listOf("after-cancel"), selections) + } + + @Test + fun longPressActionIsDiscoverableForAccessibility() { + var accessible = false + var edits = 0 + onMain { + val key = ImeActionButton(context, palette, "Edit", onAction = {}, onHold = { edits++ }) + accessible = key.isLongClickable && key.performLongClick() + } + assertTrue(accessible) + assertEquals(1, edits) + } +} + +/* + * 限制(未覆盖,需真机/附着窗口场景): + * 1) ImeActionButton 的 hold/repeat 定时器在 `!isAttachedToWindow` 时主动跳过(见 production guard), + * 本测试不附着窗口,因此不覆盖长按语音(900ms)/连发退格;这些由根 Service 的仪器测试或真机覆盖。 + * 2) 不验证触感、音效、窗口插入与 IME 连接;不覆盖横屏/大屏的具体像素密度差异。 + * 3) 笔画键视觉截断(span 数字提示)用 `maxLines/lineCount + text 完整性` 近似断言,不是像素级截图比对。 + * 4) `ImeStrokePanel` 的符号页动作键(退格/回车/语音)与翻页后最新值断言针对 root 修订后的目标语义; + * 在修订合入前会失败,这是预期的红灯。 + */ diff --git a/openless-all/android/kotlin/androidTest/ImeSessionScopeInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeSessionScopeInstrumentedTest.kt new file mode 100644 index 000000000..2c6ed04c3 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeSessionScopeInstrumentedTest.kt @@ -0,0 +1,331 @@ +package com.openless.app + +import android.content.Context +import android.content.ContextWrapper +import android.content.SharedPreferences +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * 真实 `OpenLessImeService` 的会话帧接线测试(不是 model/门禁单测的复读)。 + * + * 边界与安全: + * - 使用 isolated [ContextWrapper] 把 `getSharedPreferences` 重定向到测试命名空间, + * 并预置 `key_haptic_enabled=false`,不写用户偏好、不振动; + * - `new OpenLessImeService()` 后只做 `attachBaseContext`(沿用 + * `ImeAutoTextIntegrationTest` 的模式),**绝不调用 onCreate/onDestroy**; + * - 只调用已在源码中审读过的纯状态路径: + * `onCapsuleStateChangedWithSession` / `onImeSessionEvent(started|completed 拒绝路径)` / + * `ImeScopedFrameGate`,不调用 `toggleDictation`/`cancelImeSession`/`sendImeCommand` + * 等会发 Native 命令的方法;不发送 start/stop/cancel; + * - 所有断言在 `runOnMainSync` 之外执行(主线程内只做调用与状态采集)。 + * + * 覆盖的真实路径:`imeFrameGate.accept` 归属判定 → `applyOwnedCapsuleFrame` + * (经 `ImeVoiceFramePolicy`)→ `voiceUiState()` 投影 → `recording`/`processing`/ + * `latestVoiceLevel`/`externalRecording` 等真实字段。 + */ +@RunWith(AndroidJUnit4::class) +class ImeSessionScopeInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + + /** 隔离偏好:所有写入落到 `ime_scope_test__*` 命名空间,绝不碰真实用户偏好。 */ + private class IsolatedPrefsContext(base: Context) : ContextWrapper(base) { + override fun getSharedPreferences(name: String?, mode: Int): SharedPreferences = + super.getSharedPreferences("ime_scope_test__${name ?: "null"}", mode) + } + + /** 主线程内采集的真实 Service 状态快照(断言在主线程外做)。 */ + private data class ScopeState( + val recording: Boolean, + val processing: Boolean, + val latestVoiceLevel: Float, + val externalRecording: Boolean, + val externalProcessing: Boolean, + val activeImeOwner: ImeRequestOwner?, + val imeSessionId: String?, + val imeStopRequested: Boolean, + val imeCaptureEnded: Boolean, + val pendingCloudArm: Boolean, + val pendingImeStop: Boolean, + val cloudNoteArmed: Boolean, + val state: String, + val lastDictationText: String?, + val snapshot: ImeVoiceUiSnapshot, + ) + + // --- 构造与反射 --- + + private fun newService(): OpenLessImeService { + val isolated = IsolatedPrefsContext(instrumentation.targetContext) + isolated.getSharedPreferences("openless_ime_ui", Context.MODE_PRIVATE).edit() + .putBoolean("key_haptic_enabled", false) + .putLong("key_haptic_duration_ms", 1L) + .putInt("key_haptic_amplitude", 1) + .commit() + val service = OpenLessImeService() + ContextWrapper::class.java + .getDeclaredMethod("attachBaseContext", Context::class.java) + .apply { isAccessible = true } + .invoke(service, isolated) + return service + } + + private fun setField(service: OpenLessImeService, name: String, value: Any?) { + OpenLessImeService::class.java.getDeclaredField(name).apply { isAccessible = true }.set(service, value) + } + + private fun getField(service: OpenLessImeService, name: String): Any? = + OpenLessImeService::class.java.getDeclaredField(name).apply { isAccessible = true }.get(service) + + private fun call(service: OpenLessImeService, name: String, parameterType: Class<*>, argument: Any?): Any? = + OpenLessImeService::class.java.getDeclaredMethod(name, parameterType) + .apply { isAccessible = true } + .invoke(service, argument) + + private fun gate(service: OpenLessImeService): ImeScopedFrameGate = + getField(service, "imeFrameGate") as ImeScopedFrameGate + + private fun snapshot(service: OpenLessImeService): ScopeState = ScopeState( + recording = service.recording, + processing = getField(service, "processing") as Boolean, + latestVoiceLevel = getField(service, "latestVoiceLevel") as Float, + externalRecording = getField(service, "externalRecording") as Boolean, + externalProcessing = getField(service, "externalProcessing") as Boolean, + activeImeOwner = getField(service, "activeImeOwner") as ImeRequestOwner?, + imeSessionId = getField(service, "imeSessionId") as String?, + imeStopRequested = getField(service, "imeStopRequested") as Boolean, + imeCaptureEnded = getField(service, "imeCaptureEnded") as Boolean, + pendingCloudArm = getField(service, "pendingCloudArm") as Boolean, + pendingImeStop = getField(service, "pendingImeStop") as Boolean, + cloudNoteArmed = getField(service, "cloudNoteArmed") as Boolean, + state = getField(service, "state") as String, + lastDictationText = getField(service, "lastDictationText") as String?, + snapshot = OpenLessImeService::class.java.getDeclaredMethod("voiceUiState") + .apply { isAccessible = true } + .invoke(service) as ImeVoiceUiSnapshot, + ) + + /** 绑定 owner(可选同时把 gate 绑定到真实 sessionId)。 */ + private fun arm( + service: OpenLessImeService, + epoch: Long, + requestId: Long, + boundSessionId: String? = null, + ): ImeRequestOwner { + val owner = ImeRequestOwner(epoch, requestId) + setField(service, "sessionEpoch", epoch) + setField(service, "imeRequestId", requestId) + setField(service, "activeImeOwner", owner) + setField(service, "microphoneGranted", true) + gate(service).begin(owner) + if (boundSessionId != null) { + gate(service).bind(owner, boundSessionId) + setField(service, "imeSessionId", boundSessionId) + } + return owner + } + + private fun startedJson(requestId: Long, sessionId: String): String = + """{"kind":"started","requestId":$requestId,"sessionId":"$sessionId"}""" + + // --- 测试 --- + + @Test + fun ownedRecordingFrameUsesRealServiceSourceNoFakeBody() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + arm(service, epoch = 7L, requestId = 70L, boundSessionId = "sess-A") + + service.onCapsuleStateChangedWithSession("recording", "再次点击结束", 0.35f, "sess-A") + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertTrue(state.recording) + assertFalse(state.processing) + assertEquals(0.35f, state.latestVoiceLevel, 0.0001f) + assertFalse(state.externalRecording) + assertFalse(state.externalProcessing) + assertEquals(ImeVoicePhase.RECORDING, state.snapshot.phase) + assertEquals(0.35f, state.snapshot.audioLevel, 0.0001f) + assertEquals("speaking", state.state) + } + + @Test + fun foreignIdAndUnidentifiedFramesCannotChangeOwnFlagsOrRms() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + arm(service, epoch = 7L, requestId = 70L, boundSessionId = "sess-A") + setField(service, "latestVoiceLevel", 0.42f) + + service.onCapsuleStateChangedWithSession("recording", "other", 0.9f, "sess-B") + service.onCapsuleStateChangedWithSession("recording", "noid", 0.8f, null) + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertFalse("FOREIGN/UNIDENTIFIED 帧不得开启自有录音", state.recording) + assertEquals("RMS 不得被其他会话改写", 0.42f, state.latestVoiceLevel, 0.0001f) + assertFalse(state.externalRecording) + assertFalse(state.externalProcessing) + assertEquals(ImeVoicePhase.IDLE, state.snapshot.phase) + } + + @Test + fun afterGateFinishLateOwnedFrameIsStaleNotExternalBusy() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + val owner = arm(service, epoch = 7L, requestId = 70L, boundSessionId = "sess-A") + gate(service).finish(owner) + + service.onCapsuleStateChangedWithSession("recording", "late", 0.9f, "sess-A") + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertFalse(state.recording) + assertFalse("STALE 晚帧不得变成 external busy", state.externalRecording) + assertFalse(state.externalProcessing) + assertEquals("RMS 保持 0", 0f, state.latestVoiceLevel, 0.0001f) + assertEquals(ImeVoicePhase.IDLE, state.snapshot.phase) + } + + @Test + fun stopRequestedAndCaptureEndedLateRecordingDoesNotResurrect() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + arm(service, epoch = 7L, requestId = 70L, boundSessionId = "sess-A") + setField(service, "imeStopRequested", true) + setField(service, "imeCaptureEnded", true) + setField(service, "recording", false) + setField(service, "processing", false) + + service.onCapsuleStateChangedWithSession("recording", "late", 0.9f, "sess-A") + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertFalse("stop 已提交后的 late recording 不得复活", state.recording) + assertFalse(state.processing) + assertTrue(state.imeCaptureEnded) + assertEquals(0f, state.latestVoiceLevel, 0.0001f) + } + + @Test + fun ownedDoneWithStopSubmittedHoldsProcessingAndOwnerUntilScopedResult() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + arm(service, epoch = 7L, requestId = 70L, boundSessionId = "sess-A") + setField(service, "imeStopRequested", true) + setField(service, "imeCaptureEnded", true) + setField(service, "recording", false) + setField(service, "processing", false) + + service.onCapsuleStateChangedWithSession("done", "done-cue", 0f, "sess-A") + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertTrue("done 只是 cue,应等待 scoped 结果", state.processing) + assertFalse(state.recording) + assertNotNull("等待 scoped 结果期间必须保留 owner", state.activeImeOwner) + assertEquals("sess-A", state.imeSessionId) + assertNull("不得写入任何听写文本", state.lastDictationText) + assertEquals("thinking", state.state) + } + + @Test + fun startedEventFlushesOnlyBufferedMatchingFrame() { + var before: ScopeState? = null + var buffered: ScopeState? = null + var bufferedCount = -1 + var after: ScopeState? = null + var boundAfter = false + instrumentation.runOnMainSync { + val service = newService() + arm(service, epoch = 7L, requestId = 70L) // owner 就绪但尚未 + 不知道真实 sessionId + before = snapshot(service) + + // started 之前的真实帧:A 匹配、B 不匹配;全部只能进缓冲。 + service.onCapsuleStateChangedWithSession("recording", "pre-A", 0.4f, "sess-A") + service.onCapsuleStateChangedWithSession("recording", "pre-B", 0.9f, "sess-B") + buffered = snapshot(service) + bufferedCount = gate(service).bufferedCount + + call(service, "onImeSessionEvent", String::class.java, startedJson(70L, "sess-A")) + after = snapshot(service) + boundAfter = gate(service).isBound(ImeRequestOwner(7L, 70L), "sess-A") + } + val initial = requireNotNull(before) + assertFalse("默认不得 pending cloud", initial.pendingCloudArm) + assertFalse(initial.cloudNoteArmed) + assertFalse("默认不得 pending stop", initial.pendingImeStop) + assertEquals(ImeVoicePhase.IDLE, initial.snapshot.phase) + val bufferedState = requireNotNull(buffered) + assertFalse("started 前不得开启录音", bufferedState.recording) + assertEquals(0f, bufferedState.latestVoiceLevel, 0.0001f) + assertEquals("A/B 两帧都应进缓冲", 2, bufferedCount) + val flushed = requireNotNull(after) + assertTrue("started 后只 flush 匹配 id 的缓冲帧", flushed.recording) + assertEquals("必须使用 A 的电平(0.4)而非 B(0.9)", 0.4f, flushed.latestVoiceLevel, 0.0001f) + assertEquals("sess-A", flushed.imeSessionId) + assertTrue(boundAfter) + assertFalse("started 处理不得凭空 arm cloud", flushed.pendingCloudArm) + assertFalse(flushed.cloudNoteArmed) + assertFalse("started 处理不得发出 pending stop", flushed.pendingImeStop) + assertEquals(ImeVoicePhase.RECORDING, flushed.snapshot.phase) + assertEquals("speaking", flushed.state) + } + + @Test + fun oldCompletedWithoutActiveOwnerIsRejectedWithoutEditorIo() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + // 没有 active owner(例如新请求尚未建立或旧请求已释放)。 + setField(service, "sessionEpoch", 7L) + setField(service, "imeRequestId", 70L) + setField(service, "imeSessionId", "sess-X") + setField(service, "activeImeOwner", null) + setField(service, "lastDictationText", null) + + call( + service, + "onImeSessionEvent", + String::class.java, + """{"kind":"completed","requestId":70,"sessionId":"sess-X","text":"SHOULD_NOT_WRITE"}""", + ) + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertNull("拒绝路径不得写入文本", state.lastDictationText) + assertEquals("idle", state.state) + assertFalse(state.recording) + assertFalse(state.processing) + } + + @Test + fun unidentifiedFrameDoesNotResetRmsWhileRecording() { + var observed: ScopeState? = null + instrumentation.runOnMainSync { + val service = newService() + arm(service, epoch = 7L, requestId = 70L, boundSessionId = "sess-A") + service.onCapsuleStateChangedWithSession("recording", "live", 0.3f, "sess-A") + + service.onCapsuleStateChangedWithSession("recording", "noid", 0.95f, null) + service.onCapsuleStateChangedWithSession("recording", "other", 0.95f, "sess-B") + observed = snapshot(service) + } + val state = requireNotNull(observed) + assertTrue(state.recording) + assertEquals("UNIDENTIFIED/FOREIGN 不得改自有 RMS", 0.3f, state.latestVoiceLevel, 0.0001f) + assertEquals(ImeVoicePhase.RECORDING, state.snapshot.phase) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeSurfaceHostInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeSurfaceHostInstrumentedTest.kt new file mode 100644 index 000000000..39c58c2d9 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeSurfaceHostInstrumentedTest.kt @@ -0,0 +1,235 @@ +package com.openless.app + +import android.content.Context +import android.content.ContextWrapper +import android.content.SharedPreferences +import android.graphics.drawable.ColorDrawable +import android.view.View +import android.view.ViewGroup +import android.widget.EditText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** Stable root, bounded draft geometry, and real Service presentation without onCreate/JNI. */ +@RunWith(AndroidJUnit4::class) +class ImeSurfaceHostInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + private fun dp(value: Int) = (value * context.resources.displayMetrics.density).toInt() + + private class PreferredView(context: Context, private val preferred: Int) : View(context) { + override fun onMeasure(width: Int, height: Int) { + val bound = MeasureSpec.getSize(height) + val actual = when (MeasureSpec.getMode(height)) { + MeasureSpec.EXACTLY -> bound + MeasureSpec.AT_MOST -> minOf(bound, preferred) + else -> preferred + } + setMeasuredDimension(MeasureSpec.getSize(width), actual) + } + } + + private fun measure(host: View, height: Int, mode: Int = View.MeasureSpec.AT_MOST) { + host.measure(View.MeasureSpec.makeMeasureSpec(dp(360), View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(height, mode)) + host.layout(0, 0, host.measuredWidth, host.measuredHeight) + } + + @Test fun presentationChangesKeepTheSameRoot() { + var stable = false + var oldDetached = false + onMain { + val host = ImeSurfaceHost(context) + val first = PreferredView(context, dp(300)) + host.render(first, null) + measure(host, dp(900)) + val root = host + val second = PreferredView(context, dp(300)) + host.render(second, null) + measure(host, dp(900)) + stable = root === host && second.parent === host + oldDetached = first.parent == null + } + assertTrue(stable) + assertTrue(oldDetached) + } + + @Test fun exactAcknowledgementDoesNotRepeatedlyShrinkTheKeyboard() { + var before = 0 + var after = 0 + onMain { + val host = ImeSurfaceHost(context) + host.render(PreferredView(context, dp(300)), null) + measure(host, dp(900)) + before = host.measuredHeight + repeat(4) { measure(host, host.measuredHeight, View.MeasureSpec.EXACTLY) } + after = host.measuredHeight + } + assertEquals(dp(300), before) + assertEquals(before, after) + } + + @Test fun constrainedDraftScrollsAboveUsableKeysWithoutOverlap() { + var bounded = false + var noOverlap = false + var retained = false + onMain { + val host = ImeSurfaceHost(context) + val keys = PreferredView(context, dp(300)) + val draft = PreferredView(context, dp(500)) + host.render(keys, draft) + measure(host, dp(360)) + val scroll = host.findViewWithTag("ime-draft-scroll") + bounded = host.measuredHeight <= dp(360) && keys.measuredHeight >= dp(220) + noOverlap = keys.top >= scroll.bottom && keys.bottom <= host.measuredHeight + retained = draft.parent === scroll && draft.measuredHeight >= scroll.measuredHeight + } + assertTrue(bounded) + assertTrue(noOverlap) + assertTrue(retained) + } + + @Test fun closingDraftRemovesItsChromeButKeepsKeysAndRoot() { + var gone = false + var keysRemain = false + onMain { + val host = ImeSurfaceHost(context) + val keys = PreferredView(context, dp(300)) + host.render(keys, PreferredView(context, dp(140))) + measure(host, dp(900)) + host.render(keys, null) + measure(host, dp(900)) + gone = host.findViewWithTag("ime-draft-scroll").visibility == View.GONE + keysRemain = keys.parent === host && keys.top == 0 && host.measuredHeight == dp(300) + } + assertTrue(gone) + assertTrue(keysRemain) + } + + private class IsolatedContext(base: Context) : ContextWrapper(base) { + override fun getSharedPreferences(name: String?, mode: Int): SharedPreferences = + super.getSharedPreferences("ime_surface_test__${name ?: "null"}", mode) + } + + private fun newService(): OpenLessImeService { + val isolated = IsolatedContext(context) + isolated.getSharedPreferences("openless_ime_ui", 0).edit() + .clear().putBoolean("key_haptic_enabled", false).putInt("keyboard_height_dp", 300) + .putString("theme_mode", "dark").commit() + val service = OpenLessImeService() + ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java) + .apply { isAccessible = true }.invoke(service, isolated) + return service + } + + private fun field(service: OpenLessImeService, name: String): Any? = + OpenLessImeService::class.java.getDeclaredField(name).apply { isAccessible = true }.get(service) + private fun setField(service: OpenLessImeService, name: String, value: Any?) { + OpenLessImeService::class.java.getDeclaredField(name).apply { isAccessible = true }.set(service, value) + } + + @Test fun serviceThemeRefreshDoesNotReplaceTheFrameworkRoot() { + var same = false + var changed = false + onMain { + val service = newService() + val root = service.onCreateInputView() + val first = field(service, "keyboardSurface") as ViewGroup + service.getSharedPreferences("openless_ime_ui", 0).edit().putString("theme_mode", "light").commit() + service.refreshInputView() + val second = field(service, "keyboardSurface") as ViewGroup + same = field(service, "surfaceHost") === root && second.parent === root + changed = first !== second && + (second.getChildAt(0).background as? ColorDrawable)?.color == ImePalette.resolve(false).surface + } + assertTrue(same) + assertTrue(changed) + } + + @Test fun serviceDraftOpenClosePreservesRootAndEditorContent() { + var same = false + var content = "" + var start = -1 + var end = -1 + var draftGone = false + onMain { + val service = newService() + val root = service.onCreateInputView() + val editor = EditText(context).apply { setText("unchanged draft"); setSelection(2, 7) } + setField(service, "draftEdit", editor) + setField(service, "draftToken", 1L) + service.refreshInputView() + content = editor.text.toString() + start = editor.selectionStart + end = editor.selectionEnd + same = field(service, "surfaceHost") === root + // Use only the presentation path; never submit text to any host or backend. + setField(service, "draftEdit", null) + setField(service, "draftToken", 2L) + service.refreshInputView() + draftGone = root.findViewWithTag("ime-draft-scroll").visibility == View.GONE + same = same && field(service, "surfaceHost") === root + } + assertTrue(same) + assertEquals("unchanged draft", content) + assertEquals(2, start) + assertEquals(7, end) + assertTrue(draftGone) + } + + @Test fun previewUsesActualTypingKeysAndSuppressesFakeAccessibilityActions() { + var actualKeys = 0 + var hidden = false + onMain { + val preview = ImeKeyboardPreview(context, ImePalette.resolve(false), false) + fun count(view: View) { + if ((view.tag as? String)?.startsWith("ime-key-") == true) actualKeys++ + if (view is ViewGroup) for (i in 0 until view.childCount) count(view.getChildAt(i)) + } + count(preview) + hidden = preview.importantForAccessibility == View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + } + assertEquals(ImeKeyboardLayouts.rows(ImeKeyboardLayer.LETTERS, ImeTypingLanguage.PINYIN, ImeLetterCase.LOWER, "换行").sumOf { it.size }, actualKeys) + assertTrue(hidden) + } + + @Test fun previewTouchDoesNotPressInteractiveDescendants() { + var consumed = false + var pressed = true + onMain { + val preview = ImeKeyboardPreview(context, ImePalette.resolve(false), false) + measure(preview, dp(300), View.MeasureSpec.EXACTLY) + val key = preview.findViewWithTag("ime-key-letters_r1_c1") + val rect = android.graphics.Rect(0, 0, key.width, key.height) + preview.offsetDescendantRectToMyCoords(key, rect) + val now = android.os.SystemClock.uptimeMillis() + for (action in listOf(android.view.MotionEvent.ACTION_DOWN, android.view.MotionEvent.ACTION_UP)) { + val event = android.view.MotionEvent.obtain(now, now, action, rect.exactCenterX(), rect.exactCenterY(), 0) + consumed = preview.dispatchTouchEvent(event) + event.recycle() + } + pressed = key.isPressed + } + assertTrue(consumed) + assertFalse(pressed) + } + + @Test fun previewFitsAllSupportedHeightChoices() { + val heights = mutableListOf() + onMain { + val preview = ImeKeyboardPreview(context, ImePalette.resolve(true), true) + for (height in listOf(220, 300, 420)) { + measure(preview, dp(height), View.MeasureSpec.EXACTLY) + heights += preview.measuredHeight + } + } + assertEquals(listOf(dp(220), dp(300), dp(420)), heights) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeTypingPanelInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeTypingPanelInstrumentedTest.kt new file mode 100644 index 000000000..63434eba6 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeTypingPanelInstrumentedTest.kt @@ -0,0 +1,582 @@ +package com.openless.app + +import android.graphics.PointF +import android.graphics.Rect +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.ScrollView +import android.widget.TextView +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * 真实 View 事件级别的仪器测试:不启动 Activity,不触达 native/Service/JNI。 + * + * - 构造纯 `ImeTypingPanel`,伪造回调;固定 1080x900 测量/布局。 + * - 键盘按键通过 tag `ime-key-{id}` 定位,`offsetDescendantRectToMyCoords` 换算到面板坐标, + * 再对 `panel.dispatchTouchEvent` 发送完整 DOWN/MOVE/UP/CANCEL 序列。 + * - 候选/展开是普通可点击 View,用 `performClick()`/`performLongClick()` 走 Android 自身的 + * 点击分发,不依赖源码字符串匹配。 + * - 不等待长按计时器(KeyGrid 的 hold/repeat 依赖 `isAttachedToWindow` 且测试不附着窗口), + * 全程不使用 Thread.sleep。 + * + * 断言覆盖:轻点单次提交、取消无输入、字母拖拽重定向、功能键拖拽取消、多指取消、 + * 候选点击/长按遗忘不误选、展开不改变面板高度、层切换替换按键、所有模型按键均渲染。 + */ +@RunWith(AndroidJUnit4::class) +class ImeTypingPanelInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context get() = instrumentation.targetContext + private val palette = ImePalette.resolve(false) + + private lateinit var panel: ImeTypingPanel + private val actions = mutableListOf() + private val selections = mutableListOf() + private val voiceEnds = mutableListOf() + private val cursorMoves = mutableListOf() + private var deleteWordCount = 0 + private var clearPreeditCount = 0 + private var commitRawCount = 0 + private var forgotCount = 0 + private var feedbackCount = 0 + private var voiceStarts = 0 + + private fun onMain(block: () -> Unit) = instrumentation.runOnMainSync(block) + + private fun buildPanel() { + actions.clear() + selections.clear() + voiceEnds.clear() + cursorMoves.clear() + deleteWordCount = 0 + clearPreeditCount = 0 + commitRawCount = 0 + forgotCount = 0 + feedbackCount = 0 + voiceStarts = 0 + panel = ImeTypingPanel( + context, + palette, + View(context), + onAction = { actions += it }, + onFeedback = { feedbackCount++ }, + // 语音启动一律拒绝:本测试只验证键盘输入路径。 + onVoiceStart = { voiceStarts++; false }, + onVoiceEnd = { voiceEnds += it }, + onClearPreedit = { clearPreeditCount++ }, + onCommitRawPreedit = { commitRawCount++ }, + onCursorMove = { cursorMoves += it }, + onDeleteWord = { deleteWordCount++ }, + ) + renderKeyboard() + } + + private fun renderKeyboard( + layer: ImeKeyboardLayer = ImeKeyboardLayer.LETTERS, + language: ImeTypingLanguage = ImeTypingLanguage.ENGLISH, + letterCase: ImeLetterCase = ImeLetterCase.LOWER, + enterLabel: String = "Enter", + ) { + panel.renderKeyboard(layer, language, letterCase, enterLabel, false) + layoutPanel() + } + + private fun layoutPanel(width: Int = 1080, height: Int = 900) { + panel.measure( + View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY), + ) + panel.layout(0, 0, width, height) + } + + // --- 视图查找与坐标 --- + + private fun findView(root: View, predicate: (View) -> Boolean): View? { + if (predicate(root)) return root + if (root is ViewGroup) { + for (index in 0 until root.childCount) { + findView(root.getChildAt(index), predicate)?.let { return it } + } + } + return null + } + + private fun taggedKey(id: String): View? = findView(panel) { it.tag == "ime-key-$id" } + + private fun keyCenter(tag: String): PointF { + val key = taggedKey(tag) ?: throw AssertionError("未找到按键 tag=$tag") + val rect = Rect(0, 0, key.width, key.height) + panel.offsetDescendantRectToMyCoords(key, rect) + return PointF(rect.exactCenterX(), rect.exactCenterY()) + } + + private fun countKeys(): Int { + var count = 0 + fun walk(view: View) { + if ((view.tag as? String)?.startsWith("ime-key-") == true) count++ + if (view is ViewGroup) { + for (index in 0 until view.childCount) walk(view.getChildAt(index)) + } + } + walk(panel) + return count + } + + // --- 事件发送 --- + + private fun dispatch(action: Int, point: PointF) { + val now = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(now, now, action, point.x, point.y, 0) + panel.dispatchTouchEvent(event) + event.recycle() + } + + private fun dispatchTwoFinger(point: PointF) { + val now = SystemClock.uptimeMillis() + val properties = arrayOf( + MotionEvent.PointerProperties().apply { + id = 0 + toolType = MotionEvent.TOOL_TYPE_FINGER + }, + MotionEvent.PointerProperties().apply { + id = 1 + toolType = MotionEvent.TOOL_TYPE_FINGER + }, + ) + val coords = arrayOf( + MotionEvent.PointerCoords().apply { + x = point.x + y = point.y + pressure = 1f + size = 1f + }, + MotionEvent.PointerCoords().apply { + x = point.x + 12f + y = point.y + pressure = 1f + size = 1f + }, + ) + val event = MotionEvent.obtain( + now, + now, + MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), + 2, + properties, + coords, + 0, + 0, + 1f, + 1f, + 0, + 0, + InputDevice.SOURCE_TOUCHSCREEN, + 0, + ) + panel.dispatchTouchEvent(event) + event.recycle() + } + + private fun tapKey(tag: String) { + val point = keyCenter(tag) + dispatch(MotionEvent.ACTION_DOWN, point) + dispatch(MotionEvent.ACTION_UP, point) + } + + private fun pressKey(tag: String, thenMoveTo: String?) { + val start = keyCenter(tag) + dispatch(MotionEvent.ACTION_DOWN, start) + if (thenMoveTo != null) { + val end = keyCenter(thenMoveTo) + dispatch(MotionEvent.ACTION_MOVE, end) + dispatch(MotionEvent.ACTION_UP, end) + } else { + dispatch(MotionEvent.ACTION_UP, start) + } + } + + // --- 键盘基本提交 --- + + @Test + fun letterTapCommitsExactlyOnce() { + onMain { buildPanel(); tapKey("letters_r1_c1") } + assertEquals(listOf(ImeKeyAction.Text("q")), actions) + } + + @Test + fun enterTapCommitsOnceWithConfiguredLabel() { + var defaultEnterActions: List = emptyList() + var searchEnterActions: List = emptyList() + var searchLabel: String? = null + onMain { + buildPanel() + tapKey("enter") + defaultEnterActions = actions.toList() + } + onMain { + buildPanel() + renderKeyboard(enterLabel = "搜索") + searchLabel = (taggedKey("enter") as? TextView)?.text?.toString() + tapKey("enter") + searchEnterActions = actions.toList() + } + assertEquals(listOf(ImeKeyAction.Enter), defaultEnterActions) + assertEquals("搜索", searchLabel) + assertEquals(listOf(ImeKeyAction.Enter), searchEnterActions) + } + + @Test + fun spaceTapCommitsSpaceAndNeverStartsVoice() { + onMain { buildPanel(); tapKey("space") } + assertEquals(listOf(ImeKeyAction.Space), actions) + assertEquals(0, voiceStarts) + assertTrue("轻点空格不应结束语音会话", voiceEnds.isEmpty()) + } + + @Test + fun backspaceTapCommitsOnceWithoutRepeat() { + onMain { buildPanel(); tapKey("backspace") } + assertEquals(listOf(ImeKeyAction.Backspace), actions) + } + + @Test + fun functionalTapCommitsOnce() { + onMain { buildPanel(); tapKey("shift") } + assertEquals(listOf(ImeKeyAction.Shift), actions) + } + + // --- 取消与拖拽 --- + + @Test + fun cancelActionProducesNoInput() { + onMain { + buildPanel() + val point = keyCenter("letters_r1_c1") + dispatch(MotionEvent.ACTION_DOWN, point) + dispatch(MotionEvent.ACTION_CANCEL, point) + } + assertTrue("ACTION_CANCEL 后不应有任何提交", actions.isEmpty()) + } + + @Test + fun letterDragRetargetsToFinalKeyOnly() { + onMain { buildPanel(); pressKey("letters_r1_c1", thenMoveTo = "letters_r1_c2") } + assertEquals(listOf(ImeKeyAction.Text("w")), actions) + } + + @Test + fun functionalKeyDragCancelsInsteadOfRetargeting() { + onMain { buildPanel(); pressKey("shift", thenMoveTo = "letters_r3_c1") } + assertTrue("功能键拖到字母键应取消,不应提交", actions.isEmpty()) + } + + @Test + fun multiPointerRolloverCommitsBothKeysInOrder() { + onMain { + buildPanel() + val first = keyCenter("letters_r1_c1") + val second = keyCenter("letters_r1_c2") + val now = SystemClock.uptimeMillis() + val down = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, first.x, first.y, 0) + panel.dispatchTouchEvent(down) + down.recycle() + + val props = arrayOf( + MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER }, + MotionEvent.PointerProperties().apply { id = 1; toolType = MotionEvent.TOOL_TYPE_FINGER }, + ) + val coords = arrayOf( + MotionEvent.PointerCoords().apply { x = first.x; y = first.y; pressure = 1f; size = 1f }, + MotionEvent.PointerCoords().apply { x = second.x; y = second.y; pressure = 1f; size = 1f }, + ) + val ptrDown = MotionEvent.obtain( + now, now + 10, + MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), + 2, props, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0, + ) + panel.dispatchTouchEvent(ptrDown) + ptrDown.recycle() + + val ptrUp = MotionEvent.obtain( + now, now + 20, + MotionEvent.ACTION_POINTER_UP or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), + 2, props, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0, + ) + panel.dispatchTouchEvent(ptrUp) + ptrUp.recycle() + } + assertEquals( + listOf(ImeKeyAction.Text("q"), ImeKeyAction.Text("w")), + actions, + ) + } + + @Test + fun swipeUpOnLetterKeyCommitsSecondaryDigit() { + onMain { + buildPanel() + val start = keyCenter("letters_r1_c1") + val up = PointF(start.x, start.y - 120f) + dispatch(MotionEvent.ACTION_DOWN, start) + dispatch(MotionEvent.ACTION_MOVE, up) + dispatch(MotionEvent.ACTION_UP, up) + } + assertEquals(listOf(ImeKeyAction.Text("1")), actions) + } + + @Test + fun spaceHorizontalSlideMovesCursorWithoutInsertingSpace() { + onMain { + buildPanel() + val start = keyCenter("space") + dispatch(MotionEvent.ACTION_DOWN, start) + dispatch(MotionEvent.ACTION_MOVE, PointF(start.x + 120f, start.y)) + dispatch(MotionEvent.ACTION_UP, PointF(start.x + 120f, start.y)) + } + assertTrue("空格滑动不应提交空格", actions.isEmpty()) + assertTrue("空格右滑应触发右移光标", cursorMoves.isNotEmpty() && cursorMoves.all { it == 1 }) + } + + @Test + fun backspaceSwipeLeftTriggersWordDeleteWithoutPlainBackspace() { + onMain { + buildPanel() + val start = keyCenter("backspace") + val left = PointF(start.x - 160f, start.y) + dispatch(MotionEvent.ACTION_DOWN, start) + dispatch(MotionEvent.ACTION_MOVE, left) + dispatch(MotionEvent.ACTION_UP, left) + } + assertTrue("退格左滑不应提交普通退格", actions.isEmpty()) + assertEquals(1, deleteWordCount) + } + + @Test + fun preeditBarTapCommitsRawAndClearButtonClearsEncoding() { + onMain { + buildPanel() + panel.submitCandidates(listOf(ImeTypingPanel.Candidate("你好", select = {})), preedit = "ni hao") + layoutPanel() + findView(panel) { it.tag == "ime-cand-preedit" }?.performClick() + findView(panel) { it.tag == "ime-preedit-clear" }?.performClick() + } + assertEquals(1, commitRawCount) + assertEquals(1, clearPreeditCount) + } + + @Test + fun quickClipboardChipPastesAndDismisses() { + var pasted = 0 + var dismissed = 0 + onMain { + buildPanel() + panel.setClipboardSuggestion("验证码: 123456", onPaste = { pasted++ }, onDismiss = { dismissed++ }) + layoutPanel() + findView(panel) { it.tag == "ime-cand-quick-chip" }?.performClick() + } + assertEquals(1, pasted) + assertEquals(0, dismissed) + } + + @Test + fun casingUpdateDuringTouchKeepsTheCurrentPointer() { + onMain { + buildPanel() + val point = keyCenter("letters_r1_c1") + dispatch(MotionEvent.ACTION_DOWN, point) + renderKeyboard(letterCase = ImeLetterCase.SHIFT) + dispatch(MotionEvent.ACTION_UP, point) + } + assertEquals(listOf(ImeKeyAction.Text("Q")), actions) + } + + // --- 候选 --- + + @Test + fun candidateTapSelectsOnlyTheClickedCandidate() { + var thirdCandidate: View? = null + onMain { + buildPanel() + panel.submitCandidates( + listOf( + ImeTypingPanel.Candidate(label = "一", select = { selections += "一" }), + ImeTypingPanel.Candidate(label = "二", select = { selections += "二" }), + ImeTypingPanel.Candidate(label = "三", select = { selections += "三" }), + ), + preedit = "yi", + ) + layoutPanel() + thirdCandidate = findView(panel) { it.contentDescription == "三" } + thirdCandidate?.performClick() + } + assertNotNull("候选三应渲染", thirdCandidate) + assertEquals(listOf("三"), selections) + assertTrue("候选点击不应触发键盘动作", actions.isEmpty()) + } + + @Test + fun candidateLongPressForgetsWithoutSelecting() { + var candidate: View? = null + var handled = false + onMain { + buildPanel() + panel.submitCandidates( + listOf( + ImeTypingPanel.Candidate( + label = "自定义", + select = { selections += "自定义" }, + forget = { forgotCount++ }, + ), + ), + preedit = null, + ) + layoutPanel() + candidate = findView(panel) { it.contentDescription == "自定义" } + handled = candidate?.performLongClick() == true + } + assertNotNull("带 forget 的候选应渲染", candidate) + assertTrue("长按应被消费", handled) + assertEquals(1, forgotCount) + assertTrue("长按遗忘不应同时选中", selections.isEmpty()) + } + + @Test + fun candidateWithoutForgetIgnoresLongPress() { + var candidate: View? = null + var handled = true + onMain { + buildPanel() + panel.submitCandidates( + listOf(ImeTypingPanel.Candidate(label = "普通", select = { selections += "普通" })), + preedit = null, + ) + layoutPanel() + candidate = findView(panel) { it.contentDescription == "普通" } + handled = candidate?.performLongClick() == true + } + assertNotNull(candidate) + assertFalse("无 forget 回调时不应消费长按", handled) + assertTrue(selections.isEmpty()) + } + + @Test + fun equalCandidateLabelsUseTheLatestCallback() { + onMain { + buildPanel() + panel.submitCandidates(listOf(ImeTypingPanel.Candidate("词", select = { selections += "old" })), null) + val item = findView(panel) { it.contentDescription == "词" } + panel.submitCandidates(listOf(ImeTypingPanel.Candidate("词", select = { selections += "new" })), null) + item?.performClick() + } + assertEquals(listOf("new"), selections) + } + + @Test + fun removedCandidateViewCannotSelectAReplacement() { + onMain { + buildPanel() + panel.submitCandidates(listOf(ImeTypingPanel.Candidate("旧", select = { selections += "old" })), null) + val stale = findView(panel) { it.contentDescription == "旧" } + panel.submitCandidates(listOf(ImeTypingPanel.Candidate("新", select = { selections += "new" })), null) + stale?.performClick() + } + assertTrue(selections.isEmpty()) + } + + // --- 展开候选 --- + + @Test + fun expandingCandidatesKeepsPanelHeight() { + var heightBefore = 0 + var heightAfter = 0 + var expandedVisible = false + var expandFound = false + var gridStillVisible = false + onMain { + buildPanel() + panel.submitCandidates( + listOf( + ImeTypingPanel.Candidate(label = "甲", select = {}), + ImeTypingPanel.Candidate(label = "乙", select = {}), + ), + preedit = null, + ) + layoutPanel() + heightBefore = panel.measuredHeight + + val expand = findView(panel) { + it.isClickable && it.contentDescription?.contains("候选") == true + } + expandFound = expand != null + expand?.performClick() + layoutPanel() + heightAfter = panel.measuredHeight + + expandedVisible = findView(panel) { it is ScrollView }?.visibility == View.VISIBLE + gridStillVisible = taggedKey("letters_r1_c1") != null + } + assertTrue("展开按钮应存在", expandFound) + assertTrue("展开后键盘仍应可见", gridStillVisible) + assertEquals(900, heightBefore) + assertEquals("展开候选不应改变面板高度", heightBefore, heightAfter) + assertTrue("展开层应可见", expandedVisible) + assertTrue("展开不应提交任何按键动作", actions.isEmpty()) + } + + // --- 层切换与渲染完整性 --- + + @Test + fun switchingToNumbersReplacesLetterKeys() { + var numbersKeyPresent = false + var lettersKeyGone = false + onMain { + buildPanel() + renderKeyboard(layer = ImeKeyboardLayer.NUMBERS) + numbersKeyPresent = taggedKey("numbers_r1_c1") != null + lettersKeyGone = taggedKey("letters_r1_c1") == null + } + assertTrue(numbersKeyPresent) + assertTrue(lettersKeyGone) + } + + @Test + fun everyModelKeyIsRenderedWithATag() { + var rendered = 0 + val expected = ImeKeyboardLayouts.rows( + ImeKeyboardLayer.LETTERS, + ImeTypingLanguage.ENGLISH, + ImeLetterCase.LOWER, + "Enter", + ).flatten().size + onMain { + buildPanel() + rendered = countKeys() + } + assertEquals(expected, rendered) + } + + @Test + fun closeTransientUiCollapsesCandidatesWithoutCommitting() { + var expandedVisible = false + onMain { + buildPanel() + panel.submitCandidates(listOf(ImeTypingPanel.Candidate("候", select = {})), preedit = null) + layoutPanel() + findView(panel) { it.isClickable && it.contentDescription?.contains("候选") == true }?.performClick() + panel.closeTransientUi() + layoutPanel() + expandedVisible = findView(panel) { it is ScrollView }?.visibility == View.VISIBLE + } + assertFalse("closeTransientUi 应收起候选展开层", expandedVisible) + assertTrue(actions.isEmpty()) + } +} diff --git a/openless-all/android/kotlin/androidTest/ImeVoicePanelInstrumentedTest.kt b/openless-all/android/kotlin/androidTest/ImeVoicePanelInstrumentedTest.kt new file mode 100644 index 000000000..b54400be4 --- /dev/null +++ b/openless-all/android/kotlin/androidTest/ImeVoicePanelInstrumentedTest.kt @@ -0,0 +1,131 @@ +package com.openless.app + +import android.os.SystemClock +import android.view.MotionEvent +import android.view.View +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** Event-level coverage of the voice surface without microphone/network/JNI. */ +@RunWith(AndroidJUnit4::class) +class ImeVoicePanelInstrumentedTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val actions = mutableListOf() + private lateinit var button: ImeVoiceButton + private var startedAt = 0L + + private fun prepare(recording: Boolean = false) { + actions.clear() + val context = instrumentation.targetContext + button = ImeVoiceButton(context, ImePalette.resolve(false)) { actions += it } + button.isRecording = recording + val density = context.resources.displayMetrics.density + button.measure( + View.MeasureSpec.makeMeasureSpec((180 * density).toInt(), View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec((72 * density).toInt(), View.MeasureSpec.EXACTLY), + ) + button.layout(0, 0, button.measuredWidth, button.measuredHeight) + startedAt = SystemClock.uptimeMillis() + } + + private fun event(action: Int, dxDp: Float = 0f, dyDp: Float = 0f) { + val density = button.resources.displayMetrics.density + val event = MotionEvent.obtain( + startedAt, SystemClock.uptimeMillis(), action, + button.width / 2f + dxDp * density, + button.height / 2f + dyDp * density, 0, + ) + button.dispatchTouchEvent(event) + event.recycle() + } + + private fun swipe(dxDp: Float, dyDp: Float, recording: Boolean = false) { + instrumentation.runOnMainSync { + prepare(recording) + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_MOVE, dxDp, dyDp) + event(MotionEvent.ACTION_UP, dxDp, dyDp) + } + } + + @Test fun tapProducesExactlyOneAction() { + instrumentation.runOnMainSync { + prepare() + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_UP) + } + assertEquals(listOf(ImeVoiceGesture.TAP), actions) + } + + @Test fun swipeUpRequestsRawModeOnce() { + swipe(0f, -70f) + assertEquals(listOf(ImeVoiceGesture.RAW), actions) + } + + @Test fun swipeLeftRequestsQuickNoteOnce() { + swipe(-70f, 0f) + assertEquals(listOf(ImeVoiceGesture.QUICK_NOTE), actions) + } + + @Test fun swipeRightRequestsCloudNoteOnce() { + swipe(70f, 0f) + assertEquals(listOf(ImeVoiceGesture.CLOUD_NOTE), actions) + } + + @Test fun swipeDownCancelsOnlyAnActiveRecording() { + swipe(0f, 70f, recording = true) + assertEquals(listOf(ImeVoiceGesture.CANCEL), actions) + } + + @Test fun downwardDragWhileIdleDoesNotStartRecording() { + swipe(0f, 70f) + assertTrue(actions.isEmpty()) + } + + @Test fun cancelledTouchNeverCommitsThePreviewedAction() { + instrumentation.runOnMainSync { + prepare(recording = true) + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_MOVE, 0f, 70f) + event(MotionEvent.ACTION_CANCEL, 0f, 70f) + } + assertTrue(actions.isEmpty()) + } + + @Test fun terminalCoordinatesWinOverTheLastMovePreview() { + instrumentation.runOnMainSync { + prepare() + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_MOVE, 70f, 0f) + event(MotionEvent.ACTION_UP, -70f, 0f) + } + assertEquals(listOf(ImeVoiceGesture.QUICK_NOTE), actions) + } + + @Test fun returningToTheNeutralZoneClearsTheSwipePreview() { + instrumentation.runOnMainSync { + prepare() + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_MOVE, 70f, 0f) + event(MotionEvent.ACTION_MOVE) + event(MotionEvent.ACTION_UP) + } + assertEquals(listOf(ImeVoiceGesture.TAP), actions) + } + + @Test fun freshTapAfterCancellationDoesNotReuseOldGestureState() { + instrumentation.runOnMainSync { + prepare() + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_MOVE, 70f, 0f) + event(MotionEvent.ACTION_CANCEL, 70f, 0f) + event(MotionEvent.ACTION_DOWN) + event(MotionEvent.ACTION_UP) + } + assertEquals(listOf(ImeVoiceGesture.TAP), actions) + } +} diff --git a/openless-all/android/kotlin/test/ImeEditorFieldPolicyTest.kt b/openless-all/android/kotlin/test/ImeEditorFieldPolicyTest.kt new file mode 100644 index 000000000..676108f44 --- /dev/null +++ b/openless-all/android/kotlin/test/ImeEditorFieldPolicyTest.kt @@ -0,0 +1,17 @@ +package com.openless.app + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ImeEditorFieldPolicyTest { + @Test fun numericPhoneAndDateFieldsStartWithNumericKeys() { + for (type in listOf(0x2, 0x3, 0x4)) assertTrue(ImeEditorFieldPolicy.prefersNumeric(type)) + } + @Test fun numericFlagsAndVariationsKeepTheirClass() { + for (type in listOf(0x1002, 0x2002, 0x12, 0x3002, 0x24)) assertTrue(ImeEditorFieldPolicy.prefersNumeric(type)) + } + @Test fun ordinaryTextDoesNotOverwriteThePreferredPage() { + for (type in listOf(0, 0x1, 0x20001, 0x81, 0xe1)) assertFalse(ImeEditorFieldPolicy.prefersNumeric(type)) + } +} diff --git a/openless-all/android/kotlin/test/ImeGestureSessionTest.kt b/openless-all/android/kotlin/test/ImeGestureSessionTest.kt new file mode 100644 index 000000000..750b7cdf6 --- /dev/null +++ b/openless-all/android/kotlin/test/ImeGestureSessionTest.kt @@ -0,0 +1,130 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ImeGestureSessionTest { + private val gesture = ImeGestureSession(touchSlop = 8f) + + @Test fun tapDoesNotBecomeAModeSwipe() { + gesture.begin(0f, 0f, horizontal = true, down = true) + assertEquals(ImeGestureSession.Axis.NONE, gesture.move(4f, 2f)) + assertNull(release(4f, 2f)) + } + + @Test fun deliberateLeftSwipeCommitsOnce() { + gesture.begin(200f, 0f, horizontal = true) + assertEquals(ImeGestureSession.Axis.HORIZONTAL, gesture.move(180f, 0f)) + assertEquals(ImeGestureSession.Direction.LEFT, release(0f, 0f)) + assertNull(release(0f, 0f)) + } + + @Test fun deliberateRightSwipeCommits() { + gesture.begin(0f, 0f, horizontal = true) + gesture.move(20f, 0f) + assertEquals(ImeGestureSession.Direction.RIGHT, release(150f, 0f)) + } + + @Test fun touchSlopClaimsButDoesNotCommitAnAccidentalDrag() { + gesture.begin(0f, 0f, horizontal = true) + assertEquals(ImeGestureSession.Axis.HORIZONTAL, gesture.move(15f, 0f)) + assertNull(release(25f, 0f)) + } + + @Test fun cancelledSwipeNeverCommits() { + gesture.begin(0f, 0f, horizontal = true, down = true) + gesture.move(200f, 0f) + gesture.cancel() + assertNull(release(200f, 0f)) + } + + @Test fun cancelledDismissNeverHidesTheKeyboard() { + gesture.begin(0f, 0f, down = true) + gesture.move(0f, 200f) + gesture.cancel() + assertNull(release(0f, 200f)) + } + + @Test fun cancelledRailNeverChangesPage() { + gesture.begin(0f, 100f, up = true, down = true) + gesture.move(0f, 0f) + gesture.cancel() + assertNull(release(0f, 0f)) + } + + @Test fun nextDownStartsCleanAfterCancellation() { + gesture.begin(0f, 0f, horizontal = true) + gesture.move(200f, 0f) + gesture.cancel() + gesture.begin(50f, 50f, down = true) + gesture.move(50f, 80f) + assertEquals(ImeGestureSession.Direction.DOWN, release(50f, 200f)) + } + + @Test fun horizontalOwnerCannotTurnIntoADismiss() { + gesture.begin(0f, 0f, horizontal = true, down = true) + gesture.move(20f, 0f) + assertEquals(ImeGestureSession.Axis.HORIZONTAL, gesture.move(20f, 200f)) + assertNull(release(20f, 200f)) + } + + @Test fun verticalOwnerCannotTurnIntoAModeSwitch() { + gesture.begin(0f, 0f, horizontal = true, down = true) + gesture.move(0f, 20f) + assertEquals(ImeGestureSession.Axis.VERTICAL, gesture.move(200f, 20f)) + assertNull(release(200f, 20f)) + } + + @Test fun diagonalMotionDoesNotStealAChildGesture() { + gesture.begin(0f, 0f, horizontal = true, down = true) + assertEquals(ImeGestureSession.Axis.NONE, gesture.move(50f, 50f)) + assertNull(release(150f, 150f)) + } + + @Test fun disabledAxesStayWithTheChild() { + gesture.begin(0f, 0f) + assertEquals(ImeGestureSession.Axis.NONE, gesture.move(200f, 0f)) + assertEquals(ImeGestureSession.Axis.NONE, gesture.move(0f, 200f)) + assertNull(release(0f, 200f)) + } + + @Test fun nestedScrollCanRejectDismiss() { + gesture.begin(0f, 0f, down = true) + assertEquals(ImeGestureSession.Axis.NONE, gesture.move(0f, 30f, allowDown = false)) + assertNull(release(0f, 200f)) + } + + @Test fun upwardMotionCannotDismiss() { + gesture.begin(0f, 200f, down = true) + assertEquals(ImeGestureSession.Axis.NONE, gesture.move(0f, 0f)) + assertNull(release(0f, 0f)) + } + + @Test fun railCanPageInBothDirections() { + gesture.begin(0f, 100f, up = true, down = true) + gesture.move(0f, 80f) + assertEquals(ImeGestureSession.Direction.UP, release(0f, 0f)) + gesture.begin(0f, 0f, up = true, down = true) + gesture.move(0f, 20f) + assertEquals(ImeGestureSession.Direction.DOWN, release(0f, 100f)) + } + + @Test fun nonFiniteCoordinatesInvalidateTheSequence() { + gesture.begin(0f, 0f, horizontal = true) + gesture.move(20f, 0f) + gesture.move(Float.NaN, 0f) + assertNull(release(200f, 0f)) + gesture.begin(Float.POSITIVE_INFINITY, 0f, horizontal = true) + assertNull(release(200f, 0f)) + } + + @Test fun pressWithoutClaimCannotCommitFromTheReleaseLocation() { + gesture.begin(0f, 0f, horizontal = true) + assertNull(release(200f, 0f)) + } + + private fun release(x: Float, y: Float) = gesture.release( + x, y, horizontalThreshold = 100f, verticalThreshold = 60f, + ) +} diff --git a/openless-all/android/kotlin/test/ImeInteractionPolicyTest.kt b/openless-all/android/kotlin/test/ImeInteractionPolicyTest.kt new file mode 100644 index 000000000..95af02d1b --- /dev/null +++ b/openless-all/android/kotlin/test/ImeInteractionPolicyTest.kt @@ -0,0 +1,63 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** SDK-free JUnit4:只验证策略的默认值、边界收敛与值语义。 */ +class ImeInteractionPolicyTest { + + @Test + fun defaultIntervalIsSixtyMilliseconds() { + assertEquals(60L, ImeInteractionPolicy.DEFAULT.repeatIntervalMs) + } + + @Test + fun storedValueClampsToSupportedRange() { + assertEquals(30L, ImeInteractionPolicy.fromStoredRepeat(Long.MIN_VALUE).repeatIntervalMs) + assertEquals(30L, ImeInteractionPolicy.fromStoredRepeat(-1L).repeatIntervalMs) + assertEquals(30L, ImeInteractionPolicy.fromStoredRepeat(0L).repeatIntervalMs) + assertEquals(30L, ImeInteractionPolicy.fromStoredRepeat(29L).repeatIntervalMs) + assertEquals(30L, ImeInteractionPolicy.fromStoredRepeat(30L).repeatIntervalMs) + assertEquals(60L, ImeInteractionPolicy.fromStoredRepeat(60L).repeatIntervalMs) + assertEquals(120L, ImeInteractionPolicy.fromStoredRepeat(120L).repeatIntervalMs) + assertEquals(200L, ImeInteractionPolicy.fromStoredRepeat(200L).repeatIntervalMs) + assertEquals(200L, ImeInteractionPolicy.fromStoredRepeat(201L).repeatIntervalMs) + assertEquals(200L, ImeInteractionPolicy.fromStoredRepeat(Long.MAX_VALUE).repeatIntervalMs) + } + + @Test + fun everyStoredValueLandsInsideTheSupportedRange() { + var sample = -400L + while (sample <= 400L) { + val interval = ImeInteractionPolicy.fromStoredRepeat(sample).repeatIntervalMs + assertTrue("$sample -> $interval", interval in 30L..200L) + sample += 7L + } + } + + @Test + fun valueEqualityFollowsInterval() { + assertEquals(ImeInteractionPolicy.fromStoredRepeat(60L), ImeInteractionPolicy.DEFAULT) + assertEquals( + ImeInteractionPolicy.fromStoredRepeat(30L), + ImeInteractionPolicy.fromStoredRepeat(30L), + ) + assertNotEquals( + ImeInteractionPolicy.fromStoredRepeat(60L), + ImeInteractionPolicy.fromStoredRepeat(61L), + ) + assertNotEquals(ImeInteractionPolicy.DEFAULT, ImeInteractionPolicy.fromStoredRepeat(200L)) + } + + @Test + fun derivedPoliciesAreStableForSameInput() { + repeat(4) { + val first = ImeInteractionPolicy.fromStoredRepeat(45L) + val second = ImeInteractionPolicy.fromStoredRepeat(45L) + assertEquals(first, second) + assertEquals(45L, first.repeatIntervalMs) + } + } +} diff --git a/openless-all/android/kotlin/test/ImeKeyboardModelsTest.kt b/openless-all/android/kotlin/test/ImeKeyboardModelsTest.kt new file mode 100644 index 000000000..51f1ca1be --- /dev/null +++ b/openless-all/android/kotlin/test/ImeKeyboardModelsTest.kt @@ -0,0 +1,307 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 纯 JVM 断言:布局数据、层切换键、大小写、权重与主题不透明度。 + * 不涉及 Android 框架,也不验证真机渲染。 + */ +class ImeKeyboardModelsTest { + + private fun rows( + layer: ImeKeyboardLayer = ImeKeyboardLayer.LETTERS, + language: ImeTypingLanguage = ImeTypingLanguage.ENGLISH, + letterCase: ImeLetterCase = ImeLetterCase.LOWER, + enterLabel: String = "Enter", + ): List> = ImeKeyboardLayouts.rows(layer, language, letterCase, enterLabel) + + private fun allKeys( + layer: ImeKeyboardLayer = ImeKeyboardLayer.LETTERS, + language: ImeTypingLanguage = ImeTypingLanguage.ENGLISH, + letterCase: ImeLetterCase = ImeLetterCase.LOWER, + ): List = rows(layer, language, letterCase).flatten() + + private fun List.findByAction(action: ImeKeyAction): ImeKeySpec? = + firstOrNull { it.action == action } + + private fun List.findByLabel(label: String): ImeKeySpec? = + firstOrNull { it.label == label } + + private fun textValue(action: ImeKeyAction): String? = (action as? ImeKeyAction.Text)?.value + + // --- 结构 --- + + @Test + fun lettersLayoutHasThreeTypingRowsPlusBottomRow() { + val layout = rows() + assertEquals(4, layout.size) + assertEquals(10, layout[0].size) + assertEquals(9, layout[1].size) // 两侧半键留白由 View 加 inset,模型不出 spacer + assertEquals(9, layout[2].size) // Shift + 7 字母 + Backspace + assertEquals(6, layout[3].size) // 123 / 中EN / , / Space / . / Enter + } + + @Test + fun lettersBottomRowMatchesLanguagePunctuation() { + val zhBottom = rows(language = ImeTypingLanguage.PINYIN)[3] + assertEquals(listOf("123", "中", ",", "Space", "。", "Enter"), zhBottom.map { it.label }) + val enBottom = rows(language = ImeTypingLanguage.ENGLISH)[3] + assertEquals(listOf("123", "EN", ",", "Space", ".", "Enter"), enBottom.map { it.label }) + val numBottom = rows(layer = ImeKeyboardLayer.NUMBERS, language = ImeTypingLanguage.PINYIN)[3] + assertEquals(listOf("ABC", "中", "Space", "Enter"), numBottom.map { it.label }) + } + + @Test + fun lettersRowOneCarriesDigitSecondaries() { + val row = rows()[0] + assertEquals(listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"), row.map { it.secondary }) + assertEquals(listOf("q", "w", "e", "r", "t", "y", "u", "i", "o", "p"), row.map { it.label }) + } + + @Test + fun lettersRowTwoAndThreeCarrySymbolSecondaries() { + val secondaries = rows().drop(1) + assertEquals( + listOf("~", "@", "#", "!", "%", "&", "*", "(", ")"), + secondaries[0].map { it.secondary }, + ) + assertEquals( + listOf("'", "/", "-", "_", ":", ";", "?"), + secondaries[1].filter { it.secondary != null }.map { it.secondary }, + ) + } + + @Test + fun lettersRowThreeStartsWithShiftAndEndsWithBackspace() { + val row = rows()[2] + assertEquals(ImeKeyAction.Shift, row.first().action) + assertEquals(ImeKeyAction.Backspace, row.last().action) + assertTrue(row.first().auxiliary) + assertTrue(row.last().auxiliary) + } + + @Test + fun numbersLayerMirrorsExistingLayout() { + val layout = rows(layer = ImeKeyboardLayer.NUMBERS) + assertEquals(4, layout.size) + assertEquals(listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"), layout[0].map { it.label }) + assertEquals( + listOf("-", "/", ":", ";", "(", ")", "$", "&", "@", "\""), + layout[1].map { it.label }, + ) + assertEquals("#+=", layout[2].first().label) + assertEquals(listOf(".", ",", "?", "!", "'"), layout[2].drop(1).dropLast(1).map { it.label }) + assertEquals(ImeKeyAction.Backspace, layout[2].last().action) + } + + @Test + fun symbolsLayerMirrorsExistingLayout() { + val layout = rows(layer = ImeKeyboardLayer.SYMBOLS) + assertEquals(listOf("[", "]", "{", "}", "#", "%", "^", "*", "+", "="), layout[0].map { it.label }) + assertEquals( + listOf("_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"), + layout[1].map { it.label }, + ) + assertEquals("123", layout[2].first().label) + } + + // --- 大小写 --- + + @Test + fun textValuesFollowLetterCase() { + val lower = allKeys(letterCase = ImeLetterCase.LOWER).findByLabel("q") + val shift = allKeys(letterCase = ImeLetterCase.SHIFT).findByLabel("Q") + val caps = allKeys(letterCase = ImeLetterCase.CAPS_LOCK).findByLabel("Q") + assertEquals("q", lower?.let { textValue(it.action) }) + assertEquals("Q", shift?.let { textValue(it.action) }) + assertEquals("Q", caps?.let { textValue(it.action) }) + assertEquals("Q", shift?.label) + assertEquals("Q", caps?.label) + } + + @Test + fun letterCaseDoesNotAlterPunctuationOrSecondaries() { + val shifted = allKeys(letterCase = ImeLetterCase.SHIFT) + // 数字/符号只作为 secondary 存在,不因大小写变化。 + val q = shifted.findByLabel("Q") + assertEquals("1", q?.secondary) + val a = shifted.findByLabel("A") + assertEquals("~", a?.secondary) + + val numbers = allKeys(layer = ImeKeyboardLayer.NUMBERS, letterCase = ImeLetterCase.SHIFT) + assertEquals("1", numbers.findByLabel("1")?.let { textValue(it.action) }) + } + + // --- 层切换键 --- + + @Test + fun bottomModeKeyTogglesNumbersAndLabelsReflectLayer() { + val lettersBottom = rows(layer = ImeKeyboardLayer.LETTERS)[3].findByAction(ImeKeyAction.ToggleNumbers) + assertEquals("123", lettersBottom?.label) + assertEquals(1.3f, lettersBottom!!.weight, 0.0001f) + + for (layer in listOf(ImeKeyboardLayer.NUMBERS, ImeKeyboardLayer.SYMBOLS)) { + val bottom = rows(layer = layer)[3].findByAction(ImeKeyAction.ToggleNumbers) + assertEquals("ABC", bottom?.label) + assertEquals("mode_numbers", bottom?.id) + } + } + + @Test + fun rowThreeToggleSwitchesBetweenNumbersAndSymbols() { + val numbersToggle = rows(layer = ImeKeyboardLayer.NUMBERS)[2].findByAction(ImeKeyAction.ToggleSymbols) + assertEquals("#+=", numbersToggle?.label) + assertEquals("mode_symbols", numbersToggle?.id) + + val symbolsToggle = rows(layer = ImeKeyboardLayer.SYMBOLS)[2].findByAction(ImeKeyAction.ToggleSymbols) + assertEquals("123", symbolsToggle?.label) + assertEquals("mode_numbers_row3", symbolsToggle?.id) + } + + // --- 底行其余按键 --- + + @Test + fun languageKeyIsExplicitAndShowsCurrentLanguage() { + val pinyin = rows(language = ImeTypingLanguage.PINYIN)[3].findByAction(ImeKeyAction.Language) + assertEquals("中", pinyin?.label) + assertEquals(1.1f, pinyin!!.weight, 0.0001f) + assertTrue(pinyin.auxiliary) + + val english = rows(language = ImeTypingLanguage.ENGLISH)[3].findByAction(ImeKeyAction.Language) + assertEquals("EN", english?.label) + } + + @Test + fun spaceAndEnterArePresentWithSpecWeights() { + val bottom = rows(enterLabel = "搜索")[3] + val space = bottom.findByAction(ImeKeyAction.Space) + assertEquals("Space", space?.label) + assertEquals(3.5f, space!!.weight, 0.0001f) + assertNull(space.secondary) + + val enter = bottom.findByAction(ImeKeyAction.Enter) + assertEquals("搜索", enter?.label) + assertEquals(1.8f, enter!!.weight, 0.0001f) + } + + @Test + fun everyLayoutHasExactlyOneSpaceEnterAndLanguageKey() { + for (layer in ImeKeyboardLayer.entries) { + for (language in ImeTypingLanguage.entries) { + val keys = allKeys(layer = layer, language = language) + assertEquals(1, keys.count { it.action == ImeKeyAction.Space }) + assertEquals(1, keys.count { it.action == ImeKeyAction.Enter }) + assertEquals(1, keys.count { it.action == ImeKeyAction.Language }) + } + } + } + + // --- 通用不变量 --- + + @Test + fun idsAreUniqueAndStableAcrossEveryConfiguration() { + for (layer in ImeKeyboardLayer.entries) { + for (language in ImeTypingLanguage.entries) { + for (letterCase in ImeLetterCase.entries) { + val ids = allKeys(layer = layer, language = language, letterCase = letterCase) + .map { it.id } + assertEquals( + "duplicate id in $layer/$language/$letterCase", + ids.size, + ids.toSet().size, + ) + assertTrue("blank id in $layer/$language/$letterCase", ids.none { it.isBlank() }) + } + } + } + } + + @Test + fun allWeightsArePositive() { + for (layer in ImeKeyboardLayer.entries) { + for (letterCase in ImeLetterCase.entries) { + allKeys(layer = layer, letterCase = letterCase).forEach { key -> + assertTrue("non-positive weight on ${key.id}", key.weight > 0f) + assertTrue("unexpectedly large weight on ${key.id}", key.weight <= 5f) + } + } + } + } + + @Test + fun textActionsKeepTheirVisibleValue() { + for (layer in ImeKeyboardLayer.entries) { + for (letterCase in ImeLetterCase.entries) { + allKeys(layer = layer, letterCase = letterCase).forEach { key -> + val value = textValue(key.action) + if (value != null) { + assertEquals("label/action mismatch on ${key.id}", key.label, value) + } + } + } + } + } + + @Test + fun secondariesOnlyAppearOnLetterLayers() { + for (layer in listOf(ImeKeyboardLayer.NUMBERS, ImeKeyboardLayer.SYMBOLS)) { + assertTrue(allKeys(layer = layer).all { it.secondary == null }) + } + } + + // --- 主题 --- + + @Test + fun paletteIsOpaqueInBothThemes() { + for (dark in listOf(true, false)) { + val palette = ImePalette.resolve(dark) + val colors = listOf( + palette.surface, palette.key, palette.auxiliary, palette.accent, + palette.text, palette.secondaryText, palette.separator, + palette.pressed, palette.error, + ) + colors.forEach { color -> + assertEquals("alpha must be 0xFF for $color (dark=$dark)", 0xFF, (color ushr 24) and 0xFF) + } + } + } + + @Test + fun accentIsBlueWhileErrorStaysRed() { + for (dark in listOf(true, false)) { + val palette = ImePalette.resolve(dark) + val accentBlue = palette.accent and 0xFF + val accentRed = (palette.accent ushr 16) and 0xFF + assertTrue("accent should lean blue (dark=$dark)", accentBlue > accentRed) + + val errorRed = (palette.error ushr 16) and 0xFF + val errorBlue = palette.error and 0xFF + assertTrue("error should lean red (dark=$dark)", errorRed > errorBlue) + } + } + + @Test + fun darkAndLightPalettesAreDistinct() { + val dark = ImePalette.resolve(true) + val light = ImePalette.resolve(false) + assertNotEquals(dark.surface, light.surface) + assertNotEquals(dark.key, light.key) + assertNotEquals(dark.auxiliary, light.auxiliary) + assertNotEquals(dark.text, light.text) + assertNotEquals(dark.separator, light.separator) + assertNotEquals(dark.pressed, light.pressed) + } + + @Test + fun separatorAndKeyStayDistinguishable() { + for (dark in listOf(true, false)) { + val palette = ImePalette.resolve(dark) + assertNotEquals("separator must differ from key surface", palette.key, palette.separator) + assertNotEquals("pressed must differ from key surface", palette.key, palette.pressed) + } + } +} diff --git a/openless-all/android/kotlin/test/ImeScopedFrameGateTest.kt b/openless-all/android/kotlin/test/ImeScopedFrameGateTest.kt new file mode 100644 index 000000000..7cabab4e8 --- /dev/null +++ b/openless-all/android/kotlin/test/ImeScopedFrameGateTest.kt @@ -0,0 +1,475 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * SDK-free JUnit4:只验证帧门禁的归属/缓冲/退休语义,不依赖 Android/Service/JNI。 + */ +class ImeScopedFrameGateTest { + + private fun owner(epoch: Long, requestId: Long) = ImeRequestOwner(epoch, requestId) + + private fun frame( + sessionId: String?, + state: String = "recording", + message: String? = null, + level: Float = 0f, + ) = ImeCapsuleFrame(sessionId = sessionId, state = state, message = message, level = level) + + // --- 缓冲与 flush --- + + @Test + fun framesBeforeBindAreBufferedAndFlushedOnBind() { + val gate = ImeScopedFrameGate() + val o = owner(1, 10) + gate.begin(o) + + assertEquals(ImeFrameDisposition.BUFFERED, gate.accept(frame("A", "recording"))) + assertEquals(ImeFrameDisposition.BUFFERED, gate.accept(frame("A", "done", "ok", 0.7f))) + assertEquals(1, gate.bufferedCount) + + val flushed = gate.bind(o, "A") + assertEquals("done", flushed?.state) + assertEquals("ok", flushed?.message) + assertEquals(0.7f, flushed?.level ?: -1f, 0f) + assertEquals(0, gate.bufferedCount) + + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A", "transcribing"))) + } + + @Test + fun bufferedFramesForOtherIdsDoNotBecomeOwned() { + val gate = ImeScopedFrameGate() + val o = owner(1, 10) + gate.begin(o) + gate.accept(frame("B")) + gate.accept(frame("C")) + + assertNull("绑定 A 时不能 flush B/C 的帧", gate.bind(o, "A")) + assertEquals(0, gate.bufferedCount) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("B"))) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("C"))) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun freshIdBeforeBindIsBufferedButNeverOwned() { + val gate = ImeScopedFrameGate() + gate.begin(owner(2, 20)) + assertEquals(ImeFrameDisposition.BUFFERED, gate.accept(frame("real-id", "level", null, 0.3f))) + assertEquals(1, gate.bufferedCount) + } + + // --- 无 id / 无 owner --- + + @Test + fun framesWithoutIdAreUnidentifiedAndCannotChangeOwnState() { + val gate = ImeScopedFrameGate() + val o = owner(3, 30) + gate.begin(o) + gate.bind(o, "A") + + assertEquals(ImeFrameDisposition.UNIDENTIFIED, gate.accept(frame(null))) + assertEquals(ImeFrameDisposition.UNIDENTIFIED, gate.accept(frame(""))) + assertEquals(ImeFrameDisposition.UNIDENTIFIED, gate.accept(frame(" "))) + // 无 id 帧不进缓存,也不影响绑定。 + assertEquals(0, gate.bufferedCount) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun framesWithoutOwnerAreExternal() { + val gate = ImeScopedFrameGate() + assertEquals(ImeFrameDisposition.EXTERNAL, gate.accept(frame("A"))) + assertEquals(ImeFrameDisposition.EXTERNAL, gate.accept(frame(null))) + assertEquals(ImeFrameDisposition.EXTERNAL, gate.accept(frame(" "))) + assertEquals(0, gate.bufferedCount) + } + + @Test + fun blankIdIsNotRetirable() { + val gate = ImeScopedFrameGate() + gate.retire("") + gate.retire(" ") + assertEquals(0, gate.retiredCount) + } + + // --- 归属与绑定 --- + + @Test + fun otherSessionIdIsForeignOnceBound() { + val gate = ImeScopedFrameGate() + val o = owner(4, 40) + gate.begin(o) + gate.bind(o, "A") + + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("B"))) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun bindRejectsWrongOwnerBlankAndRetiredIds() { + val gate = ImeScopedFrameGate() + val o = owner(5, 50) + gate.begin(o) + + assertNull(gate.bind(owner(9, 90), "A")) + assertNull(gate.bind(o, "")) + assertNull(gate.bind(o, " ")) + + gate.retire("R") + assertNull(gate.bind(o, "R")) + // 拒绝的 bind 不应改变可用状态:仍可绑定真实的非退休 id。 + assertNull(gate.bind(o, "A")) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun bindCannotRebindToAnotherId() { + val gate = ImeScopedFrameGate() + val o = owner(6, 60) + gate.begin(o) + gate.bind(o, "A") + + assertNull(gate.bind(o, "B")) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("B"))) + } + + @Test + fun repeatBindIsIdempotentAndKeepsTarget() { + val gate = ImeScopedFrameGate() + val o = owner(7, 70) + gate.begin(o) + assertNull(gate.bind(o, "A")) + + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + assertNull("重复 bind 不应清掉目标", gate.bind(o, "A")) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun bindClearsAllBufferedFrames() { + val gate = ImeScopedFrameGate() + val o = owner(8, 80) + gate.begin(o) + gate.accept(frame("A", "recording")) + gate.accept(frame("B", "recording")) + assertEquals(2, gate.bufferedCount) + + val flushed = gate.bind(o, "A") + assertEquals("A", flushed?.sessionId) + assertEquals(0, gate.bufferedCount) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("B"))) + } + + // --- isBound(只读确认) --- + + @Test + fun isBoundIsFalseBeforeBindAndTrueAfterwards() { + val gate = ImeScopedFrameGate() + val o = owner(30, 300) + gate.begin(o) + assertTrue(!gate.isBound(o, "A")) + + assertNull(gate.bind(o, "A")) + assertTrue(gate.isBound(o, "A")) + // 重复 bind(无缓存时返回 null)后仍处于已绑定状态。 + assertNull(gate.bind(o, "A")) + assertTrue(gate.isBound(o, "A")) + } + + @Test + fun isBoundDistinguishesRejectedBindFromEmptyBuffer() { + val gate = ImeScopedFrameGate() + val o = owner(31, 310) + gate.begin(o) + gate.accept(frame("A", "done")) + + val flushed = gate.bind(o, "A") + assertEquals("done", flushed?.state) + assertTrue("bind 有缓存时返回帧且 isBound 为真", gate.isBound(o, "A")) + + val otherGate = ImeScopedFrameGate() + otherGate.begin(o) + assertNull("无缓存时 bind 返回 null 但不代表拒绝", otherGate.bind(o, "B")) + assertTrue("无缓存但绑定成功 → isBound 为真", otherGate.isBound(o, "B")) + assertTrue("被拒绝的 bind(错误 owner)→ isBound 为假", !otherGate.isBound(owner(9, 90), "B")) + } + + @Test + fun isBoundRejectsOldOwnerOtherIdsAndBlankIds() { + val gate = ImeScopedFrameGate() + val o = owner(32, 320) + gate.begin(o) + gate.bind(o, "A") + + assertTrue(!gate.isBound(o, "B")) + assertTrue(!gate.isBound(o, "")) + assertTrue(!gate.isBound(o, " ")) + assertTrue("不 trim,opaque 精确匹配", !gate.isBound(o, " A")) + assertTrue(!gate.isBound(owner(32, 321), "A")) + assertTrue(!gate.isBound(owner(99, 320), "A")) + } + + @Test + fun isBoundIsFalseAfterFinishAndRetire() { + val gate = ImeScopedFrameGate() + val o = owner(33, 330) + gate.begin(o) + gate.bind(o, "A") + assertTrue(gate.isBound(o, "A")) + + gate.finish(o) + assertTrue(!gate.isBound(o, "A")) + assertTrue(!gate.isBound(owner(33, 331), "A")) + + val other = ImeScopedFrameGate() + other.retire("X") + other.begin(o) + assertTrue("退休 id 不能被认为已绑定", !other.isBound(o, "X")) + } + + @Test + fun isBoundStaysTrueAfterMisplacedRetireOfActiveId() { + val gate = ImeScopedFrameGate() + val o = owner(34, 340) + gate.begin(o) + gate.bind(o, "A") + + gate.retire("A") // active retire no-op + assertTrue("误 retire 活跃 id 后绑定必须保持", gate.isBound(o, "A")) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + + gate.finish(o) + assertTrue(!gate.isBound(o, "A")) + } + + // --- begin / finish 与退休 --- + + @Test + fun beginRetiresPreviousBoundId() { + val gate = ImeScopedFrameGate() + val first = owner(9, 90) + val second = owner(9, 91) + gate.begin(first) + gate.bind(first, "old-id") + + gate.begin(second) + assertEquals("旧绑定 id 的迟到帧必须 STALE", ImeFrameDisposition.STALE, gate.accept(frame("old-id"))) + assertEquals(ImeFrameDisposition.BUFFERED, gate.accept(frame("new-id"))) + assertEquals("new-id", gate.bind(second, "new-id")?.sessionId) + } + + @Test + fun finishRetiresBoundIdAndLateFramesAreStale() { + val gate = ImeScopedFrameGate() + val o = owner(10, 100) + gate.begin(o) + gate.bind(o, "A") + gate.finish(o) + + assertEquals(1, gate.retiredCount) + assertEquals(ImeFrameDisposition.STALE, gate.accept(frame("A"))) + // 结束后回到无 owner:其他 id 一律 EXTERNAL。 + assertEquals(ImeFrameDisposition.EXTERNAL, gate.accept(frame("B"))) + } + + @Test + fun finishWithNullOwnerIsNoOp() { + val gate = ImeScopedFrameGate() + val o = owner(11, 110) + gate.begin(o) + gate.bind(o, "A") + gate.finish(null) + + assertEquals("无主清理不能结束当前 owner", ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun staleOwnerCannotBindOrFinishNewOwner() { + val gate = ImeScopedFrameGate() + val oldOwner = owner(12, 120) + val newOwner = owner(12, 121) + gate.begin(oldOwner) + gate.bind(oldOwner, "old-id") + gate.begin(newOwner) + + assertNull("过期 owner 不能 bind", gate.bind(oldOwner, "new-id")) + gate.finish(oldOwner) + assertEquals("过期 owner 不能 finish 新 owner", ImeFrameDisposition.BUFFERED, gate.accept(frame("new-id"))) + assertEquals("new-id", gate.bind(newOwner, "new-id")?.sessionId) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("new-id"))) + } + + @Test + fun finishClearsBuffer() { + val gate = ImeScopedFrameGate() + val o = owner(13, 130) + gate.begin(o) + gate.accept(frame("A")) + assertEquals(1, gate.bufferedCount) + gate.finish(o) + assertEquals(0, gate.bufferedCount) + } + + @Test + fun beginClearsBuffer() { + val gate = ImeScopedFrameGate() + val first = owner(14, 140) + gate.begin(first) + gate.accept(frame("A")) + gate.begin(owner(14, 141)) + assertEquals(0, gate.bufferedCount) + } + + // --- retire --- + + @Test + fun retiredBufferedIdIsRemovedAndCannotBeBound() { + val gate = ImeScopedFrameGate() + val o = owner(15, 150) + gate.begin(o) + gate.accept(frame("A")) + assertEquals(1, gate.bufferedCount) + + gate.retire("A") + assertEquals(0, gate.bufferedCount) + assertNull(gate.bind(o, "A")) + assertEquals(ImeFrameDisposition.STALE, gate.accept(frame("A"))) + } + + @Test + fun retireOfActiveBoundIdIsNoOpAndDoesNotSilenceLiveSession() { + val gate = ImeScopedFrameGate() + val o = owner(16, 160) + gate.begin(o) + gate.bind(o, "A") + + // 误把当前 active id 传给 retire:必须 no-op,活跃帧仍然 OWNED。 + gate.retire("A") + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + assertEquals(0, gate.retiredCount) + // 绑定仍是 A:其他 id 依旧 FOREIGN。 + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("B"))) + + // 只有 finish 才真正退休旧绑定 id,之后迟到帧才 STALE。 + gate.finish(o) + assertEquals(1, gate.retiredCount) + assertEquals(ImeFrameDisposition.STALE, gate.accept(frame("A"))) + } + + @Test + fun retiredIdWinsOverOwnerBuffering() { + val gate = ImeScopedFrameGate() + gate.retire("dead-id") + gate.begin(owner(17, 170)) + assertEquals(ImeFrameDisposition.STALE, gate.accept(frame("dead-id"))) + assertEquals(0, gate.bufferedCount) + } + + // --- 边界 --- + + @Test + fun bufferIsBoundedAndEvictsOldest() { + val gate = ImeScopedFrameGate(bufferLimit = 2) + val o = owner(18, 180) + gate.begin(o) + gate.accept(frame("A", "recording")) + gate.accept(frame("B", "recording")) + gate.accept(frame("C", "recording")) + assertEquals(2, gate.bufferedCount) + + // 最旧的 A 已被逐出,bind A 得不到帧;C 仍可 flush。 + assertNull(gate.bind(o, "A")) + assertEquals(0, gate.bufferedCount) + } + + @Test + fun bufferKeepsLatestFramePerIdAndRefreshesRecency() { + val gate = ImeScopedFrameGate(bufferLimit = 2) + val o = owner(19, 190) + gate.begin(o) + gate.accept(frame("A", "recording")) + gate.accept(frame("B", "recording")) + gate.accept(frame("A", "done")) // A 刷新为最新 + 最新内容 + gate.accept(frame("C", "recording")) // 逐出最久未更新的 B + assertEquals(2, gate.bufferedCount) + + // A 被刷新过所以仍在缓存里,且返回的是最新内容 "done"。 + val flushed = gate.bind(o, "A") + assertEquals("done", flushed?.state) + } + + @Test + fun retiredIsBoundedAndEvictsOldest() { + val gate = ImeScopedFrameGate(retiredLimit = 2) + gate.retire("A") + gate.retire("B") + gate.retire("C") + assertEquals(2, gate.retiredCount) + + // A 已被逐出 → 不再 STALE;C 仍在。 + assertEquals(ImeFrameDisposition.EXTERNAL, gate.accept(frame("A"))) + assertEquals(ImeFrameDisposition.STALE, gate.accept(frame("C"))) + } + + @Test + fun limitsAreCoercedToAtLeastOne() { + val gate = ImeScopedFrameGate(bufferLimit = 0, retiredLimit = -5) + val o = owner(20, 200) + gate.begin(o) + gate.accept(frame("A")) + gate.accept(frame("B")) + assertEquals(1, gate.bufferedCount) + + gate.retire("X") + gate.retire("Y") + assertEquals(1, gate.retiredCount) + } + + // --- opaque id 语义 --- + + @Test + fun idsAreExactOpaqueMatchWithoutTrimOrCaseFold() { + val gate = ImeScopedFrameGate() + val o = owner(21, 210) + gate.begin(o) + gate.bind(o, "A") + + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("A "))) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame(" A"))) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("a"))) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(frame("A"))) + } + + @Test + fun whitespaceAroundBufferedIdIsNotTrimmed() { + val gate = ImeScopedFrameGate() + val o = owner(22, 220) + gate.begin(o) + gate.accept(frame("A ", "recording")) + gate.accept(frame("A", "done")) + + val flushed = gate.bind(o, "A") + assertEquals("done", flushed?.state) + assertEquals(ImeFrameDisposition.FOREIGN, gate.accept(frame("A "))) + } + + // --- 帧内容不被解释 --- + + @Test + fun frameStateMessageAndLevelAreNotInterpretedByGate() { + val gate = ImeScopedFrameGate() + val o = owner(23, 230) + gate.begin(o) + val weird = ImeCapsuleFrame("A", "totally-unknown-state", "long message ✓", 0.25f) + assertEquals(ImeFrameDisposition.BUFFERED, gate.accept(weird)) + val flushed = gate.bind(o, "A") + assertEquals(weird, flushed) + assertEquals(ImeFrameDisposition.OWNED, gate.accept(weird)) + } +} diff --git a/openless-all/android/kotlin/test/ImeSelectionPolicyTest.kt b/openless-all/android/kotlin/test/ImeSelectionPolicyTest.kt new file mode 100644 index 000000000..ec7c47622 --- /dev/null +++ b/openless-all/android/kotlin/test/ImeSelectionPolicyTest.kt @@ -0,0 +1,189 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * [ImeSelectionPolicy] 的纯 JVM 单测(NoNative/NoIO)。 + * + * 只验证 UTF-16/codepoint 语义:不宣称完整 grapheme cluster(ZWJ 序列按 codepoint 单步)。 + */ +class ImeSelectionPolicyTest { + + private fun extend( + text: CharSequence?, + startOffset: Int = 0, + selectionStart: Int, + selectionEnd: Int, + previous: ImeSelectionRange? = null, + direction: Int, + ): ImeSelectionRange? = ImeSelectionPolicy.extend( + text, startOffset, selectionStart, selectionEnd, previous, direction, + ) + + private fun assertRange(anchor: Int, active: Int, actual: ImeSelectionRange?) { + assertTrue("expected ($anchor,$active) but was $actual", actual != null) + assertEquals(anchor, actual!!.anchor) + assertEquals(active, actual.active) + } + + private fun isInsideSurrogatePair(text: CharSequence, index: Int): Boolean = + index > 0 && index < text.length && + Character.isHighSurrogate(text[index - 1]) && + Character.isLowSurrogate(text[index]) + + @Test + fun asciiSelectionExtendsAndShrinksByOne() { + assertEquals(ImeSelectionRange(1, 4), extend("hello", selectionStart = 1, selectionEnd = 3, direction = 1)) + assertEquals(ImeSelectionRange(1, 2), extend("hello", selectionStart = 1, selectionEnd = 3, direction = -1)) + } + + @Test + fun partialStartOffsetProducesAbsoluteOffsets() { + val text = "abcdef" + assertRange(12, 15, extend(text, startOffset = 10, selectionStart = 2, selectionEnd = 4, direction = 1)) + assertRange(12, 13, extend(text, startOffset = 10, selectionStart = 2, selectionEnd = 4, direction = -1)) + } + + @Test + fun unknownOrInvalidInputsReturnNullWithoutGuessingZero() { + assertNull("null text", extend(null, selectionStart = 0, selectionEnd = 1, direction = 1)) + assertNull("negative offset", extend("abc", startOffset = -1, selectionStart = 0, selectionEnd = 1, direction = 1)) + assertNull("negative start", extend("abc", selectionStart = -1, selectionEnd = 1, direction = 1)) + assertNull("negative end", extend("abc", selectionStart = 0, selectionEnd = -1, direction = 1)) + assertNull("end past text", extend("abc", selectionStart = 0, selectionEnd = 4, direction = 1)) + assertNull("start past text", extend("abc", selectionStart = 5, selectionEnd = 5, direction = 1)) + assertNull( + "Int overflow", + extend("abc", startOffset = Int.MAX_VALUE, selectionStart = 0, selectionEnd = 1, direction = 1), + ) + assertNull( + "Int overflow 2", + extend("abc", startOffset = Int.MAX_VALUE - 1, selectionStart = 2, selectionEnd = 2, direction = -1), + ) + } + + @Test + fun invalidDirectionAlwaysReturnsNull() { + listOf(0, 2, -2, Int.MIN_VALUE, Int.MAX_VALUE).forEach { direction -> + assertNull( + "direction=$direction", + extend("abc", selectionStart = 1, selectionEnd = 1, direction = direction), + ) + } + } + + @Test + fun existingRangeIsReusedWhenLiveSelectionMatches() { + val text = "abcdef" + // previous 的 min/max 与当前绝对 selection (12,15) 完全一致 → 保留 anchor,移动 active。 + val grew = extend( + text, startOffset = 10, selectionStart = 2, selectionEnd = 5, + previous = ImeSelectionRange(12, 15), direction = 1, + ) + assertRange(12, 16, grew) + val shrank = extend( + text, startOffset = 10, selectionStart = 2, selectionEnd = 5, + previous = ImeSelectionRange(12, 15), direction = -1, + ) + assertRange(12, 14, shrank) + } + + @Test + fun reversedPreviousKeepsItsAnchorDirection() { + val text = "abcdef" + // 反向选择:anchor > active,但 min/max 仍与 live selection 一致 → 复用。 + val result = extend( + text, startOffset = 10, selectionStart = 2, selectionEnd = 5, + previous = ImeSelectionRange(15, 12), direction = -1, + ) + assertRange(15, 11, result) + } + + @Test + fun externalCaretMovementRebasesOnLiveSelection() { + val text = "abcdefghij" + val result = extend( + text, startOffset = 10, selectionStart = 3, selectionEnd = 3, + previous = ImeSelectionRange(12, 15), direction = 1, + ) + // 外部把 caret 挪到 13:不得沿用旧 anchor 12。 + assertRange(13, 14, result) + } + + @Test + fun initialRangeFollowsSelectionOrder() { + // 初始 range 的 anchor/active 直接来自 selectionStart/End(保持调用方顺序)。 + assertRange(3, 2, extend("abcd", selectionStart = 3, selectionEnd = 1, direction = 1)) + assertRange(3, 0, extend("abcd", selectionStart = 3, selectionEnd = 1, direction = -1)) + } + + @Test + fun emojiIsNeverSplitAcrossSurrogatePairs() { + val text = "a\uD83D\uDE00b" // a😀b, len=4 + // 从 'a' 之后向右:必须跨过一个完整 codepoint(1 → 3),不能停在 2。 + assertRange(1, 3, extend(text, selectionStart = 1, selectionEnd = 1, direction = 1)) + // 从 'b' 之前向左:必须回到 1,不能停在 2。 + assertRange(3, 1, extend(text, selectionStart = 3, selectionEnd = 3, direction = -1)) + // 落在 surrogate pair 中间一律 null。 + assertNull(extend(text, selectionStart = 2, selectionEnd = 2, direction = 1)) + assertNull(extend(text, selectionStart = 1, selectionEnd = 2, direction = 1)) + } + + @Test + fun boundaryExtremesKeepOriginalRange() { + assertEquals(ImeSelectionRange(0, 0), extend("ab", selectionStart = 0, selectionEnd = 0, direction = -1)) + assertEquals(ImeSelectionRange(2, 2), extend("ab", selectionStart = 2, selectionEnd = 2, direction = 1)) + assertEquals( + ImeSelectionRange(1, 1), + extend("a", selectionStart = 1, selectionEnd = 1, direction = 1), + ) + } + + @Test + fun chainedEmojiStepsNeverLandInsidePairAndStayMonotonic() { + val text = "a\uD83D\uDE00b\uD83D\uDE01c" // a😀b😃c, len=7 + var selection = extend(text, selectionStart = 0, selectionEnd = 0, direction = 1)!! + assertEquals(ImeSelectionRange(0, 1), selection) + var previous: ImeSelectionRange? = selection + var lastActive = selection.active + repeat(6) { + val active = selection.active + val next = extend( + text, selectionStart = active, selectionEnd = active, + previous = previous, direction = 1, + ) + if (next == null) return@repeat + assertFalse( + "active=${next.active} 落在 surrogate pair 中间", + isInsideSurrogatePair(text, next.active), + ) + assertFalse( + "anchor=${next.anchor} 落在 surrogate pair 中间", + isInsideSurrogatePair(text, next.anchor), + ) + assertTrue("active 应单调前进", next.active >= lastActive) + lastActive = next.active + previous = next + selection = next + } + assertEquals("应停在文本末尾", text.length, selection.active) + } + + @Test + fun zwjSequencesAdvanceAsCodepointsNotWholeGraphemes() { + // 👨‍👩 = man(0,1) + ZWJ(2) + woman(3,4),len=5。 + val text = "\uD83D\uDC68\u200D\uD83D\uDC69" + val first = extend(text, selectionStart = 0, selectionEnd = 0, direction = 1) + assertRange(0, 2, first) // 一次只跨 man 这一个 codepoint + val second = extend( + text, selectionStart = 0, selectionEnd = 2, + previous = first, direction = 1, + ) + // 只承诺 codepoint 粒度:下一步走到 ZWJ 之后(3),不假装一次跳过整个 ZWJ 序列。 + assertRange(0, 3, second) + } +} diff --git a/openless-all/android/kotlin/test/ImeSurfaceLayoutTest.kt b/openless-all/android/kotlin/test/ImeSurfaceLayoutTest.kt new file mode 100644 index 000000000..1aba0397d --- /dev/null +++ b/openless-all/android/kotlin/test/ImeSurfaceLayoutTest.kt @@ -0,0 +1,38 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ImeSurfaceLayoutTest { + @Test fun normalKeyboardKeepsPreferredHeight() { + assertEquals(ImeSurfaceSize(300, 0), ImeSurfaceLayout.resolve(300, 0, 900, 220)) + } + @Test fun draftAndKeysFitNormally() { + assertEquals(ImeSurfaceSize(300, 140), ImeSurfaceLayout.resolve(300, 140, 900, 220)) + } + @Test fun longDraftReservesUsableKeysAndScrolls() { + assertEquals(ImeSurfaceSize(220, 140), ImeSurfaceLayout.resolve(300, 500, 360, 220)) + } + @Test fun tinyWindowsDoNotProduceNegativeDimensions() { + assertEquals(ImeSurfaceSize(100, 0), ImeSurfaceLayout.resolve(300, 140, 100, 220)) + assertEquals(ImeSurfaceSize(0, 0), ImeSurfaceLayout.resolve(300, 140, -1, 220)) + } + @Test fun invalidPreferencesAreClampedWithoutInventingSpace() { + assertEquals(ImeSurfaceSize(0, 0), ImeSurfaceLayout.resolve(-10, -20, 400, -1)) + assertEquals(ImeSurfaceSize(200, 0), ImeSurfaceLayout.resolve(200, 0, 400, 800)) + } + @Test fun dimensionsAreBoundedAcrossConstrainedWindows() { + for (available in listOf(-1, 0, 40, 100, 220, 320, 480, 900)) { + for (keys in listOf(-10, 0, 220, 300, 420, 540)) { + for (draft in listOf(-10, 0, 80, 140, 600)) { + val result = ImeSurfaceLayout.resolve(keys, draft, available, 220) + assertTrue(result.keyboard >= 0 && result.draft >= 0) + assertTrue(result.total <= available.coerceAtLeast(0)) + assertTrue(result.keyboard <= keys.coerceAtLeast(0)) + assertTrue(result.draft <= draft.coerceAtLeast(0)) + } + } + } + } +} diff --git a/openless-all/android/kotlin/test/ImeVoiceEligibilityTest.kt b/openless-all/android/kotlin/test/ImeVoiceEligibilityTest.kt new file mode 100644 index 000000000..f60028311 --- /dev/null +++ b/openless-all/android/kotlin/test/ImeVoiceEligibilityTest.kt @@ -0,0 +1,29 @@ +package com.openless.app + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ImeVoiceEligibilityTest { + private fun state(recording: Boolean = false, processing: Boolean = false) = ImeVoiceUiProjection.fromLegacy( + "idle", recording, processing, false, false, false, false, "ready", + ) + @Test fun foreignRecordingNeverAdvertisesOwnedCancel() { + val ui = state(recording = true).withEligibility(false, true, false, true) + assertFalse(ui.canCancel) + assertFalse(ui.canStart) + assertTrue(ui.editorLocked) + } + @Test fun permissionAndSensitiveFieldsCannotStartCapture() { + assertFalse(state().withEligibility(false, false, false, false).canStart) + assertFalse(state().withEligibility(false, true, true, false).canStart) + assertTrue(state().withEligibility(false, true, false, false).canStart) + } + @Test fun ownedCaptureCanBeCancelledEvenIfPermissionWasRevoked() { + assertTrue(state(recording = true).withEligibility(true, false, false, false).canCancel) + } + @Test fun eligibilityCannotReopenProcessingOrCreateCancelForIdle() { + assertFalse(state(processing = true).withEligibility(true, true, false, false).canStart) + assertFalse(state().withEligibility(true, true, false, false).canCancel) + } +} diff --git a/openless-all/android/kotlin/test/ImeVoiceFramePolicyTest.kt b/openless-all/android/kotlin/test/ImeVoiceFramePolicyTest.kt new file mode 100644 index 000000000..b1cad3c4a --- /dev/null +++ b/openless-all/android/kotlin/test/ImeVoiceFramePolicyTest.kt @@ -0,0 +1,41 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ImeVoiceFramePolicyTest { + @Test fun bufferedFinalizationCannotSendQueuedStopOrModeAgain() { + for (state in listOf("transcribing", "polishing", "done", "cancelled", "error")) { + assertEquals(false, ImeVoiceFramePolicy.canApplyQueuedStartActions(state)) + } + assertEquals(true, ImeVoiceFramePolicy.canApplyQueuedStartActions(null)) + assertEquals(true, ImeVoiceFramePolicy.canApplyQueuedStartActions("recording")) + } + @Test fun foreignFramesNeverAcquireAnImeRequest() { + for (state in listOf("recording", "transcribing", "polishing", "done", "cancelled", "error", "idle")) { + assertEquals(ImeVoiceFrameAction.EXTERNAL, ImeVoiceFramePolicy.resolve(false, false, state)) + assertEquals(ImeVoiceFrameAction.EXTERNAL, ImeVoiceFramePolicy.resolve(false, true, state)) + } + } + @Test fun lateRecordingCannotReopenCaptureAfterRelease() { + assertEquals(ImeVoiceFrameAction.IGNORE, ImeVoiceFramePolicy.resolve(true, true, "recording")) + } + @Test fun ownedRecordingAndProcessingRemainObservable() { + assertEquals(ImeVoiceFrameAction.RECORDING, ImeVoiceFramePolicy.resolve(true, false, "recording")) + for (state in listOf("transcribing", "polishing")) { + assertEquals(ImeVoiceFrameAction.PROCESSING, ImeVoiceFramePolicy.resolve(true, false, state)) + } + } + @Test fun globalDoneWaitsForScopedResultDelivery() { + assertEquals(ImeVoiceFrameAction.WAIT_RESULT, ImeVoiceFramePolicy.resolve(true, true, "done")) + assertEquals(ImeVoiceFrameAction.EXTERNALLY_COMPLETED, ImeVoiceFramePolicy.resolve(true, false, "done")) + assertEquals(ImeVoiceFrameAction.EXTERNALLY_COMPLETED, ImeVoiceFramePolicy.resolve(true, true, "done", stopSubmitted = false)) + } + @Test fun globalIdleCannotDropAnOwnedResult() { + assertEquals(ImeVoiceFrameAction.IGNORE, ImeVoiceFramePolicy.resolve(true, true, "idle")) + } + @Test fun ownedTerminalFailuresRemainVisible() { + assertEquals(ImeVoiceFrameAction.CANCELLED, ImeVoiceFramePolicy.resolve(true, false, "cancelled")) + assertEquals(ImeVoiceFrameAction.ERROR, ImeVoiceFramePolicy.resolve(true, false, "error")) + } +} diff --git a/openless-all/android/kotlin/test/ImeVoiceUiStateTest.kt b/openless-all/android/kotlin/test/ImeVoiceUiStateTest.kt new file mode 100644 index 000000000..b6b2ffb5d --- /dev/null +++ b/openless-all/android/kotlin/test/ImeVoiceUiStateTest.kt @@ -0,0 +1,312 @@ +package com.openless.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * SDK-free JUnit4:只验证纯投影语义,不涉及 Android/Service/JNI/Gradle。 + */ +class ImeVoiceUiStateTest { + + private fun project( + state: String = "idle", + recording: Boolean = false, + processing: Boolean = false, + cloudSubmitting: Boolean = false, + raw: Boolean = false, + quickNote: Boolean = false, + cloud: Boolean = false, + message: String = "msg", + level: Float = 0f, + awaitingStart: Boolean = false, + ): ImeVoiceUiSnapshot = ImeVoiceUiProjection.fromLegacy( + state = state, + recording = recording, + processing = processing, + cloudSubmitting = cloudSubmitting, + raw = raw, + quickNote = quickNote, + cloud = cloud, + message = message, + level = level, + awaitingStart = awaitingStart, + ) + + // --- 状态优先级 --- + + @Test + fun recordingWinsOverProcessingAndCloudSubmitting() { + val snapshot = project(recording = true, processing = true, cloudSubmitting = true) + assertEquals(ImeVoicePhase.RECORDING, snapshot.phase) + } + + @Test + fun awaitingStartOnlyTurnsRecordingIntoStarting() { + assertEquals(ImeVoicePhase.STARTING, project(recording = true, awaitingStart = true).phase) + assertEquals( + ImeVoicePhase.PROCESSING, + project(processing = true, awaitingStart = true).phase, + ) + assertEquals(ImeVoicePhase.IDLE, project(awaitingStart = true).phase) + } + + @Test + fun processingWinsOverCloudSubmitting() { + val snapshot = project(processing = true, cloudSubmitting = true) + assertEquals(ImeVoicePhase.PROCESSING, snapshot.phase) + assertTrue(snapshot.processing) + } + + @Test + fun cloudSubmittingIsSubmittingAndNotCancellable() { + val snapshot = project(cloudSubmitting = true) + assertEquals(ImeVoicePhase.SUBMITTING, snapshot.phase) + assertTrue(snapshot.editorLocked) + assertFalse("webhook 提交不承诺可取消", snapshot.canCancel) + assertTrue("旧 cloudPost 未完成时允许新录音", snapshot.canStart) + assertFalse(snapshot.recording) + assertFalse(snapshot.processing) + } + + // --- legacy 终态映射 --- + + @Test + fun legacyTerminalStatesMapToTheirPhases() { + assertEquals(ImeVoicePhase.DONE, project(state = "done").phase) + assertEquals(ImeVoicePhase.CANCELLED, project(state = "cancelled").phase) + assertEquals(ImeVoicePhase.CANCELLED, project(state = "canceled").phase) + assertEquals(ImeVoicePhase.ERROR, project(state = "error").phase) + assertEquals(ImeVoicePhase.IDLE, project(state = "idle").phase) + assertEquals(ImeVoicePhase.IDLE, project(state = "").phase) + assertEquals(ImeVoicePhase.IDLE, project(state = "unknown-state").phase) + assertEquals(ImeVoicePhase.DONE, project(state = " DONE ").phase) + } + + @Test + fun legacyBusyStringsWithoutFlagsDoNotFabricateWork() { + for (state in listOf("speaking", "thinking", "recording", "processing")) { + val snapshot = project(state = state) + assertEquals("无真实 flag 不得虚构录音/处理($state)", ImeVoicePhase.IDLE, snapshot.phase) + assertFalse(snapshot.recording) + assertFalse(snapshot.processing) + assertFalse(snapshot.editorLocked) + assertFalse(snapshot.canCancel) + assertTrue(snapshot.canStart) + } + } + + @Test + fun allPhasesAreReachable() { + val phases = setOf( + project().phase, + project(recording = true, awaitingStart = true).phase, + project(recording = true).phase, + project(processing = true).phase, + project(cloudSubmitting = true).phase, + project(state = "done").phase, + project(state = "cancelled").phase, + project(state = "error").phase, + ) + assertEquals(ImeVoicePhase.entries.toSet(), phases) + } + + // --- 模式优先级 --- + + @Test + fun modePriorityRawQuickCloudDictation() { + assertEquals(ImeVoiceMode.RAW, project(raw = true, quickNote = true, cloud = true).mode) + assertEquals(ImeVoiceMode.QUICK_NOTE, project(quickNote = true, cloud = true).mode) + assertEquals(ImeVoiceMode.CLOUD_NOTE, project(cloud = true).mode) + assertEquals(ImeVoiceMode.CLOUD_NOTE, project(cloudSubmitting = true).mode) + assertEquals(ImeVoiceMode.DICTATION, project().mode) + assertEquals( + ImeVoiceMode.RAW, + project(raw = true, cloudSubmitting = true).mode, + ) + } + + // --- 电平 --- + + @Test + fun audioLevelIsOnlyExposedWhileRecording() { + assertEquals(0f, project(level = 0.8f).audioLevel, 0f) + assertEquals(0f, project(processing = true, level = 0.8f).audioLevel, 0f) + assertEquals(0f, project(cloudSubmitting = true, level = 0.8f).audioLevel, 0f) + assertEquals(0.8f, project(recording = true, level = 0.8f).audioLevel, 0f) + } + + @Test + fun audioLevelClampsAndRejectsNonFiniteValues() { + assertEquals(0f, project(recording = true, level = -1f).audioLevel, 0f) + assertEquals(1f, project(recording = true, level = 5f).audioLevel, 0f) + assertEquals(0f, project(recording = true, level = Float.NaN).audioLevel, 0f) + assertEquals(0f, project(recording = true, level = Float.POSITIVE_INFINITY).audioLevel, 0f) + assertEquals(0f, project(recording = true, level = Float.NEGATIVE_INFINITY).audioLevel, 0f) + assertEquals(0.5f, project(recording = true, level = 0.5f).audioLevel, 0f) + } + + // --- 文案与 flags --- + + @Test + fun messageIsPreservedVerbatim() { + val samples = listOf("", "点击开始说话", "Already done ✓", " padded ") + for (text in samples) { + assertEquals(text, project(message = text).message) + } + } + + @Test + fun derivedFlagsFollowRealInputsOnly() { + val idle = project() + assertFalse(idle.recording) + assertFalse(idle.processing) + assertFalse(idle.editorLocked) + assertFalse(idle.canCancel) + assertTrue(idle.canStart) + + val recording = project(recording = true) + assertTrue(recording.recording) + assertFalse(recording.processing) + assertTrue(recording.editorLocked) + assertTrue(recording.canCancel) + assertFalse(recording.canStart) + + val processing = project(processing = true) + assertTrue(processing.processing) + assertTrue(processing.editorLocked) + assertTrue(processing.canCancel) + assertFalse(processing.canStart) + } + + // --- 128 种 flags 组合不变式 --- + + @Test + fun allFlagCombinationsRespectInvariants() { + val level = 0.4f + val message = "flags-matrix" + for (mask in 0..127) { + val recording = mask and 1 != 0 + val processing = mask and 2 != 0 + val cloudSubmitting = mask and 4 != 0 + val raw = mask and 8 != 0 + val quickNote = mask and 16 != 0 + val cloud = mask and 32 != 0 + val awaitingStart = mask and 64 != 0 + val snapshot = project( + recording = recording, + processing = processing, + cloudSubmitting = cloudSubmitting, + raw = raw, + quickNote = quickNote, + cloud = cloud, + message = message, + level = level, + awaitingStart = awaitingStart, + ) + val label = "mask=$mask rec=$recording proc=$processing cloudSub=$cloudSubmitting " + + "raw=$raw quick=$quickNote cloud=$cloud awaiting=$awaitingStart" + + val expectedPhase = when { + recording -> if (awaitingStart) ImeVoicePhase.STARTING else ImeVoicePhase.RECORDING + processing -> ImeVoicePhase.PROCESSING + cloudSubmitting -> ImeVoicePhase.SUBMITTING + else -> ImeVoicePhase.IDLE + } + assertEquals("phase ($label)", expectedPhase, snapshot.phase) + + val expectedMode = when { + raw -> ImeVoiceMode.RAW + quickNote -> ImeVoiceMode.QUICK_NOTE + cloud || cloudSubmitting -> ImeVoiceMode.CLOUD_NOTE + else -> ImeVoiceMode.DICTATION + } + assertEquals("mode ($label)", expectedMode, snapshot.mode) + + assertEquals("recording echo ($label)", recording, snapshot.recording) + assertEquals("processing echo ($label)", processing, snapshot.processing) + assertEquals( + "editorLocked ($label)", + recording || processing || cloudSubmitting, + snapshot.editorLocked, + ) + assertEquals("canCancel ($label)", recording || processing, snapshot.canCancel) + assertEquals("canStart ($label)", !recording && !processing, snapshot.canStart) + assertEquals("message ($label)", message, snapshot.message) + assertEquals( + "audioLevel ($label)", + if (recording) level.coerceIn(0f, 1f) else 0f, + snapshot.audioLevel, + 0f, + ) + + // 结构不变式:锁定 == 处于忙态;未锁定 == 终态/空闲;可取消只出现在采集/处理阶段。 + if (snapshot.editorLocked) { + assertTrue( + "locked implies busy phase ($label)", + snapshot.phase in setOf( + ImeVoicePhase.STARTING, + ImeVoicePhase.RECORDING, + ImeVoicePhase.PROCESSING, + ImeVoicePhase.SUBMITTING, + ), + ) + } else { + assertTrue( + "unlocked implies terminal/idle phase ($label)", + snapshot.phase in setOf( + ImeVoicePhase.IDLE, + ImeVoicePhase.DONE, + ImeVoicePhase.CANCELLED, + ImeVoicePhase.ERROR, + ), + ) + } + if (snapshot.canCancel) { + assertTrue( + "cancellable implies capture/processing phase ($label)", + snapshot.phase in setOf( + ImeVoicePhase.STARTING, + ImeVoicePhase.RECORDING, + ImeVoicePhase.PROCESSING, + ), + ) + } + assertTrue("audio level range ($label)", snapshot.audioLevel in 0f..1f) + } + } + + // --- 请求所有权 --- + + @Test + fun ownerMatchesOnlyExactEpochAndRequestId() { + val owner = ImeRequestOwner(epoch = 7L, requestId = 42L) + assertTrue(owner.matches(7L, 42L)) + assertFalse(owner.matches(8L, 42L)) + assertFalse(owner.matches(7L, 43L)) + assertFalse(owner.matches(8L, 43L)) + } + + @Test + fun ownerMatchesIsExactForZeroAndNegativeValues() { + val zero = ImeRequestOwner(epoch = 0L, requestId = 0L) + assertTrue(zero.matches(0L, 0L)) + assertFalse(zero.matches(1L, 0L)) + assertFalse(zero.matches(0L, 1L)) + + val negative = ImeRequestOwner(epoch = -3L, requestId = -9L) + assertTrue(negative.matches(-3L, -9L)) + assertFalse(negative.matches(-3L, 9L)) + } + + @Test + fun ownerValueEqualityAndCopy() { + val owner = ImeRequestOwner(1L, 2L) + assertEquals(owner, ImeRequestOwner(1L, 2L)) + assertTrue(owner.matches(owner.epoch, owner.requestId)) + val newer = owner.copy(epoch = 3L) + assertFalse(newer.matches(1L, 2L)) + assertTrue(newer.matches(3L, 2L)) + } +} diff --git a/openless-all/android/kotlin/test/OpenLessOverlayStateTest.kt b/openless-all/android/kotlin/test/OpenLessOverlayStateTest.kt index 108d84336..c6dedc3a2 100644 --- a/openless-all/android/kotlin/test/OpenLessOverlayStateTest.kt +++ b/openless-all/android/kotlin/test/OpenLessOverlayStateTest.kt @@ -1,5 +1,6 @@ package com.openless.app +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -14,6 +15,53 @@ class OpenLessOverlayStateTest { assertFalse(shouldIgnoreOverlayRecordingFrame(false, null)) } + @Test + fun foreignRecordingFramesMirrorWithoutPromoteOrAutoCancel() { + assertEquals( + OverlayRecordingFrameAction.MIRROR_ONLY, + overlayRecordingFrameAction(ownsSession = false, processing = false, message = null), + ) + assertEquals( + OverlayRecordingFrameAction.MIRROR_ONLY, + overlayRecordingFrameAction(ownsSession = false, processing = false, message = "voice edit capture failed"), + ) + assertFalse(shouldAutoCancelOwnedSession(ownsSession = false)) + } + + @Test + fun queuedMeterFramesStillWinOverOwnership() { + for (message in listOf(null, "", " ")) { + assertEquals( + OverlayRecordingFrameAction.IGNORE, + overlayRecordingFrameAction(ownsSession = true, processing = true, message = message), + ) + assertEquals( + OverlayRecordingFrameAction.IGNORE, + overlayRecordingFrameAction(ownsSession = false, processing = true, message = message), + ) + } + } + + @Test + fun ownedRecordingKeepsPromoteAndOwnedAutoCancel() { + assertEquals( + OverlayRecordingFrameAction.PROMOTE_AND_SHOW, + overlayRecordingFrameAction(ownsSession = true, processing = false, message = null), + ) + assertTrue(shouldAutoCancelOwnedSession(ownsSession = true)) + } + + @Test + fun ownershipIsReleasedOnTerminalFailureAndManualEnds() { + val ownership = OverlaySessionOwnership() + assertFalse(ownership.owned) + ownership.markStarted() + assertTrue(ownership.owned) + // 终态/失败/手动手势都走同一个 release,后续外部帧只会镜像。 + ownership.release() + assertFalse(ownership.owned) + } + @Test fun neverTriggerBlocksOverlayDisplayButOtherModesRemainAvailable() { assertFalse(OpenLessAndroidPreferences.shouldDisplayOverlay("never")) diff --git a/openless-all/android/scripts/copy-android-scaffolding.mjs b/openless-all/android/scripts/copy-android-scaffolding.mjs index cba804678..0abc68673 100644 --- a/openless-all/android/scripts/copy-android-scaffolding.mjs +++ b/openless-all/android/scripts/copy-android-scaffolding.mjs @@ -64,6 +64,26 @@ const KOTLIN_FILES = [ 'OpenLessMigrationBundlePolicy.kt', 'OpenLessMigrationState.kt', 'OpenLessImeService.kt', + 'ImeGestureSession.kt', + 'ImeKeyboardModels.kt', + 'ImeTypingPanel.kt', + 'ImeVoicePanel.kt', + 'ImeModeBar.kt', + 'ImeKeyboardHeader.kt', + 'ImeVoiceUiState.kt', + 'ImeVoiceFramePolicy.kt', + 'ImeScopedFrameGate.kt', + 'ImeInteractionPolicy.kt', + 'ImeSurfaceLayout.kt', + 'ImeSelectionPolicy.kt', + 'ImeEditorFieldPolicy.kt', + 'ImeSurfaceHost.kt', + 'ImeDraftBar.kt', + 'ImeKeyboardPreview.kt', + 'ImeActionButton.kt', + 'ImeCandidateStrip.kt', + 'ImeClipboardPanel.kt', + 'ImeStrokePanel.kt', 'ImeLearningPolicy.kt', 'DictationSpan.kt', 'ImePrivacyPolicy.kt', @@ -95,6 +115,16 @@ const KOTLIN_FILES = [ ]; const KOTLIN_TEST_FILES = [ + 'ImeGestureSessionTest.kt', + 'ImeKeyboardModelsTest.kt', + 'ImeVoiceUiStateTest.kt', + 'ImeVoiceFramePolicyTest.kt', + 'ImeVoiceEligibilityTest.kt', + 'ImeScopedFrameGateTest.kt', + 'ImeInteractionPolicyTest.kt', + 'ImeSurfaceLayoutTest.kt', + 'ImeSelectionPolicyTest.kt', + 'ImeEditorFieldPolicyTest.kt', 'ImeLearningPolicyTest.kt', 'CloudNoteDeliveryTest.kt', 'DictationSpanTest.kt', @@ -118,6 +148,16 @@ const KOTLIN_TEST_FILES = [ 'OpenLessAccessibilityComponentIdsTest.kt', ]; const KOTLIN_ANDROID_TEST_FILES = [ + 'ImeTypingPanelInstrumentedTest.kt', + 'ImeVoicePanelInstrumentedTest.kt', + 'ImeRemainingPanelsInstrumentedTest.kt', + 'ImeBridgeCompatibilityInstrumentedTest.kt', + 'ImeSessionScopeInstrumentedTest.kt', + 'ImeDraftBarInstrumentedTest.kt', + 'ImeSurfaceHostInstrumentedTest.kt', + 'ImeInteractionFeedbackInstrumentedTest.kt', + 'ImeEditingSafetyInstrumentedTest.kt', + 'ImePanelInteractionEdgeCasesInstrumentedTest.kt', 'OpenLessRuntimeServiceInstrumentedTest.kt', 'OpenLessClipboardHistoryInstrumentedTest.kt', 'OpenLessCredentialVaultInstrumentedTest.kt', diff --git a/openless-all/app/mobile-ime/rime_engine.cpp b/openless-all/app/mobile-ime/rime_engine.cpp index 5f4ff6b7d..fc916402b 100644 --- a/openless-all/app/mobile-ime/rime_engine.cpp +++ b/openless-all/app/mobile-ime/rime_engine.cpp @@ -218,6 +218,14 @@ std::string request(const std::string& op, const std::string& handle, const std: if (n != separator || r != arg.size() - separator - 1 || revision != session.revision || !(op == "select_absolute" ? api->select_candidate(id, index) : api->select_candidate_on_current_page(id, index))) throw std::runtime_error("Rime candidate is stale"); + } else if (op == "delete_candidate") { + const auto separator = arg.find('@'); + if (separator == std::string::npos) throw std::runtime_error("Rime candidate revision required"); + size_t n = 0; auto index = std::stoul(arg.substr(0, separator), &n); + size_t r = 0; auto revision = std::stoul(arg.substr(separator + 1), &r); + if (n != separator || r != arg.size() - separator - 1 || revision != session.revision || + !api->delete_candidate(id, index)) + throw std::runtime_error("Rime candidate cannot be deleted"); } else throw std::runtime_error("Unknown Rime operation"); } // Observing a composition must not invalidate the displayed candidates. diff --git a/openless-all/app/scripts/android-ime-key-click-contract.test.mjs b/openless-all/app/scripts/android-ime-key-click-contract.test.mjs index 51ff8cd4d..2a6c08501 100644 --- a/openless-all/app/scripts/android-ime-key-click-contract.test.mjs +++ b/openless-all/app/scripts/android-ime-key-click-contract.test.mjs @@ -2,36 +2,64 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; -const source = readFileSync( - new URL('../../android/kotlin/OpenLessImeService.kt', import.meta.url), +const readAndroid = (name) => + readFileSync(new URL(`../../android/kotlin/${name}`, import.meta.url), 'utf8'); +const source = readAndroid('OpenLessImeService.kt'); +const scaffolding = readFileSync( + new URL('../../android/scripts/copy-android-scaffolding.mjs', import.meta.url), 'utf8', ); -const keyboardKey = source.slice( - source.indexOf('internal fun keyboardKey('), - source.indexOf('private fun keyRepeatIntervalMs('), -); -test('a fresh key press clears click suppression left by an out-of-bounds swipe', () => { - const down = keyboardKey.match( - /MotionEvent\.ACTION_DOWN -> \{([\s\S]*?)MotionEvent\.ACTION_MOVE/, - ); - assert.ok(down, 'keyboardKey must handle ACTION_DOWN'); - assert.match( - down[1], - /suppressNextClick = false/, - 'an out-of-bounds swipe has no native click to clear suppression before the next tap', - ); +// Source-only architecture/wiring guards. Touch behavior is exercised by the +// Android View tests, not by matching fragments of a retired key implementation. +test('the host delegates key presentation instead of retaining legacy touch widgets', () => { + assert.doesNotMatch(source, /internal fun keyboardKey\(/); + assert.doesNotMatch(source, /class (?:KeyPreviewOverlay|SwipeModeContainer|StrokeKeyView)\b/); + assert.match(source, /ImeTypingPanel\(/); + assert.match(source, /ImeClipboardPanel\(/); + assert.match(readAndroid('StrokeInputController.kt'), /ImeStrokePanel\(/); + for (const name of [ + 'ImeActionButton.kt', + 'ImeCandidateStrip.kt', + 'ImeTypingPanel.kt', + 'ImeVoicePanel.kt', + 'ImeClipboardPanel.kt', + 'ImeStrokePanel.kt', + 'ImeDraftBar.kt', + 'ImeSurfaceHost.kt', + 'ImeKeyboardPreview.kt', + ]) { + const view = readAndroid(name); + assert.doesNotMatch( + view, + /OpenLessNative\.|currentInputConnection|getSharedPreferences\(/, + `${name} must not own backend calls, editor connections, or preferences`, + ); + assert.ok(scaffolding.includes(`'${name}'`), `${name} must reach the Android build`); + } }); -test('a swipe still suppresses the click from the same touch sequence', () => { - assert.match( - keyboardKey, - /if \(event\.actionMasked == MotionEvent\.ACTION_UP && swipePreviewShown\) \{\s*swipeSpecOf\(trackedView\)\?\.first\?\.invoke\(\)\s*suppressNextClick = true/, - ); - assert.match( - keyboardKey, - /setOnClickListener \{\s*if \(suppressNextClick\) \{\s*suppressNextClick = false\s*\} else \{\s*action\(\)/, +test('normal presentation refreshes retain the system input-view root', () => { + assert.match(source, /new ImeSurfaceHost|ImeSurfaceHost\(this\)/); + assert.match(source, /surfaceHost\?\.render\(keyboard, draft, draftEdit\)/); + assert.equal((source.match(/setInputView\(onCreateInputView\(\)\)/g) ?? []).length, 1); + const refresh = source.slice( + source.indexOf('internal fun refreshInputView()'), + source.indexOf('private fun refreshInputView(slideDirection:'), ); + assert.match(refresh, /replaceSurfaceContent\(\)/); + assert.doesNotMatch(refresh, /setInputView\(/); +}); + +test('key and candidate behavior fixtures reach the Android instrumentation source set', () => { + for (const name of [ + 'ImeTypingPanelInstrumentedTest.kt', + 'ImeVoicePanelInstrumentedTest.kt', + 'ImeRemainingPanelsInstrumentedTest.kt', + ]) { + assert.ok(scaffolding.includes(`'${name}'`), `${name} must be staged`); + assert.match(readAndroid(`androidTest/${name}`), /@RunWith\(AndroidJUnit4::class\)/); + } }); test('a reused English letter panel synchronizes Shift even when its state does not change', () => { diff --git a/openless-all/app/scripts/android-ime-session-scope-contract.test.mjs b/openless-all/app/scripts/android-ime-session-scope-contract.test.mjs new file mode 100644 index 000000000..3e677aa9d --- /dev/null +++ b/openless-all/app/scripts/android-ime-session-scope-contract.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +const text = (path) => readFileSync(new URL(path, import.meta.url), 'utf8'); +const bridge = text('../../android/kotlin/OpenLessOverlayBridge.kt'); +const host = text('../../android/kotlin/OpenLessImeService.kt'); +const native = text('../src-tauri/src/android/native_bridge.rs'); +const jni = text('../src-tauri/src/android/jni.rs'); +const copy = text('../../android/scripts/copy-android-scaffolding.mjs'); + +// These are ABI and source-wiring checks, not substitutes for scoped frame +// model tests, Android View behavior tests, or a full matching-native build. +test('session metadata preserves the legacy callback ABI', () => { + assert.match( + bridge, + /fun onCapsuleStateChanged\(state: String, message: String\?, level: Float\)/, + ); + assert.match(bridge, /onCapsuleStateChangedWithSession\(state, message, level, null\)/); + assert.ok(jni.includes('"(Ljava/lang/String;Ljava/lang/String;F)V"')); + assert.ok(jni.includes('"(Ljava/lang/String;Ljava/lang/String;FLjava/lang/String;)V"')); + assert.ok(jni.includes('"onCapsuleStateChangedWithSession"')); +}); + +test('the Core payload identity reaches the Android bridge without snapshot guessing', () => { + const outlet = native.slice( + native.indexOf('pub fn notify_capsule_state('), + native.indexOf('pub fn show_overlay('), + ); + assert.match(outlet, /notify_overlay_bridge_with_session\(/); + assert.match(outlet, /payload\.session_id\.as_deref\(\)/); + assert.doesNotMatch(outlet, /backend\.snapshot\(|CORE_BACKEND\.get\(/); +}); + +test('the IME accepts owned frames only after a verified started binding', () => { + assert.match(host, /imeFrameGate\.bind\(owner, identity\)/); + assert.match(host, /imeFrameGate\.isBound\(owner, identity\)/); + assert.match(host, /when \(imeFrameGate\.accept\(frame\)\)/); + assert.match(host, /ImeFrameDisposition\.OWNED -> \{/); + assert.match(host, /ImeFrameDisposition\.UNIDENTIFIED, ImeFrameDisposition\.STALE -> Unit/); + assert.match(host, /imeFrameGate\.finish\(activeImeOwner\)/); +}); + +test('the scoped model and compatibility fixture are staged for testing', () => { + for (const name of [ + 'ImeScopedFrameGate.kt', + 'ImeScopedFrameGateTest.kt', + 'ImeBridgeCompatibilityInstrumentedTest.kt', + 'ImeSessionScopeInstrumentedTest.kt', + ]) { + assert.ok(copy.includes(`'${name}'`), `${name} must reach the generated Android project`); + } + const fixture = text( + '../../android/kotlin/androidTest/ImeBridgeCompatibilityInstrumentedTest.kt', + ); + assert.match(fixture, /@RunWith\(AndroidJUnit4::class\)/); +}); diff --git a/openless-all/app/scripts/build-mobile-rime.py b/openless-all/app/scripts/build-mobile-rime.py index ea47b971e..e424179a2 100644 --- a/openless-all/app/scripts/build-mobile-rime.py +++ b/openless-all/app/scripts/build-mobile-rime.py @@ -2,6 +2,7 @@ """Build the same pinned librime for OHOS and Android, outside the checkout.""" import argparse import concurrent.futures +import hashlib import json import os from pathlib import Path @@ -232,7 +233,11 @@ def build(name, extra, target=None, install=True): print('Rime prefix: ' + str(prefix), flush=True) print('Rime data: ' + str(data), flush=True) if opts.platform == 'android': - bridge = root / 'build-bridge' + # The bridge source lives in this checkout, unlike shared dependency + # sources. A CMake binary directory cannot be reused by another clone; + # namespace it without deleting other checkouts' build caches. + checkout_key = hashlib.sha256(str(APP).encode('utf-8')).hexdigest()[:12] + bridge = root / ('build-bridge-' + checkout_key) run(cmake, '-S', APP / 'mobile-ime', '-B', bridge, *common, '-DOPENLESS_RIME_PREFIX=' + str(prefix)) run(cmake, '--build', bridge, '--parallel', opts.jobs) @@ -251,6 +256,23 @@ def build(name, extra, target=None, install=True): raise RuntimeError('Android libc++_shared.so missing') shutil.copy2(stl[0], libraries) shutil.copytree(data, destination / 'assets/rime', dirs_exist_ok=True) + deployer = shutil.which('rime_deployer') + if deployer: + pre_user = root / 'prebuilt-user' + if pre_user.exists(): + shutil.rmtree(pre_user) + pre_user.mkdir(parents=True, exist_ok=True) + (pre_user / 'default.custom.yaml').write_text( + 'patch:\n schema_list:\n - schema: openless_pinyin_learning\n' + ' - schema: openless_pinyin_private\n - schema: pinyin_simp\n' + ' menu/page_size: 8\n', + encoding='utf-8', + ) + run(deployer, '--build', pre_user, data) + prebuilt_dest = destination / 'assets/rime-prebuilt' + if prebuilt_dest.exists(): + shutil.rmtree(prebuilt_dest) + shutil.copytree(pre_user / 'build', prebuilt_dest) if __name__ == '__main__': main() diff --git a/openless-all/app/scripts/copy-android-scaffolding.test.mjs b/openless-all/app/scripts/copy-android-scaffolding.test.mjs index 8565b45b7..66e40aabd 100644 --- a/openless-all/app/scripts/copy-android-scaffolding.test.mjs +++ b/openless-all/app/scripts/copy-android-scaffolding.test.mjs @@ -153,6 +153,25 @@ try { ), 'runtime lifecycle regression must reach the generated instrumentation source set', ); + for (const [source, destination] of [ + ['kotlin/ImeGestureSession.kt', 'src/main/java/com/openless/app/ImeGestureSession.kt'], + ['kotlin/ImeKeyboardModels.kt', 'src/main/java/com/openless/app/ImeKeyboardModels.kt'], + ['kotlin/ImeTypingPanel.kt', 'src/main/java/com/openless/app/ImeTypingPanel.kt'], + [ + 'kotlin/androidTest/ImeTypingPanelInstrumentedTest.kt', + 'src/androidTest/java/com/openless/app/ImeTypingPanelInstrumentedTest.kt', + ], + [ + 'kotlin/test/ImeGestureSessionTest.kt', + 'src/test/java/com/openless/app/ImeGestureSessionTest.kt', + ], + ]) { + assert.equal( + readFileSync(join(app, destination), 'utf8'), + readFileSync(new URL(`../../android/${source}`, import.meta.url), 'utf8'), + 'gesture behavior model and JVM tests must reach the generated Android project', + ); + } assert.match(first, /android:usesCleartextTraffic="true"/); assert.equal(run(), first, 'repeated scaffolding copies must preserve the debug manifest'); } finally { diff --git a/openless-all/app/src-tauri/src/android/jni.rs b/openless-all/app/src-tauri/src/android/jni.rs index 4cc7d14b2..235fbcc0a 100644 --- a/openless-all/app/src-tauri/src/android/jni.rs +++ b/openless-all/app/src-tauri/src/android/jni.rs @@ -832,6 +832,37 @@ pub mod android { ) } + /// Same as [`notify_overlay_bridge`], plus the optional capsule session id. + /// + /// The id-less 3-arg callback above stays as-is for compatibility. This overload + /// targets `OpenLessOverlayBridge.onCapsuleStateChangedWithSession`; a missing id is + /// sent as an empty string and normalised to null on the Kotlin side. + pub fn notify_overlay_bridge_with_session<'local>( + env: &mut JNIEnv<'local>, + context: &JObject<'local>, + state: &str, + message: Option<&str>, + level: f32, + session_id: Option<&str>, + ) -> Result<(), String> { + let state_obj = jobject_str(env, state)?; + let message_obj = jobject_str(env, message.unwrap_or(""))?; + let session_obj = jobject_str(env, session_id.unwrap_or(""))?; + call_static_void_with_context_class( + env, + context, + "com.openless.app.OpenLessOverlayBridge", + "onCapsuleStateChangedWithSession", + "(Ljava/lang/String;Ljava/lang/String;FLjava/lang/String;)V", + &[ + JValue::Object(&state_obj), + JValue::Object(&message_obj), + JValue::Float(level), + JValue::Object(&session_obj), + ], + ) + } + pub fn notify_ime_session_event<'local>( env: &mut JNIEnv<'local>, context: &JObject<'local>, diff --git a/openless-all/app/src-tauri/src/android/native_bridge.rs b/openless-all/app/src-tauri/src/android/native_bridge.rs index a87c4cfd3..0e2be2708 100644 --- a/openless-all/app/src-tauri/src/android/native_bridge.rs +++ b/openless-all/app/src-tauri/src/android/native_bridge.rs @@ -498,12 +498,13 @@ pub fn notify_capsule_state(payload: &CapsulePayload) { ); // #endregion if let Err(error) = crate::android::jni::android::with_android_env(|env, context| { - crate::android::jni::android::notify_overlay_bridge( + crate::android::jni::android::notify_overlay_bridge_with_session( env, context, state, message, payload.level, + payload.session_id.as_deref(), ) }) { log::warn!("[android-native] notify overlay bridge failed: {error}");